diff --git a/README.md b/README.md index 1388bd2..ee9f3b2 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,30 @@ # XCL Mac Native — Apple Silicon & macOS Compatibility Layer for Xbox Series X|S [![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?logo=discord&logoColor=white)](https://discord.gg/dYuNEsQMQ) +[![Latest Release](https://img.shields.io/badge/Release-Stage%206.4%20(Menu%20%26%20Intro)-blue?logo=github)](https://github.com/utkarshxdev/xcl-mac/releases/tag/v0.1.0-stage6.4-menu) [![Mac cross-build](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml/badge.svg?branch=main)](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml?query=branch%3Amain) -[![Stage 6: Ingame 3D Rendering](https://img.shields.io/badge/Status-Stage%206%20(Ingame%203D)-success?logo=apple&color=34D399)](https://github.com/utkarshxdev/xcl-mac) +[![Stage 6: Ingame 3D Rendering](https://img.shields.io/badge/Status-Stage%206%20(In--Game%20Presentation)-success?logo=apple&color=34D399)](https://github.com/utkarshxdev/xcl-mac) [![License: GPL-2.0](https://img.shields.io/badge/License-GPL%202.0-blue.svg)](LICENSE) [![Platform: macOS](https://img.shields.io/badge/Platform-macOS%20%7C%20Apple%20Silicon-black?logo=apple)](https://github.com/utkarshxdev/xcl-mac) +

+ Grand Theft Auto VI running on Apple Silicon via XCL Mac Native +

+

+ Grand Theft Auto VI running natively on Apple Silicon via XCL Mac Native under CrossOver & Apple D3DMetal (30.0 FPS locked presentation & intro sequence). +

+ +

+ GTA VI Splash Mural in XCL Window + GTA VI Finish Setup UI at 30 FPS + GTA VI Legal Terms & Policies Screen +

+

+ 🎬 Watch Full 70-Second High-Resolution Gameplay Capture (MP4) +

+ +--- + **XCL Mac Native** (`utkarshxdev/xcl-mac`) is the dedicated, production-ready macOS and Apple Silicon distribution of [XCL](https://github.com/ivall/xcl) — the Xbox Series X|S (GDK) compatibility layer. By executing console x86_64 code seamlessly via Apple's Rosetta 2 and mapping RDNA2 console GPU pipelines through DirectX 12 into Apple **D3DMetal (Game Porting Toolkit 2+)**, XCL enables GDK retail titles to run on macOS under Wine and CrossOver **without CPU emulation**. @@ -97,7 +116,12 @@ All Mac-specific subsystems are strictly gated behind `crate::util::mac_host()` 5. **D3D12 Agility SDK:** Place `D3D12Core.dll` into a `D3D12\` folder next to `xcl.exe` or configure `XCL_D3D12_DIR`. ### Pre-Built Binaries -Download the latest `xcl-mac-wine-x86_64` build directly from the **[GitHub Actions Releases](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml)**. +- **Latest Verified Release (Stage 6.4 — Menu & Intro, Pre-Series S):** + 👉 **[Download `xcl-mac-stage6.4-menu.zip`](https://github.com/utkarshxdev/xcl-mac/releases/download/v0.1.0-stage6.4-menu/xcl-mac-stage6.4-menu.zip)** *(includes `xcl.exe`, `dxcompiler.dll`, `dxil.dll` — SHA-256: `d0cf51561411a8ebb83c66b043174ebc56226dc6df5ddae33463720a24263f23`)* +- **Experimental Series S / Multi-Plane Pre-release (Run 15):** + 👉 **[Download `xcl-run15-window-checked.zip`](https://github.com/utkarshxdev/xcl-mac/releases/download/v0.1.0-stage6.4-run15-planes/xcl-run15-window-checked.zip)** *(includes `xcl.exe`, `dxcompiler.dll`, `dxil.dll` — SHA-256: `4ed9133051d74df5e30bc1be9c81d80773e5122711eaf743c72430dc32fc6d97`)* +- View all releases and changelogs on the **[GitHub Releases Page](https://github.com/utkarshxdev/xcl-mac/releases)**. +- Automated CI builds are available on the **[GitHub Actions Workflows](https://github.com/utkarshxdev/xcl-mac/actions/workflows/mac-cross.yml)**. ### Launch Command Launch your title through your Wine environment with the recommended Mac environment flags: @@ -119,8 +143,10 @@ env XCL_TEXTURE_SKIP_UNCHANGED=0 XCL_NETWORK=0 wine64 xcl.exe run "C:\Games\Your | `XCL_COHERENT_HEAPS` | `0` (Off) | `1` (On) | Avoids write-watch page protection traps on coherent heaps | | `XCL_WATCHDOG_BYPASS` | Off | — | Enables recovery for recognized watchdog sites. Unknown traps still follow normal exception handling. | | `XCL_DSTORAGE_BCPACK_ACCEPT` | Off | — | Set to `1` to complete eligible BCPack requests with solid placeholder blocks. Texture decompression is required for the original pixels. | +| `XCL_DSTORAGE_AUTO_SUBMIT_DISABLED` | On | On | A DirectStorage queue made with AutoSubmitDisabled waits for the title's Submit. Set to `0` to ignore that option: such a queue then submits by itself at half full, like any other. | | `XCL_TRACE_GPU_STALL` | Off | `1` | Logs command lists, recent dispatches and pipeline IDs when a bottom-of-pipe fence stalls | -| `XCL_PRESENT_PLANE` | `0` | `0` | Set to `1` to try the second PresentX plane. The log shows the requested and active planes and whether the resources can be presented. | +| `XCL_MS_IN_AS_SLOT` | On | On | A console mesh shader in a pipeline's AS slot, with no MS subobject, is translated as the mesh shader. Set to `0` to refuse such pipelines instead. | +| `XCL_PRESENT_PLANE` | Unset | Unset | Unset: two PresentX planes or more are composed, as the console's display does. Set to `n` to show plane `n` alone (plane `0` when the title presents fewer planes or plane `n` has no presentable resource); `0` shows plane 0 alone and turns composition off. The log shows the requested and active planes and whether the resources can be presented. | | `XCL_FRAME_DUMP` | `0` | `0` | Dumps every Nth presented frame to disk with luminance telemetry | | `XCL_FRAME_DUMP_FROM` | `0` | `0` | Delays frame sampling until frame index N is reached | @@ -157,7 +183,7 @@ cargo build --release --locked --target x86_64-pc-windows-gnullvm -p xcl ## 🧪 Subsystem Verification -We provide an automated verification suite that audits all 22 Mac-native architectural subsystems: +We provide an automated verification suite that audits all 39 Mac-native architectural subsystems: ```bash ./scripts/verify_mac_build.sh @@ -173,24 +199,41 @@ Checking: Stand-in PS dual-source blending (SV_Target0 + SV_Target1) [PASS] Checking: D3DMetal shader refusal host fallback (refused_on_mac_host) [PASS] Checking: Compute blob cache charging fix (insert_compute_blob) [PASS] Checking: Rosetta missing AMD instruction handlers (CLZERO, INSERTQ) [PASS] -Checking: Rosetta AVX masked store decoder module (maskmov.rs) [PASS] -Checking: Rosetta masked store fault helper patching [PASS] +Checking: Rosetta AVX masked store decoder module (crates/xcl/src/maskmov.rs) [PASS] +Checking: Rosetta masked store fault helper patching (replace_masked_stores) [PASS] Checking: Rosetta CPU detection (util::rosetta) [PASS] -Checking: UMA Shadowed fallback implementation [PASS] +Checking: UMA Shadowed fallback implementation (OpenExistingHeapFromAddress) [PASS] Checking: UMA note_copy_into for readback buffers [PASS] -Checking: GPU-visible fallback write-watch disable [PASS] +Checking: GPU-visible fallback write-watch disable (XCL_WATCHED_FALLBACK) [PASS] Checking: Command queue #31 GPU view page mappings (gpu_views) [PASS] Checking: Unwatched title textures content comparison (poll_unwatched) [PASS] -Checking: Unchanged title texture upload skip override [PASS] +Checking: Unchanged title texture upload skip override (XCL_TEXTURE_SKIP_UNCHANGED) [PASS] Checking: CopyMemoryToMemoryX CPU fallback for non-UMA ranges [PASS] -Checking: D3DMetal depth-only format mapping [PASS] +Checking: D3DMetal depth-only format mapping (pc_depth_view_format) [PASS] Checking: Mac host utility detection (util::mac_host) [PASS] Checking: Wine isolated thread heap for DXC (own_heaps) [PASS] Checking: Network isolation default off (netoff) [PASS] Checking: 16 MiB title stacks under Wine [PASS] +Checking: Sparse buffer lock safety (try_lock in forget_buffer) [PASS] +Checking: World-load watchdog & fatal crash bypass at 0x23cf683 [PASS] +Checking: DirectStorage BCPack acceptance (XCL_DSTORAGE_BCPACK_ACCEPT) [PASS] +Checking: Mesh root-argument layout (user_data_ms, inline_ms) [PASS] +Checking: Mesh companion DISPATCH signature creation [PASS] +Checking: Real D3D12 DispatchMesh hooking (slot 127 / newer 129) [PASS] +Checking: GPU-side root-changing ExecuteIndirect repack [PASS] +Checking: Two-pass DispatchMesh & ExecuteIndirect execution harness [PASS] Checking: Mac cross-build CI workflow (.github/workflows/mac-cross.yml) [PASS] +Checking: CreateShaderCacheSession translation layer fallback [PASS] +Checking: Pointer alignment guard in is_adopted (align_of::) [PASS] +Checking: Heap mirroring and bounded root SRVs [PASS] +Checking: Lock-free atomic pipeline building accounting (pso_async::counts) [PASS] +Checking: XUserCompare 64-bit pointer overflow prevention [PASS] +Checking: XAsyncGetResult zero-used out parameter preservation [PASS] +Checking: GetModuleFileName ERROR_INSUFFICIENT_BUFFER on size 0 [PASS] +Checking: Vertex buffer slot unbind & purge on null/zero views [PASS] +Checking: QueryInterface wrapper interface vtable release dispatch [PASS] ====================================================================== -Verification Summary: 22 Passed, 0 Failed +Verification Summary: 39 Passed, 0 Failed ====================================================================== Status: Verification SUCCESSFUL! All Mac host subsystems present. ``` diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 7a29e57..053e5df 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -7,7 +7,7 @@ //! * An unhandled-exception filter logs crashes with module+RVA and writes the report. use std::ffi::c_void; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; use std::sync::Mutex; use windows_sys::Win32::System::Diagnostics::Debug::{ @@ -87,11 +87,10 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i let c = &*ctx; // registers that point at objects: the module of their vtable (which object it is) let obj = |v: u64| -> String { - let p = v as usize; - if p < 0x10000 || !crate::gpu::shader::readable(p, 8) { + // (copied: memory unmapped meanwhile must not fault in the filter, `qwords_at`) + let Some(vt) = qwords_at(v as usize, 1).map(|q| q[0] as usize) else { return String::new(); - } - let vt = (p as *const usize).read_unaligned(); + }; let d = modules::describe_address(vt); if d.contains('+') { format!(" (vtable {d})") } else { String::new() } }; @@ -112,6 +111,10 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i crate::xlog_error!("{msg}"); crate::report::write_final(Some(msg)); crate::log::flush(); + if !ctx.is_null() { + crash_memory(&*ctx, &mut |line| crate::xlog_error!("{line}")); + crate::log::flush(); + } } match TITLE_FILTER.load(Ordering::Acquire) { 0 => 0, // EXCEPTION_CONTINUE_SEARCH @@ -119,6 +122,128 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i } } +/// `n` qwords at `at`, if all of them could be read. A copy by ReadProcessMemory: memory another +/// thread unmaps or decommits meanwhile fails the copy, not the exception filter that asks (a +/// fault there is a nested exception, and the title's own filter never runs); `readable` only +/// spares the call where nothing is. +unsafe fn qwords_at(at: usize, n: usize) -> Option> { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if at < 0x10000 || n == 0 || !crate::gpu::shader::readable(at, n * 8) { + return None; + } + let mut q = vec![0u64; n]; + let mut done = 0usize; + (ReadProcessMemory(GetCurrentProcess(), at as *const std::ffi::c_void, q.as_mut_ptr().cast(), n * 8, &mut done) != 0 && done == n * 8).then_some(q) +} + +/// What is left of a crash report's wait for XCL's locks, in ms: 100 in all, once – a thread +/// stopped while it held one would hold it for good, and the faulting thread may hold one itself. +/// Once it is spent, each lock is looked at once. +static CRASH_WAIT_MS: AtomicU32 = AtomicU32::new(100); + +/// The wait a crash's report has left (`try_lock_within`), shared by every lock it tries. +pub(crate) fn crash_wait() -> &'static AtomicU32 { + &CRASH_WAIT_MS +} + +/// `m` tried every ms while `left_ms` lasts – each wait takes the time it took from it (a +/// Sleep(1) may take more here); a poisoned lock is taken as it is. None: still busy. +pub(crate) fn try_lock_within<'a, T>(m: &'a Mutex, left_ms: &AtomicU32) -> Option> { + loop { + match m.try_lock() { + Ok(g) => return Some(g), + Err(std::sync::TryLockError::Poisoned(e)) => return Some(e.into_inner()), + Err(std::sync::TryLockError::WouldBlock) => { + if left_ms.load(Ordering::Relaxed) == 0 { + return None; + } + let t = std::time::Instant::now(); + std::thread::sleep(std::time::Duration::from_millis(1)); + let spent = (t.elapsed().as_millis() as u32).max(1); + let _ = left_ms.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| Some(n.saturating_sub(spent))); + } + } + } +} + +/// (tests) Thread `tid`'s description (Rust's thread names reach it), empty if none +#[cfg(test)] +pub(crate) fn thread_name_of(tid: u32) -> String { + use windows_sys::Win32::System::Threading::{OpenThread, THREAD_QUERY_LIMITED_INFORMATION}; + unsafe { + let h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, 0, tid); + if h.is_null() { + return String::new(); + } + let s = thread_name(h); + windows_sys::Win32::Foundation::CloseHandle(h); + s + } +} + +/// One line of a crash's memory: `what` (`p`), the qwords around it – 8 before and 8 from the +/// one holding `p` on (that one in brackets); near the start or the end of what is readable, as +/// many from that one on as are –, where they are, and the DirectStorage request that last wrote +/// their 64 KiB page. With the qwords from the one holding `p` on. +unsafe fn crash_memory_line(what: &str, p: usize) -> Option<(String, Vec)> { + let at = p & !0x7; + let (base, q) = match qwords_at(at.saturating_sub(0x40), 16) { + Some(q) => (at - 0x40, q), + None => (at, (1..=8).rev().find_map(|n| qwords_at(at, n))?), + }; + let words: Vec = q + .iter() + .enumerate() + .map(|(k, v)| if base + 8 * k == at { format!("[{v:#018x}]") } else { format!("{v:#018x}") }) + .collect(); + let line = format!( + "crash memory: {what} {p:#x} ({}; last DirectStorage write to its 64 KiB page: {}): from {base:#x}: {}", + modules::describe_address(p), + crate::hle::dstorage::last_write_at_for_crash(p), + words.join(" ") + ); + Some((line, q[(at - base) / 8..].to_vec())) +} + +/// The label of a step further: the qword `k` from the one `p` points into, as `[reg±offset]` +/// from `p` (`p` need not be 8-aligned: a tagged pointer). +fn step_label(reg: &str, p: usize, k: usize) -> String { + let off = (8 * k) as isize - (p & 0x7) as isize; + if off < 0 { format!("[{reg}-{:#x}] ->", off.unsigned_abs()) } else { format!("[{reg}+{off:#x}] ->") } +} + +/// The memory an unhandled exception's registers point at, and one step further – what the +/// first qwords there point at: whether a table the title read held pointers or something +/// streamed over it (run 63: a garbage tagged pointer read from [[rsi+0x10] + 8 * index]). Each +/// window once; one line at a time to `out`. +unsafe fn crash_memory(c: &windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, out: &mut dyn FnMut(String)) { + let regs = [ + ("rax", c.Rax), ("rbx", c.Rbx), ("rcx", c.Rcx), ("rdx", c.Rdx), + ("rsi", c.Rsi), ("rdi", c.Rdi), ("rbp", c.Rbp), ("r8", c.R8), + ("r9", c.R9), ("r10", c.R10), ("r11", c.R11), ("r12", c.R12), + ("r13", c.R13), ("r14", c.R14), ("r15", c.R15), ("rsp", c.Rsp), + ]; + let mut seen = std::collections::HashSet::new(); + for (n, v) in regs { + let p = v as usize; + if p < 0x10000 || !seen.insert(p & !0x7) { + continue; + } + let Some((line, after)) = crash_memory_line(n, p) else { continue }; + out(line); + // one step further: the first 8 qwords from the register's that point at readable memory + for (k, &q) in after.iter().take(8).enumerate() { + let q = q as usize; + if q >= 0x10000 && seen.insert(q & !0x7) { + if let Some((line, _)) = crash_memory_line(&step_label(n, p, k), q) { + out(line); + } + } + } + } +} + static ORIG_NT_TERMINATE: AtomicUsize = AtomicUsize::new(0); static ENDING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -206,6 +331,73 @@ pub fn install_crash_handler() { let _ = std::thread::Builder::new().name("xcl-probe".into()).spawn(move || arm_probes(&offsets)); } } + // local diagnostic `XCL_WATCHDOG_PROBE=` (GTA VI 1.0.2.1 only): every 2 s, the + // state of the title's stall watchdog (`title_watchdog_resume`) – its active-scope + // counter (active: while it is not 0 the countdown starts again every second), flags (the + // pause, reset and stop flags), the age of the heartbeat it counts down on (last_age: + // with no scope open it fires 30 checks after the last write, about 30 s; a resume does + // not write the heartbeat, so the next fires come about 30 s apart, at ages of about 61, + // 91 s …), the report hook armed (cb: none, or the bare `ret` at title+0x4380 when + // func_81b200 armed it), the QPC scale it uses, and the age of every open scope in its + // 64-group table (in its first loop a scope of 300 s or more fires when the title's + // tunable 0x89aee1d6 is on), measured with the same QueryPerformanceCounter – appended + // to (not the log). + if let Ok(path) = std::env::var("XCL_WATCHDOG_PROBE") { + let _ = std::thread::Builder::new().name("xcl-watchdog-probe".into()).spawn(move || { + use std::io::Write; + #[link(name = "kernel32")] + extern "system" { + fn QueryPerformanceCounter(c: *mut i64) -> i32; + } + let Ok(mut out) = std::fs::OpenOptions::new().create(true).append(true).open(&path) else { return }; + let m = loop { + match modules::main_module() { + Some(m) => break m, + None => std::thread::sleep(std::time::Duration::from_millis(200)), + } + }; + let at = |va: usize| m.base + (va - 0x1_4000_0000); + let _ = writeln!(out, "=== watchdog probe: title at {:#x} ===", m.base); + loop { + std::thread::sleep(std::time::Duration::from_secs(2)); + let mut now = 0i64; + QueryPerformanceCounter(&mut now); + let scale = (at(0x1_49e4_f5c0) as *const f32).read_volatile(); + let active = (at(0x1_471b_6334) as *const i32).read_volatile(); + let (f30, f31, f40) = ( + (at(0x1_471b_6330) as *const u8).read_volatile(), + (at(0x1_471b_6331) as *const u8).read_volatile(), + (at(0x1_471b_6340) as *const u8).read_volatile(), + ); + let last = (at(0x1_471b_6338) as *const i64).read_volatile(); + let cb = (at(0x1_471b_6348) as *const usize).read_volatile(); + let mut ages = Vec::new(); + for g in 0..64usize { + let count = (at(0x1_4684_4a20 + 72 * g + 4) as *const u32).read_volatile(); + if count == 0 { + continue; + } + let mut e = Vec::new(); + for i in 0..(count as usize).min(8) { + let ts = (at(0x1_4684_4a28 + 72 * g + 8 * i) as *const i64).read_volatile(); + e.push(if ts == 0 { "0".to_string() } else { format!("{:.1}s", (now - ts) as f32 * scale) }); + } + ages.push(format!("g{g} n={count}{} [{}]", if count > 8 { " OVERFLOW" } else { "" }, e.join(" "))); + } + let _ = writeln!(out, "t={:.1} {}", crate::log::uptime(), crate::hle::d3d12x::cpu_writes_probe()); + let _ = writeln!(out, "t={:.1} {}", crate::log::uptime(), crate::hle::dstorage::probe_line()); + let _ = writeln!( + out, + "t={:.1} qpc={now} scale={scale:e} active={active} flags={f30}/{f31}/{f40} last_age={:.1}s cb={} | {}", + crate::log::uptime(), + if last == 0 { -1.0 } else { (now - last) as f32 * scale }, + if cb == 0 { "none".to_string() } else { modules::image_base_for_addr(cb).map_or(format!("{cb:#x}"), |b| format!("title+{:#x}", cb - b)) }, + ages.join("; ") + ); + let _ = out.flush(); + } + }); + } // `XCL_DUMP_THREADS_ON=`: the same each time that file is written (its time // changes) – for a stall whose time is not known beforehand; what is in the file is // logged with the dump @@ -213,11 +405,16 @@ pub fn install_crash_handler() { let _ = std::thread::Builder::new().name("xcl-thread-dump".into()).spawn(move || { let modified = |p: &str| std::fs::metadata(p).and_then(|m| m.modified()).ok(); let mut seen = modified(&path); + // local diagnostic: opened now, while nothing is stuck + let mut raw = std::fs::OpenOptions::new().create(true).append(true).open(format!("{path}.raw.txt")).ok(); loop { std::thread::sleep(std::time::Duration::from_millis(500)); let now = modified(&path); if now.is_some() && now != seen { seen = now; + if let Some(f) = raw.as_mut() { + dump_threads_raw(f); + } crate::xlog_info!("thread stacks {:.1} s into the run (XCL_DUMP_THREADS_ON: {}):", crate::log::uptime(), std::fs::read_to_string(&path).unwrap_or_default().trim()); dump_threads(); crate::log::flush(); @@ -338,8 +535,20 @@ const HELPERS_SIZE: usize = 0x1_0000; /// Serialises site patching; `XCL_ISA_REDIRECT=0` turns it off (every use then traps). static PATCHING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); static REDIRECT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); +/// A thread was once stepped into a CLZERO loop's body (`emulate_console_only`'s fallback): a +/// loop redirected after that could have that thread return into the call's bytes, so none is. +static CLZERO_LOOP_STEPPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); static WATCHDOG: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// `XCL_PATCH_MWAITX=1`: a MONITORX site becomes a 3-byte NOP and an MWAITX site PAUSE; NOP after +/// their first use (`patch_in_place`), instead of trapping at every use. Off by default: a trap +/// under Rosetta costs tens of microseconds, which a title's MONITORX / MWAITX wait loop then +/// spends waiting (GTA VI's, about 20 a second); patched, the loop spins a whole core. +fn patch_mwaitx() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PATCH_MWAITX").is_ok_and(|v| v.trim() == "1")) +} + /// Free address space for helpers within reach of a `call rel32` from `near`: the nearest /// `size` bytes (a multiple of 64 KiB) above it, else below; committed, readable, writable and /// executable. 0: none. @@ -418,6 +627,9 @@ unsafe fn redirect(site: usize, code: &[u8], t: &isa::Thunk, helper: &[u8; isa:: if std::slice::from_raw_parts(site as *const u8, n) != code { return true; } + if t.op == isa::Op::ClzeroLoop && CLZERO_LOOP_STEPPED.load(Ordering::Acquire) { + return false; + } let mut pool = HELPERS.load(Ordering::Relaxed); if pool == 0 { pool = alloc_near(site, HELPERS_SIZE).max(1); @@ -463,6 +675,61 @@ unsafe fn redirect(site: usize, code: &[u8], t: &isa::Thunk, helper: &[u8; isa:: done } +/// Replaces the instruction `old` at `site` by `new` of the same length (instruction boundaries +/// stay where they are), in one locked 16-byte compare-exchange of the aligned block holding it – +/// a thread sees the old instruction or the new one, never a mix. `true`: replaced. +unsafe fn patch_in_place(site: usize, old: &[u8], new: &[u8]) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let n = old.len(); + let block = site & !15; + let off = site - block; + if n != new.len() || n == 0 || off + n > 16 || !REDIRECT.load(Ordering::Relaxed) { + return false; + } + if PATCHING.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() { + return false; + } + let mut prot = 0u32; + let mut done = false; + if VirtualProtect(block as *const _, 16, PAGE_EXECUTE_READWRITE, &mut prot) != 0 { + let cur = std::ptr::read_volatile(block as *const [u8; 16]); + if &cur[off..off + n] == old { + let mut want = cur; + want[off..off + n].copy_from_slice(new); + done = cas16(block as *mut u8, cur, want); + } + VirtualProtect(block as *const _, 16, prot, &mut prot); + FlushInstructionCache(GetCurrentProcess(), site as *const _, n); + } + PATCHING.store(false, Ordering::Release); + done +} + +/// `lock cmpxchg16b` on the 16-byte aligned `p`. +unsafe fn cas16(p: *mut u8, old: [u8; 16], new: [u8; 16]) -> bool { + let q = |b: &[u8]| u64::from_le_bytes(b.try_into().unwrap()); + let (old_lo, old_hi, new_lo, new_hi) = (q(&old[..8]), q(&old[8..]), q(&new[..8]), q(&new[8..])); + let ok: u64; + // RBX cannot be named: the new low quadword comes in RSI and is swapped into RBX around the + // instruction. Every operand is in a register named here – one LLVM chose could be RBX. + core::arch::asm!( + "xchg rbx, rsi", + "lock cmpxchg16b xmmword ptr [rdi]", + "sete r9b", + "movzx r9d, r9b", + "xchg rbx, rsi", + in("rdi") p, + inout("rsi") new_lo => _, + inout("rax") old_lo => _, + inout("rdx") old_hi => _, + in("rcx") new_hi, + out("r9") ok, + ); + ok != 0 +} + /// One log line per instruction kind, and one when emulation by exception turns out to be /// frequent: each such trap costs tens of microseconds. unsafe fn note_insn(kind: usize, what: &str, redirected: bool, ip: usize) { @@ -510,8 +777,9 @@ unsafe extern "system" fn unsupported_insn_handler(info: *mut EXCEPTION_POINTERS return -1; } } - // likewise a CLWB site that became NOPs: a NOP does not raise this exception - if code.first() == Some(&0x90) { + // likewise a CLWB site that became NOPs, or a MONITORX / MWAITX site that became a NOP / + // PAUSE (`patch_in_place`): those do not raise this exception + if code.first() == Some(&0x90) || code.starts_with(&[0x0F, 0x1F, 0x00]) || code.starts_with(&[0xF3, 0x90, 0x90]) { return -1; } let mut helper = [0u8; isa::THUNK_MAX]; @@ -555,19 +823,41 @@ fn isa_memory_accessible(addr: usize, bytes: usize, write: bool) -> bool { true } -/// A retail title's stall watchdog (GTA VI 1.0.2.1, exe+0x2215b91..): a thread walks 64 -/// heartbeat slots and, when one is older than its limit, calls a hook (which stores to -/// address 0 and returns) and then stores to address 0 itself – a deliberate crash that sends -/// a report. A host that is slow for a moment (shader compiles, other programs) trips it -/// although nothing hangs. `XCL_WATCHDOG_BYPASS=1` on a Mac resumes the recognized -/// stores. `XCL_TITLE_WATCHDOG=1` keeps the crash. +/// A retail title's stall watchdog (GTA VI 1.0.2.1: its thread runs exe+0x2215a60) ends the title +/// on purpose when its render thread has not gone through a frame for a while. What it measures +/// is a heartbeat – a QueryPerformanceCounter stamp at exe+0x71b6338 that the render thread's +/// per-frame function (func_120790) writes at its start and, through func_c9e330/func_c9e350, at +/// its end, that func_1c82b20's loading loop writes, and that the watchdog itself writes after a +/// Sleep measured over 2.0 s or when the title's pause or reset flag is set –, not any one wait. +/// It picks one of its two loops once, at its start (the second when exe+0x71b62f0 was set then: +/// no writer of it was found, so it likely never runs). Every second it sleeps 1000 ms; while no +/// scope is open (exe+0x71b6334 = 0) it counts 30 checks in a row with the stamp unchanged – an +/// open scope, the title's pause or reset flag (exe+0x71b6330, exe+0x71b6331) or a Sleep measured +/// over 2.0 s (the process stopped from outside) starts the count again – and then, or in its +/// first loop when one of its 64 groups has a scope open 300 s or more and the title's tunable +/// 0x89aee1d6 is on, it calls the report hook the title armed (exe+0x71b6348: a hook `mov dword +/// ptr [0], imm32`, the imm32 naming the report, then `ret` or `add rsp, imm8; ret`; or none, or +/// the bare `ret` at exe+0x4380) and then stores to address 0 itself – a deliberate crash that +/// sends a report. A frame the host holds that long trips it although nothing hangs (run 65: the +/// first world frame's pipelines waited for at their binds, 27.5 s on one recording thread). +/// `XCL_WATCHDOG_BYPASS=1` on a Mac resumes: +/// - a hook's store, only when the hook's return address (above its frame) is right after the +/// watchdog's `call rax` and on the watchdog's own store, in the hook's image: the hook's +/// epilogue runs and returns there; +/// - the watchdog's own store, in either of its two loops, at the loop's heartbeat check, which +/// starts the count again without writing the heartbeat: while the frame is still held it +/// fires again 30 checks (about 30 s) later, at a heartbeat about 61 s old, then about 91 s … +/// Any other store to address 0 still crashes. `XCL_TITLE_WATCHDOG=1` keeps the crash. Each +/// resume's line waits a few ms for a log file another thread is writing (`log::try_write_soon`): +/// one fire's line may be its only record. unsafe fn title_watchdog_resume(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT) -> bool { if !cfg!(test) && (!crate::util::mac_host() || !WATCHDOG.load(Ordering::Acquire)) { return false; } static SEEN: AtomicUsize = AtomicUsize::new(0); + static HOOKS: AtomicUsize = AtomicUsize::new(0); let rip = ctx.Rip as usize; - if rip < 0x1_0000 || !crate::gpu::shader::readable(rip, 12) { + if rip < 0x1_0000 || !crate::gpu::shader::readable(rip, 16) { return false; } let at = |a: usize, n: usize| std::slice::from_raw_parts(a as *const u8, n); @@ -575,20 +865,31 @@ unsafe fn title_watchdog_resume(ctx: &mut windows_sys::Win32::System::Diagnostic if at(rip, 7) != [0xC7, 0x04, 0x25, 0, 0, 0, 0] { return false; } - // the hook: `mov dword ptr [0], 0x2ef1e94b; ret` - if at(rip + 7, 5) == [0x4B, 0xE9, 0xF1, 0x2E, 0xC3] { - ctx.Rip += 11; - return true; - } - // the fatal error / GPU hang watchdog (`mov dword ptr [0], 0x4d8bd421`): deliberate crash - // tripped when world-load decompression or background compute pipeline builds take >30s - if at(rip + 7, 5) == [0x21, 0xD4, 0x8B, 0x4D, 0xC3] { - let n = SEEN.fetch_add(1, Ordering::Relaxed); + // a report hook (the five GTA VI arms: 0x4d8bd421 – render sync, the only one with a frame: + // `add rsp, 0x48; ret` –, 0x2ef1e94b, 0x4d795ee1, 0xb90ee778, 0x18283088): its epilogue next, + // and the return address above its frame the watchdog's call + if let Some(frame) = hook_frame(at(rip + 11, 5)) { + let image = modules::image_base_for_addr(rip); + let Some(slot) = (ctx.Rsp as usize).checked_add(frame) else { return false }; + if image.is_none() || !crate::gpu::shader::readable(slot, 8) { + return false; + } + let ret = (slot as *const usize).read_unaligned(); + if !watchdog_call(ret) || modules::image_base_for_addr(ret) != image { + return false; + } + let imm = (rip as *const u8).add(7).cast::().read_unaligned(); + let n = HOOKS.fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + WATCHDOG_RESUMED.with(|r| r.set([r.get()[0] + 1, r.get()[1], r.get()[2]])); if n < 4 || n.is_power_of_two() { - crate::log::try_write(crate::log::Level::Warn, - format_args!("the title's fatal error / GPU hang watchdog triggered (#{n}: 0x4d8bd421 at rip={rip:#x}); resuming at the existing RET")); + let said = crate::log::try_write_soon(crate::log::Level::Warn, format_args!( + "the title's stall watchdog called its report hook (#{n}): hook {imm:#010x} at {rip:#x} (image+{:#x}); resuming at the hook's epilogue, which returns into the watchdog's own store", + rip - image.unwrap_or(0) + )); + watchdog_said(0, said); } - // Let the existing RET execute with the title's stack and unwind state intact. + // the hook's epilogue runs with its stack as it is and returns to the watchdog's store ctx.Rip += 11; return true; } @@ -601,17 +902,89 @@ unsafe fn title_watchdog_resume(ctx: &mut windows_sys::Win32::System::Diagnostic && at(rip - 0x3B, 8) == [0x49, 0x89, 0xF6, 0xBD, 0x1E, 0, 0, 0] { let n = SEEN.fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + WATCHDOG_RESUMED.with(|r| r.set([r.get()[0], r.get()[1] + 1, r.get()[2]])); if n < 4 || n.is_power_of_two() { - crate::log::try_write(crate::log::Level::Warn, + let said = crate::log::try_write_soon(crate::log::Level::Warn, format_args!("the title's stall watchdog fired (#{n}); resuming at the recognized heartbeat check")); + watchdog_said(1, said); } ctx.Rsi = ctx.R14; ctx.Rip -= 0x42; return true; } + // its second loop (picked once, at the thread's start, when exe+0x71b62f0 was set: likely never; + // its walk of the scopes never fires, so only its countdown does): `mov r15, [rip+..]; mov ebp, + // 0x1e; jmp` – the path to the loop's heartbeat check when no slot is stale – 0x49 bytes + // before, its `call rax` right before, `xor eax, eax; int3` after. The loop's rsi, rdi, rbx, + // r14 and xmm6 live through the clock's and the hook's calls: no register to fix. + if crate::gpu::shader::readable(rip.wrapping_sub(0x49), 0x49 + 14) + && at(rip + 7, 7) == [0, 0, 0, 0, 0x31, 0xC0, 0xCC] + && at(rip - 2, 2) == [0xFF, 0xD0] + && at(rip - 0x49, 3) == [0x4C, 0x8B, 0x3D] + && at(rip - 0x42, 5) == [0xBD, 0x1E, 0, 0, 0] + && at(rip - 0x3D, 1) == [0xE9] + { + let n = SEEN.fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + WATCHDOG_RESUMED.with(|r| r.set([r.get()[0], r.get()[1], r.get()[2] + 1])); + if n < 4 || n.is_power_of_two() { + let said = crate::log::try_write_soon(crate::log::Level::Warn, + format_args!("the title's stall watchdog fired in its second loop (#{n}); resuming at the recognized heartbeat check")); + watchdog_said(2, said); + } + ctx.Rip -= 0x49; + return true; + } false } +/// The bytes of a report hook's frame – between its stack pointer at the store and its return +/// address, which lies above them –, from the epilogue after the hook's store: `ret` (0) or `add +/// rsp, imm8; ret` (imm8, below 0x80) – None for any other. +fn hook_frame(epilogue: &[u8]) -> Option { + match epilogue { + [0xC3, ..] => Some(0), + &[0x48, 0x83, 0xC4, ib, 0xC3, ..] if ib < 0x80 => Some(ib as usize), + _ => None, + } +} + +/// `ret` is where the title's stall watchdog's `call rax` (`ff d0`) returns: on the watchdog's own +/// `mov dword ptr [0], 0`. +unsafe fn watchdog_call(ret: usize) -> bool { + let Some(call) = ret.checked_sub(2) else { return false }; + crate::gpu::shader::readable(call, 13) + && std::slice::from_raw_parts(call as *const u8, 2) == [0xFF, 0xD0] + && std::slice::from_raw_parts(ret as *const u8, 11) == [0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0] +} + +#[cfg(test)] +thread_local! { + /// (tests) this thread's `title_watchdog_resume`s: of a report hook, of the watchdog's store in + /// its first loop, in its second + static WATCHDOG_RESUMED: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) }; + /// (tests) the same three kinds: this thread's resumes whose line was due (`#n` below 4 or a + /// power of two – of the counts all threads share), and of those the lines not given up for a + /// busy log file (`log::try_write_soon`) + static WATCHDOG_SAID: std::cell::Cell<[[usize; 2]; 3]> = const { std::cell::Cell::new([[0; 2]; 3]) }; +} + +/// A resume of kind `k` (`WATCHDOG_SAID`: a hook, the first loop, the second) had its line due; +/// `said`: not given up for a busy log file. Counted for the tests only. +#[cfg_attr(not(test), inline(always))] +fn watchdog_said(k: usize, said: bool) { + #[cfg(test)] + WATCHDOG_SAID.with(|s| { + let mut v = s.get(); + v[k][0] += 1; + v[k][1] += said as usize; + s.set(v); + }); + #[cfg(not(test))] + let _ = (k, said); +} + /// A call or jump through a null (or near-null) pointer: logged with the return address and /// the registers, since the faulting address itself says nothing about the caller. /// the probes of `XCL_PROBE_MOV`: (address, the 7 bytes that were there) @@ -935,9 +1308,21 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; } } - ConsoleOnly::Monitorx => {} + ConsoleOnly::Monitorx => { + crate::waitwatch::note_monitorx(ctx.Rax); + // (`XCL_PATCH_MWAITX=1`) the bare instruction: a 3-byte NOP (`nop dword [rax]`) from now on + if patch_mwaitx() && code.starts_with(&[0x0F, 0x01, 0xFA]) && patch_in_place(rip, &[0x0F, 0x01, 0xFA], &[0x0F, 0x1F, 0x00]) { + note_insn(16, "MONITORX", true, rip); + } + } ConsoleOnly::Mwaitx => { + crate::waitwatch::note_mwaitx(rip); std::hint::spin_loop(); + // (`XCL_PATCH_MWAITX=1`) the bare instruction: PAUSE; NOP from now on (an MWAITX may + // return at once) + if patch_mwaitx() && code.starts_with(&[0x0F, 0x01, 0xFB]) && patch_in_place(rip, &[0x0F, 0x01, 0xFB], &[0xF3, 0x90, 0x90]) { + note_insn(17, "MWAITX", true, rip); + } } ConsoleOnly::Clzero => { // with an address-size prefix (0x67, among the prefixes before 0F 01 FC) the line @@ -973,9 +1358,28 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics ctx.Rax = final_rax; ctx.EFlags = cmp_eflags(ctx.EFlags, final_rax, end); } + // an end not past the start: the do-while loop zeroes one line and leaves + _ if end <= start && start <= u64::MAX - 0x40 && is_writable(line, 64) => { + std::ptr::write_bytes(line as *mut u8, 0, 64); + ctx.Rax = start + 0x40; + ctx.EFlags = cmp_eflags(ctx.EFlags, ctx.Rax, end); + } _ if is_writable(line, 64) => { // Fall back to stepping the single `clzero` (len - 9) so the title's own - // `add / cmp / jb` runs natively for end <= start, huge/wrapping, or partial ranges. + // `add / cmp / jb` runs natively for huge/wrapping or partial ranges. + // Not into a loop another thread has redirected meanwhile (the call's bytes are + // there now: run the site again), and no loop is redirected after this. + while PATCHING.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() { + std::hint::spin_loop(); + } + let still = std::slice::from_raw_parts((rip + len - 12) as *const u8, 3) == [0x0F, 0x01, 0xFC]; + if still { + CLZERO_LOOP_STEPPED.store(true, Ordering::Release); + } + PATCHING.store(false, Ordering::Release); + if !still { + return -1; + } std::ptr::write_bytes(line as *mut u8, 0, 64); step = len - 9; } @@ -1235,6 +1639,244 @@ unsafe fn unwind(ctx: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTE out } +/// (diagnostic, `waitwatch`) Thread `tid` stopped for a moment: its RIP, RSP, the frames +/// unwound from there (after it runs again – the unwinder takes locks a stopped thread may +/// hold) and the module return addresses on its stack from RSP up (up to `n` each). +pub fn context_frames(tid: u32, n: usize) -> Option<(usize, usize, Vec, Vec)> { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Diagnostics::Debug::{GetThreadContext, CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64}; + use windows_sys::Win32::System::Threading::{OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME}; + unsafe { + let h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, tid); + if h.is_null() { + return None; + } + #[repr(align(16))] + struct Aligned(CONTEXT); + let mut c: Aligned = std::mem::zeroed(); + c.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + let got = SuspendThread(h) != u32::MAX && { + let ok = GetThreadContext(h, &mut c.0) != 0; + ResumeThread(h); + ok + }; + CloseHandle(h); + if !got { + return None; + } + let (rip, rsp) = (c.0.Rip as usize, c.0.Rsp as usize); + let mut scanned = Vec::new(); + for k in 0..4096usize { + let at = rsp + 8 * k; + if !crate::gpu::shader::readable(at, 8) { + break; + } + let v = (at as *const usize).read_unaligned(); + if modules::image_base_for_addr(v).is_some() || modules::describe_address(v).contains('+') { + if scanned.last() != Some(&v) { + scanned.push(v); + } + if scanned.len() == n { + break; + } + } + } + let frames = unwind(&mut c.0, n); + Some((rip, rsp, frames, scanned)) + } +} + +/// (diagnostic, `waitwatch`) Where thread `tid` is inside a system call, without stopping it: +/// Wine keeps the registers a thread entered its current (or last) system call with in a +/// syscall frame, `amd64_thread_data.syscall_frame` at TEB+0x328 (rax … r15 @0, rip @0x70, +/// rsp @0x88, rbp @0x98). A thread held in a wait stays in that call: its RIP and RSP there, +/// the frames unwound from them and the module return addresses on its stack (up to `n`), and +/// the thread's CPU time (ms) – unchanged between looks: it is held, not running. +pub fn syscall_frames(tid: u32, n: usize) -> Option<(usize, usize, Vec, Vec, u64)> { + use windows_sys::Win32::Foundation::{CloseHandle, FILETIME}; + use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64}; + use windows_sys::Win32::System::Threading::{GetThreadTimes, OpenThread, THREAD_QUERY_INFORMATION}; + #[link(name = "ntdll")] + extern "system" { + fn NtQueryInformationThread(h: *mut c_void, class: u32, info: *mut c_void, len: u32, ret: *mut u32) -> i32; + } + unsafe { + let h = OpenThread(THREAD_QUERY_INFORMATION, 0, tid); + if h.is_null() { + return None; + } + let mut tbi = [0usize; 6]; + let teb = if NtQueryInformationThread(h, 0, tbi.as_mut_ptr() as *mut c_void, 48, std::ptr::null_mut()) >= 0 { tbi[1] } else { 0 }; + let (mut c0, mut e0, mut k0, mut u0): (FILETIME, FILETIME, FILETIME, FILETIME) = (std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed(), std::mem::zeroed()); + let cpu_ms = if GetThreadTimes(h, &mut c0, &mut e0, &mut k0, &mut u0) != 0 { + let t = |f: FILETIME| ((f.dwHighDateTime as u64) << 32 | f.dwLowDateTime as u64) / 10_000; + t(k0) + t(u0) + } else { + 0 + }; + CloseHandle(h); + if teb == 0 || !crate::gpu::shader::readable(teb + 0x328, 8) { + return None; + } + let frame = *((teb + 0x328) as *const usize); + if frame == 0 || !crate::gpu::shader::readable(frame, 0xa8) { + return None; + } + let r = |o: usize| *((frame + o) as *const u64); + #[repr(align(16))] + struct Aligned(CONTEXT); + let mut c: Aligned = std::mem::zeroed(); + c.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + c.0.Rax = r(0); + c.0.Rbx = r(0x8); + c.0.Rcx = r(0x10); + c.0.Rdx = r(0x18); + c.0.Rsi = r(0x20); + c.0.Rdi = r(0x28); + c.0.R8 = r(0x30); + c.0.R9 = r(0x38); + c.0.R10 = r(0x40); + c.0.R11 = r(0x48); + c.0.R12 = r(0x50); + c.0.R13 = r(0x58); + c.0.R14 = r(0x60); + c.0.R15 = r(0x68); + c.0.Rip = r(0x70); + c.0.Rsp = r(0x88); + c.0.Rbp = r(0x98); + let (rip, rsp) = (c.0.Rip as usize, c.0.Rsp as usize); + if rip == 0 || !crate::gpu::shader::readable(rsp, 8) { + return None; + } + let mut scanned = Vec::new(); + for k in 0..4096usize { + let at = rsp + 8 * k; + if !crate::gpu::shader::readable(at, 8) { + break; + } + let v = (at as *const usize).read_unaligned(); + if modules::image_base_for_addr(v).is_some() || modules::describe_address(v).contains('+') { + if scanned.last() != Some(&v) { + scanned.push(v); + } + if scanned.len() == n { + break; + } + } + } + let frames = unwind(&mut c.0, n); + Some((rip, rsp, frames, scanned, cpu_ms)) + } +} + +/// Local diagnostic (stall hunting): every thread's RIP and the module return addresses found +/// by scanning 16 KiB of its stack, logged one line per thread. Unlike `dump_threads` it takes +/// no lock a stuck thread may hold: no unwinder (RtlLookupFunctionEntry), no loader +/// (GetModuleHandleEx) – module ranges come from XCL's mapped modules and the PEB loader list, +/// read without the loader lock before any thread is suspended. +pub fn dump_threads_raw(out: &mut std::fs::File) { + use std::io::Write; + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::Debug::{GetThreadContext, CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32}; + use windows_sys::Win32::System::Threading::{GetCurrentProcessId, GetCurrentThreadId, OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME}; + #[link(name = "ntdll")] + extern "system" { + fn NtQueryInformationThread(h: *mut c_void, class: u32, info: *mut c_void, len: u32, ret: *mut u32) -> i32; + } + unsafe { + let t0 = crate::log::uptime(); + // module ranges, all lock-free: XCL's title modules (atomic range table) and the PEB list + let mut ranges: Vec<(usize, usize, String)> = Vec::new(); + let peb: usize; + core::arch::asm!("mov {}, gs:[0x60]", out(reg) peb, options(nostack, readonly, preserves_flags)); + let ldr = *((peb + 0x18) as *const usize); + if ldr != 0 { + let head = ldr + 0x10; + let mut e = *(head as *const usize); + let mut guard = 0; + while e != 0 && e != head && guard < 1024 { + guard += 1; + let base = *((e + 0x30) as *const usize); + let size = *((e + 0x40) as *const u32) as usize; + let len = (*((e + 0x58) as *const u16) / 2) as usize; + let buf = *((e + 0x60) as *const usize) as *const u16; + let name = if !buf.is_null() && len > 0 && len < 260 { String::from_utf16_lossy(std::slice::from_raw_parts(buf, len)).to_ascii_lowercase() } else { format!("{base:#x}") }; + if base != 0 && size != 0 { + ranges.push((base, size, name)); + } + e = *(e as *const usize); + } + } + let classify = |a: usize| -> Option { + if let Some(b) = modules::image_base_for_addr(a) { + return Some(format!("title@{b:#x}+{:#x}", a - b)); + } + ranges.iter().find(|r| a >= r.0 && a < r.0 + r.1).map(|r| format!("{}+{:#x}", r.2, a - r.0)) + }; + let _ = writeln!(out, "=== raw thread dump at {t0:.1} s ({} PEB modules) ===", ranges.len()); + let (pid, me) = (GetCurrentProcessId(), GetCurrentThreadId()); + let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snap == INVALID_HANDLE_VALUE { + let _ = writeln!(out, "no snapshot"); + return; + } + let mut te: THREADENTRY32 = std::mem::zeroed(); + te.dwSize = std::mem::size_of::() as u32; + let mut ok = Thread32First(snap, &mut te) != 0; + let mut stack = vec![0usize; 4096]; + while ok { + if te.th32OwnerProcessID == pid && te.th32ThreadID != me { + let h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, te.th32ThreadID); + if !h.is_null() { + #[repr(align(16))] + struct Aligned(CONTEXT); + let mut c: Aligned = std::mem::zeroed(); + c.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + let susp = SuspendThread(h); + let got = susp != u32::MAX && { + let ok = GetThreadContext(h, &mut c.0) != 0; + ResumeThread(h); + ok + }; + // ThreadBasicInformation: TebBaseAddress at +8; NT_TIB StackBase at TEB+8 + let mut tbi = [0usize; 6]; + let teb = if NtQueryInformationThread(h, 0, tbi.as_mut_ptr() as *mut c_void, 48, std::ptr::null_mut()) >= 0 { tbi[1] } else { 0 }; + let stack_base = if teb != 0 { *((teb + 8) as *const usize) } else { 0 }; + if got { + let rsp = c.0.Rsp as usize; + let n = if stack_base > rsp { ((stack_base - rsp) / 8).min(stack.len()) } else { 0 }; + if n > 0 { + std::ptr::copy_nonoverlapping(rsp as *const usize, stack.as_mut_ptr(), n); + } + let rip = classify(c.0.Rip as usize).unwrap_or_else(|| format!("{:#x}", c.0.Rip)); + let mut hits: Vec = Vec::new(); + for &v in &stack[..n] { + if let Some(d) = classify(v) { + if hits.last() != Some(&d) { + hits.push(d); + } + if hits.len() == 28 { + break; + } + } + } + let _ = writeln!(out, "thread {} (suspend count {}) rip {} rsp {:#x} [{} qwords] | {}", te.th32ThreadID, susp, rip, rsp, n, hits.join(" < ")); + } else { + let _ = writeln!(out, "thread {}: no context (suspend returned {:#x})", te.th32ThreadID, susp); + } + let _ = out.flush(); + CloseHandle(h); + } + } + ok = Thread32Next(snap, &mut te) != 0; + } + CloseHandle(snap); + let _ = writeln!(out, "=== done ==="); + let _ = out.flush(); + } +} + /// `XCL_THREAD_DUMP_AT`: every other thread of the process stopped for a moment – where it is /// (RIP) and the calls on its stack that lead there, in the log. pub fn dump_threads() { @@ -1562,6 +2204,115 @@ pub fn start_probes() { mod tests { use super::*; + /// MONITORX / MWAITX replaced in place: the instruction across an 8-byte boundary (GTA VI's + /// MONITORX at +7 of its block) becomes the 3-byte NOP, its neighbours kept; a second try + /// finds the new bytes and leaves them; one past its 16-byte block is not touched. + /// A crash's memory: the qwords around what a register points at, and one step further, + /// labelled from the register (one not 8-aligned too); near the end of what is readable as + /// many qwords as are; nothing for what is not readable; a context with registers of every + /// kind gone through without a fault. + #[test] + fn crash_memory_reads_what_registers_point_at_and_one_step_further() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + let inner: Box<[u64; 16]> = Box::new(std::array::from_fn(|k| 0x1111_0000 + k as u64)); + let inner_at = inner.as_ptr() as u64; + let mut outer: Box<[u64; 16]> = Box::new([0; 16]); + // the qword a register 3 bytes into outer[8] points into, and two further on + outer[8] = inner_at; + outer[10] = inner_at + 0x40; + let p = outer.as_ptr() as usize + 8 * 8 + 3; + let (line, after) = crash_memory_line("test", p).expect("readable"); + assert!(line.contains(&format!("[{inner_at:#018x}]")), "{line}"); + assert_eq!((after[0], after[2]), (inner_at, inner_at + 0x40)); + assert!(crash_memory_line("test", 0x10).is_none()); + assert!(crash_memory_line("test", 0xDEAD_0000_0000).is_none()); + assert_eq!(step_label("rsi", p, 0), "[rsi-0x3] ->"); + assert_eq!(step_label("rsi", p, 2), "[rsi+0xd] ->"); + assert_eq!(step_label("rbx", 0x1000, 1), "[rbx+0x8] ->"); + // the last 16 bytes of a region whose next page is reserved only: 2 qwords + let r = VirtualAlloc(std::ptr::null(), 0x2_0000, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(r != 0 && !VirtualAlloc(r as *const _, 0x1_0000, MEM_COMMIT, PAGE_READWRITE).is_null()); + *((r + 0x1_0000 - 16) as *mut u64) = 0x5151; + let (line, after) = crash_memory_line("end", r + 0x1_0000 - 16).expect("the last qwords are readable"); + assert_eq!(after, [0x5151, 0], "{line}"); + let mut c: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + c.Rsi = p as u64; + c.Rax = 0xDEAD_0000_0000; + c.Rbx = 1; + c.Rcx = u64::MAX; + c.Rdx = (r + 0x1_0000 - 8) as u64; + c.Rsp = &c as *const _ as u64; + let mut lines = Vec::new(); + crash_memory(&c, &mut |l| lines.push(l)); + VirtualFree(r as *mut _, 0, MEM_RELEASE); + let has = |s: &str| lines.iter().any(|l| l.contains(s)); + assert!(has(&format!("crash memory: rsi {p:#x}")), "{lines:#?}"); + assert!(has(&format!("crash memory: [rsi-0x3] -> {inner_at:#x}")), "{lines:#?}"); + assert!(has(&format!("crash memory: [rsi+0xd] -> {:#x}", inner_at + 0x40)), "{lines:#?}"); + assert!(has(&format!("crash memory: rdx {:#x}", r + 0x1_0000 - 8)), "{lines:#?}"); + assert!(!has("crash memory: rax") && !has("crash memory: rbx") && !has("crash memory: rcx"), "{lines:#?}"); + } + } + + /// A crash report's wait for a lock (`try_lock_within`), on mutexes of the test's own (the + /// report's own wait is spent once a process): a free lock is taken with the wait spent – each + /// is looked at once; one another thread holds is given up when all of the wait is spent; one + /// this thread holds itself (a fault inside the kernel's page map) is given up too, no deadlock. + #[test] + fn a_lock_is_tried_within_the_wait_left() { + let free = Mutex::new(1u32); + assert!(try_lock_within(&free, &AtomicU32::new(0)).is_some(), "a spent wait still looks once"); + let held = std::sync::Arc::new(Mutex::new(2u32)); + let (taken, is_taken) = std::sync::mpsc::channel(); + let (go, gone) = std::sync::mpsc::channel::<()>(); + let helper = { + let held = std::sync::Arc::clone(&held); + std::thread::spawn(move || { + let _g = held.lock().unwrap_or_else(|e| e.into_inner()); + let _ = taken.send(()); + let _ = gone.recv_timeout(std::time::Duration::from_secs(2)); + }) + }; + let _ = is_taken.recv(); + let left = AtomicU32::new(20); + let busy = try_lock_within(&held, &left).is_none(); + // (the helper lets go before anything is asserted) + drop(go); + let _ = helper.join(); + assert!(busy, "a lock another thread holds is given up"); + assert_eq!(left.load(Ordering::Relaxed), 0, "once all of the wait is spent"); + assert!(try_lock_within(&held, &AtomicU32::new(0)).is_some(), "let go: taken at its one look"); + let _mine = free.lock().unwrap(); + assert!(try_lock_within(&free, &AtomicU32::new(5)).is_none(), "held by this thread: given up, no deadlock"); + } + + #[test] + fn monitorx_and_mwaitx_are_replaced_in_place() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READ}; + unsafe { + let code = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, windows_sys::Win32::System::Memory::PAGE_EXECUTE_READWRITE) as usize; + assert_ne!(code, 0); + std::ptr::write_bytes(code as *mut u8, 0xCC, 0x40); + std::ptr::copy_nonoverlapping([0x0F, 0x01, 0xFA].as_ptr(), (code + 7) as *mut u8, 3); + std::ptr::copy_nonoverlapping([0x0F, 0x01, 0xFB].as_ptr(), (code + 0x10) as *mut u8, 3); + std::ptr::copy_nonoverlapping([0x0F, 0x01, 0xFB].as_ptr(), (code + 0x2E) as *mut u8, 3); + let mut old = 0u32; + windows_sys::Win32::System::Memory::VirtualProtect(code as *const _, 0x1000, PAGE_EXECUTE_READ, &mut old); + assert!(patch_in_place(code + 7, &[0x0F, 0x01, 0xFA], &[0x0F, 0x1F, 0x00])); + assert!(patch_in_place(code + 0x10, &[0x0F, 0x01, 0xFB], &[0xF3, 0x90, 0x90])); + assert!(!patch_in_place(code + 7, &[0x0F, 0x01, 0xFA], &[0x0F, 0x1F, 0x00]), "already replaced"); + assert!(!patch_in_place(code + 0x2E, &[0x0F, 0x01, 0xFB], &[0xF3, 0x90, 0x90]), "across its 16-byte block"); + let b = std::slice::from_raw_parts(code as *const u8, 0x40); + assert_eq!(b[..7], [0xCC; 7]); + assert_eq!(b[7..10], [0x0F, 0x1F, 0x00]); + assert_eq!(b[10..16], [0xCC; 6]); + assert_eq!(b[0x10..0x13], [0xF3, 0x90, 0x90]); + assert_eq!(b[0x2E..0x31], [0x0F, 0x01, 0xFB]); + VirtualFree(code as *mut _, 0, MEM_RELEASE); + } + } + #[test] fn bounded_cstr_stops_at_nul_limit_and_unreadable_memory() { unsafe { @@ -1678,14 +2429,16 @@ mod tests { assert!(s[0x40..0xC0].iter().all(|&b| b == 0)); assert!(s[0xC0..0x140].iter().all(|&b| b == 0xA5)); - // 3) end <= start: executes the single first clzero line [0x40..0x80) and steps only 3 bytes so add/cmp/jb runs natively + // 3) end <= start: the do-while loop zeroes the single first line [0x40..0x80) and + // leaves – the whole loop is stepped, RAX one line on, the flags of its compare for end in [buf + 0x40, buf] { std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x140); ctx = std::mem::zeroed(); (ctx.Rip, ctx.Rax, ctx.Rdx, ctx.EFlags) = (code as u64, (buf + 0x53) as u64, end as u64, 0x202); assert_eq!(emulate_console_only(&mut ctx), -1); - assert_eq!(ctx.Rip, code as u64 + 3); - assert_eq!(ctx.Rax, (buf + 0x53) as u64); + assert_eq!(ctx.Rip, code as u64 + 12); + assert_eq!(ctx.Rax, (buf + 0x93) as u64); + assert_eq!(ctx.EFlags, cmp_eflags(0x202, (buf + 0x93) as u64, end as u64)); let s = std::slice::from_raw_parts(buf as *const u8, 0x140); assert!(s[..0x40].iter().all(|&b| b == 0xA5)); assert!(s[0x40..0x80].iter().all(|&b| b == 0)); @@ -1740,30 +2493,680 @@ mod tests { } } - /// The title's fatal error / GPU hang watchdog at world load (`mov dword ptr [0], 0x4d8bd421`) - /// is resumed by skipping the crash, allowing long shader compilation to complete. + /// The shapes of GTA VI 1.0.2.1's report hooks and stall watchdog where the resume rule looks + /// (a scan of the title's code finds seven `mov dword ptr [0], imm32`: these five hooks' and the + /// watchdog's two). Synthetic: each sequence holds, at its place, every byte + /// `title_watchdog_resume` reads and every instruction the real-fault test runs + /// (`title_watchdog_resumes_real_faults_through_the_exception_handler`) as the title has them, + /// and `int3` everywhere else. `n` bytes: `parts` at their offsets, `int3` elsewhere. + const fn shape(parts: &[(usize, &[u8])]) -> [u8; N] { + let mut out = [0xCC; N]; + let mut i = 0; + while i < parts.len() { + let (at, bytes) = parts[i]; + let mut k = 0; + while k < bytes.len() { + out[at + k] = bytes[k]; + k += 1; + } + i += 1; + } + out + } + /// The report hook 0x4d8bd421 (render sync), the only one with a frame: `sub rsp, 0x48` … its + /// store at +0x63, `add rsp, 0x48; ret`. + const HOOK_4D8BD421: [u8; 0x74] = shape(&[ + (0x00, &[0x48, 0x83, 0xEC, 0x48]), // sub rsp, 0x48 + (0x63, &[0xC7, 0x04, 0x25, 0, 0, 0, 0, 0x21, 0xD4, 0x8B, 0x4D]), // mov dword ptr [0], 0x4d8bd421 + (0x6E, &[0x48, 0x83, 0xC4, 0x48, 0xC3]), // add rsp, 0x48; ret + ]); + /// … the four leaf hooks: the store, `ret`, the padding after it + const LEAF_HOOKS: [[u8; 16]; 4] = [ + [0xC7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x4B, 0xE9, 0xF1, 0x2E, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC], + [0xC7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0xE1, 0x5E, 0x79, 0x4D, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC], + [0xC7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x78, 0xE7, 0x0E, 0xB9, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC], + [0xC7, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x88, 0x30, 0x28, 0x18, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC], + ]; + /// … the watchdog's first loop from its heartbeat check (`mov r15, [heartbeat]`) past its own + /// store (+0x42, right after the hook's `call rax`) and the `int3` after it + const WATCHDOG_1: [u8; 0x4E] = shape(&[ + (0x00, &[0x4C, 0x8B, 0x3D, 0, 0, 0, 0]), // mov r15, [rip+disp32]: the heartbeat + (0x07, &[0x49, 0x89, 0xF6, 0xBD, 0x1E, 0, 0, 0]), // mov r14, rsi; mov ebp, 0x1e + (0x0F, &[0x48, 0x8D, 0x74, 0x24, 0x28]), // lea rsi, [rsp+0x28] + (0x14, &[0xE9, 0, 0, 0, 0]), // jmp rel32: the loop's top + (0x19, &[0x49, 0x89, 0xF6, 0x89, 0xEB]), // mov r14, rsi; mov ebx, ebp + (0x40, &[0xFF, 0xD0]), // call rax: the hook + (0x42, &[0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0]), // mov dword ptr [0], 0 + ]); + /// … its second loop from its heartbeat check past its own store (+0x49, right after the + /// hook's `call rax`) and the `xor eax, eax; int3` after it + const WATCHDOG_2: [u8; 0x57] = shape(&[ + (0x00, &[0x4C, 0x8B, 0x3D, 0, 0, 0, 0]), // mov r15, [rip+disp32]: the heartbeat + (0x07, &[0xBD, 0x1E, 0, 0, 0]), // mov ebp, 0x1e + (0x0C, &[0xE9, 0, 0, 0, 0]), // jmp rel32: the loop's top + (0x47, &[0xFF, 0xD0]), // call rax: the hook + (0x49, &[0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0]), // mov dword ptr [0], 0 + (0x54, &[0x31, 0xC0]), // xor eax, eax + ]); + + /// Two pages registered as an image (`modules`) while the value lives – what + /// `title_watchdog_resume` takes the title's image to be. + struct TestImage { + base: usize, + } + + impl TestImage { + unsafe fn new(name: &str) -> TestImage { + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + let base = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize; + assert_ne!(base, 0); + modules::register_mapped(std::sync::Arc::new(modules::MappedModule { + name: name.into(), path: name.into(), base, size: 0x2000, entry_rva: 0, is_dll: false, + exports: Default::default(), tls_callbacks: Mutex::new(Vec::new()), no_thread_calls: Default::default(), + initialized: std::sync::atomic::AtomicBool::new(true), stack_reserve: 0, + })); + TestImage { base } + } + + /// `bytes` at `offset` into the image: their address + unsafe fn put(&self, offset: usize, bytes: &[u8]) -> usize { + assert!(offset + bytes.len() <= 0x2000); + std::ptr::copy_nonoverlapping(bytes.as_ptr(), (self.base + offset) as *mut u8, bytes.len()); + self.base + offset + } + } + + impl Drop for TestImage { + fn drop(&mut self) { + modules::unregister_mapped(self.base); + unsafe { windows_sys::Win32::System::Memory::VirtualFree(self.base as *mut _, 0, windows_sys::Win32::System::Memory::MEM_RELEASE) }; + } + } + + /// a context at `rip` with its stack at `rsp`, rsi and r14 told apart, rbx and rdi set – and + /// every other byte of it told apart too, so that a resume writing any field shows + /// (`ctx_differs`) + fn watchdog_ctx(rip: usize, rsp: usize) -> windows_sys::Win32::System::Diagnostics::Debug::CONTEXT { + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = unsafe { std::mem::zeroed() }; + let bytes = unsafe { std::slice::from_raw_parts_mut(&mut ctx as *mut _ as *mut u8, std::mem::size_of_val(&ctx)) }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i as u8).wrapping_mul(37).wrapping_add(11); + } + (ctx.Rip, ctx.Rsp, ctx.Rsi, ctx.R14, ctx.Rbx, ctx.Rdi) = (rip as u64, rsp as u64, 0x5151, 0x1414, 0xB0B0, 0xD1D1); + ctx + } + + /// Where `a` differs from `b`: the offsets in CONTEXT of the 8-byte words not the same (none: + /// every byte is) – Rip is at 0xf8, Rsi at 0xa8, Rsp at 0x98. + fn ctx_differs(a: &windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, b: &windows_sys::Win32::System::Diagnostics::Debug::CONTEXT) -> Vec { + let bytes = |c: &windows_sys::Win32::System::Diagnostics::Debug::CONTEXT| unsafe { std::slice::from_raw_parts(c as *const _ as *const u8, std::mem::size_of_val(c)).to_vec() }; + let (a, b) = (bytes(a), bytes(b)); + a.chunks(8).zip(b.chunks(8)).enumerate().filter(|(_, (x, y))| x != y).map(|(i, _)| 8 * i).collect() + } + + /// GTA VI's stall watchdog on the shapes its binary has: each of its five report hooks – four + /// ending `ret`, 0x4d8bd421 `add rsp, 0x48; ret`, its return address 0x48 bytes up – called by + /// either loop's `call rax` is resumed at its epilogue: of its whole context (every byte) only + /// Rip changes, to the store + 11, and the resume is counted on this thread + /// (`WATCHDOG_RESUMED`). The watchdog's own store that epilogue returns to is resumed at that + /// loop's heartbeat check: in the first loop only Rip and Rsi change (rsi = r14, its countdown's + /// QPC pointer), in the second only Rip; counted too. (The lines the resumes write: + /// `title_watchdog_lines_wait_a_few_ms_for_a_busy_log` – their numbers are shared with the + /// other tests' threads.) #[test] - fn title_watchdog_resumes_fatal_crash_at_world_load() { - use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + fn title_watchdog_resumes_each_report_hook_and_then_the_watchdog_on_the_binarys_shapes() { unsafe { - let code = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize; - assert!(code != 0); - // mov dword ptr [0], 0x4d8bd421; ret - let insn = [0xC7u8, 0x04, 0x25, 0, 0, 0, 0, 0x21, 0xD4, 0x8B, 0x4D, 0xC3]; - std::ptr::copy_nonoverlapping(insn.as_ptr(), code as *mut u8, insn.len()); - let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); - ctx.Rip = code as u64; - assert!(title_watchdog_resume(&mut ctx)); - assert_eq!(ctx.Rip as usize, code + 11); - // A readable stack slot does not establish the frame layout at a trap. - let return_address = code + 0x200; - let saved_rsp = (&return_address as *const usize) as u64; - (code as *mut u8).add(11).write(0xCC); - ctx.Rip = code as u64; - ctx.Rsp = saved_rsp; - assert!(!title_watchdog_resume(&mut ctx)); - assert_eq!((ctx.Rip, ctx.Rsp), (code as u64, saved_rsp)); - VirtualFree(code as *mut _, 0, MEM_RELEASE); + let image = TestImage::new("watchdog_hooks.exe"); + // the shapes: the stores at their places + assert_eq!(HOOK_4D8BD421[0x63..0x74], [0xC7, 0x04, 0x25, 0, 0, 0, 0, 0x21, 0xD4, 0x8B, 0x4D, 0x48, 0x83, 0xC4, 0x48, 0xC3, 0xCC]); + assert_eq!(WATCHDOG_1[0x40..0x4E], [0xFF, 0xD0, 0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0xCC]); + assert_eq!(WATCHDOG_2[0x47..0x57], [0xFF, 0xD0, 0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0x31, 0xC0, 0xCC]); + // (the loop's heartbeat check, its store's offset from there, the first loop) + let loops = [(image.put(0x100, &WATCHDOG_1), 0x42usize, true), (image.put(0x200, &WATCHDOG_2), 0x49usize, false)]; + // (the hook's store, its frame, its imm32) + let mut hooks = vec![(image.put(0x400, &HOOK_4D8BD421) + 0x63, 0x48usize, 0x4d8b_d421u32)]; + for (k, bytes) in LEAF_HOOKS.iter().enumerate() { + hooks.push((image.put(0x500 + 0x20 * k, bytes), 0, u32::from_le_bytes(bytes[7..11].try_into().unwrap()))); + } + assert_eq!(hooks.iter().map(|h| h.2).collect::>(), [0x4d8b_d421, 0x2ef1_e94b, 0x4d79_5ee1, 0xb90e_e778, 0x1828_3088]); + for &(store, frame, imm) in &hooks { + for &(check, store_at, first) in &loops { + let ret = check + store_at; + // the return address above the hook's frame; below it, a pointer into the hook + // (a resume that read it would not find the watchdog's call there) + let mut stack = Box::new([store - 0x20; 32]); + stack[frame / 8] = ret; + let rsp = stack.as_ptr() as usize; + let mut ctx = watchdog_ctx(store, rsp); + let mut want = ctx; + want.Rip = (store + 11) as u64; + let before = WATCHDOG_RESUMED.with(|r| r.get()); + let loop_k = if first { 1 } else { 2 }; + assert!(title_watchdog_resume(&mut ctx), "hook {imm:#x} called from loop {loop_k}"); + assert_eq!(ctx_differs(&ctx, &want), Vec::::new(), "hook {imm:#x}: at its epilogue, nothing else changed"); + assert_eq!(WATCHDOG_RESUMED.with(|r| r.get())[0], before[0] + 1, "hook {imm:#x}: counted"); + // its epilogue (`add rsp, frame` and `ret`): into the watchdog's store + (ctx.Rip, ctx.Rsp) = (ret as u64, (rsp + frame + 8) as u64); + let mut want = ctx; + want.Rip = check as u64; + if first { + want.Rsi = want.R14; + } + assert!(title_watchdog_resume(&mut ctx), "loop {loop_k}'s store after hook {imm:#x}"); + assert_eq!(ctx_differs(&ctx, &want), Vec::::new(), "loop {loop_k}: at its heartbeat check{}, nothing else changed", if first { " with rsi = r14" } else { "" }); + let after = WATCHDOG_RESUMED.with(|r| r.get()); + assert_eq!((after[0], after[loop_k]), (before[0] + 1, before[loop_k] + 1), "loop {loop_k}'s store counted"); + } + } + } + } + + /// A store to address 0 the watchdog bypass does not know stays fatal: not resumed, its whole + /// context (every byte) as it was, not counted – an epilogue neither `ret` nor `add rsp, imm8; + /// ret`; a hook whose return address is not right after a `call rax`, not on the watchdog's own + /// store, in another image or none, not readable or null; a hook in no image (its return + /// address in none either); a stack slot not readable or past the address space; either loop's + /// store with another byte at one of the places the rule looks at, before or after it (the + /// first loop's on a stack that holds no watchdog return, so that its store followed by `ret` + /// is no hook either). Each differs from a copy that is resumed in that one point. + #[test] + fn title_watchdog_keeps_stores_to_address_0_it_does_not_know_fatal() { + use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + let image = TestImage::new("watchdog_unknown.exe"); + let other = TestImage::new("watchdog_other.exe"); + // not resumed, and nothing changed + let refused = |ctx: &mut CONTEXT| { + let was = *ctx; + let before = WATCHDOG_RESUMED.with(|r| r.get()); + !title_watchdog_resume(ctx) && ctx_differs(ctx, &was).is_empty() && WATCHDOG_RESUMED.with(|r| r.get()) == before + }; + let ret = image.put(0x100, &WATCHDOG_1) + 0x42; + // every slot the watchdog's return address: frames of 0, 0x48 and 0x80 alike + let stack = Box::new([ret; 32]); + let rsp = stack.as_ptr() as usize; + // the 0x4d8bd421 hook's store with another epilogue + let store = &HOOK_4D8BD421[0x63..0x6E]; + let with_epilogue = |at: usize, epilogue: &[u8]| { + let s = image.put(at, store); + image.put(at + 11, epilogue); + s + }; + let real = with_epilogue(0x180, &[0x48, 0x83, 0xC4, 0x48, 0xC3]); + assert!(title_watchdog_resume(&mut watchdog_ctx(real, rsp)), "its own epilogue"); + let others: [[u8; 5]; 6] = [ + [0x48, 0x83, 0xC4, 0x48, 0xCC], // add rsp, 0x48 – no ret + [0x48, 0x83, 0xC4, 0x80, 0xC3], // add rsp, -0x80 + [0x48, 0x83, 0xC5, 0x48, 0xC3], // add rbp, 0x48 + [0x48, 0x83, 0xEC, 0x48, 0xC3], // sub rsp, 0x48 + [0xCC, 0xC3, 0x00, 0x00, 0x00], // int3 + [0x5B, 0xC3, 0x00, 0x00, 0x00], // pop rbx; ret + ]; + for (k, e) in others.iter().enumerate() { + let s = with_epilogue(0x200 + 0x20 * k, e); + assert!(refused(&mut watchdog_ctx(s, rsp)), "epilogue {e:02x?}"); + } + // the 0x4d8bd421 hook with its frame past the address space + assert!(refused(&mut watchdog_ctx(real, usize::MAX - 0x20)), "its frame past the address space"); + // a leaf hook whose return address is … + let leaf = image.put(0x300, &LEAF_HOOKS[2]); + let at_ret = |r: usize| { + let st = Box::new([r; 4]); + refused(&mut watchdog_ctx(leaf, st.as_ptr() as usize)) + }; + assert!(!at_ret(ret), "the watchdog's: resumed"); + // … right after `call rcx`, not `call rax` + let mut call_rcx = WATCHDOG_1.to_vec(); + call_rcx[0x41] = 0xD1; + assert!(at_ret(image.put(0x400, &call_rcx) + 0x42), "after call rcx"); + // … right after `call rax`, not on the watchdog's store: `mov dword ptr [0], 1`, `ret` + let mut store_1 = WATCHDOG_1.to_vec(); + store_1[0x42 + 7] = 1; + assert!(at_ret(image.put(0x480, &store_1) + 0x42), "on mov dword ptr [0], 1"); + let mut ret_after = WATCHDOG_1.to_vec(); + ret_after[0x42] = 0xC3; + assert!(at_ret(image.put(0x500, &ret_after) + 0x42), "on ret"); + // … in another image, in none + assert!(at_ret(other.put(0x100, &WATCHDOG_1) + 0x42), "in another image"); + let free = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let reserved = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(free != 0 && reserved != 0); + std::ptr::copy_nonoverlapping(WATCHDOG_1.as_ptr(), free as *mut u8, WATCHDOG_1.len()); + assert!(at_ret(free + 0x42), "in no image"); + // … and a hook in no image either, its return address the watchdog's call there + std::ptr::copy_nonoverlapping(LEAF_HOOKS[2].as_ptr(), (free + 0x200) as *mut u8, 16); + let st = Box::new([free + 0x42; 4]); + assert!(refused(&mut watchdog_ctx(free + 0x200, st.as_ptr() as usize)), "a hook in no image"); + // … not readable, null + assert!(at_ret(reserved + 0x42), "not readable"); + assert!(at_ret(0) && at_ret(1), "null"); + // the stack slot not readable + assert!(refused(&mut watchdog_ctx(leaf, reserved + 0x100)), "a stack not readable"); + // the second loop's store with another byte before or after it (offsets from the copy's + // start; the store at +0x49) + let v2 = image.put(0x600, &WATCHDOG_2) + 0x49; + let mut ctx = watchdog_ctx(v2, rsp); + let mut want = ctx; + want.Rip = (v2 - 0x49) as u64; + assert!(title_watchdog_resume(&mut ctx) && ctx_differs(&ctx, &want).is_empty(), "the second loop's own bytes: resumed at its heartbeat check, nothing else changed"); + for (k, (i, b)) in [(0x0C, 0xEB), (0x08, 0x1F), (0x00, 0x48), (0x48, 0xD1), (0x54, 0x33), (0x56, 0xC3)].into_iter().enumerate() { + let mut w = WATCHDOG_2.to_vec(); + assert_ne!(w[i], b); + w[i] = b; + let s = image.put(0x680 + 0x60 * k, &w) + 0x49; + assert!(refused(&mut watchdog_ctx(s, rsp)), "the second loop with {b:#04x} at +{i:#x}"); + } + // the first loop's store with another byte at each place its rule looks at (offsets from + // the copy's start = its heartbeat check; the store at +0x42): `mov r15, [rip+..]` (+0x00), + // `mov r14, rsi; mov ebp, 0x1e` (+0x07, 8 bytes), `mov r14, rsi; mov ebx, ebp` (+0x19, 5), + // the store's imm32 and the `int3` after it (+0x49, 5) – a `nop` there (+0x4d) refused by + // the loop rules themselves; a `ret` there makes the store a leaf hook's bytes, refused by + // the hook branch before the loop rules are reached: on a stack with no watchdog return + // in it + let plain = Box::new([0usize; 32]); + let prsp = plain.as_ptr() as usize; + let v1 = image.put(0x900, &WATCHDOG_1) + 0x42; + let mut ctx = watchdog_ctx(v1, prsp); + let mut want = ctx; + (want.Rip, want.Rsi) = ((v1 - 0x42) as u64, want.R14); + assert!(title_watchdog_resume(&mut ctx) && ctx_differs(&ctx, &want).is_empty(), "the first loop's own bytes: resumed at its heartbeat check with rsi = r14, nothing else changed"); + for (k, (i, b)) in [(0x00, 0x48), (0x0A, 0xB8), (0x0B, 0x1F), (0x1C, 0x8B), (0x49, 0x01), (0x4D, 0x90), (0x4D, 0xC3)].into_iter().enumerate() { + let mut w = WATCHDOG_1.to_vec(); + assert_ne!(w[i], b); + w[i] = b; + let s = image.put(0x980 + 0x60 * k, &w) + 0x42; + assert!(refused(&mut watchdog_ctx(s, prsp)), "the first loop with {b:#04x} at +{i:#x}"); + } + VirtualFree(free as *mut _, 0, MEM_RELEASE); + VirtualFree(reserved as *mut _, 0, MEM_RELEASE); + } + } + + /// The line each of the three resumes writes (a report hook's, the first loop's, the second's) + /// waits for a log file another thread is writing, a few ms at most (`log::try_write_soon`): + /// with the file held until this thread tries again, the line is written once it is let go – + /// whole, with its number (`#n`, below 4 or a power of two: shared with the other tests' + /// threads, so resumes are made until one's line is due); held past those few ms, the line is + /// given up – within 100 ms – and the resume is the same. (The test process has no log file: + /// what is looked at is the line given to the write itself, `put`, its text, and how often it + /// tried.) + #[test] + fn title_watchdog_lines_wait_a_few_ms_for_a_busy_log() { + use std::time::{Duration, Instant}; + unsafe { + let image = TestImage::new("watchdog_log.exe"); + let first = image.put(0x100, &WATCHDOG_1); + let second = image.put(0x200, &WATCHDOG_2); + let leaf = image.put(0x400, &LEAF_HOOKS[0]); + // the leaf hook's return address: the first loop's call + let stack = Box::new([first + 0x42; 4]); + let rsp = stack.as_ptr() as usize; + let tid = windows_sys::Win32::System::Threading::GetCurrentThreadId(); + // (the first `readable` of the process sets up the unified-memory windows and logs that, + // waiting for the file: done before it is held – in the title long before any fire) + let _ = crate::gpu::uma::get(); + // (kind, where its store is, what it resumes at, its line before and after its number) + let cases = [ + (0, leaf, leaf + 11, "the title's stall watchdog called its report hook (#", format!("): hook 0x2ef1e94b at {leaf:#x} (image+0x400); resuming at the hook's epilogue, which returns into the watchdog's own store")), + (1, first + 0x42, first, "the title's stall watchdog fired (#", "); resuming at the recognized heartbeat check".to_string()), + (2, second + 0x49, second, "the title's stall watchdog fired in its second loop (#", "); resuming at the recognized heartbeat check".to_string()), + ]; + for (k, store, resumed, head, tail) in &cases { + for past in [false, true] { + // (a moment: up to 5 tries – a thread put off by the system for 5 ms between + // seeing this one try and letting go makes one fail) + let mut tried = Vec::new(); + for _attempt in 0..5 { + let (held_tx, held_rx) = std::sync::mpsc::channel::<()>(); + let (done_tx, done_rx) = std::sync::mpsc::channel::<()>(); + let holder = std::thread::spawn(move || { + let file = crate::log::soon_test::hold_file(); + held_tx.send(()).unwrap(); + let t = Instant::now(); + let saw = if past { + // held until the resume came back + done_rx.recv_timeout(Duration::from_secs(5)).is_ok() + } else { + // let go as soon as this test's thread tries again + loop { + if crate::log::soon_test::waiting(tid) { + break true; + } + if t.elapsed() > Duration::from_secs(5) { + break false; + } + std::hint::spin_loop(); + } + }; + drop(file); + saw + }); + held_rx.recv().unwrap(); + let _ = crate::log::soon_test::take_seen(); + // resumes of this kind – each with its context as the rule leaves it – until + // one's line is due: (not given up, how long that resume took) + let mut due = None; + for _ in 0..4096 { + let mut ctx = watchdog_ctx(*store, rsp); + let mut want = ctx; + want.Rip = *resumed as u64; + if *k == 1 { + want.Rsi = want.R14; + } + let said = WATCHDOG_SAID.with(|s| s.get())[*k]; + let t = Instant::now(); + assert!(title_watchdog_resume(&mut ctx), "kind {k}"); + let took = t.elapsed(); + assert_eq!(ctx_differs(&ctx, &want), Vec::::new(), "kind {k}: resumed as ever"); + let now = WATCHDOG_SAID.with(|s| s.get())[*k]; + if now[0] > said[0] { + due = Some((now[1] - said[1], took)); + break; + } + } + let _ = done_tx.send(()); + let saw = holder.join().unwrap(); + let (said, took) = due.expect("a line due within 4096 resumes"); + let seen = crate::log::soon_test::take_seen(); + if past { + assert!(saw, "kind {k}: the file held until the resume came back"); + assert_eq!((said, seen.as_ref().map(|s| &s.0)), (0, None), "kind {k}: held past the few ms, the line is given up"); + // (about 5 ms and a yield: 100 ms leaves room for a loaded machine) + assert!(took >= Duration::from_millis(4) && took < Duration::from_millis(100), "kind {k}: given up after a few ms ({took:?})"); + tried.push(true); + break; + } + let ok = saw && said == 1 && seen.as_ref().is_some_and(|(line, tries)| { + let n = line.strip_prefix(head).and_then(|l| l.strip_suffix(tail.as_str())).and_then(|n| n.parse::().ok()); + assert!(n.is_some_and(|n| n < 4 || n.is_power_of_two()), "kind {k}: the line whole, a number due: {line}"); + *tries > 0 + }); + tried.push(ok); + if ok { + break; + } + eprintln!("kind {k}: the line not written after the file was let go (holder saw the try: {saw}, written: {said}, seen: {seen:?}, {took:?}) – again"); + } + assert!(tried.last() == Some(&true), "kind {k} (held past the few ms: {past}): {tried:?}"); + } + } + } + } + + /// What `xcl_watchdog_e2e_run` is given and what the stubs record (its offsets: the assembly's). + #[repr(C)] + #[derive(Clone, Copy, Debug, Default)] + struct Drive { + /// the copy's `call rax` the driver jumps to, and the hook (rax there) + call: u64, + hook: u64, + /// rbx, rbp, rsi, rdi, r12, r13, r14, r15 at that call (r14: the QPC pointer's stand-in) + set: [u64; 8], + /// xmm6 at that call + xmm6: [u64; 2], + /// the driver's rsp at its jump: the record's address at [rsp] and [rsp + 8] there + rsp: u64, + /// 1 or 2: the first or the second loop's stub ran; 0xdead: `e2e_safety_net` ended the run + reached: u64, + /// at the stub: rbx, rbp, rsi, rdi, r12, r13, r14, r15, rsp + got: [u64; 9], + got_xmm6: [u64; 2], + /// (`e2e_safety_net`) the exception's code, address, first two parameters, rip and rsp + fault: [u64; 6], + } + const _: () = assert!( + std::mem::offset_of!(Drive, set) == 0x10 + && std::mem::offset_of!(Drive, xmm6) == 0x50 + && std::mem::offset_of!(Drive, rsp) == 0x60 + && std::mem::offset_of!(Drive, reached) == 0x68 + && std::mem::offset_of!(Drive, got) == 0x70 + && std::mem::offset_of!(Drive, got_xmm6) == 0xB8 + ); + + // The driver: saves the registers the Windows x64 ABI has a callee keep (rbx, rbp, rsi, rdi, + // r12-r15, xmm6 – the resumed loops write rbp, rsi, r14 and r15), leaves the record's address + // twice on its stack with rsp 16-byte aligned as a `call` wants it, sets the registers from + // the record and jumps to the copy's `call rax`. The stubs the copies' loops jump to after the + // resumes record the registers (rax: the record, from the stack) and – also where + // `e2e_safety_net` ends a run – restore the saved ones and return to the test. + std::arch::global_asm!( + r#" + .globl xcl_watchdog_e2e_run + xcl_watchdog_e2e_run: + push rbx + push rbp + push rsi + push rdi + push r12 + push r13 + push r14 + push r15 + sub rsp, 0x18 + movdqu xmmword ptr [rsp], xmm6 + push rcx + push rcx + mov qword ptr [rcx + 0x60], rsp + movdqu xmm6, xmmword ptr [rcx + 0x50] + mov rbx, qword ptr [rcx + 0x10] + mov rbp, qword ptr [rcx + 0x18] + mov rsi, qword ptr [rcx + 0x20] + mov rdi, qword ptr [rcx + 0x28] + mov r12, qword ptr [rcx + 0x30] + mov r13, qword ptr [rcx + 0x38] + mov r14, qword ptr [rcx + 0x40] + mov r15, qword ptr [rcx + 0x48] + mov rax, qword ptr [rcx + 0x08] + jmp qword ptr [rcx] + + .globl xcl_watchdog_e2e_stub1 + xcl_watchdog_e2e_stub1: + xchg rax, qword ptr [rsp] + mov qword ptr [rax + 0x68], 1 + jmp 2f + + .globl xcl_watchdog_e2e_stub2 + xcl_watchdog_e2e_stub2: + xchg rax, qword ptr [rsp] + mov qword ptr [rax + 0x68], 2 + 2: + mov qword ptr [rax + 0x70], rbx + mov qword ptr [rax + 0x78], rbp + mov qword ptr [rax + 0x80], rsi + mov qword ptr [rax + 0x88], rdi + mov qword ptr [rax + 0x90], r12 + mov qword ptr [rax + 0x98], r13 + mov qword ptr [rax + 0xA0], r14 + mov qword ptr [rax + 0xA8], r15 + mov qword ptr [rax + 0xB0], rsp + movdqu xmmword ptr [rax + 0xB8], xmm6 + + .globl xcl_watchdog_e2e_restore + xcl_watchdog_e2e_restore: + add rsp, 0x10 + movdqu xmm6, xmmword ptr [rsp] + add rsp, 0x18 + pop r15 + pop r14 + pop r13 + pop r12 + pop rdi + pop rsi + pop rbp + pop rbx + ret + "# + ); + + extern "win64" { + /// Runs `drive`: back here from one of the stubs (or `e2e_safety_net`). + fn xcl_watchdog_e2e_run(drive: *mut Drive); + fn xcl_watchdog_e2e_stub1(); + fn xcl_watchdog_e2e_stub2(); + fn xcl_watchdog_e2e_restore(); + } + + /// The run in progress (`title_watchdog_resumes_real_faults_through_the_exception_handler`): its + /// record (0: none), its thread, the image its code is in. + static DRIVE: AtomicUsize = AtomicUsize::new(0); + static DRIVE_TID: AtomicU32 = AtomicU32::new(0); + static DRIVE_IMAGE: AtomicUsize = AtomicUsize::new(0); + + /// The last vectored handler while the real faults run: an exception of the run's thread in the + /// run's image that no handler before it resumed (`null_call_logger` should have) ends that run + /// – the exception noted in its record, the driver's caller returned to with its stack and + /// registers – instead of the whole test process. + unsafe extern "system" fn e2e_safety_net(info: *mut EXCEPTION_POINTERS) -> i32 { + let d = DRIVE.load(Ordering::Acquire) as *mut Drive; + if d.is_null() + || info.is_null() + || (*info).ExceptionRecord.is_null() + || (*info).ContextRecord.is_null() + || windows_sys::Win32::System::Threading::GetCurrentThreadId() != DRIVE_TID.load(Ordering::Acquire) + { + return 0; + } + let (rec, ctx) = (&*(*info).ExceptionRecord, &mut *(*info).ContextRecord); + let base = DRIVE_IMAGE.load(Ordering::Acquire); + if !(base..base + 0x2000).contains(&(ctx.Rip as usize)) { + return 0; + } + (*d).fault = [rec.ExceptionCode as u32 as u64, rec.ExceptionAddress as u64, rec.ExceptionInformation[0] as u64, rec.ExceptionInformation[1] as u64, ctx.Rip, ctx.Rsp]; + (*d).reached = 0xDEAD; + ctx.Rsp = (*d).rsp; + ctx.Rip = xcl_watchdog_e2e_restore as usize as u64; + -1 // EXCEPTION_CONTINUE_EXECUTION + } + + /// A vectored handler, removed when the guard drops (also when an assertion unwinds). + struct Veh(*mut c_void); + + impl Drop for Veh { + fn drop(&mut self) { + unsafe { windows_sys::Win32::System::Diagnostics::Debug::RemoveVectoredExceptionHandler(self.0) }; + } + } + + /// The resumes on real access violations, through the handler the title's process has + /// (`null_call_logger`, registered first for the test's length as `install_crash_handler` + /// registers it): in one image, a leaf hook (`mov dword ptr [0], 0x2ef1e94b; ret`) and a hook + /// with a frame (`sub rsp, 0x48; mov dword ptr [0], 0x4d8bd421; add rsp, 0x48; ret`), each + /// entered through either loop's shape and its `call rax` – each with the disp32 of its `mov + /// r15, [rip+..]` (a qword in the image: the heartbeat's stand-in) and the rel32 of its `jmp` + /// (a stub's: the loop's top) filled in – with r14 the QPC pointer's + /// stand-in and rsi apart from it. The hook's store faults and is resumed at its epilogue, + /// which returns into the watchdog's store; that faults and is resumed at the loop's heartbeat + /// check, which runs on to the stub: the first loop with r14 = the QPC pointer (the rsi = r14 a + /// resume there gives it), rsi = rsp + 0x28 (its `lea`), the second with r14 and rsi as they + /// were; both with ebp = 30 and r15 = the heartbeat as their loops set them, rbx, rdi, r12, + /// r13, xmm6 and rsp as at the call, and both resumes counted on this thread (the handler runs + /// on the faulting one). Under Wine and Rosetta 2 as the title would. No fault is raised that + /// the rule would not resume (each context is put to it first), and one the handler does not + /// resume ends its run through `e2e_safety_net`, not the process. + #[test] + fn title_watchdog_resumes_real_faults_through_the_exception_handler() { + use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, FlushInstructionCache}; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentThreadId}; + unsafe { + let image = TestImage::new("watchdog_faults.exe"); + // (int3 where nothing is put: a wrong jump traps in the image, where the safety net is) + std::ptr::write_bytes(image.base as *mut u8, 0xCC, 0x2000); + let leaf = image.put(0x000, &LEAF_HOOKS[0]); + let mut framed = vec![0x48, 0x83, 0xEC, 0x48]; + framed.extend_from_slice(&HOOK_4D8BD421[0x63..0x74]); + let framed = image.put(0x040, &framed); + const HEARTBEAT: u64 = 0x7A1E_E2E0_0000_00B7; + let heartbeat = image.put(0x400, &HEARTBEAT.to_le_bytes()); + let trampoline = |at: usize, to: usize| { + let mut t = vec![0xFF, 0x25, 0, 0, 0, 0]; // jmp [rip + 0] + t.extend_from_slice(&(to as u64).to_le_bytes()); + image.put(at, &t) + }; + let stubs = [trampoline(0x300, xcl_watchdog_e2e_stub1 as usize), trampoline(0x320, xcl_watchdog_e2e_stub2 as usize)]; + let rel32 = |end: usize, to: usize| i32::try_from(to as i64 - end as i64).unwrap().to_le_bytes(); + // the shapes with the two fields the rule does not look at filled in (it checks the + // opcodes before them: `4c 8b 3d`, the first loop nothing of its `jmp`, the second its + // `e9`) + let (one, two) = (image.base + 0x100, image.base + 0x200); + let mut w1 = WATCHDOG_1.to_vec(); + assert_eq!((&w1[..3], w1[0x14]), (&[0x4C, 0x8B, 0x3D][..], 0xE9), "the first loop: mov r15, [rip+disp32] at +0, jmp rel32 at +0x14"); + w1[3..7].copy_from_slice(&rel32(one + 7, heartbeat)); + w1[0x15..0x19].copy_from_slice(&rel32(one + 0x19, stubs[0])); + image.put(0x100, &w1); + let mut w2 = WATCHDOG_2.to_vec(); + assert_eq!((&w2[..3], w2[0x0C]), (&[0x4C, 0x8B, 0x3D][..], 0xE9), "the second loop: mov r15, [rip+disp32] at +0, jmp rel32 at +0xc"); + w2[3..7].copy_from_slice(&rel32(two + 7, heartbeat)); + w2[0x0D..0x11].copy_from_slice(&rel32(two + 0x11, stubs[1])); + image.put(0x200, &w2); + assert!(FlushInstructionCache(GetCurrentProcess(), image.base as *const c_void, 0x2000) != 0); + // (what, the hook's entry, its store, its frame) + let hooks = [("the leaf hook 0x2ef1e94b", leaf, leaf, 0usize), ("the hook 0x4d8bd421 with a frame of 0x48", framed, framed + 4, 0x48usize)]; + // (the loop, its copy, its `call rax`, its store) + let loops = [(1usize, one, one + 0x40, one + 0x42), (2, two, two + 0x47, two + 0x49)]; + // the rule on the contexts the faults will have first: no fault it would not resume + for &(k, copy, _, store) in &loops { + for &(what, _, hook_store, frame) in &hooks { + let mut st = Box::new([0usize; 32]); + st[frame / 8] = store; + let mut ctx = watchdog_ctx(hook_store, st.as_ptr() as usize); + assert!(title_watchdog_resume(&mut ctx) && ctx.Rip as usize == hook_store + 11, "{what} via loop {k}: the rule resumes its store"); + let mut ctx = watchdog_ctx(store, st.as_ptr() as usize); + assert!(title_watchdog_resume(&mut ctx) && ctx.Rip as usize == copy, "{what} via loop {k}: the rule resumes the loop's store"); + } + } + let resume = AddVectoredExceptionHandler(1, Some(null_call_logger)); + if resume.is_null() { + eprintln!("SKIPPED: AddVectoredExceptionHandler(1, null_call_logger) failed (error {})", windows_sys::Win32::Foundation::GetLastError()); + return; + } + let resume = Veh(resume); + let net = AddVectoredExceptionHandler(0, Some(e2e_safety_net)); + if net.is_null() { + eprintln!("SKIPPED: AddVectoredExceptionHandler(0, the safety net) failed (error {})", windows_sys::Win32::Foundation::GetLastError()); + return; + } + let net = Veh(net); + DRIVE_IMAGE.store(image.base, Ordering::Release); + DRIVE_TID.store(GetCurrentThreadId(), Ordering::Release); + let runs = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + const QPC: u64 = 0x7A1E_E2E0_0000_0014; + // rbx, rbp, rsi, rdi, r12, r13, r14 (the QPC pointer), r15 + let set = [0xB0B0_B0B0_B0B0_B0B0, 0xBBBB_0000_BBBB_0000, 0x5151_5151_5151_5151, 0xD1D1_D1D1_D1D1_D1D1, 0x1212_1212_1212_1212, 0x1313_1313_1313_1313, QPC, 0xF15F_15F1_5F15_F15F]; + for &(k, _, call, _) in &loops { + for &(what, entry, _, _) in &hooks { + let mut d = Drive { call: call as u64, hook: entry as u64, set, xmm6: [0x0123_4567_89AB_CDEF, 0xFEDC_BA98_7654_3210], ..Default::default() }; + let before = WATCHDOG_RESUMED.with(|r| r.get()); + eprintln!("E2E: {what} via loop {k}: its store and the loop's fault now"); + DRIVE.store(&mut d as *mut Drive as usize, Ordering::Release); + xcl_watchdog_e2e_run(&mut d); + DRIVE.store(0, Ordering::Release); + let after = WATCHDOG_RESUMED.with(|r| r.get()); + let [rbx, rbp, rsi, rdi, r12, r13, r14, r15, rsp] = d.got; + eprintln!( + "E2E: {what} via loop {k}: back through stub {:#x} – rsp {rsp:#x} (at the call {:#x}), rbp {rbp}, r15 {r15:#x}, r14 {r14:#x}, rsi {rsi:#x}, rbx {rbx:#x}, rdi {rdi:#x}, r12 {r12:#x}, r13 {r13:#x}, xmm6 {:x?}; resumed here: hooks +{}, loop 1 +{}, loop 2 +{}; safety net: {:x?}", + d.reached, d.rsp, d.got_xmm6, after[0] - before[0], after[1] - before[1], after[2] - before[2], d.fault + ); + assert_eq!(d.reached, k as u64, "{what} via loop {k}: back through the loop's stub, not the safety net (exception code, address, parameters, rip, rsp: {:x?})", d.fault); + assert_eq!(rsp, d.rsp, "{what} via loop {k}: the stack as at the call"); + assert_eq!((rbx, rdi, r12, r13), (set[0], set[3], set[4], set[5]), "{what} via loop {k}: rbx, rdi, r12, r13 as at the call"); + assert_eq!((rbp, r15), (30, HEARTBEAT), "{what} via loop {k}: ebp = 30 and r15 = the heartbeat, as the loop sets them"); + if k == 1 { + assert_eq!((r14, rsi), (QPC, rsp + 0x28), "{what} via loop 1: r14 the QPC pointer (rsi = r14 at the resume), rsi its lea"); + } else { + assert_eq!((r14, rsi), (QPC, set[2]), "{what} via loop 2: r14 and rsi as at the call"); + } + assert_eq!(d.got_xmm6, d.xmm6, "{what} via loop {k}: xmm6 as at the call"); + assert_eq!((after[0], after[k], after[3 - k]), (before[0] + 1, before[k] + 1, before[3 - k]), "{what} via loop {k}: the two resumes, on this thread"); + } + } + })); + DRIVE.store(0, Ordering::Release); + drop(net); + drop(resume); + DRIVE_TID.store(0, Ordering::Release); + if let Err(e) = runs { + std::panic::resume_unwind(e); + } } } diff --git a/crates/xcl/src/gpu/fence.rs b/crates/xcl/src/gpu/fence.rs index 4d70280..b50fd92 100644 --- a/crates/xcl/src/gpu/fence.rs +++ b/crates/xcl/src/gpu/fence.rs @@ -73,6 +73,7 @@ pub(crate) unsafe fn wait( } let start = Instant::now(); let mut remaining = timeout_ms; + let _held = crate::waitwatch::xcl(crate::waitwatch::X_GPU_FENCE, target); loop { let status = WaitForSingleObject(event, remaining); let error = (status == WAIT_FAILED).then(Error::from_thread); diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 859fbf3..03d5da4 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -828,7 +828,10 @@ fn process_cache_lock(file: &Path) -> Result { if handle.is_null() { return Err("DXIL cache: cannot create the cross-process mutex".into()); } - let wait = unsafe { WaitForSingleObject(handle, INFINITE) }; + let wait = { + let _held = crate::waitwatch::xcl(crate::waitwatch::X_DXC_MUTEX, 0); + unsafe { WaitForSingleObject(handle, INFINITE) } + }; if wait != WAIT_OBJECT_0 && wait != WAIT_ABANDONED { unsafe { CloseHandle(handle) }; return Err(format!("DXIL cache: waiting for the cross-process mutex failed ({wait:#x})")); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 8ea0f96..f646cb3 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -64,6 +64,9 @@ pub(super) struct Em { /// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits, /// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`. safe_barrier: bool, + /// a multi-wave Compute/Mesh program whose `s_barrier` stays a group barrier that waits + /// for every wave (`XCL_SAFE_BARRIER=0`): no dispatch-wide budget trip (`trip`) + real_group_barriers: bool, } /// Instructions without an effect in this execution model. @@ -490,6 +493,7 @@ impl Em { has_f64_round_op: false, dynamic_f16_rm: false, safe_barrier: false, + real_group_barriers: false, } } @@ -551,6 +555,19 @@ impl Em { self.safe_barrier = has_s_barrier && self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1) && std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0"); + self.real_group_barriers = has_s_barrier && self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1) && !self.safe_barrier; + } + + /// The dispatch-wide trip on the loop budget (`PRELUDE_TRIP`, `TRIP_AT_START`, + /// `LOOP_GUARD_TRIP`): a compute program counts its waves whose `xcl_budget` ran out, and + /// once a dispatch has `budget_trip_waves` of them its waves that start later skip their + /// loops. A lane's budget bounds one wave; a dispatch of thousands of groups whose loops + /// all run to it can keep a GPU busy for minutes. Not where a group barrier waits for every + /// wave – split wave64 halves meeting at barriers (`XCL_WAVE64_SPIN=0`), group barriers + /// without the safe form (`XCL_SAFE_BARRIER=0`): a wave that skipped its loops and one that + /// did not would wait there for each other. Off with `XCL_BUDGET_TRIP_WAVES=0`. + pub(super) fn trip(&self) -> bool { + matches!(self.opt.mode, Mode::Compute(_)) && budget_trip_waves() != 0 && !(self.x64() && !self.x64_spin()) && !self.real_group_barriers } pub fn take(&mut self) -> String { @@ -4405,6 +4422,11 @@ impl Em { } } self.safe_barrier_prelude(&mut h); + // (a program without loops has nothing to trip: no atomic for each of its waves) + let trip = self.trip() && body.contains("xcl_budget_spent()"); + if trip { + h.push_str(PRELUDE_TRIP); + } 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{{" @@ -4452,6 +4474,9 @@ impl Em { }; let _ = writeln!(h, " uint v{v} = {init};"); } + if trip { + h.push_str(TRIP_AT_START); + } h.push_str(body); if self.safe_barrier { h.push_str(" xcl_s_barrier_exit();\n"); @@ -5558,6 +5583,49 @@ void xcl_s_barrier() { } "#; +/// Waves of a dispatch of a compute program whose own loop budget (`xcl_budget`) may run out +/// before its waves that start later skip their loops (`Em::trip`): `XCL_BUDGET_TRIP_WAVES`, +/// 64 by default; 0: no trip (the HLSL as before). Counted in hardware waves; XCL writes it +/// into each dispatch's `res` block (word 2), so it is not part of the translation. +pub fn budget_trip_waves() -> u32 { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_BUDGET_TRIP_WAVES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64)) +} + +/// The dispatch-wide budget (`Em::trip`): `res` word 0 counts the waves whose budget ran out – +/// an add from the first lane of the lanes that find it spent together at a guard +/// (`LOOP_GUARD_TRIP`): one a wave when its lanes loop alike, more when lanes that left earlier +/// loops apart run out at different guards; word 2 is how many may (XCL writes it, and a +/// serial of the dispatch into word 1: the window uploads leave a chunk alone whose bytes are +/// as they were, so a count the GPU left at that address would otherwise carry over to a later +/// dispatch). Only in programs with loops. +pub(super) const PRELUDE_TRIP: &str = r#" +static bool xcl_spent = false; +void xcl_budget_spent() { + if (!xcl_spent) { + xcl_spent = true; + if (WaveIsFirstLane()) { uint o; res.InterlockedAdd(0u, 1u, o); } + } +} +"#; + +/// At the start of `main` (`Em::trip`): a wave that starts once its dispatch has its count of +/// spent waves skips its loops – each leaves at its first guard, as a spent one does. A wave +/// decides as a whole (its first lane reads the count, one atomic); the halves of a split +/// console wave may decide apart – their exchanges then time out once (`xcl_x_meet`, +/// bounded) and the wave goes on with its own half's values. +pub(super) const TRIP_AT_START: &str = " { + uint xcl_trip = 0u; + if (WaveIsFirstLane()) { + uint n = 0u; + uint w = res.Load(8u); + res.InterlockedAdd(0u, 0u, n); + xcl_trip = (w != 0u && n >= w) ? 1u : 0u; + } + if (WaveReadLaneFirst(xcl_trip) != 0u) { xcl_budget = 0u; xcl_spent = true; } + } +"; + 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 7a6641b..eababec 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -590,6 +590,20 @@ type MemoKey = (u64, u64, Option, usize, Option, Vec); /// leaves at its next iteration and the program runs to its end. const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;"; +/// `LOOP_GUARD` of a compute program with the dispatch-wide trip (`emit::Em::trip`): a wave +/// whose budget is spent counts once for its dispatch (`xcl_budget_spent`), then leaves as +/// before. +const LOOP_GUARD_TRIP: &str = "if (xcl_budget == 0u) { xcl_budget_spent(); break; } xcl_budget--;"; + +/// The loop guard `em`'s program gets. +fn loop_guard(em: &emit::Em) -> &'static str { + if em.trip() { + LOOP_GUARD_TRIP + } else { + LOOP_GUARD + } +} + /// The loops the translator emits: ranges spanned by backward jumps (far jumps included), /// partly overlapping ones merged until they nest, sorted. `x64_masks` uses them for the /// exits through `LOOP_GUARD`. @@ -942,7 +956,7 @@ fn emit_structured( } let raised: BTreeSet = match it { Item::Loop { a, b, latch, entry } => { - body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {LOOP_GUARD}\n")); + body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {}\n", loop_guard(em))); let (lcont, lin) = if entry.is_none() { (Some(a), &inner) } else { (None, &none) }; let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, lcont, lin, d + 1, blocks, flags); for &t in &r { @@ -1047,7 +1061,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d let start = c.leaders[i]; let inner = c.loops.iter().filter(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)).max_by_key(|x| x.1).copied(); if let Some((a, b)) = inner { - body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {LOOP_GUARD}\n")); + body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {}\n", loop_guard(em))); emit_range(c, em, body, a, b, depth + 1, blocks, flags); body.push_str(&format!("{pad}}}\n")); i = c.leaders.partition_point(|&l| l < b); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b256390..b80bebb 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -106,6 +106,82 @@ 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()) } +/// The bytes of DXIL the translation cache holds for `blob` – the file `console_to_dxil_for` +/// loads with these parameters and the title's memory windows – from its header (the DXIL is not +/// read). None when there is none: not translated yet, the cache off or bypassed by a debug +/// switch. A size found is kept for the run (a program's clones). +pub fn translated_dxil_len(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Option { + if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { + return None; + } + static SIZES: OnceLock>> = OnceLock::new(); + let sizes = SIZES.get_or_init(Default::default); + let windows = mem_windows(); + let k = (crate::gpu::shader::fnv64(blob), blob.len(), stage, sampler_base, windows, split_wave64); + if let Some(&n) = sizes.lock().unwrap().get(&k) { + return Some(n as usize); + } + let n = translated::dxil_len(&dxc::cache_dir(), translated::identity(), blob, stage, sampler_base, windows, split_wave64)?; + sizes.lock().unwrap().insert(k, n.min(u32::MAX as usize) as u32); + Some(n) +} + +/// The static samplers of the translation the cache holds for a program known by its hash only +/// (`fnv64` of its bytes) – the file `console_to_dxil_for` loads with these parameters and the +/// title's memory windows –, None: none. Only the header's magic and identity are checked (the +/// bytes are not at hand) and that the file is whole: what orders a pipeline in the workers' queue +/// (`pso_async::tier_of`), never what one is built from. A translation found, and every one this +/// run's builds stored or loaded (`translated::cached_in`), is kept for the run; none found is not: +/// the next look reads the disk again, so a translation a build stores meanwhile is found (a pixel +/// shader has tens of pipelines, and the first one's build translates it for all). +pub fn translated_by_hash(hash: u64, stage: Stage, sampler_base: u32, split_wave64: bool) -> Option { + let (dir, allowed) = translation_lookup(); + let at = match stage { + Stage::Vertex => 0, + Stage::Pixel => 1, + Stage::Compute => 2, + }; + if !allowed[at] { + return None; + } + translated_by_hash_in(dir, translated::identity(), hash, stage, sampler_base, mem_windows(), split_wave64) +} + +/// Where `translated_by_hash` looks – the cache folder – and for which stages (vertex, pixel, compute) +/// the cache may be used (`cache_allowed`'s debug switches), read once: `host_main` asks first, before +/// the title runs, so that no title call (a pipeline's first bind, `pso_async::tier_of`) reads the +/// environment for it; they do not change while a title runs. +pub fn translation_lookup() -> &'static (PathBuf, [bool; 3]) { + static WHERE: OnceLock<(PathBuf, [bool; 3])> = OnceLock::new(); + WHERE.get_or_init(|| { + let present = |name: &str| std::env::var_os(name).is_some(); + (dxc::cache_dir(), [Stage::Vertex, Stage::Pixel, Stage::Compute].map(|s| cache_allowed(s, present))) + }) +} + +/// `translated_by_hash` in the cache folder `dir` of the translator identity `ident` (0: the cache +/// off – none) with `windows` memory windows. +pub fn translated_by_hash_in(dir: &Path, ident: u64, hash: u64, stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Option { + translated::samplers_by_hash(dir, ident, hash, stage, sampler_base, windows, split_wave64) +} + +/// (tests) `blob`'s translation `compiled` through the translation cache in `dir` (`ident`), as a +/// build's: stored when not there, else loaded – what `translated_by_hash_in` then finds. +#[cfg(test)] +pub(crate) fn translate_for_test(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool, compiled: Compiled) -> Compiled { + translated::cached_in(dir, ident, blob, stage, sampler_base, windows, split, || Ok(compiled)).unwrap() +} + +/// This build's translator identity – the translation cache's folder (`XCL_TRANSLATED_IDENT`'s +/// when set), also with the cache off (this binary's own then): what every translation's DXIL +/// depends on (the built-pipelines ledger's name). +pub fn translator_identity() -> u64 { + match translated::identity() { + 0 => translated::identity_for(env!("XCL_TRANSLATOR_SOURCE_ID"), dxc::toolchain_identity()), + n => n, + } +} + /// `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 { @@ -148,11 +224,74 @@ pub fn console_to_dxil_shared(blob: &[u8], stage: Stage, sampler_base: u32, spli /// `XCL_TRANSLATED_CACHE=0` turns it off; `XCL_TRANSLATED_IDENT=` stands for the hash. mod translated { use super::{Compiled, Stage}; + use std::collections::HashMap; use std::path::{Path, PathBuf}; - use std::sync::OnceLock; + use std::sync::{Mutex, OnceLock, PoisonError}; const MAGIC: &[u8; 8] = b"XCLTRAN2"; + /// A translation this run found by its program's hash, stored or loaded: its folder (a hash of + /// its path), identity, program's hash, stage and parameters – `FOUND`'s key. + #[derive(Clone, Copy, PartialEq, Eq, Hash)] + struct Found { + dir: u64, + ident: u64, + hash: u64, + stage: Stage, + sampler_base: u32, + windows: u32, + split: bool, + } + + /// The static samplers of each translation in `Found`: kept for the run (a translation is never + /// taken off the disk while a title runs), only those that exist (`samplers_by_hash`). + static FOUND: Mutex>> = Mutex::new(None); + + fn found_key(dir: &Path, ident: u64, hash: u64, stage: Stage, sampler_base: u32, windows: u32, split: bool) -> Found { + Found { dir: crate::gpu::shader::fnv64(dir.as_os_str().as_encoded_bytes()), ident, hash, stage, sampler_base, windows, split } + } + + fn note_found(k: Found, samplers: usize) { + FOUND.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(HashMap::new).insert(k, samplers.min(u32::MAX as usize) as u32); + } + + /// The static samplers of the translation of the program whose `fnv64` is `hash` in `dir` for + /// `ident` (`file_by_hash`), None: none – kept for the run once found (`FOUND`); a look that + /// finds none reads the disk again the next time. + pub(super) fn samplers_by_hash(dir: &Path, ident: u64, hash: u64, stage: Stage, sampler_base: u32, windows: u32, split: bool) -> Option { + if ident == 0 || hash == 0 { + return None; + } + let k = found_key(dir, ident, hash, stage, sampler_base, windows, split); + if let Some(&n) = FOUND.lock().unwrap_or_else(PoisonError::into_inner).as_ref().and_then(|m| m.get(&k)) { + return Some(n); + } + let n = samplers_on_disk(&file_by_hash(dir, ident, hash, stage, sampler_base, windows, split), ident)?; + note_found(k, n as usize); + Some(n) + } + + /// The static samplers of the translation at `path` for `ident`, from its header – its magic + /// and identity only: the program's bytes are not at hand for the rest – and the file whole, as + /// `dxil_len` checks it. None: missing, cut, or another identity's. + pub(super) fn samplers_on_disk(path: &Path, ident: u64) -> Option { + use std::io::{Read, Seek, SeekFrom}; + let mut f = std::fs::File::open(path).ok()?; + let mut head = [0u8; 36]; + f.read_exact(&mut head).ok()?; + if head[..8] != MAGIC[..] || head[8..16] != ident.to_le_bytes() { + return None; + } + let n = u32::from_le_bytes(head[32..36].try_into().unwrap()); + // then 4 words and a byte a static sampler, the DXIL's length and the DXIL + let at = 36 + 17 * n as u64; + f.seek(SeekFrom::Start(at)).ok()?; + let mut l = [0u8; 4]; + f.read_exact(&mut l).ok()?; + let len = u32::from_le_bytes(l) as u64; + (len > 0 && f.metadata().ok()?.len() == at + 4 + len).then_some(n) + } + pub(super) fn identity_for(source: &str, toolchain: &str) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for part in ["xcl-translated-cache-v2", source, toolchain] { @@ -166,7 +305,7 @@ mod translated { /// Translation semantics and the DXC DLLs, independent of link metadata and build profile. /// Zero means the disk cache is disabled. - fn identity() -> u64 { + pub(super) fn identity() -> u64 { static I: OnceLock = OnceLock::new(); *I.get_or_init(|| { if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { @@ -189,10 +328,15 @@ mod translated { } pub(super) fn file(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool) -> PathBuf { + file_by_hash(dir, ident, crate::gpu::shader::fnv64(blob), stage, sampler_base, windows, split) + } + + /// `file` of the program whose `fnv64` is `hash` + pub(super) fn file_by_hash(dir: &Path, ident: u64, hash: u64, stage: Stage, sampler_base: u32, windows: u32, split: bool) -> PathBuf { dir.join("translated") .join("v2") .join(format!("{ident:016x}")) - .join(format!("{:016x}_{stage:?}_{sampler_base}_{windows}_{}.bin", crate::gpu::shader::fnv64(blob), split as u8)) + .join(format!("{hash:016x}_{stage:?}_{sampler_base}_{windows}_{}.bin", split as u8)) } fn header(ident: u64, blob: &[u8]) -> Vec { @@ -203,6 +347,29 @@ mod translated { h } + /// The DXIL length of the translation `file` names, from its header – what `load_in` would + /// give, without reading the DXIL: None when the file is missing, cut, or not `blob`'s + /// translation for `ident` (magic, identity, length and second hash of the bytes). + pub(super) fn dxil_len(dir: &Path, ident: u64, blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split: bool) -> Option { + use std::io::{Read, Seek, SeekFrom}; + if ident == 0 { + return None; + } + let mut f = std::fs::File::open(file(dir, ident, blob, stage, sampler_base, windows, split)).ok()?; + let mut head = [0u8; 36]; + f.read_exact(&mut head).ok()?; + if head[..32] != header(ident, blob)[..] { + return None; + } + // then 4 words and a byte a static sampler, the DXIL's length and the DXIL + let at = 36 + 17 * u32::from_le_bytes(head[32..36].try_into().unwrap()) as u64; + f.seek(SeekFrom::Start(at)).ok()?; + let mut l = [0u8; 4]; + f.read_exact(&mut l).ok()?; + let len = u32::from_le_bytes(l) as u64; + (len > 0 && f.metadata().ok()?.len() == at + 4 + len).then_some(len as usize) + } + pub(super) fn load_in(path: &Path, ident: u64, blob: &[u8]) -> Option { let b = std::fs::read(path).ok()?; let head = header(ident, blob); @@ -224,7 +391,8 @@ mod translated { (r.len() == len && len > 0).then(|| Compiled { dxil: r.to_vec(), samplers }) } - pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) { + /// `c` as `blob`'s translation at `path`; whether it is there now. + pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) -> bool { let mut b = header(ident, blob); b.extend_from_slice(&(c.samplers.len() as u32).to_le_bytes()); for (s, cmp) in &c.samplers { @@ -233,12 +401,17 @@ mod translated { } b.extend_from_slice(&(c.dxil.len() as u32).to_le_bytes()); b.extend_from_slice(&c.dxil); - let Some(dir) = path.parent() else { return }; + let Some(dir) = path.parent() else { return false }; let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id())); // written whole, then renamed: a reader never sees half a file - if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, path).is_err() { + if std::fs::create_dir_all(dir).is_err() || std::fs::write(&tmp, &b).is_err() { + return false; + } + if std::fs::rename(&tmp, path).is_err() { let _ = std::fs::remove_file(&tmp); + return false; } + true } pub(super) fn cached_in( @@ -254,13 +427,19 @@ mod translated { if ident == 0 { return translate(); } - let path = file(dir, ident, blob, stage, sampler_base, windows, split); + let hash = crate::gpu::shader::fnv64(blob); + let path = file_by_hash(dir, ident, hash, stage, sampler_base, windows, split); + // (each one there from now on is what `samplers_by_hash` finds: a pipeline sent after + // this one with the same shader goes where those that need no DXC go – `pso_async`) if let Some(c) = load_in(&path, ident, blob) { super::dxc::note_memory_hit(); + note_found(found_key(dir, ident, hash, stage, sampler_base, windows, split), c.samplers.len()); return Ok(c); } let c = translate()?; - store_in(&path, ident, blob, &c); + if store_in(&path, ident, blob, &c) { + note_found(found_key(dir, ident, hash, stage, sampler_base, windows, split), c.samplers.len()); + } Ok(c) } @@ -523,7 +702,14 @@ fn cached_shader( } fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { - !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"] + cache_allowed_with(stage, present, super::emit::budget_trip_waves()) +} + +/// `cache_allowed` with the dispatch-wide budget's threshold `trip_waves`: it is read at run +/// time, so only turning it off – 0 – changes a compute program's HLSL. +fn cache_allowed_with(stage: Stage, present: impl Fn(&str) -> bool, trip_waves: u32) -> bool { + !(stage == Stage::Compute && present("XCL_BUDGET_TRIP_WAVES") && trip_waves == 0) + && !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"] .iter() .any(|name| present(name)) && (stage != Stage::Pixel @@ -541,13 +727,23 @@ fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { /// s0…s3 are the driver's, so what is above 4 is the root arguments its compiler passed in /// registers. None: not a console compute shader. pub fn compute_user_sgprs(blob: &[u8]) -> Option { + compute_interface(blob).map(|cs| cs.user_sgprs) +} + +/// The thread group of a console compute shader (its numthreads). None: not a console +/// compute shader. +pub fn compute_threads(blob: &[u8]) -> Option<[u32; 3]> { + compute_interface(blob).map(|cs| cs.threads) +} + +fn compute_interface(blob: &[u8]) -> Option { if let Some(f) = fspx(blob) { - return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2).user_sgprs); + return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2)); } let sh = xbox::parse(blob)?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; match interface(blob, &sh, f)? { - Mode::Compute(cs) => Some(cs.user_sgprs), + Mode::Compute(cs) => Some(cs), _ => None, } } @@ -817,6 +1013,46 @@ mod shader_cache_tests { let _ = std::fs::remove_dir_all(&dir); } + /// The DXIL's length comes from a translation's header – what `load_in` would give – for the + /// same bytes and identity and a whole file only. + #[test] + fn the_dxil_size_comes_from_a_translations_header() { + let dir = std::env::temp_dir().join(format!("xcl-dxil-len-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let c = Compiled { dxil: vec![1, 2, 3, 4, 5], samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; + let back = translated::cached_in(&dir, 42, b"console", Stage::Compute, 0, 4, true, || Ok(c.clone())).unwrap(); + assert_eq!(back.dxil, c.dxil); + let len = |ident: u64| translated::dxil_len(&dir, ident, b"console", Stage::Compute, 0, 4, true); + assert_eq!(len(42), Some(5)); + let path = translated::file(&dir, 42, b"console", Stage::Compute, 0, 4, true); + let good = std::fs::read(&path).unwrap(); + translated::store_in(&path, 43, b"console", &c); + assert_eq!(len(42), None, "another identity in the header"); + translated::store_in(&path, 42, b"consolf", &c); + assert_eq!(len(42), None, "other bytes of the same length"); + std::fs::write(&path, &good[..good.len() - 1]).unwrap(); + assert_eq!(len(42), None, "a cut file"); + std::fs::write(&path, &good).unwrap(); + assert_eq!(len(42), Some(5), "the whole file again"); + assert_eq!(len(44), None, "no file"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The ledger's identity is the translation cache's folder – also a developer's + /// `XCL_TRANSLATED_IDENT` one (run it with that set: an identity that recomputes the binary's + /// passes only without it) – and the folder's formula is today's (a change of it would + /// translate every program again: an hour of a retail game's start). + #[test] + fn the_translator_identity_is_the_translation_caches_folder() { + if std::env::var_os("XCL_TRANSLATED_CACHE").is_some() { + return crate::gpu::recomp::runner::skip_config("XCL_TRANSLATED_CACHE is set"); + } + if std::env::var_os("XCL_TRANSLATED_IDENT").is_none() { + assert_eq!(translated::identity(), translated::identity_for(env!("XCL_TRANSLATOR_SOURCE_ID"), dxc::toolchain_identity())); + } + assert_eq!(translator_identity(), translated::identity()); + } + #[test] fn translated_v2_ignores_valid_entries_outside_its_namespace() { let dir = std::env::temp_dir().join(format!("xcl-translated-legacy-{}", std::process::id())); @@ -845,6 +1081,84 @@ mod shader_cache_tests { let _ = std::fs::remove_dir_all(&dir); } + /// A translation is found by its program's hash alone – the file `console_to_dxil_for` loads, + /// its static samplers from the header – for that hash, stage, sampler base, windows, split and + /// identity only, whole, and never for hash 0 or the cache off (identity 0). (PP2's P5; a folder + /// of its own: the user's cache is never written.) + #[test] + fn a_translation_is_found_by_its_programs_hash() { + let dir = std::env::temp_dir().join(format!("xcl-by-hash-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let blob = b"a console pixel shader"; + let h = crate::gpu::shader::fnv64(blob); + let c = Compiled { dxil: vec![9; 40], samplers: vec![([1, 2, 3, 4], false), ([5, 6, 7, 8], true)] }; + let path = translated::file(&dir, 42, blob, Stage::Pixel, 0, 4, true); + assert_eq!(path, translated::file_by_hash(&dir, 42, h, Stage::Pixel, 0, 4, true), "the file of its hash"); + assert!(translated::store_in(&path, 42, blob, &c)); + let by = |hash: u64, stage: Stage, base: u32, windows: u32, split: bool, ident: u64| translated_by_hash_in(&dir, ident, hash, stage, base, windows, split); + assert_eq!(by(h, Stage::Pixel, 0, 4, true, 42), Some(2), "its two static samplers"); + assert_eq!(by(h, Stage::Pixel, 1, 4, true, 42), None, "another sampler base"); + assert_eq!(by(h, Stage::Vertex, 0, 4, true, 42), None, "another stage"); + assert_eq!(by(h, Stage::Pixel, 0, 1, true, 42), None, "other windows"); + assert_eq!(by(h, Stage::Pixel, 0, 4, false, 42), None, "the other split"); + assert_eq!(by(h ^ 1, Stage::Pixel, 0, 4, true, 42), None, "another program"); + assert_eq!(by(0, Stage::Pixel, 0, 4, true, 42), None, "no program"); + assert_eq!(by(h, Stage::Pixel, 0, 4, true, 0), None, "the cache off"); + // the header: its magic and identity, the file whole + assert_eq!(translated::samplers_on_disk(&path, 42), Some(2)); + assert_eq!(translated::samplers_on_disk(&path, 43), None, "another identity"); + let good = std::fs::read(&path).unwrap(); + std::fs::write(&path, &good[..good.len() - 1]).unwrap(); + assert_eq!(translated::samplers_on_disk(&path, 42), None, "a cut file"); + let mut bad = good.clone(); + bad[0] ^= 1; + std::fs::write(&path, &bad).unwrap(); + assert_eq!(translated::samplers_on_disk(&path, 42), None, "not a translation"); + assert_eq!(translated::samplers_on_disk(&dir.join("none.bin"), 42), None, "no file"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A translation a build stores after a look found none is found by the next look – on disk, + /// and told by the store itself (its file taken away before the look: still found) –; one a + /// build loads is told the same way; what was found is kept for the run: a "none" never outlives + /// a store, and nothing not found is kept (PP2's A2). + #[test] + fn a_translation_stored_after_a_look_found_none_is_found_by_the_next() { + let dir = std::env::temp_dir().join(format!("xcl-by-hash-a2-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (vs, ps, cs) = (b"a console vertex shader".as_slice(), b"a console pixel shader".as_slice(), b"a console compute shader".as_slice()); + let fnv = crate::gpu::shader::fnv64; + let by = |blob: &[u8], stage: Stage| translated_by_hash_in(&dir, 42, fnv(blob), stage, 0, 4, true); + assert_eq!(by(vs, Stage::Vertex), None, "not translated yet"); + assert_eq!(by(ps, Stage::Pixel), None, "not translated yet"); + // a build translates them: stored + let c = Compiled { dxil: vec![3; 24], samplers: vec![([1, 1, 1, 1], false); 3] }; + let mut translated = 0; + for (blob, stage) in [(vs, Stage::Vertex), (ps, Stage::Pixel)] { + let back = translated::cached_in(&dir, 42, blob, stage, 0, 4, true, || { + translated += 1; + Ok(c.clone()) + }) + .unwrap(); + assert_eq!(back.dxil.len(), 24); + } + assert_eq!(translated, 2); + assert_eq!(by(vs, Stage::Vertex), Some(3), "stored since: found"); + // (the PS's file gone before any look: what the store told) + std::fs::remove_file(translated::file(&dir, 42, ps, Stage::Pixel, 0, 4, true)).unwrap(); + assert_eq!(by(ps, Stage::Pixel), Some(3), "the store told it"); + // one an earlier run stored, loaded by a build: told by the load (its file gone before any look) + let path = translated::file(&dir, 42, cs, Stage::Compute, 0, 4, true); + assert!(translated::store_in(&path, 42, cs, &compiled(5))); + let loaded = translated::cached_in(&dir, 42, cs, Stage::Compute, 0, 4, true, || panic!("on disk: loaded")).unwrap(); + assert_eq!(loaded.dxil[0], 5); + std::fs::remove_file(&path).unwrap(); + assert_eq!(by(cs, Stage::Compute), Some(compiled(5).samplers.len() as u32), "the load told it"); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(by(vs, Stage::Vertex), Some(3), "kept for the run"); + assert_eq!(translated_by_hash_in(&dir, 42, fnv(cs), Stage::Compute, 0, 4, false), None, "the other split: never stored, none kept"); + } + fn key(hash: u64) -> ShaderKey { ShaderKey { hash, @@ -1043,6 +1357,14 @@ mod shader_cache_tests { assert!(cache_allowed(Stage::Compute, |v| v == name)); } assert!(cache_allowed(Stage::Pixel, |_| false)); + // the dispatch-wide budget's threshold is read at run time: only 0 (no trip) changes a + // compute program's HLSL, and never a vertex or pixel program's + let set = |v: &str| v == "XCL_BUDGET_TRIP_WAVES"; + for waves in [0u32, 64, 128] { + assert!(cache_allowed_with(Stage::Vertex, set, waves) && cache_allowed_with(Stage::Pixel, set, waves)); + assert_eq!(cache_allowed_with(Stage::Compute, set, waves), waves != 0, "{waves}"); + assert!(cache_allowed_with(Stage::Compute, |_| false, waves)); + } } #[test] diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 76e080e..c3f4c9c 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -441,6 +441,15 @@ pub fn skip_test(reason: &str) { let _ = writeln!(std::io::stderr(), "SKIPPED {test}: {reason}"); } +/// A test (or a part of one) this host's configuration leaves out – not a GPU it lacks: +/// `SKIPPED : ` written to stderr itself as `skip_test` does (libtest captures +/// `eprintln!`), without its `XCL_REQUIRE_GPU` failure. +pub fn skip_config(reason: &str) { + use std::io::Write; + let thread = std::thread::current(); + let _ = writeln!(std::io::stderr(), "SKIPPED {}: {reason}", thread.name().unwrap_or("?")); +} + /// 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, &[], &[]) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 48ea3dc..50401e1 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7631,3 +7631,196 @@ fn fspx_containers_translate_and_compile() { println!("FSPX: {ok} / {n} translated and compiled"); assert_eq!(ok, n); } + +/// The dispatch-wide budget trip (`emit::Em::trip`) is in compute programs only: one check at +/// the start of `main`, the counting guard in each of the program's loops (none of the plain +/// guard), in the native and the split wave64 forms; a kernel's loops keep the plain guard. +/// Where DXC is there, the compute forms compile. +#[test] +fn budget_trip_is_in_compute_loops_only() { + if super::emit::budget_trip_waves() == 0 { + println!("XCL_BUDGET_TRIP_WAVES=0 – nothing to check"); + return; + } + // two loops: s0 counts down to 0, then s1 does + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 133)], None), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), // back to s_sub + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 133)], None), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), // back to the second s_sub + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None), + ]); + let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 2, ..Default::default() }; + for (wave64, split) in [(false, false), (true, false), (true, true)] { + let t = translate(&code, &Options { mode: Mode::Compute(cs.clone()), wave64, split_wave64: split, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported); + let h = &t.hlsl; + assert_eq!(h.matches(super::LOOP_GUARD_TRIP).count(), 2, "wave64 {wave64} split {split}:\n{h}"); + assert_eq!(h.matches(super::LOOP_GUARD).count(), 0, "wave64 {wave64} split {split}:\n{h}"); + assert_eq!(h.matches("void xcl_budget_spent()").count(), 1, "{h}"); + assert_eq!(h.matches("if (WaveReadLaneFirst(xcl_trip) != 0u) { xcl_budget = 0u; xcl_spent = true; }").count(), 1, "{h}"); + // the check comes before the program's first loop + assert!(h.find("xcl_trip").unwrap() < h.find("[loop] for (;;)").unwrap(), "{h}"); + if super::dxc::location().is_ok() { + super::dxc::compile(h, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("wave64 {wave64} split {split}: {e}\n{h}")); + } + } + let t = translate(&code, &Options::default()).unwrap(); + assert_eq!(t.hlsl.matches(super::LOOP_GUARD).count(), 2, "{}", t.hlsl); + assert!(!t.hlsl.contains("xcl_budget_spent") && !t.hlsl.contains("xcl_trip"), "{}", t.hlsl); + // a compute program without loops has nothing to trip: no atomic for each of its waves + let flat = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 133)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None), + ]); + let t = translate(&flat, &Options { mode: Mode::Compute(cs.clone()), ..Default::default() }).unwrap(); + assert!(!t.hlsl.contains("xcl_budget_spent") && !t.hlsl.contains("xcl_trip"), "{}", t.hlsl); +} + +/// The trip on the GPU, with the translator's own pieces (`PRELUDE_TRIP`, `TRIP_AT_START`, +/// `LOOP_GUARD_TRIP`) around a loop that never ends by itself: 16384 groups of 64 threads; once +/// 64 waves have spent their budget, the groups that start later skip their loop (those the GPU +/// holds already run theirs – some hundreds on an M5 Pro, more on bigger GPUs). Without the trip +/// (word 2 = 0) 1024 groups all run theirs to the budget. Bounded either way: each loop stops at +/// its own budget (2^16 iterations) – 16384 x 64 x 2^16 trivial iterations at worst, a few +/// seconds. +#[test] +fn budget_trip_stops_a_runaway_dispatch_on_the_gpu() { + use windows::core::Interface; + use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + + let hlsl = format!( + "RWByteAddressBuffer res : register(u1);\nRWByteAddressBuffer outb : register(u2);\nstatic uint xcl_budget = 1u << 16;\n{}\n[numthreads(64, 1, 1)]\nvoid main(uint3 gid : SV_GroupID, uint gi : SV_GroupIndex)\n{{\n{} uint n = 0u;\n [loop] for (;;) {{\n {}\n n++;\n if (outb.Load(12u) == 0xC0FFEEu) break;\n }}\n if (gi == 0u) {{ uint o; outb.InterlockedAdd(n == 0u ? 0u : 4u, 1u, o); }}\n}}\n", + super::emit::PRELUDE_TRIP, + super::emit::TRIP_AT_START, + super::LOOP_GUARD_TRIP + ); + let dxil = match super::dxc::location() { + Ok(_) => super::dxc::compile(&hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{hlsl}")), + Err(e) => { + runner::skip_test("no DXC"); + println!("no DXC ({e}) – skipping"); + return; + } + }; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let buffer = |bytes: u64, heap, state, flags| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() + }; + let mut out = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out).unwrap(); + out.unwrap() + }; + let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let transition = |r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES| { + let b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(r.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }) }, + ..Default::default() + }; + list.ResourceBarrier(std::slice::from_ref(&b)); + let mut t = std::mem::ManuallyDrop::into_inner(b.Anonymous.Transition); + std::mem::ManuallyDrop::drop(&mut t.pResource); + }; + // res blocks: [count, serial, waves] – the trip at 64 waves, then none (0) + let upload = buffer(1024, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE); + let mut mapped: *mut std::ffi::c_void = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::write_bytes(mapped.cast::(), 0, 1024); + let w = mapped.cast::(); + *w.add(1) = 1; + *w.add(2) = 64; + *w.add(64 + 1) = 2; + upload.Unmap(0, None); + let res: Vec = (0..2).map(|_| buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, uav)).collect(); + let outs: Vec = (0..2).map(|_| buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, uav)).collect(); + let readback = buffer(512, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + for k in 0..2 { + list.CopyBufferRegion(&res[k], 0, &upload, 256 * k as u64, 256); + list.CopyBufferRegion(&outs[k], 0, &upload, 512, 256); + transition(&res[k], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition(&outs[k], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + let descriptor = |reg| D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: reg, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let params = [descriptor(1), descriptor(2)]; + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: 2, pParameters: params.as_ptr(), ..Default::default() }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).unwrap(); + let blob = blob.unwrap(); + let root: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize())).unwrap(); + let mut pdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(root.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&pdesc).unwrap(); + std::mem::ManuallyDrop::drop(&mut pdesc.pRootSignature); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + for (k, groups) in [(0usize, 16384u32), (1, 1024)] { + list.SetComputeRootUnorderedAccessView(0, res[k].GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, outs[k].GetGPUVirtualAddress()); + list.Dispatch(groups, 1, 1); + } + for k in 0..2 { + transition(&outs[k], D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition(&res[k], D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&readback, 128 * k as u64, &outs[k], 0, 16); + list.CopyBufferRegion(&readback, 256 + 128 * k as u64, &res[k], 0, 16); + } + list.Close().unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + let t0 = std::time::Instant::now(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, event).unwrap(); + let waited = WaitForSingleObject(event, 60_000); + CloseHandle(event).unwrap(); + assert_eq!(waited, WAIT_OBJECT_0, "the dispatches did not finish in 60 s"); + let took = t0.elapsed(); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let r = |at: usize| mapped.cast::().add(at).cast::().read(); + let (skipped, ran, spent) = (r(0), r(4), r(256)); + let (skipped0, ran0, spent0) = (r(128), r(132), r(384)); + readback.Unmap(0, None); + println!("trip at 64 waves: {ran} groups ran their loop, {skipped} skipped it, {spent} waves spent; without: {ran0} ran, {skipped0} skipped, {spent0} spent; {:.2} s", took.as_secs_f64()); + assert_eq!(ran + skipped, 16384); + // the groups that start after 64 waves spent their budget skip their loop + assert!(ran >= 1 && skipped >= 1, "the trip did not happen: {ran} ran, {skipped} skipped"); + // each wave counts once; a group's two waves decide apart only when they start as the + // count reaches 64 (a group whose first wave skipped and whose second ran is counted + // as skipped above): a few such groups at most + assert!(spent >= 64 && spent <= 2 * ran + 64, "{spent} waves spent for {ran} groups"); + assert_eq!((ran0, skipped0), (1024, 0)); + assert!(spent0 == 1024 || spent0 == 2048, "every wave of the dispatch without the trip spends its budget once: {spent0}"); + } +} diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index c29522a..b86e534 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -152,6 +152,11 @@ pub unsafe fn create(dev: &ID3D12Device, queue: &ID3D12CommandQueue, t: &Image, pub const SHADER_READ: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0); fn validate_subresources(subs: &[Subresource]) -> Result<(), String> { + validate_subresources_masked(subs, None) +} + +/// `validate_subresources`; one `mask` leaves out (not copied) may have no texels. +fn validate_subresources_masked(subs: &[Subresource], mask: Option<&[bool]>) -> Result<(), String> { if subs.is_empty() { return Err("texture upload without subresources".into()); } @@ -164,7 +169,8 @@ fn validate_subresources(subs: &[Subresource]) -> Result<(), String> { .checked_mul(s.rows) .and_then(|n| n.checked_mul(s.row_bytes)) .ok_or_else(|| format!("texture subresource {i} size overflow"))?; - if s.data.len() < bytes { + let copied = mask.is_none_or(|m| m.get(i).copied().unwrap_or(false)); + if copied && s.data.len() < bytes { return Err(format!("texture subresource {i} has {} B, needs {bytes} B", s.data.len())); } } @@ -195,7 +201,10 @@ pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D1 let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; let staging = record_upload(dev, &list, res, subs, before, after)?; list.Close().map_err(err)?; - queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); + { + let _ops = crate::hle::d3d12x::d3d_ops(); + queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); + } let r = wait(dev, queue); drop(staging); r @@ -221,17 +230,90 @@ unsafe impl Send for Uploader {} /// queue (raw pointer) → its uploader, while no batch uses it static UPLOADERS: std::sync::Mutex>> = std::sync::Mutex::new(None); +/// bytes of the upload buffers kept (`Uploader::staging`) and of one made for a texture over the +/// cap while its upload runs (`OwnStaging`); one left behind by a timed-out upload stays counted – +/// it is never dropped +static STAGING_BYTES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The upload buffers' bytes (`XCL_ACTIVITY`). +pub fn staging_bytes() -> u64 { + STAGING_BYTES.load(std::sync::atomic::Ordering::Relaxed) +} + /// the smallest upload buffer made, and the placement alignment of texture data in it const STAGING_MIN: u64 = 4 << 20; const PLACEMENT: u64 = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64; -fn staging_capacity(bytes: u64) -> Option { - const LARGE: u64 = 64 << 20; - const STEP: u64 = 16 << 20; - if bytes <= LARGE { - Some(bytes.max(STAGING_MIN).next_power_of_two()) - } else { - bytes.checked_next_multiple_of(STEP) +/// `XCL_UPLOAD_STAGING_MB`'s default: the kept upload buffer's bytes and one run's at most. +pub const STAGING_CAP: u64 = 128 << 20; + +/// The cap on the kept upload buffer (`Uploader::staging`) and on one run of an upload +/// (`plan_runs`), and the title textures' batch (`batch_bytes`): `XCL_UPLOAD_STAGING_MB`, read once +/// (`host_main`, before the title runs). Before 0023.2 the kept buffer only grew, to the next power +/// of two of the largest batch: 4 → 32 → 128 → 256 MiB in run 66, the last at 92.1 s a block of its +/// own in D3DMetal's count (+256 MB for the rest of the run, wired while the GPU works). Unset or +/// not a number: 128 MiB. A number of MiB: that, raised to 16 (with 1 – 15 a texture of a few MiB +/// would go through a buffer of its own) and 4096 at most. `0`: no cap, as before 0023.2 – one run +/// a batch, the kept buffer grown to the next power of two, the title textures' batches 256 MiB. +pub fn staging_cap() -> Option { + #[cfg(test)] + if let Some(c) = TEST_CAP.with(|c| c.get()) { + return c; + } + static CAP: std::sync::OnceLock> = std::sync::OnceLock::new(); + *CAP.get_or_init(|| staging_cap_for(std::env::var("XCL_UPLOAD_STAGING_MB").ok().as_deref())) +} + +/// `XCL_UPLOAD_STAGING_MB`'s value → the cap (None: none) – `staging_cap`. +fn staging_cap_for(v: Option<&str>) -> Option { + match v.and_then(|v| v.trim().parse::().ok()) { + None => Some(STAGING_CAP), + Some(0) => None, + Some(mb) => Some(mb.clamp(16, 4096) << 20), + } +} + +/// The console bytes of one batch of title-texture uploads at most (`title_textures`): the cap – a +/// batch's PC staging bytes can be more, and `upload_batch_masked_run` cuts it in runs of at most +/// the cap; 256 MiB with none, as before 0023.2. +pub fn batch_bytes() -> usize { + batch_bytes_for(staging_cap()) +} + +fn batch_bytes_for(cap: Option) -> usize { + cap.map_or(256 << 20, |c| c as usize) +} + +#[cfg(test)] +thread_local! { + /// (tests) this thread's uploads' cap instead of `XCL_UPLOAD_STAGING_MB`'s (`Some(None)`: none) + static TEST_CAP: std::cell::Cell>> = const { std::cell::Cell::new(None) }; + /// (tests) the runs of this thread's last upload: (items, staging bytes, a buffer of its own) + static TEST_RUNS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// (tests) bytes of this thread's buffers of their own alive (`OwnStaging`): made, and not let + /// go yet – `STAGING_BYTES` is the process's, which other tests move + static TEST_OWN_LIVE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// (tests) what this thread added to and took from `STAGING_BYTES` for kept buffers + /// (`Uploader::staging`, its Drop), and the most that sum reached: (now, peak) + static TEST_KEPT_LIVE: std::cell::Cell<(i64, i64)> = const { std::cell::Cell::new((0, 0)) }; +} + +/// (tests) `TEST_KEPT_LIVE` moved by `bytes`, its peak kept +#[cfg(test)] +fn test_kept_moved(bytes: i64) { + TEST_KEPT_LIVE.with(|l| { + let now = l.get().0 + bytes; + l.set((now, l.get().1.max(now))); + }); +} + +impl Drop for Uploader { + fn drop(&mut self) { + if let Some((_, _, cap)) = &self.staging { + STAGING_BYTES.fetch_sub(*cap, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + test_kept_moved(-(*cap as i64)); + } } } @@ -244,50 +326,238 @@ impl Uploader { Ok(Uploader { alloc, list, fence, value: 0, staging: None }) } - /// An upload buffer of at least `bytes`, mapped: the one kept, or a bigger one. - unsafe fn staging(&mut self, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, *mut u8), String> { - if let Some((b, p, cap)) = &self.staging { - if *cap >= bytes { + /// An upload buffer of at least `bytes` (one run's: not over the cap), mapped: the one kept, or + /// a bigger one that replaces it – never made above the cap (`kept_capacity`). + unsafe fn staging(&mut self, dev: &ID3D12Device, bytes: u64, cap: Option) -> Result<(ID3D12Resource, *mut u8), String> { + if let Some((b, p, c)) = &self.staging { + if *c >= bytes { return Ok((b.clone(), *p)); } } - let cap = staging_capacity(bytes).ok_or("texture upload buffer size overflow")?; - // A cached uploader has passed its last copy fence. Return this reference before - // acquiring the replacement so the growth path does not keep two buffers itself. - drop(self.staging.take()); + let cap = kept_capacity(bytes, cap).ok_or("texture upload buffer size overflow")?; + // The kept buffer has passed its last copy's fence (each run waits for its own, and an + // uploader whose wait failed is forgotten, never kept): let it go before the bigger one is + // made, so that growing never holds both (upstream 9db0989). + if let Some((_, _, old)) = self.staging.take() { + STAGING_BYTES.fetch_sub(old, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + test_kept_moved(-(old as i64)); + } let b = buffer(dev, cap)?; let mut p = std::ptr::null_mut(); b.Map(0, None, Some(&mut p)).map_err(err)?; + STAGING_BYTES.fetch_add(cap, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + test_kept_moved(cap as i64); self.staging = Some((b.clone(), p as *mut u8, cap)); Ok((b, p as *mut u8)) } } +/// The kept upload buffer's capacity for a run of `bytes` when the one kept is smaller (or there is +/// none): 4 MiB or the next power of two of `bytes`, as before 0023.2 – but never above the cap, +/// which a run on the kept buffer is never over (`plan_runs`; with a cap under 4 MiB, the cap). +/// None when that power of two is past u64 (upstream 9db0989's overflow check). +fn kept_capacity(bytes: u64, cap: Option) -> Option { + let grown = bytes.max(STAGING_MIN).checked_next_power_of_two()?; + Some(cap.map_or(grown, |c| grown.min(c.max(bytes)))) +} + +/// An upload buffer of its own for one texture whose staging is over the cap (`Run::own`), the +/// size of its layout: mapped, counted in `STAGING_BYTES` while it lives, dropped once its run's +/// copies were waited for – never kept (a texture of more than the cap on the PC would otherwise +/// grow the kept buffer past it for the rest of the run). Forgotten when that wait fails, as the +/// uploader is: the GPU may still read it. +struct OwnStaging { + buffer: ID3D12Resource, + mapped: *mut u8, + bytes: u64, +} + +impl OwnStaging { + unsafe fn new(dev: &ID3D12Device, bytes: u64) -> Result { + let buffer = buffer(dev, bytes)?; + let mut p = std::ptr::null_mut(); + buffer.Map(0, None, Some(&mut p)).map_err(err)?; + STAGING_BYTES.fetch_add(bytes, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + TEST_OWN_LIVE.with(|l| l.set(l.get() + bytes)); + Ok(OwnStaging { buffer, mapped: p as *mut u8, bytes }) + } +} + +impl Drop for OwnStaging { + fn drop(&mut self) { + STAGING_BYTES.fetch_sub(self.bytes, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + TEST_OWN_LIVE.with(|l| l.set(l.get() - self.bytes)); + } +} + +/// A texture over the cap went through an upload buffer of its own (`OwnStaging`): said the first +/// 4 times, then at powers of two. +fn note_own_staging(bytes: u64, cap: Option) { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("{}", own_staging_line(bytes, cap, n)); + } +} + +fn own_staging_line(bytes: u64, cap: Option, n: u64) -> String { + format!( + "title textures: an upload of one texture's {} MB went through an upload buffer of its own, past XCL_UPLOAD_STAGING_MB={}: made for it and let go once its copy ran ({n} so far)", + bytes >> 20, + cap.unwrap_or(0) >> 20 + ) +} + +/// One submit of an upload: planned items `items` (indices into the upload's planned items, in +/// order), each from its base (multiples of D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, from 0), the +/// staging bytes they take, and whether it goes through a buffer of its own (one texture over the +/// cap) rather than the kept one. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Run { + items: std::ops::Range, + bases: Vec, + bytes: u64, + own: bool, +} + +/// The runs an upload whose planned items take `totals` staging bytes goes in: whole items in +/// order, at most `cap` bytes a run (bases from 0 in each), a texture over the cap alone in a run +/// of its own buffer; with no cap one run of everything (`XCL_UPLOAD_STAGING_MB=0`, as before +/// 0023.2). The cut is by the PC's staging bytes, not the console's: they are what the buffer +/// holds, and a texture's PC layout can be larger than its console bytes. (One texture is not cut +/// by subresource: its copy transitions the whole resource either way, and a second part would need +/// footprints of its own – for a case not seen.) +fn plan_runs(totals: &[u64], cap: Option) -> Vec { + let mut runs: Vec = Vec::new(); + for (i, &t) in totals.iter().enumerate() { + if cap.is_some_and(|c| t > c) { + runs.push(Run { items: i..i + 1, bases: vec![0], bytes: t, own: true }); + continue; + } + if let Some(r) = runs.last_mut().filter(|r| !r.own) { + let base = r.bytes.div_ceil(PLACEMENT) * PLACEMENT; + if cap.is_none_or(|c| base + t <= c) { + r.items.end = i + 1; + r.bases.push(base); + r.bytes = base + t; + continue; + } + } + runs.push(Run { items: i..i + 1, bases: vec![0], bytes: t, own: false }); + } + runs +} + +/// What `run_all` appends to the error of an item of a run that was never submitted. +const NOT_SUBMITTED: &str = " – this part of the batch was not submitted"; + +/// Whether a failed item's error (`upload_batch_masked_run`'s Ok list) says its run was never +/// submitted – none of its copies reached the queue, so an upload at a later submit lands what this +/// one did not; a layout failure would fail again. +pub fn never_submitted(e: &str) -> bool { + e.ends_with(NOT_SUBMITTED) +} + +/// How one run of an upload failed: before its list was submitted (none of its copies reach the +/// GPU), or after (a Signal or a wait that failed: its copies land on the queue in its order). +#[derive(Debug)] +enum RunError { + Before(String), + After(String), +} + +/// The runs `runs` of an upload one after the other, each through `run` (recorded, submitted and +/// waited for, as one batch was before 0023.2), and what the caller is told – `planned` is each +/// planned item's index in the caller's items, `failed` the items whose layout failed: +/// - every run ran: Ok(failed); +/// - run r failed before its submit: the first – Err, nothing was submitted (as before 0023.2); a +/// later one – Ok(failed ∪ the items of r and of every run after it, with the error): the caller +/// warns of them and tries lazy ones again, as for an item that failed; +/// - run r failed after its submit (a Signal or a wait): the last – Err with `executed`, as before +/// 0023.2 (its copies land on the queue in its order, and the caller takes them as done); one with +/// runs after it – Ok(failed ∪ the items of every run after r, with the error) and `executed`: +/// runs up to r land in the queue's order, and the textures of the runs never submitted are not +/// reported uploaded (a lazy one would be taken to hold texels its tiles do not hold). +/// +/// `executed`: whether any run was submitted. +fn run_all(runs: &[Run], planned: &[usize], mut failed: Vec<(usize, String)>, executed: &mut bool, mut run: impl FnMut(&Run) -> Result<(), RunError>) -> Result, String> { + let not_submitted = |from: &[Run], e: &str| -> Vec<(usize, String)> { + from.iter().flat_map(|r| r.items.clone()).filter_map(|i| planned.get(i)).map(|&k| (k, format!("{e}{NOT_SUBMITTED}"))).collect() + }; + for (k, r) in runs.iter().enumerate() { + match run(r) { + Ok(()) => *executed = true, + Err(RunError::Before(e)) if k == 0 => return Err(e), + Err(RunError::Before(e)) => { + failed.extend(not_submitted(&runs[k..], &e)); + return Ok(failed); + } + Err(RunError::After(e)) => { + *executed = true; + if k + 1 == runs.len() { + return Err(e); + } + failed.extend(not_submitted(&runs[k + 1..], &e)); + return Ok(failed); + } + } + } + Ok(failed) +} + /// Several uploads on one list, one wait: (resource, subresources, states) each – the states /// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 /// order). A failure of one is returned with its index; the others still run. The texels go /// through the queue's kept upload buffer (`Uploader`). pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + upload_batch_masked(dev, queue, items, &[]) +} + +/// `upload_batch` copying only the subresources `masks[i]` says of item i (None, or no mask for +/// it: all of them) – a reserved texture with tiles for some of its subresources +/// (`lazy_tex`). The barriers are the same. +pub unsafe fn upload_batch_masked( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[(ID3D12Resource, Vec, Vec)], + masks: &[Option>], +) -> Result, String> { + upload_batch_masked_run(dev, queue, items, masks, &mut false) +} + +/// `upload_batch_masked`; `executed` says, on an error too, whether copies were submitted (then +/// they land on `queue` in its order – a wait that timed out, a Signal that failed). The texels go +/// in runs of at most the cap (`staging_cap`, `plan_runs`), each recorded, submitted and waited for +/// on its own: the kept buffer is never made above the cap, and a texture over it goes through a +/// buffer of its own (`OwnStaging`). What a run that failed leaves the caller: `run_all`. +pub unsafe fn upload_batch_masked_run( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[(ID3D12Resource, Vec, Vec)], + masks: &[Option>], + executed: &mut bool, +) -> Result, String> { + *executed = false; if items.is_empty() { return Ok(Vec::new()); } let key = windows::core::Interface::as_raw(queue) as usize; let taken = UPLOADERS.lock().unwrap().as_mut().and_then(|m| m.remove(&key)); - let mut up = match taken { + let up = match taken { Some(u) => u, None => Uploader::new(dev)?, }; - // where each texture's texels go in the upload buffer + // where each texture's texels go in the upload buffer: its layout (the runs place it) let mut failed = Vec::new(); let mut planned = Vec::with_capacity(items.len()); - let mut total = 0u64; for (k, (res, subs, states)) in items.iter().enumerate() { - match layout(dev, res, subs, states, states) { - Ok(l) => { - let base = total.div_ceil(PLACEMENT) * PLACEMENT; - total = base + l.total; - planned.push((k, l, base)); - } + let mask = masks.get(k).and_then(|m| m.as_deref()); + match layout_masked(dev, res, subs, states, states, mask) { + Ok(l) => planned.push((k, l)), Err(e) => failed.push((k, e)), } } @@ -295,26 +565,82 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items put_back(key, up); return Ok(failed); } - let (staging, mapped) = up.staging(dev, total)?; - up.alloc.Reset().map_err(err)?; - up.list.Reset(&up.alloc, None).map_err(err)?; - for (k, l, base) in &planned { - let (res, subs, states) = &items[*k]; - record_into(&up.list, res, subs, l, states, states, &staging, mapped, *base); + let cap = staging_cap(); + let runs = plan_runs(&planned.iter().map(|(_, l)| l.total).collect::>(), cap); + #[cfg(test)] + TEST_RUNS.with(|t| *t.borrow_mut() = runs.iter().map(|r| (r.items.len(), r.bytes, r.own)).collect()); + let index: Vec = planned.iter().map(|(k, _)| *k).collect(); + let mut up = Some(up); + let done = run_all(&runs, &index, failed, executed, |run| { + let Some(u) = up.as_mut() else { return Err(RunError::Before("texture copy: no uploader".into())) }; + let r = one_run(dev, queue, u, items, masks, &planned, run, cap); + match &r { + Ok(()) => {} + // (a fresh uploader next time, as after a batch that failed before 0023.2) + Err(RunError::Before(_)) => up = None, + // the GPU may still read the upload buffer and run the list: they stay alive (a fresh + // uploader next time) – freeing them under the GPU removed the device + Err(RunError::After(_)) => std::mem::forget(up.take()), + } + r + }); + if let Some(u) = up { + put_back(key, u); + } + done +} + +/// One run of `upload_batch_masked_run` on `up`: its texels into the kept buffer (or one of its +/// own), its copies recorded on the uploader's list, submitted, signalled and waited for (10 s). +#[allow(clippy::too_many_arguments)] +unsafe fn one_run( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + up: &mut Uploader, + items: &[(ID3D12Resource, Vec, Vec)], + masks: &[Option>], + planned: &[(usize, Layout)], + run: &Run, + cap: Option, +) -> Result<(), RunError> { + use RunError::{After, Before}; + let own = if run.own { + let o = OwnStaging::new(dev, run.bytes).map_err(Before)?; + note_own_staging(run.bytes, cap); + Some(o) + } else { + None + }; + let (staging, mapped) = match &own { + Some(o) => (o.buffer.clone(), o.mapped), + None => up.staging(dev, run.bytes, cap).map_err(Before)?, + }; + up.alloc.Reset().map_err(|e| Before(err(e)))?; + up.list.Reset(&up.alloc, None).map_err(|e| Before(err(e)))?; + for (i, &base) in run.items.clone().zip(&run.bases) { + let Some((k, l)) = planned.get(i) else { continue }; + let Some((res, subs, states)) = items.get(*k) else { continue }; + let mask = masks.get(*k).and_then(|m| m.as_deref()); + record_into(&up.list, res, subs, l, states, states, &staging, mapped, base, mask); + } + up.list.Close().map_err(|e| Before(err(e)))?; + { + let _ops = crate::hle::d3d12x::d3d_ops(); + queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(|e| Before(err(e)))?)]); } - up.list.Close().map_err(err)?; - queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(err)?)]); up.value += 1; let copy_error = |e| format!("texture copy: {e}"); - queue.Signal(&up.fence, up.value).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; - if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) { - // the GPU may still read the upload buffer and run the list: they stay alive (a fresh - // uploader next time) – freeing them under the GPU removed the device - std::mem::forget(up); - return Err(copy_error(e)); - } - put_back(key, up); - Ok(failed) + let waited = match queue.Signal(&up.fence, up.value) { + Err(e) => Err(copy_error(fence::api_error(dev, "Signal", e))), + Ok(()) => fence::wait(&up.fence, up.value, dev, None, 10_000).map_err(copy_error), + }; + if let Err(e) = waited { + // (the list was submitted: a buffer of its own it reads stays alive, as the uploader does) + std::mem::forget(own); + return Err(After(e)); + } + drop(own); + Ok(()) } fn put_back(key: usize, up: Uploader) { @@ -342,7 +668,7 @@ pub unsafe fn record_upload_states( let up = buffer(dev, l.total)?; let mut p = std::ptr::null_mut(); up.Map(0, None, Some(&mut p)).map_err(err)?; - record_into(list, res, subs, &l, before, after, &up, p as *mut u8, 0); + record_into(list, res, subs, &l, before, after, &up, p as *mut u8, 0, None); up.Unmap(0, None); Ok(up) } @@ -357,8 +683,13 @@ struct Layout { /// The `Layout` of uploading `subs` into `res`, checked against the resource. unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES]) -> Result { - validate_subresources(subs)?; - let rd = res.GetDesc(); + layout_masked(dev, res, subs, before, after, None) +} + +/// `layout`, the subresources `mask` leaves out (not copied) allowed to have no texels. +unsafe fn layout_masked(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], mask: Option<&[bool]>) -> Result { + validate_subresources_masked(subs, mask)?; + let rd = copyable_desc(res); let n = subs.len(); validate_subresource_count(&rd, n)?; for s in [before, after] { @@ -382,13 +713,38 @@ unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], Ok(Layout { fps, rows, total }) } +/// The description of `res` for GetCopyableFootprints: a reserved texture's 64 KiB tiled +/// layout as the default one (the footprints of the texels are the same; `lazy_tex`). +pub unsafe fn copyable_desc(res: &ID3D12Resource) -> D3D12_RESOURCE_DESC { + let mut d = res.GetDesc(); + if d.Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE || d.Layout == D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE { + d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + } + d +} + /// Write `subs` into the mapped upload buffer `up` (`mapped`) from `base` (a multiple of /// D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT) as `l` places them, and record their copies into -/// `res` on `list` (barriers from `before` and back to `after`). +/// `res` on `list` (barriers from `before` and back to `after`) – those `mask` has (None: all). #[allow(clippy::too_many_arguments)] -unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], l: &Layout, before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], up: &ID3D12Resource, mapped: *mut u8, base: u64) { +unsafe fn record_into( + list: &ID3D12GraphicsCommandList, + res: &ID3D12Resource, + subs: &[Subresource], + l: &Layout, + before: &[D3D12_RESOURCE_STATES], + after: &[D3D12_RESOURCE_STATES], + up: &ID3D12Resource, + mapped: *mut u8, + base: u64, + mask: Option<&[bool]>, +) { let n = subs.len(); - for ((s, fp), &nrows) in subs.iter().zip(&l.fps).zip(&l.rows) { + let wanted = |k: usize| mask.is_none_or(|m| m.get(k).copied().unwrap_or(false)); + for (k, ((s, fp), &nrows)) in subs.iter().zip(&l.fps).zip(&l.rows).enumerate() { + if !wanted(k) { + continue; + } let pitch = fp.Footprint.RowPitch as usize; let row = s.row_bytes.min(pitch); // depth slices are NumRows rows apart (rows of 4×4 blocks for BCn) @@ -405,6 +761,9 @@ unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, su list.ResourceBarrier(&to_copy); } for (k, fp) in l.fps.iter().enumerate() { + if !wanted(k) { + continue; + } let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, @@ -810,17 +1169,282 @@ mod tests { } } + /// (tests) This thread's uploads go with cap `cap` until the guard is dropped. + fn cap_for_test(cap: Option) -> impl Drop { + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + TEST_CAP.with(|c| c.set(None)); + } + } + TEST_CAP.with(|c| c.set(Some(cap))); + Restore + } + + /// (tests) The runs of this thread's last upload: (textures, staging bytes, a buffer of its own). + fn last_runs() -> Vec<(usize, u64, bool)> { + TEST_RUNS.with(|t| t.borrow().clone()) + } + + /// (tests) The upload buffer `queue`'s uploader keeps: (buffer, capacity). + fn kept(queue: &ID3D12CommandQueue) -> Option<(usize, u64)> { + let key = windows::core::Interface::as_raw(queue) as usize; + UPLOADERS.lock().unwrap().as_ref().and_then(|m| m.get(&key)).and_then(|u| u.staging.as_ref()).map(|s| (windows::core::Interface::as_raw(&s.0) as usize, s.2)) + } + + /// (tests) No uploader kept for `queue`: one an earlier queue left at its address (idle – an + /// uploader is kept only after its last wait) is let go. + fn forget_uploader(queue: &ID3D12CommandQueue) { + let key = windows::core::Interface::as_raw(queue) as usize; + let gone = UPLOADERS.lock().unwrap().as_mut().and_then(|m| m.remove(&key)); + drop(gone); + } + + /// (tests) A 2D texture of `w` × `h` with `mips` levels in the shader-read states. + unsafe fn texture_2d(dev: &ID3D12Device, w: u64, h: u32, mips: u16, format: DXGI_FORMAT) -> ID3D12Resource { + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: mips, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, SHADER_READ, None, &mut r).unwrap(); + r.unwrap() + } + + /// (tests) Every subresource of `r`, filled with a pattern of `seed`. + unsafe fn pattern(dev: &ID3D12Device, r: &ID3D12Resource, seed: u8) -> Vec { + let rd = r.GetDesc(); + let n = rd.MipLevels as usize; + let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; + let (mut rows, mut row_bytes) = (vec![0u32; n], vec![0u64; n]); + dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), None); + (0..n) + .map(|k| { + let (r, b, d) = (rows[k] as usize, row_bytes[k] as usize, fps[k].Footprint.Depth as usize); + Subresource { rows: r, row_bytes: b, depth: d, data: (0..r * b * d).map(|i| (i as u8).wrapping_mul(31) ^ (i >> 9) as u8 ^ seed ^ k as u8).collect() } + }) + .collect() + } + + /// (tests) Every texture of `items` reads back what was uploaded into it. + unsafe fn assert_read_back(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)], what: &str) { + for (i, (r, want, _)) in items.iter().enumerate() { + let got = read_back(dev, queue, r, want); + for (k, (g, w)) in got.iter().zip(want).enumerate() { + assert!(g == w, "{what}: texture {i}, subresource {k} differs"); + } + } + } + + /// GP3 at 1/128 of its scale – this thread's cap 1 MiB for XCL_UPLOAD_STAGING_MB's 128: a batch + /// of seven textures of 320 KiB on the PC (2.2 MiB, as a batch of 300 MB is 2.3 caps) goes in 3 + /// runs of whole textures through the queue's kept buffer, made at the cap and never above it; + /// then one texture of 1.6 MiB (as one of 200 MB is 1.6 caps) goes through a buffer of its own + /// and leaves the kept one as it was. Every texel reads back as uploaded. + #[test] + fn gpu_an_upload_over_the_staging_cap_goes_in_runs_and_never_grows_the_kept_buffer_past_it() { + let Some((dev, queue)) = device() else { + println!("no D3D12 device – skipping"); + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let cap = 1u64 << 20; + let _cap = cap_for_test(Some(cap)); + unsafe { + forget_uploader(&queue); + let textures: Vec<_> = (0..7).map(|_| texture_2d(&dev, 256, 320, 1, DXGI_FORMAT_R8G8B8A8_UNORM)).collect(); + let items: Vec<_> = textures.iter().enumerate().map(|(i, r)| (r.clone(), pattern(&dev, r, i as u8 * 16), vec![SHADER_READ])).collect(); + assert!(upload_batch(&dev, &queue, &items).unwrap().is_empty(), "an upload failed"); + let runs = last_runs(); + assert_eq!(runs.iter().map(|r| (r.0, r.2)).collect::>(), [(3, false), (3, false), (1, false)], "runs: {runs:?}"); + assert!(runs.iter().all(|r| r.1 <= cap), "a run over the cap: {runs:?}"); + assert_read_back(&dev, &queue, &items, "in runs"); + let before = kept(&queue).expect("the queue's upload buffer is kept"); + assert_eq!(before.1, cap, "the kept buffer is made at the cap (4 MiB before 0023.2)"); + // one texture over the cap: a buffer of its own, the kept one untouched + let big = texture_2d(&dev, 512, 800, 1, DXGI_FORMAT_R8G8B8A8_UNORM); + let one = vec![(big.clone(), pattern(&dev, &big, 0x5A), vec![SHADER_READ])]; + assert_eq!(TEST_OWN_LIVE.with(|l| l.get()), 0); + assert!(upload_batch(&dev, &queue, &one).unwrap().is_empty(), "the upload over the cap failed"); + let runs = last_runs(); + assert!(runs.len() == 1 && runs[0].0 == 1 && runs[0].1 > cap && runs[0].2, "runs: {runs:?}"); + assert_eq!(TEST_OWN_LIVE.with(|l| l.get()), 0, "the buffer of its own is let go once its copy ran"); + assert_read_back(&dev, &queue, &one, "through a buffer of its own"); + assert_eq!(kept(&queue), Some(before), "the kept buffer is the one it was, at the cap"); + // and a batch under the cap after it: the kept buffer again + assert!(upload_batch(&dev, &queue, &items[..2]).unwrap().is_empty()); + assert_eq!(last_runs().iter().map(|r| (r.0, r.2)).collect::>(), [(2, false)]); + assert_read_back(&dev, &queue, &items[..2], "after it"); + assert_eq!(kept(&queue), Some(before)); + forget_uploader(&queue); + } + } + + /// A small batch with the default cap (or XCL_UPLOAD_STAGING_MB=0, or any cap of 16 MiB or + /// more) is one run through the queue's kept buffer, made as before 0023.2: 4 MiB, the next + /// power of two of 4 MiB or more. + #[test] + fn gpu_a_small_upload_batch_is_one_run_through_the_kept_buffer_as_before() { + let Some((dev, queue)) = device() else { + println!("no D3D12 device – skipping"); + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + unsafe { + forget_uploader(&queue); + let textures = [ + texture_2d(&dev, 64, 64, 7, DXGI_FORMAT_R8G8B8A8_UNORM), + texture_2d(&dev, 100, 30, 1, DXGI_FORMAT_R8G8B8A8_UNORM), + texture_2d(&dev, 256, 256, 9, DXGI_FORMAT_BC7_UNORM), + ]; + let items: Vec<_> = textures.iter().enumerate().map(|(i, r)| (r.clone(), pattern(&dev, r, 0x40 + i as u8), vec![SHADER_READ])).collect(); + assert!(upload_batch(&dev, &queue, &items).unwrap().is_empty(), "an upload failed"); + let runs = last_runs(); + assert!(runs.len() == 1 && runs[0].0 == 3 && !runs[0].2, "one run: {runs:?}"); + assert_eq!(kept(&queue).map(|k| k.1), Some(STAGING_MIN), "the kept buffer as before 0023.2"); + assert_read_back(&dev, &queue, &items, "one run"); + forget_uploader(&queue); + } + } + + /// The runs of an upload (`plan_runs`): 300 MiB of 1-MiB textures at the cap of 128 MiB go in 3 + /// runs of whole textures (128, 128 and 44), each from base 0; a texture of 200 MiB alone in a + /// run through a buffer of its own, the ones around it in runs of their own; bases at the + /// placement alignment; exactly the cap fits a run; with no cap (`XCL_UPLOAD_STAGING_MB=0`) one + /// run of everything, as before 0023.2. The kept buffer for capped runs is never above the cap. #[test] - fn large_staging_uses_sixteen_mib_growth_steps() { - let mib = 1 << 20; - assert_eq!(staging_capacity(1), Some(4 * mib)); - assert_eq!(staging_capacity(33 * mib), Some(64 * mib)); - assert_eq!(staging_capacity(64 * mib + 1), Some(80 * mib)); - assert_eq!(staging_capacity(138_713_408), Some(144 * mib)); - assert_eq!(staging_capacity(256 * mib + 1), Some(272 * mib)); - assert_eq!(staging_capacity(u64::MAX), None); + fn an_upload_plan_goes_in_runs_of_at_most_the_cap() { + let mib = 1u64 << 20; + let cap = Some(STAGING_CAP); + let runs = plan_runs(&[mib; 300], cap); + assert_eq!(runs.iter().map(|r| r.items.len()).collect::>(), [128, 128, 44]); + assert!(runs.iter().all(|r| !r.own && r.bytes <= STAGING_CAP && r.bases[0] == 0), "{runs:?}"); + assert_eq!((runs[1].items.clone(), runs[2].items.clone()), (128..256, 256..300)); + assert_eq!(runs[2].bases, (0..44).map(|k| k * mib).collect::>()); + assert!(runs.iter().all(|r| kept_capacity(r.bytes, cap).is_some_and(|c| c <= STAGING_CAP))); + // a texture of 200 MiB between smaller ones: alone, through a buffer of its own + assert_eq!( + plan_runs(&[3 * mib, 5 * mib, 200 * mib, 7 * mib], cap), + [ + Run { items: 0..2, bases: vec![0, 3 * mib], bytes: 8 * mib, own: false }, + Run { items: 2..3, bases: vec![0], bytes: 200 * mib, own: true }, + Run { items: 3..4, bases: vec![0], bytes: 7 * mib, own: false }, + ] + ); + // bases at the placement alignment (512 B) + assert_eq!(plan_runs(&[1000, 1000, 1000], cap), [Run { items: 0..3, bases: vec![0, 1024, 2048], bytes: 3048, own: false }]); + // exactly the cap fits; a byte more starts a run + assert_eq!(plan_runs(&[64 * mib, 64 * mib], cap).len(), 1); + assert_eq!(plan_runs(&[64 * mib, 64 * mib + 1], cap).len(), 2); + assert_eq!(plan_runs(&[STAGING_CAP], cap), [Run { items: 0..1, bases: vec![0], bytes: STAGING_CAP, own: false }]); + // no cap: one run of everything, its buffer grown as before 0023.2 + let runs = plan_runs(&[mib; 300], None); + assert_eq!((runs.len(), runs[0].items.clone(), runs[0].bytes, runs[0].own), (1, 0..300, 300 * mib, false)); + assert_eq!(kept_capacity(runs[0].bytes, None), Some(512 * mib)); + assert_eq!(plan_runs(&[200 * mib, mib], None).len(), 1); + assert!(plan_runs(&[], cap).is_empty()); } + /// `XCL_UPLOAD_STAGING_MB`: unset or not a number 128 MiB; a number of MiB raised to 16 and at + /// most 4096; `0` no cap. The title textures' batch follows it (256 MiB with none, as before + /// 0023.2). The kept buffer is grown as before 0023.2 – the next power of two of 4 MiB or more – + /// but never above the cap (one under 4 MiB: the cap). This process's switch as it was read; the + /// line of an upload over the cap. + #[test] + fn the_upload_staging_cap_is_read_in_mib_and_zero_is_as_before() { + let mib = 1u64 << 20; + assert_eq!(staging_cap_for(None), Some(128 * mib)); + assert_eq!(staging_cap_for(Some("x")), Some(128 * mib)); + assert_eq!(staging_cap_for(Some("")), Some(128 * mib)); + assert_eq!(staging_cap_for(Some(" 64 ")), Some(64 * mib)); + assert_eq!(staging_cap_for(Some("5")), Some(16 * mib)); + assert_eq!(staging_cap_for(Some("99999")), Some(4096 * mib)); + assert_eq!(staging_cap_for(Some("0")), None); + assert_eq!(batch_bytes_for(Some(128 * mib)), 128 << 20); + assert_eq!(batch_bytes_for(Some(16 * mib)), 16 << 20); + assert_eq!(batch_bytes_for(None), 256 << 20); + assert_eq!(kept_capacity(mib, Some(128 * mib)), Some(4 * mib)); + assert_eq!(kept_capacity(33 * mib, Some(128 * mib)), Some(64 * mib)); + assert_eq!(kept_capacity(100 * mib, Some(128 * mib)), Some(128 * mib)); + assert_eq!(kept_capacity(128 * mib, Some(128 * mib)), Some(128 * mib)); + assert_eq!(kept_capacity(129 * mib, None), Some(256 * mib), "no cap: as before 0023.2"); + assert_eq!(kept_capacity(u64::MAX, None), None, "past u64: an error, not a buffer of 0 bytes"); + assert_eq!(kept_capacity(700 << 10, Some(mib)), Some(mib), "a cap under 4 MiB: the cap"); + let env = std::env::var("XCL_UPLOAD_STAGING_MB").ok(); + assert_eq!(staging_cap(), staging_cap_for(env.as_deref()), "this process's switch"); + assert_eq!(batch_bytes(), batch_bytes_for(staging_cap())); + assert_eq!( + own_staging_line(200 << 20, Some(128 << 20), 3), + "title textures: an upload of one texture's 200 MB went through an upload buffer of its own, past XCL_UPLOAD_STAGING_MB=128: made for it and let go once its copy ran (3 so far)" + ); + } + + /// What a run that failed leaves the caller (`run_all`; the design check's A4): a failure after + /// its submit (a Signal or a wait) in run 1 of 3 gives runs 2-3's textures as failed – never + /// submitted – and the copies before as submitted (Ok, `executed`); in the last run Err with + /// `executed`, as one batch's failure before 0023.2; one before its submit in run 1 is Err with + /// nothing submitted, in run 2 gives runs 2-3's textures as failed. A texture whose layout failed + /// stays failed; the texts name the failure. + #[test] + fn a_failed_run_gives_the_textures_of_the_runs_not_submitted_as_failed() { + // ten textures: #4's layout failed; the others in 3 runs of 3 textures of 40 MiB at 128 + let planned = [0usize, 1, 2, 3, 5, 6, 7, 8, 9]; + let runs = plan_runs(&[40 << 20; 9], Some(STAGING_CAP)); + assert_eq!(runs.iter().map(|r| r.items.clone()).collect::>(), [0..3, 3..6, 6..9]); + let layout = vec![(4usize, "layout".to_string())]; + let go = |fail: Option<(usize, bool)>| { + let (mut executed, mut called) = (false, 0usize); + let r = run_all(&runs, &planned, layout.clone(), &mut executed, |_| { + called += 1; + match fail { + Some((at, true)) if at + 1 == called => Err(RunError::After("texture copy: timed out".into())), + Some((at, false)) if at + 1 == called => Err(RunError::Before("Reset".into())), + _ => Ok(()), + } + }); + (r, executed, called) + }; + let failed = |r: &Result, String>| r.as_ref().map(|f| f.iter().map(|x| x.0).collect::>()).map_err(Clone::clone); + let (r, executed, called) = go(None); + assert_eq!((failed(&r), executed, called), (Ok(vec![4]), true, 3), "all ran"); + let (r, executed, called) = go(Some((0, true))); + assert_eq!((failed(&r), executed, called), (Ok(vec![4, 3, 5, 6, 7, 8, 9]), true, 1), "a wait in run 1 of 3: runs 2-3 not submitted"); + assert_eq!(r.as_ref().unwrap()[1].1, "texture copy: timed out – this part of the batch was not submitted"); + // (what the caller tells them by – C-F3: the textures never submitted, not the layout failure) + let unsent: Vec = r.unwrap().into_iter().filter(|(_, e)| never_submitted(e)).map(|(k, _)| k).collect(); + assert_eq!(unsent, [3, 5, 6, 7, 8, 9], "every texture of the runs not submitted, not #4"); + let (before, _, _) = go(Some((1, false))); + assert!(before.unwrap().iter().filter(|(k, _)| *k != 4).all(|(_, e)| never_submitted(e)), "before run 2's submit: runs 2-3 never submitted"); + assert!(!never_submitted("layout") && !never_submitted("texture copy: timed out")); + let (r, executed, called) = go(Some((1, true))); + assert_eq!((failed(&r), executed, called), (Ok(vec![4, 7, 8, 9]), true, 2), "a wait in run 2: run 3 not submitted"); + let (r, executed, called) = go(Some((2, true))); + assert_eq!((failed(&r), executed, called), (Err("texture copy: timed out".to_string()), true, 3), "a wait in the last run: as before 0023.2"); + let (r, executed, called) = go(Some((0, false))); + assert_eq!((failed(&r), executed, called), (Err("Reset".to_string()), false, 1), "before run 1's submit: nothing submitted"); + let (r, executed, called) = go(Some((1, false))); + assert_eq!((failed(&r), executed, called), (Ok(vec![4, 3, 5, 6, 7, 8, 9]), true, 2), "before run 2's submit: runs 2-3 not submitted"); + // one run (a batch under the cap): as before 0023.2 + let one = plan_runs(&[1 << 20; 3], Some(STAGING_CAP)); + let mut executed = false; + assert_eq!(run_all(&one, &[0, 1, 2], Vec::new(), &mut executed, |_| Err(RunError::After("lost".into()))), Err("lost".to_string())); + assert!(executed); + } + + /// (upstream 9db0989) A large mixed batch – a 128 MiB RGBA texture, then it with a 4 MiB BC7 + /// one – reads back byte for byte and keeps its staging tight: under the cap (`staging_cap`, + /// 128 MiB by default) the 132 MiB batch goes in two runs on the kept buffer of 128 MiB, which + /// the repeated batch reuses; no D3D12 debug errors with XCL_D3D12_DEBUG. Before that the kept + /// buffer grows: the BC7 texture alone keeps one of 4 MiB, and the RGBA one alone then a new + /// one of 128 MiB – the 4 MiB one let go, and taken off `STAGING_BYTES`, before the bigger one + /// is made, so this thread's kept bytes peak at 128 MiB, never 132 (`TEST_KEPT_LIVE`); both + /// read back byte for byte, and the uploader's Drop takes its buffer off again. #[test] fn gpu_large_mixed_upload_keeps_tight_staging_and_exact_pixels() { use windows::core::Interface; @@ -845,6 +1469,10 @@ mod tests { }; println!("large upload adapter: {}", String::from_utf16_lossy(&desc.Description).trim_end_matches('\0')); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + // the default cap on this thread whatever XCL_UPLOAD_STAGING_MB says, and no uploader an + // earlier queue left at this queue's address + let _cap = cap_for_test(Some(STAGING_CAP)); + forget_uploader(&queue); let make = |width, height, format| { let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: width, Height: height, @@ -869,8 +1497,21 @@ mod tests { (stage.0.as_raw() as usize, stage.2) }; let batch = [rgba, bc7]; + // the growth: this thread's kept bytes from here, the peak reset + let base = TEST_KEPT_LIVE.with(|l| { + let now = l.get().0; + l.set((now, now)); + now + }); + assert!(upload_batch(&dev, &queue, &batch[1..]).unwrap().is_empty()); + let small = kept(); + assert_eq!(small.1, 4 << 20, "the BC7 texture alone: a kept buffer of 4 MiB"); + assert!(read_back(&dev, &queue, &batch[1].0, &batch[1].1) == batch[1].1, "BC7 alone pixel mismatch"); assert!(upload_batch(&dev, &queue, &batch[..1]).unwrap().is_empty()); let first = kept(); + let (now, peak) = TEST_KEPT_LIVE.with(|l| l.get()); + assert_eq!((now - base, peak - base), (128 << 20, 128 << 20), "grown to 128 MiB, the 4 MiB buffer let go before"); + assert!(read_back(&dev, &queue, &batch[0].0, &batch[0].1) == batch[0].1, "RGBA alone pixel mismatch"); let before = std::time::Instant::now(); assert!(upload_batch(&dev, &queue, &batch).unwrap().is_empty()); let growth = before.elapsed(); @@ -888,6 +1529,7 @@ mod tests { // Drop the test's large uploader after its last copy fence and readbacks have passed. let uploader = UPLOADERS.lock().unwrap().as_mut().unwrap().remove(&key); drop(uploader); + assert_eq!(TEST_KEPT_LIVE.with(|l| l.get().0) - base, 0, "the kept buffer taken off STAGING_BYTES with its uploader"); if let Ok(info) = dev.cast::() { let mut errors = 0; for index in 0..info.GetNumStoredMessagesAllowedByRetrievalFilter() { @@ -906,8 +1548,8 @@ mod tests { println!("large upload: request={} B first_capacity={} B grown_capacity={} B growth={growth:?} repeat={repeat:?} byte_exact=true", (128 + 4) << 20, first.1, grown.1); assert_eq!(first.1, 128 << 20); + assert_eq!(grown, first, "132 MiB at the cap of 128 MiB: two runs on the kept buffer, never a bigger one"); assert_eq!(grown, reused, "the repeated batch must reuse the staging buffer"); - assert_eq!(grown.1, 144 << 20, "staging for 132 MiB must fit the next large size class"); } } diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 173e21b..5dd5a4e 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -13,7 +13,7 @@ //! 4095 MiB works (exactly 4 GiB is rejected), opening 4 GiB takes ~0.5 s. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Mutex, OnceLock}; use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; @@ -31,8 +31,39 @@ pub const MAX_WINDOWS: usize = 4; /// bytes of sparse window 0 only 32-bit descriptor heaps get (`Uma::desc_range`) const DESC_HEADROOM: usize = 512 << 20; -/// cap on the eager committed coherent window in `for_runtime` (per-draw args, readback buffers) -const RUNTIME_COMMITTED_CAP: usize = 512 << 20; + +/// XCL's own part of the committed coherent window – its floor, and what it is made with beside +/// the title's need (`coherent_hint`): XCL's per-draw arguments (its pool, `POOL`, and blocks), +/// readback heaps and buffers, a title's few committed textures (`real.rs`: while 128 MiB stay +/// free). A Mac's window has a copy in video memory of its whole size (D3DMetal has no +/// OpenExistingHeapFromAddress), wired while the GPU works: 256 MB there – run 66 used 139 MB of +/// 512, still rising (120 → 139 MB from 162.7 to 186.0 s), and a full window skips draws, which the +/// `coherent window:` line counts –, 512 MB elsewhere. GTA VI's four committed textures (run 66: +/// 8, 16, 16 and 8 MB at 34 s, the use 64 → 112 MB) still fit 256 MB, the last by 16 MB; a texture +/// past that becomes a plain PC texture, as one that finds the window full. `XCL_COHERENT_OWN_MB` +/// (read once, with `XCL_COHERENT_MB` – the whole window instead, with this as its floor) sets it: +/// unset or not a number → the default; a number → that many MiB, raised to 64 (a window that small +/// gets a pool of a quarter of it, 16 MiB) and 4095 at most; `512` is a Mac's window before 0023.2. +pub fn own_part() -> usize { + static OWN: OnceLock = OnceLock::new(); + *OWN.get_or_init(|| own_part_for(crate::util::mac_host(), std::env::var("XCL_COHERENT_OWN_MB").ok().as_deref())) +} + +/// `own_part` on a Mac or not, with `XCL_COHERENT_OWN_MB`'s value. +fn own_part_for(mac: bool, var: Option<&str>) -> usize { + match var.and_then(|v| v.trim().parse::().ok()) { + Some(mb) => mb.clamp(64, 4095) << 20, + None if mac => 256 << 20, + None => 512 << 20, + } +} + +/// The committed coherent window of a layout of `size` bytes asked for with `coherent` (the title's +/// need and XCL's part, or `XCL_COHERENT_MB`): never less than XCL's part `own` unless the whole +/// layout is smaller, whole 64 KiB grains, at most a window. +fn committed_for(size: usize, coherent: usize, own: usize) -> usize { + ((size.min(coherent.max(own)) + GRAIN - 1) & !(GRAIN - 1)).clamp(GRAIN, MAX_SIZE) +} #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum WindowKind { @@ -55,6 +86,11 @@ pub struct Uma { pool: Mutex<(usize, usize, Vec)>, /// the committed windows are not the GPU's memory: it has copies of them (`set_shadowed`) shadowed: AtomicBool, + /// `used` now and at most so far – kept with it under `inner`'s lock (`grew`, `shrank`) – and + /// the per-draw blocks `Arena::take` found no room for so far (`usage`) + used_now: AtomicUsize, + used_most: AtomicUsize, + arena_full: AtomicU64, } /// bytes of XCL's arena pool (`Uma::new`) @@ -148,6 +184,7 @@ impl Uma { g.free.insert(at + bytes, start + len - at - bytes); } g.used.insert(at, bytes); + self.grew(bytes); at }; let p = self.base + at; @@ -160,17 +197,48 @@ impl Uma { self.pool.lock().unwrap().2.pop() } + /// `used` grew by `bytes` (under `inner`'s lock): the use now and its high-water. + fn grew(&self, bytes: usize) { + let now = self.used_now.fetch_add(bytes, Ordering::Relaxed) + bytes; + self.used_most.fetch_max(now, Ordering::Relaxed); + } + + /// `used` shrank by `bytes` (under `inner`'s lock). + fn shrank(&self, bytes: usize) { + self.used_now.fetch_sub(bytes, Ordering::Relaxed); + } + + /// A per-draw block `Arena::take` found no room for: its draw or dispatch is skipped. + fn refused(&self) { + self.arena_full.fetch_add(1, Ordering::Relaxed); + } + + /// The committed windows' use now and at most so far – as `used`, the blocks handed out: XCL's + /// pool counted whole from the start, its 64 MiB of a runtime window – and the per-draw blocks + /// refused so far for want of room (their draws and dispatches skipped). + pub fn usage(&self) -> (usize, usize, u64) { + (self.used_now.load(Ordering::Relaxed), self.used_most.load(Ordering::Relaxed), self.arena_full.load(Ordering::Relaxed)) + } + + /// XCL's per-draw pool: (its bytes, the bytes of its blocks free now). + pub fn pool_usage(&self) -> (usize, usize) { + let g = self.pool.lock().unwrap_or_else(|e| e.into_inner()); + (g.1 - g.0, g.2.len() * ARENA_BLOCK) + } + /// Runtime layout: windows 0..3 (12 GiB) reserved as write-watched sparse VRAM windows /// (window 0 holds 32-bit-addressed descriptor heaps + buffers + XMem, windows 1..2 hold /// large title reservations and overflow), and window 3 as a smaller committed coherent - /// window (`OpenExistingHeapFromAddress`) for per-draw arguments and CPU readback buffers. + /// window (`OpenExistingHeapFromAddress`) for per-draw arguments and CPU readback buffers: + /// XCL's own part of it (`own_part`). pub fn for_runtime(size: usize) -> Option { - Self::for_runtime_with(size, RUNTIME_COMMITTED_CAP) + Self::for_runtime_with(size, own_part()) } - /// `for_runtime` with a coherent window of up to `coherent` bytes (`coherent_hint`). + /// `for_runtime` with a coherent window of up to `coherent` bytes (`coherent_hint`), XCL's + /// part at least (`committed_for`). pub fn for_runtime_with(size: usize, coherent: usize) -> Option { - let committed = ((size.min(coherent.max(RUNTIME_COMMITTED_CAP)) + GRAIN - 1) & !(GRAIN - 1)).clamp(GRAIN, MAX_SIZE); + let committed = committed_for(size, coherent, own_part()); let sparse_len = (MAX_WINDOWS - 1) * WINDOW; for slot in (4usize..512).step_by(MAX_WINDOWS) { let base = slot << 32; @@ -202,6 +270,9 @@ impl Uma { sparse_free: Mutex::new(sparse_free), pool: Mutex::new((0, 0, Vec::new())), shadowed: AtomicBool::new(false), + used_now: AtomicUsize::new(0), + used_most: AtomicUsize::new(0), + arena_full: AtomicU64::new(0), }; u.reserve_pool(POOL); return Some(u); @@ -426,6 +497,9 @@ impl Uma { sparse_free: Mutex::new(Default::default()), pool: Mutex::new((0, 0, Vec::new())), shadowed: AtomicBool::new(false), + used_now: AtomicUsize::new(0), + used_most: AtomicUsize::new(0), + arena_full: AtomicU64::new(0), }); } for p in got { @@ -540,14 +614,15 @@ impl Uma { self.alloc_where(size, align, Some(k), true) } - /// `XCL_TRACE_MEM`: each committed-window allocation of 1 MB or more and each one that - /// fails, with the XCL code that asked for it (what fills the window). + /// `XCL_TRACE_MEM`: each committed-window allocation of 1 MB or more and the failed ones that + /// `failure_traced` takes (the failures so far appended), with the XCL code that asked for it + /// (what fills the window). #[track_caller] - fn trace(&self, size: usize, got: Option, used: usize) { + fn trace(&self, size: usize, got: Option, used: usize, failures: u64) { let at = std::panic::Location::caller(); match got { Some(p) => crate::xlog_info!("UMA: {} KB at {p:#x} for {}:{} ({} MB used)", size >> 10, at.file(), at.line(), used >> 20), - None => crate::xlog_info!("UMA: {} KB for {}:{} – no room ({} MB used)", size >> 10, at.file(), at.line(), used >> 20), + None => crate::xlog_info!("UMA: {} KB for {}:{} – no room ({} MB used) – {failures} failures so far", size >> 10, at.file(), at.line(), used >> 20), } } @@ -566,10 +641,16 @@ impl Uma { (at.checked_add(size).is_some_and(|end| end <= o + l)).then_some((o, l, at)) }); let Some((start, len, at)) = found else { + // (a full window refuses every per-draw block of every list: the first 16 failures, then + // the 32nd, 64th, … – the trace sums the used map under `inner` and writes on the title's + // binding threads) if Self::tracing() { - let used = g.used.values().sum(); - drop(g); - self.trace(size, None, used); + let k = TRACED_FAILURES.fetch_add(1, Ordering::Relaxed) + 1; + if failure_traced(k) { + let used = g.used.values().sum(); + drop(g); + self.trace(size, None, used, k); + } } return None; }; @@ -581,11 +662,12 @@ impl Uma { g.free.insert(at + size, start + len - at - size); } g.used.insert(at, size); + self.grew(size); let used = if Self::tracing() && size >= 1 << 20 { Some(g.used.values().sum()) } else { None }; drop(g); let p = (self.base + at) as *mut u8; if let Some(used) = used { - self.trace(size, Some(p as usize), used); + self.trace(size, Some(p as usize), used, 0); } if zero { unsafe { std::ptr::write_bytes(p, 0, size) }; @@ -609,6 +691,7 @@ impl Uma { let mut g = self.inner.lock().unwrap(); let off = p - self.base; let Some(orig) = g.used.remove(&off) else { return false }; + self.shrank(orig); let (mut start, mut len) = (off, orig); // merge with the free neighbours if let Some((&o, &l)) = g.free.range(..off).next_back() { @@ -670,14 +753,23 @@ impl Arena { } if n > ARENA_BLOCK / 2 { // a large piece: a block of its own (the current one stays in use) - let p = u.alloc(n, align)?; + let Some(p) = u.alloc(n, align) else { + u.refused(); + return None; + }; blocks.push(p as usize); return Some(p); } // XCL's pool first, then any free part of committed unified memory let p = match u.pool_block() { Some(p) => p, - None => u.alloc(ARENA_BLOCK, GRAIN)? as usize, + None => match u.alloc(ARENA_BLOCK, GRAIN) { + Some(p) => p as usize, + None => { + u.refused(); + return None; + } + }, }; blocks.push(p); self.at = p + n; @@ -688,33 +780,55 @@ impl Arena { static GLOBAL: OnceLock> = OnceLock::new(); +/// `XCL_TRACE_MEM`'s failed window allocations so far (`Uma::alloc_where`) +static TRACED_FAILURES: AtomicU64 = AtomicU64::new(0); + +/// Whether the `k`-th failed window allocation (from 1) is traced: the first 16, then the 32nd, 64th, +/// … – a full window would otherwise write one line per refused per-draw block (one per draw or +/// dispatch of every list), at run 66's world rates thousands a second on the title's binding threads. +fn failure_traced(k: u64) -> bool { + k <= 16 || k.is_power_of_two() +} + /// The title's graphics memory XCL places in the coherent window (`note_coherent_need`) is /// known only once it asks for it, and the window is committed when it is made: its size is /// what the title asked for in its last run (`/cache/uma_coherent.txt`) and XCL's own -/// 512 MB, at most a window. `XCL_COHERENT_MB` chooses it. +/// part (`own_part`: 256 MB on a Mac, 512 elsewhere), at most a window. `XCL_COHERENT_MB` chooses +/// it. fn coherent_file() -> std::path::PathBuf { crate::state::data_dir().join("cache").join("uma_coherent.txt") } /// Bytes the coherent window is made with. pub fn coherent_hint() -> usize { - if let Some(mb) = std::env::var("XCL_COHERENT_MB").ok().and_then(|v| v.parse::().ok()) { - return (mb << 20).clamp(GRAIN, MAX_SIZE); + let env = std::env::var("XCL_COHERENT_MB").ok().and_then(|v| v.parse::().ok()); + let title = if env.is_some() { 0 } else { std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::().ok()).unwrap_or(0) }; + let free = if env.is_none() && title > 0 { free_commit() } else { usize::MAX }; + let (bytes, short) = coherent_hint_for(env, title, free, own_part()); + if short { + crate::xlog_warn!( + "UMA: {} MB of commit free, under {} MB: the title's GPU heaps stay outside unified memory (a larger page file gives them the coherent window)", + free >> 20, + NEEDS_FOR_COHERENT_HEAPS >> 20 + ); + } + bytes +} + +/// `coherent_hint` of `XCL_COHERENT_MB` (`env_mb`), the title's need in its last run, the commit +/// free and XCL's part: (bytes, whether the title's heaps stay out for want of commit). +fn coherent_hint_for(env_mb: Option, title: usize, free_commit: usize, own: usize) -> (usize, bool) { + if let Some(mb) = env_mb { + return ((mb << 20).clamp(GRAIN, MAX_SIZE), false); } - let title = std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::().ok()).unwrap_or(0); // only with the commit for all of it: the title's ~13 GB, video memory for its render targets // and textures (WDDM charges commit for each video-memory allocation too) and the window // itself – a retail game took ~18 GB; with less free it runs without (its GPU heaps outside // unified memory: no image) rather than taking the system's commit - if title > 0 && free_commit() < NEEDS_FOR_COHERENT_HEAPS { - crate::xlog_warn!( - "UMA: {} MB of commit free, under {} MB: the title's GPU heaps stay outside unified memory (a larger page file gives them the coherent window)", - free_commit() >> 20, - NEEDS_FOR_COHERENT_HEAPS >> 20 - ); - return RUNTIME_COMMITTED_CAP; + if title > 0 && free_commit < NEEDS_FOR_COHERENT_HEAPS { + return (own, true); } - (title + RUNTIME_COMMITTED_CAP).min(MAX_SIZE) + ((title + own).min(MAX_SIZE), false) } /// Commit free before the title starts for its GPU heaps to go to the coherent window. @@ -741,7 +855,7 @@ pub fn note_coherent_need(bytes: usize) { let _ = std::fs::create_dir_all(d); } let _ = std::fs::write(&f, bytes.to_string()); - crate::xlog_info!("UMA: the title's graphics memory for the coherent window: {} MB (a window of up to {} MB from the next run)", bytes >> 20, (bytes + RUNTIME_COMMITTED_CAP).min(MAX_SIZE) >> 20); + crate::xlog_info!("UMA: the title's graphics memory for the coherent window: {} MB (a window of up to {} MB from the next run)", bytes >> 20, (bytes + own_part()).min(MAX_SIZE) >> 20); } } @@ -752,6 +866,48 @@ impl Uma { } } +/// What the `coherent window:` line said last (`CoherentWatch::look`): the high-water and the +/// refused per-draw blocks then. +#[derive(Default)] +pub struct CoherentWatch { + said: Option<(usize, u64)>, +} + +impl CoherentWatch { + /// The coherent window's line (xcl-activity, every 2 s), when it is due: at the first look with a + /// window, then when its high-water rose 4 MiB or more since it was said, or when a per-draw block + /// was refused since – about 10-40 lines a run. `own`: XCL's part (`own_part`). + pub fn look(&mut self, u: &Uma, own: usize) -> Option { + let (now, most, full) = u.usage(); + if self.said.is_some_and(|(m, f)| most < m + (4 << 20) && full == f) { + return None; + } + self.said = Some((most, full)); + let (pool, pool_free) = u.pool_usage(); + Some(coherent_line(now, most, u.size(), own, pool.saturating_sub(pool_free), pool, full)) + } +} + +/// The line `CoherentWatch::look` says. The use counts XCL's per-draw pool whole from the start (64 +/// MiB of a runtime window), as `bind`'s "coherent N/M MB" does: run 66's 139 MB is that figure. +fn coherent_line(now: usize, most: usize, size: usize, own: usize, pool_used: usize, pool: usize, full: u64) -> String { + format!( + "coherent window: {} MB in use (its per-draw pool counted whole), {} MB at most so far, of {} MB (XCL's own part {} MB, XCL_COHERENT_OWN_MB); XCL's per-draw pool {} of {} MB in use; {full} per-draw blocks found no room so far (each a draw or dispatch skipped, or the title's middleware's upload memory taken from the sparse windows instead)", + now >> 20, + most >> 20, + size >> 20, + own >> 20, + pool_used >> 20, + pool >> 20 + ) +} + +/// The title's graphics memory if it was made already (`get` makes it): for what only looks at it +/// (xcl-activity), so that the window is never made off the title's own first call. +pub fn made() -> Option<&'static Uma> { + GLOBAL.get().and_then(Option::as_ref) +} + /// The title's graphics memory (created on first use; `XCL_UMA_MB`, default 2048). pub fn get() -> Option<&'static Uma> { GLOBAL @@ -963,4 +1119,190 @@ mod tests { // Contiguous sparse windows 0..2 are reported as one OS watch region; window 3 as another. assert_eq!(u.watch_regions(), vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]); } + + /// XCL's own part of the coherent window (`own_part_for`): 256 MiB on a Mac (its copy in video + /// memory, wired while the GPU works), 512 elsewhere as before 0023.2; `XCL_COHERENT_OWN_MB` a + /// number of MiB raised to 64 and at most 4095 (`512`: a Mac's window before 0023.2), not a + /// number the default. This process's part as it was read. + #[test] + fn xcls_part_of_the_coherent_window_is_256_mb_on_a_mac_and_512_elsewhere() { + let mib = 1usize << 20; + assert_eq!(own_part_for(true, None), 256 * mib); + assert_eq!(own_part_for(false, None), 512 * mib, "off a Mac: as before 0023.2"); + assert_eq!(own_part_for(true, Some("512")), 512 * mib, "the switch: a Mac's window before 0023.2"); + assert_eq!(own_part_for(true, Some(" 384 ")), 384 * mib); + assert_eq!(own_part_for(true, Some("x")), 256 * mib); + assert_eq!(own_part_for(false, Some("")), 512 * mib); + assert_eq!(own_part_for(true, Some("16")), 64 * mib, "raised to 64"); + assert_eq!(own_part_for(true, Some("0")), 64 * mib); + assert_eq!(own_part_for(false, Some("9000")), 4095 * mib, "at most 4095"); + let env = std::env::var("XCL_COHERENT_OWN_MB").ok(); + assert_eq!(own_part(), own_part_for(crate::util::mac_host(), env.as_deref()), "this process's part"); + } + + /// The window is the title's need and XCL's part (`coherent_hint_for`), never less than XCL's + /// part unless the whole layout is (`committed_for`): on a Mac XCL's 256 MB and the title's need + /// (run 66's window: 256 MB, none of the title's heaps there), 512 off a Mac; XCL_COHERENT_MB the + /// whole window, XCL's part its floor (on a Mac 256-511 now give that size; before 0023.2 512); + /// the title's heaps out for want of commit: XCL's part alone, with a warning. + #[test] + fn the_coherent_window_is_the_titles_need_plus_xcls_part_and_never_less() { + let mib = 1usize << 20; + let (mac, pc) = (own_part_for(true, None), own_part_for(false, None)); + let plenty = usize::MAX; + assert_eq!(coherent_hint_for(None, 0, plenty, mac), (256 * mib, false)); + assert_eq!(coherent_hint_for(None, 0, plenty, pc), (512 * mib, false)); + assert_eq!(coherent_hint_for(None, 100 * mib, plenty, mac), (356 * mib, false), "the title's need and XCL's part"); + assert_eq!(coherent_hint_for(None, 100 * mib, NEEDS_FOR_COHERENT_HEAPS - 1, mac), (256 * mib, true), "commit short: XCL's part alone"); + assert_eq!(coherent_hint_for(None, 4 << 30, plenty, mac), (MAX_SIZE, false), "at most a window"); + assert_eq!(coherent_hint_for(Some(128), 100 * mib, 0, mac), (128 * mib, false), "XCL_COHERENT_MB: its size, the file and the commit not asked"); + assert_eq!(coherent_hint_for(Some(1024), 0, plenty, mac), (1024 * mib, false)); + // the committed window of the runtime layout (`get`: XCL_UMA_MB or more, the hint) + let uma = 2048 * mib; + assert_eq!(committed_for(uma, 256 * mib, mac), 256 * mib, "a Mac: 256 MB (run 66: 512)"); + assert_eq!(committed_for(uma, 512 * mib, pc), 512 * mib, "off a Mac: as before 0023.2"); + assert_eq!(committed_for(uma, 128 * mib, mac), 256 * mib, "XCL_COHERENT_MB=128: XCL's part is its floor"); + assert_eq!(committed_for(uma, 300 * mib, mac), 300 * mib, "XCL_COHERENT_MB=300 on a Mac: 300 (before 0023.2: 512)"); + assert_eq!(committed_for(uma, 128 * mib, pc), 512 * mib); + assert_eq!(committed_for(uma, 1024 * mib, mac), 1024 * mib); + assert_eq!(committed_for(16 * mib, 256 * mib, mac), 16 * mib, "a smaller layout: all of it"); + assert_eq!(committed_for(8 << 30, 8 << 30, mac), MAX_SIZE, "at most a window"); + assert_eq!(committed_for(uma, 100 * mib + 1, 64 * mib), 100 * mib + GRAIN, "whole grains"); + // the runtime layout as `get` makes it: XCL's part of this host (256 MiB on a Mac – this test + // process under the bottle's Wine –, 512 elsewhere), the title's need on top of it, and an + // XCL_COHERENT_MB below it raised to it + let own = own_part(); + for (coherent, want, what) in [(own, own, "XCL's part alone"), (64 * mib, own, "XCL_COHERENT_MB=64: XCL's part is its floor"), (own + 32 * mib, own + 32 * mib, "a title's need of 32 MiB on top")] { + let u = Uma::for_runtime_with(uma, coherent).unwrap(); + assert_eq!((u.size(), u.committed_window()), (want, Some(3)), "{what}"); + // (XCL's pool: 64 MiB, a quarter of a window under 256 MiB) + let pool = POOL.min(want / 4) / ARENA_BLOCK * ARENA_BLOCK; + assert_eq!(u.pool_usage(), (pool, pool), "{what}: XCL's pool in it, all free"); + } + } + + /// A window's use now, its high-water and the per-draw blocks refused (`Uma::usage`): a runtime + /// window of its own of 4 MiB (pool 1 MiB, counted from the start); allocations and frees move + /// the use, the high-water stays; `Arena::take` until it finds no room counts each refusal, for a + /// block and for a large piece. + #[test] + fn the_windows_high_water_and_refused_blocks_are_counted() { + let mib = 1usize << 20; + let u = Uma::for_runtime(4 * mib).unwrap(); + assert_eq!((u.size(), u.pool_usage()), (4 * mib, (mib, mib)), "4 MiB, a pool of a quarter of it, all free"); + assert_eq!(u.usage(), (mib, mib, 0), "the pool counted whole from the start"); + let a = u.alloc(mib, 0).unwrap() as usize; + assert_eq!(u.usage(), (2 * mib, 2 * mib, 0)); + assert!(u.free(a)); + assert_eq!(u.usage(), (mib, 2 * mib, 0), "a free lowers the use, the high-water stays"); + let b = u.alloc(2 * mib, 0).unwrap() as usize; + assert_eq!(u.usage(), (3 * mib, 3 * mib, 0)); + assert_eq!(u.usage().0, u.used(), "the use is `used`"); + // per-draw blocks: the pool's 4, the window's last 1 MiB in 4 more, then no room + let mut blocks = Vec::new(); + let mut taken = 0; + while Arena::default().take(&u, 64, 16, &mut blocks).is_some() { + taken += 1; + } + assert_eq!((taken, u.usage().2), (8, 1), "8 blocks, then one refused"); + assert_eq!(u.pool_usage(), (mib, 0), "the pool all in use"); + assert!(Arena::default().take(&u, 64, 16, &mut blocks).is_none()); + assert!(Arena::default().take(&u, ARENA_BLOCK, 256, &mut blocks).is_none(), "a large piece with no room"); + assert_eq!(u.usage().2, 3, "each refusal counted"); + assert_eq!(u.usage().1, 4 * mib, "the high-water: the whole window"); + for p in blocks { + assert!(u.free(p)); + } + assert!(u.free(b)); + assert_eq!(u.usage(), (mib, 4 * mib, 3), "the pool's blocks back in it, the rest freed"); + assert_eq!(u.pool_usage(), (mib, mib)); + } + + /// The `coherent window:` line (`CoherentWatch::look`): said at the first look, then only when + /// the high-water rose 4 MiB or more since it was said or a per-draw block was refused since; its + /// text with the window's use, high-water, size, XCL's part and the pool. + #[test] + fn the_coherent_window_line_is_said_when_its_high_water_rose_or_a_block_was_refused() { + let mib = 1usize << 20; + let u = Uma::with_windows(1, 16 * mib).unwrap(); + u.reserve_pool(4 * ARENA_BLOCK); + let mut w = CoherentWatch::default(); + assert_eq!( + w.look(&u, 256 * mib).as_deref(), + Some("coherent window: 1 MB in use (its per-draw pool counted whole), 1 MB at most so far, of 16 MB (XCL's own part 256 MB, XCL_COHERENT_OWN_MB); XCL's per-draw pool 0 of 1 MB in use; 0 per-draw blocks found no room so far (each a draw or dispatch skipped, or the title's middleware's upload memory taken from the sparse windows instead)") + ); + assert_eq!(w.look(&u, 256 * mib), None, "nothing moved"); + assert_eq!( + coherent_line(3 * mib, 5 * mib, 16 * mib, 256 * mib, mib, 2 * mib, 7), + "coherent window: 3 MB in use (its per-draw pool counted whole), 5 MB at most so far, of 16 MB (XCL's own part 256 MB, XCL_COHERENT_OWN_MB); XCL's per-draw pool 1 of 2 MB in use; 7 per-draw blocks found no room so far (each a draw or dispatch skipped, or the title's middleware's upload memory taken from the sparse windows instead)", + "each field in its place" + ); + let a = u.alloc(3 * mib, 0).unwrap() as usize; + assert_eq!(w.look(&u, 256 * mib), None, "3 MiB higher: not yet"); + let b = u.alloc(mib, 0).unwrap() as usize; + assert!(w.look(&u, 256 * mib).is_some_and(|l| l.starts_with("coherent window: 5 MB in use (its per-draw pool counted whole), 5 MB at most so far, of 16 MB")), "4 MiB higher"); + assert!(u.free(a) && u.free(b)); + assert_eq!(w.look(&u, 256 * mib), None, "lower: nothing"); + // the pool used up and the rest of the window taken: a refused block + let mut blocks = Vec::new(); + while let Some(p) = u.alloc(GRAIN, GRAIN) { + blocks.push(p as usize); + } + let mut arena = Vec::new(); + while Arena::default().take(&u, 64, 16, &mut arena).is_some() {} + let l = w.look(&u, 256 * mib).expect("a refused block, and the window full"); + assert!(l.contains("16 MB at most so far, of 16 MB") && l.contains("XCL's per-draw pool 1 of 1 MB in use; 1 per-draw blocks found no room so far"), "{l}"); + assert_eq!(w.look(&u, 256 * mib), None); + assert!(Arena::default().take(&u, 64, 16, &mut arena).is_none()); + assert!(w.look(&u, 256 * mib).is_some_and(|l| l.contains("; 2 per-draw blocks found no room so far")), "refused again"); + for p in blocks.into_iter().chain(arena) { + assert!(u.free(p)); + } + } + + /// C-F4: with XCL_TRACE_MEM a failed window allocation is traced for the first 16, then the 32nd, + /// 64th, … – not one line per refused per-draw block of a full window. + #[test] + fn failed_window_allocations_are_traced_at_a_bounded_rate() { + let traced: Vec = (1..=600).filter(|&k| failure_traced(k)).collect(); + assert_eq!(traced, (1..=16).chain([32, 64, 128, 256, 512]).collect::>()); + assert!(failure_traced(1 << 40) && !failure_traced((1 << 40) + 1)); + assert!(!failure_traced(17) && !failure_traced(31) && !failure_traced(33)); + } + + /// C-F4's wiring and text (step Fm's open issue: no test set XCL_TRACE_MEM): with it (a process of + /// its own, `EXTRA_ENV=XCL_TRACE_MEM=1`) a window allocation that finds no room is traced at the + /// failures `failure_traced` takes – the first 16, then the 32nd, 64th, … –, each line HEAD's + /// with " – {k} failures so far" appended; without it none is said and none counted. On a unified + /// memory of the test's own (one 16 MiB window, no arena pool): 40 refusals on this thread, its + /// lines (`log::kept`), the count from where it stood – the exact lines when no other thread + /// counted meanwhile (in a process of its own, always so). + #[test] + fn failed_window_allocations_are_traced_with_their_count_only_with_xcl_trace_mem() { + let u = Uma::with_windows(1, 16 << 20).unwrap(); + let k0 = TRACED_FAILURES.load(Ordering::Relaxed); + let kept = crate::log::kept::keep(); + for _ in 0..40 { + assert!(u.alloc(32 << 20, 0).is_none(), "no room"); + } + let lines: Vec = kept.take().into_iter().filter(|l| l.starts_with("UMA: ")).collect(); + drop(kept); + let k1 = TRACED_FAILURES.load(Ordering::Relaxed); + if !Uma::tracing() { + assert!(lines.is_empty(), "{lines:#?}"); + assert_eq!(k1, k0, "not counted without XCL_TRACE_MEM"); + return; + } + let ks: Vec = lines + .iter() + .map(|l| { + assert!(l.starts_with("UMA: 32768 KB for ") && l.contains("uma.rs:") && l.contains(" – no room (0 MB used) – "), "HEAD's line, the count after it: {l}"); + l.strip_suffix(" failures so far").and_then(|s| s.rsplit(' ').next()).and_then(|k| k.parse().ok()).unwrap_or_else(|| panic!("the count at the end: {l}")) + }) + .collect(); + assert!(ks.iter().all(|&k| k0 < k && k <= k1 && failure_traced(k)), "{ks:?} in {k0}..={k1}"); + if k1 - k0 == 40 { + assert_eq!(ks, (k0 + 1..=k0 + 40).filter(|&k| failure_traced(k)).collect::>(), "each traced failure said once, in order"); + } + } } diff --git a/crates/xcl/src/hle/bcpack/tables.rs b/crates/xcl/src/hle/bcpack/tables.rs index 5b5cd3d..cd1ced8 100644 --- a/crates/xcl/src/hle/bcpack/tables.rs +++ b/crates/xcl/src/hle/bcpack/tables.rs @@ -1438,7 +1438,7 @@ pub static BC6: [(Bc6Ep, Bc6Ix); DICTIONARY] = [ (Bc6Ep { e: [[45056, 40960, 38400], [0, 38912, 45056], [29696, 37888, 36864], [12288, 26624, 45056]] }, Bc6Ix { mode: 8, ix: [-4, 3, -2, -3, -2, 0, -3, -3, 1, -2, -4, -3, 2, -3, -3, -3] }), ]; pub static BC7: [(Bc7Ep, Bc7Ix); DICTIONARY] = [ - (Bc7Ep { ctrl: 0, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [4, 0], ix: [[2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }), + (Bc7Ep { ctrl: 0, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [4, 0], ix: [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }), (Bc7Ep { ctrl: 1, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [3, 0], ix: [[1, 0, 0, 0, 0, 0, -1, -1, 0, -1, 0, 0, 0, -1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }), (Bc7Ep { ctrl: 4, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [4, 0], ix: [[4, 5, 3, 4, 4, 4, 4, 3, 4, 4, 5, 4, 5, 4, 4, 4], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }), (Bc7Ep { ctrl: 5, rows: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] }, Bc7Ix { bits: [4, 0], ix: [[2, -2, -4, -2, 3, -2, -4, -2, -2, 1, -4, -3, -2, -1, -4, -3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }), diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs index 70c425a..ccfaf23 100644 --- a/crates/xcl/src/hle/bcpack/tests.rs +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -103,14 +103,17 @@ fn junk_streams_do_not_panic() { } /// The BC7 dictionary indices follow VIctory PR #658: a set with 0 bits holds no -/// indices, and pixel 0 is the anchor (top bit clear). Entry 0 stores all 32 indices -/// directly without the repeated width word, keeping its leading `[2, 1, 0, ...]` values. +/// indices, and pixel 0 is the anchor (top bit clear). Entry 0 is read like the other 254: +/// every BC7 record of `bcpack-tables.bin` is 116 bytes, and the u16 after the two widths is +/// skipped in all of them (in entry 0 it is 2, not its widths). So entry 0's first indices are +/// `[1, 0, ...]`, as `scripts/gen_bcpack_victory_tables.py` writes them; reading that u16 as +/// an index instead would make them `[2, 1, 0, ...]`. #[test] fn bc7_dictionary_indices_line_up() { let (ep0, ix0) = super::tables::BC7[0]; assert_eq!(ep0.ctrl, 0); assert_eq!(ix0.bits, [4, 0]); - assert_eq!(ix0.ix[0], [2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + assert_eq!(ix0.ix[0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); assert_eq!(ix0.ix[1], [0; 16]); for (k, (_, ix)) in super::tables::BC7.iter().enumerate() { assert!(ix.bits[0] > 0, "entry {k}: the first index set has no bits"); diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 6fd8cb2..ece2296 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -315,6 +315,12 @@ mod tests { drop(lists); drop(list); drop(alloc); + // (where its last Release is held until the queues are past its work, nothing of it + // goes before that – `late_release`) + let t = std::time::Instant::now(); + while current(a as usize) != a as usize && t.elapsed().as_secs() < 10 { + std::thread::sleep(std::time::Duration::from_millis(5)); + } assert_eq!(current(a as usize), a as usize, "a released allocator leaves nothing behind"); assert!(!STATE.lock().unwrap().as_ref().unwrap().types.contains_key(&(a as usize))); } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7b997d0..aff8250 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; use std::ffi::c_void; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use windows::core::Interface; @@ -37,6 +37,11 @@ struct State { arena: crate::gpu::uma::Arena, res_buf: Option<(ID3D12Resource, u64, usize)>, res_retired: Vec<(ID3D12Resource, u64, usize)>, + /// the `res` blocks (unified memory) of this recording's translated compute dispatches + /// (`res_block`): given a new serial and a count of 0 when the recording runs again + res_blocks: Vec, + /// this recording was submitted (`before_submit`) + submitted: bool, } static ALLOC_RES: Mutex>>> = Mutex::new(None); @@ -76,6 +81,12 @@ const DISPATCHES: usize = 3; const DISPATCHES_SKIPPED: usize = 4; fn count(k: usize) { + #[cfg(test)] + MY_COUNTS.with(|c| { + let mut v = c.get(); + v[k] += 1; + c.set(v); + }); let n = COUNTS[k].fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() && n >= 64 { let c: Vec = COUNTS.iter().map(|c| c.load(Ordering::Relaxed)).collect(); @@ -89,6 +100,155 @@ fn count(k: usize) { } } +/// Why a pipeline must not reach the PC (`unbuilt`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Unbuilt { + /// a stand-in whose real pipeline was not there when the bind resolved it (a build that ended + /// just after, or one no bind waited for) + Building, + /// … still being built while binds go on without it (`pso_async`: past its wait, the big lane) + Late, + /// a stand-in whose build failed or was refused (`XCL_PSO_MAX_DXIL_KB`, `XCL_NO_BUILD_CS`) + Failed, + /// a pipeline of XCL's fallback shaders (`real::fallback_kind`) + Fallback, +} + +impl Unbuilt { + fn describe(self) -> &'static str { + match self { + Unbuilt::Building => "its pipeline was still being built when this was recorded", + Unbuilt::Late => "its pipeline is late: still being built while binds go on without it", + Unbuilt::Failed => "its pipeline's build failed or was refused", + Unbuilt::Fallback => "XCL's fallback shaders stand in for shaders without a translation", + } + } +} + +/// work skipped because its pipeline was not built or is a fallback (`skip_unbuilt`), by where +/// (`pso_async::note_skip` is told of the same skips less those of fallbacks) +static UNBUILT: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +const U_DISPATCH: usize = 0; +const U_INDIRECT_COMPUTE: usize = 1; +const U_INDIRECT_DRAW: usize = 2; +const U_DISPATCH_MESH: usize = 3; +const U_DRAW: usize = 4; +const U_WHERE: [&str; 5] = ["Dispatch", "ExecuteIndirect (compute)", "ExecuteIndirect (draws)", "DispatchMesh", "draw"]; + +/// `XCL_STANDIN_SKIP=0`: ExecuteIndirect and DispatchMesh hold back only a stand-in whose build is +/// not over, as before 0023 – a failed or refused one, and a pipeline of XCL's fallback shaders, go +/// to the PC with the title's arguments and whatever root signature the list holds (the invalid +/// pair of `execute_indirect`'s note). For bisecting only: with group A's refusals it is that call. +fn standin_skip_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_STANDIN_SKIP").map_or(true, |v| v.trim() != "0"); + if !on { + crate::xlog_warn!("XCL_STANDIN_SKIP=0: ExecuteIndirect and DispatchMesh of a stand-in whose build failed or was refused, or of XCL's fallback shaders, go to the PC as before 0023 – a root signature that does not match the pipeline"); + } + on + }) +} + +/// `XCL_STANDIN_SKIP_DRAWS=0`: a draw with a stand-in whose pipeline is not built, or with XCL's +/// fallback shaders, is drawn with them and counted with the PC pipelines, as before 0023 (they +/// draw nothing; a point list one magenta pixel at the centre). +fn standin_skip_draws_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_STANDIN_SKIP_DRAWS").map_or(true, |v| v.trim() != "0")) +} + +/// Why `raw`, resolved to `resolved` (`pso_async::resolve_wait`), must not go to the PC, and whether +/// it computes. A stand-in the bind still holds – `resolved == raw`: its real pipeline was not there +/// when it was resolved; a build that ends between the two looks must not send the stand-in – or a +/// pipeline of XCL's fallback shaders. None: a real pipeline, or the title's own PC pipeline. +fn unbuilt(raw: usize, resolved: usize) -> Option<(Unbuilt, bool)> { + if resolved == raw { + if let Some(s) = super::pso_async::standin_state(raw) { + let why = if s.late && !s.done { + Unbuilt::Late + } else if s.done && !s.built { + Unbuilt::Failed + } else { + Unbuilt::Building + }; + return Some((why, s.compute)); + } + } + super::real::fallback_kind(resolved).map(|compute| (Unbuilt::Fallback, compute)) +} + +/// The gate of ExecuteIndirect and DispatchMesh (`XCL_STANDIN_SKIP=0`: only a stand-in whose +/// build is not over, as `is_pending` did). +fn held_back(raw: usize, resolved: usize) -> Option<(Unbuilt, bool)> { + if standin_skip_on() { + return unbuilt(raw, resolved); + } + super::pso_async::standin_state(raw).filter(|s| !s.done).map(|s| (if s.late { Unbuilt::Late } else { Unbuilt::Building }, s.compute)) +} + +#[cfg(test)] +thread_local! { + /// (tests) this thread's last skip: (pipeline, where, why) + static LAST_UNBUILT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// (tests) `COUNTS` of this thread's binds: the suite runs on 6 threads, and exact deltas of the + /// process's counts race + static MY_COUNTS: std::cell::Cell<[u64; 5]> = const { std::cell::Cell::new([0; 5]) }; +} + +#[cfg(test)] +fn take_last_unbuilt() -> Option<(usize, usize, Unbuilt)> { + LAST_UNBUILT.with(|c| c.take()) +} + +/// Work with `raw` (`why`) skipped at `at`: counted (`UNBUILT`, and the dispatches or draws +/// skipped), a stand-in's skip told to `pso_async` (its program's tally – at every place, never +/// for a fallback), the first 8 of each place and then every 2^k-th logged. +fn skip_unbuilt(at: usize, raw: usize, why: Unbuilt) { + UNBUILT[at].fetch_add(1, Ordering::Relaxed); + count(if matches!(at, U_DISPATCH | U_INDIRECT_COMPUTE) { DISPATCHES_SKIPPED } else { DRAWS_SKIPPED }); + if why != Unbuilt::Fallback { + super::pso_async::note_skip(raw); + } + #[cfg(test)] + LAST_UNBUILT.with(|c| c.set(Some((raw, at, why)))); + static LOGGED: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + let n = LOGGED[at].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + let u: [u64; 5] = std::array::from_fn(|k| UNBUILT[k].load(Ordering::Relaxed)); + crate::xlog_warn!( + "D3D12.X: {} with the pipeline {raw:#x} skipped – {} (#{n} there; so far {} Dispatch, {} compute and {} draw ExecuteIndirect, {} DispatchMesh, {} draws)", + U_WHERE[at], why.describe(), u[0], u[1], u[2], u[3], u[4] + ); + } +} + +/// (`XCL_ACTIVITY`) ExecuteIndirect of translated pipelines recorded so far, by where their +/// arguments were and what became of them (`indirect::census`), and the work skipped for a +/// pipeline not built (`skip_unbuilt`). None: nothing counted, or nothing new since the last line. +pub fn indirect_line() -> Option { + // (the counts at the last call, the draws checked then: the activity thread calls this every 2 s) + static LAST: Mutex<(u64, u64)> = Mutex::new((0, 0)); + let c = indirect::census_snapshot(); + let u: [u64; 5] = std::array::from_fn(|k| UNBUILT[k].load(Ordering::Relaxed)); + let sum = c.sum() + u.iter().sum::(); + let checked = c.checked_draws(); + let (last_sum, last_checked) = std::mem::replace(&mut *LAST.lock().unwrap_or_else(|e| e.into_inner()), (sum, checked)); + if sum == 0 || sum == last_sum { + return None; + } + let census = if indirect::census_on() { c.text(checked.saturating_sub(last_checked)) } else { "not counted (XCL_INDIRECT_CENSUS=0)".to_string() }; + Some(indirect_line_text(&census, &u)) +} + +/// The line itself (what run 65's tools read). +fn indirect_line_text(census: &str, u: &[u64; 5]) -> String { + format!( + "ExecuteIndirect recorded so far: {census}; work skipped for a pipeline not built: {} Dispatch, {} compute and {} draw ExecuteIndirect, {} DispatchMesh, {} draws", + u[0], u[1], u[2], u[3], u[4] + ) +} + fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default()) } @@ -111,6 +271,8 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + s.res_blocks.clear(); + s.submitted = false; let mut res_bufs = std::mem::take(&mut s.res_retired); if let Some(b) = s.res_buf.take() { res_bufs.push(b); @@ -119,6 +281,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { }); console_list::hold_until_reset(old, blocks); hold_res_until_reset(old, res_bufs); + super::stall::list_reset(list); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults @@ -155,6 +318,8 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.args_gfx = args_gfx; s.rs_gfx = rs_gfx; s.pso = pso; + s.res_blocks.clear(); + s.submitted = false; let mut res_bufs = std::mem::take(&mut s.res_retired); if let Some(b) = s.res_buf.take() { res_bufs.push(b); @@ -163,6 +328,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u }); console_list::hold_until_reset(old, blocks); hold_res_until_reset(old, res_bufs); + super::stall::list_reset(to); } /// Kickoff can move a list to another backing without going through the bind Reset hook. @@ -174,6 +340,8 @@ fn sync_recording_backing(list: *mut c_void) { } let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); + s.res_blocks.clear(); + s.submitted = false; let mut res = std::mem::take(&mut s.res_retired); res.extend(s.res_buf.take()); Some((old, std::mem::take(&mut s.uma), res)) @@ -194,6 +362,36 @@ pub(super) fn forget(list: *mut c_void) { } hold_res_until_reset(s.allocator, s.res_retired); } + super::stall::list_reset(list); +} + +/// `lists` are about to be submitted – before XCL sends the CPU's writes to video memory +/// (`title_textures::refresh`). A recording submitted before runs again: its compute `res` +/// blocks get a count of 0 and a new serial on the CPU, so the upload clears what the GPU +/// counted in its last run (`res_block`). +pub(super) fn before_submit(lists: &[*mut c_void]) { + let mut g = STATES.lock().unwrap(); + let Some(m) = g.as_mut() else { return }; + for &l in lists { + let Some(s) = m.get_mut(&(l as usize)) else { continue }; + if !s.submitted { + s.submitted = true; + continue; + } + for &p in &s.res_blocks { + // (XCL's own block in unified memory, held until the recording's allocator is reset) + unsafe { std::ptr::write_volatile(p as *mut [u32; 2], [0, next_res_serial()]) }; + } + } +} + +/// KickoffX submitted `list` and reset it on the PC: it records anew. +pub(super) fn kicked_off(list: *mut c_void) { + with(list, |s| { + s.res_blocks.clear(); + s.submitted = false; + }); + super::stall::list_reset(list); } #[cfg(test)] @@ -634,8 +832,10 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: } return; } - if super::pso_async::is_pending(raw_pso) { - count(DRAWS_SKIPPED); + // a stand-in whose pipeline is not built, or XCL's fallback: its dummy mesh shader draws + // nothing, with a root signature the list may not hold (`unbuilt`) + if let Some((why, _)) = held_back(raw_pso, pso) { + skip_unbuilt(U_DISPATCH_MESH, raw_pso, why); return; } let rs = with(this, |s| s.rs_gfx) as *mut c_void; @@ -649,12 +849,16 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a /// translated pipeline, on XCL's ABI with the kept root arguments and any per-command updates. 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) { + let _xcl_api = crate::waitwatch::api("bind::execute_indirect"); 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 raw_pso = with(this, |s| s.pso); let pso = super::pso_async::resolve_wait(raw_pso); let args_pc_off = args_off + super::real::buffer_delta(args); - let count_off = count_off + super::real::buffer_delta(count_buf); + // the count's offset as the title gave it, and as the PC's ExecuteIndirect takes it (`count_off`: + // from offset 0 of the buffer's PC resource, `buffer_delta`) + let count_title_off = count_off; + let count_off = count_title_off + super::real::buffer_delta(count_buf); let mac = crate::util::mac_host(); if let Some(tp) = mac.then(|| super::real::two_pass_of(pso)).flatten() { @@ -721,20 +925,30 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); if !gfx && !compute { - // A pipeline still being built (or whose build failed): its stand-in draws nothing, and - // the list may hold XCL's ABI root signature from a translated draw before it – the PC - // call with that pair is invalid (debug layer 953, "the currently set Root Signature - // doesn't match the currently set Pipeline State Object"; a retail title's world then - // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. - if super::pso_async::is_pending(raw_pso) { - count(DRAWS_SKIPPED); - 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: ExecuteIndirect with a pipeline that is still being built skipped"); + // A stand-in whose pipeline is not built – still being built, late, failed or refused + // (`pso_async`) – or a pipeline of XCL's fallback shaders. It draws and computes nothing, + // and the list may hold XCL's ABI root signature from a translated draw or dispatch before + // it: the PC call with that pair is invalid (debug layer 953, "the currently set Root + // Signature doesn't match the currently set Pipeline State Object"; a retail title's world + // then hung the GPU, 0x887a0006), with the title's arguments unchecked. A compute one never + // has the title's compute root signature on the PC list at all (it stays here: + // `set_compute_root_signature`). Skipped, like a draw or dispatch of such a pipeline. + if let Some((why, computes)) = held_back(raw_pso, pso) { + let at = if dispatch_mesh_stride(sig).is_some() { + U_DISPATCH_MESH + } else if computes { + U_INDIRECT_COMPUTE + } else { + U_INDIRECT_DRAW + }; + if at == U_INDIRECT_COMPUTE { + let call = super::skip_roots::Call::Indirect { sig, max, args: (args, args_off), count: (count_buf, count_title_off) }; + skipped_unbuilt_roots(this, raw_pso, why, call); } + skip_unbuilt(at, raw_pso, why); return; } - // a PC pipeline: the title's root signature, as for a draw (`graphics_bound`) + // a PC pipeline (the title's own shaders): the title's root signature, as for a draw (`graphics_bound`) let rs = with(this, |s| s.rs_gfx) as *mut c_void; if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { list.SetGraphicsRootSignature(r); @@ -750,40 +964,123 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let (hash, threads) = if compute { super::real::pso_console_cs(pso).unwrap_or((0, 0)) } else { (0, 0) }; + // (the title's arguments and count as it gave them: `[indirect]` and XCL_SKIP_CS's root views + // name their addresses) + let at = ArgsAt { args: (args, args_off), count: (count_buf, count_title_off) }; + if compute && skip_cs(this, hash, threads, super::skip_roots::Call::Indirect { sig, max, args: at.args, count: at.count }) { + return; + } + // where the arguments are – for every translated ExecuteIndirect while anything counts or checks + // them (the census, the draw check, XCL_INDIRECT_OWN, the lists' counts by place – + // `stall::indirect_on`); else compute and the draws `[indirect]` still logs, as before 0023 + let place = if compute || indirect::census_on() || indirect::draw_check_on() || indirect::own_skip() || super::stall::indirect_on() || note_indirect_draws() { + indirect::classify(args, args_off) + } else { + super::stall::Args::Unknown + }; + if count_buf != 0 && indirect::census_on() { + indirect::census_count_buffer(gfx, indirect::classify(count_buf, count_title_off)); + } + let key = if compute { hash } else { pso as u64 }; + // `XCL_INDIRECT_OWN=skip`: arguments in a PC resource of their own – which no translated + // program and no CPU write of the title reaches – are not recorded (nor counted for the list) + if place == super::stall::Args::Own && indirect::own_skip() { + indirect::census(gfx, place, indirect::Fate::SkippedOwn); + note_indirect_args(gfx, key, place, at, max, false, Some(&"XCL_INDIRECT_OWN=skip".to_string())); + count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); + return; + } + let mut checked = false; let result = match mac.then(|| indirect::lookup(sig)).flatten() { Some(Some(signature)) => { sync_recording_backing(this); let allocator = with(this, |s| s.allocator); if allocator == 0 { - return; - } - let repack = indirect::Repack { signature: &signature, resource: args, offset: args_off, max, gfx }; - bind_abi_before(this, list, pso, gfx, |layout, inline, shadow, io, root| { - let u = crate::gpu::uma::get().ok_or("no unified memory")?; - repack.record(list, root, layout.ok_or("no bound console root layout")?, inline, shadow, io, |size| { - with(this, |s| s.arena.take(u, size, 16, &mut s.uma)).map(|p| p as usize) + // (nothing is recorded either way: counted and named like the other refusals) + Err("no allocator for the repacked arguments".to_string()) + } else { + let repack = indirect::Repack { signature: &signature, resource: args, offset: args_off, max, gfx }; + // (the repacker drops a dispatch command with absurd group counts – `groups_ok`) + checked = compute && indirect::sanitize_on(); + bind_abi_before(this, list, pso, gfx, |layout, inline, shadow, io, root| { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + repack.record(list, root, layout.ok_or("no bound console root layout")?, inline, shadow, io, |size| { + with(this, |s| s.arena.take(u, size, 16, &mut s.uma)).map(|p| p as usize) + }) + }).map(|packed| { + let offset = packed.bind_arguments(list); + fresh_indirect_arguments(this, || { + pc(this, packed.signature.as_raw() as usize, max, packed.arguments.as_raw() as usize, offset, count_buf, count_off); + }); + packed.finish_gpu(list); + with(this, |s| { + let shadow = if gfx { &mut s.args_gfx } else { &mut s.args }; + packed.retain_and_clear(s.allocator, shadow); + }); + if offset == 0 { "indirect repacked" } else { "indirect repacked single dispatch" } }) - }).map(|packed| { - let offset = packed.bind_arguments(list); - fresh_indirect_arguments(this, || { - pc(this, packed.signature.as_raw() as usize, max, packed.arguments.as_raw() as usize, offset, count_buf, count_off); - }); - packed.finish_gpu(list); - with(this, |s| { - let shadow = if gfx { &mut s.args_gfx } else { &mut s.args }; - packed.retain_and_clear(s.allocator, shadow); - }); - if offset == 0 { "indirect repacked" } else { "indirect repacked single dispatch" } - }) + } } Some(None) => Err("unsupported root-changing command signature".into()), - None => bind_abi(this, list, pso, gfx).map(|()| { - fresh_indirect_arguments(this, || { - pc(this, sig, max, args, args_pc_off, count_buf, count_off); - }); - "indirect direct arguments" - }), + None => { + let check = if !mac || max == 0 { + None + } else if compute { + // a dispatch signature: the group counts checked on the GPU first (`indirect::Sanitize`) + indirect::sanitize_on().then(|| indirect::plain_dispatch(sig)).flatten().map(|stride| (stride, indirect::Command::Dispatch)) + } else { + // a draw signature with its arguments outside unified memory or in a resource XCL does + // not know (once work was skipped, or `all`: anywhere): its commands checked on the GPU first + indirect::draw_check(place, sig, || bound_indices(this)) + }; + // the title's arguments as they are, after the writes before them (`fresh_indirect_arguments`) + let direct = || { + bind_abi(this, list, pso, gfx).map(|()| { + fresh_indirect_arguments(this, || { + pc(this, sig, max, args, args_pc_off, count_buf, count_off); + }); + "indirect direct arguments" + }) + }; + // (not in a bundle: barriers are not allowed there) + match check.filter(|_| list.GetType() != D3D12_COMMAND_LIST_TYPE_BUNDLE) { + // (XCL's checked copy is a buffer of its own, in INDIRECT_ARGUMENT after the check) + Some((stride, cmd)) => match checked_execute_indirect(this, list, pso, gfx, cmd, stride, max, args, args_off, count_buf, count_off, pc) { + Ok(()) => { + checked = true; + if gfx { + // (the check's SetPipelineState moved list_x's key off the title's + // pipeline: depth bias and splits look it up by that key) + super::list_x::on_set_pipeline_state(this, raw_pso); + } + Ok("indirect checked arguments") + } + Err(e) => { + unchecked_warning(gfx, hash, pso, &e); + direct() + } + }, + None => direct(), + } + } }; + let checked = checked && result.is_ok(); + indirect::census(gfx, place, match (&result, checked) { + (Err(_), _) => indirect::Fate::Failed, + (Ok(_), true) => indirect::Fate::Checked, + (Ok(_), false) => indirect::Fate::AsIs, + }); + note_indirect_args(gfx, key, place, at, max, checked, result.as_ref().err()); + // a draw's: counted for its list as recorded, and as run with each submission of the list + // (compute's are counted with their record – `stall::note`) + if gfx && result.is_ok() { + super::stall::note_indirect_draw(this, place); + } + if compute && result.is_ok() { + super::stall::count_indirect(checked); + super::stall::note(this, super::stall::Rec { hash, threads, what: super::stall::What::Indirect { max, args: place, checked, count: count_buf != 0 } }); + } match result { Ok(kind) => { super::list_x::note_stall_work(this, kind, pso, [args as u64, count_buf as u64, max.into()]); @@ -799,6 +1096,129 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } +/// The PC's ExecuteIndirect (#59). +type ExecuteIndirectFn = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); + +/// A translated pipeline's per-dispatch block `res` (u1). Compute: word 0 counts the waves whose +/// loop budget ran out (`xcl_budget_spent` – 0 here), word 1 is a serial of the dispatch (the +/// windows upload a chunk only when its bytes changed: without it a count the GPU left at this +/// address would carry over to the next dispatch there; a recording run again gets new ones – +/// `before_submit`), word 2 how many such waves a dispatch has before its later ones skip their +/// loops (`emit::budget_trip_waves`). One block serves all the commands of an ExecuteIndirect, +/// and a bundle's dispatch in all its runs (bundles and lists of console code – +/// `XCL_CONSOLE_LISTS=1` – get no fresh blocks when they run again). Graphics: zeros, as before. +pub(super) fn res_block(gfx: bool) -> [u8; 256] { + let mut b = [0u8; 256]; + if !gfx { + b[4..8].copy_from_slice(&next_res_serial().to_le_bytes()); + b[8..12].copy_from_slice(&crate::gpu::recomp::emit::budget_trip_waves().to_le_bytes()); + } + b +} + +/// A serial for a compute `res` block (never 0). +fn next_res_serial() -> u32 { + static SERIAL: AtomicU64 = AtomicU64::new(0); + ((SERIAL.fetch_add(1, Ordering::Relaxed) + 1) as u32).max(1) +} + +/// ExecuteIndirect of a translated pipeline with a plain signature of `stride` bytes and one +/// DISPATCH, DRAW or DRAW_INDEXED argument (`cmd`): XCL's pass copies the commands to a buffer of its +/// own, the absurd ones made 0 (`indirect::Sanitize`), and the ExecuteIndirect reads them there. +/// Err: nothing was recorded (the caller passes the title's arguments as they are). +#[allow(clippy::too_many_arguments)] +unsafe fn checked_execute_indirect( + this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, cmd: indirect::Command, stride: u32, max: u32, + args: usize, args_off: u64, count_buf: usize, count_off: u64, pc: ExecuteIndirectFn, +) -> Result<(), String> { + sync_recording_backing(this); + let allocator = with(this, |s| s.allocator); + if allocator == 0 { + return Err("no allocator for the checked arguments".into()); + } + // (made before anything is recorded: a failure leaves the list as it was) + let prepared = indirect::Sanitize::prepare_command(list, allocator, args, args_off, stride, max, cmd)?; + // (a draw's check is a compute pass: the draw's own root signature, root UAVs and pipeline are + // bound after it, the pipeline last) + let checked = bind_abi_before(this, list, pso, gfx, |_, _, _, _, _| Ok(prepared.record(list)))?; + pc(this, checked.signature.as_raw() as usize, max, checked.buffer.as_raw() as usize, checked.offset, count_buf, count_off); + checked.finish(list); + Ok(()) +} + +/// A compute or draw ExecuteIndirect whose check could not be made (the first 8 of each). +fn unchecked_warning(gfx: bool, hash: u64, pso: usize, e: &str) { + static N: [std::sync::atomic::AtomicU32; 2] = [const { std::sync::atomic::AtomicU32::new(0) }; 2]; + if N[gfx as usize].fetch_add(1, Ordering::Relaxed) < 8 { + if gfx { + crate::xlog_warn!("D3D12.X: ExecuteIndirect of a draw (pipeline {pso:#x}): its arguments are not checked ({e}) – the title's arguments go to the GPU as they are"); + } else { + crate::xlog_warn!("D3D12.X: ExecuteIndirect of {hash:016x}: its group counts are not checked ({e}) – the title's arguments go to the GPU as they are"); + } + } +} + +/// Indices the index buffer bound on `list` holds (u32::MAX: none XCL knows – the check does not +/// look at the index range then). +unsafe fn bound_indices(list: *mut c_void) -> u32 { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT}; + match super::list_x::bound_index_buffer(list) { + Some(v) if v.Format == DXGI_FORMAT_R32_UINT => v.SizeInBytes / 4, + Some(v) if v.Format == DXGI_FORMAT_R16_UINT => v.SizeInBytes / 2, + _ => u32::MAX, + } +} + +/// The title's arguments of an ExecuteIndirect and its count: (resource, the title's offset) – +/// as the title gave them (never XCL's checked copy). +#[derive(Clone, Copy)] +struct ArgsAt { + args: (usize, u64), + count: (usize, u64), +} + +/// `[indirect]`: the first ExecuteIndirect of each console program (compute – `key` its hash) +/// or pipeline (draws – `key` its address) with its arguments in each kind of place, the first +/// 128 of compute and 32 of draws, with where they are in title memory (`outside::args_at`) – +/// translated programs reach title memory through unified memory only, and what a GPU producer +/// writes outside it never reaches the arguments a PC ExecuteIndirect reads. +#[allow(clippy::too_many_arguments)] +fn note_indirect_args(gfx: bool, key: u64, place: super::stall::Args, at: ArgsAt, max: u32, checked: bool, skipped: Option<&String>) { + static SEEN: Mutex>> = Mutex::new(None); + { + let mut g = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(Default::default); + let budget = if gfx { &INDIRECT_DRAWS_LOGGED } else { &INDIRECT_COMPUTE_LOGGED }; + if budget.load(Ordering::Relaxed) >= if gfx { 32 } else { 128 } || !s.insert((gfx, key, place)) { + return; + } + budget.fetch_add(1, Ordering::Relaxed); + } + let what = if gfx { format!("a draw (pipeline {key:#x})") } else { format!("{key:016x}") }; + crate::xlog_info!( + "[indirect] {what} ExecuteIndirect (up to {max} command(s){}): arguments {}{}{}", + if at.count.0 != 0 { ", a count buffer" } else { "" }, + place.describe(), + // (a live resource of the title's: the call it came with is going on) + unsafe { super::outside::args_at(at.args.0, at.args.1, at.count) }, + match (checked, skipped) { + (_, Some(e)) => format!("; skipped: {e}"), + (true, None) if gfx => "; its arguments checked on the GPU first".to_string(), + (true, None) => "; group counts checked on the GPU first".to_string(), + (false, None) => String::new(), + } + ); +} + +static INDIRECT_COMPUTE_LOGGED: AtomicU64 = AtomicU64::new(0); +static INDIRECT_DRAWS_LOGGED: AtomicU64 = AtomicU64::new(0); + +/// Whether draws' ExecuteIndirect are still logged (`note_indirect_args`; past its 32 the +/// arguments of draws are not looked at). +fn note_indirect_draws() -> bool { + INDIRECT_DRAWS_LOGGED.load(Ordering::Relaxed) < 32 +} + /// XCL's own buffers for `fresh_indirect_arguments` cached per device (device -> buffer): COMMON between its uses static ARGUMENT_ORDER: Mutex>> = Mutex::new(None); @@ -985,15 +1405,14 @@ 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::is_translated_graphics(super::pso_async::resolve_wait(pso)) { - count(DRAWS_PC); + let real = super::pso_async::resolve_wait(pso); + if !super::real::is_translated_graphics(real) { if super::present::trace_frame() { // which pipelines draw without a translation (first 12 distinct) static SEEN: Mutex> = Mutex::new(Vec::new()); let mut g = SEEN.lock().unwrap(); if !g.contains(&pso) && g.len() < 12 { g.push(pso); - let real = super::pso_async::resolve_wait(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), @@ -1002,9 +1421,19 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option ); } } - // a PC pipeline (also a stand-in or fallback: made with the title's root signature): - // the title's root signature, which nothing else binds on the PC list – a draw without - // one is invalid (the debug layer reports it on every GPU; WARP faults on it) + // a stand-in whose pipeline is not built, or XCL's fallback: its dummy shaders would draw + // nothing (a point list one magenta pixel) – skipped (`unbuilt`; XCL_STANDIN_SKIP_DRAWS=0: drawn) + if standin_skip_draws_on() { + if let Some((why, _)) = unbuilt(pso, real) { + skip_unbuilt(U_DRAW, pso, why); + return None; + } + } + count(DRAWS_PC); + // a PC pipeline (the title's own shaders – with XCL_STANDIN_SKIP_DRAWS=0 also a stand-in or + // a fallback, made with the title's root signature): the title's root signature, which + // nothing else binds on the PC list – a draw without one is invalid (the debug layer reports + // it on every GPU; WARP faults on it) let rs = with(this, |s| s.rs_gfx) as *mut c_void; if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) { list.SetGraphicsRootSignature(r); @@ -1290,11 +1719,33 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + dispatch_call(this, [x, y, z], None) +} + +/// DispatchX (`list_x::dispatch_x`): a Dispatch – its flags are not applied, only named +/// (`note_dispatch_x_flags`). +pub(super) unsafe fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + dispatch_call(this, [x, y, z], Some(flags)) +} + +/// A Dispatch of `[x, y, z]` groups – DispatchX's `flags`, None for a Dispatch. +unsafe fn dispatch_call(this: *mut c_void, [x, y, z]: [u32; 3], flags: Option) { + let _xcl_api = crate::waitwatch::api("bind::dispatch"); + let raw = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(raw); + if let Some(f) = flags { + note_dispatch_x_flags(&DISPATCH_X_FLAGS, f, [x, y, z], || program_of(raw, pso)); + } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; if !super::real::is_translated_compute(pso) { - // a console pipeline without a translation (including a background build that - // failed): nothing to run (its root arguments were not given to the PC list either) + // a stand-in not built or XCL's fallback: counted and logged as such (`skip_unbuilt`) + if let Some((why, _)) = unbuilt(raw, pso) { + skipped_unbuilt_roots(this, raw, why, super::skip_roots::Call::Dispatch { groups: [x, y, z], flags }); + skip_unbuilt(U_DISPATCH, raw, why); + return; + } + // any other pipeline without a translated console shader: nothing to run (its root + // arguments were not given to the PC list either) 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_warn!("D3D12.X: Dispatch with a pipeline that has no translated console shader ({pso:#x}) skipped"); @@ -1302,8 +1753,15 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, count(DISPATCHES_SKIPPED); return; } + let (hash, threads) = super::real::pso_console_cs(pso).unwrap_or((0, 0)); + if skip_cs(this, hash, threads, super::skip_roots::Call::Dispatch { groups: [x, y, z], flags }) { + return; + } match translated_dispatch(this, list, pso, x, y, z) { - Ok(()) => count(DISPATCHES), + Ok(()) => { + count(DISPATCHES); + super::stall::note(this, super::stall::Rec { hash, threads, what: super::stall::What::Groups([x, y, z]) }); + } Err(e) => { count(DISPATCHES_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -1314,6 +1772,128 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, } } +/// `XCL_SKIP_CS`: a dispatch of a listed console program is not recorded (counted, noted, the +/// first 8 logged; at the program's first skips its root views – `skip_roots`). True: skipped. +/// `call`: the Dispatch, DispatchX or ExecuteIndirect it came with (the title's resources, alive +/// for the call). +fn skip_cs(list: *mut c_void, hash: u64, threads: u32, call: super::skip_roots::Call) -> bool { + if !super::stall::skipped(hash) { + return false; + } + // (the world's first frame is near: `XCL_FRAME_DUMP_WORLD` – the first one kept) + super::present::note_world_mark(hash); + count(DISPATCHES_SKIPPED); + super::stall::count_skipped(); + super::stall::note(list, super::stall::Rec { hash, threads, what: super::stall::What::Skipped }); + 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: XCL_SKIP_CS: a dispatch of {hash:016x} not recorded"); + } + // (past a program's first skips: one look) + unsafe { super::skip_roots::note_skip(list, hash, super::skip_roots::Pipeline::Built { threads }, call, || compute_roots(list)) }; + true +} + +/// A dispatch of stand-in `raw`, not built (`why`), skipped: a program XCL_SKIP_CS lists has its +/// root views logged at it all the same – log only, its work stays skipped as unbuilt, within the +/// same budget as `skip_cs`'s. B-1 skips such a dispatch before `skip_cs` sees it: a listed program +/// late at its first world frame's bind would have left no root view line, its key data lost if +/// the title crashed then (run 63) or stalled (run 64). Such a skip marks the world's first frame +/// too (`XCL_FRAME_DUMP_WORLD`), as `skip_cs`'s does. +fn skipped_unbuilt_roots(list: *mut c_void, raw: usize, why: Unbuilt, call: super::skip_roots::Call) { + // (no root view left to log – none listed, XCL_SKIP_CS_ROOTS=0, the budget spent – and the + // world marked or not to be: one look each) + let recording = super::skip_roots::recording(); + let marking = super::present::world_mark_open(); + if !recording && !marking { + return; + } + let Some(hash) = super::pso_async::program_hash(raw).filter(|&h| super::stall::skipped(h)) else { return }; + if marking { + super::present::note_world_mark(hash); + } + if recording { + unsafe { super::skip_roots::note_skip(list, hash, super::skip_roots::Pipeline::Unbuilt(why.describe()), call, || compute_roots(list)) }; + } +} + +/// The compute root signature's layout and the arguments `list` keeps (none for a list bind does +/// not know: nothing is made for it). +fn compute_roots(list: *mut c_void) -> (Option>, Vec) { + let g = STATES.lock().unwrap_or_else(|e| e.into_inner()); + g.as_ref().and_then(|m| m.get(&(list as usize))).map_or((None, Vec::new()), |s| (s.layout.clone(), s.args.clone())) +} + +/// The console program a Dispatch of `raw`, resolved to `pso`, runs – a look only: a translated +/// pipeline's (`real::pso_console_cs` of a pipeline already resolved), else its stand-in's +/// (`pso_async::program_hash`); 0: none known. +fn program_of(raw: usize, pso: usize) -> u64 { + if super::real::is_translated_compute(pso) { + super::real::pso_console_cs(pso).map_or(0, |c| c.0) + } else { + super::pso_async::program_hash(raw).unwrap_or(0) + } +} + +/// DispatchX's flags (`dispatch_x`) are not applied: XCL takes its counts as groups. cool_fox's +/// notes say flag 0x20 makes them threads – taken as groups, such a stage of the title's +/// structure builder ran up to 64 times its threads. Each distinct value but 0 is named once, +/// with the program and the counts as given, the first 16 values in the process; after that one +/// look at the values named, no lock. +fn note_dispatch_x_flags(seen: &FirstValues, flags: u32, groups: [u32; 3], program: impl FnOnce() -> u64) { + if !seen.first(flags) { + return; + } + let line = dispatch_x_flags_line(flags, program(), groups); + crate::xlog_info!("{line}"); + #[cfg(test)] + FLAGS_LINES.with(|l| l.borrow_mut().push(line)); +} + +fn dispatch_x_flags_line(flags: u32, hash: u64, groups: [u32; 3]) -> String { + format!("D3D12.X: DispatchX flags {flags:#x} ({hash:016x}, counts {}×{}×{}): not applied", groups[0], groups[1], groups[2]) +} + +/// the DispatchX flags named so far +static DISPATCH_X_FLAGS: FirstValues = FirstValues::new(); + +/// Values seen for the first time (`first`): each distinct one but 0 once, the first 16. +struct FirstValues { + seen: [AtomicU32; 16], + n: std::sync::atomic::AtomicUsize, + lock: Mutex<()>, +} + +impl FirstValues { + const fn new() -> FirstValues { + FirstValues { seen: [const { AtomicU32::new(0) }; 16], n: std::sync::atomic::AtomicUsize::new(0), lock: Mutex::new(()) } + } + + /// `v` is new (not 0, and fewer than 16 kept): kept. A value kept before is found without the + /// lock; a new one is taken under it. + fn first(&self, v: u32) -> bool { + let known = |n: usize| self.seen.iter().take(n).any(|s| s.load(Ordering::Relaxed) == v); + if v == 0 || self.n.load(Ordering::Acquire) >= self.seen.len() || known(self.n.load(Ordering::Acquire)) { + return false; + } + let _g = self.lock.lock().unwrap_or_else(|e| e.into_inner()); + let n = self.n.load(Ordering::Acquire); + let Some(slot) = self.seen.get(n) else { return false }; + if known(n) { + return false; + } + slot.store(v, Ordering::Relaxed); + self.n.store(n + 1, Ordering::Release); + true + } +} + +#[cfg(test)] +thread_local! { + /// (tests) the DispatchX flags lines this thread logged + static FLAGS_LINES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + /// `XCL_TRACE_FRAME`: a full-screen dispatch (enough groups to cover a 4K target in tiles of up /// to 128 pixels) – what its root arguments say. A bindless title passes the indices of its /// descriptors in root constants and constant buffers: every small value there is looked up @@ -1423,8 +2003,12 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis if super::present::trace_frame() { trace_fullscreen(this, pso, [x, y, z]); } - bind_abi(this, list, pso, false)?; + { + let _xcl_api = crate::waitwatch::api("bind::translated_dispatch: bind_abi"); + bind_abi(this, list, pso, false)?; + } super::list_x::note_stall_work(this, "dispatch", pso, [x.into(), y.into(), z.into()]); + let _xcl_api = crate::waitwatch::api("bind::translated_dispatch: the PC's Dispatch"); list.Dispatch(x, y, z); Ok(()) } @@ -1441,6 +2025,7 @@ unsafe fn bind_abi_before( before: impl FnOnce(Option<&Layout>, usize, &[u8], &[u32], &ID3D12RootSignature) -> Result, ) -> Result { if crate::util::mac_host() { + let _xcl_api = crate::waitwatch::api("bind::bind_abi: sync_recording_backing"); sync_recording_backing(this); } let u = crate::gpu::uma::get().ok_or("no unified memory")?; @@ -1451,9 +2036,13 @@ unsafe fn bind_abi_before( if first == 0 && u.shadowed() { return Err("window 0 of unified memory has no buffer on the GPU".into()); } - let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); + let (layout, args) = { + let _xcl_api = crate::waitwatch::api("bind::bind_abi: the list's state (args)"); + with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }) + }; // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) let copy = |bytes: &[u8]| -> Result { + let _xcl_api = crate::waitwatch::api("bind::bind_abi: arena.take"); let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); Ok(p as usize) @@ -1461,7 +2050,10 @@ unsafe fn bind_abi_before( // 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 user_sgprs = { + let _xcl_api = crate::waitwatch::api("bind::bind_abi: pso_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()); let table_at = copy(&args[inline..])?; let mut io = match layout.as_ref() { @@ -1472,14 +2064,23 @@ unsafe fn bind_abi_before( io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; - let res_at = copy(&[0u8; 256])?; + let res_at = copy(&res_block(gfx))?; + if !gfx { + with(this, |s| s.res_blocks.push(res_at)); + } 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 = { + let _xcl_api = crate::waitwatch::api("bind::bind_abi: root signature lookup"); + 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 pc = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&pc).ok_or("pipeline")?; - let value = before(layout.as_deref(), inline, &args, &io, rs)?; + let value = { + let _xcl_api = crate::waitwatch::api("bind::bind_abi: before()"); + before(layout.as_deref(), inline, &args, &io, rs)? + }; 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); @@ -1487,11 +2088,13 @@ unsafe fn bind_abi_before( list.SetGraphicsRootUnorderedAccessView(k as u32, v); } } else { + let _xcl_api = crate::waitwatch::api("bind::bind_abi: the PC's SetComputeRootSignature / root UAVs"); list.SetComputeRootSignature(rs); for (k, v) in views.enumerate() { list.SetComputeRootUnorderedAccessView(k as u32, v); } } + let _xcl_api = crate::waitwatch::api("bind::bind_abi: the PC's SetPipelineState"); list.SetPipelineState(pc); Ok(value) } @@ -1503,7 +2106,8 @@ pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { #[cfg(test)] pub(super) fn counts_snapshot() -> [u64; 5] { - std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) + // (this thread's binds: exact deltas of the process's counts race under 6 test threads) + MY_COUNTS.with(|c| c.get()) } #[cfg(test)] @@ -1522,6 +2126,38 @@ mod tests { use super::*; use std::sync::atomic::AtomicUsize; + /// A recording submitted again gets its compute `res` blocks back to a count of 0 with a new + /// serial (the upload then clears what the GPU counted in its last run); its first submission + /// and a new recording (KickoffX) leave them as recorded. + #[test] + fn a_recording_run_again_gets_fresh_dispatch_blocks() { + let list = 0x7a_1000usize as *mut c_void; + // (a serial the counter will not reach in a test run) + let mut block = [7u32, 0xDEAD_BEEF, 64, 0]; + let at = block.as_mut_ptr() as usize; + with(list, |s| { + s.res_blocks = vec![at]; + s.submitted = false; + }); + let read = |p: usize| unsafe { std::ptr::read_volatile(p as *const [u32; 4]) }; + before_submit(&[list]); + assert_eq!(read(at), [7, 0xDEAD_BEEF, 64, 0], "the first run is as recorded"); + before_submit(&[list]); + let again = read(at); + assert_eq!((again[0], again[2], again[3]), (0, 64, 0)); + assert!(again[1] != 0xDEAD_BEEF && again[1] != 0, "a new serial: {again:?}"); + before_submit(&[list]); + assert_ne!(read(at)[1], again[1], "each run again a new one"); + // KickoffX: the list records anew – its blocks are not this recording's any more + unsafe { std::ptr::write_volatile(at as *mut u32, 5) }; + kicked_off(list); + before_submit(&[list]); + before_submit(&[list]); + assert_eq!(read(at)[0], 5); + remove_state_for_test(list); + let _ = &mut block; + } + /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. #[test] fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() { @@ -1533,26 +2169,35 @@ mod tests { assert!(cpu_rect_expansion(with_gs)); } - /// An ExecuteIndirect whose bound pipeline is still being built is skipped (its stand-in - /// with XCL's ABI root signature on the list is the debug layer's 953 and a hung GPU); - /// a built or failed one goes to the PC call. The gate `execute_indirect` uses. + /// The predicate every bind site skips by (`unbuilt`): a stand-in the bind still holds – its + /// build not over, failed, or over only after the bind resolved it – and a pipeline of XCL's + /// fallback shaders are held back (its stand-in or fallback with XCL's ABI root signature on + /// the list is the debug layer's 953 and a hung GPU); a stand-in resolved to its built + /// pipeline, a pipeline with no stand-in (the title's own) and none go on. #[test] - fn execute_indirect_with_a_pipeline_still_building_is_skipped() { - let (building, built, failed) = (0x7E57_6001usize, 0x7E57_6002usize, 0x7E57_6003usize); + fn unbuilt_holds_back_stand_ins_not_built_and_fallbacks_only() { + let (building, built, failed) = (0x7B00_1001usize, 0x7B00_1002usize, 0x7B00_1003usize); + let (pc, fallback) = (0x7B00_1004usize, 0x7B00_1005usize); // lazy submits: no worker starts them, so the states stay under the test's control - pso_async::submit_lazy(building, false, Box::new(|| 0x1234), 0); - pso_async::submit_lazy(built, false, Box::new(|| 0x1235), 0); + pso_async::submit_lazy(building, false, Box::new(|| 0x7B00_1234), 0); + pso_async::submit_lazy(built, false, Box::new(|| 0x7B00_1235), 0); pso_async::submit_lazy(failed, false, Box::new(|| 0), 0); - assert!(pso_async::is_pending(building)); - assert_eq!(pso_async::resolve_wait(built), 0x1235); + real::register_fallback_for_test(fallback, true); + assert_eq!(pso_async::resolve_wait(built), 0x7B00_1235); assert_eq!(pso_async::resolve_wait(failed), failed); - assert!(!pso_async::is_pending(built) && !pso_async::is_pending(failed)); - // never resolved: still pending (the skip case), then forgotten - assert!(pso_async::is_pending(building)); + assert_eq!(unbuilt(building, building), Some((Unbuilt::Building, false)), "still being built"); + assert_eq!(unbuilt(failed, failed), Some((Unbuilt::Failed, false)), "its build failed"); + assert_eq!(unbuilt(built, 0x7B00_1235), None, "built: its real pipeline goes on"); + assert_eq!(unbuilt(built, built), Some((Unbuilt::Building, false)), "resolved before it was built: still held back"); + assert_eq!(unbuilt(pc, pc), None, "the title's own pipeline"); + assert_eq!(unbuilt(0, 0), None, "no pipeline"); + assert_eq!(unbuilt(fallback, fallback), Some((Unbuilt::Fallback, true)), "XCL's fallback shaders"); + real::forget_pso_for_test(fallback); + assert_eq!(unbuilt(fallback, fallback), None, "a fallback is forgotten with its pipeline"); pso_async::released(building); pso_async::released(built); pso_async::released(failed); - assert!(!pso_async::is_pending(building)); + assert_eq!(unbuilt(building, building), None, "a released stand-in is none any more"); } /// A dispatch writes an ExecuteIndirect's group count through another buffer over the same @@ -1766,78 +2411,194 @@ void main(uint t : SV_GroupIndex) { forget(list); } + /// A command list of console code as bind's hooks see it, recording what reaches the PC: its + /// table (`real::test_ext_table`) is laid out as an adopted object's, so `real::orig_fn` and + /// the PC methods `ID3D12GraphicsCommandList` calls find the slots below. The one fake of the + /// tests of the bind paths. #[repr(C)] - struct FakeAdoptedList { + struct FakeList { vt: *const usize, refs: AtomicUsize, - dispatch_calls: AtomicUsize, - set_compute_rs_calls: AtomicUsize, - set_compute_uav_calls: AtomicUsize, - set_pso_calls: AtomicUsize, - execute_indirect_calls: AtomicUsize, + /// GetType's answer (DIRECT, or BUNDLE) + ty: std::sync::atomic::AtomicI32, + /// the device GetDevice answers with (0: E_NOINTERFACE) + device: usize, + /// (slot, a, b) of every call but IUnknown's, in order + calls: Mutex>, + /// each SetComputeRoot32BitConstants' words + constants: Mutex>>, + /// each ExecuteIndirect: (signature, max, arguments, offset, count, count offset) + indirect: Mutex>, + } + + /// A `FakeList` with its 96-slot table: both live until the test ends, and nothing outside + /// the test's thread calls into them. + struct Fake { + list: Box, + _tables: (Box<[usize; 96]>, Vec), + } + + impl Fake { + /// A list whose GetDevice answers with `device` (0: none). + fn new(device: usize) -> Fake { + let mut orig = Box::new([0usize; 96]); + orig[0] = fake_query_interface as usize; + orig[1] = fake_add_ref as usize; + orig[2] = fake_release as usize; + orig[7] = fake_get_device as usize; + orig[8] = fake_get_type as usize; + orig[12] = fake_draw_instanced as usize; + orig[14] = fake_dispatch as usize; + orig[25] = fake_set_pipeline_state as usize; + orig[26] = fake_resource_barrier as usize; + orig[29] = fake_set_compute_root_signature as usize; + orig[30] = fake_set_graphics_root_signature as usize; + orig[35] = fake_set_compute_root_constants as usize; + orig[39] = fake_set_compute_root_srv as usize; + orig[41] = fake_set_compute_root_uav as usize; + orig[42] = fake_set_graphics_root_uav as usize; + orig[43] = fake_ia_set_index_buffer as usize; + orig[59] = fake_execute_indirect as usize; + orig[79] = fake_dispatch_mesh as usize; + let (ext, vt) = real::test_ext_table(&orig[..]); + let list = Box::new(FakeList { + vt, + refs: AtomicUsize::new(1), + ty: std::sync::atomic::AtomicI32::new(D3D12_COMMAND_LIST_TYPE_DIRECT.0), + device, + calls: Mutex::new(Vec::new()), + constants: Mutex::new(Vec::new()), + indirect: Mutex::new(Vec::new()), + }); + Fake { list, _tables: (orig, ext) } + } + + /// The list as the title hands it to bind's hooks. + fn ptr(&self) -> *mut c_void { + &*self.list as *const FakeList as *mut c_void + } + + /// How many calls of PC slot `slot` reached the list so far. + fn count(&self, slot: usize) -> usize { + self.list.calls.lock().unwrap().iter().filter(|c| c.0 == slot).count() + } + + /// (a, b) of the last call of PC slot `slot`. + fn last(&self, slot: usize) -> Option<(u64, u64)> { + self.list.calls.lock().unwrap().iter().rev().find(|c| c.0 == slot).map(|c| (c.1, c.2)) + } + } + + unsafe fn fake_of<'a>(this: *mut c_void) -> &'a FakeList { + &*(this as *const FakeList) + } + + unsafe fn fake_call(this: *mut c_void, slot: usize, a: u64, b: u64) { + fake_of(this).calls.lock().unwrap().push((slot, a, b)); + } + + unsafe extern "system" fn fake_query_interface(this: *mut c_void, _riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> windows::core::HRESULT { + fake_add_ref(this); + *ppv = this; + windows::core::HRESULT(0) } unsafe extern "system" fn fake_add_ref(this: *mut c_void) -> u32 { - (*(this as *const FakeAdoptedList)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + fake_of(this).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 } unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 { - (*(this as *const FakeAdoptedList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + fake_of(this).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + + unsafe extern "system" fn fake_get_device(this: *mut c_void, riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> windows::core::HRESULT { + fake_call(this, 7, 0, 0); + let device = fake_of(this).device as *mut c_void; + match ID3D12Device::from_raw_borrowed(&device) { + Some(d) => d.query(riid, ppv), + None => { + *ppv = std::ptr::null_mut(); + windows::Win32::Foundation::E_NOINTERFACE + } + } + } + + unsafe extern "system" fn fake_get_type(this: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { + fake_call(this, 8, 0, 0); + D3D12_COMMAND_LIST_TYPE(fake_of(this).ty.load(Ordering::Relaxed)) + } + + unsafe extern "system" fn fake_draw_instanced(this: *mut c_void, vertices: u32, instances: u32, _first_vertex: u32, _first_instance: u32) { + fake_call(this, 12, vertices.into(), instances.into()); + } + + unsafe extern "system" fn fake_dispatch(this: *mut c_void, x: u32, y: u32, _z: u32) { + fake_call(this, 14, x.into(), y.into()); + } + + unsafe extern "system" fn fake_set_pipeline_state(this: *mut c_void, pso: *mut c_void) { + fake_call(this, 25, pso as u64, 0); + } + + unsafe extern "system" fn fake_resource_barrier(this: *mut c_void, n: u32, _barriers: *const c_void) { + fake_call(this, 26, n.into(), 0); + } + + unsafe extern "system" fn fake_set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { + fake_call(this, 29, rs as u64, 0); + } + + unsafe extern "system" fn fake_set_graphics_root_signature(this: *mut c_void, rs: *mut c_void) { + fake_call(this, 30, rs as u64, 0); } - unsafe extern "system" fn fake_dispatch(this: *mut c_void, _x: u32, _y: u32, _z: u32) { - (*(this as *const FakeAdoptedList)).dispatch_calls.fetch_add(1, Ordering::Relaxed); + unsafe extern "system" fn fake_set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + fake_call(this, 35, i.into(), offset.into()); + let words = if data.is_null() { Vec::new() } else { std::slice::from_raw_parts(data, n as usize).to_vec() }; + fake_of(this).constants.lock().unwrap().push(words); } - unsafe extern "system" fn fake_set_pso(this: *mut c_void, _pso: *mut c_void) { - (*(this as *const FakeAdoptedList)).set_pso_calls.fetch_add(1, Ordering::Relaxed); + unsafe extern "system" fn fake_set_compute_root_srv(this: *mut c_void, i: u32, va: u64) { + fake_call(this, 39, i.into(), va); } - unsafe extern "system" fn fake_set_compute_rs(this: *mut c_void, _rs: *mut c_void) { - (*(this as *const FakeAdoptedList)).set_compute_rs_calls.fetch_add(1, Ordering::Relaxed); + unsafe extern "system" fn fake_set_compute_root_uav(this: *mut c_void, i: u32, va: u64) { + fake_call(this, 41, i.into(), va); } - unsafe extern "system" fn fake_set_compute_uav(this: *mut c_void, _slot: u32, _va: u64) { - (*(this as *const FakeAdoptedList)).set_compute_uav_calls.fetch_add(1, Ordering::Relaxed); + unsafe extern "system" fn fake_set_graphics_root_uav(this: *mut c_void, i: u32, va: u64) { + fake_call(this, 42, i.into(), va); } - unsafe extern "system" fn fake_execute_indirect( - this: *mut c_void, - _sig: usize, - _max: u32, - _args: usize, - _args_off: u64, - _count_buf: usize, - _count_off: u64, - ) { - (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + unsafe extern "system" fn fake_ia_set_index_buffer(this: *mut c_void, view: *const D3D12_INDEX_BUFFER_VIEW) { + let (va, bytes) = view.as_ref().map_or((0, 0), |v| (v.BufferLocation, v.SizeInBytes.into())); + fake_call(this, 43, va, bytes); } + unsafe extern "system" fn fake_execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count: usize, count_off: u64) { + fake_call(this, 59, sig as u64, args as u64); + fake_of(this).indirect.lock().unwrap().push((sig, max, args, args_off, count, count_off)); + } + + unsafe extern "system" fn fake_dispatch_mesh(this: *mut c_void, x: u32, y: u32, _z: u32) { + fake_call(this, 79, x.into(), y.into()); + } + + /// A compute pipeline built in the background takes the translated path once resolved; one + /// whose build failed has its Dispatch and its ExecuteIndirect skipped, named and counted at + /// their places (XCL_STANDIN_SKIP=0: its ExecuteIndirect goes to the PC, as before 0023); a + /// genuine PC pipeline's ExecuteIndirect goes to the PC with the title's root signature. #[test] fn async_compute_pso_success_and_failure_in_dispatch_and_execute_indirect() { - let mut orig_vt = [0usize; 64]; - orig_vt[1] = fake_add_ref as usize; - orig_vt[2] = fake_release as usize; - orig_vt[14] = fake_dispatch as usize; - orig_vt[25] = fake_set_pso as usize; - orig_vt[29] = fake_set_compute_rs as usize; - orig_vt[41] = fake_set_compute_uav as usize; - orig_vt[59] = fake_execute_indirect as usize; - - // Extended vtable laid out as `real::orig_fn` reads it, with the COM method pointers used - // via `ID3D12GraphicsCommandList`. - let (_ext_vt, ext) = crate::hle::d3d12x::real::test_ext_table(&orig_vt); - - let fake = Box::new(FakeAdoptedList { - vt: ext, - refs: AtomicUsize::new(1), - dispatch_calls: AtomicUsize::new(0), - set_compute_rs_calls: AtomicUsize::new(0), - set_compute_uav_calls: AtomicUsize::new(0), - set_pso_calls: AtomicUsize::new(0), - execute_indirect_calls: AtomicUsize::new(0), - }); - let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; + let fake = Fake::new(0); + let list_ptr = fake.ptr(); + // the title's graphics root signature (no layout noted: only `rs_gfx` is set), which the + // PC path binds + let rs_title = 0x7B00_02F5usize; + let reset_with_rs = |pso: usize| { + reset(list_ptr, 0x7200_0100, pso); + unsafe { set_graphics_root_signature(list_ptr, rs_title as *mut c_void) }; + }; // 1. Background compute build SUCCEEDS: real PSO R is registered in TRANSLATED_COMPUTE, // stand-in S is NOT. ExecuteIndirect resolves S -> R and treats it as translated. @@ -1859,50 +2620,74 @@ void main(uint t : SV_GroupIndex) { assert!(!real::is_translated_compute(standin_ok)); assert!(real::is_translated_compute(real_ok)); - reset(list_ptr, 0x7200_0100, standin_ok); + reset_with_rs(standin_ok); unsafe { // With `sig_root_changing`, a translated compute PSO rejects this unsupported signature // instead of falling through to `pc` (which happened when `R` wasn't registered). execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); } - assert_eq!( - fake.execute_indirect_calls.load(Ordering::Relaxed), - 0, - "ExecuteIndirect must recognize resolved async compute PSO R as translated" - ); + assert_eq!(fake.count(59), 0, "ExecuteIndirect must recognize resolved async compute PSO R as translated"); + assert_eq!(take_last_unbuilt(), None, "a built pipeline is not held back"); + assert_eq!(super::super::stall::ledger_indirect_for_test(list_ptr), [[0; 4]; 2], "a compute ExecuteIndirect not recorded is not counted"); // 2. Background compute build FAILS (returns 0): stand-in S_fail is NOT in // TRANSLATED_COMPUTE. Dispatch must skip cleanly without binding XCL's ABI RS/UAVs - // onto S_fail, and ExecuteIndirect must not enter bind_abi either. + // onto S_fail, and its ExecuteIndirect must not reach the PC either. let standin_fail = 0x7200_0003usize; pso_async::submit(standin_fail, true, Box::new(|| 0)); assert_eq!(pso_async::resolve_wait(standin_fail), standin_fail); assert!(!real::is_translated_compute(standin_fail)); - reset(list_ptr, 0x7200_0100, standin_fail); + reset_with_rs(standin_fail); let before = counts_snapshot(); unsafe { dispatch(list_ptr, 1, 1, 1); } let after = counts_snapshot(); assert_eq!(after[DISPATCHES], before[DISPATCHES]); - assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); - assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.dispatch_calls.load(Ordering::Relaxed), 0); + assert_eq!(after[DISPATCHES_SKIPPED], before[DISPATCHES_SKIPPED] + 1); + // no compute root signature, UAV, pipeline or Dispatch of XCL's ABI on the PC list + for slot in [29, 41, 25, 14] { + assert_eq!(fake.count(slot), 0, "PC slot {slot}"); + } + assert_eq!(take_last_unbuilt(), Some((standin_fail, U_DISPATCH, Unbuilt::Failed))); + assert_eq!(pso_async::take_last_skip(), Some(standin_fail), "a stand-in's skip is told to pso_async"); + let (calls, rs_calls, before) = (fake.count(59), fake.count(30), counts_snapshot()); unsafe { execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); } - assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); - assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); - assert_eq!( - fake.execute_indirect_calls.load(Ordering::Relaxed), - 1, - "failed async compute stand-in must not enter translated ExecuteIndirect path" - ); + let after = counts_snapshot(); + for slot in [29, 41, 25] { + assert_eq!(fake.count(slot), 0, "failed async compute stand-in must not enter translated ExecuteIndirect path (PC slot {slot})"); + } + if standin_skip_on() { + assert_eq!( + (fake.count(59) - calls, fake.count(30) - rs_calls), + (0, 0), + "a failed async compute stand-in's ExecuteIndirect must not reach the PC" + ); + assert_eq!(take_last_unbuilt(), Some((standin_fail, U_INDIRECT_COMPUTE, Unbuilt::Failed))); + assert_eq!(pso_async::take_last_skip(), Some(standin_fail)); + assert_eq!(after[DISPATCHES_SKIPPED], before[DISPATCHES_SKIPPED] + 1); + } else { + // XCL_STANDIN_SKIP=0: only a stand-in whose build is not over is held back, as before 0023 + assert_eq!((fake.count(59) - calls, fake.count(30) - rs_calls), (1, 1), "XCL_STANDIN_SKIP=0: 0022's PC call"); + assert_eq!(take_last_unbuilt(), None); + assert_eq!(pso_async::take_last_skip(), None); + } + + // 3. A genuine PC pipeline (no stand-in, no fallback): the PC call, after the title's + // root signature + reset_with_rs(0x7B00_0205); + let (calls, rs_calls) = (fake.count(59), fake.count(30)); + unsafe { + execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + } + assert_eq!((fake.count(59) - calls, fake.count(30) - rs_calls), (1, 1), "the title's own pipeline goes to the PC"); + assert_eq!(fake.last(30), Some((rs_title as u64, 0))); + assert_eq!(take_last_unbuilt(), None); + assert_eq!(pso_async::take_last_skip(), None); forget(list_ptr); indirect::forget(sig_root_changing); @@ -1911,6 +2696,656 @@ void main(uint t : SV_GroupIndex) { real::forget_pso_for_test(real_ok); } + /// DispatchMesh with a stand-in whose build failed, or with a pipeline of XCL's fallback + /// shaders, is skipped – named and counted at its place, a stand-in's skip told to pso_async + /// (XCL_STANDIN_SKIP=0: both go to the PC, as before 0023); a genuine PC mesh pipeline's goes + /// to the PC after the title's root signature. + #[test] + fn dispatch_mesh_with_a_stand_in_not_built_or_a_fallback_is_skipped() { + let fake = Fake::new(0); + let list = fake.ptr(); + let rs_title = 0x7B00_20F5usize; + let (failed, fallback, pc) = (0x7B00_2001usize, 0x7B00_2002usize, 0x7B00_20F1usize); + pso_async::submit(failed, false, Box::new(|| 0)); + assert_eq!(pso_async::resolve_wait(failed), failed); + real::register_fallback_for_test(fallback, false); + // one DispatchMesh with `pso` bound: the DispatchMesh and SetGraphicsRootSignature calls + // that reached the PC list, and what it added to this thread's counts + let mesh = |pso: usize| -> (usize, usize, [u64; 5]) { + reset(list, 0x7B00_2100, pso); + unsafe { set_graphics_root_signature(list, rs_title as *mut c_void) }; + let (calls, rs_calls, before) = (fake.count(79), fake.count(30), counts_snapshot()); + unsafe { dispatch_mesh(list, 2, 1, 1) }; + let after = counts_snapshot(); + (fake.count(79) - calls, fake.count(30) - rs_calls, std::array::from_fn(|k| after[k] - before[k])) + }; + let skip = standin_skip_on(); + for (pso, why) in [(failed, Unbuilt::Failed), (fallback, Unbuilt::Fallback)] { + let (calls, rs_calls, d) = mesh(pso); + if skip { + assert_eq!((calls, rs_calls), (0, 0), "{why:?}: skipped"); + assert_eq!(take_last_unbuilt(), Some((pso, U_DISPATCH_MESH, why))); + assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (1, 0), "{why:?}"); + } else { + assert_eq!((calls, rs_calls), (1, 1), "{why:?}: XCL_STANDIN_SKIP=0: 0022's PC call"); + assert_eq!(take_last_unbuilt(), None); + assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (0, 1), "{why:?}"); + } + assert_eq!( + pso_async::take_last_skip(), + (skip && why != Unbuilt::Fallback).then_some(pso), + "{why:?}: a stand-in's skip is told to pso_async, a fallback's is not" + ); + } + let (calls, rs_calls, d) = mesh(pc); + assert_eq!((calls, rs_calls), (1, 1), "the title's own mesh pipeline goes to the PC"); + assert_eq!(fake.last(30), Some((rs_title as u64, 0))); + assert_eq!(fake.last(79), Some((2, 1))); + assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (0, 1)); + assert_eq!(take_last_unbuilt(), None); + assert_eq!(pso_async::take_last_skip(), None); + + forget(list); + let _ = pso_async::released(failed); + real::forget_pso_for_test(fallback); + } + + /// A draw with a stand-in whose build failed, or with a pipeline of XCL's fallback shaders, is + /// skipped – named and counted at its place, not with the PC pipelines, a stand-in's skip told + /// to pso_async (XCL_STANDIN_SKIP_DRAWS=0: drawn, as before 0023); a genuine PC pipeline's draw + /// goes to the PC after the title's root signature. + #[test] + fn draws_with_a_stand_in_not_built_or_a_fallback_are_skipped() { + let fake = Fake::new(0); + let list = fake.ptr(); + let rs_title = 0x7B00_60F5usize; + let (failed, fallback, pc) = (0x7B00_6001usize, 0x7B00_6002usize, 0x7B00_60F1usize); + pso_async::submit(failed, false, Box::new(|| 0)); + assert_eq!(pso_async::resolve_wait(failed), failed); + real::register_fallback_for_test(fallback, false); + // one DrawInstanced with `pso` bound: the DrawInstanced and SetGraphicsRootSignature calls + // that reached the PC list, and what it added to this thread's counts (`draw_rects` and + // `sync_title_buffers` pass over a list list_x does not know) + let draw = |pso: usize| -> (usize, usize, [u64; 5]) { + reset(list, 0x7B00_6100, pso); + unsafe { set_graphics_root_signature(list, rs_title as *mut c_void) }; + let (calls, rs_calls, before) = (fake.count(12), fake.count(30), counts_snapshot()); + unsafe { draw_instanced(list, 3, 1, 0, 0) }; + let after = counts_snapshot(); + (fake.count(12) - calls, fake.count(30) - rs_calls, std::array::from_fn(|k| after[k] - before[k])) + }; + let skip = standin_skip_draws_on(); + for (pso, why) in [(failed, Unbuilt::Failed), (fallback, Unbuilt::Fallback)] { + let (calls, rs_calls, d) = draw(pso); + if skip { + assert_eq!((calls, rs_calls), (0, 0), "{why:?}: skipped"); + assert_eq!(take_last_unbuilt(), Some((pso, U_DRAW, why))); + assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (1, 0), "{why:?}: counted as skipped, not with the PC pipelines"); + } else { + assert_eq!((calls, rs_calls), (1, 1), "{why:?}: XCL_STANDIN_SKIP_DRAWS=0: drawn, as before 0023"); + assert_eq!(take_last_unbuilt(), None); + assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (0, 1), "{why:?}"); + } + assert_eq!( + pso_async::take_last_skip(), + (skip && why != Unbuilt::Fallback).then_some(pso), + "{why:?}: a stand-in's skip is told to pso_async, a fallback's is not" + ); + } + let (calls, rs_calls, d) = draw(pc); + assert_eq!((calls, rs_calls), (1, 1), "the title's own pipeline draws"); + assert_eq!(fake.last(30), Some((rs_title as u64, 0))); + assert_eq!(fake.last(12), Some((3, 1))); + assert_eq!((d[DRAWS_SKIPPED], d[DRAWS_PC]), (0, 1)); + assert_eq!(take_last_unbuilt(), None); + assert_eq!(pso_async::take_last_skip(), None); + + forget(list); + let _ = pso_async::released(failed); + real::forget_pso_for_test(fallback); + } + + /// A big compute pipeline no run built is late at its first bind (group A's big lane builds it, + /// binds do not wait): its ExecuteIndirect is skipped at once – named late, nothing on the PC + /// list – until it is built; then its real pipeline's goes on. + #[test] + fn execute_indirect_with_a_late_stand_in_is_skipped_until_it_is_built() { + let Some(_lanes) = pso_async::lane_tests::lanes() else { return }; + let fake = Fake::new(0); + let list = fake.ptr(); + let (s, built, key) = (0x7B00_3001usize, 0x7B00_3011usize, 0x7B00_3AAAu64); + // the build waits at a gate, 3 s at most: dropping `open` opens it (also when an assertion + // unwinds – the entry is then left: its job's result is no pipeline to release) + let (open, gate) = std::sync::mpsc::channel::<()>(); + let job: pso_async::Job = Box::new(move || { + let _ = gate.recv_timeout(std::time::Duration::from_secs(3)); + built + }); + pso_async::submit_program(s, true, job, true, key, pso_async::Program { hash: 0x7B00_3BBB, kind: b'C', dxil: 1 << 20, key, ..Default::default() }); + reset(list, 0x7B00_3100, s); + let t = std::time::Instant::now(); + unsafe { execute_indirect(list, 0x7B00_30F0, 1, 0, 0, 0, 0) }; + let waited = t.elapsed(); + assert!(waited < std::time::Duration::from_millis(500), "a late pipeline was waited for: {waited:?}"); + assert_eq!(fake.count(59), 0, "a late stand-in's ExecuteIndirect must not reach the PC"); + assert_eq!(take_last_unbuilt(), Some((s, U_INDIRECT_COMPUTE, Unbuilt::Late))); + assert_eq!(pso_async::take_last_skip(), Some(s), "a stand-in's skip is told to pso_async"); + assert!(pso_async::is_pending(s), "still being built"); + drop(open); + let t = std::time::Instant::now(); + while pso_async::is_pending(s) { + assert!(t.elapsed() < std::time::Duration::from_secs(10), "its build did not end"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + unsafe { execute_indirect(list, 0x7B00_30F0, 1, 0, 0, 0, 0) }; + assert_eq!(fake.count(59), 1, "built: its real pipeline (here not a translated one) goes to the PC"); + assert_eq!(take_last_unbuilt(), None); + forget(list); + let _ = pso_async::released(s); + } + + /// The adapter's device (None: the test says SKIPPED) and a DEFAULT buffer of `bytes` on it: + /// title memory outside unified memory as `indirect::classify` sees it (`Own`). + unsafe fn device_and_own_buffer(bytes: u64) -> Option<(ID3D12Device, ID3D12Resource)> { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + let dev = dev.unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() + }; + let mut own: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut own) + .expect("a DEFAULT buffer"); + Some((dev, own.unwrap())) + } + + /// `XCL_INDIRECT_OWN=skip`: an ExecuteIndirect of a translated pipeline – draws or compute – with + /// its arguments outside unified memory is not recorded (nothing on the PC list, counted as + /// skipped for the lever); without the lever never so. + #[test] + fn xcl_indirect_own_skip_keeps_arguments_outside_unified_memory_off_the_gpu() { + use super::super::stall::Args; + unsafe { + let Some((_dev, own)) = device_and_own_buffer(256) else { return }; + let fake = Fake::new(0); + let list = fake.ptr(); + let (draws, computes) = (0x7B00_4001usize, 0x7B00_4002usize); + real::register_translated_graphics_for_test(draws); + real::register_translated_compute_for_test(computes); + for (pso, gfx) in [(draws, true), (computes, false)] { + reset(list, 0x7B00_4100, pso); + let (calls, rs_calls, before) = (fake.count(59), fake.count(30), counts_snapshot()); + // (an unregistered signature: no repacker, no check) + execute_indirect(list, 0x7B00_40F0, 1, own.as_raw() as usize, 0, 0, 0); + let after = counts_snapshot(); + let census = indirect::take_last_census(); + if indirect::own_skip() { + assert_eq!(census, indirect::census_on().then_some((gfx, Args::Own, indirect::Fate::SkippedOwn)), "gfx {gfx}"); + assert_eq!((fake.count(59) - calls, fake.count(30) - rs_calls), (0, 0), "gfx {gfx}: not recorded"); + let skipped = if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }; + assert_eq!(after[skipped] - before[skipped], 1, "gfx {gfx}: counted as skipped"); + } else if let Some(c) = census { + // (`bind_abi` fails in a test process: unified memory is not open on the GPU) + assert!(matches!(c, (g, Args::Own, indirect::Fate::AsIs | indirect::Fate::Failed) if g == gfx), "gfx {gfx}: {c:?}"); + } + } + forget(list); + real::forget_pso_for_test(draws); + real::forget_pso_for_test(computes); + } + } + + /// Indirect draws are counted by where their arguments are past the 32 `[indirect]` lines (the + /// census classifies every one), and those whose signature the check does not read are counted + /// as such; with XCL_INDIRECT_CENSUS=0 neither count moves. + #[test] + fn indirect_draws_are_counted_by_place_past_the_log_cap() { + use super::super::stall::Args; + unsafe { + let Some((_dev, own)) = device_and_own_buffer(256) else { return }; + let fake = Fake::new(0); + let list = fake.ptr(); + let psos: Vec = (0..40).map(|k| 0x7B00_5000 + 0x10 * k).collect(); + for &p in &psos { + real::register_translated_graphics_for_test(p); + } + let counted = || (indirect::census_of(true, Args::Own), indirect::census_snapshot().unread); + let (own_before, unread_before) = counted(); + for &p in &psos { + reset(list, 0x7B00_5F00, p); + // (an unregistered signature: one the check does not read) + execute_indirect(list, 0x7B00_5FF0, 1, own.as_raw() as usize, 0, 0, 0); + } + let (own_after, unread_after) = counted(); + if indirect::census_on() { + assert!(own_after - own_before >= 40, "40 draws outside unified memory counted: {}", own_after - own_before); + if indirect::draw_check_on() && !indirect::own_skip() { + assert!(unread_after - unread_before >= 40, "40 draws with a signature the check does not read: {}", unread_after - unread_before); + } + } else { + assert_eq!((own_after, unread_after), (own_before, unread_before), "XCL_INDIRECT_CENSUS=0: nothing counted"); + } + forget(list); + for p in psos { + real::forget_pso_for_test(p); + } + } + } + + /// The sequence run 65 records for a translated draw's ExecuteIndirect with its arguments + /// outside unified memory: XCL's check (a compute pass) first, then the draw's own root + /// signature, root UAVs and pipeline, then the ExecuteIndirect of XCL's checked commands with + /// XCL's signature, and list_x's key back on the title's pipeline; an indexed draw's check knows + /// the indices bound; a bundle's is not checked (barriers are not allowed there). + #[test] + fn a_checked_indirect_draw_records_the_check_then_the_draws_own_state() { + use super::super::stall::Args; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT; + if !crate::util::mac_host() { + return; + } + unsafe { + let Some((dev, own)) = device_and_own_buffer(256) else { return }; + if crate::gpu::recomp::dxc::create_instance().is_none() { + return crate::gpu::recomp::runner::skip_test("no DXC"); + } + let fake = Fake::new(dev.as_raw() as usize); + let list = fake.ptr(); + let (pso, rs, allocator) = (0x7B00_7001usize, 0x7B00_70F5usize, 0x7B00_7100usize); + let (sig, sig_indexed) = (0x7B00_70A0usize, 0x7B00_70A1usize); + let own_raw = own.as_raw() as usize; + real::register_translated_graphics_for_test(pso); + real::set_pso_root_signature_for_test(pso, rs); + // (open windows, which only XCL's device creation opens) + let _windows = real::window_vas_for_test(vec![0x7B00_7000_0000; 4]); + reset(list, allocator, pso); + indirect::note_plain_draw(sig, 16, false); + indirect::note_plain_draw(sig_indexed, 20, true); + // list_x's key moved off the title's pipeline, as XCL's own SetPipelineState calls move it + list_x::on_set_pipeline_state(list, 0x7B00_70EE); + let checks = indirect::draw_check_on(); + let census = |fate: indirect::Fate| indirect::census_on().then_some((true, Args::Own, fate)); + + // 1. a DRAW + execute_indirect(list, sig, 1, own_raw, 0, 0, 0); + let calls = std::mem::take(&mut *fake.list.calls.lock().unwrap()); + let ei = calls.iter().position(|c| c.0 == 59).expect("an ExecuteIndirect"); + let (got_sig, max, got_args, _, count, _) = *fake.list.indirect.lock().unwrap().last().unwrap(); + if checks { + let dispatch = calls.iter().position(|c| c.0 == 14).expect("the check's Dispatch"); + assert!(calls[dispatch..ei].iter().any(|c| c.0 == 30 && c.1 == rs as u64), "the draw's root signature after the check: {calls:x?}"); + let last_pso = calls[..ei].iter().rev().find(|c| c.0 == 25).map(|c| c.1 as usize); + assert_eq!(last_pso, Some(pso), "the draw's pipeline the last one set before its ExecuteIndirect"); + assert!(got_sig != sig && got_args != own_raw, "XCL's signature and checked commands, not the title's"); + assert_eq!((max, count), (1, 0), "max 1, no count buffer"); + assert_eq!(indirect::take_last_census(), census(indirect::Fate::Checked)); + assert_eq!(list_x::bound_pso_for_test(list), pso, "list_x's key back on the title's pipeline"); + } else { + assert!(!calls.iter().any(|c| c.0 == 14), "XCL_INDIRECT_SANITIZE_DRAWS=0: no check"); + assert_eq!((got_sig, got_args), (sig, own_raw), "the title's signature and arguments"); + assert_eq!(indirect::take_last_census(), census(indirect::Fate::AsIs)); + } + // counted for its list as recorded: it runs with each submission of the list + if super::super::stall::indirect_on() { + assert_eq!(super::super::stall::ledger_indirect_for_test(list)[1][Args::Own.index()], 1, "the draw counted for its list, by where its arguments are"); + } + + // 2. a DRAW_INDEXED with 32 indices bound (an address reserved, never committed: not + // readable, so never mirrored into unified memory) + let reserved = windows_sys::Win32::System::Memory::VirtualAlloc(std::ptr::null(), 0x1_0000, windows_sys::Win32::System::Memory::MEM_RESERVE, windows_sys::Win32::System::Memory::PAGE_NOACCESS); + assert!(!reserved.is_null(), "reserve the index buffer's address"); + let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: reserved as u64, SizeInBytes: 64, Format: DXGI_FORMAT_R16_UINT }; + list_x::ia_set_index_buffer_x(list, &view); + fake.list.constants.lock().unwrap().clear(); + execute_indirect(list, sig_indexed, 1, own_raw, 0, 0, 0); + if checks { + let words = fake.list.constants.lock().unwrap().last().cloned().expect("the check's root constants"); + assert_eq!(words.len(), 8); + assert_eq!(words[6], if indirect::draw_indices_on() { 32 } else { u32::MAX }, "the indices the check bounds the range by"); + assert_eq!(indirect::take_last_census(), census(indirect::Fate::Checked)); + } + + // 3. a bundle: no check, the title's signature and arguments + fake.list.ty.store(D3D12_COMMAND_LIST_TYPE_BUNDLE.0, Ordering::Relaxed); + fake.list.calls.lock().unwrap().clear(); + execute_indirect(list, sig, 1, own_raw, 0, 0, 0); + assert_eq!(fake.count(14), 0, "no check in a bundle"); + let (got_sig, _, got_args, ..) = *fake.list.indirect.lock().unwrap().last().unwrap(); + assert_eq!((got_sig, got_args), (sig, own_raw), "a bundle's: the title's signature and arguments"); + assert_eq!(indirect::take_last_census(), census(indirect::Fate::AsIs)); + + real::forget_pso_for_test(pso); + indirect::forget(sig); + indirect::forget(sig_indexed); + // (XCL's checked commands were never run: the chunk is still in its UAV state) + indirect::allocator_reset(allocator); + forget(list); + console_list::allocator_reset(allocator as *mut c_void); + list_x::on_release(list as usize); + windows_sys::Win32::System::Memory::VirtualFree(reserved, 0, windows_sys::Win32::System::Memory::MEM_RELEASE); + } + } + + /// A draw ExecuteIndirect that records nothing (here: an unsupported root-changing signature) + /// is not counted for its list – only what entered a list runs with its submissions. + #[test] + fn a_failed_draw_execute_indirect_is_not_counted_for_its_list() { + let fake = Fake::new(0); + let list = fake.ptr(); + let (pso, sig) = (0x7D0D_5000usize, 0x7D0D_50F0usize); + real::register_translated_graphics_for_test(pso); + indirect::register(sig, 0, &[]); + note_root_changing_signature(sig); + reset(list, 0x7D0D_5100, pso); + // (a Mac: an Err in the tail; elsewhere the root-changing skip) + unsafe { execute_indirect(list, sig, 1, 0, 0, 0, 0) }; + assert_eq!(fake.count(59), 0, "nothing reached the PC"); + assert_eq!(super::super::stall::ledger_indirect_for_test(list), [[0; 4]; 2], "a draw ExecuteIndirect not recorded is not counted for its list"); + forget(list); + indirect::forget(sig); + real::forget_pso_for_test(pso); + } + + /// A root signature of 3 parameters: 4 constants, a root UAV and a descriptor table (RTS0 v2). + fn three_param_blob() -> Vec { + let words: [u32; 18] = [ + 2, 3, 24, 0, 0, 0, // version 2, 3 parameters at 24, no static samplers + 1, 0, 60, // constants, their payload at 60 + 4, 0, 0, // a root UAV + 0, 0, 0, // a descriptor table + 0, 0, 4, // register 0, space 0, 4 values + ]; + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + /// A program XCL_SKIP_CS skips has its root views logged at its first 2 skips, as run 65 reads + /// them (`skip_roots`): the call (Dispatch, DispatchX with its flags, ExecuteIndirect), the list, + /// its threads and root parameters; its constants; its root descriptor and its table's slots, + /// each with where its memory is and who wrote it – an empty V# of XCL's with the memory it + /// would have named –, the CPU's bytes outside unified memory; every line under 480 bytes + /// starting with the program's hash. Nothing reaches the PC. XCL_SKIP_CS_ROOTS=0: no line. + #[test] + fn a_skipped_program_logs_the_root_views_it_names() { + use super::super::{console_heap, skip_roots, stall}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + let _census = super::super::outside::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(u) = crate::gpu::uma::get() else { return }; + let fake = Fake::new(0); + let list = fake.ptr(); + let (pso, pso2, rs) = (0x7F0F_1001usize, 0x7F0F_1002usize, 0x7F0F_10F5usize); + let (hash, hash2) = (0x7F0F_0000_0000_1001u64, 0x7F0F_0000_0000_1002u64); + let _skip = stall::skip_for_test(&[hash, hash2]); + let _roots = skip_roots::budget_for_test(&[hash, hash2], 2, 16); + for (p, h) in [(pso, hash), (pso2, hash2)] { + real::register_translated_compute_for_test(p); + real::register_console_cs_for_test(p, h, 64); + } + console_list::note_root_signature(rs, &three_param_blob()); + // GPU-visible title memory outside unified memory, committed: 0x2a 1 1 0 at +0x100 + let mem = unsafe { VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) } as usize; + assert_ne!(mem, 0); + crate::hle::kernelx::note_plain_gpu_for_test(mem, 0x1_0000); + for (k, v) in [0x2au32, 1, 1, 0].into_iter().enumerate() { + unsafe { ((mem + 0x100) as *mut u32).add(k).write(v) }; + } + // a heap of XCL's: slot 0 XCL's empty V# of that memory, slot 1 the title's own V# of it, + // the rest zeros + let obj = 0x7F0F_1E00usize; + assert!(console_heap::register(obj, 8, 0x7F0F_2000, 0, 32, false, false, true)); + let v = console_heap::start(obj).unwrap() as usize; + unsafe { std::ptr::write_bytes(v as *mut u8, 0, 8 * 32) }; + console_heap::write_view(&console_heap::slot(v as u64).unwrap(), &[0; 4], "buffer SRV", || Some((mem + 0x100, 4096))); + let title_v = crate::gpu::desc::buffer_words((mem + 0x200) as u64, 0, 64, 22); + unsafe { std::ptr::copy_nonoverlapping(title_v.as_ptr(), (v + 32) as *mut u32, 4) }; + let bind_roots = |pso: usize| unsafe { + reset(list, 0x7F0F_1100, pso); + set_compute_root_signature(list, rs as *mut c_void); + let consts = [1u32, 2, 3, 4]; + set_compute_root_constants(list, 0, 4, consts.as_ptr(), 0); + set_compute_root_descriptor(list, 1, (mem + 0x100) as u64); + set_compute_root_table(list, 2, v as u64); + }; + bind_roots(pso); + let before = counts_snapshot(); + unsafe { dispatch(list, 3, 2, 1) }; + let first = skip_roots::take_lines_for_test(); + unsafe { dispatch_x(list, 4, 1, 1, 0x20) }; + let second = skip_roots::take_lines_for_test(); + unsafe { dispatch(list, 1, 1, 1) }; + let third = skip_roots::take_lines_for_test(); + bind_roots(pso2); + unsafe { execute_indirect(list, 0x7F0F_10A0, 1, 0, 0, 0, 0) }; + let indirect = skip_roots::take_lines_for_test(); + let after = counts_snapshot(); + for slot in [14, 25, 29, 41, 59] { + assert_eq!(fake.count(slot), 0, "PC slot {slot}: a skipped program records nothing"); + } + assert_eq!(after[DISPATCHES_SKIPPED] - before[DISPATCHES_SKIPPED], 4); + forget(list); + console_heap::unregister(obj); + crate::hle::kernelx::forget_plain_gpu_for_test(mem); + unsafe { VirtualFree(mem as *mut c_void, 0, MEM_RELEASE) }; + real::forget_pso_for_test(pso); + real::forget_pso_for_test(pso2); + // (XCL_SKIP_CS_ROOTS as this process was started with: 0 turns the root views off) + let roots_off = std::env::var("XCL_SKIP_CS_ROOTS").is_ok_and(|v| v.trim() == "0"); + assert_eq!(skip_roots::switch_for_test(), !roots_off, "XCL_SKIP_CS_ROOTS=0: off, else on"); + if !skip_roots::switch_for_test() { + assert_eq!((first, second, third, indirect), (vec![], vec![], vec![], vec![]), "XCL_SKIP_CS_ROOTS=0: no line"); + return; + } + let prefix = format!("D3D12.X: XCL_SKIP_CS: {hash:016x} "); + for l in first.iter().chain(&second).chain(&third) { + assert!(l.starts_with(&prefix) && l.len() < 480, "{} bytes: {l}", l.len()); + } + let all = first.join("\n"); + let plain = format!("outside unified memory: in GPU-visible title memory at {mem:#x} of 64 KB (a test, flags 0x0, protection 0x0)"); + // (memory below 4 GiB: what translated programs read there – `skip_roots::low_note`) + let low = if mem < 1 << 32 { "below 4 GiB: translated programs read window 0's bytes there and write nowhere; " } else { "" }; + let t = v - u.base(); + for want in [ + format!("{prefix}root views at its skip #1 (#1 logged in the process): Dispatch 3×2×1 on list {:#x}, 64 threads; 3 root parameters (1 constants, 1 root descriptors, 1 tables)", list as usize), + format!("{prefix}p0: 4 constants [0x1, 0x2, 0x3, 0x4]"), + format!("{prefix}p1: root descriptor {:#x}: {plain}; the title's (its root argument); {low}on the CPU: 0000002a 00000001 00000001 00000000 (dwords)", mem + 0x100), + format!("{prefix}p2: table {t:#x}: slots of heap {obj:#x} from #0 (XCL's memory, shader visible); empty, no view of XCL's made there (zeros of the title's, or its copy of an empty V#): [2, 3, 4, 5, 6, 7]"), + format!( + "{prefix}p2[0]: empty V# (XCL's buffer SRV named {:#x}, 4096 bytes, or a copy of an empty V# over it: the same bytes); {plain}; XCL's buffer SRV or a copy of an empty V# over it (the same bytes); {low}on the CPU: 0000002a 00000001 00000001 00000000 (dwords)", + mem + 0x100 + ), + format!("{prefix}p2[1]: V# {:#x}, 64 bytes (stride 0, 64 records, format 22); {plain}; the title's bytes (no view of XCL's made in this slot: its own descriptor or a copy); {low}on the CPU: 00000000 00000000 00000000 00000000 (dwords)", mem + 0x200), + ] { + assert!(first.contains(&want), "missing:\n{want}\nin:\n{all}"); + } + assert_eq!(first.len(), 6, "{all}"); + assert!(second[0].starts_with(&format!("{prefix}root views at its skip #2 (#2 logged in the process): DispatchX 4×1×1 (flags 0x20) on list ")), "{second:?}"); + assert_eq!(&second[1..], &first[1..], "the same views at its second skip"); + assert_eq!(third, Vec::::new(), "a program's third skip: no line"); + assert!( + indirect[0].starts_with(&format!("D3D12.X: XCL_SKIP_CS: {hash2:016x} root views at its skip #1 (#3 logged in the process): ExecuteIndirect of up to 1 command(s) with signature 0x7f0f10a0: arguments unknown on list ")), + "{indirect:?}" + ); + assert_eq!(indirect.len(), 6, "{indirect:?}"); + } + + /// A program XCL_SKIP_CS lists whose stand-in is not built – late at its bind (a Dispatch), or + /// failed (an ExecuteIndirect) – has its root views logged at its skip all the same, the head + /// saying its work is skipped as unbuilt; the work stays skipped, nothing reaches the PC (F-6). + /// Pipelines and hashes 0x7A0C_90xx. + #[test] + fn a_listed_program_not_built_yet_logs_its_root_views_at_its_skip() { + use super::super::{skip_roots, stall}; + let fake = Fake::new(0); + let list = fake.ptr(); + let (late, failed) = (0x7A0C_9001usize, 0x7A0C_9002usize); + let (h_late, h_failed) = (0x7A0C_0000_0000_9001u64, 0x7A0C_0000_0000_9002u64); + let _skip = stall::skip_for_test(&[h_late, h_failed]); + let _roots = skip_roots::budget_for_test(&[h_late, h_failed], 2, 16); + let prog = |h: u64| pso_async::Program { hash: h, kind: b'C', dxil: 16 << 10, ..Default::default() }; + // late: a lazy one past its wait, never sent (its job never runs); failed: refused when made + pso_async::submit_program(late, true, Box::new(|| 0), true, 0, prog(h_late)); + pso_async::make_late_for_test(late); + pso_async::submit_refused(failed, true, 0, prog(h_failed)); + reset(list, 0x7A0C_9100, late); + unsafe { dispatch(list, 3, 2, 1) }; + let dispatched = skip_roots::take_lines_for_test(); + let skipped_late = take_last_unbuilt(); + reset(list, 0x7A0C_9100, failed); + unsafe { execute_indirect(list, 0x7A0C_90A0, 1, 0, 0, 0, 0) }; + let indirect = skip_roots::take_lines_for_test(); + let skipped_failed = take_last_unbuilt(); + let pc = (fake.count(14), fake.count(59)); + forget(list); + let _ = pso_async::released(late); + let _ = pso_async::released(failed); + assert_eq!(pc, (0, 0), "work of a pipeline not built never reaches the PC"); + assert_eq!(skipped_late, Some((late, U_DISPATCH, Unbuilt::Late)), "the Dispatch skipped as unbuilt"); + assert_eq!(skipped_failed, Some((failed, U_INDIRECT_COMPUTE, Unbuilt::Failed)), "the ExecuteIndirect skipped as unbuilt"); + if !skip_roots::switch_for_test() { + assert_eq!((dispatched, indirect), (vec![], vec![]), "XCL_SKIP_CS_ROOTS=0: no line"); + return; + } + let head = format!( + "D3D12.X: XCL_SKIP_CS: {h_late:016x} root views at its skip #1 (#1 logged in the process): Dispatch 3×2×1 on list {:#x}, its pipeline not built yet – its work skipped as unbuilt ({})", + list as usize, + Unbuilt::Late.describe() + ); + assert!(dispatched.first().is_some_and(|l| l.starts_with(&head)), "missing:\n{head}\nin:\n{dispatched:?}"); + let head = format!("D3D12.X: XCL_SKIP_CS: {h_failed:016x} root views at its skip #1 (#2 logged in the process): ExecuteIndirect of up to 1 command(s) with signature 0x7a0c90a0: arguments unknown on list {:#x}, its pipeline not built yet", list as usize); + assert!(indirect.first().is_some_and(|l| l.starts_with(&head) && l.contains(Unbuilt::Failed.describe())), "missing:\n{head}\nin:\n{indirect:?}"); + } + + /// The world's first frame (`XCL_FRAME_DUMP_WORLD`) is marked by the first skipped dispatch of a + /// program XCL_SKIP_CS lists – one not built yet (`skipped_unbuilt_roots`, with no root views to + /// log) or a built one (`skip_cs`) –, the first kept; the title's DeserializePipelineStateX before + /// it (GTA VI's first: ~4.6 s into its loading) and the skip of a program not listed are no + /// mark. Nothing reaches the PC. On a world mark of this thread's own. Pipelines and hashes + /// 0x7A1E_70xx. + #[test] + fn the_first_skip_of_a_listed_program_marks_the_worlds_first_frame() { + use super::super::{device_x, present, stall}; + let fake = Fake::new(0); + let list = fake.ptr(); + let (late, other, built) = (0x7A1E_7001usize, 0x7A1E_7003usize, 0x7A1E_7002usize); + let (h_late, h_other, h_built) = (0x7A1E_0000_0000_7001u64, 0x7A1E_0000_0000_7003u64, 0x7A1E_0000_0000_7002u64); + let _skip = stall::skip_for_test(&[h_late, h_built]); + let prog = |h: u64| pso_async::Program { hash: h, kind: b'C', dxil: 16 << 10, ..Default::default() }; + // not built yet: lazy ones past their wait, never sent (their jobs never run) + for (p, h) in [(late, h_late), (other, h_other)] { + pso_async::submit_program(p, true, Box::new(|| 0), true, 0, prog(h)); + pso_async::make_late_for_test(p); + } + real::register_translated_compute_for_test(built); + real::register_console_cs_for_test(built, h_built, 64); + let dispatch_of = |pso: usize| unsafe { + reset(list, 0x7A1E_7100, pso); + dispatch(list, 2, 1, 1); + }; + // a Deserialize call and the skip of a program not listed first: no mark; then the one not + // built yet, then a built one + let world = present::world_mark_for_test(); + let mut out = std::ptr::null_mut(); + let _ = unsafe { device_x::deserialize_pso_x(std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), &mut out) }; + dispatch_of(other); + let before_any = (present::test_world_mark(), present::world_mark_open()); + let p0 = present::presents(); + dispatch_of(late); + let p1 = present::presents(); + let by_late = present::test_world_mark(); + dispatch_of(built); + let kept = (present::test_world_mark(), present::world_mark_open()); + drop(world); + // a built one's skip first + let world = present::world_mark_for_test(); + dispatch_of(built); + dispatch_of(late); + let by_built = present::test_world_mark(); + drop(world); + let skipped_late = take_last_unbuilt(); + let pc = (fake.count(14), fake.count(25)); + forget(list); + let _ = pso_async::released(late); + let _ = pso_async::released(other); + real::forget_pso_for_test(built); + assert_eq!(before_any, (None, true), "a DeserializePipelineStateX call and the skip of a program not listed are no mark"); + let (at, hash) = by_late.expect("the skip of a listed program not built yet marks the world"); + assert!(hash == h_late && at >= p0 && at <= p1, "{by_late:?} ({p0}-{p1})"); + assert_eq!(kept, (by_late, false), "a later skip leaves the first mark"); + assert_eq!(by_built.map(|m| m.1), Some(h_built), "a built one's skip (skip_cs) marks it"); + assert_eq!(skipped_late, Some((late, U_DISPATCH, Unbuilt::Late)), "the one not built yet skipped as unbuilt, as before"); + assert_eq!(pc, (0, 0), "nothing reaches the PC"); + } + + /// DispatchX's flags are named once per value – never 0, 16 values at most – with the program + /// and the counts as given (`D3D12.X: DispatchX flags …: not applied`); the DispatchX goes on as + /// a Dispatch of those counts. + #[test] + fn dispatch_x_flags_are_named_once_per_value_and_never_for_zero() { + let seen = FirstValues::new(); + assert!(!seen.first(0), "0: no flags"); + assert!(seen.first(0x20)); + assert!(!seen.first(0x20), "once per value"); + assert!(seen.first(0x40)); + for v in 1..=14u32 { + assert!(seen.first(0x1000 + v), "{v}"); + } + assert!(!seen.first(0x2000), "16 values at most"); + assert!(!seen.first(0x40)); + assert_eq!(dispatch_x_flags_line(0x20, 0x71f4_ac8a_d5eb_a33c, [64, 1, 1]), "D3D12.X: DispatchX flags 0x20 (71f4ac8ad5eba33c, counts 64×1×1): not applied"); + // through DispatchX (#78): once per value, the counts as given; each DispatchX a Dispatch + let fake = Fake::new(0); + let list = fake.ptr(); + let (pso, hash) = (0x7F0F_6001usize, 0x7F0F_0000_0000_6001u64); + // (skipped: a test process has no unified memory open on the GPU to bind) + let _skip = super::super::stall::skip_for_test(&[hash]); + real::register_translated_compute_for_test(pso); + real::register_console_cs_for_test(pso, hash, 64); + reset(list, 0x7F0F_6100, pso); + // (a value no other test gives) + let flags = 0x7F0F_0020; + let before = counts_snapshot(); + unsafe { + list_x::dispatch_x(list, 5, 6, 7, flags); + list_x::dispatch_x(list, 8, 9, 10, flags); + list_x::dispatch_x(list, 1, 1, 1, 0); + } + let lines = FLAGS_LINES.with(|l| std::mem::take(&mut *l.borrow_mut())); + let after = counts_snapshot(); + forget(list); + real::forget_pso_for_test(pso); + assert_eq!(lines, vec![dispatch_x_flags_line(flags, hash, [5, 6, 7])]); + assert_eq!(after[DISPATCHES_SKIPPED] - before[DISPATCHES_SKIPPED], 3, "each DispatchX went on as a Dispatch"); + assert_eq!(fake.count(14), 0); + } + + /// The `ExecuteIndirect recorded so far` line, as run 65's tools read it: each kind, place and + /// fate in its place, the draws checked in the last 2 s, the work skipped for pipelines not built. + #[test] + fn the_indirect_line_names_each_kind_place_and_fate() { + use super::super::stall::Args; + use indirect::Fate; + let (window, own, unknown) = (Args::Window(0).index(), Args::Own.index(), Args::Unknown.index()); + let mut c = indirect::CensusSnapshot::default(); + c.n[0][window][Fate::Checked as usize] = 8; + c.n[0][own][Fate::Checked as usize] = 113; + c.counted[0] = [2, 1]; + c.n[1][window][Fate::AsIs as usize] = 6; + c.n[1][own][Fate::Checked as usize] = 20; + c.n[1][own][Fate::AsIs as usize] = 3; + c.n[1][own][Fate::Failed as usize] = 3; + c.n[1][unknown][Fate::Failed as usize] = 1; + c.unread = 4; + assert_eq!( + indirect_line_text(&c.text(7), &[5, 3, 0, 0, 40]), + "ExecuteIndirect recorded so far: compute 121 (unified memory 8, upload 0, outside unified memory 113, unknown 0; checked 121, as they were 0, skipped for XCL_INDIRECT_OWN 0, not recorded 0; 2 with a count buffer, 1 of those outside unified memory), draws 33 (unified memory 6, upload 0, outside unified memory 26, unknown 1; checked 20, as they were 9, skipped for XCL_INDIRECT_OWN 0, not recorded 4; 0 with a count buffer, 0 of those outside unified memory; 4 with a signature the check does not read), 7 draws checked in the last 2 s; work skipped for a pipeline not built: 5 Dispatch, 3 compute and 0 draw ExecuteIndirect, 0 DispatchMesh, 40 draws" + ); + } + #[test] fn create_list_reset_and_clear_state_track_initial_pso_on_d3d12() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; diff --git a/crates/xcl/src/hle/d3d12x/compose.rs b/crates/xcl/src/hle/d3d12x/compose.rs new file mode 100644 index 0000000..f35ad55 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/compose.rs @@ -0,0 +1,278 @@ +//! The console's display planes, composed for the XCL window. +//! +//! A title may present more than one plane in a PresentX: GTA VI as a Series S shows its 3D +//! image at 1920×1080 in plane 0 and its interface at 3840×2160 in plane 1, both over the whole +//! screen. The console's display composes them – each plane's source rectangle scaled to its +//! place on the screen, each over the ones before it with its alpha (premultiplied, as the +//! display planes are). One full-screen triangle does the same into the XCL window's back +//! buffer: the planes are sampled with a linear filter (a 1080p plane under a 2160p one is +//! scaled up as the display scaler would), composed over black, and written opaque. + +use std::ffi::c_void; +use std::mem::transmute_copy; + +use windows::core::Interface; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::*; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// Planes one composition takes (a console shows two title planes; more are not drawn). +pub const MAX_PLANES: usize = 4; + +/// Root constants: four source rects, four destinations (float4 each), the plane count. +const CONSTANT_WORDS: u32 = 4 * MAX_PLANES as u32 * 2 + 1; + +const HLSL: &str = r#" +Texture2D plane0 : register(t0); +Texture2D plane1 : register(t1); +Texture2D plane2 : register(t2); +Texture2D plane3 : register(t3); +SamplerState linear_clamp : register(s0); + +cbuffer Planes : register(b0) { + float4 src[4]; // the part of each plane shown, 0..1 of its texels: left, top, right, bottom + float4 dst[4]; // where on the screen, 0..1: left, top, right, bottom + uint count; +}; + +struct V { + float4 pos : SV_Position; + float2 uv : TEXCOORD0; +}; + +V vs_main(uint id : SV_VertexID) { + V o; + float2 uv = float2((id << 1) & 2, id & 2); + o.pos = float4(uv * float2(2, -2) + float2(-1, 1), 0, 1); + o.uv = uv; + return o; +} + +float4 layer(Texture2D t, float4 s, float4 d, float2 uv) { + if (uv.x < d.x || uv.y < d.y || uv.x >= d.z || uv.y >= d.w) { + return 0; + } + float2 f = (uv - d.xy) / max(d.zw - d.xy, 1e-6); + return t.SampleLevel(linear_clamp, lerp(s.xy, s.zw, f), 0); +} + +// premultiplied alpha: the plane over what is under it +float4 over(float4 top, float4 under) { + return top + (1 - top.a) * under; +} + +float4 ps_main(V v) : SV_Target { + float4 c = float4(0, 0, 0, 1); + c = over(layer(plane0, src[0], dst[0], v.uv), c); + if (count > 1) { c = over(layer(plane1, src[1], dst[1], v.uv), c); } + if (count > 2) { c = over(layer(plane2, src[2], dst[2], v.uv), c); } + if (count > 3) { c = over(layer(plane3, src[3], dst[3], v.uv), c); } + return float4(c.rgb, 1); +} +"#; + +/// One plane of a present: its resource, the part of it shown (texels: left, top, right, +/// bottom) and where on the screen (0..1: left, top, right, bottom). +pub struct Plane { + pub res: ID3D12Resource, + pub src: [f32; 4], + pub dst: [f32; 4], +} + +/// The pipeline that composes planes into a back buffer of one format. +pub struct Composer { + dev: usize, + fmt: DXGI_FORMAT, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// SRVs of the planes (shader visible; rewritten for each present – the presenter waits for + /// the previous one first) + srvs: ID3D12DescriptorHeap, + rtvs: ID3D12DescriptorHeap, + inc: usize, +} + +// D3D12 objects are free-threaded +unsafe impl Send for Composer {} + +/// The format a plane is read with: its typeless and sRGB forms as their UNORM one (the bytes +/// go to the window as they are, as a copy would take them). +fn view_format(f: DXGI_FORMAT) -> DXGI_FORMAT { + super::present::swap_format(f).unwrap_or(f) +} + +impl Composer { + /// The composer for back buffers of format `fmt` on `dev`. + pub unsafe fn new(dev: &ID3D12Device, fmt: DXGI_FORMAT) -> Result { + let vs = crate::gpu::recomp::dxc::compile(HLSL, "vs_main", "vs_6_0", &[])?; + let ps = crate::gpu::recomp::dxc::compile(HLSL, "ps_main", "ps_6_0", &[])?; + let range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: MAX_PLANES as u32, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &range } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: CONSTANT_WORDS } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + }, + ]; + let sampler = D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MipLODBias: 0.0, + MaxAnisotropy: 1, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + BorderColor: D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, + MinLOD: 0.0, + MaxLOD: f32::MAX, + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + }; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: 1, + pStaticSamplers: &sampler, + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).map_err(|e| format!("serialize the plane composer's root signature: {e}"))?; + let blob = blob.ok_or("no root signature blob for the plane composer")?; + let root: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize())) + .map_err(|e| format!("create the plane composer's root signature: {e}"))?; + let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&root), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + 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] = fmt; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|e| format!("create the plane composer's pipeline: {e}"))?; + let srvs: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: MAX_PLANES as u32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .map_err(|e| format!("the plane composer's SRV heap: {e}"))?; + let rtvs: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }) + .map_err(|e| format!("the plane composer's RTV heap: {e}"))?; + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + Ok(Composer { dev: dev.as_raw() as usize, fmt, root, pso, srvs, rtvs, inc }) + } + + /// Made for back buffers of `fmt` on `dev`. + pub fn fits(&self, dev: &ID3D12Device, fmt: DXGI_FORMAT) -> bool { + self.dev == dev.as_raw() as usize && self.fmt == fmt + } + + /// Records into `list` the composition of `planes` (bottom first) into `target` (`w`×`h`, + /// in the RENDER_TARGET state). The planes are read from the COMMON state the console's + /// PresentX leaves them in (implicitly promoted, as the single plane's copy is). + pub unsafe fn record(&self, dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, target: &ID3D12Resource, w: u32, h: u32, planes: &[Plane]) { + let cpu = self.srvs.GetCPUDescriptorHandleForHeapStart(); + let mut constants = [0u32; CONSTANT_WORDS as usize]; + for k in 0..MAX_PLANES { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu.ptr + k * self.inc }; + let plane = planes.get(k); + let format = plane.map_or(DXGI_FORMAT_R8G8B8A8_UNORM, |p| view_format(p.res.GetDesc().Format)); + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }, + }; + dev.CreateShaderResourceView(plane.map(|p| &p.res), Some(&desc), at); + if let Some(p) = plane { + let d = p.res.GetDesc(); + let (pw, ph) = ((d.Width as f32).max(1.0), (d.Height as f32).max(1.0)); + let src = [p.src[0] / pw, p.src[1] / ph, p.src[2] / pw, p.src[3] / ph]; + for j in 0..4 { + constants[4 * k + j] = src[j].to_bits(); + constants[4 * MAX_PLANES + 4 * k + j] = p.dst[j].to_bits(); + } + } + } + constants[8 * MAX_PLANES] = planes.len().min(MAX_PLANES) as u32; + let rtv = self.rtvs.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(target, None, rtv); + list.SetGraphicsRootSignature(&self.root); + list.SetDescriptorHeaps(&[Some(self.srvs.clone())]); + list.SetGraphicsRootDescriptorTable(0, self.srvs.GetGPUDescriptorHandleForHeapStart()); + list.SetGraphicsRoot32BitConstants(1, CONSTANT_WORDS, constants.as_ptr() as *const c_void, 0); + list.SetPipelineState(&self.pso); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: w as f32, Height: h as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); + list.RSSetScissorRects(&[RECT { left: 0, top: 0, right: w as i32, bottom: h as i32 }]); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list.DrawInstanced(3, 1, 0, 0); + } +} + +/// A plane's source rect from the title's (texels, as i32: left, top, right, bottom) – the +/// whole resource when there is none or it is empty or outside it. +pub fn source_rect(rect: Option<[i32; 4]>, w: u64, h: u64) -> [f32; 4] { + let full = [0.0, 0.0, w as f32, h as f32]; + let Some([l, t, r, b]) = rect else { return full }; + if l < 0 || t < 0 || r <= l || b <= t || r as u64 > w || b as u64 > h { + return full; + } + [l as f32, t as f32, r as f32, b as f32] +} + +/// A plane's place on the screen from the title's (0..1: left, top, right, bottom) – the whole +/// screen when there is none or it is not a sane rectangle. +pub fn destination(rect: Option<[f32; 4]>) -> [f32; 4] { + let full = [0.0, 0.0, 1.0, 1.0]; + let Some([l, t, r, b]) = rect else { return full }; + let sane = [l, t, r, b].iter().all(|v| v.is_finite() && (-1.0..=2.0).contains(v)) && r > l && b > t; + if sane { + [l, t, r, b] + } else { + full + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plane_rects() { + assert_eq!(source_rect(Some([0, 0, 1920, 1080]), 1920, 1080), [0.0, 0.0, 1920.0, 1080.0]); + assert_eq!(source_rect(Some([0, 0, 1280, 720]), 1920, 1080), [0.0, 0.0, 1280.0, 720.0]); // dynamic resolution + assert_eq!(source_rect(Some([0, 0, 4000, 1080]), 1920, 1080), [0.0, 0.0, 1920.0, 1080.0]); + assert_eq!(source_rect(Some([10, 10, 5, 20]), 1920, 1080), [0.0, 0.0, 1920.0, 1080.0]); + assert_eq!(source_rect(None, 3840, 2160), [0.0, 0.0, 3840.0, 2160.0]); + assert_eq!(destination(Some([0.0, 0.0, 1.0, 1.0])), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(destination(Some([0.25, 0.25, 0.75, 0.75])), [0.25, 0.25, 0.75, 0.75]); + assert_eq!(destination(Some([f32::NAN, 0.0, 1.0, 1.0])), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(destination(Some([0.0, 0.0, 0.0, 1.0])), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(destination(None), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(CONSTANT_WORDS, 33); + } +} diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index efc4d80..94bf74a 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -161,6 +161,8 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { next: 0, free: Vec::new(), }); + // (the view census's map of it, while the heap is still held: before any view goes there) + super::view_census::make(cap); } true } @@ -212,6 +214,72 @@ pub fn in_global(obj: usize) -> bool { HEAPS.lock().unwrap().iter().any(|h| h.obj == obj && !h.pages.is_empty()) } +/// The shared heap's extent for the view census: (descriptors given out – places `[0, next)` were +/// all used once –, its size, its released ranges (first, count) sorted by first). None: no shared +/// heap. +pub(super) fn global_extent() -> Option<(u32, u32, Vec<(u32, u32)>)> { + let (next, cap, mut free) = { + let g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.as_ref()?; + (s.next, s.cap, s.free.clone()) + }; + free.sort_unstable(); + Some((next, cap, free)) +} + +/// `f(place)` for the places in the shared heap of CPU-only heaps' view slots whose words no longer +/// hold their own image T# – the title wrote them over as memory (a CBV, a buffer V#, zeros, a copy +/// of another slot), or nothing was ever written: the resync walks shader-visible heaps only, so +/// the shared heap's descriptors there (the slot's SRV and UAV places, both given) still name what +/// XCL last put there, reachable through any T# that carries the place (the view census). The words +/// are read a page at a time under the heaps' lock – a heap's memory goes only once it is out of +/// `HEAPS` –, so a title's view call waits for one page's look at most. +pub(super) fn cpu_only_stale(mut f: impl FnMut(u32)) { + let pages: Vec<(usize, usize)> = HEAPS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|h| !h.visible && !h.sampler && h.shadow != 0) + .flat_map(|h| h.pages.iter().enumerate().filter(|&(_, &first)| first != UNMAPPED).map(move |(p, _)| (h.obj, p))) + .collect(); + let mut words = vec![[0u32; 8]; PAGE_SLOTS as usize]; + for (obj, p) in pages { + let (first, n) = { + let heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + // (gone since, or its object's address another heap's now: that one's page, if placed) + let Some(h) = heaps.iter().find(|h| h.obj == obj && !h.visible && !h.sampler && h.shadow != 0) else { continue }; + let Some(&first) = h.pages.get(p).filter(|&&first| first != UNMAPPED) else { continue }; + let k0 = p as u32 * PAGE_SLOTS; + let n = (k0 + PAGE_SLOTS).min(h.n).saturating_sub(k0); + for (j, w) in words.iter_mut().enumerate().take(n as usize) { + unsafe { std::ptr::copy_nonoverlapping((h.shadow + ((k0 + j as u32) * SLOT) as usize) as *const u32, w.as_mut_ptr(), 8) }; + } + (first, n) + }; + for (j, w) in words.iter().enumerate().take(n as usize) { + let own = first + 2 * j as u32; + if !(w[3] >> 28 >= 8 && w[0] == own) { + f(own); + f(own + 1); + } + } + } +} + +/// Tests that take places in the shared heap and give them back: one at a time (where the next +/// place goes depends on what was given back before – `large_heaps_get_shared_pages_as_used` +/// counts on two small heaps getting places side by side; the view census's tests read what their +/// heap's places hold). +#[cfg(test)] +pub(super) static SHARED_RANGES: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// (tests) the shared heap's device – what a test's own descriptor heaps and resources are made +/// with, so `publish`'s copies stay on one device. +#[cfg(test)] +pub(super) fn shared_device_for_test() -> Option { + GLOBAL.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|g| g.dev.clone()) +} + /// Memory for a heap of `bytes` from the title's allocation hook – where the title expects the /// heap then. Only what descriptor tables can address (window 0) and is committed; anything else /// goes back to the title. @@ -294,8 +362,15 @@ fn unregister_with_resync(obj: usize, track_resync: bool) { }) }; if let Some(h) = gone { + // (the view census: the title heap's descriptors go with it before its places go back; + // atomics only – this can run on the ledger's thread) + let names = super::view_census::names(); for (p, &f) in h.pages.iter().enumerate().filter(|&(_, &f)| f != UNMAPPED) { - release_global(f, page_descriptors(h.n, p as u32)); + let count = page_descriptors(h.n, p as u32); + if let Some(m) = names { + m.heap_gone(f, count); + } + release_global(f, count); } match h.memory { Memory::Sparse => { @@ -308,6 +383,15 @@ fn unregister_with_resync(obj: usize, track_resync: bool) { } Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) }, } + // (XCL's views in its slots: the memory may be another heap's next) + let end = h.shadow.saturating_add(h.n as usize * h.slot_bytes() as usize); + WROTE.lock().unwrap_or_else(|e| e.into_inner()).forget(h.shadow, end); + #[cfg(test)] + TEST_RECORD.with(|t| { + if let Some(r) = t.borrow_mut().as_mut() { + r.forget(h.shadow, end); + } + }); } } @@ -354,6 +438,38 @@ pub fn slot(cpu: u64) -> Option { Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k }) } +/// The PC view just made in slot `s` – its SRV, or with `uav` its UAV, in the title's heap – names +/// `res` (0: a null view): one store into the view census's map (`view_census`), after the driver's +/// call. A slot with no place in the shared heap is counted, not mapped. +#[inline] +pub fn note_pc_view(s: &Slot, uav: bool, res: usize) { + if s.sampler { + return; + } + let Some(m) = super::view_census::names() else { return }; + if s.shared_srv != 0 { + m.title_view(s.index, uav, res); + } else { + m.note_untracked(); + } +} + +/// A device copy (`real::copy_console_slots`) wrote both PC descriptors of view slot `d` – in the +/// title's heap and then the shared heap's – from slot `s` (None: not a console slot): the view +/// census's map follows (a source with no place in the shared heap: not known). +#[inline] +pub fn note_copied_view(d: &Slot, s: Option<&Slot>) { + if d.sampler { + return; + } + let Some(m) = super::view_census::names() else { return }; + match s { + _ if d.shared_srv == 0 => m.note_untracked(), + Some(s) if s.shared_srv != 0 && !s.sampler => m.copied(d.index, s.index), + _ => m.copied_unknown(d.index), + } +} + /// The view just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap. pub unsafe fn publish(s: &Slot, uav: bool) { if s.shared_srv == 0 { @@ -362,6 +478,9 @@ pub unsafe fn publish(s: &Slot, uav: bool) { if let Some(g) = GLOBAL.lock().unwrap().as_ref() { let (dst, src) = if uav { (s.shared_srv + g.inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) }; g.dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if let Some(m) = super::view_census::names() { + m.published(s.index + uav as u32); + } } } @@ -404,29 +523,251 @@ pub fn resource_at(at: usize) -> Option { RES.lock().unwrap().as_ref()?.get(&at).copied() } +/// `words` into slot `s` (`write_view`: a view of XCL's, not named). pub fn write(s: &Slot, words: &[u32]) { + write_view(s, words, "view", || None) +} + +/// XCL's view of `what` ("buffer SRV", "CBV" …) into slot `s`: its words; `at` gives the title +/// memory the view names – an empty V#'s, the memory it would have named –, asked only while +/// XCL's views are recorded (`Wrote`). +pub fn write_view(s: &Slot, words: &[u32], what: &'static str, at: impl FnOnce() -> Option<(usize, u64)>) { + write_named(s, words, what, || at().map(|(a, n)| Names::Memory(a, n))) +} + +/// XCL's view of `what` of texture `res` (its T#, or an empty view of a shape XCL cannot describe) +/// into slot `s`: the texture's title address is looked up only when a line names the slot +/// (`Names::Texture`), not in the title's view calls. +pub fn write_texture_view(s: &Slot, words: &[u32], what: &'static str, res: usize) { + write_named(s, words, what, || (res != 0).then_some(Names::Texture(res))) +} + +fn write_named(s: &Slot, words: &[u32], what: &'static str, names: impl FnOnce() -> Option) { let n = words.len().min(if s.sampler { 4 } else { 8 }); unsafe { std::ptr::copy_nonoverlapping(words.as_ptr(), s.at as *mut u32, n) }; + if !s.sampler && super::skip_roots::recording() { + // (the slot's 8 words as the write left them – a buffer V#'s 4 leave the other 4 as they + // were: a later copy that differs in those is the title's) + let mut now = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping(s.at as *const u32, now.as_mut_ptr(), 8) }; + note_wrote(s.at, Wrote { what, tag: tag(&now), names: names() }); + } +} + +/// The title memory a view of XCL's names (`Wrote`): an address and its bytes – or a texture, its +/// address looked up when a line names the slot (`now`): `title_textures`' lock stays off the +/// title's view calls (run 64: some 770 texture views a second while its world loaded). A key +/// lookup – a texture gone since names nothing, and is never touched. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Names { + Memory(usize, u64), + Texture(usize), +} + +impl Names { + /// (address, bytes) now – a texture's bytes not counted: 0 + fn now(self) -> Option<(usize, u64)> { + match self { + Names::Memory(a, n) => Some((a, n)), + Names::Texture(res) => super::real::texture_address(res), + } + } +} + +/// A view XCL wrote into a slot: what it is, a tag of the slot's 8 words as XCL's write left them, +/// and the title memory it names. Kept while `XCL_SKIP_CS`'s root views are still to be logged +/// (`skip_roots::recording`: they tell XCL's descriptors from the title's own bytes – its own +/// descriptors, its copies of slots – by it), for `WROTE_MAX` slots. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Wrote { + what: &'static str, + tag: u64, + names: Option, +} + +/// XCL's record of the views it wrote: slot address → what XCL last wrote there, `max` slots at +/// most; `full`: a slot was not recorded for want of room – an unrecorded slot's writer is not +/// known from then on. +struct Record { + wrote: std::collections::BTreeMap, + max: usize, + full: bool, +} + +impl Record { + const fn new(max: usize) -> Record { + Record { wrote: std::collections::BTreeMap::new(), max, full: false } + } + + /// `w` is what XCL wrote at `at`; Some(max): that filled the record (its first slot not + /// recorded – once). + fn note(&mut self, at: usize, w: Wrote) -> Option { + if self.wrote.len() >= self.max && !self.wrote.contains_key(&at) { + return (!std::mem::replace(&mut self.full, true)).then_some(self.max); + } + self.wrote.insert(at, w); + None + } + + /// The records of slots in `[from, end)` dropped (a heap gone: its memory may be another's next). + fn forget(&mut self, from: usize, end: usize) { + let gone: Vec = self.wrote.range(from..end).map(|(&a, _)| a).collect(); + for a in gone { + self.wrote.remove(&a); + } + } +} + +/// slot address → what XCL last wrote there +static WROTE: Mutex = Mutex::new(Record::new(WROTE_MAX)); +/// slots recorded at most (some 10 MB) +const WROTE_MAX: usize = 1 << 17; + +#[cfg(test)] +thread_local! { + /// (tests) this thread's record instead of the process's (`record_for_test`) + static TEST_RECORD: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// `f` on the record: the process's – (tests) this thread's while it has one +fn with_record(f: impl FnOnce(&mut Record) -> R) -> R { + #[cfg(test)] + if TEST_RECORD.with(|t| t.borrow().is_some()) { + return TEST_RECORD.with(|t| f(t.borrow_mut().as_mut().expect("this thread's record"))); + } + f(&mut WROTE.lock().unwrap_or_else(|e| e.into_inner())) +} + +/// (tests) XCL's views this thread writes recorded in a record of `max` slots of its own (the +/// process's record is shared by the suite's threads) until the guard goes. +#[cfg(test)] +pub(super) fn record_for_test(max: usize) -> impl Drop { + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + TEST_RECORD.with(|t| *t.borrow_mut() = None); + } + } + TEST_RECORD.with(|t| *t.borrow_mut() = Some(Record::new(max))); + Restore +} + +/// FNV-1a of `words`. +fn tag(words: &[u32]) -> u64 { + words.iter().flat_map(|w| w.to_le_bytes()).fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)) +} + +fn note_wrote(at: usize, w: Wrote) { + // (the line after the record's lock) + if let Some(max) = with_record(|r| r.note(at, w)) { + let line = full_line(max); + crate::xlog_warn!("{line}"); + #[cfg(test)] + FULL_LINES.with(|l| l.borrow_mut().push(line)); + } +} + +#[cfg(test)] +thread_local! { + /// (tests) the "record … is full" lines this thread logged + static FULL_LINES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// (tests) the "record … is full" lines this thread logged since the last call +#[cfg(test)] +pub(super) fn take_full_lines_for_test() -> Vec { + FULL_LINES.with(|l| std::mem::take(&mut *l.borrow_mut())) +} + +/// The line of a record that just filled (`Record::note`) – it holds `XCL_SKIP_CS`: run65_events.sh +/// shows it. +fn full_line(max: usize) -> String { + format!("D3D12.X: XCL_SKIP_CS: XCL's record of the views it writes is full ({max} slots): later slots' writers are unknown") +} + +fn wrote_at(at: usize) -> Option { + with_record(|r| r.wrote.get(&at).copied()) } /// Copy a console slot's descriptor to another slot of the same kind, the PC heap index /// in it (T# word 0, S# word 3 [11:0]) renumbered for the destination. Buffer V# carry -/// their address and stay as they are. +/// their address and stay as they are. (XCL's write: of the source's view, as recorded – while the +/// source still holds XCL's bytes; the title's bytes there make it a plain copy.) pub fn copy_words(src: &Slot, dst: &Slot) { let n = if src.sampler { 4 } else { 8 }; let mut w = [0u32; 8]; unsafe { std::ptr::copy_nonoverlapping(src.at as *const u32, w.as_mut_ptr(), n) }; + let source = w; if src.sampler { w[3] = (w[3] & !0xFFF) | (dst.index & 0xFFF); } else if w[3] >> 28 >= 8 { w[0] = dst.index; } - write(dst, &w[..n]); + let from = if !src.sampler && super::skip_roots::recording() { wrote_at(src.at).filter(|f| tag(&source) == f.tag) } else { None }; + write_named(dst, &w[..n], from.map_or("view copied by CopyDescriptors", |f| f.what), || from.and_then(|f| f.names)); if !src.sampler { note_resource(dst, resource_at(src.at).unwrap_or(0)); } } +/// Who wrote what a view slot holds, as far as XCL can tell (`peek`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Writer { + /// XCL: its view of `.0` (as `write_view` names it), naming the title memory `.1` + Xcl(&'static str, Option<(usize, u64)>), + /// the title, over a view of XCL's (`.0`): its own descriptor or a copy of a slot + Over(&'static str), + /// the title: XCL wrote nothing there + Title, + /// not known (why) + Unknown(&'static str), +} + +/// What a console slot holds and who wrote it – a look only (`slot` would give a page of the +/// slot its place in the shared heap). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Peek { + pub words: [u32; 8], + /// the heap object, the slot's number in it, its first byte + pub heap: usize, + pub k: u32, + pub at: usize, + pub sampler: bool, + /// the heap's slots are in the title's memory (its allocation hook), not XCL's + pub title_memory: bool, + pub visible: bool, + pub writer: Writer, +} + +/// The console slot at `at` (any byte of it) of XCL's heaps (None: in none of them). Its words are +/// read under the heaps' lock (a heap's memory goes only once it is out of `HEAPS`). +pub fn peek(at: usize) -> Option { + let (words, heap, k, slot_at, sampler, title_memory, visible) = { + let heaps = HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let h = heaps.iter().find(|h| at >= h.shadow && at - h.shadow < h.n as usize * h.slot_bytes() as usize)?; + let k = (at - h.shadow) / h.slot_bytes() as usize; + let slot_at = h.shadow + k * h.slot_bytes() as usize; + let mut w = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping(slot_at as *const u32, w.as_mut_ptr(), if h.sampler { 4 } else { 8 }) }; + (w, h.obj, k as u32, slot_at, h.sampler, h.memory == Memory::Title, h.visible) + }; + let writer = if sampler { Writer::Unknown("a sampler slot") } else { writer_of(slot_at, &words) }; + Some(Peek { words, heap, k, at: slot_at, sampler, title_memory, visible, writer }) +} + +/// (a line names the slot: a texture's address is looked up now – `Names::now`) +fn writer_of(at: usize, words: &[u32; 8]) -> Writer { + if !super::skip_roots::recorded() { + return Writer::Unknown("XCL's views are not recorded"); + } + match with_record(|r| (r.wrote.get(&at).copied(), r.full)) { + (Some(w), _) if tag(words) == w.tag => Writer::Xcl(w.what, w.names.and_then(Names::now)), + (Some(w), _) => Writer::Over(w.what), + (None, true) => Writer::Unknown("XCL's record of its views is full"), + (None, false) => Writer::Title, + } +} + /// `XCL_TRACE_FRAME`: what the slots of each shader-visible view heap hold – images whose /// PC index is the slot's own (made or copied through the device) or another (copied by the /// title itself, as memory), buffers, empty. @@ -501,25 +842,6 @@ pub fn words_at(addr32: u32) -> Option<[u32; 8]> { static LAST_TAGS: Mutex>> = Mutex::new(None); -/// Find the CPU-only mirror of a global SRV. D3D12 cannot copy descriptors from -/// the shader-visible global heap, even if its CPU handle is available. -fn cpu_mirror_srv(heaps: &[Heap], index: u32) -> Option { - for h in heaps.iter().filter(|h| h.pc_gpu == 0) { - for (page, &first) in h.pages.iter().enumerate() { - let page = page as u32; - if first == UNMAPPED || index < first { - continue; - } - let offset = index - first; - if offset % 2 == 0 && offset < page_descriptors(h.n, page) { - let slot = page * PAGE_SLOTS + offset / 2; - return Some(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h.pc_cpu as usize + 2 * slot as usize * h.inc as usize }); - } - } - } - None -} - /// Brings the host descriptor heap (`GLOBAL`) up to date with descriptors the title wrote into /// heap memory itself (copies of whole slots or converting image slots to buffers/CBVs/zeroes), /// before a submission runs (`real::q_execute_command_lists`). @@ -535,20 +857,60 @@ fn cpu_mirror_srv(heaps: &[Heap], index: u32) -> Option, put: impl FnOnce(Mirror)) -> Mirror { + let m = if w.iter().all(|&x| x == 0) || w[3] >> 28 < 8 { + Mirror::Null + } else if w[0] != own && w[0] < cap { + Mirror::From(w[0]) + } else { + Mirror::Nothing + }; + put(m); + if let Some(n) = names { + match m { + Mirror::Null => n.shared_cleared(own), + Mirror::From(s) => n.shared_copied(own, s), + Mirror::Nothing => {} + } + } + m +} + +/// `resync_title_writes` under the heaps' locks (HEAPS, GLOBAL, LAST_TAGS – as before). +unsafe fn resync_slots(found: &mut super::outside::HeapVs) { let heaps = HEAPS.lock().unwrap(); let g = GLOBAL.lock().unwrap(); let Some(g) = g.as_ref() else { return }; let mut tags_lock = LAST_TAGS.lock().unwrap(); let tags = tags_lock.get_or_insert_with(HashMap::new); + let names = super::view_census::names(); - let process = GetCurrentProcess(); - let mut snapshot = [[0u32; 8]; PAGE_SLOTS as usize]; for h in heaps.iter().filter(|h| h.visible && !h.sampler) { if h.shadow == 0 { continue; @@ -559,55 +921,62 @@ pub unsafe fn resync_title_writes() { } let k_start = p as u32 * PAGE_SLOTS; let k_end = (k_start + PAGE_SLOTS).min(h.n); - let count = (k_end - k_start) as usize; - if count == 0 { - continue; - } - let address = h.shadow + k_start as usize * SLOT as usize; - let bytes = count * SLOT as usize; - let mut copied = 0; - // The title owns some heap allocations and can decommit their backing memory. - if ReadProcessMemory(process, address as *const c_void, snapshot.as_mut_ptr().cast(), bytes, &mut copied) == 0 - || copied != bytes - { - continue; - } - - for (offset, w) in snapshot[..count].iter().enumerate() { - let k = k_start + offset as u32; + for k in k_start..k_end { + let slot_va = h.shadow + (k * SLOT) as usize; + let w = std::slice::from_raw_parts(slot_va as *const u32, 8); let tag = ((w[3] as u64) << 32) | (w[0] as u64); - let own_idx = first + 2 * offset as u32; + let own_idx = first + 2 * (k - k_start); if tags.get(&(h.obj, k)) == Some(&tag) { continue; } + // (a slot whose words changed since the last submit: counted when it is a buffer + // V# outside unified memory – `outside`) + found.look(w); + // (diagnostic `XCL_TRACE_PAGES`) a descriptor the title wrote naming a traced page + { + let buffer_base = (w[0] as usize) | (((w[1] & 0xFFFF) as usize) << 32); + let image_base = ((w[0] as usize) | (((w[1] & 0xFF) as usize) << 32)) << 8; + let (kind, base) = if w[3] >> 28 >= 8 { ("image", image_base) } else { ("buffer", buffer_base) }; + if crate::hle::kernelx::traced_range(base, 16) { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 { + crate::xlog_info!("[trace] the title wrote a {kind} descriptor naming {base:#x} into slot {k} of heap {:#x}: {:08x?}", h.obj, w); + } + } + } let dst_cpu = g.cpu + (own_idx as u64) * (g.inc as u64); - if w.iter().all(|&x| x == 0) || (w[3] >> 28 < 8) { - // Overwritten with buffer / CBV or cleared: install null raw buffer SRV - // so mesh shader loads past bounds safely return 0 rather than fault at address 0. - let null_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_TYPELESS, - ViewDimension: D3D12_SRV_DIMENSION_BUFFER, - Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_SRV { - FirstElement: 0, - NumElements: 0, - StructureByteStride: 0, - Flags: D3D12_BUFFER_SRV_FLAG_RAW, + resync_slot(w, own_idx, g.cap, names, |m| match m { + Mirror::Null => { + // Overwritten with buffer / CBV or cleared: install null raw buffer SRV + // so mesh shader loads past bounds safely return 0 rather than fault at address 0. + let null_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 0, + NumElements: 0, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, }, - }, - }; - g.dev.CreateShaderResourceView(None, Some(&null_desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst_cpu as usize }); - } else if w[0] != own_idx { - let Some(src_cpu) = cpu_mirror_srv(&heaps, w[0]) else { continue }; - g.dev.CopyDescriptorsSimple( - 1, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst_cpu as usize }, - src_cpu, - D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - ); - } + }; + g.dev.CreateShaderResourceView(None, Some(&null_desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst_cpu as usize }); + } + Mirror::From(src_idx) => { + // Copied whole slot from another slot index in GLOBAL: mirror source descriptor + let src_cpu = g.cpu + (src_idx as u64) * (g.inc as u64); + g.dev.CopyDescriptorsSimple( + 1, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst_cpu as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src_cpu as usize }, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); + } + Mirror::Nothing => {} + }); tags.insert((h.obj, k), tag); } } @@ -618,25 +987,21 @@ pub unsafe fn resync_title_writes() { mod tests { use super::*; + /// XCL's record of its views says once that it filled – its first slot without room –, not at + /// the later ones; a slot it holds is updated all the same (F-1). Its line holds XCL_SKIP_CS. #[test] - fn global_srv_resolves_only_to_a_live_cpu_mirror() { - let heap = Heap { - obj: 1, - shadow: 0, - n: PAGE_SLOTS + 4, - pc_cpu: 0x1000, - pc_gpu: 0, - inc: 32, - sampler: false, - pages: vec![UNMAPPED, 64], - visible: true, - memory: Memory::Title, - }; - let heaps = [heap]; - assert_eq!(cpu_mirror_srv(&heaps, 68).unwrap().ptr, 0x1000 + 2 * (PAGE_SLOTS as usize + 2) * 32); - assert!(cpu_mirror_srv(&heaps, 69).is_none()); // UAV - assert!(cpu_mirror_srv(&heaps, 72).is_none()); // past the last partial page - assert!(cpu_mirror_srv(&heaps, 0).is_none()); // no assigned page + fn the_record_of_xcl_s_views_says_once_that_it_filled() { + let w = Wrote { what: "view", tag: 1, names: None }; + let mut r = Record::new(1); + assert_eq!(r.note(0x100, w), None); + assert_eq!(r.note(0x120, w), Some(1), "full: said"); + assert_eq!(r.note(0x140, w), None, "said once"); + assert_eq!(r.note(0x100, Wrote { tag: 2, ..w }), None, "a slot it holds is updated"); + assert_eq!(r.wrote.get(&0x100).map(|w| w.tag), Some(2)); + assert!(r.full && !r.wrote.contains_key(&0x120)); + r.forget(0x100, 0x120); + assert!(r.wrote.is_empty(), "a heap's slots forgotten when it goes"); + assert_eq!(full_line(WROTE_MAX), "D3D12.X: XCL_SKIP_CS: XCL's record of the views it writes is full (131072 slots): later slots' writers are unknown"); } #[test] @@ -734,6 +1099,7 @@ mod tests { fn large_heaps_get_shared_pages_as_used() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; + let _one = SHARED_RANGES.lock().unwrap_or_else(|e| e.into_inner()); if crate::gpu::uma::get().is_none() { return; } @@ -782,4 +1148,197 @@ mod tests { unregister(0xB100); unregister(0xB101); } + + /// A buffer V# outside unified memory found in a slot changed since the last submit is shown + /// to `outside::HeapVs` once per change – whichever submit's resync finds it (each holds the + /// heaps for its whole loop); an image T# and a buffer V# of unified memory are not. + #[test] + fn buffer_vsharps_new_outside_unified_memory_are_seen_once_per_change() { + use super::super::outside::{forget_heap_seen_for_test, heap_seen_for_test}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS}; + let _one = SHARED_RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let Some(u) = crate::gpu::uma::get() else { return }; + let Some(inside) = (0..u.windows()).map(|k| u.window(k)).find(|w| w.1 > 0x20_0000).map(|w| (w.0 + 0x10_0000) as u64) else { return }; + let dev = unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + dev.expect("D3D12 device") + }; + if !unsafe { shared_heap(&dev) } { + return crate::gpu::recomp::runner::skip_config("no shared shader-visible heap"); + } + // (8 slots: the place it gives back, 16 descriptors, is two small heaps' side by side) + let obj = 0x7D0D_6000usize; + assert!(register(obj, 8, 0x30_0000, 0, 32, false, true, true)); + let v = start(obj).unwrap(); + let s: Vec = (0..3u64).map(|k| slot(v + k * SLOT as u64).unwrap()).collect(); + if s.iter().any(|x| x.shared_srv == 0) { + unregister(obj); + return crate::gpu::recomp::runner::skip_config("the heap's slots have no place in the shared heap"); + } + let out = unsafe { VirtualAlloc(std::ptr::null(), 0x10_0000, MEM_RESERVE, PAGE_NOACCESS) } as u64; + assert_ne!(out, 0, "a reservation outside the windows"); + let (base, base2) = (out + 0x100, out + 0x8000); + let vsharp = |b: u64| { + let w = crate::gpu::desc::buffer_words(b, 0, 64, 22); + [w[0], w[1], w[2], w[3], 0, 0, 0, 0] + }; + write(&s[0], &vsharp(base)); + // (an image T#: its words, read as a buffer V#'s, would name base2) + write(&s[1], &[base2 as u32, (base2 >> 32) as u32, 0, 9 << 28, 0, 0, 0, 0]); + write(&s[2], &vsharp(inside)); + unsafe { + resync_title_writes(); + resync_title_writes(); + } + let seen = (heap_seen_for_test(base), heap_seen_for_test(base2), heap_seen_for_test(inside)); + write(&s[0], &vsharp(base + 0x40)); + unsafe { resync_title_writes() }; + let again = heap_seen_for_test(base + 0x40); + unregister(obj); + // (before the reservation goes: a later test's may get its address) + for b in [base, base + 0x40] { + forget_heap_seen_for_test(b); + } + unsafe { VirtualFree(out as *mut std::ffi::c_void, 0, MEM_RELEASE) }; + assert_eq!(seen, (1, 0, 0), "the buffer V# outside unified memory once in two submits; not the image, not one of unified memory"); + assert_eq!(again, 1, "the slot written again: seen again"); + } + + /// The resync's step for a changed slot (`resync_slot`, the view census's binding amendment A5: + /// tested on a map of its own, not through the process's resync, which any test's submit runs): + /// a buffer V#, a CBV or zeros get a null SRV at the slot's place – the map's shared descriptor + /// there names nothing, the title heap's keeps its texture –; an image T# copied from another + /// slot gets that slot's shared descriptor, and the map with it; the slot's own T#, or one whose + /// index is past the shared heap, gets nothing. The map follows the heap, never before it. + #[test] + fn the_resync_s_step_updates_the_view_map_after_the_shared_heap() { + let m = super::super::view_census::window(0, 64); + let (a, b) = (0x7A1E_2B01usize, 0x7A1E_2B02usize); + for (i, r) in [(4, a), (8, b)] { + m.title_view(i, false, r); + m.published(i); + } + let buffer = [0x1000, 0, 64, 0x3101_6FAC, 0, 0, 0, 0]; + let mut seen = None; + assert_eq!(resync_slot(&buffer, 4, 64, Some(m), |x| seen = Some((x, m.at(4)))), Mirror::Null); + assert_eq!(seen, Some((Mirror::Null, (a, a))), "the heap first, then the map"); + assert_eq!(m.at(4), (a, 0), "the title heap's descriptor still names it"); + let cbv = crate::gpu::desc::cbv_words(0x1000, 256); + assert_eq!(resync_slot(&[cbv[0], cbv[1], cbv[2], cbv[3], 0, 0, 0, 0], 8, 64, None, |_| {}), Mirror::Null, "a CBV"); + assert_eq!(resync_slot(&[0; 8], 8, 64, None, |_| {}), Mirror::Null, "zeros"); + // slot 8's T# copied (as memory) into the slot at place 10 + let t8 = [8, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0]; + assert_eq!(resync_slot(&t8, 10, 64, Some(m), |_| {}), Mirror::From(8)); + assert_eq!(m.at(10), (0, b)); + let own = [12, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0]; + assert_eq!(resync_slot(&own, 12, 64, Some(m), |_| {}), Mirror::Nothing, "its own T#"); + let past = [64, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0]; + assert_eq!(resync_slot(&past, 12, 64, Some(m), |_| {}), Mirror::Nothing, "an index past the shared heap"); + assert_eq!((m.at(8), m.at(12)), ((b, b), (0, 0))); + } + + /// The view census's map follows the shared heap's places: a view made in a slot names its + /// texture in the title heap's descriptor, its publication in the shared heap's (a UAV at the + /// place after its slot's SRV); a CPU-only slot the title wrote over as memory is told (its + /// shared descriptors still name what XCL put there); the heap's release takes its title heap's + /// descriptors and leaves the shared ones; a view into a heap with no place in the shared heap + /// is counted, not mapped. (The heap is CPU-only, as the title's are with a shared heap: no + /// resync walks it; the map is this thread's – `names_for_test`.) + #[test] + fn publish_and_unregister_keep_the_view_map_in_step() { + use super::super::view_census::names_for_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let _one = SHARED_RANGES.lock().unwrap_or_else(|e| e.into_inner()); + if crate::gpu::uma::get().is_none() { + return; + } + let dev = unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + dev.expect("D3D12 device") + }; + if !unsafe { shared_heap(&dev) } { + return crate::gpu::recomp::runner::skip_config("no shared shader-visible heap"); + } + let dev = shared_device_for_test().expect("the shared heap's device"); + // the title's PC heap: CPU-only, 2 descriptors a slot, null SRVs in all (what `publish` copies) + let pc: ID3D12DescriptorHeap = unsafe { dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 16, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0 }) }.expect("a CPU-only heap"); + let cpu = unsafe { pc.GetCPUDescriptorHandleForHeapStart() }.ptr as u64; + let inc = unsafe { dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) }; + let null = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Buffer: D3D12_BUFFER_SRV { FirstElement: 0, NumElements: 0, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW } }, + }; + for k in 0..16u64 { + unsafe { dev.CreateShaderResourceView(None, Some(&null), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + k * inc as u64) as usize }) }; + } + let obj = 0x7A1E_2001usize; + assert!(register(obj, 8, cpu, 0, inc, false, true, false)); + let v = start(obj).unwrap(); + let s: Vec = (0..4u64).map(|k| slot(v + k * SLOT as u64).unwrap()).collect(); + if s.iter().any(|x| x.shared_srv == 0) { + unregister(obj); + return crate::gpu::recomp::runner::skip_config("the heap's slots have no place in the shared heap"); + } + let first = s[0].index; + assert!(s.iter().enumerate().all(|(k, x)| x.index == first + 2 * k as u32), "a page's places side by side"); + let (m, window) = names_for_test(first, 16); + let (a, b) = (0x7A1E_2A11usize, 0x7A1E_2A12usize); + note_pc_view(&s[0], false, a); + assert_eq!(m.at(first), (a, 0), "the title heap's descriptor first"); + unsafe { publish(&s[0], false) }; + assert_eq!(m.at(first), (a, a), "then the shared heap's"); + note_pc_view(&s[1], true, b); + unsafe { publish(&s[1], true) }; + assert_eq!((m.at(s[1].index), m.at(s[1].index + 1)), ((0, 0), (b, b)), "a UAV at the place after its slot's SRV"); + // the title writes a CBV over slot 0 (as memory); slot 1 holds its own image T# + let cbv = crate::gpu::desc::cbv_words(0x1000, 256); + unsafe { + std::ptr::copy_nonoverlapping([cbv[0], cbv[1], cbv[2], cbv[3], 0, 0, 0, 0].as_ptr(), s[0].at as *mut u32, 8); + std::ptr::copy_nonoverlapping([s[1].index, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0].as_ptr(), s[1].at as *mut u32, 8); + } + let mut stale = Vec::new(); + cpu_only_stale(|i| { + if (first..first + 16).contains(&i) { + stale.push(i); + } + }); + assert!(stale.contains(&first) && stale.contains(&(first + 1)), "slot 0's places: written over ({stale:?})"); + assert!(!stale.contains(&s[1].index) && !stale.contains(&(s[1].index + 1)), "slot 1 holds its own T#"); + assert_eq!(stale.len(), 14, "every other slot of the heap's page (never written)"); + unregister(obj); + assert!((first..first + 16).all(|i| m.at(i).0 == 0), "the title heap's descriptors went with it"); + assert_eq!((m.at(first).1, m.at(s[1].index + 1).1), (a, b), "the shared heap's stay, in a released range now"); + drop(window); + // a heap without places in the shared heap: its views are counted + let other = 0x7A1E_2002usize; + assert!(register(other, 2, 0x10_0000, 0, 32, false, false, true)); + let (m2, _w2) = names_for_test(0, 16); + let x = slot(start(other).unwrap()).unwrap(); + note_pc_view(&x, false, a); + note_copied_view(&x, Some(&s[0])); + // a sampler slot's views and copies name no view: neither mapped nor counted + let sampler = Slot { at: 0, index: 3, pc_srv: 0, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv: 0, k: 3 }; + note_pc_view(&sampler, false, a); + note_copied_view(&sampler, Some(&sampler)); + unregister(other); + assert_eq!(m2.counts(), (2, 0), "a view and a copy into it: untracked"); + assert!((0..16).all(|i| m2.at(i) == (0, 0))); + // the census reads the released ranges sorted by first, whatever order they went back in + let (y, z) = (0x7A1E_2003usize, 0x7A1E_2004usize); + assert!(register(y, 2, cpu, 0, inc, false, true, false) && register(z, 2, cpu, 0, inc, false, true, false)); + let _ = (slot(start(y).unwrap()), slot(start(z).unwrap())); + unregister(z); + unregister(y); + let (_, _, free) = global_extent().expect("the shared heap"); + assert!(free.windows(2).all(|w| w[0].0 < w[1].0), "released ranges sorted ({free:?})"); + } } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index e1bdeb9..40e758d 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -847,7 +847,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?; - let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?; + let res_at = uma_copy(st, &super::bind::res_block(false)).ok_or("UMA: res")?; // the pipeline's own root signature when it has static samplers let own = super::real::pso_root_signature(real).or(((*p).rs != 0).then_some((*p).rs)).map(|r| r as *mut c_void); match own.as_ref().and_then(|r| ID3D12RootSignature::from_raw_borrowed(r)) { diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 97d6600..2d9dc8e 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -9,11 +9,10 @@ //! queue signals it, and a worker thread does the writes, in submission order, when the GPU is //! there – what bottom of pipe means. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::ffi::c_void; use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; -use std::time::{Duration, Instant}; +use std::sync::{mpsc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::HANDLE; @@ -34,6 +33,29 @@ pub(super) enum Write { /// the GPU would see them (`title_textures::read_memory`: a GPU view's pages where the CPU /// has them), to `dst` in the title's own memory Copy { dst: usize, src: usize, len: usize }, + /// Local fix: `len` bytes the GPU copied into a persistently mapped READBACK buffer (`src`: + /// its mapped address), written to `dst` in the title's own memory once the queue is past + /// the copy – CopyMemoryToMemoryX whose source is a PC resource standing for title memory. + /// `_src` (that resource) stays until the copy ran: its last Release is then held against + /// a mark taken after the list was submitted (`late_release`). + ReadbackCopy { dst: usize, src: usize, len: usize, _buf: ID3D12Resource, _src: ID3D12Resource }, + /// Local fix: a title texture's subresources the GPU copied into a mapped READBACK buffer + /// (`mapped`, one D3D12 footprint each, mip-major within an array slice), laid out again as + /// the console has the texture in memory (`tex`), of which `len` bytes from `skip` go to `dst`. + TextureReadback { + dst: usize, + len: usize, + skip: usize, + mapped: usize, + footprints: Vec, + mips: u32, + array: u32, + side: u32, + tex: std::sync::Arc, + _buf: ID3D12Resource, + /// the texture copied out of (kept as `ReadbackCopy` keeps its source) + _src: ID3D12Resource, + }, } /// copies done so far, and those whose source had no memory for some of its bytes (zeros) @@ -44,13 +66,54 @@ pub fn copies() -> (u64, u64) { (COPIES[0].load(Ordering::Relaxed), COPIES[1].load(Ordering::Relaxed)) } +/// local diagnostic: where the worker is (0 waiting for a job, 1 waiting for the fence, +/// 2 immediate/readback writes, 3 copy: writable(), 4 copy: read_memory(), 5 copy: memcpy), +/// since when (ms of the log clock), and job counters – read by `probe_line`. +static PHASE: AtomicU32 = AtomicU32::new(0); +static PHASE_SINCE_MS: AtomicU64 = AtomicU64::new(0); +static JOBS_IN: AtomicU64 = AtomicU64::new(0); +static JOBS_DONE: AtomicU64 = AtomicU64::new(0); +static LAST_WANTED: AtomicU64 = AtomicU64::new(0); +static LAST_SEEN: AtomicU64 = AtomicU64::new(0); +static LAST_COPY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +fn phase(p: u32) { + PHASE.store(p, Ordering::Relaxed); + PHASE_SINCE_MS.store((crate::log::uptime() * 1000.0) as u64, Ordering::Relaxed); +} + +/// One line for the local probe: the worker's phase and how long it has been in it. +pub(super) fn probe_line() -> String { + let now = (crate::log::uptime() * 1000.0) as u64; + let since = PHASE_SINCE_MS.load(Ordering::Relaxed); + let names = ["idle", "fence-wait", "writes", "copy:writable", "copy:read_memory", "copy:memcpy"]; + let p = PHASE.load(Ordering::Relaxed) as usize; + format!( + "cpu_writes: {} for {:.1}s | jobs in {} done {} | fence wanted {} seen {} | copies {} | last copy {:#x}<-{:#x} ({:#x} B)", + names.get(p).copied().unwrap_or("?"), + now.saturating_sub(since) as f64 / 1000.0, + JOBS_IN.load(Ordering::Relaxed), + JOBS_DONE.load(Ordering::Relaxed), + LAST_WANTED.load(Ordering::Relaxed), + LAST_SEEN.load(Ordering::Relaxed), + COPIES[0].load(Ordering::Relaxed), + LAST_COPY[0].load(Ordering::Relaxed), + LAST_COPY[1].load(Ordering::Relaxed), + LAST_COPY[2].load(Ordering::Relaxed), + ) +} + struct Job { + /// the queue the submission went to (its worker's key) queue: usize, fence: ID3D12Fence, value: u64, writes: Vec, - submitted: Instant, - warned: bool, + /// signalled to `value` by the worker once the writes are done (jobs with a CPU copy, see + /// `copy_ordered`) + done: Option, + /// the submission's lists and their last work, for a wait past `WAIT_MS` (`XCL_TRACE_GPU_STALL=1`; + /// empty without it) lists: Vec, } @@ -61,87 +124,147 @@ unsafe impl Send for Job {} struct QueueFence { fence: ID3D12Fence, value: u64, + /// what the queue waits on after a submission with a CPU copy (made on first use) + done: Option, +} + +/// Local fix (`XCL_CPU_COPY_ORDERED`, on unless "0"): a submission whose lists carry a +/// CopyMemoryToMemoryX done by the CPU makes its queue wait – on the GPU timeline, right after +/// XCL's own signal – until the worker has done the copy. Without it the title saw its own +/// fence complete (the queue's later Signal) before the worker had written the destination, read +/// it too early and waited for ever: GTA VI 1.0.2.1 stopped submitting at its first loading +/// screen, right after "copied by the CPU once the GPU is there". +fn copy_ordered() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_CPU_COPY_ORDERED").map_or(true, |v| v.trim() != "0")) } unsafe impl Send for QueueFence {} static FENCES: Mutex>> = Mutex::new(None); -const STALL_AFTER: Duration = Duration::from_secs(10); -static INCOMING: Mutex> = Mutex::new(Vec::new()); +/// how long the worker waits for one submission before it says so in the log (it goes on +/// waiting: writing early made the title see its work done and free what the GPU still used) +const WAIT_MS: u32 = 10_000; -fn worker_event() -> usize { - static EVENT: OnceLock = OnceLock::new(); - *EVENT.get_or_init(|| unsafe { - let event = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize; - if event == 0 { - crate::xlog_error!("D3D12.X: could not create the bottom-of-pipe completion event"); - return 0; +/// Wait until `fence` reaches `value`. Every wake is checked against the fence: the event is +/// one per worker, and a completion asked for before (a wait that timed out) can set it late, +/// which let a later job write before its own submission had run. A removed device (the fence +/// reads all ones) or an event that cannot be armed ends the wait. Past the first `WAIT_MS`, with +/// `XCL_TRACE_GPU_STALL=1`, the queue's waits and the submission's lists are logged once (upstream +/// 9db0989). +unsafe fn wait_for_fence(fence: &ID3D12Fence, value: u64, event: windows_sys::Win32::Foundation::HANDLE, writes: usize, queue: usize, lists: &[String]) { + let mut waited_ms = 0u64; + loop { + let now = fence.GetCompletedValue(); + if now >= value { + return; } - let spawned = std::thread::Builder::new().name("xcl-cpu-writes".into()).spawn(move || complete_jobs(event)); - if let Err(e) = spawned { - crate::xlog_error!("D3D12.X: no thread for the writes after the GPU: {e}"); - windows_sys::Win32::Foundation::CloseHandle(event as _); - return 0; + if fence.SetEventOnCompletion(value, HANDLE(event as *mut c_void)).is_err() { + crate::xlog_warn!("D3D12.X: writes after the GPU: SetEventOnCompletion failed (fence at {now}, wanted {value}) – done now"); + return; } - event - }) -} - -unsafe fn complete_jobs(event: usize) { - let mut pending: Vec = Vec::new(); - let mut completed = HashMap::new(); - let mut stalled = HashSet::new(); - loop { - for job in std::mem::take(&mut *INCOMING.lock().unwrap()) { - if job.fence.GetCompletedValue() < job.value { - let _ = job.fence.SetEventOnCompletion(job.value, HANDLE(event as _)); + if th::WaitForSingleObject(event, WAIT_MS) == windows_sys::Win32::Foundation::WAIT_TIMEOUT && fence.GetCompletedValue() < value { + waited_ms += WAIT_MS as u64; + static LATE: AtomicU64 = AtomicU64::new(0); + let k = LATE.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: writes after the GPU: a queue has not got to its submission after {} s (fence at {}, wanted {value}; {writes} writes) – still waiting ({k} such waits so far)", + waited_ms / 1000, + fence.GetCompletedValue() + ); } - pending.push(job); - } - completed.clear(); - stalled.clear(); - pending.retain_mut(|job| { - // One sample per queue keeps its writes in order if the fence advances mid-scan. - let done = *completed.entry(job.queue).or_insert_with(|| job.fence.GetCompletedValue()); - if done == u64::MAX { - return false; // device removed: its readbacks are invalid + if waited_ms == WAIT_MS as u64 && super::list_x::trace_gpu_stall() { + super::list_x::log_gpu_stall(queue); + for list in lists { + crate::xlog_warn!("D3D12.X: submission for fence {value}: {list}"); + } } - if done < job.value { - if stalled.insert(job.queue) && !job.warned && job.submitted.elapsed() >= STALL_AFTER { - job.warned = true; - crate::xlog_warn!("D3D12.X: bottom-of-pipe writes still pending (fence at {done}, wanted {}; {} writes)", job.value, job.writes.len()); - if super::list_x::trace_gpu_stall() { - super::list_x::log_gpu_stall(job.queue); - for list in &job.lists { - crate::xlog_warn!("D3D12.X: submission for fence {}: {list}", job.value); + } + } +} + +/// The worker of `queue`'s jobs: one per queue, so a queue that waits (on the GPU) for another +/// queue's copy is never held back by a job of its own queue's – one worker for every queue +/// made such a wait last until the 10 s timeout wrote early. +fn worker(queue: usize) -> Option> { + static W: Mutex>>> = Mutex::new(None); + let mut g = W.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + if let Some(tx) = m.get(&queue) { + return Some(tx.clone()); + } + let (tx, rx) = mpsc::channel::(); + let spawned = std::thread::Builder::new().name(format!("xcl-cpu-writes-{queue:x}")).spawn(move || unsafe { + let event = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); + for job in rx { + phase(1); + LAST_WANTED.store(job.value, Ordering::Relaxed); + wait_for_fence(&job.fence, job.value, event, job.writes.len(), job.queue, &job.lists); + let seen = job.fence.GetCompletedValue(); + LAST_SEEN.store(seen, Ordering::Relaxed); + phase(2); + // a removed device (the fence reads all ones): its readbacks are invalid – the writes + // are not done (upstream 9db0989) – and the title is stopped here with the report, + // as at its next submit or present (`real::stop_if_device_removed`): a title waiting + // on a marker of this job would not get there. (A device that still answers: the + // writes are left out, as upstream does.) + let writes: &[Write] = if seen == u64::MAX { + super::real::stop_if_device_removed(); + static REMOVED: std::sync::Once = std::sync::Once::new(); + REMOVED.call_once(|| crate::xlog_warn!("D3D12.X: writes after the GPU: the device was removed – the writes of its submissions are not done ({} in the first)", job.writes.len())); + &[] + } else { + &job.writes + }; + for w in writes { + match w { + Write::Immediate(va, words) => write_now(*va, words), + Write::ReadbackU64 { va, src, .. } => { + let value = (*(*src as *const AtomicU64)).load(Ordering::Acquire); + write_u64_now(*va, value); + } + Write::Copy { dst, src, len } => copy_now(*dst, *src, *len), + Write::TextureReadback { dst, len, skip, mapped, footprints, mips, array, side, tex, .. } => { + texture_readback(*dst, *len, *skip, *mapped, footprints, *mips, *array, *side, tex); + } + Write::ReadbackCopy { dst, src, len, .. } => { + if writable(*dst, *len) { + std::ptr::copy_nonoverlapping(*src as *const u8, *dst as *mut u8, *len); + let n = COPIES[0].fetch_add(1, Ordering::Relaxed); + if n < 4 { + let data = std::slice::from_raw_parts(*src as *const u8, *len); + let nonzero = data.iter().filter(|&&b| b != 0).count(); + let head: String = data.iter().take(32).map(|b| format!("{b:02x}")).collect(); + crate::xlog_info!("D3D12.X: GPU copy read back into {:#x} ({:#x} B, {nonzero} non-zero bytes): {head}", *dst, *len); + } + } } } } - return true; - } - for w in &job.writes { - match w { - Write::Immediate(va, words) => write_now(*va, words), - Write::ReadbackU64 { va, src, .. } => { - let value = (*(*src as *const AtomicU64)).load(Ordering::Acquire); - write_u64_now(*va, value); - } - Write::Copy { dst, src, len } => copy_now(*dst, *src, *len), + if let Some(done) = &job.done { + let _ = done.Signal(job.value); } + JOBS_DONE.fetch_add(1, Ordering::Relaxed); + phase(0); } - false }); - // Both new jobs and GPU completion wake the worker. Poll if a host drops a fence event. - th::WaitForSingleObject(event as _, if pending.is_empty() { th::INFINITE } else { 100 }); + if let Err(e) = spawned { + crate::xlog_error!("D3D12.X: no thread for the writes after the GPU: {e}"); + return None; } + m.insert(queue, tx.clone()); + Some(tx) } -fn enqueue(job: Job) { - let event = worker_event(); - INCOMING.lock().unwrap().push(job); - if event != 0 { - unsafe { th::SetEvent(event as _) }; +/// local diagnostic: bottom-of-pipe writes dropped because their memory was not committed and +/// writable (the title then never sees its marker), logged for the first few +static DROPPED: AtomicU64 = AtomicU64::new(0); +fn note_dropped(kind: &str, va: usize, state: u32, protect: u32) { + let k = DROPPED.fetch_add(1, Ordering::Relaxed); + if k < 16 || k.is_power_of_two() { + crate::xlog_warn!("D3D12.X: [diag] bottom-of-pipe {kind} to {va:#x} dropped (#{k}): state {state:#x} protect {protect:#x}"); } } @@ -150,9 +273,11 @@ unsafe fn write_now(va: usize, words: &[u32]) { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { + note_dropped("dwords", va, m.State, m.Protect); return; } if m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 || (m.BaseAddress as usize + m.RegionSize) < va + 4 * words.len() { + note_dropped("dwords", va, m.State, m.Protect); return; } for (i, &w) in words.iter().enumerate() { @@ -166,21 +291,87 @@ unsafe fn write_u64_now(va: usize, value: u64) { let Some(end) = va.checked_add(8) else { return }; let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { + note_dropped("u64", va, m.State, m.Protect); return; } if m.Protect & PAGE_GUARD != 0 || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 || (m.BaseAddress as usize).saturating_add(m.RegionSize) < end { + note_dropped("u64", va, m.State, m.Protect); return; } (*(va as *const AtomicU64)).store(value, Ordering::Release); } +/// The texture the GPU copied out (`TextureReadback`) in the console's layout, then `len` bytes of +/// it from `skip` to `dst`. +#[allow(clippy::too_many_arguments)] +unsafe fn texture_readback(dst: usize, len: usize, skip: usize, mapped: usize, footprints: &[D3D12_PLACED_SUBRESOURCE_FOOTPRINT], mips: u32, array: u32, side: u32, tex: &crate::hle::xg::Texture) { + if !writable(dst, len) { + return; + } + let size = tex.size() as usize; + let Some(end) = skip.checked_add(len) else { return }; + if end > size { + return; + } + let mut img = vec![0u8; size]; + let side = side.max(1) as usize; + for slice in 0..array as usize { + for mip in 0..mips as usize { + let Some(fp) = footprints.get(mip + slice * mips as usize) else { continue }; + let w = (fp.Footprint.Width as usize).div_ceil(side); + let h = (fp.Footprint.Height as usize).div_ceil(side); + if w == 0 || h == 0 { + continue; + } + let pitch = fp.Footprint.RowPitch as usize; + // bytes per element: what a footprint row holds per element (rows are padded to 256) + let e = pitch / w; + let e = [16usize, 8, 4, 2, 1].into_iter().find(|&b| b <= e && w * b <= pitch).unwrap_or(1); + let base = mapped + fp.Offset as usize; + for y in 0..h { + let row = (base + y * pitch) as *const u8; + for x in 0..w { + let o = tex.element_offset(mip, x, y, slice) as usize; + if o + e <= size { + std::ptr::copy_nonoverlapping(row.add(x * e), img.as_mut_ptr().add(o), e); + } + } + } + } + } + std::ptr::copy_nonoverlapping(img.as_ptr().add(skip), dst as *mut u8, len); + let n = COPIES[0].fetch_add(1, Ordering::Relaxed); + if n < 4 { + let nonzero = img[skip..end].iter().filter(|&&b| b != 0).count(); + let head: String = img[skip..end].iter().take(32).map(|b| format!("{b:02x}")).collect(); + crate::xlog_info!("D3D12.X: texture read back into {dst:#x} ({len:#x} B from +{skip:#x} of {size:#x}; {nonzero} non-zero bytes): {head}"); + } +} + /// `len` bytes from `src` as the GPU would see them to `dst`, if `dst` is still writable. unsafe fn copy_now(dst: usize, src: usize, len: usize) { + LAST_COPY[0].store(dst as u64, Ordering::Relaxed); + LAST_COPY[1].store(src as u64, Ordering::Relaxed); + LAST_COPY[2].store(len as u64, Ordering::Relaxed); + phase(3); if !writable(dst, len) { + phase(2); return; } + phase(4); let (data, all) = super::title_textures::read_memory(src, len); + phase(5); + { + static SHOWN: AtomicU64 = AtomicU64::new(0); + if SHOWN.fetch_add(1, Ordering::Relaxed) < 8 { + let nonzero = data.iter().filter(|&&b| b != 0).count(); + let head: String = data.iter().take(64).map(|b| format!("{b:02x}")).collect(); + let before: String = std::slice::from_raw_parts(dst as *const u8, len.min(32)).iter().map(|b| format!("{b:02x}")).collect(); + crate::xlog_info!("D3D12.X: [diag] CPU copy {src:#x} → {dst:#x} ({len:#x} B): all source present {all}, {nonzero} non-zero bytes; dst before {before}; data {head}"); + } + } std::ptr::copy_nonoverlapping(data.as_ptr(), dst as *mut u8, len); + phase(2); let n = COPIES[0].fetch_add(1, Ordering::Relaxed); if !all && COPIES[1].fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: CopyMemoryToMemoryX {src:#x} → {dst:#x} ({len:#x} bytes), copy #{n} by the CPU: part of the source has no memory (zeros there)"); @@ -199,13 +390,19 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { && m.BaseAddress as usize + m.RegionSize >= va + bytes } -/// `writes` of lists just submitted to `queue`: done when the GPU has finished them. +/// `writes` of lists just submitted to `queue`: done when the GPU has finished them. `lists`: the +/// submission's lists for a wait that lasts (`XCL_TRACE_GPU_STALL=1`; empty without it). pub(super) unsafe fn after(queue: *mut c_void, writes: Vec, lists: Vec) { if writes.is_empty() || queue.is_null() { return; } let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; - { + let ordered = copy_ordered() && writes.iter().any(|w| matches!(w, Write::Copy { .. } | Write::ReadbackCopy { .. } | Write::TextureReadback { .. })); + // (the job goes to its worker under FENCES, right after its value: two threads submitting to + // one queue at once sent their jobs the other way round, and the worker waited for the later + // value while the queue waited, on the GPU, for the earlier job's copy) + let Some(tx) = worker(queue as usize) else { return }; + let (writes_n, sent) = { let mut g = FENCES.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); let entry = match m.entry(queue as usize) { @@ -217,17 +414,40 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec, lists: Vec(0, D3D12_FENCE_FLAG_NONE) else { return }; - v.insert(QueueFence { fence, value: 0 }) + v.insert(QueueFence { fence, value: 0, done: None }) } }; + if ordered && entry.done.is_none() { + let mut dev: Option = None; + if q.GetDevice(&mut dev).is_ok() { + if let Some(dev) = dev { + entry.done = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok(); + } + } + } entry.value += 1; if q.Signal(&entry.fence, entry.value).is_err() { return; } - static FIRST: std::sync::Once = std::sync::Once::new(); - FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({} in the first submission)", writes.len())); - // Signal and enqueue under the same lock so concurrent submits cannot reorder the writes. - enqueue(Job { queue: queue as usize, fence: entry.fence.clone(), value: entry.value, writes, submitted: Instant::now(), warned: false, lists }); + let done = if ordered { entry.done.clone() } else { None }; + if let Some(d) = &done { + // the queue goes on (and the title's own later signals complete) only once the + // worker has done this submission's copy + crate::waitwatch::note_gpu_wait("cpu copy landed", queue as usize, d, entry.value); + if q.Wait(d, entry.value).is_err() { + crate::xlog_warn!("D3D12.X: CPU copy: the queue cannot wait for it (Wait failed) – it may be seen late"); + } else { + static FIRST_ORDERED: std::sync::Once = std::sync::Once::new(); + FIRST_ORDERED.call_once(|| crate::xlog_info!("D3D12.X: CPU copies are ordered on their queue: its later work waits until the copy has landed (XCL_CPU_COPY_ORDERED=0: not)")); + } + } + let n = writes.len(); + JOBS_IN.fetch_add(1, Ordering::Relaxed); + (n, tx.send(Job { queue: queue as usize, fence: entry.fence.clone(), value: entry.value, writes, done, lists }).is_ok()) + }; + static FIRST: std::sync::Once = std::sync::Once::new(); + if sent { + FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({writes_n} in the first submission)")); } } @@ -267,8 +487,12 @@ mod tests { } } + /// (upstream 9db0989) A queue whose fence has not got to its submission keeps that submission's + /// writes pending – never written early – while another queue's land: each queue has its own + /// worker (`worker`). #[test] fn stalled_queue_keeps_writes_pending_without_blocking_other_queues() { + use std::time::{Duration, Instant}; unsafe { let mut dev: Option = None; if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { @@ -281,15 +505,16 @@ mod tests { let cell = || Box::leak(Box::new(AtomicU32::new(0))) as &AtomicU32; let first = cell(); let second = cell(); + // (each fence stands for a queue of its own: the worker's key) let job = |fence: &ID3D12Fence, at: &AtomicU32| Job { queue: fence.as_raw() as usize, fence: fence.clone(), value: 1, writes: vec![Write::Immediate(at.as_ptr() as usize, vec![1])], - submitted: Instant::now() - STALL_AFTER, - warned: false, + done: None, lists: Vec::new(), }; + let enqueue = |j: Job| worker(j.queue).expect("no worker").send(j).unwrap(); enqueue(job(&held, first)); enqueue(job(&done, second)); let wait = |at: &AtomicU32| { @@ -310,6 +535,92 @@ mod tests { } } + /// A submission whose fence reads all ones – what a removed device's fences read – while the + /// device still answers (`real::stop_if_device_removed` finds nothing to stop): its writes are + /// not done (upstream 9db0989), its `done` fence is still signalled, so a queue that waits on + /// it goes on, and the queue's next job is done as usual. + #[test] + fn a_fence_at_all_ones_leaves_the_writes_out_and_still_signals_done() { + use std::time::{Duration, Instant}; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + fence.Signal(u64::MAX).unwrap(); + assert_eq!(fence.GetCompletedValue(), u64::MAX); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let next_fence: ID3D12Fence = dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).unwrap(); + let marker = Box::leak(Box::new(AtomicU32::new(0))) as &AtomicU32; + let next = Box::leak(Box::new(AtomicU32::new(0))) as &AtomicU32; + // (the fence stands for a queue of its own: the worker's key) + let key = fence.as_raw() as usize; + let tx = worker(key).expect("no worker"); + let job = |fence: &ID3D12Fence, at: &AtomicU32, word: u32, done: Option| Job { + queue: key, + fence: fence.clone(), + value: 1, + writes: vec![Write::Immediate(at.as_ptr() as usize, vec![word])], + done, + lists: Vec::new(), + }; + tx.send(job(&fence, marker, 1, Some(done.clone()))).unwrap(); + tx.send(job(&next_fence, next, 7, None)).unwrap(); + let start = Instant::now(); + while next.load(Ordering::Acquire) == 0 { + assert!(start.elapsed() < Duration::from_secs(5), "the queue's next job was never done"); + std::thread::sleep(Duration::from_millis(1)); + } + assert_eq!(done.GetCompletedValue(), 1, "done signalled for the job at all ones"); + assert_eq!(marker.load(Ordering::Acquire), 0, "no write for a fence at all ones"); + assert_eq!(next.load(Ordering::Acquire), 7); + } + } + + /// The title's own signal on the queue, made right after a submission with a CPU copy, + /// completes only once the copy has landed (`copy_ordered`) – what GTA VI 1.0.2.1 relies on + /// when it reads the destination as soon as its fence says the work is done. + #[test] + fn a_titles_later_signal_completes_after_the_copy() { + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let title_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + for round in 1..=32u64 { + // a 16 KiB header, as the title copies it, with a pattern that differs per round + let from: Vec = (0..0x4000u32).map(|i| (i as u64 * 31 + round * 7) as u8).collect(); + let to = vec![0u8; 0x4000]; + let (src, dst) = (from.as_ptr() as usize, to.as_ptr() as usize); + after(q.as_raw(), vec![Write::Copy { dst, src, len: from.len() }], Vec::new()); + q.Signal(&title_fence, round).unwrap(); + let t = std::time::Instant::now(); + while title_fence.GetCompletedValue() < round { + assert!(t.elapsed().as_secs() < 15, "the title's signal never completed (round {round})"); + std::thread::yield_now(); + } + assert!(to == from, "round {round}: the title's signal completed before the copy landed"); + } + } + } + /// A ReadbackU64 write copies the 64-bit value from the mapped readback buffer after the queue finishes. #[test] fn readback_u64_lands_after_the_queue() { diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 621991f..f0e096c 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -225,6 +225,7 @@ pub(super) unsafe extern "system" fn create_shader_cache_session_x( /// the desc is a PC D3D12_GRAPHICS_PIPELINE_STATE_DESC with console shaders; the extensions /// are not modelled pub(super) unsafe extern "system" fn create_graphics_pso_x(this: *mut c_void, desc: *const c_void, extensions: u32, _ext: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _xcl_api = crate::waitwatch::api("device_x::create_graphics_pso_x"); static N: AtomicU64 = AtomicU64::new(0); if extensions != 0 && once(&N, 1) { crate::xlog_info!("D3D12.X: CreateGraphicsPipelineStateX with {extensions} extension(s) – not modelled"); @@ -489,6 +490,22 @@ pub(super) fn depth_bias_cache_len() -> usize { DEPTH_BIAS_PSOS.lock().unwrap().as_ref().map_or(0, HashMap::len) } +/// (tests) `derived` as the cached depth-bias variant of (`base`, `bias`) – Some – or that entry +/// taken out again without releasing it – None (a test's fake pipeline is never released). +#[cfg(test)] +pub(super) fn set_depth_bias_pso_for_test(base: usize, bias: DepthBias, derived: Option) { + let mut g = DEPTH_BIAS_PSOS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + match derived { + Some(d) => { + m.insert((base, bias), d); + } + None => { + m.remove(&(base, bias)); + } + } +} + #[cfg(test)] pub(super) fn register_test_base(pso: usize, dynamic_depth_bias: bool, static_bias: DepthBias) { let base = Arc::new(Base { @@ -657,6 +674,7 @@ pub(super) unsafe extern "system" fn create_derived_pso_x(this: *mut c_void, bas /// device #86 CreatePipelineState(stream desc, riid, pipeline) pub(super) unsafe extern "system" fn create_pipeline_state_x(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _xcl_api = crate::waitwatch::api("device_x::create_pipeline_state_x"); real::dev_create_pipeline_state(this, desc, riid, ppv) } @@ -1036,6 +1054,7 @@ fn note_alias(va: usize, x: &[u8; 0x38]) { /// memory (placed in its UMA heap); a texture gets a PC texture kept in step with the memory /// (`title_textures`: detiled as the console lays it out, uploaded again after CPU writes). pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, va: u64, desc: *const u8, state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _xcl_api = crate::waitwatch::api("device_x::create_placed_resource_x"); static N: AtomicU64 = AtomicU64::new(0); if desc.is_null() || ppv.is_null() || !crate::gpu::shader::readable(desc as usize, 0x38) { return E_INVALIDARG; @@ -1043,6 +1062,16 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); let d = pc_resource_desc(&x); let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; + if crate::hle::kernelx::traced_range(va as usize, 1) { + let u64at = |o: usize| u64::from_le_bytes(d[o..o + 8].try_into().unwrap()); + crate::xlog_info!( + "[trace] CreatePlacedResourceX at {va:#x}: dimension {}, width {}, state {state:#x}; console desc {:02x?}; from {}", + u32::from_le_bytes(d[0..4].try_into().unwrap()), + u64at(0x10), + &x[..0x38], + crate::hle::kernelx::callers(1) + ); + } note_alias(va as usize, &x); // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the // PC's: the PC refused the resource (E_INVALIDARG) and the title threw @@ -1059,12 +1088,15 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } } // render targets, depth buffers, UAV textures: in video memory, aliased by address (`vram`); - // sampled textures: on the same shared 64 KiB pages when tiled resources allow, else committed + // sampled textures: on the same shared 64 KiB pages when tiled resources allow, else – in a + // GPU view, `lazy_tex` – reserved with tiles where the title's memory is, else committed let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); let mut placed_hr = None; + let mut made = Made::Committed; + let mut pc_bytes = 0u64; + let console_bytes = if buffer { None } else { crate::hle::xg::Texture::new(&x).ok().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0) }; if !buffer { let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); - let console_bytes = crate::hle::xg::Texture::new(&x).ok().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { if hr >= 0 && !(*ppv).is_null() { @@ -1072,11 +1104,29 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, super::title_textures::retire_overlapping(va as usize, bytes as usize); } real::note_title_address(*ppv as usize, va as usize); + note_made(Made::Arena, console_bytes.unwrap_or(0), 0); + made_as(MadeAs { how: Made::Arena, pc: 0, kept: false }); } return hr; } + made = Made::OwnedCommitted; + if super::title_textures::census_on() { + pc_bytes = real::pc_size(this, &d); + } } else { placed_hr = super::vram::place_pages(this, va as usize, &pc, state, clear, console_bytes, riid, ppv); + if placed_hr.is_some() { + made = Made::Pages; + } else { + // (the PC's size: what a lazy texture's tiles are weighed against, and the census) + if super::lazy_tex::enabled() || super::title_textures::census_on() { + pc_bytes = real::pc_size(this, &d); + } + placed_hr = super::lazy_tex::create(this, va as usize, &pc, &x, pc_bytes, state, clear, riid, ppv, &|a, n| super::title_textures::pages_present(a, n)); + if placed_hr.is_some() { + made = Made::Lazy; + } + } } } let hr = match placed_hr { @@ -1088,24 +1138,34 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, }; 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)) { + note_made(made, console_bytes.unwrap_or(0), pc_bytes); + match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32), pc_bytes) { Ok(()) => { real::note_title_address(*ppv as usize, va as usize); + note_source(console_bytes.unwrap_or(0)); + made_as(MadeAs { how: made, pc: pc_bytes, kept: true }); return hr; } - Err(e) if once(&M, 4) => { - let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); - crate::xlog_warn!( - "D3D12.X: CreatePlacedResourceX texture at {va:#x} (dimension {} {}x{}x{}, {} mips, format {}, {} samples, layout {:#x}, flags {:#x}): not kept in step with the memory ({e})", - u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u16::from_le_bytes(x[0x1C..0x1E].try_into().unwrap()), - u16::from_le_bytes(x[0x1E..0x20].try_into().unwrap()), u(0x20), u(0x24), u(0x2C), u(0x30) - ) + Err(e) => { + note_made(Made::NotKept, console_bytes.unwrap_or(0), pc_bytes); + made_as(MadeAs { how: made, pc: pc_bytes, kept: false }); + if once(&M, 4) { + let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + crate::xlog_warn!( + "D3D12.X: CreatePlacedResourceX texture at {va:#x} (dimension {} {}x{}x{}, {} mips, format {}, {} samples, layout {:#x}, flags {:#x}): not kept in step with the memory ({e})", + u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u16::from_le_bytes(x[0x1C..0x1E].try_into().unwrap()), + u16::from_le_bytes(x[0x1E..0x20].try_into().unwrap()), u(0x20), u(0x24), u(0x2C), u(0x30) + ) + } } - Err(_) => {} } } if hr >= 0 && !(*ppv).is_null() { real::note_title_address(*ppv as usize, va as usize); + // (a buffer reaches this point only with a PC resource of its own: the census, `outside`) + if buffer { + super::outside::note_placed(*ppv as usize, va as usize, &d); + } } if hr < 0 || once(&N, 4) { let w = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); @@ -1124,8 +1184,126 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, /// device #133 (a retail game): CreatePlacedResourceX with a barrier layout (D3D12_BARRIER_LAYOUT, seen: /// 0xFFFFFFFF = undefined for a buffer) in the initial state's place. pub(super) unsafe extern "system" fn create_placed_resource_layout_x(this: *mut c_void, va: u64, desc: *const u8, layout: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _xcl_api = crate::waitwatch::api("device_x::create_placed_resource_layout_x"); real::note_newer_device_method(133); - create_placed_resource_x(this, va, desc, layout_state(layout), clear, riid, ppv) + with_source(Source::Layout, || create_placed_resource_x(this, va, desc, layout_state(layout), clear, riid, ppv)) +} + +/// How a title texture placed in its memory was made (`creation_stats`; the view census). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Made { + /// sampled: committed + Committed, + /// sampled: reserved with tiles where the title's memory is (`lazy_tex`) + Lazy, + /// sampled: on shared pages (`vram::place_pages`) + Pages, + /// GPU-owned: in an arena (`vram::place`) + Arena, + /// GPU-owned: committed (no arena for it) + OwnedCommitted, + /// of those above, not kept in step with the memory (`title_textures::register` refused it: + /// render targets, depth buffers, the console's 116 / 117 floats) + NotKept, +} + +/// Which method of the title's made a resource (`with_source`). +#[derive(Clone, Copy, PartialEq)] +pub(super) enum Source { + /// device #44 CreatePlacedResourceX + Placed, + /// device #133, the same with a barrier layout + Layout, + /// a view by address (device #70 / #71, `real::resource_at`) + ViewAt, + /// CreateCommittedResource of a texture in console memory (`real::place_console_texture`) + Committed, +} + +thread_local! { + static SOURCE: std::cell::Cell = const { std::cell::Cell::new(Source::Placed) }; + /// how the last texture `create_placed_resource_x` made on this thread was made, while the view + /// census is on (`made_as`): `real::resource_at` takes it after its call (beside `SOURCE`, on + /// the same path) + static LAST_MADE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// `f` making resources for the title's method `s`. +pub(super) fn with_source(s: Source, f: impl FnOnce() -> R) -> R { + let was = SOURCE.with(|c| c.replace(s)); + let r = f(); + SOURCE.with(|c| c.set(was)); + r +} + +/// How `create_placed_resource_x` made a texture (the view census: what a views-by-address one +/// is, `real::ViewTexture`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct MadeAs { + pub how: Made, + /// the PC's committed size of it (0: not known – arenas, pages) + pub pc: u64, + /// kept in step with the memory (`title_textures::register` took it) + pub kept: bool, +} + +/// The texture just made was made as `m`: kept for this thread's caller while the view census is +/// on – nothing otherwise (no thread-local on the title's creation path then). +fn made_as(m: MadeAs) { + if super::view_census::on() { + LAST_MADE.with(|c| c.set(Some(m))); + } +} + +/// How the texture `create_placed_resource_x` last made on this thread was made – taken: the next +/// take gives None until another is made (None: none since, or the view census is off). +pub(super) fn take_last_made() -> Option { + LAST_MADE.with(|c| c.take()) +} + +/// (count, console bytes, PC bytes) by `Made` +static MADE: [[AtomicU64; 3]; 6] = [const { [const { AtomicU64::new(0) }; 3] }; 6]; +/// (count, console bytes) of the textures kept in step by `Source` +static SOURCES: [[AtomicU64; 2]; 4] = [const { [const { AtomicU64::new(0) }; 2] }; 4]; + +fn note_made(m: Made, console: u64, pc: u64) { + let k = &MADE[m as usize]; + k[0].fetch_add(1, Ordering::Relaxed); + k[1].fetch_add(console, Ordering::Relaxed); + k[2].fetch_add(pc, Ordering::Relaxed); +} + +fn note_source(console: u64) { + let k = &SOURCES[SOURCE.with(|c| c.get()) as usize]; + k[0].fetch_add(1, Ordering::Relaxed); + k[1].fetch_add(console, Ordering::Relaxed); +} + +/// The title textures placed in its memory so far by how they were made and by the method that +/// made them, as text (`XCL_ACTIVITY`). +pub fn creation_stats() -> String { + let l = |a: &AtomicU64| a.load(Ordering::Relaxed); + let m = |k: Made| { + let x = &MADE[k as usize]; + format!("{} ({} MB, {} MB on the PC)", l(&x[0]), l(&x[1]) >> 20, l(&x[2]) >> 20) + }; + let s = |k: Source| { + let x = &SOURCES[k as usize]; + format!("{} ({} MB)", l(&x[0]), l(&x[1]) >> 20) + }; + format!( + "title textures made: sampled committed {}, lazy {}, on pages {}; GPU-owned in arenas {}, committed {}; of those not kept in step {}; kept in step from #44 {}, #133 {}, views by address {}, committed by the title {}", + m(Made::Committed), + m(Made::Lazy), + m(Made::Pages), + m(Made::Arena), + m(Made::OwnedCommitted), + m(Made::NotKept), + s(Source::Placed), + s(Source::Layout), + s(Source::ViewAt), + s(Source::Committed) + ) } /// The resource state (D3D12_RESOURCE_STATES) of a D3D12_BARRIER_LAYOUT (undefined: COMMON). @@ -1201,6 +1379,27 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi super::indirect::register(sig, stride, &list); } else if matches!(list.as_slice(), [a] if a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32) { super::bind::note_dispatch_mesh_signature(sig, stride); + } else if matches!(list.as_slice(), [a] if a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32) { + // (its group counts are checked before the GPU runs them: `indirect::sanitize`) + super::indirect::note_plain_dispatch(sig, stride); + super::indirect::warm_up(this as usize); + } else if let [a] = list.as_slice() { + // (a translated draw's arguments outside unified memory are checked before the GPU + // runs them: `indirect::draw_check`) + let indexed = a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32; + if indexed || a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW.0 as u32 { + super::indirect::note_plain_draw(sig, stride, indexed); + super::indirect::warm_up(this as usize); + } + } else if list.iter().any(|a| a[0] <= D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32) { + // a draw with vertex or index buffer views among its arguments: not checked (the first 8 told) + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!( + "D3D12.X: a draw command signature with other arguments (stride {stride}, argument types {:?}): its ExecuteIndirect are not checked", + list.iter().map(|a| a[0]).collect::>() + ); + } } } else if needs_root { super::bind::note_root_changing_signature(sig); @@ -1213,6 +1412,26 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi mod tests { use super::*; + /// How a texture was made goes to this thread's caller once (`take_last_made`: a second take + /// gives none – a later creation that says nothing never hands over an older one), and only + /// while the view census is on (`made_as`; the census-on case in a process of its own with + /// `EXTRA_ENV=XCL_ACTIVITY=1`) (M17). + #[test] + fn a_creations_made_record_is_handed_to_its_caller_once() { + let m = MadeAs { how: Made::Lazy, pc: 0x7A1E_4000, kept: true }; + let _ = take_last_made(); + LAST_MADE.with(|c| c.set(Some(m))); + assert_eq!(take_last_made(), Some(m)); + assert_eq!(take_last_made(), None, "taken: none left"); + made_as(MadeAs { kept: false, ..m }); + assert_eq!(take_last_made(), super::super::view_census::on().then_some(MadeAs { kept: false, ..m }), "kept only with the census on"); + assert_eq!(take_last_made(), None); + // (another thread's is its own) + LAST_MADE.with(|c| c.set(Some(m))); + assert_eq!(std::thread::spawn(take_last_made).join().unwrap(), None); + assert_eq!(take_last_made(), Some(m)); + } + #[test] fn slot_73_preserves_a_null_initial_pipeline_for_command_lists() { let params = [2, 0, 1]; @@ -1431,4 +1650,60 @@ mod tests { assert!(!is_shader_cache_session_guid(&IID_XBOX_DMA_COMMAND_LIST)); assert!(!is_shader_cache_session_guid(&IID_GRAPHICS_COMMAND_LIST)); } + + /// The title's plain draw signatures (one DRAW, or one DRAW_INDEXED) are noted when it makes + /// them – the draw check reads their commands – and forgotten with them (`gone`); a draw + /// signature with a vertex buffer view among its arguments is none. + #[test] + fn plain_draw_signatures_are_noted_when_made() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + if !crate::util::mac_host() { + return; + } + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let dev = dev.unwrap(); + // (XCL's device: `real::dev_create_command_signature` calls the driver through its table) + real::adopt(dev.as_raw(), real::Kind::Device); + let iid = GUID::from_u128(ID3D12CommandSignature::IID.to_u128()); + // a console desc (stride, count, the arguments, node mask); null: refused + let make = |stride: u32, args: &[[u32; 4]]| -> *mut c_void { + let mut desc = [0u8; 24]; + desc[0..4].copy_from_slice(&stride.to_le_bytes()); + desc[4..8].copy_from_slice(&(args.len() as u32).to_le_bytes()); + desc[8..16].copy_from_slice(&(args.as_ptr() as u64).to_le_bytes()); + let mut out: *mut c_void = std::ptr::null_mut(); + if create_command_signature_x(dev.as_raw(), desc.as_ptr(), 0, &iid, &mut out) < 0 { + return std::ptr::null_mut(); + } + out + }; + let (draw, indexed) = (D3D12_INDIRECT_ARGUMENT_TYPE_DRAW.0 as u32, D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32); + let vertex_buffer = D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW.0 as u32; + let sigs = [ + (make(16, &[[draw, 0, 0, 0]]), Some((16, false))), + (make(20, &[[indexed, 0, 0, 0]]), Some((20, true))), + (make(32, &[[indexed, 0, 0, 0]]), Some((32, true))), + (make(32, &[[vertex_buffer, 0, 0, 0], [draw, 0, 0, 0]]), None), + ]; + for (k, &(sig, want)) in sigs.iter().enumerate() { + if sig.is_null() { + // (the driver may refuse the last one: its branch only logs) + assert_eq!(k, 3, "signature {k} was not made"); + crate::gpu::recomp::runner::skip_config("its last case only: the driver refused a draw signature with a vertex buffer view"); + continue; + } + assert_eq!(super::super::indirect::plain_draw(sig as usize), want, "signature {k}"); + } + for (sig, _) in sigs.into_iter().filter(|s| !s.0.is_null()) { + // (what `gone` calls when the title releases it) + super::super::bind::forget_mac_signatures(sig as usize); + assert_eq!(super::super::indirect::plain_draw(sig as usize), None, "forgotten with it"); + drop(ID3D12CommandSignature::from_raw(sig)); + } + } + } } diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index 6915c08..c0a0206 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -25,9 +25,24 @@ struct Fence { waited: u64, } -/// (fences are never freed: XCL holds a reference to each) +/// the fences queues were told to signal or wait for – never freed while their values are asked +/// from other threads (`refresh`, `snapshot`): a reference to each is held for good (`entry`) static FENCES: Mutex>> = Mutex::new(None); +/// `fence`'s entry. One seen for the first time is held for good: the title's from their +/// creation (`real::dev_create_fence`), any other – one of XCL's that a hooked queue was told +/// to signal – by a reference taken here (D3DMetal's objects are outside the memory +/// `VirtualQuery` reports, so a pointer is not checked: every caller passes a fence a queue +/// was just given). +fn entry(g: &mut Option>, fence: usize) -> &mut Fence { + g.get_or_insert_with(HashMap::new).entry(fence).or_insert_with(|| { + if !super::real::is_title_fence(fence) { + unsafe { borrowed(fence, |f| std::mem::forget(f.clone())) }; + } + Fence::default() + }) +} + /// the event a completion sets (auto-reset); the first use starts the thread that follows it fn event() -> usize { static E: OnceLock = OnceLock::new(); @@ -65,11 +80,8 @@ fn refresh() { for (&p, f) in g.iter().flatten() { if let Some(c) = f.cell { if let Some(v) = unsafe { borrowed(p, |f| f.GetCompletedValue()) } { - // If the device has been removed, GetCompletedValue returns UINT64_MAX. - // Do not update the cell or treat this as a completed fence value. - if v == u64::MAX { - continue; - } + // (a removed device's all-ones goes to the cell too: the title's wait on it ends, + // and its next call reaches `real::stop_if_device_removed`) let was = c.0.swap(v, Ordering::AcqRel); if was != v { unsafe { @@ -94,7 +106,7 @@ unsafe fn arm(fence: usize, value: u64) { pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) { let cell = { let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); + let f = entry(&mut g, fence); f.signalled = f.signalled.max(value); f.cell.is_some() }; @@ -109,18 +121,52 @@ pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) { /// A queue was told to wait for `fence` (one of the title's) to reach `value`. pub(super) fn note_queue_wait(fence: usize, value: u64) { let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); + let f = entry(&mut g, fence); f.waited = f.waited.max(value); } -/// The CPU signalled `fence`. -pub(super) fn note_cpu_signal(fence: usize) { - let known = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.get(&fence).is_some_and(|f| f.cell.is_some())); +/// The CPU signalled `fence` with `value`; its completed value was `before`. Signal sets the +/// value: one below `before` rewinds the fence (used again from 0), and the values queues were +/// told of before are behind it then. A Signal forward (a CPU job done – DirectStorage's – +/// while queues still wait for later values, or signal them) changes nothing of theirs. +pub(super) fn note_cpu_signal(fence: usize, value: u64, before: u64) { + let known = { + let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); + match g.as_mut().and_then(|m| m.get_mut(&fence)) { + Some(f) => { + if value < before { + f.signalled = f.signalled.min(value); + f.waited = f.waited.min(value); + } + f.cell.is_some() + } + None => false, + } + }; if known { refresh(); } } +/// (tests) A fence a test named with a stand-in pointer is forgotten. +#[cfg(test)] +pub(super) fn forget_for_test(fence: usize) { + if let Some(m) = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + m.remove(&fence); + } +} + +/// Every title fence a queue was told to signal or wait for: (fence, completed value, highest +/// value a queue was told to signal, highest value a queue was told to wait for) – `stall`. +pub(super) fn snapshot() -> Vec<(usize, u64, u64, u64)> { + let fences: Vec<(usize, u64, u64)> = { + let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); + g.iter().flatten().map(|(&p, f)| (p, f.signalled, f.waited)).collect() + }; + // (the completed values outside the lock: a queue's Signal takes it) + fences.into_iter().map(|(p, sig, wait)| (p, unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(u64::MAX), sig, wait)).collect() +} + /// Diagnostic summary of title fences whose completed value lags their signalled or waited value. pub(super) fn pending_summary() -> String { let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); @@ -142,7 +188,7 @@ pub(super) fn pending_summary() -> String { pub(super) unsafe extern "system" fn completed_value_address(this: *mut c_void) -> *const u64 { let (cell, pending) = { let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); + let f = entry(&mut g, this as usize); match f.cell { Some(c) => return c.0.as_ptr(), None => { @@ -170,30 +216,6 @@ mod tests { use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::*; - #[test] - fn fence_cell_updates_on_advance_and_rewind_excluding_device_removal() { - let cell = Cell(AtomicU64::new(100)); - - // 1. Advance: 100 -> 101 - let v1 = 101; - let was1 = cell.0.swap(v1, Ordering::AcqRel); - assert_eq!(was1, 100); - assert_eq!(cell.0.load(Ordering::Acquire), 101); - - // 2. Legitimate rewind / reset: 101 -> 50 - let v2 = 50; - let was2 = cell.0.swap(v2, Ordering::AcqRel); - assert_eq!(was2, 101); - assert_eq!(cell.0.load(Ordering::Acquire), 50); - - // 3. Device removal sentinel (u64::MAX) must be excluded - let v_removed = u64::MAX; - if v_removed != u64::MAX { - cell.0.swap(v_removed, Ordering::AcqRel); - } - assert_eq!(cell.0.load(Ordering::Acquire), 50); - } - /// The cell follows the fence: CPU signals at once, queue signals when the GPU is there – /// also one queued before the address was asked for. #[test] @@ -225,8 +247,51 @@ mod tests { note_queue_signal(p as usize, 7); wait(cell, 7); fence.Signal(9).unwrap(); - note_cpu_signal(p as usize); + note_cpu_signal(p as usize, 9, 7); assert_eq!(*cell, 9); + // a real fence is held (`entry`): its value can be asked from any thread + let mine = |p: usize| { + let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); + let f = &g.as_ref().unwrap()[&p]; + (unsafe { borrowed(p, |f| f.GetCompletedValue()) }, f.signalled, f.waited) + }; + assert_eq!(mine(p as usize), (Some(9), 7, 0)); + // a CPU Signal forward, below what a queue waits for or was told to signal: theirs stay + note_queue_wait(p as usize, 20); + note_queue_signal(p as usize, 15); + fence.Signal(12).unwrap(); + note_cpu_signal(p as usize, 12, 9); + assert_eq!(mine(p as usize), (Some(12), 15, 20)); + // a rewind (below the value it had): what queues were told is behind it + fence.Signal(2).unwrap(); + note_cpu_signal(p as usize, 2, 12); + assert_eq!(mine(p as usize), (Some(2), 2, 2)); + assert_eq!(*cell, 2); + std::mem::forget(fence); // the map keeps its address + } + } + + /// The all-ones a removed device's fences read reaches the cell too (here a CPU Signal of + /// u64::MAX stands for it): the title's wait on the cell ends, and its next call reaches + /// `real::stop_if_device_removed` – the cell is not left at the last value it had. + #[test] + fn the_cell_takes_all_ones_too() { + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().unwrap(); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.unwrap(); + let fence: ID3D12Fence = dev.CreateFence(3, D3D12_FENCE_FLAG_NONE).unwrap(); + let p = fence.as_raw(); + let cell = completed_value_address(p); + assert_eq!(*cell, 3); + fence.Signal(u64::MAX).unwrap(); + assert_eq!(fence.GetCompletedValue(), u64::MAX); + note_cpu_signal(p as usize, u64::MAX, 3); + assert_eq!(*cell, u64::MAX, "the cell reads all ones after refresh"); std::mem::forget(fence); // the map keeps its address } } diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index 1a78f0c..5c693e7 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -333,7 +333,10 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t }; let mut hs = vec![internal as HANDLE]; hs.extend(extra); - let r = WaitForMultipleObjects(hs.len() as u32, hs.as_ptr(), (flags & WAIT_ALL != 0) as i32, timeout_ms); + let r = { + let _held = crate::waitwatch::xcl(crate::waitwatch::X_FRAME_EVENT, ty as u64); + WaitForMultipleObjects(hs.len() as u32, hs.as_ptr(), (flags & WAIT_ALL != 0) as i32, timeout_ms) + }; ACTIVITY[0].fetch_add(1, Ordering::Relaxed); if r == WAIT_TIMEOUT { ACTIVITY[1].fetch_add(1, Ordering::Relaxed); diff --git a/crates/xcl/src/hle/d3d12x/gpu_views.rs b/crates/xcl/src/hle/d3d12x/gpu_views.rs index dbabc38..08e7d63 100644 --- a/crates/xcl/src/hle/d3d12x/gpu_views.rs +++ b/crates/xcl/src/hle/d3d12x/gpu_views.rs @@ -157,6 +157,7 @@ const MAX_BATCHES: usize = 1 << 16; /// XMemMapPhysicalPagesScatter got in the CPU range in the call before. The result is not /// looked at. pub(super) unsafe fn update(n: u32, batches: *const u8, pool: usize, arg: u32) { + let _xcl_api = crate::waitwatch::api("gpu_views::update"); let call = CALLS.fetch_add(1, Ordering::Relaxed); // `XCL_GPU_PAGE_MAPPINGS=0`: the calls are not kept – a GPU view is read by the pairing of // the two reservations alone (`kernelx::mirrors`), to compare the two @@ -202,6 +203,23 @@ pub(super) unsafe fn update(n: u32, batches: *const u8, pool: usize, arg: u32) { .collect(); // (the trace's distances: asked of the kernel before the table is locked) let places: Vec> = if trace() { resolved.iter().map(|&(_, page)| page.and_then(crate::hle::kernelx::page_address)).collect() } else { Vec::new() }; + // (diagnostic `kernelx::traced`: asked of the kernel before the table is locked) + for (&(view, page), &(_, pool_page)) in resolved.iter().zip(&asked) { + if crate::hle::kernelx::traced(view) || page.is_some_and(crate::hle::kernelx::traced) { + let place = page.and_then(crate::hle::kernelx::page_address); + crate::xlog_info!( + "[trace] queue #31 call #{call}: GPU view {view:#x} → pool page {pool_page:x?} (pool address {:x?}) → physical page {page:x?}, which is at {place:x?} ({:?} non-zero bytes there)", + pool_page.map(|p| pool + p as usize * PAGE), + place.and_then(crate::hle::kernelx::page_nonzero) + ); + if let Some(p) = page { + crate::hle::kernelx::trace_add(p); + } + if let Some(a) = place { + crate::hle::kernelx::trace_add(a); + } + } + } let (mut mapped, mut unmapped, mut lost) = (0usize, 0usize, 0usize); { let mut g = VIEWS.lock().unwrap(); @@ -280,6 +298,11 @@ fn page_at(addr: usize) -> Option { VIEWS.lock().unwrap().as_ref()?.at.get(&(addr & !(PAGE - 1))).copied() } +/// (diagnostic) The physical page the queue's mappings show at the GPU-view page of `addr`. +pub fn physical_page_at(addr: usize) -> Option { + page_at(addr) +} + /// What the queue's page mappings say of `addr`: None – no page is mapped at its GPU-view page /// (or it is no GPU-view address); Some(place) – one is, and `place` is where the CPU has the /// memory the GPU sees at `addr` (None: a page with no memory yet). @@ -329,6 +352,15 @@ pub fn counts() -> (usize, u64) { (MAPPED.load(Ordering::Relaxed), CALLS.load(Ordering::Relaxed)) } +/// (diagnostic) Whether the queue's mappings show each of `pages` in a GPU view now. +pub fn pages_in_views(pages: &[usize]) -> Vec { + if !any() { + return vec![false; pages.len()]; + } + let g = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + pages.iter().map(|p| g.as_ref().is_some_and(|v| v.of.contains_key(p))).collect() +} + #[cfg(test)] mod tests { use super::*; @@ -400,6 +432,7 @@ mod tests { let ranges = [[1u32, 2, 1]]; let batch: [usize; 3] = [gpu + 5 * PAGE, 1, ranges.as_ptr() as usize]; update(1, batch.as_ptr() as *const u8, pool, 4); + assert_eq!(pages_in_views(&[pages[2], pages[1]]), [true, false], "the page shown in the view, not its neighbour"); // (a texture over virtual pages 4..7 of the GPU's range, as the content comparison sees it) let hash = || crate::hle::d3d12x::title_textures::memory_hash_for_tests(gpu + 4 * PAGE + 0x30, 3 * PAGE - 0x50); let before = hash(); @@ -418,6 +451,7 @@ mod tests { update(1, batch.as_ptr() as *const u8, pool, 4); assert_eq!(memory_at(gpu + 5 * PAGE + 0x40), None); assert!(views_of(cpu + 5 * PAGE, PAGE).is_empty()); + assert_eq!(pages_in_views(&[pages[2], pages[1]]), [false, false]); assert_ne!(written, hash(), "a page unmapped from the view shows too"); assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 4, pages.as_mut_ptr()), 1); for r in [pool, cpu, gpu] { diff --git a/crates/xcl/src/hle/d3d12x/indirect.rs b/crates/xcl/src/hle/d3d12x/indirect.rs index 5374918..9f40768 100644 --- a/crates/xcl/src/hle/d3d12x/indirect.rs +++ b/crates/xcl/src/hle/d3d12x/indirect.rs @@ -1,19 +1,284 @@ //! Repack root-changing indirect draws and dispatches on the GPU. The native signature //! consumes an ABI io UAV address followed by the draw or dispatch arguments for each item. +//! +//! On a Mac the group counts of a translated compute ExecuteIndirect are checked on the GPU +//! before it runs (`Sanitize`). GPU-driven work computes them on the GPU (GTA VI's VFX heap +//! defragmentation: one program writes (count, 1, 1) for the next, which indexes its records by +//! group), and a producer whose writes do not reach the PC arguments – title memory outside +//! unified memory – leaves whatever that memory held. The likely cause of GTA VI's first world +//! frame keeping a Mac's GPU busy for minutes with no Metal error (run 61): such a count, which +//! D3DMetal ran as it was. +//! +//! A translated draw's ExecuteIndirect with its arguments outside unified memory or in a resource +//! XCL does not know (once work of a pipeline not built was skipped, or with +//! `XCL_INDIRECT_SANITIZE_DRAWS=all`: anywhere) is checked as well (`draw_check`; plain DRAW and +//! DRAW_INDEXED signatures): a vertex or index count, an instance count, a first vertex, index or +//! instance, or an index range that could hang or fault the GPU makes the command draw nothing. Every +//! ExecuteIndirect of a translated pipeline is counted when recorded, by where its arguments are +//! and what became of it (`census`). use std::collections::HashMap; use std::ffi::c_void; use std::mem::ManuallyDrop; -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; -use super::{console_list::{Layout, Param}, real}; +use super::{console_list::{Layout, Param}, real, stall::Args}; use crate::gpu::recomp::{self, KERNEL_SGPRS}; const IO_BYTES: u32 = 4 * KERNEL_SGPRS as u32; const THREADS: u32 = 64; -const CONFIG_WORDS: u32 = 13; +const CONFIG_WORDS: u32 = 14; + +/// `XCL_INDIRECT_SANITIZE=0`: a translated compute ExecuteIndirect on a Mac gets the title's +/// arguments as they are (no check of its group counts). +pub(super) fn sanitize_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INDIRECT_SANITIZE").map_or(true, |v| v.trim() != "0")) +} + +/// Groups a checked dispatch command may have (`XCL_INDIRECT_MAX_GROUPS`, default 2^22 – some +/// 30 times a full-screen pass of 8 x 8 tiles at 4K); more, or Y or Z above D3D12's 65 535, +/// and the command runs no group. +pub(super) fn max_groups() -> u32 { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_INDIRECT_MAX_GROUPS").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(1 << 22)) +} + +/// What the check lets through – `SANITIZE_HLSL` and the repacker test the same on the GPU +/// (this copy is the tests' reference: keep them equal). +#[cfg_attr(not(test), allow(dead_code))] +pub(super) fn groups_ok(g: [u32; 3], cap: u32) -> bool { + if g[0] > cap || g[1] > 65_535 || g[2] > 65_535 { + return false; + } + g.contains(&0) || (g[1] <= cap / g[0] && g[2] <= cap / (g[0] * g[1])) +} + +/// How translated draws' ExecuteIndirect arguments are checked (`XCL_INDIRECT_SANITIZE_DRAWS`). +/// The check reads plain signatures only – one DRAW or DRAW_INDEXED argument –, never in a bundle +/// (barriers are not allowed there); a root-changing signature (the repacker copies its draws as +/// they are) and one with vertex or index buffer views go as the title gave them in every mode +/// (the census: "as they were", "with a signature the check does not read"). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum DrawCheck { + /// `0`, or `XCL_INDIRECT_SANITIZE=0`: as the title gave them (0022) + Off, + /// unset (the default) or `own`: those outside unified memory or in a resource XCL does not + /// know – unset, those in unified memory and upload buffers too once work of a pipeline not + /// built was skipped (`effective_mode`); `own` keeps to the first + Own, + /// `all`: wherever they are – unified memory and upload buffers too + All, +} + +/// The mode `XCL_INDIRECT_SANITIZE_DRAWS` says (`value`; None: unset), and whether it becomes `All` +/// once a pipeline's work was skipped (`effective_mode`): the default does, an explicit `own` +/// never – the mode before work could be skipped (0023's first runs) – nor `0` or `all`. Any other +/// value is the default, as before. +fn draw_check_of(value: Option<&str>) -> (DrawCheck, bool) { + match value.map(str::trim) { + Some("0") => (DrawCheck::Off, false), + Some(v) if v.eq_ignore_ascii_case("all") => (DrawCheck::All, false), + Some(v) if v.eq_ignore_ascii_case("own") => (DrawCheck::Own, false), + _ => (DrawCheck::Own, true), + } +} + +/// (`XCL_INDIRECT_SANITIZE_DRAWS`, read once) the mode, and whether the default's upgrade applies +fn draw_check_setting() -> (DrawCheck, bool) { + static M: OnceLock<(DrawCheck, bool)> = OnceLock::new(); + *M.get_or_init(|| { + if !sanitize_on() { + return (DrawCheck::Off, false); + } + let v = std::env::var("XCL_INDIRECT_SANITIZE_DRAWS").ok(); + let setting = draw_check_of(v.as_deref()); + match setting { + (DrawCheck::All, _) => crate::xlog_info!( + "XCL_INDIRECT_SANITIZE_DRAWS=all: translated draws' ExecuteIndirect whose signature is one DRAW or DRAW_INDEXED argument (not in bundles) are checked on the GPU first, in unified memory and upload buffers too; root-changing (repacked) signatures and ones with vertex or index buffer views go as they are (the census: as they were / with a signature the check does not read)" + ), + (DrawCheck::Own, false) => crate::xlog_info!( + "XCL_INDIRECT_SANITIZE_DRAWS=own: translated draws' ExecuteIndirect of one DRAW or DRAW_INDEXED argument (not in bundles) are checked on the GPU only with their arguments outside unified memory or in a resource XCL does not know – also once work of a pipeline not built was skipped" + ), + _ => {} + } + setting + }) +} + +/// The mode `XCL_INDIRECT_SANITIZE_DRAWS` sets (before `effective_mode`). +pub(super) fn draw_check_mode() -> DrawCheck { + draw_check_setting().0 +} + +pub(super) fn draw_check_on() -> bool { + draw_check_mode() != DrawCheck::Off +} + +/// The mode a draw is checked in: `Own` – the default – becomes `All` once work of a pipeline not +/// built was skipped (`skipped`: `pso_async::work_skipped`). 0023 skips the work of late, refused, +/// failed and big-lane pipelines as a matter of course, GPU producers among them; a draw whose +/// arguments such a producer writes into unified memory reads what was there before – in a first +/// world frame stale or aliased bytes, an unbounded draw (the hang class before this Mac's kernel +/// panics). `Off` and `All` stay. +pub(super) fn effective_mode(mode: DrawCheck, skipped: bool) -> DrawCheck { + match (mode, skipped) { + (DrawCheck::Own, true) => DrawCheck::All, + (m, _) => m, + } +} + +/// `XCL_INDIRECT_DRAW_INDICES=0`: the check of a DRAW_INDEXED does not compare its index range with +/// the bound index buffer (D3D12 reads an index past it as 0; Metal need not). The caps and the +/// wrap rules stay. +pub(super) fn draw_indices_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INDIRECT_DRAW_INDICES").map_or(true, |v| v.trim() != "0")) +} + +/// `XCL_INDIRECT_MAX_DRAW_COUNT` (default 2^23 − 1, `MAX_DRAW_COUNT`): vertices or indices a checked +/// draw command may draw per instance – a command of 2^23 or more an instance draws nothing. +pub(super) fn max_draw_count() -> u32 { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_INDIRECT_MAX_DRAW_COUNT").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(MAX_DRAW_COUNT)) +} + +/// The default of `max_draw_count`: 2^23 − 1, cool_fox's empirical cut (a command of 2^23 vertices +/// or indices an instance or more draws nothing) after a window checker found 90 records of 2^24 +/// vertices in one list of GTA VI's GPU-written ones – kept by a cap of 2^24, they ask D3DMetal for +/// 1.5 G vertex invocations a list (that checker may have reported larger counts clamped to 2^24; +/// the cut drops both). +pub(super) const MAX_DRAW_COUNT: u32 = (1 << 23) - 1; + +/// `XCL_INDIRECT_MAX_DRAW_WORK` (default 2^26, a 4K screen's pixels eight times over): those times +/// its instances. (The check divides, so products of 2^32 or more are dropped whatever this is.) +pub(super) fn max_draw_work() -> u32 { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_INDIRECT_MAX_DRAW_WORK").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(1 << 26)) +} + +/// What the draw check lets through – `SANITIZE_DRAW_HLSL` tests the same on the GPU (this copy is +/// the tests' reference: keep them equal). `n` vertices or indices an instance, `instances`, `first` +/// the first vertex or index, `first_instance`; `bound` the indices the bound index buffer holds +/// (u32::MAX: not looked at – a DRAW, no index buffer XCL knows, or `XCL_INDIRECT_DRAW_INDICES=0`). +/// A DRAW_INDEXED's base vertex is not looked at. +#[cfg_attr(not(test), allow(dead_code))] +pub(super) fn draw_ok(n: u32, instances: u32, first: u32, first_instance: u32, cap: u32, work: u32, bound: u32) -> bool { + n <= cap && instances <= work / n.max(1) && first <= u32::MAX - n && first_instance <= u32::MAX - instances && first + n <= bound +} + +/// `XCL_INDIRECT_OWN=skip` (a lever for a test run; default off): an ExecuteIndirect of a translated +/// pipeline whose arguments are in a PC resource of their own – title memory outside unified memory, +/// which neither translated programs nor the title's CPU writes reach – is not recorded. Counted +/// (`census`), and `[indirect]` names the first of each program. +pub(super) fn own_skip() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_INDIRECT_OWN").is_ok_and(|v| v.trim().eq_ignore_ascii_case("skip")); + if on { + crate::xlog_warn!("XCL_INDIRECT_OWN=skip: ExecuteIndirect of translated pipelines with their arguments outside unified memory (a PC resource of their own) are not recorded"); + } + on + }) +} + +/// `XCL_INDIRECT_CENSUS=0`: no census (its counts, the `ExecuteIndirect recorded so far` line); a +/// draw's arguments are then looked at only when the draw check or `XCL_INDIRECT_OWN` needs them, +/// or while `[indirect]` still logs draws (0022). +pub(super) fn census_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INDIRECT_CENSUS").map_or(true, |v| v.trim() != "0")) +} + +/// Plain dispatch signatures (one DISPATCH argument, no root arguments): signature → stride. +static PLAIN: Mutex>> = Mutex::new(None); + +pub(super) fn note_plain_dispatch(sig: usize, stride: u32) { + if stride >= 12 && stride % 4 == 0 { + PLAIN.lock().unwrap().get_or_insert_with(HashMap::new).insert(sig, stride); + } +} + +/// The stride of a plain dispatch signature. +pub(super) fn plain_dispatch(sig: usize) -> Option { + PLAIN.lock().unwrap().as_ref()?.get(&sig).copied() +} + +/// Plain draw signatures (one DRAW or DRAW_INDEXED argument, no root arguments): signature → +/// (stride, indexed). +static PLAIN_DRAW: Mutex>> = Mutex::new(None); + +pub(super) fn note_plain_draw(sig: usize, stride: u32, indexed: bool) { + if stride >= if indexed { 20 } else { 16 } && stride % 4 == 0 { + PLAIN_DRAW.lock().unwrap().get_or_insert_with(HashMap::new).insert(sig, (stride, indexed)); + } +} + +/// The stride of a plain draw signature, and whether it draws indexed. +pub(super) fn plain_draw(sig: usize) -> Option<(u32, bool)> { + PLAIN_DRAW.lock().unwrap().as_ref()?.get(&sig).copied() +} + +/// The check of a translated draw's ExecuteIndirect: (stride, command), or None – the check is off, +/// the arguments are where the mode does not look (`Own` before any work was skipped: unified +/// memory, an upload buffer – what the title's GPU work or CPU wrote), or the signature is not one +/// DRAW or DRAW_INDEXED (counted; a root-changing one does not come here: the repacker's). The +/// caller leaves a bundle's unchecked. `indices`: what the bound index buffer holds (asked only for +/// an indexed draw). The mode is the effective one (`effective_mode`); the first draw its upgrade +/// checks is logged. +pub(super) fn draw_check(place: Args, sig: usize, indices: impl FnOnce() -> u32) -> Option<(u32, Command)> { + let (mode, upgrades) = draw_check_setting(); + let now = if upgrades { effective_mode(mode, super::pso_async::work_skipped()) } else { mode }; + let check = draw_check_in(now, place, sig, indices); + // (`Own` would have let it go as it was) + if now != mode && check.is_some() && !matches!(place, Args::Own | Args::Unknown) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + crate::xlog_info!( + "D3D12.X: work of a pipeline not built was skipped – from now on translated draws' ExecuteIndirect of one DRAW or DRAW_INDEXED argument (not in bundles) are checked on the GPU in unified memory and upload buffers too, as with XCL_INDIRECT_SANITIZE_DRAWS=all (this first one's arguments: {}); XCL_INDIRECT_SANITIZE_DRAWS=own keeps to those outside unified memory or in a resource XCL does not know", + place.short() + ) + }); + } + check +} + +fn draw_check_in(mode: DrawCheck, place: Args, sig: usize, indices: impl FnOnce() -> u32) -> Option<(u32, Command)> { + match mode { + DrawCheck::Off => return None, + DrawCheck::Own if !matches!(place, Args::Own | Args::Unknown) => return None, + _ => {} + } + let Some((stride, indexed)) = plain_draw(sig) else { + note_unread_draw(); + return None; + }; + Some((stride, if indexed { Command::DrawIndexed { indices: if draw_indices_on() { indices() } else { u32::MAX } } } else { Command::Draw })) +} + +/// Where ExecuteIndirect's arguments at console offset `offset` of `resource` are. +pub(super) unsafe fn classify(resource: usize, offset: u64) -> Args { + if resource == 0 { + return Args::Unknown; + } + if let Some((p, _)) = real::console_buffer(resource) { + let k = crate::gpu::uma::get().and_then(|u| u.window_of(p.saturating_add(offset as usize))); + return k.map_or(Args::Unknown, |k| Args::Window(k as u8)); + } + let raw = resource as *mut c_void; + let Some(r) = ID3D12Resource::from_raw_borrowed(&raw) else { return Args::Unknown }; + if r.GetDesc().Dimension != D3D12_RESOURCE_DIMENSION_BUFFER { + return Args::Unknown; + } + let mut props = D3D12_HEAP_PROPERTIES::default(); + if r.GetHeapProperties(Some(&mut props), None).is_ok() && matches!(props.Type, D3D12_HEAP_TYPE_UPLOAD | D3D12_HEAP_TYPE_GPU_UPLOAD) { + return Args::Upload; + } + Args::Own +} #[derive(Clone, Copy)] enum RootArg { @@ -46,6 +311,12 @@ pub(super) fn forget(sig: usize) { if let Some(sigs) = SIGNATURES.lock().unwrap().as_mut() { sigs.remove(&sig); } + if let Some(sigs) = PLAIN.lock().unwrap().as_mut() { + sigs.remove(&sig); + } + if let Some(sigs) = PLAIN_DRAW.lock().unwrap().as_mut() { + sigs.remove(&sig); + } } impl Signature { @@ -132,6 +403,513 @@ pub(super) fn retain_resource(allocator: usize, resource: ID3D12Resource) { pub(super) fn allocator_reset(allocator: usize) { let buffers = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); drop(buffers); + // the checked arguments' buffers serve the next recordings (dropped outside the locks: + // a Release may call back into D3D12) + let chunks = CHUNKS.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)).unwrap_or_default(); + let mut extra = Vec::new(); + { + let mut free = FREE_CHUNKS.lock().unwrap(); + for mut c in chunks { + c.used = 0; + if free.len() < 16 && c.cap == CHUNK_BYTES { + free.push(c); + } else { + extra.push(c); + } + } + } + drop(extra); +} + +// --- the check of a translated compute ExecuteIndirect's group counts (a Mac) --- + +/// A buffer the checked arguments of one recording go into, piece by piece (`take_chunk`). +struct Chunk { + buf: ID3D12Resource, + cap: u64, + used: u64, + dev: usize, +} + +/// allocator → its chunks (the last one is filled); released when the allocator is reset +static CHUNKS: Mutex>>> = Mutex::new(None); +/// chunks of reset allocators, for the next recordings +static FREE_CHUNKS: Mutex> = Mutex::new(Vec::new()); +const CHUNK_BYTES: u64 = 64 << 10; + +/// `bytes` of a buffer (UNORDERED_ACCESS, the state it is left in) for the recording on +/// `allocator`: (the buffer, the offset). +unsafe fn take_chunk(dev: &ID3D12Device, allocator: usize, bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let bytes = bytes.max(1).next_multiple_of(256); + let key = dev.as_raw() as usize; + { + let mut g = CHUNKS.lock().unwrap(); + let v = g.get_or_insert_with(HashMap::new).entry(allocator).or_default(); + if let Some(c) = v.last_mut().filter(|c| c.dev == key && c.cap - c.used >= bytes) { + let at = c.used; + c.used += bytes; + return Ok((c.buf.clone(), at)); + } + } + let cap = bytes.max(CHUNK_BYTES); + let picked = { + let mut free = FREE_CHUNKS.lock().unwrap(); + free.iter().position(|c| c.dev == key && c.cap >= cap).map(|i| free.swap_remove(i)) + }; + let mut c = match picked { + Some(c) => c, + None => { + let mut buf = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: cap, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() + }, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + None, + &mut buf, + ) + .map_err(|e| format!("a buffer for checked indirect arguments ({cap} B): {e}"))?; + Chunk { buf: buf.ok_or("no buffer for checked indirect arguments")?, cap, used: 0, dev: key } + } + }; + c.used = bytes; + let buf = c.buf.clone(); + CHUNKS.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().push(c); + Ok((buf, 0)) +} + +/// The check (one thread a command): a command's group counts are copied to XCL's buffer as +/// they are when `groups_ok`, else as 0 x 0 x 0 – the command runs nothing. +const SANITIZE_HLSL: &str = r#" +cbuffer Config : register(b0) { uint count; uint src_at; uint stride; uint cap; uint dst_at; } +#ifdef SRC_UAV +RWByteAddressBuffer src : register(u1); +#else +ByteAddressBuffer src : register(t0); +#endif +RWByteAddressBuffer dst : register(u0); +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= count) + return; + uint3 g = src.Load3(src_at + id.x * stride); + bool ok = g.x <= cap && g.y <= 65535u && g.z <= 65535u + && (g.x == 0u || g.y == 0u || g.z == 0u || (g.y <= cap / g.x && g.z <= cap / (g.x * g.y))); + dst.Store3(dst_at + id.x * 12u, ok ? g : uint3(0u, 0u, 0u)); +} +"#; + +#[derive(Clone)] +struct SanitizePipeline { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +/// The check's root signature: `constants` root constants (b0), XCL's buffer (u0), the source as a +/// UAV (u1, unified memory) or an SRV (t0). +unsafe fn check_root(dev: &ID3D12Device, src_uav: bool, constants: u32) -> Result { + let descriptor = |kind, reg| D3D12_ROOT_PARAMETER { + ParameterType: kind, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: reg, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let params = [ + 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, + }, + descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 0), + if src_uav { descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 1) } else { descriptor(D3D12_ROOT_PARAMETER_TYPE_SRV, 0) }, + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).map_err(|e| format!("serialize the indirect check's root signature: {e}"))?; + let blob = blob.ok_or("no indirect check root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize())) + .map_err(|e| format!("create the indirect check's root signature: {e}")) +} + +/// The check's pipeline for `dev`, reading its source as a UAV (unified memory) or an SRV. +unsafe fn sanitize_pipeline(dev: &ID3D12Device, src_uav: bool) -> Result { + static CACHE: Mutex>> = Mutex::new(None); + let key = (dev.as_raw() as usize, src_uav); + if let Some(p) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(p); + } + let hlsl = if src_uav { format!("#define SRC_UAV 1\n{SANITIZE_HLSL}") } else { SANITIZE_HLSL.to_string() }; + let dxil = recomp::dxc::compile_cached(&hlsl, "main", "cs_6_6")?.0; + let root = check_root(dev, src_uav, 5)?; + let pso = compute_pso(dev, &root, &dxil).map_err(|e| format!("create the indirect check's pipeline: {e}"))?; + let made = SanitizePipeline { root, pso }; + // (another thread may have made one meanwhile: the first stays – lists may have recorded it – + // and this one, never used, goes after the lock: its Release comes back into XCL, `gone`) + let (p, spare) = { + let mut g = CACHE.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + match m.get(&key) { + Some(p) => (p.clone(), Some(made)), + None => { + m.insert(key, made.clone()); + (made, None) + } + } + }; + drop(spare); + Ok(p) +} + +/// A plain dispatch signature of 12 bytes for `dev` (what the checked arguments are read with). +unsafe fn dispatch_signature(dev: &ID3D12Device) -> Result { + static CACHE: Mutex>> = Mutex::new(None); + let key = dev.as_raw() as usize; + if let Some(s) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(s); + } + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }; + let mut out = None; + dev.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut out).map_err(|e| format!("create the checked dispatch signature: {e}"))?; + let made: ID3D12CommandSignature = out.ok_or("no checked dispatch signature")?; + // (the first one made stays: lists may have recorded it; a second goes after the lock) + let (s, spare) = { + let mut g = CACHE.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + match m.get(&key) { + Some(s) => (s.clone(), Some(made)), + None => { + m.insert(key, made.clone()); + (made, None) + } + } + }; + drop(spare); + Ok(s) +} + +/// The check of a translated draw's ExecuteIndirect (one thread a command). It reads a DRAW (16 +/// bytes: vertices, instances, first vertex, first instance) or, with `INDEXED`, a DRAW_INDEXED (20 +/// bytes: indices, instances, first index, base vertex, first instance), and copies it to XCL's +/// buffer as it is when it is sane (`draw_ok`), else as zeros: it draws nothing. +const SANITIZE_DRAW_HLSL: &str = r#" +cbuffer Config : register(b0) { uint count; uint src_at; uint stride; uint cap; uint work; uint dst_at; uint indices; uint pad; } +#ifdef SRC_UAV +RWByteAddressBuffer src : register(u1); +#else +ByteAddressBuffer src : register(t0); +#endif +RWByteAddressBuffer dst : register(u0); +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= count) + return; + uint at = src_at + id.x * stride; + uint4 a = src.Load4(at); +#ifdef INDEXED + uint e = src.Load(at + 16u); + uint first_instance = e; + uint bound = indices; +#else + uint first_instance = a.w; + uint bound = 0xffffffffu; +#endif + // a.x vertices or indices an instance, a.y instances, a.z the first vertex or index + bool ok = a.x <= cap && a.y <= work / max(a.x, 1u) + && a.z <= 0xffffffffu - a.x && first_instance <= 0xffffffffu - a.y + && a.z + a.x <= bound; +#ifdef INDEXED + uint o = dst_at + id.x * 20u; + dst.Store4(o, ok ? a : uint4(0u, 0u, 0u, 0u)); + dst.Store(o + 16u, ok ? e : 0u); +#else + dst.Store4(dst_at + id.x * 16u, ok ? a : uint4(0u, 0u, 0u, 0u)); +#endif +} +"#; + +fn draw_check_hlsl(src_uav: bool, indexed: bool) -> String { + format!("{}{}{SANITIZE_DRAW_HLSL}", if src_uav { "#define SRC_UAV 1\n" } else { "" }, if indexed { "#define INDEXED 1\n" } else { "" }) +} + +/// The draw check's pipeline for `dev`: its source read as a UAV (unified memory) or an SRV; a +/// DRAW or (`indexed`) a DRAW_INDEXED. +unsafe fn sanitize_draw_pipeline(dev: &ID3D12Device, src_uav: bool, indexed: bool) -> Result { + static CACHE: Mutex>> = Mutex::new(None); + let key = (dev.as_raw() as usize, src_uav, indexed); + if let Some(p) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(p); + } + let dxil = recomp::dxc::compile_cached(&draw_check_hlsl(src_uav, indexed), "main", "cs_6_6")?.0; + let root = check_root(dev, src_uav, 8)?; + let pso = compute_pso(dev, &root, &dxil).map_err(|e| format!("create the indirect draw check's pipeline: {e}"))?; + let made = SanitizePipeline { root, pso }; + // (as `sanitize_pipeline`: the first one made stays, a second goes after the lock) + let (p, spare) = { + let mut g = CACHE.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + match m.get(&key) { + Some(p) => (p.clone(), Some(made)), + None => { + m.insert(key, made.clone()); + (made, None) + } + } + }; + drop(spare); + Ok(p) +} + +/// A plain draw signature for `dev` – one DRAW of 16 bytes or (`indexed`) one DRAW_INDEXED of 20 – +/// which checked draw arguments are read with. No root signature: it changes no root argument. +unsafe fn draw_signature(dev: &ID3D12Device, indexed: bool) -> Result { + static CACHE: Mutex>> = Mutex::new(None); + let key = (dev.as_raw() as usize, indexed); + if let Some(s) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(s); + } + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: if indexed { D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED } else { D3D12_INDIRECT_ARGUMENT_TYPE_DRAW }, + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: if indexed { 20 } else { 16 }, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }; + let mut out = None; + dev.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut out).map_err(|e| format!("create the checked draw signature: {e}"))?; + let made: ID3D12CommandSignature = out.ok_or("no checked draw signature")?; + // (the first one made stays: lists may have recorded it; a second goes after the lock) + let (s, spare) = { + let mut g = CACHE.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + match m.get(&key) { + Some(s) => (s.clone(), Some(made)), + None => { + m.insert(key, made.clone()); + (made, None) + } + } + }; + drop(spare); + Ok(s) +} + +/// The checks' pipelines and signatures made in the background when the title makes its first plain +/// dispatch or draw signature (it is still loading then), for `dev` (the device the title made it +/// on: it lives for the process). Their DXC compile and the driver's compile are then not done in a +/// frame, on a title thread, at the first checked ExecuteIndirect – where DXC's pool and its memory +/// gate are busy with the title's shaders (run 64: compiles held back at 245.9 s, LOG:21677-21680). +/// Only the checks that are on – the draw check's window (UAV) ones in the default mode too: once +/// work was skipped it checks arguments in unified memory (`effective_mode`). Not in unit tests. +pub(super) fn warm_up(dev: usize) { + if cfg!(test) || dev == 0 || !sanitize_on() { + return; + } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let spawned = std::thread::Builder::new().name("xcl-indirect-warm".into()).spawn(move || { + let t = std::time::Instant::now(); + let raw = dev as *mut c_void; + let Some(dev) = (unsafe { ID3D12Device::from_raw_borrowed(&raw) }) else { return }; + let (mut made, mut failed) = (0u32, Vec::new()); + let mut note = |r: Result<(), String>| match r { + Ok(()) => made += 1, + Err(e) => failed.push(e), + }; + unsafe { + for uav in [false, true] { + note(sanitize_pipeline(dev, uav).map(|_| ())); + if draw_check_on() { + note(sanitize_draw_pipeline(dev, uav, false).map(|_| ())); + note(sanitize_draw_pipeline(dev, uav, true).map(|_| ())); + } + } + note(dispatch_signature(dev).map(|_| ())); + if draw_check_on() { + note(draw_signature(dev, false).map(|_| ())); + note(draw_signature(dev, true).map(|_| ())); + } + } + if failed.is_empty() { + crate::xlog_info!("D3D12.X: the indirect argument checks are ready ({made} pipelines and signatures, {} ms)", t.elapsed().as_millis()); + } else { + crate::xlog_warn!("D3D12.X: the indirect argument checks were not all made ahead ({}) – the rest are made at their first use", failed.join("; ")); + } + }); + if let Err(e) = spawned { + crate::xlog_warn!("D3D12.X: no thread to make the indirect argument checks ahead: {e}"); + } + }); +} + +/// What a checked ExecuteIndirect runs (`Sanitize`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Command { + /// a DISPATCH (12 bytes: groups x, y, z) + Dispatch, + /// a DRAW (16 bytes: vertices, instances, first vertex, first instance) + Draw, + /// a DRAW_INDEXED (20 bytes: indices, instances, first index, base vertex, first instance); + /// `indices`: what the bound index buffer holds (u32::MAX: not looked at) + DrawIndexed { indices: u32 }, +} + +impl Command { + /// the bytes of one command (what the check reads and writes) + fn bytes(self) -> u32 { + match self { + Command::Dispatch => 12, + Command::Draw => 16, + Command::DrawIndexed { .. } => 20, + } + } +} + +/// Where the check reads the title's arguments. +enum Source { + /// a UMA window as a UAV (what translated programs wrote through it): window VA, offset + Window(u64, u32), + /// an SRV at a 16-byte aligned address, the offset from it; with the title's resource of + /// its own when it must be read in a shader-readable state for the pass + Srv(u64, u32, Option), +} + +/// The check of one ExecuteIndirect, made (`prepare_command`: everything that can fail) before +/// anything is recorded. +pub(super) struct Sanitize { + pipe: SanitizePipeline, + signature: ID3D12CommandSignature, + source: Source, + buffer: ID3D12Resource, + at: u64, + max: u32, + stride: u32, + cmd: Command, +} + +/// Checked arguments: ExecuteIndirect them with `signature` from `buffer` at `offset`, then +/// `finish`. +pub(super) struct Checked { + pub(super) signature: ID3D12CommandSignature, + pub(super) buffer: ID3D12Resource, + pub(super) offset: u64, +} + +impl Sanitize { + /// The check of `max` dispatch commands of `stride` bytes at console offset `offset` of + /// `resource`, into a buffer of the recording on `allocator` (`prepare_command`). + #[cfg_attr(not(test), allow(dead_code))] + pub(super) unsafe fn prepare(list: &ID3D12GraphicsCommandList, allocator: usize, resource: usize, offset: u64, stride: u32, max: u32) -> Result { + Self::prepare_command(list, allocator, resource, offset, stride, max, Command::Dispatch) + } + + /// The check of `max` commands `cmd` of `stride` bytes at console offset `offset` of + /// `resource`, into a buffer of the recording on `allocator`. + pub(super) unsafe fn prepare_command( + list: &ID3D12GraphicsCommandList, allocator: usize, resource: usize, offset: u64, stride: u32, max: u32, cmd: Command, + ) -> Result { + if max == 0 || stride < cmd.bytes() || stride % 4 != 0 || offset % 4 != 0 { + return Err("no commands, or a stride or offset the check does not read".into()); + } + if max.div_ceil(THREADS) > D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION { + return Err("too many commands for the check's dispatch".into()); + } + // the last command reads only its own 12, 16 or 20 bytes + let bytes = u64::from(max - 1).checked_mul(u64::from(stride)).and_then(|b| b.checked_add(u64::from(cmd.bytes()))).ok_or("too many commands")?; + let source = match source(resource, offset, bytes) { + Some((false, va, at)) => Source::Window(va, at), + Some((true, va, at)) => Source::Srv(va, at, None), + None => own_source(resource, offset + real::buffer_delta(resource), bytes).ok_or("the arguments are in no buffer the check can read")?, + }; + let mut dev = None; + list.GetDevice(&mut dev).map_err(|e| format!("the list's device: {e}"))?; + let dev: ID3D12Device = dev.ok_or("no device")?; + let uav = matches!(source, Source::Window(..)); + let pipe = match cmd { + Command::Dispatch => sanitize_pipeline(&dev, uav)?, + Command::Draw => sanitize_draw_pipeline(&dev, uav, false)?, + Command::DrawIndexed { .. } => sanitize_draw_pipeline(&dev, uav, true)?, + }; + let signature = match cmd { + Command::Dispatch => dispatch_signature(&dev)?, + Command::Draw => draw_signature(&dev, false)?, + Command::DrawIndexed { .. } => draw_signature(&dev, true)?, + }; + let (buffer, at) = take_chunk(&dev, allocator, u64::from(max) * u64::from(cmd.bytes()))?; + u32::try_from(at + u64::from(max) * u64::from(cmd.bytes())).map_err(|_| "checked arguments past 4 GB")?; + Ok(Self { pipe, signature, source, buffer, at, max, stride, cmd }) + } + + /// The check's pass on `list` (the list's compute root signature and pipeline are XCL's + /// after it: the caller binds its own – `bind::bind_abi_before`). + pub(super) unsafe fn record(self, list: &ID3D12GraphicsCommandList) -> Checked { + // what translated programs (or a copy) wrote before is what the pass reads + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, ..Default::default() }]); + let readable = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0); + if let Source::Srv(_, _, Some(r)) = &self.source { + transition(list, r, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, readable); + } + list.SetComputeRootSignature(&self.pipe.root); + list.SetPipelineState(&self.pipe.pso); + let src_at = match &self.source { + Source::Window(_, at) | Source::Srv(_, at, _) => *at, + }; + match self.cmd { + Command::Dispatch => { + let config = [self.max, src_at, self.stride, max_groups(), self.at as u32]; + list.SetComputeRoot32BitConstants(0, config.len() as u32, config.as_ptr().cast(), 0); + } + Command::Draw | Command::DrawIndexed { .. } => { + let indices = match self.cmd { + Command::DrawIndexed { indices } => indices, + _ => u32::MAX, + }; + let config = [self.max, src_at, self.stride, max_draw_count(), max_draw_work(), self.at as u32, indices, 0]; + list.SetComputeRoot32BitConstants(0, config.len() as u32, config.as_ptr().cast(), 0); + } + } + list.SetComputeRootUnorderedAccessView(1, self.buffer.GetGPUVirtualAddress()); + match &self.source { + Source::Window(va, _) => list.SetComputeRootUnorderedAccessView(2, *va), + Source::Srv(va, _, _) => list.SetComputeRootShaderResourceView(2, *va), + } + list.Dispatch(self.max.div_ceil(THREADS), 1, 1); + if let Source::Srv(_, _, Some(r)) = &self.source { + transition(list, r, readable, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + } + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, ..Default::default() }]); + transition(list, &self.buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + Checked { signature: self.signature, buffer: self.buffer, offset: self.at } + } +} + +impl Checked { + /// After the ExecuteIndirect: the buffer back in its state (a list can run more than once). + pub(super) unsafe fn finish(&self, list: &ID3D12GraphicsCommandList) { + transition(list, &self.buffer, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } +} + +/// The title's own PC buffer (title memory outside unified memory), `bytes` at PC offset +/// `offset`, read as an SRV. +unsafe fn own_source(resource: usize, offset: u64, bytes: u64) -> Option { + let raw = resource as *mut c_void; + let r = ID3D12Resource::from_raw_borrowed(&raw)?; + let d = r.GetDesc(); + if d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || d.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || offset.checked_add(bytes)? > d.Width { + return None; + } + let mut props = D3D12_HEAP_PROPERTIES::default(); + if r.GetHeapProperties(Some(&mut props), None).is_ok() && matches!(props.Type, D3D12_HEAP_TYPE_READBACK) { + return None; + } + let va = r.GetGPUVirtualAddress().checked_add(offset)?; + if va == 0 { + return None; + } + u32::try_from((va & 15).checked_add(bytes - 1)?).ok()?; + Some(Source::Srv(va & !15, (va & 15) as u32, Some(r.clone()))) } unsafe fn repacker(dev: &ID3D12Device, upload: bool) -> Result, String> { @@ -353,6 +1131,8 @@ impl Repack<'_> { self.max, input_offset, sig.stride, sig.action_offset, sig.action_bytes, scratch_stride, template_bytes, patches.len() as u32, scratch as u32, (scratch >> 32) as u32, scratch_va as u32, (scratch_va >> 32) as u32, IO_BYTES, + // a dispatch command with absurd group counts runs none (`groups_ok`) + if self.gfx || !sanitize_on() { 0 } else { max_groups() }, ]; repack.dispatch(list, upload, input, scratch_va, &arguments, &config, groups); Ok(Recorded { signature, arguments, bound_io, patches }) @@ -382,6 +1162,109 @@ impl Repacker { } } +// --- the census: every ExecuteIndirect of a translated pipeline, counted when recorded --- + +/// What became of an ExecuteIndirect of a translated pipeline (`census`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Fate { + /// its arguments went to the GPU as the title gave them + AsIs = 0, + /// … through XCL's check first (`Sanitize`; compute: also the repacker's group cap) + Checked = 1, + /// not recorded: `XCL_INDIRECT_OWN=skip` + SkippedOwn = 2, + /// not recorded: an error (`[indirect]` names it) + Failed = 3, +} + +/// ExecuteIndirect of translated pipelines so far, counted when recorded: +/// [compute, draws][unified memory, upload, outside unified memory, unknown (`Args::index`)][`Fate`] +static CENSUS: [[[AtomicU64; 4]; 4]; 2] = [const { [const { [const { AtomicU64::new(0) }; 4] }; 4] }; 2]; +/// … with a count buffer: [compute, draws][all, the count outside unified memory] +static COUNTED: [[AtomicU64; 2]; 2] = [const { [const { AtomicU64::new(0) }; 2] }; 2]; +/// draws the check would have read but whose signature it does not (`draw_check`) +static UNREAD_DRAWS: AtomicU64 = AtomicU64::new(0); + +pub(super) fn census(gfx: bool, place: Args, fate: Fate) { + if !census_on() { + return; + } + CENSUS[gfx as usize][place.index()][fate as usize].fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + LAST_CENSUS.with(|c| c.set(Some((gfx, place, fate)))); +} + +pub(super) fn census_count_buffer(gfx: bool, place: Args) { + COUNTED[gfx as usize][0].fetch_add(1, Ordering::Relaxed); + if place == Args::Own { + COUNTED[gfx as usize][1].fetch_add(1, Ordering::Relaxed); + } +} + +fn note_unread_draw() { + if census_on() { + UNREAD_DRAWS.fetch_add(1, Ordering::Relaxed); + } +} + +/// The census at one moment (`bind::indirect_line`). +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub(super) struct CensusSnapshot { + pub(super) n: [[[u64; 4]; 4]; 2], + pub(super) counted: [[u64; 2]; 2], + pub(super) unread: u64, +} + +pub(super) fn census_snapshot() -> CensusSnapshot { + CensusSnapshot { + n: std::array::from_fn(|k| std::array::from_fn(|p| std::array::from_fn(|f| CENSUS[k][p][f].load(Ordering::Relaxed)))), + counted: std::array::from_fn(|k| std::array::from_fn(|i| COUNTED[k][i].load(Ordering::Relaxed))), + unread: UNREAD_DRAWS.load(Ordering::Relaxed), + } +} + +impl CensusSnapshot { + /// everything counted (a line is printed when it moved) + pub(super) fn sum(&self) -> u64 { + self.n.iter().flatten().flatten().sum::() + self.counted.iter().flatten().sum::() + self.unread + } + + pub(super) fn checked_draws(&self) -> u64 { + (0..4).map(|p| self.n[1][p][Fate::Checked as usize]).sum() + } + + /// The line's census part; `checked_2s`: draws checked since the last line. + pub(super) fn text(&self, checked_2s: u64) -> String { + let part = |k: usize| { + let place = |p: usize| self.n[k][p].iter().sum::(); + let fate = |f: usize| (0..4).map(|p| self.n[k][p][f]).sum::(); + let total: u64 = (0..4).map(place).sum(); + format!( + "{total} (unified memory {}, upload {}, outside unified memory {}, unknown {}; checked {}, as they were {}, skipped for XCL_INDIRECT_OWN {}, not recorded {}; {} with a count buffer, {} of those outside unified memory{})", + place(0), place(1), place(2), place(3), fate(1), fate(0), fate(2), fate(3), self.counted[k][0], self.counted[k][1], + if k == 1 { format!("; {} with a signature the check does not read", self.unread) } else { String::new() } + ) + }; + format!("compute {}, draws {}, {checked_2s} draws checked in the last 2 s", part(0), part(1)) + } +} + +#[cfg(test)] +thread_local! { + /// (tests) the last ExecuteIndirect this thread counted: (draws, place, fate) + static LAST_CENSUS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +pub(super) fn take_last_census() -> Option<(bool, Args, Fate)> { + LAST_CENSUS.with(|c| c.take()) +} + +#[cfg(test)] +pub(super) fn census_of(gfx: bool, place: Args) -> u64 { + (0..4).map(|f| CENSUS[gfx as usize][place.index()][f].load(Ordering::Relaxed)).sum() +} + #[cfg(test)] mod tests { use super::*; @@ -482,7 +1365,7 @@ mod tests { ).unwrap(); let work = compute_pso(&dev, &prep.root, &work).unwrap(); let va = scratch.GetGPUVirtualAddress(); - let config = [max, 0, stride, 8, 12, IO_BYTES, IO_BYTES, 2, 0, 0, va as u32, (va >> 32) as u32, IO_BYTES]; + let config = [max, 0, stride, 8, 12, IO_BYTES, IO_BYTES, 2, 0, 0, va as u32, (va >> 32) as u32, IO_BYTES, 1 << 22]; prep.dispatch(&list, false, src.GetGPUVirtualAddress(), va, &packed, &config, 1); list.SetPipelineState(&work); list.SetComputeRootSignature(&prep.root); @@ -536,4 +1419,677 @@ mod tests { allocator_reset(allocator_key); } } + + #[test] + fn the_check_keeps_sane_group_counts_and_drops_absurd_ones() { + let cap = 1 << 22; + for g in [[0, 0, 0], [480, 270, 1], [65_535, 1, 1], [4_194_304, 1, 1], [2048, 2048, 1], [1, 65_535, 64], [7, 0, 9], [0, 65_535, 65_535]] { + assert!(groups_ok(g, cap), "{g:?}"); + } + for g in [[4_194_305, 1, 1], [2048, 2049, 1], [65_535, 65_535, 1], [0x3f80_0000, 1, 1], [u32::MAX, u32::MAX, u32::MAX], [1, 65_536, 1], [1, 1, 65_536], [0, 65_536, 1], [2, 2048, 1025]] { + assert!(!groups_ok(g, cap), "{g:?}"); + } + assert!(groups_ok([5, 1, 1], 5) && !groups_ok([6, 1, 1], 5)); + } + + #[test] + fn plain_dispatch_signatures_are_known_until_forgotten() { + let sig = 0x6a_1000; + note_plain_dispatch(sig, 16); + assert_eq!(plain_dispatch(sig), Some(16)); + // not a stride the check reads + note_plain_dispatch(sig + 1, 10); + assert_eq!(plain_dispatch(sig + 1), None); + forget(sig); + assert_eq!(plain_dispatch(sig), None); + } + + /// The check on D3DMetal (or any D3D12), its three sources: an upload buffer (SRV), the + /// title's own buffer in INDIRECT_ARGUMENT state (SRV, transitioned for the pass and back) + /// and a window-like UAV. Six commands – two sane, one of zero groups, three absurd: the + /// counting program must run 2 + 65 535 groups. (Were nothing dropped: about 8.5 million + /// one-thread groups – well under a second, nothing that could hang the GPU.) + #[test] + fn gpu_sanitize_runs_only_sane_group_counts() { + use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + if recomp::dxc::create_instance().is_none() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let buffer = |bytes: u64, heap, state, flags| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() + }; + let mut out = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out).unwrap(); + out.unwrap() + }; + let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // six commands of 16 bytes (a stride with a word the check does not read) + let commands: [[u32; 4]; 6] = [[2, 1, 1, 7], [4_194_305, 1, 1, 7], [2048, 2049, 1, 7], [1, 65_536, 1, 7], [3, 1, 0, 7], [65_535, 1, 1, 7]]; + let upload = buffer(256, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE); + let mut mapped: *mut c_void = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::write_bytes(mapped.cast::(), 0, 256); + std::ptr::copy_nonoverlapping(commands.as_ptr().cast::(), mapped.cast::(), 96); + upload.Unmap(0, None); + let own = buffer(96, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + let window = buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, uav); + let results: Vec = (0..3).map(|_| buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, uav)).collect(); + let readback = buffer(3 * 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + list.CopyBufferRegion(&own, 0, &upload, 0, 96); + // the window-like source: the commands 32 bytes in + list.CopyBufferRegion(&window, 32, &upload, 0, 96); + for r in &results { + list.CopyBufferRegion(r, 0, &upload, 128, 16); + } + transition(&list, &own, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + transition(&list, &window, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + for r in &results { + transition(&list, r, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + // the program the commands run: it counts its groups + let params = [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: 1, pParameters: params.as_ptr(), ..Default::default() }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).unwrap(); + let blob = blob.unwrap(); + let root: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize())).unwrap(); + let work = recomp::dxc::compile( + "RWByteAddressBuffer result : register(u0); [numthreads(1,1,1)] void main() { uint o; result.InterlockedAdd(0, 1, o); }", + "main", "cs_6_0", &[], + ).unwrap(); + let work = compute_pso(&dev, &root, &work).unwrap(); + let key = allocator.as_raw() as usize; + let mut checked = Vec::new(); + for (k, result) in results.iter().enumerate() { + let s = match k { + 0 => Sanitize::prepare(&list, key, upload.as_raw() as usize, 0, 16, 6).unwrap(), + 1 => Sanitize::prepare(&list, key, own.as_raw() as usize, 0, 16, 6).unwrap(), + _ => { + let mut s = Sanitize::prepare(&list, key, upload.as_raw() as usize, 0, 16, 6).unwrap(); + s.pipe = sanitize_pipeline(&dev, true).unwrap(); + s.source = Source::Window(window.GetGPUVirtualAddress(), 32); + s + } + }; + match (k, &s.source) { + (0, Source::Srv(_, _, None)) | (1, Source::Srv(_, _, Some(_))) | (2, Source::Window(..)) => {} + _ => panic!("source {k} is not the one meant"), + } + let c = s.record(&list); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&work); + list.SetComputeRootUnorderedAccessView(0, result.GetGPUVirtualAddress()); + list.ExecuteIndirect(&c.signature, 6, &c.buffer, c.offset, None, 0); + c.finish(&list); + checked.push(c); + } + for (k, r) in results.iter().enumerate() { + transition(&list, r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&readback, 256 * k as u64, r, 0, 16); + } + list.Close().unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, event).unwrap(); + let waited = WaitForSingleObject(event, 30_000); + CloseHandle(event).unwrap(); + assert_eq!(waited, WAIT_OBJECT_0); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let got: Vec = (0..3).map(|k| mapped.cast::().add(256 * k).cast::().read()).collect(); + readback.Unmap(0, None); + assert_eq!(got, vec![2 + 65_535; 3], "groups run from the upload / own / window sources"); + drop(checked); + allocator_reset(key); + } + } + + /// What the draw check lets through (`draw_ok`, the GPU check's reference): sane draws – big + /// ones within the caps, ranges up to the last vertex or instance 32 bits reach, an index range + /// inside the bound index buffer – are kept and absurd ones dropped; over an edge grid it is + /// the rule in 64 bits (a release build wraps silently: a wrap term missing, or one that wraps + /// itself like `first + n <= u32::MAX`, shows here; the terms' order cannot – none of them + /// panics or has an effect). + #[test] + fn the_draw_check_keeps_sane_draws_and_drops_absurd_ones() { + // (the default caps: up to 2^23 - 1 vertices an instance, 2^26 vertex instances) + let (cap, work, any) = (MAX_DRAW_COUNT, 1u32 << 26, u32::MAX); + let ok = |d: [u32; 4], bound: u32| draw_ok(d[0], d[1], d[2], d[3], cap, work, bound); + for d in [[3, 1, 0, 0], [36, 1000, 0, 0], [6, 1_000_000, 0, 0], [(1 << 23) - 1, 1, 0, 0], [8192, 8192, 0, 0], [0, 1 << 26, 0, 0], [0, 0, 0, 0], [3, 1, 0xFFFF_FFFC, 0], [3, 2, 0, 0xFFFF_FFFD]] { + assert!(ok(d, any), "kept: {d:?}"); + } + for d in [[100, 1, 0, 0], [10, 2, 90, 0]] { + assert!(ok(d, 100), "kept with 100 indices bound: {d:?}"); + } + // (2^24 vertices: GTA VI's GPU-written records cool_fox found by the list – `MAX_DRAW_COUNT`) + for d in [[1 << 23, 1, 0, 0], [1 << 24, 1, 0, 0], [(1 << 24) + 1, 1, 0, 0], [8192, 8193, 0, 0], [0, (1 << 26) + 1, 0, 0], [3, 1, 0xFFFF_FFFD, 0], [3, 2, 0, 0xFFFF_FFFE], [0x3f80_0000, 0x3f80_0000, 0, 0], [u32::MAX; 4]] { + assert!(!ok(d, any), "dropped: {d:?}"); + } + for d in [[100, 1, 1, 0], [101, 1, 0, 0]] { + assert!(!ok(d, 100), "dropped with 100 indices bound: {d:?}"); + } + assert!(draw_ok(5, 1, 0, 0, 5, work, any) && !draw_ok(6, 1, 0, 0, 5, work, any), "the count cap is the given one"); + // the rule in 64 bits, where nothing wraps + let wide = |n: u32, instances: u32, first: u32, first_instance: u32, bound: u32| { + let (n, instances, first, first_instance) = (u64::from(n), u64::from(instances), u64::from(first), u64::from(first_instance)); + n <= u64::from(cap) + && n.max(1) * instances <= u64::from(work) + && first + n <= u64::from(u32::MAX) + && first_instance + instances <= u64::from(u32::MAX) + && first + n <= u64::from(bound) + }; + let grid: Vec = [0, 1, 2, 3, 100, 8191, 8192, 8193, 1 << 16, (1 << 23) - 1, 1 << 23, (1 << 23) + 1, (1 << 24) - 1, 1 << 24, (1 << 24) + 1, 1 << 26, 1 << 31] + .into_iter() + .chain(u32::MAX - 3..=u32::MAX) + .collect(); + for bound in [100, u32::MAX] { + for &n in &grid { + for &instances in &grid { + for &first in &grid { + for &first_instance in &grid { + assert_eq!( + draw_ok(n, instances, first, first_instance, cap, work, bound), + wide(n, instances, first, first_instance, bound), + "({n}, {instances}, {first}, {first_instance}) with {bound} indices bound" + ); + } + } + } + } + } + } + + /// The draw check's default count cap is 2^23 - 1 (B2-1): a command of 2^24 vertices – GTA VI's + /// records cool_fox found 90 of in one list – or of 2^23 is dropped, one of 2^23 - 1 kept. With + /// the caps' switches as the process was started (set: what they say). + #[test] + fn the_draw_count_cap_is_2_23_less_1_by_default() { + let set = |v: &str| std::env::var(v).is_ok_and(|s| s.trim().parse::().is_ok_and(|n| n > 0)); + if set("XCL_INDIRECT_MAX_DRAW_COUNT") || set("XCL_INDIRECT_MAX_DRAW_WORK") { + assert_ne!(max_draw_count(), 0); + return crate::gpu::recomp::runner::skip_config("XCL_INDIRECT_MAX_DRAW_COUNT or _WORK set"); + } + assert_eq!((max_draw_count(), max_draw_work()), ((1 << 23) - 1, 1 << 26)); + let ok = |n: u32| draw_ok(n, 1, 0, 0, max_draw_count(), max_draw_work(), u32::MAX); + assert!(!ok(1 << 24), "2^24 vertices: dropped"); + assert!(!ok(1 << 23), "2^23: dropped"); + assert!(ok((1 << 23) - 1), "2^23 - 1: kept"); + } + + /// The mode a draw is checked in: the default (`Own`) checks arguments in unified memory and + /// upload buffers too once work of a pipeline not built was skipped; `0` and `all` stay, and an + /// explicit `own` keeps to arguments outside unified memory (PB-2). Any other value is the + /// default. + #[test] + fn the_default_draw_check_covers_unified_memory_once_work_was_skipped() { + assert_eq!(effective_mode(DrawCheck::Own, true), DrawCheck::All); + assert_eq!(effective_mode(DrawCheck::Own, false), DrawCheck::Own); + assert_eq!((effective_mode(DrawCheck::All, false), effective_mode(DrawCheck::All, true)), (DrawCheck::All, DrawCheck::All)); + assert_eq!((effective_mode(DrawCheck::Off, false), effective_mode(DrawCheck::Off, true)), (DrawCheck::Off, DrawCheck::Off)); + assert_eq!(draw_check_of(None), (DrawCheck::Own, true), "unset: the default, upgraded"); + assert_eq!(draw_check_of(Some(" own ")), (DrawCheck::Own, false), "own: never upgraded"); + assert_eq!(draw_check_of(Some("OWN")), (DrawCheck::Own, false)); + assert_eq!(draw_check_of(Some("all")), (DrawCheck::All, false)); + assert_eq!(draw_check_of(Some("0")), (DrawCheck::Off, false)); + assert_eq!(draw_check_of(Some("1")), (DrawCheck::Own, true), "another value: the default"); + // the setting is what the switch says as the process was started + let env = std::env::var("XCL_INDIRECT_SANITIZE_DRAWS").ok(); + let set = if sanitize_on() { draw_check_of(env.as_deref()) } else { (DrawCheck::Off, false) }; + assert_eq!(draw_check_setting(), set, "XCL_INDIRECT_SANITIZE_DRAWS={env:?}"); + // what the upgrade decides for a plain draw in window 0 (`draw_check_in`, its mode given) + let s = 0x7A0C_3000usize; + note_plain_draw(s, 16, false); + let never = || -> u32 { panic!("not an indexed draw") }; + assert_eq!(draw_check_in(effective_mode(DrawCheck::Own, false), Args::Window(0), s, never), None, "nothing skipped: as it was"); + assert_eq!(draw_check_in(effective_mode(DrawCheck::Own, true), Args::Window(0), s, never), Some((16, Command::Draw)), "work skipped: checked"); + assert_eq!(draw_check_in(effective_mode(DrawCheck::Own, true), Args::Upload, s, never), Some((16, Command::Draw))); + // `draw_check` itself, with the switch as the process was started: once work was skipped – + // this test skips some; the count never goes down – the default checks it in window 0 too + super::super::pso_async::note_skip(0x7A0C_30FF); + let want = match draw_check_setting() { + (DrawCheck::Off, _) | (DrawCheck::Own, false) => None, + _ => Some((16, Command::Draw)), + }; + assert_eq!(draw_check(Args::Window(0), s, never), want, "{:?}", draw_check_setting()); + forget(s); + } + + /// Plain draw signatures – one DRAW of 16 bytes or more, or one DRAW_INDEXED of 20 – are known + /// until forgotten; the check looks at their arguments where its mode says (by default outside + /// unified memory or in a resource XCL does not know; `all`: anywhere) and asks for the bound + /// index buffer only for an indexed draw. + #[test] + fn plain_draw_signatures_are_known_until_forgotten_and_checked_where_they_live() { + let s = 0x7B00_8000usize; + note_plain_draw(s, 16, false); + note_plain_draw(s + 1, 20, true); + note_plain_draw(s + 2, 16, true); + note_plain_draw(s + 3, 18, false); + note_plain_draw(s + 4, 32, false); + assert_eq!(plain_draw(s), Some((16, false))); + assert_eq!(plain_draw(s + 1), Some((20, true))); + assert_eq!(plain_draw(s + 2), None, "an indexed draw reads 20 bytes"); + assert_eq!(plain_draw(s + 3), None, "not a stride the check reads"); + assert_eq!(plain_draw(s + 4), Some((32, false))); + let never = || -> u32 { panic!("the bound index buffer is asked only for an indexed draw") }; + assert_eq!(draw_check_in(DrawCheck::Off, Args::Own, s, never), None, "off"); + assert_eq!(draw_check_in(DrawCheck::Own, Args::Own, s, never), Some((16, Command::Draw))); + assert_eq!(draw_check_in(DrawCheck::Own, Args::Window(0), s, never), None, "unified memory: what translated programs wrote"); + assert_eq!(draw_check_in(DrawCheck::Own, Args::Unknown, s, never), Some((16, Command::Draw))); + assert_eq!(draw_check_in(DrawCheck::All, Args::Window(0), s, never), Some((16, Command::Draw)), "all: anywhere"); + let indices = if draw_indices_on() { 7 } else { u32::MAX }; + assert_eq!(draw_check_in(DrawCheck::All, Args::Upload, s + 1, || 7), Some((20, Command::DrawIndexed { indices }))); + assert_eq!(draw_check_in(DrawCheck::Own, Args::Own, s + 5, never), None, "a signature the check does not read"); + forget(s); + assert_eq!(plain_draw(s), None); + forget(s + 1); + forget(s + 4); + assert_eq!((plain_draw(s + 1), plain_draw(s + 4)), (None, None)); + } + + /// A buffer of `bytes` on `heap` for the GPU tests. + unsafe fn test_buffer(dev: &ID3D12Device, bytes: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, flags: D3D12_RESOURCE_FLAGS) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() + }; + let mut out = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out).unwrap(); + out.unwrap() + } + + /// An upload buffer of `bytes` holding `words` from its start. + unsafe fn test_upload(dev: &ID3D12Device, bytes: u64, words: &[u32]) -> ID3D12Resource { + let upload = test_buffer(dev, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE); + let mut mapped: *mut c_void = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::write_bytes(mapped.cast::(), 0, bytes as usize); + std::ptr::copy_nonoverlapping(words.as_ptr(), mapped.cast::(), words.len()); + upload.Unmap(0, None); + upload + } + + /// `list` closed, run on `queue` and waited for (`limit_ms`). + unsafe fn run_and_wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue, list: &ID3D12GraphicsCommandList, limit_ms: u32) { + use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + list.Close().unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, event).unwrap(); + let waited = WaitForSingleObject(event, limit_ms); + CloseHandle(event).unwrap(); + assert_eq!(waited, WAIT_OBJECT_0, "the GPU did not finish within {limit_ms} ms"); + } + + /// The adapter's device; None (the test says SKIPPED) without one. + unsafe fn gpu() -> Option { + let mut dev: Option = None; + if D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + dev + } + + /// The adapter's device and DXC; None (the test says SKIPPED) without them. + unsafe fn gpu_and_dxc() -> Option { + let dev = gpu()?; + if recomp::dxc::create_instance().is_none() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return None; + } + Some(dev) + } + + /// The draw check on D3DMetal (or any D3D12) is its CPU reference (`draw_ok`), word for word, + /// for its three sources – an upload buffer (SRV), the title's own buffer in INDIRECT_ARGUMENT + /// state (SRV, transitioned for the pass and back) and a window-like UAV: DRAWs of 20 bytes a + /// command and DRAW_INDEXEDs of 24 (a word the check does not read after each), these with an + /// index buffer of 100 indices bound and with none known. + #[test] + fn gpu_draw_check_matches_its_cpu_reference() { + unsafe { + let Some(dev) = gpu_and_dxc() else { return }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + // 8 DRAWs kept and 4 dropped (the default caps: 2^23 - 1 vertices an instance at most – + // 2^24 dropped), at 0, 20 bytes apart + let draws: [[u32; 4]; 12] = [ + [3, 1, 0, 0], [36, 1000, 0, 0], [6, 1_000_000, 0, 0], [(1 << 23) - 1, 1, 0, 0], [8192, 8192, 0, 0], [0, 1 << 26, 0, 0], + [3, 1, 0xFFFF_FFFC, 0], [3, 2, 0, 0xFFFF_FFFD], [1 << 24, 1, 0, 0], [8192, 8193, 0, 0], [3, 1, 0xFFFF_FFFD, 0], [u32::MAX; 4], + ]; + // DRAW_INDEXEDs (indices, instances, first index, base vertex, first instance), at 256, 24 bytes apart + // (2^23 indices: the default cap's first dropped count) + let indexed: [[u32; 5]; 8] = [ + [100, 1, 0, (-5i32) as u32, 0], [10, 2, 90, 0, 0], [100, 1, 1, 0, 0], [101, 1, 0, 0, 0], + [1 << 23, 1, 0, 0, 0], [3, 2, 0, 0, 0xFFFF_FFFE], [0, 0, 0, 0, 0], [u32::MAX; 5], + ]; + let mut words = vec![0u32; 128]; + for (k, d) in draws.iter().enumerate() { + words[k * 5..k * 5 + 4].copy_from_slice(d); + words[k * 5 + 4] = 0xDEAD; + } + for (k, d) in indexed.iter().enumerate() { + let at = 64 + k * 6; + words[at..at + 5].copy_from_slice(d); + words[at + 5] = 0xDEAD; + } + let upload = test_upload(&dev, 512, &words); + let own = test_buffer(&dev, 512, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + let window = test_buffer(&dev, 1024, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let readback = test_buffer(&dev, 9 * 256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + list.CopyBufferRegion(&own, 0, &upload, 0, 512); + // the window-like source: the commands 32 bytes in + list.CopyBufferRegion(&window, 32, &upload, 0, 512); + transition(&list, &own, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + transition(&list, &window, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + let key = allocator.as_raw() as usize; + // (command, commands, stride, where they are) + let runs = [(Command::Draw, 12u32, 20u32, 0u64), (Command::DrawIndexed { indices: 100 }, 8, 24, 256), (Command::DrawIndexed { indices: u32::MAX }, 8, 24, 256)]; + let mut checked = Vec::new(); + for src in 0..3 { + for (r, &(cmd, max, stride, at)) in runs.iter().enumerate() { + let s = match src { + 0 => Sanitize::prepare_command(&list, key, upload.as_raw() as usize, at, stride, max, cmd).unwrap(), + 1 => Sanitize::prepare_command(&list, key, own.as_raw() as usize, at, stride, max, cmd).unwrap(), + _ => { + let mut s = Sanitize::prepare_command(&list, key, upload.as_raw() as usize, at, stride, max, cmd).unwrap(); + s.pipe = sanitize_draw_pipeline(&dev, true, cmd != Command::Draw).unwrap(); + s.source = Source::Window(window.GetGPUVirtualAddress(), 32 + at as u32); + s + } + }; + match (src, &s.source) { + (0, Source::Srv(_, _, None)) | (1, Source::Srv(_, _, Some(_))) | (2, Source::Window(..)) => {} + _ => panic!("source {src} is not the one meant"), + } + let c = s.record(&list); + // XCL's checked commands to the readback buffer; the chunk back to its state for the + // next pass (which writes it as a UAV) + transition(&list, &c.buffer, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&readback, 256 * (3 * src + r) as u64, &c.buffer, c.offset, u64::from(max * cmd.bytes())); + transition(&list, &c.buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + checked.push(c); + } + } + run_and_wait(&dev, &queue, &list, 30_000); + let mut mapped: *mut c_void = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let read = |slot: usize, at: usize| mapped.cast::().add(256 * slot + at).cast::().read(); + let (cap, work) = (max_draw_count(), max_draw_work()); + for src in 0..3 { + for (k, d) in draws.iter().enumerate() { + let want = if draw_ok(d[0], d[1], d[2], d[3], cap, work, u32::MAX) { *d } else { [0; 4] }; + let got: [u32; 4] = std::array::from_fn(|w| read(3 * src, k * 16 + w * 4)); + assert_eq!(got, want, "source {src}: DRAW {k} {d:?}"); + } + for (r, bound) in [(1, 100), (2, u32::MAX)] { + for (k, d) in indexed.iter().enumerate() { + let want = if draw_ok(d[0], d[1], d[2], d[4], cap, work, bound) { *d } else { [0; 5] }; + let got: [u32; 5] = std::array::from_fn(|w| read(3 * src + r, k * 20 + w * 4)); + assert_eq!(got, want, "source {src}: DRAW_INDEXED {k} {d:?} with {bound} indices bound"); + } + } + } + readback.Unmap(0, None); + drop(checked); + allocator_reset(key); + } + } + + /// A 16×16 R8G8B8A8 target on the adapter's device, its own queue and recording list, an empty + /// root signature and a pipeline whose triangle t (vertices 3t … 3t + 2) of instance i covers + /// the centre of pixel (t mod 16, i mod 16) only. Every draw of the tests starts at vertex 0 + /// and instance 0: nothing depends on SV_VertexID's base. + struct Pixels { + dev: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + target: ID3D12Resource, + rtv_heap: ID3D12DescriptorHeap, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + } + + const PIXELS_VS: &str = r#" +float4 main(uint vid : SV_VertexID, uint iid : SV_InstanceID) : SV_Position { + uint t = vid / 3u; + uint c = vid % 3u; + float2 p = float2(float(t % 16u), float(iid % 16u)) + 0.25; + if (c == 1u) + p.x += 1.0; + if (c == 2u) + p.y += 1.0; + return float4(p.x / 8.0 - 1.0, 1.0 - p.y / 8.0, 0.0, 1.0); +} +"#; + + const PIXELS_PS: &str = "float4 main() : SV_Target { return float4(1.0, 1.0, 1.0, 1.0); }"; + + impl Pixels { + /// None: no GPU or no DXC (the test says SKIPPED). + unsafe fn new() -> Option { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + let dev = gpu_and_dxc()?; + let vs = recomp::dxc::compile(PIXELS_VS, "main", "vs_6_0", &[]).expect("the harness's VS"); + let ps = recomp::dxc::compile(PIXELS_PS, "main", "ps_6_0", &[]).expect("the harness's PS"); + let mut blob = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).unwrap(); + let blob = blob.unwrap(); + let root: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize())).unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(root.clone())), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr().cast(), BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = true.into(); + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: windows::core::Result = dev.CreateGraphicsPipelineState(&desc); + ManuallyDrop::drop(&mut desc.pRootSignature); + let pso = pso.expect("the harness's pipeline"); + let tex = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 16, Height: 16, DepthOrArraySize: 1, MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, ..Default::default() + }; + let clear = D3D12_CLEAR_VALUE { Format: DXGI_FORMAT_R8G8B8A8_UNORM, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] } }; + let mut target: 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(&clear), &mut target, + ).unwrap(); + let target = target.unwrap(); + let rtv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }).unwrap(); + dev.CreateRenderTargetView(&target, None, rtv_heap.GetCPUDescriptorHandleForHeapStart()); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + Some(Pixels { dev, queue, allocator, list, target, rtv_heap, root, pso }) + } + + /// The target bound and cleared, its viewport and scissor, a triangle list, the root + /// signature and the pipeline. + unsafe fn start(&self) { + let rtv = self.rtv_heap.GetCPUDescriptorHandleForHeapStart(); + self.list.OMSetRenderTargets(1, Some(&rtv), false, None); + self.list.ClearRenderTargetView(rtv, &[0.0; 4], None); + self.list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: 16.0, Height: 16.0, MinDepth: 0.0, MaxDepth: 1.0 }]); + self.list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: 0, top: 0, right: 16, bottom: 16 }]); + self.list.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + self.bind(); + } + + /// The root signature and the pipeline (again: XCL's check pass binds its own). + unsafe fn bind(&self) { + self.list.SetGraphicsRootSignature(&self.root); + self.list.SetPipelineState(&self.pso); + } + + /// The list run (10 s at most); the pixels that are not 0, as (x, y), row by row. + unsafe fn lit(&self) -> Vec<(u32, u32)> { + let tex = self.target.GetDesc(); + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + self.dev.GetCopyableFootprints(&tex, 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); + let readback = test_buffer(&self.dev, total, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + transition(&self.list, &self.target, D3D12_RESOURCE_STATE_RENDER_TARGET, 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: footprint }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&self.target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + self.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + run_and_wait(&self.dev, &self.queue, &self.list, 10_000); + let mut mapped: *mut c_void = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let pitch = footprint.Footprint.RowPitch as usize; + let mut lit = Vec::new(); + for y in 0..16u32 { + for x in 0..16u32 { + if mapped.cast::().add(y as usize * pitch + x as usize * 4).cast::().read() != 0 { + lit.push((x, y)); + } + } + } + readback.Unmap(0, None); + lit + } + } + + /// XCL's checked draws end to end on D3DMetal (or any D3D12): six DRAW commands from the title's + /// own buffer go through the check to an ExecuteIndirect with XCL's 16-byte signature – the two + /// absurd ones (2^24 + 3 vertices; 22 369 622 instances of 3, over 2^26) draw nothing, the two + /// of nothing nothing, the two sane ones draw – after a direct draw: exactly 7 pixels lit, (0,2) + /// by the direct draw only (what it drew outlived the check's compute pass between the two). + /// (Were nothing dropped: row 0 and column 0, about 32 pixels – some 84 million vertices, well + /// under a second.) + #[test] + fn gpu_checked_indirect_draws_draw_only_sane_commands() { + unsafe { + let Some(px) = Pixels::new() else { return }; + // the title's own buffer: six DRAW commands of 20 bytes (a word the check does not read after each) + let commands: [[u32; 4]; 6] = [[6, 2, 0, 0], [16_777_219, 1, 0, 0], [0, 7, 0, 0], [3, 22_369_622, 0, 0], [12, 1, 0, 0], [3, 0, 0, 0]]; + let words: Vec = commands.iter().flat_map(|c| c.iter().copied().chain([0xDEAD])).collect(); + let upload = test_upload(&px.dev, 256, &words); + let own = test_buffer(&px.dev, 128, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + px.list.CopyBufferRegion(&own, 0, &upload, 0, 120); + transition(&px.list, &own, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + px.start(); + // the harness: (0,0) (0,1) (0,2) lit directly, before the check + px.list.DrawInstanced(3, 3, 0, 0); + let key = px.allocator.as_raw() as usize; + let c = Sanitize::prepare_command(&px.list, key, own.as_raw() as usize, 0, 20, 6, Command::Draw).unwrap().record(&px.list); + px.bind(); + px.list.ExecuteIndirect(&c.signature, 6, &c.buffer, c.offset, None, 0); + c.finish(&px.list); + let lit = px.lit(); + assert!( + [(0, 0), (0, 1), (0, 2)].iter().all(|p| lit.contains(p)), + "the harness failed on this GPU, not the check: the direct draw lit {lit:?}" + ); + assert_eq!(lit, vec![(0, 0), (1, 0), (2, 0), (3, 0), (0, 1), (1, 1), (0, 2)], "only the sane commands drew"); + drop(c); + allocator_reset(key); + } + } + + /// (probe) D3D12 runs min(count, max) commands of an ExecuteIndirect with a count buffer; the + /// checks (0021's and the draw check) keep the title's count and check `max` commands, so they + /// rely on D3DMetal doing the same: four commands, k lighting (0,0) … (k,0), a count of 3 and a + /// max of 2 must light 2 pixels (3: the count is not clamped – the checks need a count clamp). + #[test] + #[ignore = "a probe of D3DMetal (min(count, max) commands of an ExecuteIndirect); run it with --ignored"] + fn gpu_an_indirect_draw_count_above_its_max_runs_max_commands() { + unsafe { + let Some(px) = Pixels::new() else { return }; + let mut words = vec![0u32; 65]; + for k in 0..4u32 { + words[k as usize * 4..k as usize * 4 + 4].copy_from_slice(&[3 * (k + 1), 1, 0, 0]); + } + // the count, 256 bytes in + words[64] = 3; + let upload = test_upload(&px.dev, 512, &words); + px.start(); + let sig = draw_signature(&px.dev, false).unwrap(); + px.list.ExecuteIndirect(&sig, 2, &upload, 0, &upload, 256); + let lit = px.lit(); + assert_eq!(lit, vec![(0, 0), (1, 0)], "2 commands: min(count 3, max 2); 3 pixels: the count is not clamped to max"); + } + } + + /// (probe) A new committed DEFAULT buffer reads zeros (what a title buffer XCL makes outside the + /// windows holds before anything writes it); 16 bytes copied into another new one first are + /// read back as they are (the copies work). + #[test] + #[ignore = "a probe of D3DMetal (does a new DEFAULT buffer read zeros?); run it with --ignored"] + fn gpu_a_new_default_buffer_reads_zero() { + unsafe { + let Some(dev) = gpu() else { return }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + const MIB: u64 = 1 << 20; + let fresh = test_buffer(&dev, MIB, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + let written = test_buffer(&dev, MIB, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + let upload = test_upload(&dev, 256, &[0xABAB_ABAB; 4]); + let readback = test_buffer(&dev, 2 * MIB, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + list.CopyBufferRegion(&written, 0, &upload, 0, 16); + for b in [&fresh, &written] { + transition(&list, b, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + } + list.CopyBufferRegion(&readback, 0, &fresh, 0, MIB); + list.CopyBufferRegion(&readback, MIB, &written, 0, MIB); + run_and_wait(&dev, &queue, &list, 10_000); + let mut mapped: *mut c_void = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let bytes = std::slice::from_raw_parts(mapped.cast::(), 2 * MIB as usize); + let copied = bytes[MIB as usize..MIB as usize + 16].to_vec(); + let not_zero = bytes[..MIB as usize].iter().filter(|&&b| b != 0).count(); + let first = bytes[..MIB as usize].iter().position(|&b| b != 0); + readback.Unmap(0, None); + assert_eq!(copied, vec![0xAB; 16], "a copy into a new buffer is read back (else this probe says nothing)"); + assert_eq!(not_zero, 0, "a new DEFAULT buffer reads zeros: {not_zero} bytes are not, the first at {first:?}"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl b/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl index 4612354..edce25b 100644 --- a/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl +++ b/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl @@ -11,6 +11,9 @@ cbuffer Config : register(b0) { uint action_bytes, scratch_stride, template_bytes, patch_count; uint scratch_lo, scratch_hi, va_lo, va_hi; uint io_bytes; + // groups a dispatch command may have (0: not checked – draws); more, or Y or Z above + // 65535, and it runs none (`indirect::groups_ok`) + uint cap; }; uint2 offset_address(uint lo, uint hi, uint offset) { @@ -36,6 +39,13 @@ void main(uint3 id : SV_DispatchThreadID) { uint record = id.x * (8 + action_bytes); packed.Store2(record, offset_address(va_lo, va_hi, dst)); - for (uint k = 0; k < action_bytes; k += 4) - packed.Store(record + 8 + k, source.Load(src + action_offset + k)); + if (action_bytes == 12u && cap != 0u) { + uint3 g = source.Load3(src + action_offset); + bool ok = g.x <= cap && g.y <= 65535u && g.z <= 65535u + && (g.x == 0u || g.y == 0u || g.z == 0u || (g.y <= cap / g.x && g.z <= cap / (g.x * g.y))); + packed.Store3(record + 8u, ok ? g : uint3(0u, 0u, 0u)); + } else { + for (uint k = 0; k < action_bytes; k += 4) + packed.Store(record + 8 + k, source.Load(src + action_offset + k)); + } } diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index d559259..7275443 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -1,247 +1,1121 @@ -//! The title's last `Release` of a resource, put off until the GPU is past the work in flight. +//! The last `Release` of a GPU object, put off until the GPU is past the work in flight. //! //! D3D12 on the PC asks that an object outlives the GPU work that uses it. A console title //! keeps to that by its own count of finished frames – but XCL's submits are not the title's: //! texture uploads go out with a later submit, tile mappings on a queue of XCL's own. A retail //! title's final `Release` of a resource then came while a queue still had work on it (debug -//! layer: "CORRUPTION: … is referenced by GPU operations in-flight", id 921). +//! layer: "CORRUPTION: … is referenced by GPU operations in-flight", id 921). On a Mac that is +//! worse than corruption: Apple's D3DMetal records Metal command buffers with unretained +//! references, and an object (or a tile mapping) that goes while a committed command buffer +//! still names it is walked by the GPU driver when Metal submits that buffer – GTA VI's world +//! load kernel-panicked macOS three times out of three inside IOGPUFamily / AGX +//! (`IOGPUCommandQueueSubmitCommandBuffers`), once with a tag-check fault (a freed kernel +//! object used) in the thread that retires command buffers. //! -//! The last reference is held here instead. Each batch of held resources gets a fence value -//! signalled on every queue with work on it; the batch goes once all of them have passed it. -use std::collections::{HashMap, VecDeque}; +//! So the last reference is held here, against a *mark*: +//! * every queue XCL knows has a clock – XCL's fence on it and the last value *reserved* for a +//! submission. A submission (`submit`) reserves its value before it enters the driver and +//! signals it after, so a mark taken while a submission is in progress (D3DMetal releases +//! objects from inside `ExecuteCommandLists`) waits for that very submission; +//! * a mark is the value reserved on every clock when the object went; it has passed once every +//! clock's fence has reached it; +//! * on the Mac an entry also waits out a grace period after it passed (Metal reports command +//! buffers complete only after the kernel retires them, a little after their fence value is +//! written), and at most a few go per tick, on a thread of their own, outside every lock. +//! +//! The same marks order the sparse windows' tile unmappings (`sparse`): a tile the title +//! decommitted stays mapped until the work submitted before the decommit is done. +use std::cell::RefCell; +use std::collections::VecDeque; use std::ffi::c_void; -use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; -/// a batch is not closed more often than this (a `Signal` a queue each time) -const SEAL_EVERY: Duration = Duration::from_millis(10); -/// how often the thread here looks for batches that can go +use super::real::Kind; + +/// how often the thread here looks for entries that can go const TICK: Duration = Duration::from_millis(4); +/// entries released per tick at most (a burst of thousands is spread out) +const MAX_PER_TICK: usize = 64; +/// clocks (queues) at most (a mark keeps a value of each: `RING`) +const MAX_CLOCKS: usize = 32; + +// --- the switches ----------------------------------------------------------------------- +// +// A Release hook can run on a thread D3DMetal made itself – a Metal completion handler on a +// dispatch queue releases the objects it kept for a command buffer through their tables. Such a +// thread has no TEB: no environment, no thread-local, no heap, no lock that can block works +// there (one that touched any of them faulted, Wine's handler on that thread never came back, +// and the queue never signalled its fence again). So what a hook reads was settled before, on a +// thread of Wine's (`init`), and what it does with a reference it holds touches atomics only +// (`RING`). + +static SETTLED: AtomicBool = AtomicBool::new(false); +static ON: AtomicBool = AtomicBool::new(false); +static MAC: AtomicBool = AtomicBool::new(false); +static SERIAL: AtomicBool = AtomicBool::new(false); +/// `XCL_LATE_RELEASE_TOUCH=1` (off by default): `touched` re-marks a held object when XCL lets +/// go of a reference of its own. Off: XCL looks at the textures it keeps in step every frame +/// (a clone, then its Release), and a texture the title had let go of was touched again before +/// its grace was up, every time – never let go: GTA VI's world load piled up 8 GB of them in 16 s. +static TOUCH: AtomicBool = AtomicBool::new(false); +/// a bit per `Kind` (`kind as u32`) whose last Release is held +static DEFERRED: AtomicU32 = AtomicU32::new(0); +static GRACE_MS: AtomicU64 = AtomicU64::new(0); + +/// The switches, read once (on a thread of Wine's: any call but a Release hook's), and – on the +/// Mac – the ledger's thread started. +pub fn init() { + if SETTLED.load(Ordering::Acquire) { + return; + } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let env = |k: &str| std::env::var(k).ok().map(|v| v.trim().to_string()); + let on = env("XCL_LATE_RELEASE").as_deref() != Some("0"); + let mac = crate::util::mac_host(); + // Resources always (but with XCL_LATE_RELEASE=0); heaps, descriptor heaps, pipelines, + // allocators, lists, command signatures, query heaps and root signatures on the Mac + // (XCL_LATE_RELEASE_ALL=0: not; =1: elsewhere too). Queues, fences, the device: never. + let all = match env("XCL_LATE_RELEASE_ALL").as_deref() { + Some("0") => false, + Some("1") => true, + _ => mac, + }; + let mut mask = 1u32 << (Kind::Resource as u32); + if all { + for k in [Kind::Heap, Kind::DescriptorHeap, Kind::PipelineState, Kind::CommandAllocator, Kind::CommandList, Kind::DmaList, Kind::CommandSignature, Kind::QueryHeap, Kind::RootSignature] { + mask |= 1 << (k as u32); + } + } + let grace = env("XCL_LATE_RELEASE_GRACE_MS").and_then(|v| v.parse::().ok()).unwrap_or(if mac { 100 } else { 0 }); + TOUCH.store(env("XCL_LATE_RELEASE_TOUCH").as_deref() == Some("1"), Ordering::Relaxed); + let mut serial = env("XCL_LATE_RELEASE_SERIAL").as_deref() == Some("1"); + if serial && mac && env("XCL_SERIALIZE_TILES").as_deref() == Some("1") { + // (a submitter holds d3d_ops while it waits for the gate; the worker holds the gate + // while a release unmaps tiles, which takes d3d_ops) + crate::xlog_warn!("D3D12.X: XCL_LATE_RELEASE_SERIAL=1 is not taken with XCL_SERIALIZE_TILES=1 (they would wait for each other)"); + serial = false; + } + if serial { + crate::xlog_info!("D3D12.X: deferred releases never overlap a submission (XCL_LATE_RELEASE_SERIAL=1)"); + } + ON.store(on, Ordering::Relaxed); + MAC.store(mac, Ordering::Relaxed); + SERIAL.store(serial, Ordering::Relaxed); + DEFERRED.store(if on { mask } else { 0 }, Ordering::Relaxed); + GRACE_MS.store(grace, Ordering::Relaxed); + SETTLED.store(true, Ordering::Release); + if on && mac { + start_worker(); + } + }); +} + +/// Whether last releases are held (`XCL_LATE_RELEASE=0` turns it off). (Not from a hook.) +pub fn enabled() -> bool { + init(); + ON.load(Ordering::Relaxed) +} + +/// Whether the last Release of an adopted object of `kind` is held here (atomics only: a hook +/// asks; before `init`, nothing is). +pub fn defers(kind: Kind) -> bool { + SETTLED.load(Ordering::Acquire) && DEFERRED.load(Ordering::Relaxed) & (1 << (kind as u32)) != 0 +} + +/// Whether XCL runs on a Mac (atomics only; false before `init`). +pub fn mac() -> bool { + MAC.load(Ordering::Relaxed) +} + +/// How long an entry waits after its mark passed: 100 ms on the Mac, none elsewhere +/// (`XCL_LATE_RELEASE_GRACE_MS` sets it). +fn grace() -> Duration { + Duration::from_millis(GRACE_MS.load(Ordering::Relaxed)) +} + +/// `XCL_LATE_RELEASE_SERIAL=1` (an experiment, off by default): the worker's final releases +/// never overlap a submission – it skips a tick while one is in progress, and a submission +/// waits for at most one batch of releases. +fn serial() -> bool { + SERIAL.load(Ordering::Relaxed) +} + +/// submissions hold it shared, the worker's releases exclusively (`serial`) +static GATE: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +/// signals `v` on the queue (the pointer `submit` was given) after a submission +type SignalFn = Box; + +/// A queue's clock. +pub struct Clock { + key: usize, + /// the last value reserved: by `submit` for queues of XCL's own fence, by the owner for + /// external clocks (published before each driver call that is signalled after) + reserved: Reserved, + /// the value the GPU has reached + progress: Box u64 + Send + Sync>, + /// None: the owner signals + signal: Option, + /// submissions to one queue reserve and signal in order + submits: Mutex<()>, +} -struct Batch { - dead: Vec, - /// (fence, value) a queue: all reached = nothing submitted before the batch closed is left - marks: Vec<(ID3D12Fence, u64)>, +enum Reserved { + Own(AtomicU64), + External(&'static AtomicU64), } +impl Reserved { + fn get(&self) -> &AtomicU64 { + match self { + Reserved::Own(a) => a, + Reserved::External(a) => a, + } + } +} + +/// An append-only table of clocks, read without a lock. +pub struct Clocks { + list: [OnceLock; MAX_CLOCKS], + n: AtomicUsize, + adding: Mutex<()>, +} + +impl Clocks { + pub const fn new() -> Self { + Clocks { list: [const { OnceLock::new() }; MAX_CLOCKS], n: AtomicUsize::new(0), adding: Mutex::new(()) } + } + + fn len(&self) -> usize { + self.n.load(Ordering::Acquire) + } + + fn get(&self, i: usize) -> Option<&Clock> { + self.list.get(i)?.get() + } + + fn find(&self, key: usize) -> Option<&Clock> { + (0..self.len()).filter_map(|i| self.get(i)).find(|c| c.key == key) + } + + /// Adds `c` unless a clock of its key is there (a queue at the address of one that went goes + /// on with its clock: the values only grow). False: the table is full. + fn add(&self, c: Clock) -> bool { + let _g = self.adding.lock().unwrap_or_else(|e| e.into_inner()); + if self.find(c.key).is_some() { + return true; + } + let i = self.len(); + if i >= MAX_CLOCKS { + return false; + } + let _ = self.list[i].set(c); + self.n.store(i + 1, Ordering::Release); + true + } + + /// The value reserved on every clock now (index = clock index; 0 = nothing to wait for). + /// Lock-free and no driver call: safe inside a driver call that releases objects. + pub fn mark(&self) -> Arc { + let values = (0..self.len()).map(|i| self.get(i).map_or(0, |c| c.reserved.get().load(Ordering::SeqCst))).collect(); + Arc::new(Mark { values }) + } + + /// The value each clock has reached (read once per drain). + pub fn progress(&self) -> Progress { + Progress((0..self.len()).map(|i| self.get(i).map_or(u64::MAX, |c| (c.progress)())).collect()) + } + + pub fn passed(&self, m: &Mark) -> bool { + self.progress().passed(m) + } + + /// `f` (a submission to the queue `key`) with a value reserved before and signalled after + /// it; a submission nested on this thread in another to the same queue is covered by the + /// outer one's value. + pub fn submit(&self, key: usize, f: impl FnOnce() -> R) -> R { + let Some(c) = self.find(key) else { + note_unknown(key); + return f(); + }; + let Some(signal) = c.signal.as_ref() else { return f() }; + if IN_SUBMIT.with(|s| s.borrow().contains(&key)) { + return f(); + } + // (the worker never waits for this: it only tries – no submission waits behind a + // writer that waits) + let _gate = serial().then(|| GATE.read().unwrap_or_else(|e| e.into_inner())); + let _order = c.submits.lock().unwrap_or_else(|e| e.into_inner()); + let v = c.reserved.get().fetch_add(1, Ordering::SeqCst) + 1; + IN_SUBMIT.with(|s| s.borrow_mut().push(key)); + struct Out(usize); + impl Drop for Out { + fn drop(&mut self) { + IN_SUBMIT.with(|s| { + let mut s = s.borrow_mut(); + if let Some(i) = s.iter().rposition(|&k| k == self.0) { + s.remove(i); + } + }); + } + } + let r = { + let _out = Out(key); + f() + }; + signal(key as *mut c_void, v); + r + } +} + +/// A submission to a queue without a clock: said once per queue, for the log. +fn note_unknown(key: usize) { + static SEEN: Mutex> = Mutex::new(Vec::new()); + let mut g = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() < 16 && !g.contains(&key) { + g.push(key); + crate::xlog_warn!("D3D12.X: a submission to queue {key:#x}, which XCL made no clock for – deferred releases do not wait for its work"); + } +} + +thread_local! { + /// queues this thread is submitting to (`submit`) + static IN_SUBMIT: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// The value to reach on each clock (by clock index; clocks added later are not waited for). +#[derive(Debug)] +pub struct Mark { + values: Box<[u64]>, +} + +impl Mark { + fn passed_at(&self, progress: &[u64]) -> bool { + self.values.iter().enumerate().all(|(i, &v)| v == 0 || progress.get(i).is_none_or(|&p| p >= v)) + } +} + +/// What every clock has reached, read once for many marks. +pub struct Progress(Vec); + +impl Progress { + pub fn passed(&self, m: &Mark) -> bool { + m.passed_at(&self.0) + } +} + +static CLOCKS: Clocks = Clocks::new(); + +/// A queue made through the adopted device: XCL's fence on it, signalled after each submission +/// (`submit`). The clock keeps the fence, not the queue (a queue the title releases goes; the +/// work submitted to it, the signal last, still runs). +pub unsafe fn register_queue(queue: *mut c_void) { + // (in the unit tests a queue made through a hook gets no clock: a test that leaves its + // queue stalled would hold back every other test's marks; tests that want one ask for it) + #[cfg(not(test))] + register_queue_now(queue); + #[cfg(test)] + let _ = queue; +} + +unsafe fn register_queue_now(queue: *mut c_void) { + if queue.is_null() || !enabled() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let mut dev: Option = None; + if q.GetDevice(&mut dev).is_err() { + return; + } + let Some(fence) = dev.and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()) else { return }; + static SIGNAL: OnceLock = OnceLock::new(); + let slot = *SIGNAL.get_or_init(|| super::layout::find("ID3D12CommandQueue").and_then(|i| super::layout::slot(i, "Signal")).unwrap_or(14)); + let ff = fence.into_raw() as usize; + let progress = move || { + let raw = ff as *mut c_void; + ID3D12Fence::from_raw_borrowed(&raw).map_or(u64::MAX, |f| f.GetCompletedValue()) + }; + let signal = move |qr: *mut c_void, v: u64| { + // the queue's own Signal, not a hook of XCL's (nothing of the title's to note) + let s: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> i32 = if super::real::is_adopted(qr) { + std::mem::transmute(super::real::orig_fn(qr, slot)) + } else { + std::mem::transmute(*(*(qr as *const *const usize)).add(slot)) + }; + let hr = s(qr, ff as *mut c_void, v); + if hr < 0 { + static FAILED: std::sync::Once = std::sync::Once::new(); + FAILED.call_once(|| crate::xlog_warn!("D3D12.X: deferred releases: Signal on queue {:#x} failed ({hr:#x})", qr as usize)); + } + }; + let added = CLOCKS.add(Clock { + key: queue as usize, + reserved: Reserved::Own(AtomicU64::new(0)), + progress: Box::new(progress), + signal: Some(Box::new(signal)), + submits: Mutex::new(()), + }); + if !added { + static FULL: std::sync::Once = std::sync::Once::new(); + FULL.call_once(|| crate::xlog_warn!("D3D12.X: more than {MAX_CLOCKS} queues – later ones are not waited for by deferred releases")); + // (the fence stays: a few bytes) + return; + } + let n = CLOCKS.len(); + if n <= 16 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: queue {:#x} has a clock for deferred releases ({n} clocks)", queue as usize); + } +} + +/// A queue whose owner signals its own fence after its driver calls and publishes the value it +/// will signal in `reserved` before each of them (the sparse windows' queue). +pub unsafe fn register_external(queue: usize, fence: &ID3D12Fence, reserved: &'static AtomicU64) { + if !enabled() { + return; + } + let ff = fence.clone().into_raw() as usize; + let progress = move || { + let raw = ff as *mut c_void; + ID3D12Fence::from_raw_borrowed(&raw).map_or(u64::MAX, |f| f.GetCompletedValue()) + }; + CLOCKS.add(Clock { key: queue, reserved: Reserved::External(reserved), progress: Box::new(progress), signal: None, submits: Mutex::new(()) }); +} + +/// `f`, a submission to `queue`, ordered against the marks (see the module notes). +pub fn submit(queue: *mut c_void, f: impl FnOnce() -> R) -> R { + if !enabled() { + return f(); + } + CLOCKS.submit(queue as usize, f) +} + +/// The mark of now (lock-free). +pub fn mark() -> Arc { + CLOCKS.mark() +} + +/// What every queue has reached now. +pub fn progress() -> Progress { + CLOCKS.progress() +} + +/// Whether every queue is past `m`. +pub fn passed(m: &Mark) -> bool { + CLOCKS.passed(m) +} + +// --- the objects held ------------------------------------------------------------------- + +struct Entry { + ptr: usize, + kind: Kind, + mark: Arc, + passed_at: Option, + /// its place in the ledger (`Ledger::live`, `Ledger::moved`) + seq: u64, +} + +impl Entry { + fn new(ptr: usize, kind: Kind, mark: Arc) -> Self { + Entry { ptr, kind, mark, passed_at: None, seq: 0 } + } +} + +/// Entries in the order they were held (marks only grow along it). #[derive(Default)] -struct Held { - /// queue → its fence here and the last value signalled on it - fences: HashMap, - open: Vec, - sealed: VecDeque, - last_seal: Option, -} - -// (the interface pointers are only used under the lock) -unsafe impl Send for Held {} - -impl Held { - fn is_empty(&self) -> bool { - self.open.is_empty() && self.sealed.is_empty() - } - - /// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`, - /// and take out the batches every queue is past: the resources to release now. - unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { - if !self.open.is_empty() && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) { - let mut marks = Vec::with_capacity(queues.len()); - let mut ok = true; - for q in queues { - let key = q.as_raw() as usize; - if !self.fences.contains_key(&key) { - let mut dev: Option = None; - let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()); - let Some(f) = made else { - ok = false; - break; - }; - self.fences.insert(key, (f, 0)); - } - let (fence, value) = self.fences.get_mut(&key).unwrap(); - if q.Signal(&*fence, *value + 1).is_err() { - ok = false; - break; - } - *value += 1; - marks.push((fence.clone(), *value)); +struct Ledger { + q: VecDeque, + /// object → the entry that holds its reference + live: std::collections::HashMap, + /// entries whose reference went on to a later one (`touch`): let go of without a Release + moved: std::collections::HashSet, + next: u64, +} + +impl Ledger { + /// `e` holds a reference of its object. + fn add(&mut self, mut e: Entry) { + e.seq = self.next; + self.next += 1; + self.live.insert(e.ptr, e.seq); + self.q.push_back(e); + } + + /// XCL let go of a reference of its own to `e.ptr` after work of its own on it (an upload, + /// a read-back): if a reference of the object is held here, it waits for `e.mark` now – its + /// entry goes to the back with it (the earlier one is let go of without a Release). + fn touch(&mut self, e: Entry) { + if let Some(&old) = self.live.get(&e.ptr) { + self.moved.insert(old); + self.add(e); + } + } + + /// The entries that can go now: passed, `grace` ago at least, at most `cap`, in order. + fn drain(&mut self, progress: &Progress, now: Instant, grace: Duration, cap: usize) -> Vec<(usize, Kind)> { + for e in self.q.iter_mut() { + if e.passed_at.is_some() || self.moved.contains(&e.seq) { + continue; } - // (no fence or no signal: the device is gone – the batch stays open, and held) - if ok { - self.last_seal = Some(Instant::now()); - let dead = std::mem::take(&mut self.open); - self.sealed.push_back(Batch { dead, marks }); + if !progress.passed(&e.mark) { + break; } + e.passed_at = Some(now); } - let mut gone = Vec::new(); - while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { - gone.extend(self.sealed.pop_front().unwrap().dead); + let mut out = Vec::new(); + while out.len() < cap { + let Some(e) = self.q.front() else { break }; + if self.moved.remove(&e.seq) { + self.q.pop_front(); + continue; + } + match e.passed_at { + Some(t) if now.duration_since(t) >= grace => { + let e = self.q.pop_front().unwrap(); + if self.live.get(&e.ptr) == Some(&e.seq) { + self.live.remove(&e.ptr); + } + out.push((e.ptr, e.kind)); + } + _ => break, + } } - gone + out } } -static HELD: Mutex> = Mutex::new(None); -// A Mac host can re-enter Release from a driver call. The callback only moves the -// reference into this queue. The worker owns all fence operations and physical releases. -static INCOMING: Mutex> = Mutex::new(Vec::new()); +static LEDGER: Mutex> = Mutex::new(None); +/// entries held so far and let go (for the log) +static HELD: AtomicU64 = AtomicU64::new(0); +static GONE: AtomicU64 = AtomicU64::new(0); -/// Whether last releases are held (`XCL_LATE_RELEASE=0` turns it off). -pub fn enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| !std::env::var("XCL_LATE_RELEASE").is_ok_and(|v| v.trim() == "0")) +// --- the ring a hook puts a held reference in ------------------------------------------- +// +// Atomics only (see the switches): a hook takes the next slot, writes the object, its kind and +// the value reserved on each clock (its mark), and publishes it; the ledger's thread takes the +// slots in order. A slot still full (the ring went round before the thread emptied it – it does +// every tick, whatever the grace) is waited for. + +const RING: usize = 4096; +const EMPTY: u8 = 0; +const WRITING: u8 = 1; +const FULL: u8 = 2; + +struct Slot { + state: AtomicU8, + ptr: AtomicUsize, + kind: AtomicU8, + /// a touch (`Ledger::touch`), not a hold + touch: AtomicBool, + clocks: AtomicU8, + values: [AtomicU64; MAX_CLOCKS], } -/// how long a last `Release` itself waits for queues with nothing to do to say so -const IDLE_WAIT: Duration = Duration::from_micros(300); +impl Slot { + const fn new() -> Self { + Slot { state: AtomicU8::new(EMPTY), ptr: AtomicUsize::new(0), kind: AtomicU8::new(0), touch: AtomicBool::new(false), clocks: AtomicU8::new(0), values: [const { AtomicU64::new(0) }; MAX_CLOCKS] } + } +} + +/// The ring: slots, the next one a hook takes, the next one the ledger's thread takes. +struct Ring { + slots: [Slot; RING], + head: AtomicUsize, + tail: AtomicUsize, +} + +impl Ring { + const fn new() -> Self { + Ring { slots: [const { Slot::new() }; RING], head: AtomicUsize::new(0), tail: AtomicUsize::new(0) } + } + + /// `ptr` (of `kind`) with the mark of now on `clocks` (any thread): held, or touched. + fn put(&self, clocks: &Clocks, ptr: usize, kind: Kind, touch: bool) { + let s = &self.slots[self.head.fetch_add(1, Ordering::AcqRel) % RING]; + while s.state.compare_exchange(EMPTY, WRITING, Ordering::Acquire, Ordering::Relaxed).is_err() { + std::hint::spin_loop(); + } + s.ptr.store(ptr, Ordering::Relaxed); + s.kind.store(kind as u8, Ordering::Relaxed); + s.touch.store(touch, Ordering::Relaxed); + let n = clocks.len().min(MAX_CLOCKS); + for (i, v) in s.values.iter().enumerate().take(n) { + v.store(clocks.get(i).map_or(0, |c| c.reserved.get().load(Ordering::SeqCst)), Ordering::Relaxed); + } + s.clocks.store(n as u8, Ordering::Relaxed); + s.state.store(FULL, Ordering::Release); + } + + /// The entries in order, up to the first one not written yet (one thread at a time), each + /// with whether it is a touch. + fn take(&self, into: &mut Vec<(Entry, bool)>) { + loop { + let t = self.tail.load(Ordering::Relaxed); + let s = &self.slots[t % RING]; + if s.state.load(Ordering::Acquire) != FULL { + return; + } + let n = s.clocks.load(Ordering::Relaxed) as usize; + let values: Box<[u64]> = s.values[..n].iter().map(|v| v.load(Ordering::Relaxed)).collect(); + let kind = kind_of(s.kind.load(Ordering::Relaxed)); + into.push((Entry::new(s.ptr.load(Ordering::Relaxed), kind, Arc::new(Mark { values })), s.touch.load(Ordering::Relaxed))); + s.state.store(EMPTY, Ordering::Release); + self.tail.store(t + 1, Ordering::Relaxed); + } + } +} + +static HELD_RING: Ring = Ring::new(); -/// `res` (an adopted resource) holds one reference that is now this module's. With no work in -/// flight it goes before this returns (the queues pass a fence value at once): a title that -/// frees the memory under a resource right after its last `Release` finds it unpinned, as -/// before. Otherwise the thread here lets it go. -pub unsafe fn hold(res: usize) { - if crate::util::mac_host() { - INCOMING.lock().unwrap_or_else(|e| e.into_inner()).push(res); - start_worker(); +/// How many references of objects of each hash the ledger may hold (a few false positives: +/// shared counters) – a hook asks it before it touches (atomics only). +static MAYBE_HELD: [AtomicU16; 1 << 14] = [const { AtomicU16::new(0) }; 1 << 14]; + +fn held_slot(ptr: usize) -> &'static AtomicU16 { + &MAYBE_HELD[((ptr >> 4).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 50) as usize] +} + +/// XCL let go of a reference of its own to `ptr` (of `kind`), and one is left – maybe the +/// ledger's: the work XCL submitted on it so far is waited for too (`Ledger::touch`). Any thread +/// (atomics only); on the Mac. +pub fn touched(ptr: usize, kind: Kind) { + if TOUCH.load(Ordering::Relaxed) && mac() && held_slot(ptr).load(Ordering::Relaxed) != 0 { + TOUCHES.fetch_add(1, Ordering::Relaxed); + HELD_RING.put(&CLOCKS, ptr, kind, true); + } +} + +static TOUCHES: AtomicU64 = AtomicU64::new(0); + +/// (references held so far, let go so far, held now) – for the activity log. +pub fn stats() -> (u64, u64, usize) { + let backlog = HELD_RING.head.load(Ordering::Relaxed).saturating_sub(HELD_RING.tail.load(Ordering::Relaxed)); + let ledger = LEDGER.try_lock().ok().and_then(|g| g.as_ref().map(|l| l.q.len().saturating_sub(l.moved.len()))).unwrap_or(0); + (HELD.load(Ordering::Relaxed), GONE.load(Ordering::Relaxed), ledger + backlog) +} + +/// The kinds that can be held, by `kind as u8`. +fn kind_of(k: u8) -> Kind { + [Kind::Resource, Kind::Heap, Kind::DescriptorHeap, Kind::PipelineState, Kind::CommandAllocator, Kind::CommandList, Kind::DmaList, Kind::CommandSignature, Kind::QueryHeap, Kind::RootSignature] + .into_iter() + .find(|&x| x as u8 == k) + .unwrap_or(Kind::Resource) +} + +/// `ptr` (an adopted object of `kind`) holds one reference that is now this module's: its last +/// (`real::hooked_release`). Any thread – a hook's (atomics only on the Mac). +pub unsafe fn hold(ptr: usize, kind: Kind) { + put(ptr, kind); +} + +/// `obj` (an object of XCL's own, adopted or not, of `kind`; its last reference) goes once the +/// GPU is past the work submitted so far. +pub unsafe fn defer(obj: usize, kind: Kind) { + if obj == 0 { return; } - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(res); - let start = Instant::now(); - drain_known(true); - while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { - std::hint::spin_loop(); - drain_known(false); + if !enabled() { + // its Release as it is (a hook of XCL's for an adopted object) + let raw = obj as *mut c_void; + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw as *const *const usize)).add(2)); + f(raw); + return; } - if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { + put(obj, kind); +} + +unsafe fn put(ptr: usize, kind: Kind) { + HELD.fetch_add(1, Ordering::Relaxed); + if mac() { + // (the ledger's thread runs since `init`) + held_slot(ptr).fetch_add(1, Ordering::Relaxed); + HELD_RING.put(&CLOCKS, ptr, kind, false); + return; + } + // elsewhere (every thread is one of Windows' own): with nothing in flight it goes before + // this returns (a title that frees the memory under a resource right after its last Release + // finds it unpinned, as before) + let e = Entry::new(ptr, kind, mark()); + if grace().is_zero() && passed(&e.mark) && LEDGER.lock().unwrap().as_ref().is_none_or(|l| l.q.is_empty()) { + GONE.fetch_add(1, Ordering::Relaxed); + super::real::release_held(ptr, kind); return; } + LEDGER.lock().unwrap().get_or_insert_with(Ledger::default).add(e); start_worker(); } fn start_worker() { // A thread of its own lets the held ones go: the title may release a resource and then - // wait for its memory without another submit (an imported heap pins the pages under its - // resources – unmapping them stood still while one was held "until the next submit"). + // wait for its memory without another submit. static THREAD: std::sync::Once = std::sync::Once::new(); THREAD.call_once(|| { if let Err(e) = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop { std::thread::sleep(TICK); - unsafe { drain_on_worker() }; + unsafe { drain() }; }) { crate::xlog_warn!("D3D12.X: could not start the deferred release worker: {e}"); } }); } -/// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the -/// upload ones. -pub unsafe fn drain_known(seal_now: bool) { +/// Release what is past its mark (the worker; on Windows also after a present). +pub unsafe fn drain_known(_seal_now: bool) { if !crate::util::mac_host() { - drain(seal_now, false); + drain(); } } -unsafe fn drain_on_worker() { - let mac = crate::util::mac_host(); - if mac { - let incoming = std::mem::take(&mut *INCOMING.lock().unwrap_or_else(|e| e.into_inner())); - if !incoming.is_empty() { - HELD.lock().unwrap().get_or_insert_with(Held::default).open.extend(incoming); +unsafe fn drain() { + // (`serial`: a submission in progress – the next tick) + let _gate = if serial() { + match GATE.try_write() { + Ok(g) => Some(g), + Err(_) => return, + } + } else { + None + }; + let gone = { + let mut g = LEDGER.lock().unwrap(); + let l = g.get_or_insert_with(Ledger::default); + let mut taken = Vec::new(); + HELD_RING.take(&mut taken); + for (e, touch) in taken { + if touch { + l.touch(e); + } else { + l.add(e); + } } + if l.q.is_empty() { + return; + } + let gone = l.drain(&CLOCKS.progress(), Instant::now(), grace(), MAX_PER_TICK); + let (before, after) = { + let n = gone.len() as u64; + let after = GONE.fetch_add(n, Ordering::Relaxed) + n; + (after - n, after) + }; + // (for the log: how many went so far, and how many wait – each time the count doubles) + if after >= 1024 && (after.ilog2() != before.max(1).ilog2()) { + crate::xlog_info!( + "D3D12.X: deferred releases: {after} let go of {} held so far, {} waiting (grace {} ms, {} clocks)", + HELD.load(Ordering::Relaxed), + l.q.len(), + grace().as_millis(), + CLOCKS.len() + ); + } + gone + }; + // (outside the lock: a release may end other objects, whose releases come back here) + for (ptr, kind) in gone { + if mac() { + let _ = held_slot(ptr).fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1)); + } + super::real::release_held(ptr, kind); } - drain(false, mac); } -unsafe fn drain(seal_now: bool, mac: bool) { - if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { - return; +// --- one last-reference test at a time per object ----------------------------------------- + +const STRIPES: usize = 64; +static STRIPE: [AtomicBool; STRIPES] = [const { AtomicBool::new(false) }; STRIPES]; + +/// While it lives, no other thread runs the last-reference test of an object of the same stripe. +pub struct Stripe(Option); + +impl Drop for Stripe { + fn drop(&mut self) { + if let Some(i) = self.0 { + STRIPE[i].store(false, Ordering::Release); + } } - let mut queues: Vec = Vec::new(); - for raw in super::present::known_queues() { - let raw = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { - queues.push(q.clone()); +} + +/// The stripe of `ptr`: a spin lock (atomics only – any thread, see the switches). A release +/// nested in another on the same stripe (an object's end releasing another under it) cannot +/// tell itself from another thread's: after a while it goes on without the stripe. +pub fn stripe(ptr: usize) -> Stripe { + let i = ((ptr >> 4).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 58) as usize; + for _ in 0..(1 << 20) { + if STRIPE[i].compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_ok() { + return Stripe(Some(i)); } + std::hint::spin_loop(); } - // Sealing without the sparse queue could release resources still used by it. - if mac { - let Ok(queue) = super::sparse::try_queue() else { return }; - queues.extend(queue); - } else { - queues.extend(super::sparse::queue()); + Stripe(None) +} + +/// Tests that take marks of the process's clocks run one at a time (a mark in flight of one +/// test holds back the others'). +#[cfg(test)] +pub static TEST_CLOCKS: Mutex<()> = Mutex::new(()); + +/// A mark no queue has passed, and what lets it pass – when called, or dropped (a test that +/// fails before must not leave work in flight for the next ones): a test's stand-in for work in +/// flight. +#[cfg(test)] +pub fn test_mark_in_flight() -> (Arc, TestWork) { + static N: AtomicUsize = AtomicUsize::new(0); + let done: &'static AtomicU64 = Box::leak(Box::new(AtomicU64::new(0))); + let reserved: &'static AtomicU64 = Box::leak(Box::new(AtomicU64::new(1))); + let key = 0x7E57_0000 + N.fetch_add(1, Ordering::Relaxed); + assert!(CLOCKS.add(Clock { key, reserved: Reserved::External(reserved), progress: Box::new(|| done.load(Ordering::SeqCst)), signal: None, submits: Mutex::new(()) })); + (mark(), TestWork(done)) +} + +/// Work in flight of a test (`test_mark_in_flight`): done when called or dropped. +#[cfg(test)] +pub struct TestWork(&'static AtomicU64); + +#[cfg(test)] +impl TestWork { + pub fn done(&self) { + self.0.store(1, Ordering::SeqCst); } - queues.extend(super::title_textures::upload_queues()); - let gone = match HELD.lock().unwrap().as_mut() { - Some(h) => h.drain(&queues, seal_now), - None => return, - }; - // (outside the lock: a release may end other objects, whose releases come back here) - for res in gone { - super::real::release_held_resource(res as *mut c_void, mac); +} + +#[cfg(test)] +impl Drop for TestWork { + fn drop(&mut self) { + self.done(); } } #[cfg(test)] mod tests { use super::*; - use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use std::sync::atomic::{AtomicBool, AtomicU32}; + + /// A clock on counters: `done` is what the "GPU" reached, `signals` what was signalled. + fn clock(c: &Clocks, key: usize, done: &'static AtomicU64, signals: &'static Mutex>) { + assert!(c.add(Clock { + key, + reserved: Reserved::Own(AtomicU64::new(0)), + progress: Box::new(move || done.load(Ordering::SeqCst)), + signal: Some(Box::new(move |_, v| signals.lock().unwrap().push(v))), + submits: Mutex::new(()), + })); + } + + fn leak_u64() -> &'static AtomicU64 { + Box::leak(Box::new(AtomicU64::new(0))) + } + + fn leak_signals() -> &'static Mutex> { + Box::leak(Box::new(Mutex::new(Vec::new()))) + } + + /// A mark taken inside a submission waits for that submission: D3DMetal's release from + /// inside ExecuteCommandLists, without D3DMetal. + #[test] + fn a_mark_taken_inside_a_submit_waits_for_that_submit() { + let c = Clocks::new(); + let (done, signals) = (leak_u64(), leak_signals()); + clock(&c, 1, done, signals); + let inside = c.submit(1, || c.mark()); + assert_eq!(*signals.lock().unwrap(), vec![1], "signalled after the submission"); + assert!(!c.passed(&inside), "the submission's work is still in flight"); + done.store(1, Ordering::SeqCst); + assert!(c.passed(&inside)); + } + + /// A mark waits for every queue; an idle queue and one added later hold nothing back. + #[test] + fn a_mark_waits_for_every_queue_and_only_for_work_before_it() { + let c = Clocks::new(); + let (da, db, sa, sb) = (leak_u64(), leak_u64(), leak_signals(), leak_signals()); + clock(&c, 1, da, sa); + clock(&c, 2, db, sb); + let idle = c.mark(); + assert!(c.passed(&idle), "queues made but not submitted to hold nothing back"); + c.submit(1, || ()); + c.submit(2, || ()); + let m = c.mark(); + assert_eq!(m.values.as_ref(), &[1, 1]); + da.store(1, Ordering::SeqCst); + assert!(!c.passed(&m), "queue 2 is still busy"); + db.store(1, Ordering::SeqCst); + assert!(c.passed(&m)); + // work submitted after the mark does not hold it back; a queue added later neither + c.submit(1, || ()); + let (dc, sc) = (leak_u64(), leak_signals()); + clock(&c, 3, dc, sc); + c.submit(3, || ()); + assert!(c.passed(&m)); + assert!(!c.passed(&c.mark()), "queue 1's second submission and queue 3's first are pending"); + // a queue at the address of one that went goes on with its clock + let (dd, sd) = (leak_u64(), leak_signals()); + clock(&c, 1, dd, sd); + assert_eq!(c.len(), 3); + } + + /// A submission nested in another to the same queue on one thread reserves nothing more; + /// two threads submitting to one queue signal strictly increasing values. + #[test] + fn submissions_signal_in_order() { + let c = Clocks::new(); + let (done, signals) = (leak_u64(), leak_signals()); + clock(&c, 1, done, signals); + c.submit(1, || c.submit(1, || ())); + assert_eq!(*signals.lock().unwrap(), vec![1]); + let c = Arc::new(c); + let threads: Vec<_> = (0..4) + .map(|_| { + let c = c.clone(); + std::thread::spawn(move || { + for _ in 0..500 { + c.submit(1, std::hint::spin_loop); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + let s = signals.lock().unwrap(); + assert_eq!(s.len(), 2001); + assert!(s.windows(2).all(|w| w[1] == w[0] + 1), "values go up one by one, in order"); + } + + /// Entries go in the order they were held, once passed and `grace` ago, at most `cap` at once. + #[test] + fn entries_go_in_order_after_grace_and_a_few_at_a_time() { + let mut l = Ledger::default(); + let m = |v: u64| Arc::new(Mark { values: vec![v].into_boxed_slice() }); + let p = |v: u64| Progress(vec![v]); + for k in 0..100 { + l.add(Entry::new(k, Kind::Resource, m(1))); + } + l.add(Entry::new(1000, Kind::Heap, m(2))); + let t0 = Instant::now(); + let g = Duration::from_millis(100); + assert!(l.drain(&p(0), t0, g, 64).is_empty(), "not passed"); + assert!(l.drain(&p(1), t0, g, 64).is_empty(), "passed, but not grace ago"); + assert!(l.drain(&p(1), t0 + g - Duration::from_millis(1), g, 64).is_empty(), "1 ms short of the grace"); + let first = l.drain(&p(1), t0 + g, g, 64); + assert_eq!(first, (0..64).map(|k| (k, Kind::Resource)).collect::>()); + let rest = l.drain(&p(1), t0 + g, g, 64); + assert_eq!(rest.len(), 36); + assert!(l.drain(&p(1), t0 + 3 * g, g, 64).is_empty(), "the last one waits for its own mark"); + assert!(l.drain(&p(2), t0 + 3 * g, g, 64).is_empty(), "passed now: its grace starts"); + assert_eq!(l.drain(&p(2), t0 + 4 * g, g, 64), vec![(1000, Kind::Heap)]); + } + + /// The last-reference test under the stripe: of two last-but-one releases at once, exactly + /// one sees the count at 2 (as `real::hooked_release` does it). + #[test] + fn the_last_reference_test_is_not_raced() { + for round in 0..2000 { + let count = Arc::new(AtomicU32::new(2)); // the two holders' references + let holds = Arc::new(AtomicU32::new(0)); + let go = Arc::new(AtomicBool::new(false)); + let threads: Vec<_> = (0..2) + .map(|_| { + let (count, holds, go) = (count.clone(), holds.clone(), go.clone()); + std::thread::spawn(move || { + while !go.load(Ordering::Acquire) { + std::hint::spin_loop(); + } + let _s = stripe(0x1234_5670); + // AddRef, compare with 2, Release (once: held; twice: not the last) + if count.fetch_add(1, Ordering::SeqCst) + 1 == 2 { + count.fetch_sub(1, Ordering::SeqCst); + holds.fetch_add(1, Ordering::SeqCst); + } else { + count.fetch_sub(2, Ordering::SeqCst); + } + }) + }) + .collect(); + go.store(true, Ordering::Release); + for t in threads { + t.join().unwrap(); + } + assert_eq!(holds.load(Ordering::SeqCst), 1, "round {round}: exactly one hold"); + assert_eq!(count.load(Ordering::SeqCst), 1, "round {round}: the hold keeps the object"); + } + } + + /// A stripe taken again on the same thread (a release nested in another) goes on after a + /// while without it, and the stripe is free again once the first goes. + #[test] + fn a_stripe_taken_again_on_one_thread_goes_on() { + let a = stripe(0x4000); + let b = stripe(0x4000); + assert!(b.0.is_none(), "no deadlock: the nested one goes on without the stripe"); + drop(b); + drop(a); + let c = stripe(0x4000); + assert!(c.0.is_some()); + } + + /// The hook's path touches atomics only (see the switches). Many threads put held + /// references in a ring at once; taken in order, each is there once, with the mark of + /// when it was put. + #[test] + fn a_ring_takes_every_held_reference_with_its_mark() { + let ring: &'static Ring = Box::leak(Box::new(Ring::new())); + let clocks: &'static Clocks = Box::leak(Box::new(Clocks::new())); + let (done, signals) = (leak_u64(), leak_signals()); + clock(clocks, 1, done, signals); + clocks.submit(1, || ()); + let threads: Vec<_> = (0..4) + .map(|t| { + std::thread::spawn(move || { + for k in 0..(RING / 4 - 1) { + ring.put(clocks, 0x1000 * t + k, Kind::CommandList, false); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + let mut q = Vec::new(); + ring.take(&mut q); + assert_eq!(q.len(), 4 * (RING / 4 - 1)); + let mut seen: Vec = q.iter().map(|(e, _)| e.ptr).collect(); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), q.len(), "each one once"); + assert!(q.iter().all(|(e, touch)| e.kind == Kind::CommandList && e.mark.values.as_ref() == [1] && !touch), "with the mark of when it was put"); + // round the ring again: the slots are free + for k in 0..RING { + ring.put(clocks, k, Kind::Heap, k % 2 == 0); + } + q.clear(); + ring.take(&mut q); + assert_eq!(q.len(), RING); + assert_eq!(q.iter().filter(|(_, touch)| *touch).count(), RING / 2); + } + + /// XCL's own work on an object the title has released (an upload into a texture it let go + /// of): the held reference waits for that work too – its entry goes to the back with the + /// later mark, and the earlier one is let go of without a Release. A touch of an object not + /// held changes nothing. + #[test] + fn a_touched_hold_waits_for_the_later_work() { + let m = |v: u64| Arc::new(Mark { values: vec![v].into_boxed_slice() }); + let p = |v: u64| Progress(vec![v]); + let mut l = Ledger::default(); + l.add(Entry::new(7, Kind::Resource, m(1))); + l.add(Entry::new(8, Kind::Resource, m(1))); + l.touch(Entry::new(9, Kind::Resource, m(5))); + assert_eq!(l.q.len(), 2, "not held: no entry"); + l.touch(Entry::new(7, Kind::Resource, m(3))); + let t0 = Instant::now(); + let g = Duration::from_millis(10); + assert!(l.drain(&p(1), t0, g, 64).is_empty()); + assert_eq!(l.drain(&p(1), t0 + g, g, 64), vec![(8, Kind::Resource)], "the untouched one goes on its mark; 7's first entry goes without a Release"); + assert!(l.drain(&p(2), t0 + 3 * g, g, 64).is_empty(), "7 waits for its later work"); + assert!(l.drain(&p(3), t0 + 4 * g, g, 64).is_empty()); + assert_eq!(l.drain(&p(3), t0 + 5 * g, g, 64), vec![(7, Kind::Resource)], "once, on the later mark and its grace"); + assert!(l.q.is_empty() && l.live.is_empty() && l.moved.is_empty()); + } - /// A held resource stays while a queue has not got past the work submitted before it was - /// released, and goes once the queue has. + /// Which kinds wait: resources always (with the ledger on), the other GPU objects on the Mac. #[test] - fn a_held_resource_goes_when_the_queue_is_past_its_batch() { + fn what_waits() { + init(); + assert!(defers(Kind::Resource) == enabled()); + assert!(!defers(Kind::CommandQueue)); + assert!(!defers(Kind::Fence)); + assert!(!defers(Kind::Device)); + if crate::util::mac_host() && enabled() && std::env::var("XCL_LATE_RELEASE_ALL").is_err() { + for k in [Kind::Heap, Kind::DescriptorHeap, Kind::PipelineState, Kind::CommandAllocator, Kind::CommandList, Kind::CommandSignature, Kind::QueryHeap, Kind::RootSignature] { + assert!(defers(k), "{k:?} waits on the Mac"); + } + } + } + + /// On a real queue (GPU-gated): a resource held from inside a submission stays while the + /// queue is stalled on a fence no one has signalled, and goes once the queue gets past the + /// submission (and the grace). + #[test] + fn a_release_from_inside_a_stalled_submission_waits_for_it() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + if !enabled() { + return; + } + let _one = TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); unsafe { - let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { return crate::gpu::recomp::runner::skip_test("no GPU"); }; let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); - // the queue stands still, as with work in flight: it waits for a fence nobody has signalled + register_queue_now(queue.as_raw()); let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + // (whatever happens below, the queue is not left stalled for the other tests) + struct Open(ID3D12Fence); + impl Drop for Open { + fn drop(&mut self) { + unsafe { + let _ = self.0.Signal(1); + } + } + } + let _open = Open(gate.clone()); queue.Wait(&gate, 1).unwrap(); - let mut res: Option = None; - let desc = D3D12_RESOURCE_DESC { + 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 hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let rd = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: 4096, + Width: 65536, Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; - dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res).unwrap(); - let raw = res.unwrap().into_raw() as usize; - - let mut held = Held::default(); - held.open.push(raw); - let queues = [queue.clone()]; - assert!(held.drain(&queues, false).is_empty(), "the queue has not passed the batch's fence value"); - std::thread::sleep(Duration::from_millis(100)); - assert!(held.drain(&queues, false).is_empty(), "still in flight: still held"); - assert!(!held.is_empty()); - + let mut res: Option = None; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut res).unwrap(); + let res = res.unwrap(); + list.Close().unwrap(); + let lists = [Some(list.cast::().unwrap())]; + let raw = res.as_raw(); + // the test's own reference stays (to look at the count); the ledger gets one + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw as *const *const usize)).add(1)); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw as *const *const usize)).add(2)); + let count = || { + let n = add(raw); + rel(raw); + n - 1 + }; + add(raw); + submit(queue.as_raw(), || { + queue.ExecuteCommandLists(&lists); + hold(raw as usize, Kind::Resource); + }); + let t = Instant::now(); + while t.elapsed() < Duration::from_millis(300) { + std::thread::sleep(Duration::from_millis(10)); + if !crate::util::mac_host() { + drain_known(false); + } + assert_eq!(count(), 2, "held while the queue is stalled before the submission"); + } gate.Signal(1).unwrap(); - let start = Instant::now(); - let mut gone = Vec::new(); - while gone.is_empty() && start.elapsed() < Duration::from_secs(10) { + let t = Instant::now(); + while count() != 1 { + if !crate::util::mac_host() { + drain_known(false); + } + assert!(t.elapsed() < Duration::from_secs(10), "let go once the queue is past it"); std::thread::sleep(Duration::from_millis(5)); - gone = held.drain(&queues, false); } - assert_eq!(gone, vec![raw], "released once the queue is past the batch"); - assert!(held.is_empty()); - drop(ID3D12Resource::from_raw(raw as *mut c_void)); + assert!(t.elapsed() >= grace().saturating_sub(Duration::from_millis(5)), "not before the grace"); + drop(lists); } } - - /// With no queue at all nothing can be in flight: the next drain lets the batch go. - #[test] - fn without_queues_a_batch_goes_at_once() { - let mut held = Held::default(); - held.open.push(0x1000); - assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]); - assert!(held.is_empty()); - } } diff --git a/crates/xcl/src/hle/d3d12x/lazy_tex.rs b/crates/xcl/src/hle/d3d12x/lazy_tex.rs new file mode 100644 index 0000000..135cb08 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/lazy_tex.rs @@ -0,0 +1,2032 @@ +//! Sampled textures a title places in a GPU view of its memory (`kernelx::mirrors`), made as +//! reserved (tiled) resources that get video memory only for what the title's memory holds. +//! +//! Where reserved textures on the same tiles do not show each other's contents (Apple's +//! D3DMetal, `vram::on_pages`) a sampled title texture is a committed texture of its whole size +//! (`device_x::create_placed_resource_x`). A retail game streams its textures into a 16 GiB GPU +//! view of which it maps a 3.9 GiB pool, page by page: in a world load it placed 32 768 of them +//! in 70 s, 90 % over pages with nothing mapped yet, and Metal's memory grew by 6 GiB in 15 s +//! until the run was stopped. +//! +//! Here such a texture (2D, arrays and cubes, single-sample, no other use, a format of +//! `XCL_TEX_LAZY_FORMATS`, at least `XCL_TEX_LAZY_MIN_KB` on the console) is a reserved resource +//! with no tile mapped when it is made. Its tiles are in groups (`Shape`): each standard mip of +//! each slice, and each slice's packed mips (`XCL_TEX_LAZY_GRAIN=texture`: one group). Before an +//! upload (`title_textures::upload_batches`) the groups that have memory on the title's side – at +//! least half of the bytes of one of their mips in the console's layout lie in 64 KiB pages with +//! memory (`present`) – get tiles from this module's pool heaps, mapped on XCL's upload queue +//! ahead of the copy, and only their subresources are copied; a group with no tiles reads as +//! zero. A copy of the title's GPU work into the texture backs all of it first (`force_all`). A +//! released texture's tiles are parked until every queue is past the mark taken then +//! (`late_release`), and reused after. A texture whose groups got no tiles (none to be had) is +//! uploaded again only once its pool has free tiles for one of the groups it lacks, or may make +//! a heap again (`retries`). +//! +//! No tile of a live texture is ever unmapped. `XCL_TEX_LAZY`: 0 (default) off, 1 textures not +//! wholly present when they are made, 2 every eligible one. `XCL_TEX_LAZY_MAX_OVERHEAD` (1.25): +//! a shape whose tiles would take more than that times its committed size (plus a tile a slice) +//! stays committed; `XCL_TEX_LAZY_MAX_MB` (0: none) caps the pool heaps. + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use super::late_release::Mark; +use crate::hle::xg; +use crate::util::HRESULT; + +/// a tile of a reserved resource (64 KiB) +const TILE: u64 = 0x1_0000; +/// tiles of a pool heap: 64 MiB less one tile (D3DMetal adds the heap's alignment to its size: +/// four of these fill one of its 256 MiB blocks) +const HEAP_TILES: u32 = 1023; +/// the GPU-view pages presence is looked for at (`kernelx::PHYS_PAGE_SIZE`) +const PAGE: usize = 0x1_0000; + +// --- switches ----------------------------------------------------------------------------- + +/// Which formats may be lazy. +enum Formats { + /// the block-compressed ones (BC1 – BC5, BC6H, BC7: no compression metadata on D3DMetal) + Bc, + All, + List(Vec), +} + +impl Formats { + fn allows(&self, f: u32) -> bool { + match self { + Formats::Bc => is_bc(f), + Formats::All => true, + Formats::List(l) => l.contains(&f), + } + } +} + +fn is_bc(f: u32) -> bool { + matches!(f, 70..=84 | 94..=99) +} + +struct Config { + /// 0 off, 1 textures not wholly present when made, 2 every eligible one + mode: u8, + /// tiles in groups by mip (else one group) + by_mip: bool, + formats: Formats, + min_bytes: u64, + max_overhead: f64, + /// pool heaps at most (0: no limit) + max_heaps: usize, +} + +/// Tests force a mode (`test_mode`): 0 the environment's, else mode + 1. +static TEST_MODE: AtomicU8 = AtomicU8::new(0); + +fn config() -> &'static Config { + static C: OnceLock = OnceLock::new(); + C.get_or_init(|| { + let var = |k: &str| std::env::var(k).ok().map(|v| v.trim().to_ascii_lowercase()).filter(|v| !v.is_empty()); + let mode = var("XCL_TEX_LAZY").and_then(|v| v.parse::().ok()).unwrap_or(0).min(2); + let by_mip = var("XCL_TEX_LAZY_GRAIN").is_none_or(|v| v != "texture"); + let formats = match var("XCL_TEX_LAZY_FORMATS").as_deref() { + None | Some("bc") => Formats::Bc, + Some("all") => Formats::All, + Some(l) => Formats::List(l.split(',').filter_map(|s| s.trim().parse().ok()).collect()), + }; + let min_bytes = var("XCL_TEX_LAZY_MIN_KB").and_then(|v| v.parse::().ok()).unwrap_or(128) << 10; + let max_overhead = var("XCL_TEX_LAZY_MAX_OVERHEAD").and_then(|v| v.parse::().ok()).filter(|x| *x >= 1.0).unwrap_or(1.25); + let max_mb = var("XCL_TEX_LAZY_MAX_MB").and_then(|v| v.parse::().ok()).unwrap_or(0); + let c = Config { mode, by_mip, formats, min_bytes, max_overhead, max_heaps: max_mb.div_ceil(64) }; + if c.mode != 0 { + crate::xlog_info!( + "D3D12.X: sampled title textures in GPU views as reserved resources with tiles where the title's memory is (XCL_TEX_LAZY={}; by {}, {} formats, from {} KiB, overhead up to {:.2}, pool {})", + c.mode, + if c.by_mip { "mip" } else { "texture" }, + match &c.formats { + Formats::Bc => "BC".to_string(), + Formats::All => "all".to_string(), + Formats::List(l) => format!("{l:?}"), + }, + c.min_bytes >> 10, + c.max_overhead, + if c.max_heaps == 0 { "unlimited".to_string() } else { format!("{} MB at most", c.max_heaps * 64) } + ); + } + c + }) +} + +fn mode() -> u8 { + match TEST_MODE.load(Ordering::Relaxed) { + 0 => config().mode, + m => m - 1, + } +} + +/// Whether lazy textures are made at all (`XCL_TEX_LAZY` not 0). +pub(super) fn enabled() -> bool { + mode() != 0 +} + +/// Tests: lazy textures in mode `m` whatever the environment says (None: as it says). +#[cfg(test)] +pub(super) fn test_mode(m: Option) { + TEST_MODE.store(m.map_or(0, |m| m + 1), Ordering::Relaxed); +} + +/// Tests: the pool heaps a device may have (+1; 0: as `XCL_TEX_LAZY_MAX_MB` says). +static TEST_MAX_HEAPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Pool heaps a device may have (0: no limit). +fn max_heaps() -> usize { + match TEST_MAX_HEAPS.load(Ordering::Relaxed) { + 0 => config().max_heaps, + n => n - 1, + } +} + +/// Tests: `device`'s pool may have the heaps it has now and no more (None: as configured), and +/// all but `keep` of its free tiles are taken out (returned: `test_give_back` them). +#[cfg(test)] +pub(super) fn test_full_pool(device: usize, keep: Option) -> Vec { + let mut g = POOLS.lock().unwrap(); + let Some(p) = g.as_mut().and_then(|m| m.get_mut(&device)) else { + TEST_MAX_HEAPS.store(0, Ordering::Relaxed); + return Vec::new(); + }; + match keep { + None => { + TEST_MAX_HEAPS.store(0, Ordering::Relaxed); + Vec::new() + } + Some(keep) => { + TEST_MAX_HEAPS.store(p.heaps.len() + 1, Ordering::Relaxed); + p.unpark(&|_| true); + let n = p.free.len().saturating_sub(keep); + p.take(n, &|_| true).unwrap_or_default() + } + } +} + +/// Tests: tiles taken out by `test_full_pool` back among the free ones. +#[cfg(test)] +pub(super) fn test_give_back(device: usize, tiles: Vec) { + if let Some(p) = POOLS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&device)) { + p.give_back(tiles); + } +} + +// --- shapes --------------------------------------------------------------------------- + +/// Tiles of a reserved texture that get memory together. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Group { + /// its first tile in the resource's order of tiles (D3D12: subresource after subresource, + /// a slice's packed mips after its other mips) + start: u32, + tiles: u32, + /// its subresources (D3D12 order) + subs: Vec, +} + +/// The tiles of a reserved texture and their groups. +#[derive(Debug, PartialEq, Eq)] +struct Shape { + total: u32, + groups: Vec, +} + +/// The groups of a reserved texture of `mips` levels and `array` slices from what +/// GetResourceTiling gives (`total` tiles, its packed mips, every subresource's tiling): per +/// slice a group for each standard mip and one for its packed mips – checked to cover every +/// tile and subresource once, else (and with `by_mip` false) one group of all of them. +fn shape_from_tiling(total: u32, packed: &D3D12_PACKED_MIP_INFO, tilings: &[D3D12_SUBRESOURCE_TILING], mips: u32, array: u32, by_mip: bool) -> Shape { + let n = (mips * array) as usize; + let whole = || Shape { total, groups: vec![Group { start: 0, tiles: total, subs: (0..n as u32).collect() }] }; + if !by_mip || total == 0 || tilings.len() != n || n == 0 { + return whole(); + } + let std = packed.NumStandardMips as u32; + let npacked = packed.NumPackedMips as u32; + if std + npacked != mips || (npacked > 0 && packed.NumTilesForPackedMips == 0) { + return whole(); + } + let mut groups = Vec::with_capacity(n); + for s in 0..array { + let mut end = None; + for m in 0..std { + let t = &tilings[(s * mips + m) as usize]; + let tiles = t.WidthInTiles * t.HeightInTiles as u32 * t.DepthInTiles as u32; + if t.StartTileIndexInOverallResource == D3D12_PACKED_TILE || tiles == 0 { + return whole(); + } + groups.push(Group { start: t.StartTileIndexInOverallResource, tiles, subs: vec![s * mips + m] }); + end = Some(t.StartTileIndexInOverallResource + tiles); + } + if npacked > 0 { + // (a slice's packed mips follow its standard ones; with none, slices of packed + // tiles follow each other from the first one's start) + let start = match end { + Some(e) => e, + None => packed.StartTileIndexInOverallResource + s * packed.NumTilesForPackedMips, + }; + groups.push(Group { start, tiles: packed.NumTilesForPackedMips, subs: (std..mips).map(|m| s * mips + m).collect() }); + } + } + // every tile once, every subresource once + let mut by_start: Vec<&Group> = groups.iter().collect(); + by_start.sort_by_key(|g| g.start); + let mut at = 0u32; + for g in &by_start { + if g.start != at { + return whole(); + } + at = g.start + g.tiles; + } + let mut seen = vec![false; n]; + for s in groups.iter().flat_map(|g| g.subs.iter()) { + if std::mem::replace(&mut seen[*s as usize], true) { + return whole(); + } + } + if at != total || !seen.iter().all(|&b| b) { + return whole(); + } + Shape { total, groups } +} + +/// The tiles of reserved texture `res` (made on `dev`) and their groups. +unsafe fn shape_of(dev: &ID3D12Device, res: &ID3D12Resource, by_mip: bool) -> Option { + let d = res.GetDesc(); + let (mips, array) = (d.MipLevels as u32, d.DepthOrArraySize as u32); + let n = mips * array; + if n == 0 { + return None; + } + let mut total = 0u32; + let mut packed = D3D12_PACKED_MIP_INFO::default(); + let mut tile_shape = D3D12_TILE_SHAPE::default(); + let mut count = n; + let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); n as usize]; + dev.GetResourceTiling(res, Some(&mut total), Some(&mut packed), Some(&mut tile_shape), Some(&mut count), 0, tilings.as_mut_ptr()); + if total == 0 { + return None; + } + tilings.truncate(count as usize); + Some(shape_from_tiling(total, &packed, &tilings, mips, array, by_mip)) +} + +/// The bytes of each group of `shape` in the console's layout of `tex` (a 2D texture of `mips` +/// levels): per group the range of each of its mips (offset from the texture's address, bytes; +/// the mips of the console's tail block share it – once). None: not such a texture. +fn console_ranges(tex: &xg::Texture, shape: &Shape, mips: u32) -> Option>> { + let (s, at) = tex.plane_surface(tex.main as u32)?; + let c = &s.chain; + if s.depth != 0 || c.levels.len() != mips as usize || mips == 0 { + return None; + } + let level = |slice: usize, m: usize| -> (usize, usize) { + let base = at as usize + slice * c.slice_bytes; + let l = &c.levels[m]; + if l.tail.is_some() { + (base, c.layout.block_bytes) + } else { + // levels lie from the smallest to mip 0: a level ends where the next larger begins + let end = if m == 0 { c.slice_bytes } else { c.levels[m - 1].offset }; + (base + l.offset, end.saturating_sub(l.offset)) + } + }; + Some( + shape + .groups + .iter() + .map(|g| { + let mut r: Vec<(usize, usize)> = g.subs.iter().map(|&sub| level((sub / mips) as usize, (sub % mips) as usize)).filter(|r| r.1 > 0).collect(); + r.sort_unstable(); + r.dedup(); + r + }) + .collect(), + ) +} + +/// Whether at least half of the bytes of `ranges` (offsets from `va`) lie in 64 KiB pages with +/// memory (`has`, by page). A title streams a mip by mapping all of its pages; textures lie side +/// by side, 1 – 2 KiB apart, so a page mapped for one texture's mip tail also holds the end of +/// the texture before it (its level 0): with any page counting, that whole level got tiles for a +/// sliver of it (896 textures backed where 512 had memory, in a test laid out so). +fn present(ranges: &[(usize, usize)], va: usize, has: &mut dyn FnMut(usize) -> bool) -> bool { + let (mut with, mut all) = (0usize, 0usize); + for &(off, len) in ranges { + let (a, b) = (va + off, va + off + len); + let mut p = a & !(PAGE - 1); + while p < b { + let n = (p + PAGE).min(b) - p.max(a); + all += n; + if has(p) { + with += n; + } + p += PAGE; + } + } + with > 0 && 2 * with >= all +} + +/// Whether a group (`ranges`: its mips' bytes, `console_ranges`) has memory: one of its mips is +/// `present` – a group of several mips (packed ones, a whole texture by `XCL_TEX_LAZY_GRAIN`) is +/// when its small mips are streamed in and its large ones are not yet. +fn group_present(ranges: &[(usize, usize)], va: usize, has: &mut dyn FnMut(usize) -> bool) -> bool { + ranges.iter().any(|r| present(std::slice::from_ref(r), va, has)) +} + +// --- the pool of tiles -------------------------------------------------------------------- + +/// A pool tile: (pool heap, tile in it). +type Tile = (u32, u32); + +/// Pool heaps (`H`) and their tiles: free, given out, or parked behind a mark (`M`) until the +/// GPU is past what used them. +struct Pool { + heaps: Vec, + /// tiles to give out (a stack: a new heap's come in order) + free: Vec, + /// tiles of released textures, each batch with the mark it waits for, oldest first + parked: VecDeque<(Vec, M)>, + /// tiles given out and not given back + used: usize, +} + +impl Pool { + const fn new() -> Self { + Pool { heaps: Vec::new(), free: Vec::new(), parked: VecDeque::new(), used: 0 } + } + + /// Parked tiles whose mark has passed (`passed`) back among the free ones, in order. + fn unpark(&mut self, passed: &dyn Fn(&M) -> bool) { + while self.parked.front().is_some_and(|(_, m)| passed(m)) { + if let Some((t, _)) = self.parked.pop_front() { + self.free.extend(t.into_iter().rev()); + } + } + } + + /// `n` tiles – free ones, after the parked whose mark passed –, or None (none taken). + fn take(&mut self, n: usize, passed: &dyn Fn(&M) -> bool) -> Option> { + self.unpark(passed); + if self.free.len() < n { + return None; + } + let mut t = self.free.split_off(self.free.len() - n); + t.reverse(); + self.used += n; + Some(t) + } + + fn add_heap(&mut self, h: H, tiles: u32) { + let k = self.heaps.len() as u32; + self.heaps.push(h); + self.free.extend((0..tiles).rev().map(|t| (k, t))); + } + + /// Tiles given out that the GPU may still use until `m` passes. + fn park(&mut self, tiles: Vec, m: M) { + self.used = self.used.saturating_sub(tiles.len()); + if !tiles.is_empty() { + self.parked.push_back((tiles, m)); + } + } + + /// Tiles given out and never used. + fn give_back(&mut self, tiles: Vec) { + self.used = self.used.saturating_sub(tiles.len()); + self.free.extend(tiles.into_iter().rev()); + } + + fn parked_tiles(&self) -> usize { + self.parked.iter().map(|(t, _)| t.len()).sum() + } +} + +/// A texture some of whose wanted groups got no tiles: its device, and the tiles of each of +/// those groups, smallest first (the order `back` serves them in). +#[derive(Clone, Debug, PartialEq)] +struct Short { + res: usize, + device: usize, + lacking: Vec, +} + +/// The textures short of tiles, oldest first. One is tried again when its pool can serve it – +/// free tiles enough for one of the groups it lacks, or a heap may be made –, not at every +/// submit: a full pool that cannot grow re-uploaded them all at every submit, and any tiles +/// coming back woke every one of them for one's worth. +struct Shorts(Vec); + +impl Shorts { + /// `s` is short (again: it keeps its place, with what it lacks now). + fn note(&mut self, s: Short) { + match self.0.iter_mut().find(|x| x.res == s.res) { + Some(x) => *x = s, + None => self.0.push(s), + } + } + + fn forget(&mut self, res: usize) { + self.0.retain(|x| x.res != res); + } + + /// Those to try again, oldest first: each one whose pool's free tiles (`free`, what is left + /// after the older ones) give it at least one of the groups it lacks – it is given them as + /// `back` will, smallest first while they fit, and they are taken off for the ones after it + /// –, and one more a device that may make a heap (`grow`: the first is to make it, the + /// others follow when it has). They stay listed until their upload says what they got. + fn wake(&mut self, free: &mut HashMap, grow: &mut HashMap) -> Vec { + let mut out = Vec::new(); + for s in &self.0 { + let f = free.entry(s.device).or_insert(0); + let mut left = *f; + // (smallest first: once one does not fit, the larger ones do not) + for &t in &s.lacking { + if t as usize > left { + break; + } + left -= t as usize; + } + if left < *f { + *f = left; + out.push(s.res); + } else if grow.get(&s.device).copied().unwrap_or(false) { + grow.insert(s.device, false); + out.push(s.res); + } + } + out + } +} + +/// some texture is short of tiles (`forget_short` returns at once otherwise) +static ANY_SHORT: AtomicBool = AtomicBool::new(false); + +static SHORTS: Mutex = Mutex::new(Shorts(Vec::new())); + +/// After CreateHeap failed (no video memory), no heap is asked for until then: every upload of a +/// texture short of tiles would ask again. +static NO_HEAPS_UNTIL: Mutex> = Mutex::new(None); + +/// Whether a heap may be made now for a pool of `heaps` heaps (not at the limit, and not right +/// after CreateHeap failed). +fn may_make_heap(heaps: usize) -> bool { + let cap = max_heaps(); + (cap == 0 || heaps < cap) && NO_HEAPS_UNTIL.lock().unwrap().is_none_or(|t| std::time::Instant::now() >= t) +} + +/// The lazy textures to upload again – some of their groups got no tiles, and their pool can +/// serve them now (`Shorts::wake`; parked tiles whose mark passed are freed first), oldest +/// first: the caller makes them pending and uploads them before the others (what the pool has +/// was counted out for them). Before each refresh. +pub(super) fn retries() -> Vec { + if !ANY_SHORT.load(Ordering::Relaxed) { + return Vec::new(); + } + if SHORTS.lock().unwrap().0.is_empty() { + ANY_SHORT.store(false, Ordering::Relaxed); + return Vec::new(); + } + let (mut free, mut grow) = (HashMap::new(), HashMap::new()); + if let Some(m) = POOLS.lock().unwrap().as_mut() { + let progress = super::late_release::progress(); + for (&device, p) in m.iter_mut() { + p.unpark(&|mk: &Arc| progress.passed(mk)); + free.insert(device, p.free.len()); + grow.insert(device, may_make_heap(p.heaps.len())); + } + } + SHORTS.lock().unwrap().wake(&mut free, &mut grow) +} + +/// Lazy texture `res` is not to be tried again for tiles it lacked (it is not uploaded now: +/// shadowed, released, nothing of it to back) – listed again if an upload of it comes short. +pub(super) fn forget_short(res: usize) { + if ANY_SHORT.load(Ordering::Relaxed) { + SHORTS.lock().unwrap().forget(res); + } +} + +/// The ranges of one UpdateTileMappings call for pool heap `heap` over a resource whose tile i +/// goes to `tiles[i]` (None: left as it is): (mapped, tile offset in the heap, count) – runs of +/// consecutive tiles of the heap, skipped runs for the others. +fn heap_ranges(heap: u32, tiles: &[Option]) -> Vec<(bool, u32, u32)> { + let mut out: Vec<(bool, u32, u32)> = Vec::new(); + for t in tiles { + let (mine, off) = match *t { + Some((h, o)) if h == heap => (true, o), + _ => (false, 0), + }; + match out.last_mut() { + Some(r) if mine && r.0 && r.1 + r.2 == off => r.2 += 1, + Some(r) if !mine && !r.0 => r.2 += 1, + _ => out.push((mine, off, 1)), + } + } + out +} + +// --- the textures --------------------------------------------------------------------- + +struct Lazy { + device: usize, + shape: Arc, + /// per group: its bytes on the title's side (offsets from the texture's address) + ranges: Arc>>, + /// per group: its tiles once it has them + tiles: Vec>, + /// every group is to have tiles at the next upload (the title's GPU work writes it) + force: bool, + /// its console size + bytes: u64, + /// per group: its tiles hold no copy of the title's memory yet (mapped, the upload not done) + uncopied: Vec, + /// uploads into new tiles that failed (`failed_upload`) + failed: u8, +} + +// raw COM pointers only; D3D12 heaps are free-threaded +unsafe impl Send for Lazy {} + +/// PC texture → its tiles +static LAZY: Mutex>> = Mutex::new(None); +/// a lazy texture was made (every other path returns early until then) +static ANY: AtomicBool = AtomicBool::new(false); +/// device → its pool +static POOLS: Mutex>>>> = Mutex::new(None); +/// (width, height, slices, mips, format, grain) → its shape (None: too wasteful as tiles) +type ShapeKey = (u64, u32, u16, u16, i32, bool); +static SHAPES: Mutex>>>> = Mutex::new(None); + +/// why a texture eligible by kind was not made lazy, as indices of `SKIPS` +#[derive(Clone, Copy)] +enum Skip { + Format, + Small, + Kind, + Present, + Overhead, + Failed, + Host, +} +static SKIPS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; +static MADE: AtomicU64 = AtomicU64::new(0); +static MADE_BYTES: AtomicU64 = AtomicU64::new(0); +/// uploads left out (nothing of the texture's memory there) and their console bytes +static LEFT_OUT: AtomicU64 = AtomicU64::new(0); +static LEFT_OUT_BYTES: AtomicU64 = AtomicU64::new(0); +static MAPS: AtomicU64 = AtomicU64::new(0); +static MAP_NANOS: AtomicU64 = AtomicU64::new(0); +static FORCED: AtomicU64 = AtomicU64::new(0); +/// groups that wanted tiles and got none (no memory for more) +static SHORT: AtomicU64 = AtomicU64::new(0); +static RESIDENCY_CALLS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +static RESIDENCY_LEFT_OUT: AtomicU64 = AtomicU64::new(0); + +/// the PC's committed size of the textures of each `SKIPS` reason (the view census, with +/// `XCL_ACTIVITY`) +static SKIP_BYTES: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +#[cfg(test)] +thread_local! { + /// (tests) this thread's `SKIP_BYTES`, whether the census is on or not (the suite's threads + /// share the process's) + static MY_SKIP_BYTES: std::cell::Cell<[u64; 7]> = const { std::cell::Cell::new([0; 7]) }; +} + +/// A texture of `pc_size` PC bytes not made lazy for `s`: counted – its bytes too while the census +/// is kept (`title_textures::census_on`: nothing more on the title's thread otherwise). +fn skip(s: Skip, pc_size: u64) -> Option { + SKIPS[s as usize].fetch_add(1, Ordering::Relaxed); + if super::title_textures::census_on() { + SKIP_BYTES[s as usize].fetch_add(pc_size, Ordering::Relaxed); + } + #[cfg(test)] + MY_SKIP_BYTES.with(|c| { + let mut v = c.get(); + v[s as usize] += pc_size; + c.set(v); + }); + None +} + +/// The PC bytes of the textures committed instead of made lazy, by reason (format, small, kind, +/// present, overhead, failed, host) – counted with the census only (`skip`). +pub(super) fn skip_bytes() -> [u64; 7] { + std::array::from_fn(|k| SKIP_BYTES[k].load(Ordering::Relaxed)) +} + +/// (resource, tiles it has) of every lazy texture into `out`, copied under the table's lock (the +/// view census, off the title's threads; `stats` makes the same walk). +pub(super) fn tiles_by_texture(out: &mut Vec<(usize, u32)>) { + if !any() { + return; + } + let g = LAZY.lock().unwrap_or_else(|e| e.into_inner()); + out.extend(g.as_ref().into_iter().flat_map(|m| m.iter()).map(|(&res, l)| (res, l.tiles.iter().map(|t| t.len() as u32).sum()))); +} + +/// Whether any lazy texture was made. +pub(super) fn any() -> bool { + ANY.load(Ordering::Relaxed) +} + +/// Whether `res` is a lazy texture. +pub(super) fn is_lazy(res: usize) -> bool { + any() && LAZY.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&res)) +} + +/// Whether lazy textures can be made on `dev`: tiled resources and resource heaps of tier 2 +/// (unmapped tiles read as zero), deferred releases on (tiles of a released texture wait for its +/// mark), console lists off (their copies are not seen). Asked once per device. +unsafe fn device_ok(dev: &ID3D12Device) -> bool { + static DEVICES: Mutex>> = Mutex::new(None); + let key = dev.as_raw() as usize; + if let Some(&ok) = DEVICES.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { + return ok; + } + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + let tiers = dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_ok() + && o.TiledResourcesTier.0 >= D3D12_TILED_RESOURCES_TIER_2.0 + && o.ResourceHeapTier.0 >= D3D12_RESOURCE_HEAP_TIER_2.0; + let ledger = super::late_release::enabled(); + let lists = super::console_list::enabled(); + let ok = tiers && ledger && !lists; + if !ok { + crate::xlog_info!( + "D3D12.X: no lazy title textures on this device (tiled resources tier {}, resource heap tier {}, deferred releases {}, console lists {})", + o.TiledResourcesTier.0, + o.ResourceHeapTier.0, + if ledger { "on" } else { "off" }, + if lists { "on" } else { "off" } + ); + } + DEVICES.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, ok); + ok +} + +/// A sampled texture the title places at `va` (`pc`: its PC description, `console` the +/// console's, `pc_size` the PC's committed size of it) as a lazy reserved resource – see the +/// module. None: it is not one (the caller makes it committed). `pages`: (pages with memory, +/// pages) of a range of the title's memory. +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn create( + this: *mut c_void, + va: usize, + pc: &D3D12_RESOURCE_DESC, + console: &[u8; 0x38], + pc_size: u64, + state: u32, + clear: *const c_void, + riid: *const windows_sys::core::GUID, + ppv: *mut *mut c_void, + pages: &dyn Fn(usize, usize) -> (usize, usize), +) -> Option { + let mode = mode(); + if mode == 0 { + return None; + } + let c = config(); + if pc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || pc.SampleDesc.Count != 1 || pc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN || pc.Flags != D3D12_RESOURCE_FLAG_NONE { + return skip(Skip::Kind, pc_size); + } + if crate::hle::kernelx::mirrors::source(va).is_none() { + return skip(Skip::Kind, pc_size); + } + // (the console's 32-bit 116 / 117 are half floats here: not uploaded as they are) + let console_format = u32::from_le_bytes(console[0x20..0x24].try_into().unwrap()); + let Ok(tex) = xg::Texture::new(console) else { return skip(Skip::Kind, pc_size) }; + if tex.planes.len() != 1 || tex.texels().is_none_or(|s| s.depth != 0) || matches!(console_format, 116 | 117) { + return skip(Skip::Kind, pc_size); + } + if !c.formats.allows(pc.Format.0 as u32) { + return skip(Skip::Format, pc_size); + } + let size = tex.size(); + if size < c.min_bytes.max(1) { + return skip(Skip::Small, pc_size); + } + let dev = ID3D12Device::from_raw_borrowed(&this)?; + if !device_ok(dev) { + return skip(Skip::Host, pc_size); + } + if mode == 1 { + let (with, all) = pages(va, size as usize); + if with == all { + return skip(Skip::Present, pc_size); + } + } + let key: ShapeKey = (pc.Width, pc.Height, pc.DepthOrArraySize, pc.MipLevels, pc.Format.0, c.by_mip); + let known = SHAPES.lock().unwrap().get_or_insert_with(HashMap::new).get(&key).cloned(); + if let Some(None) = known { + return skip(Skip::Overhead, pc_size); + } + // reserved textures have the PC's 64 KiB tiles + let tiled = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*pc }; + let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); + if hr < 0 || (*ppv).is_null() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: a title texture at {va:#x} ({}x{}x{}, {} mips, format {}) cannot be reserved ({hr:#x}): committed", pc.Width, pc.Height, pc.DepthOrArraySize, pc.MipLevels, pc.Format.0); + } + if !(*ppv).is_null() { + drop(windows::core::IUnknown::from_raw(*ppv)); + *ppv = std::ptr::null_mut(); + } + return skip(Skip::Failed, pc_size); + } + let raw = *ppv; + let undo = |s: Skip| -> Option { + drop(windows::core::IUnknown::from_raw(raw)); + *ppv = std::ptr::null_mut(); + skip(s, pc_size) + }; + let Some(res) = ID3D12Resource::from_raw_borrowed(&raw) else { return undo(Skip::Failed) }; + let mips = res.GetDesc().MipLevels as u32; + let shape = match known { + Some(Some(s)) => s, + _ => { + let Some(s) = shape_of(dev, res, c.by_mip) else { return undo(Skip::Failed) }; + let slices = pc.DepthOrArraySize.max(1) as f64; + let worth = (s.total as f64 * TILE as f64) <= c.max_overhead * pc_size as f64 + slices * TILE as f64; + let s = worth.then(|| Arc::new(s)); + if s.is_none() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!( + "D3D12.X: title textures of {}x{}x{}, {} mips, format {} stay committed: {} tiles of 64 KiB against {} KiB committed", + pc.Width, pc.Height, pc.DepthOrArraySize, pc.MipLevels, pc.Format.0, key_tiles(res, dev), pc_size >> 10 + ); + } + } + SHAPES.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, s.clone()); + match s { + Some(s) => s, + None => return undo(Skip::Overhead), + } + } + }; + let Some(ranges) = console_ranges(&tex, &shape, mips) else { return undo(Skip::Kind) }; + let lazy = Lazy { device: this as usize, tiles: vec![Vec::new(); shape.groups.len()], shape, ranges: Arc::new(ranges), force: false, bytes: size, uncopied: Vec::new(), failed: 0 }; + LAZY.lock().unwrap().get_or_insert_with(HashMap::new).insert(raw as usize, lazy); + ANY.store(true, Ordering::Relaxed); + let n = MADE.fetch_add(1, Ordering::Relaxed) + 1; + MADE_BYTES.fetch_add(size, Ordering::Relaxed); + if n == 1 { + crate::xlog_info!("D3D12.X: first lazy title texture at {va:#x} ({}x{}x{}, {} mips, format {}, {} KiB)", pc.Width, pc.Height, pc.DepthOrArraySize, mips, pc.Format.0, size >> 10); + } + Some(hr) +} + +/// The tiles of `res` (for a log line). +unsafe fn key_tiles(res: &ID3D12Resource, dev: &ID3D12Device) -> u32 { + let mut total = 0u32; + dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + total +} + +/// Before an upload of lazy texture `res` (at `va`): per group, whether it is to have tiles – +/// it has them, every group is wanted (`force_all`), or it has memory (`group_present`; `has`: +/// whether a page has memory). None: `res` is not lazy (or no longer: released). +pub(super) fn wanted(res: usize, va: usize, has: &mut dyn FnMut(usize) -> bool) -> Option> { + if !any() { + return None; + } + let (ranges, backed, force) = { + let g = LAZY.lock().unwrap(); + let l = g.as_ref()?.get(&res)?; + (Arc::clone(&l.ranges), l.tiles.iter().map(|t| !t.is_empty()).collect::>(), l.force) + }; + Some(ranges.iter().zip(backed).map(|(r, b)| b || force || group_present(r, va, has)).collect()) +} + +/// The upload into new tiles of lazy texture `res` failed (the copy was not recorded or not +/// run: they hold what earlier textures left there, `Backed::fresh` has them until a copy +/// lands): whether to upload it again – twice at most. +/// `whole`: that upload was to copy every group with tiles (its memory had changed) – they all +/// wait for a copy again. +pub(super) fn failed_upload(res: usize, whole: bool) -> bool { + let mut g = LAZY.lock().unwrap(); + let Some(l) = g.as_mut().and_then(|m| m.get_mut(&res)) else { return false }; + if whole { + l.uncopied = l.tiles.iter().map(|t| !t.is_empty()).collect(); + } + l.failed = l.failed.saturating_add(1); + l.failed <= 2 +} + +/// The upload into lazy texture `res`'s new tiles failed, and the title's GPU work writes it in +/// this submit (a copy or a resolve recorded since the last refresh): what that work writes is +/// its content from now on – no copy of the title's memory goes over it later (what it does not +/// write keeps what earlier textures left). +pub(super) fn drop_uncopied(res: usize) { + if let Some(l) = LAZY.lock().unwrap().as_mut().and_then(|m| m.get_mut(&res)) { + l.uncopied.clear(); + } +} + +/// Where lazy texture `res` is read from changed (`title_textures::recheck_source`): every group +/// with tiles is to get a copy of the new place's bytes. +pub(super) fn resend(res: usize) { + if !any() { + return; + } + if let Some(l) = LAZY.lock().unwrap().as_mut().and_then(|m| m.get_mut(&res)) { + l.uncopied = l.tiles.iter().map(|t| !t.is_empty()).collect(); + } +} + +/// The upload of lazy texture `res` with `Backed::fresh` (or more) in its mask ran: its tiles +/// hold the title's texels. +pub(super) fn copied(res: usize) { + if !any() { + return; + } + if let Some(l) = LAZY.lock().unwrap().as_mut().and_then(|m| m.get_mut(&res)) { + l.uncopied.clear(); + l.failed = 0; + } +} + +/// An upload of lazy texture `res` (`bytes` on the console) was left out: nothing of it has +/// memory. +pub(super) fn note_left_out(bytes: u64) { + LEFT_OUT.fetch_add(1, Ordering::Relaxed); + LEFT_OUT_BYTES.fetch_add(bytes, Ordering::Relaxed); +} + +/// The title's GPU work writes lazy texture `res`: every group is to have tiles at its next +/// upload. Whether some group had none (the caller makes the texture pending). +pub(super) fn force_all(res: usize) -> bool { + if !any() { + return false; + } + let mut g = LAZY.lock().unwrap(); + let Some(l) = g.as_mut().and_then(|m| m.get_mut(&res)) else { return false }; + if l.tiles.iter().all(|t| !t.is_empty()) { + return false; + } + if !l.force { + l.force = true; + FORCED.fetch_add(1, Ordering::Relaxed); + } + true +} + +/// Pool heaps' tiles for `n` tiles on `dev`: free, parked whose mark passed, or of new heaps. +/// Fewer when no more can be had (`XCL_TEX_LAZY_MAX_MB`, CreateHeap failed). +unsafe fn take_tiles(dev: &ID3D12Device, n: usize) -> Vec { + let key = dev.as_raw() as usize; + for _ in 0..3 { + let make = { + let mut g = POOLS.lock().unwrap(); + let pool = g.get_or_insert_with(HashMap::new).entry(key).or_insert_with(Pool::new); + let progress = super::late_release::progress(); + let passed = |m: &Arc| progress.passed(m); + if let Some(t) = pool.take(n, &passed) { + return t; + } + let missing = n - pool.free.len(); + let mut make = missing.div_ceil(HEAP_TILES as usize); + let cap = max_heaps(); + if cap != 0 { + make = make.min(cap.saturating_sub(pool.heaps.len())); + } + if !may_make_heap(pool.heaps.len()) { + make = 0; + } + if make == 0 { + let have = pool.free.len(); + return pool.take(have, &passed).unwrap_or_default(); + } + make + }; + let mut made = Vec::new(); + for _ in 0..make { + let desc = D3D12_HEAP_DESC { + SizeInBytes: HEAP_TILES as u64 * TILE, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + // (every tile is copied over before it is used) + Flags: D3D12_HEAP_FLAG_CREATE_NOT_ZEROED | D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option = None; + match super::title_textures::own_work(|| dev.CreateHeap(&desc, &mut heap)) { + Ok(()) if heap.is_some() => made.extend(heap), + r => { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: no video memory for more tiles of lazy title textures ({:?})", r.err()); + } + *NO_HEAPS_UNTIL.lock().unwrap() = Some(std::time::Instant::now() + std::time::Duration::from_secs(1)); + break; + } + } + } + let mut g = POOLS.lock().unwrap(); + let pool = g.get_or_insert_with(HashMap::new).entry(key).or_insert_with(Pool::new); + let none = made.is_empty(); + for h in made { + pool.add_heap(h, HEAP_TILES); + } + if none { + let have = pool.free.len().min(n); + let progress = super::late_release::progress(); + return pool.take(have, &|m: &Arc| progress.passed(m)).unwrap_or_default(); + } + } + // (heaps were made but not enough: what there is) + let mut g = POOLS.lock().unwrap(); + let Some(pool) = g.as_mut().and_then(|m| m.get_mut(&key)) else { return Vec::new() }; + let progress = super::late_release::progress(); + pool.unpark(&|m: &Arc| progress.passed(m)); + let have = pool.free.len().min(n); + pool.take(have, &|m: &Arc| progress.passed(m)).unwrap_or_default() +} + +/// Map `assign` (tile i of `res` → its pool tile; None: left as it is) on `queue`, one call per +/// pool heap of `heaps`. +unsafe fn map(queue: &ID3D12CommandQueue, res: &ID3D12Resource, heaps: &[(u32, ID3D12Heap)], assign: &[Option]) { + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: assign.len() as u32, UseBox: false.into(), ..Default::default() }; + // (the order of every submission: d3d_ops, then the queue's clock – real::q_execute_command_lists) + let _ops = super::d3d_ops(); + for (h, heap) in heaps { + let ranges = heap_ranges(*h, assign); + if !ranges.iter().any(|r| r.0) { + continue; + } + let flags: Vec = ranges.iter().map(|r| if r.0 { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }).collect(); + let offsets: Vec = ranges.iter().map(|r| r.1).collect(); + let counts: Vec = ranges.iter().map(|r| r.2).collect(); + let t0 = std::time::Instant::now(); + super::late_release::submit(queue.as_raw(), || { + queue.UpdateTileMappings( + res, + 1, + Some(&coord), + Some(®ion), + heap, + ranges.len() as u32, + Some(flags.as_ptr()), + Some(offsets.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ) + }); + MAPS.fetch_add(1, Ordering::Relaxed); + MAP_NANOS.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed); + } +} + +/// What `back` did for an upload: the subresources with tiles (None: not a lazy texture – all +/// of them; none: a lazy one released meanwhile), those whose tiles hold no copy yet (got them in +/// this call, or an upload into them failed), and whether a wanted group got none. +pub(super) struct Backed { + pub subs: Option>, + pub fresh: Option>, + pub short: bool, +} + +/// Before uploads on `queue` (XCL's upload queue of `dev`): the groups `want` of each lazy +/// texture of `items` that have no tiles yet get them, mapped on `queue` – the copies that +/// follow on it see them, and the title's work after the upload's wait does. +pub(super) unsafe fn back(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(&ID3D12Resource, Option<&[bool]>)]) -> Vec { + // (a lazy texture's upload copies nothing unless it still has its tiles: one released + // meanwhile – `forget` – parked them, and they may be another texture's already) + let mut out: Vec = items.iter().map(|(_, w)| Backed { subs: w.map(|_| Vec::new()), fresh: w.map(|_| Vec::new()), short: false }).collect(); + if !any() { + return out; + } + // (item, group, its tiles, its first tile) of every group to back + let mut needs: Vec<(usize, usize, u32, u32)> = Vec::new(); + let mut totals: Vec = vec![0; items.len()]; + // per item: the tiles of each group it wants and does not get, in the order served + let mut lacking: Vec> = items.iter().map(|_| Vec::new()).collect(); + { + let g = LAZY.lock().unwrap(); + let Some(m) = g.as_ref() else { return out }; + for (i, (r, want)) in items.iter().enumerate() { + let (Some(want), Some(l)) = (want, m.get(&(r.as_raw() as usize))) else { continue }; + totals[i] = l.shape.total; + let first = needs.len(); + for (k, &w) in want.iter().enumerate().take(l.tiles.len()) { + if w && l.tiles[k].is_empty() { + let grp = &l.shape.groups[k]; + needs.push((i, k, grp.tiles, grp.start)); + } + } + // the small groups first: the packed tail and the small mips are what a title + // streams first; when tiles run short, a texture has its whole chain but its + // largest mips rather than those alone (and `Shorts::wake` counts them out so) + needs[first..].sort_by_key(|x| x.2); + } + } + let n: usize = needs.iter().map(|x| x.2 as usize).sum(); + let mut got = if n > 0 { take_tiles(dev, n) } else { Vec::new() }; + // whole groups, in order, while the tiles last; one assignment per texture + let mut given: Vec<(usize, usize, Vec)> = Vec::with_capacity(needs.len()); + let mut by_item: Vec>> = items.iter().map(|_| Vec::new()).collect(); + for &(i, k, t, start) in &needs { + if got.len() < t as usize { + SHORT.fetch_add(1, Ordering::Relaxed); + out[i].short = true; + lacking[i].push(t); + continue; + } + let rest = got.split_off(t as usize); + let tiles = std::mem::replace(&mut got, rest); + let a = &mut by_item[i]; + if a.is_empty() { + a.resize(totals[i] as usize, None); + } + for (j, tile) in tiles.iter().enumerate() { + if let Some(slot) = a.get_mut(start as usize + j) { + *slot = Some(*tile); + } + } + given.push((i, k, tiles)); + } + let key = dev.as_raw() as usize; + if !got.is_empty() { + if let Some(p) = POOLS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + p.give_back(got); + } + } + if !given.is_empty() { + let heaps: Vec<(u32, ID3D12Heap)> = { + let g = POOLS.lock().unwrap(); + let Some(p) = g.as_ref().and_then(|m| m.get(&key)) else { return out }; + let mut used: Vec = given.iter().flat_map(|(_, _, t)| t.iter().map(|x| x.0)).collect(); + used.sort_unstable(); + used.dedup(); + used.into_iter().filter_map(|h| p.heaps.get(h as usize).map(|x| (h, x.clone()))).collect() + }; + for (i, a) in by_item.iter().enumerate() { + if a.iter().any(|t| t.is_some()) { + map(queue, items[i].0, &heaps, a); + } + } + } + // the tiles are the textures' now; what has tiles + let mut orphans: Vec = Vec::new(); + { + let mut g = LAZY.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + for (i, k, tiles) in given { + match m.get_mut(&(items[i].0.as_raw() as usize)) { + Some(l) => { + l.tiles[k] = tiles; + if l.uncopied.len() != l.tiles.len() { + l.uncopied = vec![false; l.tiles.len()]; + } + l.uncopied[k] = true; + } + None => orphans.extend(tiles), + } + } + for (i, (r, want)) in items.iter().enumerate() { + if want.is_none() { + continue; + } + let Some(l) = m.get_mut(&(r.as_raw() as usize)) else { continue }; + let nsubs = l.shape.groups.iter().map(|g| g.subs.len()).sum::(); + let mut subs = vec![false; nsubs]; + for (k, grp) in l.shape.groups.iter().enumerate() { + if !l.tiles[k].is_empty() { + for &s in &grp.subs { + if let Some(x) = subs.get_mut(s as usize) { + *x = true; + } + } + } + } + if l.force && l.tiles.iter().all(|t| !t.is_empty()) { + l.force = false; + } + let mut new = vec![false; nsubs]; + for (k, grp) in l.shape.groups.iter().enumerate() { + if l.uncopied.get(k).copied().unwrap_or(false) { + for &s in &grp.subs { + if let Some(x) = new.get_mut(s as usize) { + *x = true; + } + } + } + } + out[i].subs = Some(subs); + out[i].fresh = Some(new); + } + } + // short ones are tried again when their pool can serve them (`retries`); the others are not + if ANY_SHORT.load(Ordering::Relaxed) || lacking.iter().any(|l| !l.is_empty()) { + let mut g = SHORTS.lock().unwrap(); + for (i, (r, want)) in items.iter().enumerate() { + let res = r.as_raw() as usize; + if !lacking[i].is_empty() { + g.note(Short { res, device: key, lacking: std::mem::take(&mut lacking[i]) }); + } else if want.is_some() { + g.forget(res); + } + } + ANY_SHORT.store(!g.0.is_empty(), Ordering::Relaxed); + } + if !orphans.is_empty() { + // (mapped to a texture that went meanwhile: after the GPU is past this) + let mark = super::late_release::mark(); + if let Some(p) = POOLS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + p.park(orphans, mark); + } + } + out +} + +/// A PC texture was released for good: a lazy one's tiles wait for the GPU to be past now, +/// then go to the next textures. +pub(super) fn forget(res: usize) { + if !any() { + return; + } + let Some(l) = LAZY.lock().unwrap().as_mut().and_then(|m| m.remove(&res)) else { return }; + forget_short(res); + let tiles: Vec = l.tiles.into_iter().flatten().collect(); + if tiles.is_empty() { + return; + } + let mark = super::late_release::mark(); + if let Some(p) = POOLS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&l.device)) { + p.park(tiles, mark); + } +} + +/// The title's MakeResident (`evict` false) / Evict of `objects`: those that are not lazy +/// textures (a reserved texture out of Metal's residency set would be used while not resident +/// – a lazy texture is always resident). Counted. +pub(super) fn residency(evict: bool, objects: &[*mut c_void]) -> Vec<*mut c_void> { + let k = RESIDENCY_CALLS[evict as usize].fetch_add(1, Ordering::Relaxed); + if k == 0 { + crate::xlog_info!("D3D12.X: the title calls {} ({} objects)", if evict { "Evict" } else { "MakeResident" }, objects.len()); + } + if !any() { + return objects.to_vec(); + } + let g = LAZY.lock().unwrap(); + let Some(m) = g.as_ref() else { return objects.to_vec() }; + let kept: Vec<*mut c_void> = objects.iter().copied().filter(|&p| !m.contains_key(&(p as usize))).collect(); + RESIDENCY_LEFT_OUT.fetch_add((objects.len() - kept.len()) as u64, Ordering::Relaxed); + kept +} + +/// The lazy textures as text for the activity log (None: off and none made). +pub fn stats() -> Option { + if mode() == 0 && !any() { + return None; + } + let mb = |b: u64| b >> 20; + let (live, unbacked, unbacked_bytes, backed, groups) = { + let g = LAZY.lock().unwrap(); + let mut s = (0usize, 0usize, 0u64, 0usize, 0usize); + for l in g.as_ref().into_iter().flat_map(|m| m.values()) { + s.0 += 1; + let b = l.tiles.iter().filter(|t| !t.is_empty()).count(); + if b == 0 { + s.1 += 1; + s.2 += l.bytes; + } + s.3 += b; + s.4 += l.tiles.len(); + } + s + }; + let (heaps, free, parked, used) = { + let g = POOLS.lock().unwrap(); + g.as_ref().into_iter().flat_map(|m| m.values()).fold((0usize, 0usize, 0usize, 0usize), |a, p| (a.0 + p.heaps.len(), a.1 + p.free.len(), a.2 + p.parked_tiles(), a.3 + p.used)) + }; + let l = |a: &AtomicU64| a.load(Ordering::Relaxed); + let s = |k: Skip| l(&SKIPS[k as usize]); + Some(format!( + "lazy title textures: {} made ({} MB on the console), {live} live, {unbacked} with no tiles ({} MB); tiles {} MB in use, heaps {} MB ({} free, {} parked); groups {backed} of {groups} backed; committed instead: format {}, small {}, kind {}, present {}, overhead {}, failed {}, host {}; uploads left out {} ({} MB); {} tile mappings in {} ms; {} backed whole for GPU writes; {} groups short of tiles; MakeResident {} / Evict {} calls ({} lazy left out)", + l(&MADE), + mb(l(&MADE_BYTES)), + mb(unbacked_bytes), + mb(used as u64 * TILE), + heaps as u64 * HEAP_TILES as u64 * TILE >> 20, + free, + parked, + s(Skip::Format), + s(Skip::Small), + s(Skip::Kind), + s(Skip::Present), + s(Skip::Overhead), + s(Skip::Failed), + s(Skip::Host), + l(&LEFT_OUT), + mb(l(&LEFT_OUT_BYTES)), + l(&MAPS), + l(&MAP_NANOS) / 1_000_000, + l(&FORCED), + l(&SHORT), + l(&RESIDENCY_CALLS[0]), + l(&RESIDENCY_CALLS[1]), + l(&RESIDENCY_LEFT_OUT), + )) +} + +/// Tests: (tiles with each group of `res`, its total tiles, groups) – None: not lazy. +#[cfg(test)] +pub(super) fn test_tiles(res: usize) -> Option<(Vec, u32)> { + let g = LAZY.lock().unwrap(); + let l = g.as_ref()?.get(&res)?; + Some((l.tiles.iter().map(|t| t.len()).collect(), l.shape.total)) +} + +/// Tests: (heaps, free, parked, used) of `device`'s pool. +#[cfg(test)] +pub(super) fn test_pool(device: usize) -> (usize, usize, usize, usize) { + let g = POOLS.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&device)).map_or((0, 0, 0, 0), |p| (p.heaps.len(), p.free.len(), p.parked_tiles(), p.used)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::texture::{self, Subresource}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + use windows::Win32::Graphics::Dxgi::*; + + fn tiling(start: u32, w: u32, h: u16) -> D3D12_SUBRESOURCE_TILING { + D3D12_SUBRESOURCE_TILING { WidthInTiles: w, HeightInTiles: h, DepthInTiles: 1, StartTileIndexInOverallResource: start } + } + + fn packed_tile() -> D3D12_SUBRESOURCE_TILING { + D3D12_SUBRESOURCE_TILING { StartTileIndexInOverallResource: D3D12_PACKED_TILE, ..Default::default() } + } + + fn packed(std: u8, npacked: u8, tiles: u32, start: u32) -> D3D12_PACKED_MIP_INFO { + D3D12_PACKED_MIP_INFO { NumStandardMips: std, NumPackedMips: npacked, NumTilesForPackedMips: tiles, StartTileIndexInOverallResource: start } + } + + /// The bytes committed instead of made lazy go to their own reason, exactly (this thread's + /// mirror: the process's counts only with the census on – its case in a process of its own with + /// `EXTRA_ENV=XCL_ACTIVITY=1`, where they grow at least as much) (M18). + #[test] + fn committed_instead_bytes_follow_each_reason() { + let mine = || MY_SKIP_BYTES.with(|c| c.get()); + let (before, all) = (mine(), skip_bytes()); + assert_eq!(skip(Skip::Format, 0x7A1E_2000), None); + assert_eq!(skip(Skip::Small, 0x10), None); + let d: Vec = mine().iter().zip(before).map(|(a, b)| a - b).collect(); + assert_eq!(d, [0x7A1E_2000, 0x10, 0, 0, 0, 0, 0]); + let now = skip_bytes(); + if super::super::title_textures::census_on() { + assert!(now[0] - all[0] >= 0x7A1E_2000 && now[1] - all[1] >= 0x10, "counted with the census on"); + } else { + assert_eq!(now, all, "nothing counted with the census off"); + } + } + + /// Groups follow the tiling as D3DMetal lays it out (slice after slice, each slice's packed + /// mips after its standard ones), cover every tile and subresource once, and anything else + /// is one group. + #[test] + fn shape_groups_follow_the_tiling() { + // 2D, 3 mips: 4 + 1 tiles, 1 packed (1 tile) + let t = [tiling(0, 2, 2), tiling(4, 1, 1), packed_tile()]; + let s = shape_from_tiling(6, &packed(2, 1, 1, 5), &t, 3, 1, true); + assert_eq!(s.groups, vec![Group { start: 0, tiles: 4, subs: vec![0] }, Group { start: 4, tiles: 1, subs: vec![1] }, Group { start: 5, tiles: 1, subs: vec![2] }]); + // the same by texture: one group + let w = shape_from_tiling(6, &packed(2, 1, 1, 5), &t, 3, 1, false); + assert_eq!(w.groups, vec![Group { start: 0, tiles: 6, subs: vec![0, 1, 2] }]); + // 2 slices of 2 mips (2 + packed 1 each) + let t = [tiling(0, 2, 1), packed_tile(), tiling(3, 2, 1), packed_tile()]; + let s = shape_from_tiling(6, &packed(1, 1, 1, 2), &t, 2, 2, true); + assert_eq!(s.groups.len(), 4); + assert_eq!(s.groups[1], Group { start: 2, tiles: 1, subs: vec![1] }); + assert_eq!(s.groups[3], Group { start: 5, tiles: 1, subs: vec![3] }); + // all packed, 6 slices (a small cube) of 2 tiles each + let t = [packed_tile(); 12]; + let s = shape_from_tiling(12, &packed(0, 2, 2, 0), &t, 2, 6, true); + assert_eq!(s.groups.len(), 6); + assert!(s.groups.iter().enumerate().all(|(k, g)| g.start == 2 * k as u32 && g.tiles == 2 && g.subs == vec![2 * k as u32, 2 * k as u32 + 1])); + // inconsistent: a gap, a total that does not match, counts that do not add up + let t = [tiling(0, 2, 2), tiling(5, 1, 1), packed_tile()]; + assert_eq!(shape_from_tiling(7, &packed(2, 1, 1, 6), &t, 3, 1, true).groups.len(), 1); + let t = [tiling(0, 2, 2), tiling(4, 1, 1), packed_tile()]; + assert_eq!(shape_from_tiling(9, &packed(2, 1, 1, 5), &t, 3, 1, true).groups.len(), 1); + assert_eq!(shape_from_tiling(6, &packed(1, 1, 1, 5), &t, 3, 1, true).groups.len(), 1); + assert_eq!(shape_from_tiling(6, &packed(2, 1, 0, 5), &t, 3, 1, true).groups.len(), 1); + // no mips but one level, non-packed: one group per slice + let t = [tiling(0, 4, 4), tiling(16, 4, 4)]; + let s = shape_from_tiling(32, &packed(1, 0, 0, 0), &t, 1, 2, true); + assert_eq!(s.groups, vec![Group { start: 0, tiles: 16, subs: vec![0] }, Group { start: 16, tiles: 16, subs: vec![1] }]); + } + + /// A group's bytes on the console: per slice the mip tail block first, then the levels from + /// the smallest to mip 0, slices `slice_bytes` apart (`gpu::tiling::Chain`). + #[test] + fn console_ranges_follow_the_mip_chain() { + // BC7 1024² with 11 mips, 64 KB swizzle, 2 slices + let mut d = [0u8; 0x38]; + d[0..4].copy_from_slice(&3u32.to_le_bytes()); + d[0x10..0x18].copy_from_slice(&1024u64.to_le_bytes()); + d[0x18..0x1C].copy_from_slice(&1024u32.to_le_bytes()); + d[0x1C..0x1E].copy_from_slice(&2u16.to_le_bytes()); + d[0x1E..0x20].copy_from_slice(&11u16.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&98u32.to_le_bytes()); + d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + d[0x2C..0x30].copy_from_slice(&0x109u32.to_le_bytes()); + let tex = xg::Texture::new(&d).unwrap(); + let s = tex.texels().unwrap(); + let c = &s.chain; + let mips = c.levels.len() as u32; + assert_eq!(mips, 11); + // one group per subresource + let groups: Vec = (0..2 * mips).map(|k| Group { start: k, tiles: 1, subs: vec![k] }).collect(); + let shape = Shape { total: 2 * mips, groups }; + let r = console_ranges(&tex, &shape, mips).unwrap(); + let sb = c.slice_bytes; + // level 0 is the last part of each slice + assert_eq!(r[0], vec![(c.levels[0].offset, sb - c.levels[0].offset)]); + assert_eq!(r[mips as usize], vec![(sb + c.levels[0].offset, sb - c.levels[0].offset)]); + // level 1 ends where level 0 begins + assert_eq!(r[1], vec![(c.levels[1].offset, c.levels[0].offset - c.levels[1].offset)]); + // a level in the tail: the tail block, the slice's first + let tail = c.levels.iter().position(|l| l.tail.is_some()).unwrap(); + assert_eq!(r[tail], vec![(0, c.layout.block_bytes)]); + assert_eq!(r[mips as usize + tail], vec![(sb, c.layout.block_bytes)]); + // the groups' ranges cover each slice once + let mut all: Vec<(usize, usize)> = r.iter().flatten().copied().collect(); + all.sort_unstable(); + all.dedup(); + let covered: usize = all.iter().map(|x| x.1).sum(); + assert_eq!(covered, 2 * sb); + // one group of everything: each mip's range (the tail block once a slice), together + // the texture's whole range + let whole = Shape { total: 1, groups: vec![Group { start: 0, tiles: 1, subs: (0..2 * mips).collect() }] }; + let w = console_ranges(&tex, &whole, mips).unwrap(); + assert_eq!(w.len(), 1); + assert_eq!(w[0].len(), 2 * (tail + 1), "{:?}", w[0]); + assert_eq!(w[0].iter().map(|x| x.1).sum::(), 2 * sb); + // such a group has memory when one of its mips has: the small ones streamed in alone + let va0 = 0x2000_0000; + let tail_page = |p: usize| p < va0 + c.levels[0].offset; + assert!(group_present(&w[0], va0, &mut |p| tail_page(p)), "the small mips' pages: the whole texture backed"); + assert!(!present(&w[0], va0, &mut |p| tail_page(p)), "(less than half of all its bytes)"); + assert!(!group_present(&w[0], va0, &mut |_| false)); + // presence: at least half of a group's bytes in pages with memory (level 0: 1 MiB, 16 + // pages from a 1 KiB-aligned address – 17 pages, the first and last partly) + let ranges = &r[0]; + let va = 0x1000_0400; + let mut asked = Vec::new(); + assert!(!present(ranges, va, &mut |p| { + asked.push(p); + false + })); + assert_eq!(asked.len(), 17); + assert_eq!(asked[0], (va + ranges[0].0) & !(PAGE - 1)); + let last = asked[16]; + assert!(!present(ranges, va, &mut |p| p == last), "a sliver of it (the page it shares with the next texture)"); + assert!(!present(ranges, va, &mut |p| p < asked[7]), "less than half"); + assert!(present(ranges, va, &mut |p| p <= asked[8]), "half"); + assert!(present(ranges, va, &mut |_| true)); + // the tail block, 64 KiB over two pages: the page with most of it is enough + let tail = &r[c.levels.iter().position(|l| l.tail.is_some()).unwrap()]; + let first = (va + tail[0].0) & !(PAGE - 1); + assert!(present(tail, va, &mut |p| p == first), "63 KiB of 64"); + assert!(!present(tail, va, &mut |p| p != first), "1 KiB of 64"); + } + + /// A tile is never both free and given out, parked tiles come back only after their mark, + /// and taking never waits. + #[test] + fn pool_gives_each_tile_once_and_reuses_it_only_after_its_mark() { + let mut p: Pool = Pool::new(); + let done = std::cell::Cell::new(0u64); + let passed = |m: &u64| *m <= done.get(); + assert!(p.take(1, &passed).is_none()); + p.add_heap(7, 8); + let a = p.take(3, &passed).unwrap(); + assert_eq!(a, vec![(0, 0), (0, 1), (0, 2)], "a new heap's tiles in order"); + let b = p.take(5, &passed).unwrap(); + assert!(p.take(1, &passed).is_none(), "8 tiles given out"); + p.park(a.clone(), 3); + assert!(p.take(1, &passed).is_none(), "parked until mark 3"); + done.set(2); + assert!(p.take(1, &passed).is_none()); + done.set(3); + let c = p.take(3, &passed).unwrap(); + assert_eq!(c, a, "the parked tiles again"); + p.give_back(b); + assert_eq!(p.used, 3); + // random: never twice, never before the mark + let mut p: Pool = Pool::new(); + let mut out: Vec> = Vec::new(); + let mut held: std::collections::HashSet = std::collections::HashSet::new(); + let mut parked: Vec<(u64, Vec)> = Vec::new(); + let mut seed = 0x1234_5678u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let mut clock = 0u64; + for step in 0..20_000u64 { + let r = next(); + match r % 4 { + 0 | 1 => { + let n = 1 + (r >> 8) as usize % 16; + let now = clock; + let got = match p.take(n, &|m: &u64| *m <= now) { + Some(t) => t, + None => { + let before = p.heaps.len(); + p.add_heap(before as u32, 64); + p.take(n, &|m: &u64| *m <= now).unwrap() + } + }; + for t in &got { + assert!(held.insert(*t), "tile {t:?} given twice (step {step})"); + assert!(!parked.iter().any(|(_, v)| v.contains(t)), "parked tile {t:?} given before its mark"); + } + out.push(got); + } + 2 if !out.is_empty() => { + let k = (r >> 8) as usize % out.len(); + let t = out.swap_remove(k); + for x in &t { + held.remove(x); + } + let mark = clock + 1 + (r >> 20) % 8; + parked.push((mark, t.clone())); + p.park(t, mark); + } + _ => { + clock += 1; + parked.retain(|(m, _)| *m > clock); + } + } + assert_eq!(p.used, held.len()); + } + // bounded: at most what was held and in flight at once, in heaps of 64 + assert!(p.heaps.len() * 64 <= (held.len() + p.parked_tiles() + p.free.len()).max(64), "{} heaps", p.heaps.len()); + } + + /// Textures short of tiles are tried again, oldest first, only while their pool's free + /// tiles give each at least one group it lacks – what it will take (smallest first, while + /// they fit) is taken off for the ones after it –, plus one a device that may make a heap; + /// the others wait, in their place. + #[test] + fn short_textures_wait_until_their_pool_can_serve_them() { + let short = |res, device, lacking: &[u32]| Short { res, device, lacking: lacking.to_vec() }; + let mut s = Shorts(Vec::new()); + s.note(short(1, 10, &[16])); + s.note(short(2, 10, &[1, 1, 4, 16])); + s.note(short(3, 20, &[4])); + let (mut free, mut grow) = (HashMap::new(), HashMap::new()); + assert!(s.wake(&mut free, &mut grow).is_empty(), "no free tile, no heap: nothing"); + // 20 tiles: texture 1 takes its 16, texture 2 then its 1 + 1 of the 4 left (not its 4) + free.insert(10, 20); + assert_eq!(s.wake(&mut free, &mut grow), vec![1, 2]); + assert_eq!(free[&10], 2); + // 3 tiles: not texture 1 (16); texture 2 its two 1s + free.insert(10, 3); + assert_eq!(s.wake(&mut free, &mut grow), vec![2]); + assert_eq!(free[&10], 1); + // they stay listed, in their place, until an upload says what they got + assert_eq!(s.0.iter().map(|x| x.res).collect::>(), vec![1, 2, 3]); + s.note(short(1, 10, &[4])); + assert_eq!(s.0.iter().map(|x| x.res).collect::>(), vec![1, 2, 3], "noted again: same place"); + s.forget(2); + free.insert(10, 4); + free.insert(20, 100); + assert_eq!(s.wake(&mut free, &mut grow), vec![1, 3]); + // a device that may make a heap: its first texture that no free tile serves goes, to + // make it; the next ones wait for it + let mut s = Shorts(vec![short(4, 10, &[64]), short(5, 10, &[64])]); + let mut free = HashMap::new(); + grow.insert(10, true); + assert_eq!(s.wake(&mut free, &mut grow), vec![4]); + s.forget(4); + s.forget(5); + assert!(s.0.is_empty()); + } + + /// One call per heap: its tiles in runs, the others and those left as they are skipped. + #[test] + fn heap_ranges_map_runs_and_skip_the_rest() { + let t = [Some((0, 5)), Some((0, 6)), None, Some((1, 2)), Some((0, 7)), Some((0, 9)), None, None]; + assert_eq!(heap_ranges(0, &t), vec![(true, 5, 2), (false, 0, 2), (true, 7, 1), (true, 9, 1), (false, 0, 2)]); + assert_eq!(heap_ranges(1, &t), vec![(false, 0, 3), (true, 2, 1), (false, 0, 4)]); + let total: u32 = heap_ranges(0, &t).iter().map(|r| r.2).sum(); + assert_eq!(total, t.len() as u32); + } + + // --- on the GPU (each format group alone first: Metal ends the process on what it cannot + // make) --------------------------------------------------------------------------------- + + struct Gpu { + dev: ID3D12Device, + queue: ID3D12CommandQueue, + adapter: IDXGIAdapter3, + } + + fn gpu() -> Option { + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let Ok(adapter) = factory.EnumAdapters1(0) else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 || String::from_utf16_lossy(&d.Description).contains("Basic Render Driver")) { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + }; + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_err() + || o.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 + || o.ResourceHeapTier.0 < 2 + { + crate::gpu::recomp::runner::skip_test("tiled resources tier < 2"); + return None; + } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; + let adapter: IDXGIAdapter3 = adapter.cast().ok()?; + Some(Gpu { dev, queue, adapter }) + } + } + + impl Gpu { + fn local(&self) -> u64 { + let mut i = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + unsafe { + let _ = self.adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut i); + } + i.CurrentUsage + } + + unsafe fn reserved(&self, w: u64, h: u32, array: u16, mips: u16, format: i32) -> Option { + let d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: h, + DepthOrArraySize: array, + MipLevels: mips, + Format: DXGI_FORMAT(format), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + ..Default::default() + }; + let mut r: Option = None; + self.dev.CreateReservedResource(&d, D3D12_RESOURCE_STATE_COMMON, None, &mut r).ok()?; + r + } + + unsafe fn committed(&self, like: &ID3D12Resource) -> ID3D12Resource { + let d = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, ..like.GetDesc() }; + let mut r: Option = None; + self.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + } + + /// Every subresource of `r` as a pattern of `seed` (D3D12 order). + unsafe fn pattern(&self, r: &ID3D12Resource, seed: u8) -> Vec { + let d = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, ..r.GetDesc() }; + let n = d.MipLevels as u32 * d.DepthOrArraySize as u32; + let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n as usize]; + let mut rows = vec![0u32; n as usize]; + let mut row_bytes = vec![0u64; n as usize]; + self.dev.GetCopyableFootprints(&d, 0, n, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), None); + (0..n as usize) + .map(|k| { + let (rows, rb) = (rows[k] as usize, row_bytes[k] as usize); + let data = (0..rows * rb).map(|i| seed.wrapping_add((k * 37) as u8) ^ (i * 13 + i / 251) as u8 | 1).collect(); + Subresource { rows, row_bytes: rb, depth: 1, data } + }) + .collect() + } + + /// Subresource `sub` of `r` as it holds it (rows of its footprint). + unsafe fn read(&self, r: &ID3D12Resource, sub: u32) -> Vec { + let rd = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, ..r.GetDesc() }; + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + self.dev.GetCopyableFootprints(&rd, sub, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + self.dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &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() }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = self.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = self.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + 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(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + self.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&self.dev, &self.queue).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + rb.Unmap(0, None); + out + } + + fn removed(&self) { + unsafe { self.dev.GetDeviceRemovedReason() }.expect("the device was removed"); + } + } + + /// A reserved texture of each shape the title streams, in `formats` (the first a typed one; + /// a typeless one gets views of the others): every group mapped from two pool heaps in turn, + /// uploaded through `upload_batch`, read back exactly; every kind of view XCL makes of it; + /// the device never removed. + fn gate(formats: &[i32], label: &str) { + let Some(g) = gpu() else { return }; + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let shapes: [(&str, u64, u32, u16, u16); 7] = [ + ("2D 256x256, 9 mips", 256, 256, 1, 9), + ("2D 2048x2048, 12 mips", 2048, 2048, 1, 12), + ("2D 1024x512, 11 mips", 1024, 512, 1, 11), + ("2D 1000x600, 10 mips", 1000, 600, 1, 10), + ("2D 128x128, 8 mips (all packed?)", 128, 128, 1, 8), + ("array 512x512x4, 10 mips", 512, 512, 4, 10), + ("cube 256x256x6, 9 mips", 256, 256, 6, 9), + ]; + let mut pool: Pool = Pool::new(); + for _ in 0..2 { + let desc = D3D12_HEAP_DESC { + SizeInBytes: HEAP_TILES as u64 * TILE, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_CREATE_NOT_ZEROED | D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut h: Option = None; + g.dev.CreateHeap(&desc, &mut h).expect("pool heap"); + pool.add_heap(h.unwrap(), HEAP_TILES); + } + let heaps: Vec<(u32, ID3D12Heap)> = pool.heaps.iter().enumerate().map(|(k, h)| (k as u32, h.clone())).collect(); + let views: ID3D12DescriptorHeap = g.dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 64, ..Default::default() }).unwrap(); + let step = g.dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let mut slot = 0usize; + let mut round = 0u32; + for &format in formats { + for (name, w, h, array, mips) in shapes { + let what = format!("{label} format {format} {name}"); + eprintln!("{what}: reserving"); + let Some(r) = g.reserved(w, h, array, mips, format) else { + panic!("{what}: CreateReservedResource failed"); + }; + let shape = shape_of(&g.dev, &r, true).expect("tiling"); + let mut packed = D3D12_PACKED_MIP_INFO::default(); + let mut total = 0; + g.dev.GetResourceTiling(&r, Some(&mut total), Some(&mut packed), None, None, 0, std::ptr::null_mut()); + eprintln!( + "{what}: {} tiles, {} groups (standard mips {}, packed {} in {} tiles from {}); committed {} KiB", + shape.total, + shape.groups.len(), + packed.NumStandardMips, + packed.NumPackedMips, + packed.NumTilesForPackedMips, + packed.StartTileIndexInOverallResource, + g.dev.GetResourceAllocationInfo(0, &[D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, ..r.GetDesc() }]).SizeInBytes >> 10 + ); + // tiles of both heaps in turn, scattered in each (7 and 1023 have no common + // factor: no tile twice): one call per heap, runs and skips in each + let assign: Vec> = (0..shape.total).map(|k| Some((k % 2, (k / 2 + 1 + round * 97) * 7 % HEAP_TILES))).collect(); + round += 1; + map(&g.queue, &r, &heaps, &assign); + let subs = g.pattern(&r, format as u8); + let failed = texture::upload_batch(&g.dev, &g.queue, &[(r.clone(), subs.clone(), vec![D3D12_RESOURCE_STATE_COMMON])]).expect("upload"); + assert!(failed.is_empty(), "{what}: {failed:?}"); + for (k, s) in subs.iter().enumerate() { + let got = g.read(&r, k as u32); + assert!(got == s.data, "{what}: subresource {k} differs ({} of {} bytes)", got.iter().zip(&s.data).filter(|(x, y)| x != y).count(), s.data.len()); + } + g.removed(); + // the views XCL makes: the texture's own, its slices, a cube as a cube + // array, and for a typeless texture each typed format of the group + let typed: Vec = if formats.len() > 1 && format == formats[formats.len() - 1] { formats[..formats.len() - 1].to_vec() } else { vec![format] }; + for f in typed { + let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT(f), Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; + let kinds: Vec = if array == 6 { + vec![ + D3D12_SHADER_RESOURCE_VIEW_DESC { ViewDimension: D3D12_SRV_DIMENSION_TEXTURECUBEARRAY, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { TextureCubeArray: D3D12_TEXCUBE_ARRAY_SRV { MostDetailedMip: 0, MipLevels: u32::MAX, First2DArrayFace: 0, NumCubes: 1, ResourceMinLODClamp: 0.0 } }, ..v }, + D3D12_SHADER_RESOURCE_VIEW_DESC { ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: 0, MipLevels: u32::MAX, FirstArraySlice: 0, ArraySize: 6, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }, ..v }, + ] + } else if array > 1 { + vec![D3D12_SHADER_RESOURCE_VIEW_DESC { ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: 0, MipLevels: u32::MAX, FirstArraySlice: 0, ArraySize: array as u32, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }, ..v }] + } else { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Anonymous = D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: u32::MAX, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }; + vec![v, D3D12_SHADER_RESOURCE_VIEW_DESC { Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 1, MipLevels: 2, PlaneSlice: 0, ResourceMinLODClamp: 1.0 } }, ..v }] + }; + for k in kinds { + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: views.GetCPUDescriptorHandleForHeapStart().ptr + (slot % 64) * step }; + slot += 1; + g.dev.CreateShaderResourceView(&r, Some(&k), cpu); + } + } + g.removed(); + eprintln!("{what}: ok"); + } + } + } + } + + #[test] + fn gate_bc1_reserved_textures_map_upload_and_read_back() { + gate(&[71, 72, 70], "BC1"); + } + + #[test] + fn gate_bc2_reserved_textures_map_upload_and_read_back() { + gate(&[74, 75, 73], "BC2"); + } + + #[test] + fn gate_bc3_reserved_textures_map_upload_and_read_back() { + gate(&[77, 78, 76], "BC3"); + } + + #[test] + fn gate_bc4_reserved_textures_map_upload_and_read_back() { + gate(&[80, 81, 79], "BC4"); + } + + #[test] + fn gate_bc5_reserved_textures_map_upload_and_read_back() { + gate(&[83, 84, 82], "BC5"); + } + + #[test] + fn gate_bc6h_reserved_textures_map_upload_and_read_back() { + gate(&[95, 96, 94], "BC6H"); + } + + #[test] + fn gate_bc7_reserved_textures_map_upload_and_read_back() { + gate(&[98, 99, 97], "BC7"); + } + + #[test] + fn gate_rgba8_reserved_textures_map_upload_and_read_back() { + gate(&[28, 29, 27], "RGBA8"); + } + + /// Mip by mip: a group mapped alone holds what was copied into it and the others read as + /// zero; a copy to a subresource with no tiles goes nowhere; tiles of a released texture + /// serve the next one. + #[test] + fn gate_groups_map_one_by_one() { + let Some(g) = gpu() else { return }; + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let mut pool: Pool = Pool::new(); + let desc = D3D12_HEAP_DESC { + SizeInBytes: HEAP_TILES as u64 * TILE, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_CREATE_NOT_ZEROED | D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut h: Option = None; + g.dev.CreateHeap(&desc, &mut h).unwrap(); + pool.add_heap(h.unwrap(), HEAP_TILES); + let heaps: Vec<(u32, ID3D12Heap)> = vec![(0, pool.heaps[0].clone())]; + for (w, h, array, mips, format, label) in [(1024u64, 1024u32, 1u16, 11u16, 98, "BC7 1024² 11 mips"), (512, 512, 4, 10, 71, "BC1 512² x4 10 mips"), (256, 256, 6, 9, 77, "BC3 cube 256² 9 mips")] { + let r = g.reserved(w, h, array, mips, format).expect("reserved"); + let shape = shape_of(&g.dev, &r, true).unwrap(); + assert!(shape.groups.len() > 1, "{label}: groups by mip ({} tiles)", shape.total); + let subs = g.pattern(&r, 0x5A); + let nsubs = subs.len(); + // the groups in an order that is not the tiles' (the last first) + let mut order: Vec = (0..shape.groups.len()).collect(); + order.reverse(); + let third = order.len() / 3; + order.rotate_left(third); + let mut backed = vec![false; nsubs]; + let mut taken: Vec> = Vec::new(); + for (step, &k) in order.iter().enumerate() { + let grp = &shape.groups[k]; + let tiles = pool.take(grp.tiles as usize, &|_| true).unwrap(); + let mut assign = vec![None; shape.total as usize]; + for (j, t) in tiles.iter().enumerate() { + assign[grp.start as usize + j] = Some(*t); + } + map(&g.queue, &r, &heaps, &assign); + taken.push(tiles); + for &s in &grp.subs { + backed[s as usize] = true; + } + // the whole texture uploaded, as for a texture whose memory came: copies + // only into what has tiles + let mask: Vec = backed.clone(); + let failed = texture::upload_batch_masked(&g.dev, &g.queue, &[(r.clone(), subs.clone(), vec![D3D12_RESOURCE_STATE_COMMON])], &[Some(mask)]).unwrap(); + assert!(failed.is_empty()); + if step % 3 == 0 || step + 1 == order.len() { + for (s, sub) in subs.iter().enumerate() { + let got = g.read(&r, s as u32); + if backed[s] { + assert!(got == sub.data, "{label}: step {step}: subresource {s} (backed) differs"); + } else { + assert!(got.iter().all(|&b| b == 0), "{label}: step {step}: subresource {s} (no tiles) is not zero"); + } + } + } + g.removed(); + } + // a copy into a texture with no tiles at all goes nowhere and harms nothing + let bare = g.reserved(w, h, array, mips, format).unwrap(); + let failed = texture::upload_batch(&g.dev, &g.queue, &[(bare.clone(), subs.clone(), vec![D3D12_RESOURCE_STATE_COMMON])]).unwrap(); + assert!(failed.is_empty()); + assert!(g.read(&bare, 0).iter().all(|&b| b == 0), "{label}: a texture with no tiles reads as zero"); + g.removed(); + // the tiles of a released texture serve the next one + drop(r); + texture::wait(&g.dev, &g.queue).unwrap(); + let next = g.reserved(w, h, array, mips, format).unwrap(); + let mut assign = vec![None; shape.total as usize]; + for (k, tiles) in order.iter().zip(&taken) { + let grp = &shape.groups[*k]; + for (j, t) in tiles.iter().enumerate() { + assign[grp.start as usize + j] = Some(*t); + } + } + map(&g.queue, &next, &heaps, &assign); + let other = g.pattern(&next, 0xC3); + texture::upload_batch(&g.dev, &g.queue, &[(next.clone(), other.clone(), vec![D3D12_RESOURCE_STATE_COMMON])]).unwrap(); + for (s, sub) in other.iter().enumerate() { + assert!(g.read(&next, s as u32) == sub.data, "{label}: reused tiles: subresource {s} differs"); + } + for t in taken { + pool.give_back(t); + } + g.removed(); + eprintln!("{label}: ok"); + } + } + } + + /// Reserved textures with no tiles cost next to nothing; tiles cost their size; making one + /// is quick. + #[test] + fn gate_unbacked_reserved_textures_cost_little() { + let Some(g) = gpu() else { return }; + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let before = g.local(); + let t0 = std::time::Instant::now(); + let made: Vec = (0..1024).map(|_| g.reserved(1024, 1024, 1, 11, 98).expect("reserved")).collect(); + let per = t0.elapsed().as_secs_f64() * 1e6 / 1024.0; + let after = g.local(); + let grew = after.saturating_sub(before); + eprintln!("1024 reserved BC7 1024² textures with no tiles: +{} MiB local video memory, {per:.0} µs each", grew >> 20); + let shape = shape_of(&g.dev, &made[0], true).unwrap(); + // their tiles: 128 of them backed whole + let mut pool: Pool = Pool::new(); + let need = 128 * shape.total as usize; + let heaps_n = need.div_ceil(HEAP_TILES as usize); + let t1 = std::time::Instant::now(); + for _ in 0..heaps_n { + let desc = D3D12_HEAP_DESC { + SizeInBytes: HEAP_TILES as u64 * TILE, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_CREATE_NOT_ZEROED | D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut h: Option = None; + g.dev.CreateHeap(&desc, &mut h).unwrap(); + pool.add_heap(h.unwrap(), HEAP_TILES); + } + let heaps: Vec<(u32, ID3D12Heap)> = pool.heaps.iter().enumerate().map(|(k, h)| (k as u32, h.clone())).collect(); + let with_heaps = g.local(); + let t2 = std::time::Instant::now(); + for r in made.iter().take(128) { + let tiles = pool.take(shape.total as usize, &|_| true).unwrap(); + let assign: Vec> = tiles.into_iter().map(Some).collect(); + map(&g.queue, r, &heaps, &assign); + } + texture::wait(&g.dev, &g.queue).unwrap(); + let per_map = t2.elapsed().as_secs_f64() * 1e3 / 128.0; + let mapped = g.local(); + eprintln!( + "{} pool heaps of 64 MiB: +{} MiB in {} ms; 128 textures of {} tiles mapped: +{} MiB more, {per_map:.2} ms a texture", + heaps_n, + with_heaps.saturating_sub(after) >> 20, + t1.elapsed().as_millis(), + shape.total, + mapped.saturating_sub(with_heaps) >> 20 + ); + assert!(grew < 64 << 20, "1024 reserved textures with no tiles took {} MiB", grew >> 20); + g.removed(); + } + } + + /// Copies between a reserved texture and a committed one, both ways, give the same bytes; + /// a copy out of a group with no tiles gives zeros. + #[test] + fn gate_copies_between_reserved_and_committed_textures() { + let Some(g) = gpu() else { return }; + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let mut pool: Pool = Pool::new(); + let desc = D3D12_HEAP_DESC { + SizeInBytes: HEAP_TILES as u64 * TILE, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_CREATE_NOT_ZEROED | D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut h: Option = None; + g.dev.CreateHeap(&desc, &mut h).unwrap(); + pool.add_heap(h.unwrap(), HEAP_TILES); + let heaps: Vec<(u32, ID3D12Heap)> = vec![(0, pool.heaps[0].clone())]; + let r = g.reserved(512, 512, 1, 10, 98).unwrap(); + let shape = shape_of(&g.dev, &r, true).unwrap(); + let all = pool.take(shape.total as usize, &|_| true).unwrap(); + map(&g.queue, &r, &heaps, &all.iter().copied().map(Some).collect::>()); + let c = g.committed(&r); + let subs = g.pattern(&c, 0x33); + texture::upload_batch(&g.dev, &g.queue, &[(c.clone(), subs.clone(), vec![D3D12_RESOURCE_STATE_COMMON])]).unwrap(); + let copy = |dst: &ID3D12Resource, src: &ID3D12Resource, whole: bool| { + let alloc: ID3D12CommandAllocator = g.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = g.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + if whole { + list.CopyResource(dst, src); + } else { + for k in 0..subs.len() as u32 { + let d = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(dst), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k } }; + let s = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(src), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k } }; + list.CopyTextureRegion(&d, 0, 0, 0, &s, None); + } + } + list.Close().unwrap(); + g.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&g.dev, &g.queue).unwrap(); + }; + for whole in [true, false] { + copy(&r, &c, whole); + for (k, s) in subs.iter().enumerate() { + assert!(g.read(&r, k as u32) == s.data, "committed → reserved ({}): subresource {k}", if whole { "CopyResource" } else { "CopyTextureRegion" }); + } + let back = g.committed(&r); + copy(&back, &r, whole); + for (k, s) in subs.iter().enumerate() { + assert!(g.read(&back, k as u32) == s.data, "reserved → committed ({}): subresource {k}", if whole { "CopyResource" } else { "CopyTextureRegion" }); + } + g.removed(); + } + // a reserved texture with only its last group backed: out of it, zeros elsewhere + let part = g.reserved(512, 512, 1, 10, 98).unwrap(); + let last = shape.groups.last().unwrap().clone(); + let tiles = pool.take(last.tiles as usize, &|_| true).unwrap(); + let mut assign = vec![None; shape.total as usize]; + for (j, t) in tiles.iter().enumerate() { + assign[last.start as usize + j] = Some(*t); + } + map(&g.queue, &part, &heaps, &assign); + let mut mask = vec![false; subs.len()]; + for &s in &last.subs { + mask[s as usize] = true; + } + texture::upload_batch_masked(&g.dev, &g.queue, &[(part.clone(), subs.clone(), vec![D3D12_RESOURCE_STATE_COMMON])], &[Some(mask.clone())]).unwrap(); + let out = g.committed(&part); + copy(&out, &part, true); + for (k, s) in subs.iter().enumerate() { + let got = g.read(&out, k as u32); + if mask[k] { + assert!(got == s.data, "partly backed → committed: subresource {k} (backed)"); + } else { + assert!(got.iter().all(|&b| b == 0), "partly backed → committed: subresource {k} (no tiles) not zero"); + } + } + g.removed(); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 6c8d0c0..e1d0f54 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1857,6 +1857,7 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, (pre_ok.0, pre_ok.1, pre_ok.2, wait_seq) }; + crate::waitwatch::note_gpu_wait("Wait64 (title memory value)", q_raw as usize, &fence, w.value); if let Err(e) = q.Wait(&fence, w.value) { let mut g = SYNC_GRAPH.lock().unwrap(); if let Some(cell) = g.as_mut().and_then(|gr| gr.cells.get_mut(&w.va)) { @@ -2056,6 +2057,7 @@ pub(super) unsafe fn execute_with_waits(lists: &[*mut c_void], submit: impl FnMu /// command list #60 CopyMemoryToMemoryX(destination, source, size, flags) pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, src: u64, size: u64, _flags: u32) { + let _xcl_api = crate::waitwatch::api("list_x::copy_memory_x"); static N: AtomicU64 = AtomicU64::new(0); const W: &str = "CopyMemoryToMemoryX"; if size == 0 || !size.is_multiple_of(4) { @@ -2063,12 +2065,23 @@ pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, } let (Some((d, doff)), Some((s, soff))) = (real::uma_window_buffer(dst as usize, size as usize), real::uma_window_buffer(src as usize, size as usize)) else { note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); + note_view_copy(dst as usize, src as usize, size as usize); + if readback_copy(this, dst as usize, src as usize, size as usize) { + return; + } if crate::util::mac_host() && cpu_copy(this, dst as usize, src as usize, size as usize) { return; } return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) is not in unified memory")); }; note_gpu_write("CopyMemoryToMemoryX", dst as usize, size); + { + static U: AtomicU64 = AtomicU64::new(0); + let k = U.fetch_add(1, Ordering::Relaxed); + if k < 6 || k.is_power_of_two() { + crate::xlog_info!("D3D12.X: [diag] CopyMemoryToMemoryX #{k} in unified memory: {src:#x} → {dst:#x} ({size:#x} B, flags {_flags:#x})"); + } + } if d == s && dst < src + size && src < dst + size { return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) overlap")); } @@ -2121,6 +2134,222 @@ unsafe fn cpu_copy(list: *mut c_void, dst: usize, src: usize, len: usize) -> boo true } +/// Whether `[src, src + len)` is in a GPU view of the title's memory (its page pool's: what the +/// title streams in, through the CPU's view of the same pages). +fn in_gpu_view(src: usize, len: usize) -> bool { + crate::hle::kernelx::mirrors::source(src).is_some() || super::gpu_views::in_range(src, len) +} + +/// Local diagnostic: a CopyMemoryToMemoryX out of a GPU view of the title's memory – the +/// physical page the GPU sees there, where the CPU has it and what is there now, the CPU-view +/// address paired with it and its page, and the DirectStorage request that last wrote either. +unsafe fn note_view_copy(dst: usize, src: usize, len: usize) { + if in_gpu_view(dst, len) { + static M: AtomicU64 = AtomicU64::new(0); + if M.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!("D3D12.X: [diag] CopyMemoryToMemoryX into a GPU view: {src:#x} → {dst:#x} ({len:#x} B); from {}", crate::hle::kernelx::callers(2)); + } + } + if !in_gpu_view(src, len) { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) >= 8 { + return; + } + let phys = super::gpu_views::physical_page_at(src); + let place = super::gpu_views::memory_at(src); + let paired = crate::hle::kernelx::mirrors::source(src); + let nonzero = |a: Option| a.filter(|&a| crate::gpu::shader::readable(a, len)).map(|a| std::slice::from_raw_parts(a as *const u8, len).iter().filter(|&&b| b != 0).count()); + let (seen, all) = super::title_textures::read_memory(src, len); + let dst_nonzero = crate::gpu::shader::readable(dst, len).then(|| std::slice::from_raw_parts(dst as *const u8, len).iter().filter(|&&b| b != 0).count()); + let dst_head: String = if crate::gpu::shader::readable(dst, len) { std::slice::from_raw_parts(dst as *const u8, len.min(128)).iter().map(|b| format!("{b:02x}")).collect() } else { String::new() }; + crate::xlog_info!("D3D12.X: [diag] that copy's other end {dst:#x} holds {dst_nonzero:?} non-zero bytes of {len:#x} now: {dst_head}; called from {}", crate::hle::kernelx::callers(2)); + crate::xlog_info!( + "D3D12.X: [diag] copy out of a GPU view {src:#x} → {dst:#x} ({len:#x} B): the GPU's page {} ({}); the CPU has it at {:x?}: {:?} non-zero bytes, last written by {}; the paired CPU address {:x?} (page there {:x?}): {:?} non-zero bytes, last written by {}; as the GPU would read it: {} non-zero (all there {all}); textures over it {:x?}; {}", + phys.map_or("none".into(), |p| format!("{p:#x}")), + phys.map_or(String::new(), crate::hle::kernelx::describe_physical_page), + place, + nonzero(place), + place.map_or("-".into(), crate::hle::dstorage::last_write_at), + paired, + paired.and_then(crate::hle::kernelx::page_at), + nonzero(paired), + paired.map_or("-".into(), crate::hle::dstorage::last_write_at), + seen.iter().filter(|&&b| b != 0).count(), + super::title_textures::overlapping(src, len), + crate::hle::dstorage::probe_line() + ); +} + +/// Local fix (`XCL_GPU_READBACK_COPY`, on unless "0"): CopyMemoryToMemoryX into the title's own +/// writable memory from a buffer the title placed at its own address that has a PC resource of +/// its own (`real::title_buffer_at`). What the GPU wrote there (ResolveQueryData, copies, UAVs) +/// is only in that PC resource – the title's memory at that address holds nothing (GTA VI +/// 1.0.2.1 copied 16 KiB of zeros at its first loading screen and waited for ever). The copy is +/// recorded on the GPU at this point of the list, into a READBACK buffer, and the worker writes +/// the bytes to `dst` once the queue is past it (`cpu_writes`, ordered before the title's own +/// later signals). Whether the copy was taken. +unsafe fn readback_copy(list: *mut c_void, dst: usize, src: usize, len: usize) -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_GPU_READBACK_COPY").map_or(true, |v| v.trim() != "0")) { + return false; + } + if len == 0 || !super::cpu_writes::writable(dst, len) { + return false; + } + // a GPU view of the title's memory (its page pool: streamed data) is read where the CPU has + // its pages (`cpu_copy`, as upstream), unless the GPU wrote a texture there – + // `XCL_GPU_VIEW_READBACK=1`: read back the PC texture over it instead + static VIEW_READBACK: std::sync::OnceLock = std::sync::OnceLock::new(); + if in_gpu_view(src, len) && !super::title_textures::gpu_written_over(src, len) && !*VIEW_READBACK.get_or_init(|| std::env::var("XCL_GPU_VIEW_READBACK").is_ok_and(|v| v.trim() == "1")) { + return false; + } + if let Some(done) = texture_readback_copy(list, dst, src, len) { + return done; + } + // (the copy source comes with a reference of its own: the job keeps it until the copy ran) + let Some((src_res, off)) = real::title_buffer_at(src, len) else { + static DIAG: AtomicU64 = AtomicU64::new(0); + if DIAG.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: [diag] copy source {src:#x} ({len:#x} B): no placed buffer covers it; textures over it {:x?}; {}", + super::title_textures::overlapping(src, len), + real::describe_near(src) + ); + } + return false; + }; + let Some(dev) = device_of(list) else { return false }; + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: len as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb: Option = None; + if dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).is_err() { + return false; + } + let Some(rb) = rb else { return false }; + let mut mapped: *mut c_void = std::ptr::null_mut(); + if rb.Map(0, None, Some(&mut mapped)).is_err() || mapped.is_null() { + return false; + } + let rb_raw = rb.as_raw() as usize; + let res = src_res.as_raw() as usize; + { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { return false }; + s.cpu_writes.push(super::cpu_writes::Write::ReadbackCopy { dst, src: mapped as usize, len, _buf: rb, _src: src_res }); + } + transition(list, res, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + copy_buffer_region(list, rb_raw, 0, res, off, len as u64); + transition(list, res, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: CopyMemoryToMemoryX: {src:#x} → {dst:#x} ({len:#x} bytes): the source is a title buffer with a PC resource of its own – copied on the GPU and read back (#{n})"); + } + true +} + +/// Local fix: CopyMemoryToMemoryX out of a title texture's memory (`title_textures::covering`). +/// On the console the bytes there are what the GPU drew; here they are in the PC texture. Its +/// subresources are copied on the GPU (at this point of the list) into a READBACK buffer and +/// the worker lays them out as the console has the texture, writing the copied range to `dst`. +/// None: not a texture (the caller goes on); Some(taken). +unsafe fn texture_readback_copy(list: *mut c_void, dst: usize, src: usize, len: usize) -> Option { + let (tres, tva, tex) = super::title_textures::covering(src, len)?; + let surf = tex.texels()?; + let desc = crate::gpu::texture::copyable_desc(&tres); + if desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D { + return Some(false); + } + let (mips, array) = (desc.MipLevels.max(1) as u32, desc.DepthOrArraySize.max(1) as u32); + let n = (mips * array) as usize; + if n == 0 || n > 512 { + return Some(false); + } + let dev = device_of(list)?; + let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; + let mut total = 0u64; + dev.GetCopyableFootprints(&desc, 0, n as u32, 0, Some(fps.as_mut_ptr()), None, None, Some(&mut total)); + if total == 0 || total > 64 << 20 { + return Some(false); + } + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb: Option = None; + if dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).is_err() { + return Some(false); + } + let rb = rb?; + let mut mapped: *mut c_void = std::ptr::null_mut(); + if rb.Map(0, None, Some(&mut mapped)).is_err() || mapped.is_null() { + return Some(false); + } + { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { return Some(false) }; + s.cpu_writes.push(super::cpu_writes::Write::TextureReadback { + dst, + len, + skip: src - tva, + mapped: mapped as usize, + footprints: fps.clone(), + mips, + array, + side: surf.side, + tex: std::sync::Arc::clone(&tex), + _buf: rb.clone(), + // (the texture stays until the copy out of it ran, the list's reference to it the + // only one otherwise) + _src: tres.clone(), + }); + } + let tres_raw = tres.as_raw() as usize; + transition(list, tres_raw, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + type Ctr = unsafe extern "system" fn(*mut c_void, *const D3D12_TEXTURE_COPY_LOCATION, u32, u32, u32, *const D3D12_TEXTURE_COPY_LOCATION, *const D3D12_BOX); + for (k, fp) in fps.iter().enumerate() { + let d = 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 s = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&tres), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 }, + }; + pc::(list, PC_COPY_TEXTURE_REGION)(list, &d, 0, 0, 0, &s, std::ptr::null()); + } + transition(list, tres_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if k < 4 || k.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: CopyMemoryToMemoryX: {src:#x} → {dst:#x} ({len:#x} bytes) out of a title texture at {tva:#x} ({}x{}, {mips} mips, {array} slices, format {}) – copied on the GPU and read back (#{k})", + desc.Width, desc.Height, desc.Format.0 + ); + } + Some(true) +} + unsafe fn device_of(list: *mut c_void) -> Option { let mut dev: Option = None; ID3D12GraphicsCommandList::from_raw_borrowed(&list)?.GetDevice(&mut dev).ok()?; @@ -2647,9 +2876,10 @@ pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min: pc::(this, PC_OM_SET_DEPTH_BOUNDS)(this, min, max); } -/// command list #78 DispatchX(x, y, z, flags) -pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, _flags: u32) { - super::bind::dispatch(this, x, y, z); +/// command list #78 DispatchX(x, y, z, flags): a Dispatch – its flags are named, not applied +/// (`bind::dispatch_x`) +pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + super::bind::dispatch_x(this, x, y, z, flags); } /// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH @@ -2839,6 +3069,7 @@ pub unsafe extern "system" fn set_predication_buffer_x(this: *mut c_void, desc: /// # Safety /// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { + let _xcl_api = crate::waitwatch::api("list_x::kickoff_x"); static NO_QUEUE: AtomicU64 = AtomicU64::new(0); static ERR: AtomicU64 = AtomicU64::new(0); let ty = list_type(this); @@ -2901,6 +3132,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let q_raw = queue as *mut c_void; + // (a recording run again: its dispatch blocks start afresh before the CPU's writes go up) + super::bind::before_submit(&[this]); + sync_view_mirrors(); super::title_textures::refresh(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); @@ -2911,7 +3145,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { execute_with_waits_on(q_raw, prior, |chunk| { - exec(q_raw, chunk.len() as u32, chunk.as_ptr()); + super::stall::submitted(q_raw, chunk); + // (KickoffX goes past the queue hook: the value deferred releases wait for is + // reserved and signalled here – `late_release`) + super::late_release::submit(q_raw, || exec(q_raw, chunk.len() as u32, chunk.as_ptr())); super::alloc_pool::executed(q_raw, chunk); signal_write64_fences(q_raw, chunk); readback_sparse_writes(q_raw, chunk); @@ -2929,7 +3166,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let one = [this]; - exec(q_raw, 1, one.as_ptr()); + super::stall::submitted(q_raw, &one); + super::late_release::submit(q_raw, || exec(q_raw, 1, one.as_ptr())); + // (it records anew after the PC Reset below) + super::bind::kicked_off(this); super::alloc_pool::executed(q_raw, &one); signal_write64_pairs(q_raw, &write64_signals); // what ran is in the textures' states; the list records anew after its Reset below @@ -2989,6 +3229,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } + if target != this { + super::bind::kicked_off(target); + } let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(target as usize))).map(|s| s.bindings.clone()); if let Some(b) = bindings { restore_bindings(target, &b, ty); @@ -3140,6 +3383,14 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b } } +#[cfg(test)] +thread_local! { + /// (tests) Called with the depth-bias variant between `prepare_draw`'s two looks at it – + /// after `resolve_for_bind` gave its stand-in, before `standin_state` – where a worker's build + /// of it can complete. + static TEST_BETWEEN_LOOKS: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + /// Apply a pending fallback `RSSetDepthBiasX` override before a draw call on `list`. pub(super) unsafe fn prepare_draw(list: *mut c_void) { if !DEPTH_BIAS_USED.load(Ordering::Acquire) { @@ -3162,6 +3413,16 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { let (target, is_fallback) = match bias { Some(b) => { static MISS: AtomicU64 = AtomicU64::new(0); + // (run 64 did not tell whether GTA VI calls RSSetDepthBiasX: the fallback logged only failures) + static FIRST: std::sync::Once = std::sync::Once::new(); + FIRST.call_once(|| { + crate::xlog_info!( + "D3D12.X: RSSetDepthBiasX – the title draws with a depth bias ({}, clamp {}, slope {} on pipeline {bound_pso:#x}): drawn with pipelines derived for each bias (the patched-PSO fallback, no native dynamic depth bias)", + b.depth_bias(), + b.depth_bias_clamp(), + b.slope_scaled_depth_bias() + ) + }); let Some(dev) = device_of(list) else { return }; match device_x::depth_bias_pso(dev.as_raw(), bound_pso, b) { Some(derived) => (derived, true), @@ -3175,7 +3436,42 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { } None => (bound_pso, false), }; - let resolved = super::pso_async::resolve_for_bind(target); + let mut resolved = super::pso_async::resolve_for_bind(target); + // A variant made of a translated pipeline is a stand-in until a worker builds it (`resolve` sent + // it): the PC list keeps the base pipeline `bind` set with XCL's root signature – a valid pair, + // only the bias missing –, never the stand-in, whose shaders are XCL's on the title's root + // signature (the pair `bind`'s gate keeps off the PC). The next draw looks again; a variant + // whose build is over without a pipeline (failed, refused) is not looked for again. + if is_fallback && resolved == target { + #[cfg(test)] + TEST_BETWEEN_LOOKS.with(|h| { + if let Some(f) = h.borrow_mut().as_mut() { + f(target) + } + }); + match super::pso_async::standin_state(target) { + Some(st) if !st.built => { + if !st.done { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.pso_dirty = true; + } + } + static UNBUILT: AtomicU64 = AtomicU64::new(0); + let n = UNBUILT.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: RSSetDepthBiasX – a draw with the depth-bias variant {target:#x} of pipeline {bound_pso:#x} {}: drawn with the base pipeline, without the bias ({n} such draws so far)", + if st.done { "whose build failed or was refused" } else { "not built yet" } + ); + } + return; + } + // built since `resolve_for_bind` looked (a worker's `complete` came in between): the + // built variant `resolve` gives now is set, not the stand-in that look gave + Some(_) => resolved = super::pso_async::resolve(target), + None => {} + } + } pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { s.using_fallback_pso = is_fallback; @@ -3255,6 +3551,86 @@ static MIRRORS: Mutex> = Mutex::new(Vec::new()); /// bytes of mirrors made (never freed) static MIRROR_BYTES: AtomicU64 = AtomicU64::new(0); +/// Local fix (`XCL_VIEW_MIRRORS=1`, off by default): buffer views the title made of its own +/// memory outside unified memory (SRVs, CBVs) read through a mirror (`mirror_of`), refreshed +/// from the title's memory before every submit (`sync_view_mirrors`). Translated shaders reach +/// buffers through unified memory only; these got an empty V# before and read zeros (GTA VI +/// 1.0.2.1: over 64 such buffers by its first loading screen, up to 5.7 MB each). +static VIEW_MIRRORS: Mutex> = Mutex::new(Vec::new()); + +pub(super) fn view_mirrors_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_VIEW_MIRRORS").is_ok_and(|v| v.trim() == "1")) +} + +/// The mirror address standing for the title's buffer `[va, va + bytes)` in a view (made and +/// filled the first time, refreshed before each submit), if mirrors are on and it is readable. +pub(super) unsafe fn view_mirror(va: u64, bytes: usize, what: &str) -> Option { + if !view_mirrors_on() || va == 0 || bytes == 0 || !crate::gpu::shader::readable(va as usize, bytes) { + return None; + } + let p = mirror_of(va, bytes, what)?; + let range = MIRRORS.lock().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).copied(); + if let Some(r) = range { + let mut g = VIEW_MIRRORS.lock().unwrap(); + if !g.iter().any(|&(s, _, _)| s == r.0) { + g.push(r); + let total: usize = g.iter().map(|&(_, l, _)| l).sum(); + if g.len() <= 4 || g.len().is_power_of_two() { + crate::xlog_info!("D3D12.X: buffer views outside unified memory read through mirrors: {} range(s), {} KB refreshed before each submit", g.len(), total >> 10); + } + } + } + Some(p) +} + +/// Before a title submit: the mirrors of buffer views refreshed from the title's memory. +pub(super) unsafe fn sync_view_mirrors() { + if !view_mirrors_on() { + return; + } + let v = VIEW_MIRRORS.lock().unwrap().clone(); + if v.is_empty() { + return; + } + let t0 = std::time::Instant::now(); + let mut bytes = 0usize; + for (s, l, m) in v { + if crate::gpu::shader::readable(s as usize, l) { + bytes += refresh_changed(s as usize, m, l); + } + } + // (what it costs: every 2^k-th refresh logs the totals) + static N: AtomicU64 = AtomicU64::new(0); + static NANOS: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + let ns = NANOS.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed) + t0.elapsed().as_nanos() as u64; + if n.is_power_of_two() && n >= 16 { + crate::xlog_info!("D3D12.X: view mirrors refreshed {n} times, {} KB written this time, {:.2} ms on average", bytes >> 10, ns as f64 / n as f64 / 1e6); + } +} + +/// `[m, m + len)` made equal to `[s, s + len)`, page by page, writing only the pages that differ +/// (a mirror is in write-watched unified memory: every page written faults once after each look +/// for CPU writes and is uploaded again – 576 KiB written whole before each submit cost 13 ms +/// a submit under Wine). Returns the bytes written. +unsafe fn refresh_changed(s: usize, m: usize, len: usize) -> usize { + const PAGE: usize = 0x1000; + let mut written = 0; + let mut at = 0; + while at < len { + let n = (PAGE - (m + at) % PAGE).min(len - at); + let src = std::slice::from_raw_parts((s + at) as *const u8, n); + let dst = std::slice::from_raw_parts_mut((m + at) as *mut u8, n); + if src != &*dst { + dst.copy_from_slice(src); + written += n; + } + at += n; + } + written +} + /// Where `[va, va + bytes)` is in a mirror, if it is in one. fn mirrored(va: u64, bytes: usize) -> Option { MIRRORS.lock().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m)| m + (va - s) as usize) @@ -3499,6 +3875,17 @@ pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, vi set_index_buffer(this, Some(&v)); } +/// The index buffer view bound on `list` for the PC (`ia_set_index_buffer_x`: its address made the +/// PC's), if any: the indices an indexed ExecuteIndirect may read (`indirect::draw_check`). +pub(super) fn bound_index_buffer(list: *mut c_void) -> Option { + LISTS.lock().unwrap().as_ref()?.get(&(list as usize))?.index_buffer +} + +#[cfg(test)] +pub(super) fn bound_pso_for_test(list: *mut c_void) -> usize { + LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).map_or(0, |s| s.bound_pso) +} + /// command list #81 DrawIndexedX(index address, index format, index count, flags): one /// instance of `count` indices read from that address; the bound index buffer stays pub(super) unsafe extern "system" fn draw_indexed_x(this: *mut c_void, va: u64, format: DXGI_FORMAT, count: u32, _flags: u32) { @@ -3543,6 +3930,7 @@ type QueryFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u /// # Safety /// `this` must be a valid adopted `ID3D12GraphicsCommandList` pointer. pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usize) -> i32 { + let _xcl_api = crate::waitwatch::api("list_x::reset_x"); // A failed native Reset leaves the old recording alive. Do not discard its tracked state or // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); @@ -3697,6 +4085,7 @@ unsafe fn is_buffer(res: usize) -> bool { /// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it) pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { + let _xcl_api = crate::waitwatch::api("list_x::dma_close_x"); let ext = *(this as *const usize); let hr = pc:: i32>(this, 9)(this); real::preserve_vtable(this, ext); @@ -3735,6 +4124,9 @@ fn note_gpu_write(what: &str, va: usize, n: u64) { } pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { + if real::traced_res(dst).is_some() || real::traced_res(src).is_some() { + crate::xlog_info!("[trace] CopyBufferRegion {src:#x}+{src_off:#x} (at {:x?}) → {dst:#x}+{dst_off:#x} (at {:x?}), {n:#x} bytes; from {}", real::traced_res(src), real::traced_res(dst), crate::hle::kernelx::callers(1)); + } if super::present::trace_frame() { if let Some(a) = real::title_address(dst) { note_gpu_write("CopyBufferRegion", a + dst_off as usize, n); @@ -3770,6 +4162,12 @@ unsafe fn trace_watched_copy(what: &str, dst: usize, src: usize) { /// CopyTextureRegion(dst, x, y, z, src, box) (PC #16; DMA list #12) pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) { + if let (Some(d), Some(sl)) = (dst.as_ref(), src.as_ref()) { + let (dr, sr): (usize, usize) = (transmute_copy(&d.pResource), transmute_copy(&sl.pResource)); + if real::traced_res(dr).is_some() || real::traced_res(sr).is_some() { + crate::xlog_info!("[trace] CopyTextureRegion {sr:#x} (at {:x?}, type {}) → {dr:#x} (at {:x?}, type {}); from {}", real::traced_res(sr), sl.Type.0, real::traced_res(dr), d.Type.0, crate::hle::kernelx::callers(1)); + } + } if let Some(d) = dst.as_ref() { let r: usize = transmute_copy(&d.pResource); super::present::note_use(r, super::present::USE_COPY); @@ -3907,6 +4305,8 @@ unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: /// command list #19 ResolveSubresource(dst, dst sub, src, src sub, format) (PC #19) pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32) { super::present::note_use(dst, super::present::USE_COPY); + // (a lazy title texture gets tiles for all of it before this list runs) + super::title_textures::note_gpu_write_lazy(dst); trace_resolve("ResolveSubresource", dst, src, format, ""); pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) } @@ -3916,6 +4316,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds #[allow(clippy::too_many_arguments)] pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_void, dst: usize, dst_sub: u32, x: u32, y: u32, src: usize, src_sub: u32, rect: *const windows::Win32::Foundation::RECT, format: i32, mode: i32) { super::present::note_use(dst, super::present::USE_COPY); + super::title_textures::note_gpu_write_lazy(dst); if super::present::trace_frame() { trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); } @@ -3925,6 +4326,9 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v /// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address /// are copied as their own bytes (the PC resources also hold what lies before them) pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { + if real::traced_res(dst).is_some() || real::traced_res(src).is_some() { + crate::xlog_info!("[trace] CopyResource {src:#x} (at {:x?}) → {dst:#x} (at {:x?}); from {}", real::traced_res(src), real::traced_res(dst), crate::hle::kernelx::callers(1)); + } super::present::note_use(dst, super::present::USE_COPY); super::title_textures::note_gpu_write(dst); if super::present::trace_frame() { @@ -3990,6 +4394,13 @@ pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize, /// `buffer_delta(dest)` to the destination offset. pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, heap: usize, ty: D3D12_QUERY_TYPE, first: u32, count: u32, dest: usize, offset: u64) { let pc_offset = offset.saturating_add(real::buffer_delta(dest)); + { + static DIAG: AtomicU64 = AtomicU64::new(0); + let k = DIAG.fetch_add(1, Ordering::Relaxed); + if k < 6 || k.is_power_of_two() { + crate::xlog_info!("D3D12.X: [diag] ResolveQueryData #{k}: type {} first {first} count {count} → dest title address {:x?} + {offset:#x}", ty.0, real::title_address(dest)); + } + } type F = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); // (8 bytes a query; pipeline statistics, the largest, are 11 values) note_copy_into(this as usize, dest, offset, count as u64 * if ty == D3D12_QUERY_TYPE_PIPELINE_STATISTICS { 88 } else { 8 }); @@ -4539,6 +4950,206 @@ mod tests { device_x::forget_base(pso_static_only); } + /// A draw with a depth bias on the patched-PSO fallback whose variant of a translated pipeline is + /// a stand-in still being built keeps the pipeline `bind` set on the PC – the base, its pair + /// with XCL's root signature valid, only the bias missing – never the stand-in, and the next draw + /// looks again; once the variant is built, it is set (PB-3). A variant whose build is over + /// without a pipeline (refused) keeps the base too, and is not looked for again. A list, device + /// and pipelines of the test's own: 0x7A0C_40xx. + #[test] + fn a_depth_bias_variant_not_built_yet_never_reaches_the_pc() { + #[repr(C)] + struct FakeCom { + vt: *const usize, + } + static DEVICE: AtomicUsize = AtomicUsize::new(0); + thread_local! { + /// the pipelines the PC's SetPipelineState got on this thread + static SET: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + unsafe extern "system" fn query_interface(this: *mut c_void, _riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> windows::core::HRESULT { + *ppv = this; + windows::core::HRESULT(0) + } + unsafe extern "system" fn add_ref(_this: *mut c_void) -> u32 { + 2 + } + unsafe extern "system" fn release(_this: *mut c_void) -> u32 { + 1 + } + unsafe extern "system" fn get_device(_this: *mut c_void, _riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> windows::core::HRESULT { + *ppv = DEVICE.load(Ordering::Acquire) as *mut c_void; + windows::core::HRESULT(0) + } + unsafe extern "system" fn set_pipeline_state(_this: *mut c_void, pso: usize) { + SET.with(|s| s.borrow_mut().push(pso)); + } + let device_vt = [query_interface as usize, add_ref as usize, release as usize]; + let mut device = FakeCom { vt: device_vt.as_ptr() }; + DEVICE.store(&mut device as *mut FakeCom as usize, Ordering::Release); + let mut orig = Box::new([0usize; 96]); + orig[0] = query_interface as usize; + orig[1] = add_ref as usize; + orig[2] = release as usize; + orig[7] = get_device as usize; + orig[PC_SET_PIPELINE_STATE] = set_pipeline_state as usize; + let (_ext, vt) = real::test_ext_table(&orig[..]); + let mut object = FakeCom { vt }; + let list = &mut object as *mut FakeCom as *mut c_void; + let key = list as usize; + let (base, variant, built) = (0x7A0C_4001usize, 0x7A0C_4002usize, 0x7A0C_40F1usize); + let bias = DepthBias::new(-100.0, 0.0, 1.5); + // the variant: a stand-in a worker builds once its first bind sends it, held at a gate + let (open, gate) = std::sync::mpsc::channel::<()>(); + super::super::pso_async::submit_lazy( + variant, + false, + Box::new(move || { + let _ = gate.recv_timeout(Duration::from_secs(5)); + built + }), + 0, + ); + device_x::set_depth_bias_pso_for_test(base, bias, Some(variant)); + unsafe { on_create(list, 0x7A0C_4100, base, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + let arm = |bias: DepthBias| { + let mut g = LISTS.lock().unwrap(); + let s = g.as_mut().unwrap().get_mut(&key).unwrap(); + s.depth_bias = Some(bias); + s.pso_dirty = true; + DEPTH_BIAS_USED.store(true, Ordering::Release); + }; + let dirty = || LISTS.lock().unwrap().as_ref().unwrap().get(&key).unwrap().pso_dirty; + arm(bias); + unsafe { prepare_draw(list) }; + let not_built = SET.with(|s| std::mem::take(&mut *s.borrow_mut())); + let retry = dirty(); + // built (by a worker, or here if none took it yet): the next draw sets it + drop(open); + let resolved = super::super::pso_async::resolve_wait(variant); + arm(bias); + unsafe { prepare_draw(list) }; + let once_built = SET.with(|s| std::mem::take(&mut *s.borrow_mut())); + let fallback = LISTS.lock().unwrap().as_ref().unwrap().get(&key).unwrap().using_fallback_pso; + // a variant of another bias refused when made: its build is over, with no pipeline + let (refused, other) = (0x7A0C_4003usize, DepthBias::new(-200.0, 0.0, 1.5)); + let prog = super::super::pso_async::Program { hash: 0x7A0C_40A3, kind: b'G', dxil: 16 << 10, ..Default::default() }; + super::super::pso_async::submit_refused(refused, false, 0, prog); + device_x::set_depth_bias_pso_for_test(base, other, Some(refused)); + arm(other); + unsafe { prepare_draw(list) }; + let over = SET.with(|s| std::mem::take(&mut *s.borrow_mut())); + let again = dirty(); + device_x::set_depth_bias_pso_for_test(base, other, None); + let _ = super::super::pso_async::released(refused); + device_x::set_depth_bias_pso_for_test(base, bias, None); + on_release(key); + // (built: no release of the test's fake pipeline) + let _ = super::super::pso_async::released(variant); + assert_eq!(not_built, Vec::::new(), "an unbuilt variant's stand-in must not reach the PC"); + assert!(retry, "the next draw looks for the variant again"); + assert_eq!(resolved, built); + assert_eq!(once_built, vec![built], "a built variant is set"); + assert!(fallback); + assert_eq!(over, Vec::::new(), "a refused variant's stand-in must not reach the PC"); + assert!(!again, "a variant whose build is over is not looked for again"); + } + + /// A depth-bias variant whose build completes between `prepare_draw`'s two looks at it – after + /// `resolve_for_bind` gave its stand-in, before `standin_state` says it is built – is set built + /// on the PC, never as the stand-in that first look gave (GR-1: the draw went on with the + /// stand-in). A list, device and pipelines of the test's own: 0x7A0D_40xx. + #[test] + fn a_depth_bias_variant_built_between_the_two_looks_is_set_built() { + #[repr(C)] + struct FakeCom { + vt: *const usize, + } + static DEVICE: AtomicUsize = AtomicUsize::new(0); + thread_local! { + /// the pipelines the PC's SetPipelineState got on this thread + static SET: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + unsafe extern "system" fn query_interface(this: *mut c_void, _riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> windows::core::HRESULT { + *ppv = this; + windows::core::HRESULT(0) + } + unsafe extern "system" fn add_ref(_this: *mut c_void) -> u32 { + 2 + } + unsafe extern "system" fn release(_this: *mut c_void) -> u32 { + 1 + } + unsafe extern "system" fn get_device(_this: *mut c_void, _riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> windows::core::HRESULT { + *ppv = DEVICE.load(Ordering::Acquire) as *mut c_void; + windows::core::HRESULT(0) + } + unsafe extern "system" fn set_pipeline_state(_this: *mut c_void, pso: usize) { + SET.with(|s| s.borrow_mut().push(pso)); + } + let device_vt = [query_interface as usize, add_ref as usize, release as usize]; + let mut device = FakeCom { vt: device_vt.as_ptr() }; + DEVICE.store(&mut device as *mut FakeCom as usize, Ordering::Release); + let mut orig = Box::new([0usize; 96]); + orig[0] = query_interface as usize; + orig[1] = add_ref as usize; + orig[2] = release as usize; + orig[7] = get_device as usize; + orig[PC_SET_PIPELINE_STATE] = set_pipeline_state as usize; + let (_ext, vt) = real::test_ext_table(&orig[..]); + let mut object = FakeCom { vt }; + let list = &mut object as *mut FakeCom as *mut c_void; + let key = list as usize; + let (base, variant, built) = (0x7A0D_4001usize, 0x7A0D_4002usize, 0x7A0D_40F1usize); + let bias = DepthBias::new(-300.0, 0.0, 2.5); + // the variant: a stand-in a worker builds once its first bind sends it, held at a gate + let (open, gate) = std::sync::mpsc::channel::<()>(); + super::super::pso_async::submit_lazy( + variant, + false, + Box::new(move || { + let _ = gate.recv_timeout(Duration::from_secs(5)); + built + }), + 0, + ); + device_x::set_depth_bias_pso_for_test(base, bias, Some(variant)); + unsafe { on_create(list, 0x7A0D_4100, base, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + { + let mut g = LISTS.lock().unwrap(); + let s = g.as_mut().unwrap().get_mut(&key).unwrap(); + s.depth_bias = Some(bias); + s.pso_dirty = true; + DEPTH_BIAS_USED.store(true, Ordering::Release); + } + // between the two looks the gate opens and the build is waited for (by a worker, or here if + // none took it yet): it completes after `resolve_for_bind` gave the stand-in and sent it + let between = std::rc::Rc::new(std::cell::Cell::new(None)); + let (seen, mut open) = (between.clone(), Some(open)); + TEST_BETWEEN_LOOKS.with(|h| { + *h.borrow_mut() = Some(Box::new(move |pso| { + if pso == variant { + drop(open.take()); + seen.set(Some(super::super::pso_async::resolve_wait(variant))); + } + })) + }); + unsafe { prepare_draw(list) }; + TEST_BETWEEN_LOOKS.with(|h| *h.borrow_mut() = None); + let set = SET.with(|s| std::mem::take(&mut *s.borrow_mut())); + let fallback = LISTS.lock().unwrap().as_ref().unwrap().get(&key).unwrap().using_fallback_pso; + device_x::set_depth_bias_pso_for_test(base, bias, None); + on_release(key); + // (built – waited for here too, should the hook not have run: dropping it opened the gate, + // and a stand-in released while its build still runs has the build's end release the + // test's fake pipeline, a page fault that ends the test process) + let _ = super::super::pso_async::resolve_wait(variant); + let _ = super::super::pso_async::released(variant); + assert_eq!(between.get(), Some(built), "the build completed between the two looks"); + assert_eq!(set, vec![built], "a variant built between the two looks is set built, never as its stand-in"); + assert!(fallback); + } + #[test] fn resolve_query_data_applies_buffer_delta_to_pc_resolve_and_occlusion_writeback() { use std::cell::RefCell; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index fa09c9a..6297c90 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -11,17 +11,42 @@ mod alloc_pool; pub mod bind; +pub mod compose; pub mod console_heap; pub mod console_list; pub mod device_x; pub mod dxgi_device; mod cpu_writes; +/// local diagnostic (see `cpu_writes::probe_line`) +pub fn cpu_writes_probe() -> String { + cpu_writes::probe_line() +} mod fence_x; pub mod frame; pub mod gpu_views; pub mod guard; pub mod indirect; mod late_release; +mod lazy_tex; +pub(crate) mod outside; +pub(crate) mod skip_roots; +mod stall; + +/// The deferred releases' counters (references held so far, let go so far, held now). +pub(crate) fn deferred_releases() -> (u64, u64, usize) { + late_release::stats() +} + +/// The lazy title textures' line for the activity log (None: off, none made). +pub(crate) fn lazy_stats() -> Option { + lazy_tex::stats() +} +pub(crate) mod view_census; + +/// The views' census lines for the activity log (`view_census::lines`: every 10 s). +pub(crate) fn view_census_lines() -> Vec { + view_census::lines() +} pub mod layout; pub mod list_x; pub mod null; @@ -251,3 +276,178 @@ pub unsafe extern "system" fn D3D12ConfigureVirtualMemoryX(config: *const c_void } S_OK } + +/// (diagnostic `XCL_WATCH_WAITS`) title fences whose completed value lags what a queue was told. +pub fn fences_pending() -> String { + fence_x::pending_summary() +} + +/// (`XCL_ACTIVITY`, every 30 s) the buffers the title placed outside unified memory, when that +/// changed (`outside`). +pub(crate) fn outside_census() -> Option { + outside::census_line() +} + +/// (`XCL_ACTIVITY`) translated compute ExecuteIndirect so far and how many had their group +/// counts checked (`indirect::Sanitize`), dispatches not recorded (`XCL_SKIP_CS`), +/// ExecuteIndirect recorded and in lists submitted by kind and with arguments outside unified +/// memory (`indirect_lists`), views given an empty descriptor by kind (`outside`), acceleration +/// structures outside unified memory, views by address, buffer V#s new in the heaps outside +/// unified memory. +pub fn gpu_work_line() -> String { + let (_, rtas) = real::outside_uma_views(); + let census = indirect::census_on().then(indirect::census_snapshot); + work_line(stall::counts(), indirect_lists(census.as_ref(), stall::indirect_counts()), &outside::views(), rtas) +} + +/// ExecuteIndirect of translated pipelines (compute, draws) by place of their arguments +/// (`stall::Args::index`): recorded into lists, and in lists submitted. Recorded is the census's +/// (`indirect::census`: every one of a translated pipeline, counted with its fate) of those checked +/// first or sent as they were – the ones that entered a list, the same event the lists count for +/// their submissions (`stall::indirect_counts`); one that failed or that `XCL_INDIRECT_OWN=skip` +/// kept back never did. Err: either half is not counted (`census`: None – `XCL_INDIRECT_CENSUS=0`; +/// the other's switch). +fn indirect_lists(census: Option<&indirect::CensusSnapshot>, submitted: Result<[[u64; 4]; 2], &'static str>) -> Result<([[u64; 4]; 2], [[u64; 4]; 2]), &'static str> { + use indirect::Fate; + let c = census.ok_or("XCL_INDIRECT_CENSUS=0")?; + let recorded = std::array::from_fn(|k| std::array::from_fn(|p| c.n[k][p][Fate::Checked as usize] + c.n[k][p][Fate::AsIs as usize])); + Ok((recorded, submitted?)) +} + +/// The line itself. Its start is what the run scripts read, and it must not change: +/// "GPU work so far: N translated compute ExecuteIndirect (N with". +fn work_line(c: [u64; 3], indirect: Result<([[u64; 4]; 2], [[u64; 4]; 2]), &'static str>, v: &outside::Views, rtas: u64) -> String { + let own = stall::Args::Own.index(); + let sum = |m: &[[u64; 4]; 2], g: usize| m[g].iter().sum::(); + let lists = match indirect { + Ok((r, s)) => format!( + "ExecuteIndirect recorded / in lists submitted: compute {} / {} ({} / {} with arguments outside unified memory), draws {} / {} ({} / {} outside)", + sum(&r, 0), sum(&s, 0), r[0][own], s[0][own], sum(&r, 1), sum(&s, 1), r[1][own], s[1][own] + ), + Err(why) => format!("ExecuteIndirect recorded / in lists submitted: not counted ({why})"), + }; + let mut line = format!( + "GPU work so far: {} translated compute ExecuteIndirect ({} with their group counts checked), {} dispatches not recorded (XCL_SKIP_CS); {lists}; views given an empty descriptor: {}, {rtas} acceleration structures outside unified memory (an empty BVH descriptor each); {}", + c[0], c[1], c[2], v.empty_clause(), v.by_address_clause() + ); + if let Some(h) = v.heap_clause() { + line.push_str("; "); + line.push_str(&h); + } + line +} + +/// (diagnostic `XCL_WATCH_WAITS`) pipelines built and failed. +pub fn pso_probe() -> String { + pso_async::probe_line() +} + +/// Local experiment (`XCL_SERIALIZE_TILES=1`, off by default; a Mac only): XCL's tile mappings +/// (`vram`, `sparse`) and its submissions to D3DMetal (sparse uploads and readbacks, title +/// texture uploads, the title's ExecuteCommandLists) one at a time. GTA VI 1.0.2.1 stopped at +/// its first loading screen with its render thread inside D3DMetal on the sparse readback +/// queue and its streaming thread inside D3DMetal unmapping tiles, both held for good in a +/// wait of D3DMetal's own. Serializing these did not keep it from stopping (it stopped with +/// both threads outside them): kept as a switch. Reentrant on a thread; CPU waits for the GPU +/// stay outside. +pub(crate) struct D3dOps(Option>, bool); + +impl Drop for D3dOps { + fn drop(&mut self) { + if self.1 { + D3D_OPS_DEPTH.with(|d| d.set(d.get() - 1)); + } + } +} + +thread_local! { + static D3D_OPS_DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +pub(crate) fn d3d_ops() -> D3dOps { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + if !*ON.get_or_init(|| crate::util::mac_host() && std::env::var("XCL_SERIALIZE_TILES").is_ok_and(|v| v.trim() == "1")) { + return D3dOps(None, false); + } + let outer = D3D_OPS_DEPTH.with(|d| { + let v = d.get(); + d.set(v + 1); + v == 0 + }); + D3dOps(outer.then(|| LOCK.lock().unwrap_or_else(|e| e.into_inner())), true) +} + +#[cfg(test)] +mod work_line_tests { + use super::*; + + /// The figures of `outside`'s test of its clauses. + fn views() -> outside::Views { + outside::Views { all: 3713, kinds: [3500, 100, 0, 113, 0], no_address: 12, shapeless_buffers: [110, 104], pages: Some((412, false)), by_address: [7, 2, 0], heap: Some((52, 3, 31, false)) } + } + + /// The `GPU work so far` line as run 65's tools read it: every field in its place, and 0022's + /// start – what run64_events.sh and E's status match, and the `XCL_SKIP_CS` that keeps the + /// line out of the events – unchanged before the new clauses. + #[test] + fn the_gpu_work_line_keeps_the_prefix_the_run_scripts_read() { + let lists = Ok(([[16, 0, 300, 13], [6, 0, 26, 0]], [[3, 0, 38, 0], [1, 0, 9, 0]])); + let line = work_line([329, 329, 4], lists, &views(), 5); + assert_eq!( + line, + "GPU work so far: 329 translated compute ExecuteIndirect (329 with their group counts checked), 4 dispatches not recorded (XCL_SKIP_CS); ExecuteIndirect recorded / in lists submitted: compute 329 / 41 (300 / 38 with arguments outside unified memory), draws 32 / 10 (26 / 9 outside); views given an empty descriptor: 3713 (outside unified memory: 3500 buffer SRVs, 100 buffer UAVs, 0 CBVs, 12 of them of no title address – they name 412 pages of 64 KiB; shapes XCL cannot describe: 113 SRVs, 0 UAVs, 110 of them of buffers, 104 of those in unified memory), 5 acceleration structures outside unified memory (an empty BVH descriptor each); views by address: 7 buffers outside unified memory (2 below 4 GiB: read from window 0, written nowhere), 0 textures XCL could not make; buffer V#s new in the heaps at submits: 52 outside unified memory (3 below 4 GiB), their bases on 31 pages of 64 KiB" + ); + // 0022's line with the same figures + let old = format!( + "GPU work so far: {} translated compute ExecuteIndirect ({} with their group counts checked), {} dispatches not recorded (XCL_SKIP_CS); views given an empty descriptor: {} (buffers outside unified memory, shapes XCL cannot describe), {} acceleration structures outside unified memory (an empty BVH descriptor each)", + 329, 329, 4, 3713, 5 + ); + let to = |s: &str, end: &str| s[..s.find(end).unwrap() + end.len()].to_string(); + assert_eq!(to(&line, "(329 with"), to(&old, "(329 with"), "the start the run scripts read"); + assert_eq!(to(&line, "(XCL_SKIP_CS); "), to(&old, "(XCL_SKIP_CS); "), "0022's fields before the new ones"); + let off = work_line([329, 329, 4], Err("XCL_INDIRECT_SUBMITTED=0"), &views(), 5); + assert!(off.contains("; ExecuteIndirect recorded / in lists submitted: not counted (XCL_INDIRECT_SUBMITTED=0); views given"), "{off}"); + let none = work_line([329, 329, 4], lists, &outside::Views { heap: None, ..views() }, 5); + assert!(none.ends_with("textures XCL could not make"), "{none}"); + } + + /// "Recorded" is what entered a list – the census's ExecuteIndirect checked first or sent as + /// they were, not those that failed or that XCL_INDIRECT_OWN=skip kept back – the same event the + /// lists count for their submissions; either half not counted says which switch, on the line + /// too. + #[test] + fn recorded_is_what_entered_a_list() { + use indirect::Fate; + let mut c = indirect::CensusSnapshot::default(); + for k in 0..2 { + for p in 0..4 { + let unit = (1 + p + 4 * k) as u64; + c.n[k][p][Fate::AsIs as usize] = unit; + c.n[k][p][Fate::Checked as usize] = 10 * unit; + c.n[k][p][Fate::SkippedOwn as usize] = 100 * unit; + c.n[k][p][Fate::Failed as usize] = 1000 * unit; + } + } + let submitted = [[1, 2, 3, 4], [5, 6, 7, 8]]; + let recorded: [[u64; 4]; 2] = std::array::from_fn(|k| std::array::from_fn(|p| 11 * (1 + p + 4 * k) as u64)); + assert_eq!(indirect_lists(Some(&c), Ok(submitted)), Ok((recorded, submitted)), "checked and as they were, by kind and place"); + assert_eq!(indirect_lists(None, Ok(submitted)), Err("XCL_INDIRECT_CENSUS=0")); + assert_eq!(indirect_lists(Some(&c), Err("XCL_INDIRECT_SUBMITTED=0")), Err("XCL_INDIRECT_SUBMITTED=0")); + // the line of this process: the switch that keeps a half from being counted + let line = gpu_work_line(); + let why = if !indirect::census_on() { + Some("XCL_INDIRECT_CENSUS=0") + } else if !stall::on() { + Some("XCL_GPU_STALL_WATCH=0") + } else if !stall::indirect_on() { + Some("XCL_INDIRECT_SUBMITTED=0") + } else { + None + }; + match why { + Some(w) => assert!(line.contains(&format!("; ExecuteIndirect recorded / in lists submitted: not counted ({w}); ")), "{line}"), + None => assert!(line.contains("; ExecuteIndirect recorded / in lists submitted: compute "), "{line}"), + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/outside.rs b/crates/xcl/src/hle/d3d12x/outside.rs new file mode 100644 index 0000000..ba47f68 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/outside.rs @@ -0,0 +1,1035 @@ +//! Title memory outside unified memory: what XCL counts of it (diagnostics – nothing here +//! changes what the GPU is given). +//! +//! Translated programs reach title memory through unified memory only (`gpu::uma`'s windows): +//! a view of memory outside them gets an empty descriptor, an ExecuteIndirect reads its +//! arguments from a PC resource no translated program writes, a buffer the title places there +//! gets a PC resource of its own (`device_x::create_placed_resource_x`), and a buffer V# the title +//! writes into a heap itself reads 0 there – below 4 GiB, window 0's bytes – and writes nowhere. +//! Counted here, for the `GPU work so far` line: the empty views by kind (`note_empty_view`), views +//! by address of buffers outside the windows and of textures XCL could not make +//! (`note_view_by_address`, `note_no_texture`), buffer V#s found new in the heaps at a submit +//! (`HeapVs`); for the `[indirect]` lines, where an ExecuteIndirect's arguments are in title memory +//! (`args_at`); every 30 s, the buffers the title placed outside the windows (`note_placed`, +//! `census_line`). The tables – the pages views and V#s name, the census, kernelx's record of +//! GPU-visible title memory outside the windows (`kernelx::plain_gpu_at`) – and the heap V# counts +//! are kept with `XCL_ACTIVITY` only (`XCL_OUTSIDE_CENSUS=0`: not even then); the other counts +//! are atomics. + +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +// ---- the switch ------------------------------------------------------------------------------- + +/// The tables are kept: `XCL_ACTIVITY` set and `XCL_OUTSIDE_CENSUS` not `0`. +fn census_on(activity: bool, census: Option<&str>) -> bool { + activity && census.map_or(true, |v| v.trim() != "0") +} + +/// Whether the tables are kept (read once; `host_main` reads it before the title runs – kernelx +/// asks from inside the title's VirtualAlloc, where reading the environment would change the +/// title's last error). +pub(crate) fn on() -> bool { + #[cfg(test)] + if let Some(v) = TEST_ON.with(|c| c.get()) { + return v; + } + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| census_on(std::env::var_os("XCL_ACTIVITY").is_some(), std::env::var("XCL_OUTSIDE_CENSUS").ok().as_deref())) +} + +// ---- views given an empty descriptor ----------------------------------------------------------- + +/// A view given an empty descriptor (its index in the counts). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum EmptyView { + /// a buffer SRV of a buffer outside unified memory (no view mirror) + BufferSrv = 0, + /// a buffer UAV of one + BufferUav = 1, + /// a CBV of memory outside unified memory + Cbv = 2, + /// an SRV of a shape XCL cannot describe (`real::view_shape`: a NULL desc of a buffer, a + /// dimension it does not know) + SrvShape = 3, + /// a UAV of one + UavShape = 4, +} + +/// views given an empty descriptor: all of them, by `EmptyView` +static EMPTY: AtomicU64 = AtomicU64::new(0); +static KINDS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +/// buffer views and CBVs of no title address (a committed PC buffer, a null CBV) +static NO_ADDRESS: AtomicU64 = AtomicU64::new(0); +/// shapeless views of buffers, those of them whose buffer is in unified memory +static SHAPELESS_BUFFERS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +/// views by address (#70 / #71): of buffers outside unified memory, those below 4 GiB, of +/// textures XCL could not make +static BY_ADDRESS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +/// buffer V#s found new in the heaps at a submit outside unified memory, those below 4 GiB +/// (with `on`) +static HEAP_VS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// 64 KiB pages of title memory (with `on`). +#[derive(Default)] +struct Pages { + set: HashSet, + /// pages were left out: the table is full + full: bool, +} + +/// pages a table keeps (4 GiB of title memory), pages of one view (256 MiB) +const PAGES_MAX: usize = 1 << 16; +const VIEW_PAGES_MAX: u64 = 1 << 12; + +/// the pages empty views name; the pages buffer V#s new in the heaps have their bases on +static PAGES: Mutex> = Mutex::new(None); +static HEAP_PAGES: Mutex> = Mutex::new(None); + +impl Pages { + /// Page `p` (false: the table is full and does not hold it). + fn add_page(&mut self, p: u64) -> bool { + if self.set.len() >= PAGES_MAX && !self.set.contains(&p) { + self.full = true; + return false; + } + self.set.insert(p); + true + } + + /// The pages of `[va, va + bytes)` – its first `VIEW_PAGES_MAX` (no bytes: the first). + fn add(&mut self, va: usize, bytes: u64) { + let first = va as u64 >> 16; + let last = (va as u64).saturating_add(bytes.max(1) - 1) >> 16; + for p in first..=last.min(first + VIEW_PAGES_MAX - 1) { + if !self.add_page(p) { + return; + } + } + } +} + +/// A view given an empty descriptor (`real::buffer_view`, `real::cbv_view`, +/// `real::shape_or_count`): its kind; a buffer view's or CBV's title memory (None: no title +/// address); a shapeless view's resource when it is a buffer: whether that buffer is in unified +/// memory (None: not a buffer). +pub(super) fn note_empty_view(kind: EmptyView, at: Option<(usize, u64)>, buffer: Option) { + if EMPTY.fetch_add(1, Ordering::Relaxed) == 0 { + // (`real::note_buffer_view`'s line, word for word: LOG:467) + crate::xlog_warn!("buffer view in the console heap: the buffer is not in UMA – the shader gets an empty V# (num_records 0)"); + } + KINDS[kind as usize].fetch_add(1, Ordering::Relaxed); + match kind { + EmptyView::SrvShape | EmptyView::UavShape => { + if let Some(in_uma) = buffer { + SHAPELESS_BUFFERS[0].fetch_add(1, Ordering::Relaxed); + if in_uma { + SHAPELESS_BUFFERS[1].fetch_add(1, Ordering::Relaxed); + } + } + } + _ => match at { + Some((va, bytes)) if va != 0 => { + if on() { + PAGES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(Pages::default).add(va, bytes); + } + } + _ => { + NO_ADDRESS.fetch_add(1, Ordering::Relaxed); + } + }, + } + #[cfg(test)] + NOTED.with(|n| n.borrow_mut().push(Noted::Empty(kind, at, buffer))); +} + +/// A buffer view by address (`real::buffer_words_at`) of the buffer at `va`, its V# at `base`: +/// counted when that is outside unified memory (a null view – `va` 0 – is not). +pub(super) fn note_view_by_address(va: u64, base: u64) { + if va == 0 || crate::gpu::uma::get().is_some_and(|u| u.contains(base as usize)) { + return; + } + BY_ADDRESS[0].fetch_add(1, Ordering::Relaxed); + if base < 1 << 32 { + BY_ADDRESS[1].fetch_add(1, Ordering::Relaxed); + } + #[cfg(test)] + NOTED.with(|n| n.borrow_mut().push(Noted::ByAddress(base))); +} + +/// A texture view by address (#70 / #71) whose texture XCL could not make (`real::resource_at` +/// gave none): its slot gets an empty descriptor. +pub(super) fn note_no_texture() { + BY_ADDRESS[2].fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + NOTED.with(|n| n.borrow_mut().push(Noted::NoTexture)); +} + +/// Views given an empty descriptor so far (`real::outside_uma_views`). +pub(super) fn empty_views() -> u64 { + EMPTY.load(Ordering::Relaxed) +} + +// ---- buffer V#s found new in the descriptor heaps ---------------------------------------------- + +/// pages one submit notes at most (more are counted only) +const HEAP_PAGES_PER_SUBMIT: usize = 4096; + +/// Buffer V#s found new in the descriptor heaps at a submit (`console_heap::resync_title_writes`: +/// slots whose words changed since the last – the title's own writes and copies, and XCL's views +/// by address, whose slots `console_heap::write` fills without telling the resync) whose base is +/// outside unified memory: counted, and the 64 KiB pages of their bases noted once the heaps' +/// locks are let go (`flush`). With `on` only; a changed slot is counted once, whoever wrote it. +pub(super) struct HeapVs { + on: bool, + uma: Option<&'static crate::gpu::uma::Uma>, + n: u64, + low: u64, + pages: Vec, +} + +impl HeapVs { + pub(super) fn new() -> HeapVs { + HeapVs { on: on(), uma: crate::gpu::uma::get(), n: 0, low: 0, pages: Vec::new() } + } + + /// A slot found changed: its 8 words. + pub(super) fn look(&mut self, w: &[u32]) { + // a buffer V# (images: 8 and up in word 3's top bits), not a null one, outside the windows – + // and not XCL's BVH SRSRC (`desc::bvh_words`: word 3 is 0 on purpose, word 2 all ones, its + // base in 256-byte units – not a buffer V#: read as one, an acceleration structure in + // unified memory would count as a V# outside it below 4 GiB) + if w[3] >> 28 >= 8 || (w[3] == 0 && w[2] == u32::MAX) { + return; + } + let base = w[0] as u64 | ((w[1] & 0xFFFF) as u64) << 32; + if base == 0 || self.uma.is_some_and(|u| u.contains(base as usize)) { + return; + } + #[cfg(test)] + { + let mut g = TEST_SEEN.lock().unwrap_or_else(|e| e.into_inner()); + *g.get_or_insert_with(HashMap::new).entry(base).or_default() += 1; + } + if !self.on { + return; + } + self.n += 1; + if base < 1 << 32 { + self.low += 1; + } + if self.pages.len() < HEAP_PAGES_PER_SUBMIT { + self.pages.push(base >> 16); + } + } + + /// The counts, and the pages noted (after the heaps' locks: a leaf lock of its own). + pub(super) fn flush(mut self) { + if self.n == 0 { + return; + } + HEAP_VS[0].fetch_add(self.n, Ordering::Relaxed); + HEAP_VS[1].fetch_add(self.low, Ordering::Relaxed); + self.pages.sort_unstable(); + self.pages.dedup(); + let mut g = HEAP_PAGES.lock().unwrap_or_else(|e| e.into_inner()); + let t = g.get_or_insert_with(Pages::default); + for &p in &self.pages { + t.add_page(p); + } + } +} + +// ---- the figures of the `GPU work so far` line ------------------------------------------------- + +/// The views counted so far. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct Views { + pub(super) all: u64, + /// by `EmptyView` + pub(super) kinds: [u64; 5], + pub(super) no_address: u64, + /// shapeless views of buffers, those of them in unified memory + pub(super) shapeless_buffers: [u64; 2], + /// distinct pages the views outside unified memory name, the table full (None: not kept) + pub(super) pages: Option<(usize, bool)>, + /// views by address: of buffers outside unified memory, those below 4 GiB, of textures XCL + /// could not make + pub(super) by_address: [u64; 3], + /// buffer V#s new in the heaps at submits outside unified memory, those below 4 GiB, the + /// pages of their bases, the table full (None: not counted) + pub(super) heap: Option<(u64, u64, usize, bool)>, +} + +pub(super) fn views() -> Views { + let l = |a: &AtomicU64| a.load(Ordering::Relaxed); + let len = |t: &Mutex>| t.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map_or((0, false), |p| (p.set.len(), p.full)); + let kept = on(); + Views { + all: l(&EMPTY), + kinds: std::array::from_fn(|k| l(&KINDS[k])), + no_address: l(&NO_ADDRESS), + shapeless_buffers: [l(&SHAPELESS_BUFFERS[0]), l(&SHAPELESS_BUFFERS[1])], + pages: kept.then(|| len(&PAGES)), + by_address: std::array::from_fn(|k| l(&BY_ADDRESS[k])), + heap: kept.then(|| { + let (p, full) = len(&HEAP_PAGES); + (l(&HEAP_VS[0]), l(&HEAP_VS[1]), p, full) + }), + } +} + +impl Views { + /// "3713 (outside unified memory: 3500 buffer SRVs, 100 buffer UAVs, 0 CBVs, 12 of them of no + /// title address – they name 412 pages of 64 KiB; shapes XCL cannot describe: 113 SRVs, 0 + /// UAVs, 110 of them of buffers, 104 of those in unified memory)"; the pages left out when not + /// kept, "65536+" when the table is full. + pub(super) fn empty_clause(&self) -> String { + let k = &self.kinds; + let pages = match self.pages { + Some((n, full)) => format!(" – they name {n}{} pages of 64 KiB", if full { "+" } else { "" }), + None => String::new(), + }; + format!( + "{} (outside unified memory: {} buffer SRVs, {} buffer UAVs, {} CBVs, {} of them of no title address{pages}; shapes XCL cannot describe: {} SRVs, {} UAVs, {} of them of buffers, {} of those in unified memory)", + self.all, k[0], k[1], k[2], self.no_address, k[3], k[4], self.shapeless_buffers[0], self.shapeless_buffers[1] + ) + } + + /// "views by address: 7 buffers outside unified memory (2 below 4 GiB: read from window 0, + /// written nowhere), 0 textures XCL could not make" + pub(super) fn by_address_clause(&self) -> String { + let b = &self.by_address; + format!("views by address: {} buffers outside unified memory ({} below 4 GiB: read from window 0, written nowhere), {} textures XCL could not make", b[0], b[1], b[2]) + } + + /// "buffer V#s new in the heaps at submits: 52 outside unified memory (3 below 4 GiB), their + /// bases on 31 pages of 64 KiB" (None: not counted) + pub(super) fn heap_clause(&self) -> Option { + let (n, low, pages, full) = self.heap?; + Some(format!( + "buffer V#s new in the heaps at submits: {n} outside unified memory ({low} below 4 GiB), their bases on {pages}{} pages of 64 KiB", + if full { "+" } else { "" } + )) + } +} + +// ---- where an ExecuteIndirect's arguments are -------------------------------------------------- + +/// `[indirect]`'s address part: where the title's arguments at its offset `off` of `res` are in +/// title memory, and its count (`count`: resource, the title's offset; resource 0: none) – +/// ", at 0x… (0x… into a buffer of N bytes at 0x…[, in GPU-visible title memory at 0x… of M MB | +/// , in no GPU-visible title memory XCL knows])" or ", at no title address (0x… into …)", then +/// ", count at 0x…" / ", count at no title address". Empty for no resource. No ';' in it: readers +/// split the line's end at "; ". `res` is the title's resource – never XCL's checked copy of its +/// arguments – alive for the call it came with. +pub(super) unsafe fn args_at(res: usize, off: u64, count: (usize, u64)) -> String { + if res == 0 { + return String::new(); + } + let mut s = match super::real::title_address(res) { + Some(base) => { + let at = base.saturating_add(off as usize); + format!(", at {at:#x} ({off:#x} into {} at {base:#x}{})", size_text(res), alloc_text(at)) + } + None => format!(", at no title address ({off:#x} into {})", size_text(res)), + }; + if count.0 != 0 { + match super::real::title_address(count.0) { + Some(b) => s.push_str(&format!(", count at {:#x}", b.saturating_add(count.1 as usize))), + None => s.push_str(", count at no title address"), + } + } + s +} + +/// "a buffer of N bytes" (its console size: a buffer placed below its address – `buffer_delta` – +/// without the bytes before it), "a resource of dimension D", "a resource". +unsafe fn size_text(res: usize) -> String { + if let Some((_, n)) = super::real::console_buffer(res) { + return format!("a buffer of {n} bytes"); + } + let raw = res as *mut c_void; + match ID3D12Resource::from_raw_borrowed(&raw).map(|r| r.GetDesc()) { + Some(d) if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER => format!("a buffer of {} bytes", d.Width.saturating_sub(super::real::buffer_delta(res))), + Some(d) => format!("a resource of dimension {}", d.Dimension.0), + None => "a resource".into(), + } +} + +/// ", in GPU-visible title memory at 0x… of M MB" (kernelx's record, with `on`), ", in no +/// GPU-visible title memory XCL knows", or nothing (in unified memory, or no record kept). +fn alloc_text(at: usize) -> String { + if !on() || crate::gpu::uma::get().is_some_and(|u| u.contains(at)) { + return String::new(); + } + match crate::hle::kernelx::plain_gpu_at(at) { + Some((base, bytes)) => format!(", in GPU-visible title memory at {base:#x} of {} MB", bytes >> 20), + None => ", in no GPU-visible title memory XCL knows".into(), + } +} + +// ---- the census of placed buffers outside unified memory --------------------------------------- + +/// A buffer the title placed at its own address that got a PC resource of its own. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Placed { + va: usize, + bytes: u64, + /// ALLOW_UNORDERED_ACCESS (0x4) + uav: bool, + /// a window it lies in nonetheless (`real::place_at_title_address` did not place it there) + window: Option, + /// the GPU-visible title memory outside the windows it lies in (`kernelx::plain_gpu_at`) + alloc: Option<(usize, usize)>, +} + +/// entries the census keeps (some 6 MB at most) +const CENSUS_MAX: usize = 1 << 16; + +/// The live entries in one GPU-visible allocation (`Census::groups`). +#[derive(Clone, Copy, Debug, Default)] +struct Group { + n: u64, + bytes: u64, + /// the allocation's size + alloc_bytes: usize, +} + +/// The entries and their running sums: a note or a release changes them in O(log n), a line is +/// made in O(allocations) – the lock is never held for long (`forget` takes it on any thread). +struct Census { + live: HashMap, + /// (bytes, resource) of the live entries: the largest is the last + by_size: BTreeSet<(u64, usize)>, + /// (address, resource) of the live entries (`placed_at`) + by_va: BTreeSet<(usize, usize)>, + max: usize, + /// sums of the live entries: bytes, those for unordered access (count, bytes), those in a window + bytes: u64, + uav: (u64, u64), + windowed: u64, + /// those outside the windows by the GPU-visible allocation they lie in (None: none XCL knows) + groups: HashMap, Group>, + made: u64, + made_bytes: u64, + /// made when the census was full (not kept) + dropped: u64, + /// changes so far, and how many there were at the last line + gen: u64, + logged: u64, +} + +impl Census { + fn new(max: usize) -> Census { + Census { + live: HashMap::new(), + by_size: BTreeSet::new(), + by_va: BTreeSet::new(), + max, + bytes: 0, + uav: (0, 0), + windowed: 0, + groups: HashMap::new(), + made: 0, + made_bytes: 0, + dropped: 0, + gen: 0, + logged: 0, + } + } + + fn add(&mut self, res: usize, p: Placed) { + self.live.insert(res, p); + self.by_size.insert((p.bytes, res)); + self.by_va.insert((p.va, res)); + self.bytes += p.bytes; + if p.uav { + self.uav.0 += 1; + self.uav.1 += p.bytes; + } + if p.window.is_some() { + self.windowed += 1; + } else { + let g = self.groups.entry(p.alloc.map(|a| a.0)).or_default(); + g.n += 1; + g.bytes += p.bytes; + g.alloc_bytes = p.alloc.map_or(0, |a| a.1); + } + } + + fn sub(&mut self, res: usize, p: &Placed) { + self.by_size.remove(&(p.bytes, res)); + self.by_va.remove(&(p.va, res)); + self.bytes -= p.bytes; + if p.uav { + self.uav.0 -= 1; + self.uav.1 -= p.bytes; + } + if p.window.is_some() { + self.windowed -= 1; + } else { + let key = p.alloc.map(|a| a.0); + if let Some(g) = self.groups.get_mut(&key) { + g.n -= 1; + g.bytes -= p.bytes; + if g.n == 0 { + self.groups.remove(&key); + } + } + } + } + + fn note(&mut self, res: usize, p: Placed) { + self.made += 1; + self.made_bytes += p.bytes; + self.gen += 1; + // (a resource address used again before its end was seen: the newer one) + if let Some(old) = self.live.remove(&res) { + self.sub(res, &old); + } + if self.live.len() >= self.max { + self.dropped += 1; + return; + } + self.add(res, p); + } + + fn forget(&mut self, res: usize) -> bool { + let Some(p) = self.live.remove(&res) else { return false }; + self.sub(res, &p); + self.gen += 1; + true + } + + /// The census as a line when it changed since the last one (None: no change, none made). + fn line(&mut self) -> Option { + if self.made == 0 || self.gen == self.logged { + return None; + } + self.logged = self.gen; + let mb = |b: u64| b >> 20; + let largest = self.by_size.last().and_then(|&(_, r)| self.live.get(&r)); + let mut parts = vec![format!( + "D3D12.X: placed buffers with a PC resource of their own: {} now ({} MB summed{})", + self.live.len(), + mb(self.bytes), + largest.map_or(String::new(), |l| format!(", the largest {} KB at {:#x}", l.bytes >> 10, l.va)) + )]; + parts.push(format!("{} of them for unordered access ({} MB)", self.uav.0, mb(self.uav.1))); + parts.push(format!("{} made so far ({} MB)", self.made, mb(self.made_bytes))); + let mut groups: Vec<(usize, Group)> = self.groups.iter().filter_map(|(k, g)| k.map(|b| (b, *g))).collect(); + groups.sort_by(|a, b| b.1.bytes.cmp(&a.1.bytes).then(a.0.cmp(&b.0))); + for &(base, g) in groups.iter().take(4) { + parts.push(format!("in GPU-visible title memory at {base:#x} ({} MB): {} ({} MB)", g.alloc_bytes >> 20, g.n, mb(g.bytes))); + } + if groups.len() > 4 { + let (n, b) = groups[4..].iter().fold((0, 0), |s, g| (s.0 + g.1.n, s.1 + g.1.bytes)); + parts.push(format!("in {} more GPU-visible allocations: {n} ({} MB)", groups.len() - 4, mb(b))); + } + if let Some(g) = self.groups.get(&None) { + parts.push(format!("outside the GPU-visible allocations XCL knows: {} ({} MB)", g.n, mb(g.bytes))); + } + if self.windowed > 0 { + parts.push(format!("in a window but not placed there: {}", self.windowed)); + } + if self.dropped > 0 { + parts.push(format!("{} not kept (the census is full)", self.dropped)); + } + Some(parts.join("; ")) + } +} + +static CENSUS: Mutex> = Mutex::new(None); +/// entries in the census (a release looks at its lock only while there are some) +static LIVE: AtomicUsize = AtomicUsize::new(0); + +/// The title placed a buffer (`d`: the PC's desc – width at 0x10, flags at 0x30) at `va` and it +/// got a PC resource of its own, `res` (`device_x::create_placed_resource_x`, with `on`). +pub(super) fn note_placed(res: usize, va: usize, d: &[u8; 0x38]) { + if !on() || res == 0 { + return; + } + let bytes = u64::from_le_bytes(d[0x10..0x18].try_into().unwrap()); + let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); + let window = crate::gpu::uma::get().and_then(|u| u.window_of(va)).map(|k| k as u8); + // (before the census's lock: kernelx's is a leaf of its own) + let alloc = crate::hle::kernelx::plain_gpu_at(va); + let p = Placed { va, bytes, uav: flags & 0x4 != 0, window, alloc }; + let mut g = CENSUS.lock().unwrap_or_else(|e| e.into_inner()); + let c = g.get_or_insert_with(|| Census::new(CENSUS_MAX)); + c.note(res, p); + LIVE.store(c.live.len(), Ordering::Release); +} + +/// `res`, a resource the title placed, is gone (`real::forget_resource`: any thread – a release +/// of D3DMetal's too; the lock is held for an O(log n) change). +pub(super) fn forget(res: usize) { + if LIVE.load(Ordering::Acquire) == 0 { + return; + } + let mut g = CENSUS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(c) = g.as_mut() { + if c.forget(res) { + LIVE.store(c.live.len(), Ordering::Release); + } + } +} + +/// The buffer the title placed outside the windows with a PC resource of its own that `va` lies in +/// (the census, with `on`): (resource, its address, bytes, for unordered access). The 64 nearest +/// entries at or below `va` are looked at – buffers that hold one another are rare. For +/// `XCL_SKIP_CS`'s root views (`skip_roots`); the lock is held for the look only. +pub(super) fn placed_at(va: usize) -> Option<(usize, usize, u64, bool)> { + if LIVE.load(Ordering::Acquire) == 0 { + return None; + } + let g = CENSUS.lock().unwrap_or_else(|e| e.into_inner()); + let c = g.as_ref()?; + c.by_va + .range(..=(va, usize::MAX)) + .rev() + .take(64) + .filter_map(|&(at, res)| c.live.get(&res).map(|p| (res, at, p))) + .find(|&(_, at, p)| u64::try_from(va - at).is_ok_and(|off| off < p.bytes)) + .map(|(res, at, p)| (res, at, p.bytes, p.uav)) +} + +/// (`XCL_ACTIVITY`, every 30 s) the census, when it changed since the last line. +pub(super) fn census_line() -> Option { + if !on() { + return None; + } + CENSUS.lock().unwrap_or_else(|e| e.into_inner()).as_mut()?.line() +} + +// ---- tests' hooks ------------------------------------------------------------------------------- + +#[cfg(test)] +thread_local! { + /// `on` for this test thread (None: as the environment says) + static TEST_ON: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// what this thread noted (`take_noted_for_test`) + static NOTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Noted { + Empty(EmptyView, Option<(usize, u64)>, Option), + ByAddress(u64), + NoTexture, +} + +#[cfg(test)] +pub(super) fn take_noted_for_test() -> Vec { + NOTED.with(|n| std::mem::take(&mut *n.borrow_mut())) +} + +/// `on` for this thread until dropped +#[cfg(test)] +pub(crate) struct TestOn(Option); + +#[cfg(test)] +impl Drop for TestOn { + fn drop(&mut self) { + TEST_ON.with(|c| c.set(self.0)); + } +} + +#[cfg(test)] +pub(crate) fn test_on(on: bool) -> TestOn { + TestOn(TEST_ON.with(|c| c.replace(Some(on)))) +} + +/// D's tests that touch the census, kernelx's record or the heap V# counts: one at a time +#[cfg(test)] +pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(()); + +/// buffer V#s outside unified memory each changed slot showed `HeapVs::look`, whatever `on` says +/// (any thread's resync – they are one at a time under the heaps' lock) +#[cfg(test)] +static TEST_SEEN: Mutex>> = Mutex::new(None); + +#[cfg(test)] +pub(super) fn heap_seen_for_test(base: u64) -> u32 { + TEST_SEEN.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(&base).copied()).unwrap_or(0) +} + +/// `base` seen no more (before its test lets the memory go: a later test's reservation may get +/// the same address) +#[cfg(test)] +pub(super) fn forget_heap_seen_for_test(base: u64) { + if let Some(m) = TEST_SEEN.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + m.remove(&base); + } +} + +#[cfg(test)] +impl HeapVs { + pub(super) fn for_test(on: bool) -> HeapVs { + HeapVs { on, uma: crate::gpu::uma::get(), n: 0, low: 0, pages: Vec::new() } + } +} + +#[cfg(test)] +pub(super) fn heap_page_kept_for_test(page: u64) -> bool { + HEAP_PAGES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|p| p.set.contains(&page)) +} + +/// a census entry for `res` whatever `on` says +#[cfg(test)] +pub(super) fn note_for_test(res: usize, va: usize, bytes: u64) { + let mut g = CENSUS.lock().unwrap_or_else(|e| e.into_inner()); + let c = g.get_or_insert_with(|| Census::new(CENSUS_MAX)); + c.note(res, Placed { va, bytes, uav: false, window: None, alloc: None }); + LIVE.store(c.live.len(), Ordering::Release); +} + +#[cfg(test)] +pub(super) fn in_census_for_test(res: usize) -> bool { + CENSUS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|c| c.live.contains_key(&res)) +} + +/// (va, bytes, uav, window, allocation) of `res`'s entry +#[cfg(test)] +pub(super) fn census_entry_for_test(res: usize) -> Option<(usize, u64, bool, Option, Option<(usize, usize)>)> { + CENSUS.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.live.get(&res).map(|p| (p.va, p.bytes, p.uav, p.window, p.alloc)) +} + +#[cfg(test)] +mod tests { + use super::super::real; + use super::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS}; + + /// MEM_TOP_DOWN (windows-sys has no name for it) + const MEM_TOP_DOWN: u32 = 0x10_0000; + + /// A fresh reservation of `bytes` (never in a window: plain address space Windows gives). + unsafe fn reserve(bytes: usize, top_down: bool) -> usize { + let p = VirtualAlloc(std::ptr::null(), bytes, MEM_RESERVE | if top_down { MEM_TOP_DOWN } else { 0 }, PAGE_NOACCESS) as usize; + assert_ne!(p, 0, "a reservation of {bytes:#x} bytes"); + p + } + + unsafe fn release(p: usize) { + VirtualFree(p as *mut c_void, 0, MEM_RELEASE); + } + + /// The first window longer than `room` bytes: (its index, its base). + fn a_window(u: &crate::gpu::uma::Uma, room: usize) -> Option<(usize, usize)> { + (0..u.windows()).map(|k| (k, u.window(k))).find(|&(_, (_, len))| len > room).map(|(k, (base, _))| (k, base)) + } + + /// The pages empty views name are a set, each view's first `VIEW_PAGES_MAX` of them, its end + /// not in it; a table of `PAGES_MAX` pages says it is full and takes no new one. + #[test] + fn empty_views_name_their_pages_once_within_caps() { + let mut p = Pages::default(); + p.add(0x1_9532_2600, 2 << 20); + assert_eq!(p.set.len(), 33, "a 2 MiB view"); + p.add(0x1_9532_2600, 2 << 20); + assert_eq!(p.set.len(), 33, "the same view again"); + p.add(0x1_9533_0000, 4); + assert_eq!(p.set.len(), 33, "a view on one of its pages"); + p.add(0x2_0000_0000, 0x1_0000); + assert_eq!(p.set.len(), 34, "a view ending on a page boundary names one page"); + p.add(0x1_0000_0000, 4 << 30); + assert_eq!(p.set.len(), 34 + VIEW_PAGES_MAX as usize, "a view's first VIEW_PAGES_MAX pages"); + p.add(0x3_0000_0000, 0); + assert_eq!(p.set.len(), 35 + VIEW_PAGES_MAX as usize, "a view of no bytes names its first page"); + assert!(!p.full); + let mut page = 0x100_0000u64; + while p.set.len() < PAGES_MAX { + assert!(p.add_page(page)); + page += 1; + } + assert!(!p.full, "full only once a page is left out"); + assert!(!p.add_page(page), "a new page of a full table"); + assert!(p.full && p.set.len() == PAGES_MAX, "full, {} pages", p.set.len()); + assert!(p.add_page(0x19532), "a page it holds"); + p.add(0x7_0000_0000, 1 << 20); + assert_eq!(p.set.len(), PAGES_MAX, "a view of new pages adds none"); + } + + /// The clauses of the `GPU work so far` line read as their counts (run 65's tools parse them). + #[test] + fn the_views_clause_reads_as_its_counts() { + let v = Views { all: 3713, kinds: [3500, 100, 0, 113, 0], no_address: 12, shapeless_buffers: [110, 104], pages: Some((412, false)), by_address: [7, 2, 0], heap: Some((52, 3, 31, false)) }; + assert_eq!( + v.empty_clause(), + "3713 (outside unified memory: 3500 buffer SRVs, 100 buffer UAVs, 0 CBVs, 12 of them of no title address – they name 412 pages of 64 KiB; shapes XCL cannot describe: 113 SRVs, 0 UAVs, 110 of them of buffers, 104 of those in unified memory)" + ); + assert_eq!( + Views { pages: Some((65536, true)), ..v }.empty_clause(), + "3713 (outside unified memory: 3500 buffer SRVs, 100 buffer UAVs, 0 CBVs, 12 of them of no title address – they name 65536+ pages of 64 KiB; shapes XCL cannot describe: 113 SRVs, 0 UAVs, 110 of them of buffers, 104 of those in unified memory)" + ); + assert_eq!( + Views { pages: None, ..v }.empty_clause(), + "3713 (outside unified memory: 3500 buffer SRVs, 100 buffer UAVs, 0 CBVs, 12 of them of no title address; shapes XCL cannot describe: 113 SRVs, 0 UAVs, 110 of them of buffers, 104 of those in unified memory)" + ); + assert_eq!(v.by_address_clause(), "views by address: 7 buffers outside unified memory (2 below 4 GiB: read from window 0, written nowhere), 0 textures XCL could not make"); + assert_eq!(v.heap_clause().as_deref(), Some("buffer V#s new in the heaps at submits: 52 outside unified memory (3 below 4 GiB), their bases on 31 pages of 64 KiB")); + assert_eq!(Views { heap: None, ..v }.heap_clause(), None); + assert_eq!( + Views { heap: Some((52, 3, 31, true)), ..v }.heap_clause().as_deref(), + Some("buffer V#s new in the heaps at submits: 52 outside unified memory (3 below 4 GiB), their bases on 31+ pages of 64 KiB") + ); + } + + fn placed(va: usize, bytes: u64, uav: bool, window: Option, alloc: Option<(usize, usize)>) -> Placed { + Placed { va, bytes, uav, window, alloc } + } + + /// The census keeps running sums of the placed buffers alive, by the GPU-visible allocation + /// they lie in (the four largest, the rest summed), the largest one, and says itself only when + /// it changed; a release takes its entry out, an address used again replaces it. + #[test] + fn the_census_counts_placed_buffers_until_they_go() { + let heap = Some((0x1_8009_0000usize, 4usize << 30)); + let mut c = Census::new(CENSUS_MAX); + assert_eq!(c.line(), None, "nothing made"); + c.note(1, placed(0x1_9532_2600, 2 << 20, false, None, heap)); + c.note(2, placed(0x1_921f_e300, 115_200, true, None, heap)); + c.note(3, placed(0x8470_0000, 4096, false, None, None)); + c.note(4, placed(0x5_0000_0000, 64, false, Some(1), None)); + assert_eq!( + c.line().as_deref(), + Some("D3D12.X: placed buffers with a PC resource of their own: 4 now (2 MB summed, the largest 2048 KB at 0x195322600); 1 of them for unordered access (0 MB); 4 made so far (2 MB); in GPU-visible title memory at 0x180090000 (4096 MB): 2 (2 MB); outside the GPU-visible allocations XCL knows: 1 (0 MB); in a window but not placed there: 1") + ); + assert_eq!(c.line(), None, "no change since the last line"); + assert!(c.forget(1)); + assert!(!c.forget(1), "gone already"); + let l = c.line().expect("a line after a release"); + assert!(l.contains(": 3 now (0 MB summed, the largest 112 KB at 0x1921fe300)"), "{l}"); + assert!(l.contains("; 4 made so far (2 MB)"), "{l}"); + assert!(l.contains("in GPU-visible title memory at 0x180090000 (4096 MB): 1 (0 MB)"), "{l}"); + + // six allocations: the four with the most bytes, the rest summed + let mut c = Census::new(CENSUS_MAX); + for k in 0..6usize { + let base = 0x3_0000_0000 + k * 0x1000_0000; + c.note(10 + k, placed(base + 0x1000, (k as u64 + 1) << 20, false, None, Some((base, 0x1000_0000)))); + } + let l = c.line().unwrap(); + let at = |k: usize| l.find(&format!("; in GPU-visible title memory at {:#x} (256 MB): 1 ({} MB)", 0x3_0000_0000usize + k * 0x1000_0000, k + 1)); + let shown: Vec = [5, 4, 3, 2].iter().map(|&k| at(k).unwrap_or_else(|| panic!("allocation {k}: {l}"))).collect(); + assert!(shown.windows(2).all(|w| w[0] < w[1]), "the largest first: {l}"); + assert!(at(1).is_none() && at(0).is_none(), "{l}"); + assert!(l.ends_with("; in 2 more GPU-visible allocations: 2 (3 MB)"), "{l}"); + + // full: what is made past its entries is counted, not kept + let mut c = Census::new(2); + for r in 1..=3usize { + c.note(r, placed(0x4_0000_0000 + r * 0x1000, 64, false, None, None)); + } + let l = c.line().unwrap(); + assert!(l.contains(": 2 now (") && l.contains("; 3 made so far (") && l.ends_with("; 1 not kept (the census is full)"), "{l}"); + + // a resource address used again before its end was seen: the newer entry + let mut c = Census::new(CENSUS_MAX); + c.note(7, placed(0x1_0000_1000, 1 << 20, false, None, Some((0x1_0000_0000, 1 << 30)))); + c.note(7, placed(0x2_0000_1000, 3 << 20, false, None, Some((0x2_0000_0000, 1 << 30)))); + let l = c.line().unwrap(); + assert!(l.contains(": 1 now (3 MB summed, the largest 3072 KB at 0x200001000)"), "{l}"); + assert!(l.contains("; 2 made so far (4 MB)"), "{l}"); + assert!(l.contains("; in GPU-visible title memory at 0x200000000 (1024 MB): 1 (3 MB)") && !l.contains("at 0x100000000 ("), "{l}"); + } + + /// The adapter's device and committed DEFAULT buffers of these sizes on it (None: the test + /// says SKIPPED – no GPU). + unsafe fn default_buffers(sizes: &[u64]) -> Option<(ID3D12Device, Vec)> { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + let dev = dev?; + let mut bufs = Vec::new(); + for &bytes in sizes { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r) + .expect("a DEFAULT buffer"); + bufs.push(r.unwrap()); + } + Some((dev, bufs)) + } + + /// `[indirect]`'s address part: the title's address of the arguments (its console offset and + /// size, not the PC's), the GPU-visible title memory it lies in – or none XCL knows, or no part + /// without the record –, and where the count is. + #[test] + fn indirect_lines_name_where_the_arguments_are() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _on = test_on(true); + unsafe { + let Some((_dev, bufs)) = default_buffers(&[65536, 256]) else { return }; + let (res, cres) = (bufs[0].as_raw() as usize, bufs[1].as_raw() as usize); + if real::console_buffer(res).is_some() || real::console_buffer(cres).is_some() { + return crate::gpu::recomp::runner::skip_config("a buffer of the test's is known as one in unified memory"); + } + // GPU-visible title memory kernelx knows (1 MiB), and memory it does not + let (heap, other) = (reserve(0x10_0000, false), reserve(0x10_0000, false)); + crate::hle::kernelx::note_plain_gpu_for_test(heap, 0x10_0000); + // (what the test set goes, also when an assertion unwinds – before the buffers) + struct Undo(usize, usize, usize, usize); + impl Drop for Undo { + fn drop(&mut self) { + real::set_test_title_address(self.0, None); + real::set_test_title_address(self.1, None); + real::set_test_buffer_delta(self.0, None); + crate::hle::kernelx::forget_plain_gpu_for_test(self.2); + unsafe { + release(self.2); + release(self.3); + } + } + } + let _undo = Undo(res, cres, heap, other); + let base = heap + 0x2_0300; + real::set_test_title_address(res, Some(base)); + real::set_test_title_address(cres, Some(heap + 0x8_0000)); + assert_eq!(args_at(res, 0x40, (0, 0)), format!(", at {:#x} (0x40 into a buffer of 65536 bytes at {base:#x}, in GPU-visible title memory at {heap:#x} of 1 MB)", base + 0x40)); + real::set_test_buffer_delta(res, Some(0x300)); + assert_eq!( + args_at(res, 0x40, (0, 0)), + format!(", at {:#x} (0x40 into a buffer of 64768 bytes at {base:#x}, in GPU-visible title memory at {heap:#x} of 1 MB)", base + 0x40), + "a buffer placed below its address: the console's offset and size" + ); + real::set_test_buffer_delta(res, None); + let s = args_at(res, 0x40, (cres, 8)); + assert!(s.ends_with(&format!("), count at {:#x}", heap + 0x8_0008)), "{s}"); + real::set_test_title_address(cres, None); + let s = args_at(res, 0x40, (cres, 8)); + assert!(s.ends_with("), count at no title address"), "{s}"); + real::set_test_title_address(res, None); + assert_eq!(args_at(res, 0x10, (0, 0)), ", at no title address (0x10 into a buffer of 65536 bytes)"); + let base = other + 0x2_0300; + real::set_test_title_address(res, Some(base)); + assert_eq!(args_at(res, 0x40, (0, 0)), format!(", at {:#x} (0x40 into a buffer of 65536 bytes at {base:#x}, in no GPU-visible title memory XCL knows)", base + 0x40)); + { + let _off = test_on(false); + assert_eq!(args_at(res, 0x40, (0, 0)), format!(", at {:#x} (0x40 into a buffer of 65536 bytes at {base:#x})", base + 0x40), "no record kept: no allocation part"); + } + assert_eq!(args_at(0, 0x40, (cres, 8)), "", "no arguments resource"); + } + } + + /// Buffer V#s new in the heaps are counted when their base is outside unified memory (those + /// below 4 GiB apart) and their pages noted at the flush – images, null V#s and bases in + /// unified memory are not; without `on` nothing is. + #[test] + fn heap_vsharps_are_counted_by_where_their_base_is() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(u) = crate::gpu::uma::get() else { return }; + let Some((_, window)) = a_window(u, 0x20_0000) else { return }; + let inside = (window + 0x10_0000) as u64; + unsafe { + // (top down: an address above 4 GiB) + let out = reserve(0x10_0000, true); + let (a, b) = (out as u64 + 0x100, 0x8470_0100u64); + if a < 1 << 32 || u.contains(b as usize) { + release(out); + return crate::gpu::recomp::runner::skip_config("no reservation above 4 GiB, or a window over 0x84700100"); + } + let v = |base: u64| { + let w = crate::gpu::desc::buffer_words(base, 0, 64, 22); + [w[0], w[1], w[2], w[3], 0, 0, 0, 0] + }; + // a T# of an image at a + 0x2_0000 (its base in 256-byte units) + let t = a + 0x2_0000; + let image = [(t >> 8) as u32, ((t >> 40) & 0xFF) as u32, 0, 9 << 28, 0, 0, 0, 0]; + // XCL's BVH SRSRC of an acceleration structure in unified memory (D-BVH-1): read as a + // buffer V#, its base – the address in 256-byte units – is outside the windows + let bvh = { + let b = crate::gpu::desc::bvh_words(inside, true); + [b[0], b[1], b[2], b[3], 0, 0, 0, 0] + }; + let as_vsharp = bvh[0] as u64 | ((bvh[1] & 0xFFFF) as u64) << 32; + if as_vsharp == 0 || u.contains(as_vsharp as usize) { + release(out); + return crate::gpu::recomp::runner::skip_config("a BVH's words read as a V# of no memory or in a window"); + } + let counts = || (HEAP_VS[0].load(Ordering::Relaxed), HEAP_VS[1].load(Ordering::Relaxed)); + let before = counts(); + let mut h = HeapVs::for_test(true); + for w in [v(a), v(a + 0x40), v(b), v(inside), [0; 8], image, bvh] { + h.look(&w); + } + assert_eq!((h.n, h.low), (3, 1), "a, a + 0x40 and b; b below 4 GiB – not the image, not the BVH"); + h.flush(); + let after = counts(); + assert_eq!((after.0 - before.0, after.1 - before.1), (3, 1)); + assert!(heap_page_kept_for_test(a >> 16) && heap_page_kept_for_test(b >> 16), "the pages of their bases"); + assert!(!heap_page_kept_for_test(t >> 16), "not an image's"); + let mut off = HeapVs::for_test(false); + off.look(&v(a)); + assert_eq!(off.n, 0, "not counted without on"); + off.flush(); + assert_eq!(counts(), after); + for base in [a, a + 0x40, b] { + forget_heap_seen_for_test(base); + } + release(out); + } + } + + /// The census is kept with XCL_ACTIVITY only, and XCL_OUTSIDE_CENSUS=0 turns it off. + #[test] + fn the_census_switch_follows_activity_and_its_own_value() { + assert!(census_on(true, None)); + assert!(!census_on(true, Some("0"))); + assert!(!census_on(true, Some(" 0 "))); + assert!(census_on(true, Some("1"))); + assert!(!census_on(false, None)); + assert!(!census_on(false, Some("1")), "no XCL_ACTIVITY: off whatever it says"); + } + + /// A buffer placed with a PC resource of its own is noted with its size, unordered access, + /// the window it lies in nonetheless and the GPU-visible allocation it lies in – with `on` + /// only. + #[test] + fn a_placed_buffer_is_noted_with_its_size_access_and_allocation() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let heap = reserve(1 << 20, false); + crate::hle::kernelx::note_plain_gpu_for_test(heap, 1 << 20); + let mut d = [0u8; 0x38]; + d[0x10..0x18].copy_from_slice(&4096u64.to_le_bytes()); + d[0x30..0x34].copy_from_slice(&4u32.to_le_bytes()); + let (r, rw, roff) = (0x7D0D_3000usize, 0x7D0D_4000usize, 0x7D0D_3800usize); + { + let _on = test_on(true); + note_placed(r, heap + 0x100, &d); + assert_eq!(census_entry_for_test(r), Some((heap + 0x100, 4096, true, None, Some((heap, 1 << 20))))); + if let Some((k, base)) = crate::gpu::uma::get().and_then(|u| a_window(u, 0x20_0000)) { + note_placed(rw, base + 0x10_0000, &d); + assert_eq!(census_entry_for_test(rw), Some((base + 0x10_0000, 4096, true, Some(k as u8), None)), "in window {k}"); + } + } + { + let _off = test_on(false); + note_placed(roff, heap + 0x200, &d); + assert_eq!(census_entry_for_test(roff), None, "not noted without on"); + } + for res in [r, rw, roff] { + forget(res); + } + assert!(!in_census_for_test(r) && !in_census_for_test(rw)); + crate::hle::kernelx::forget_plain_gpu_for_test(heap); + release(heap); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 744b095..f89b798 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -54,6 +54,8 @@ struct PlaneConfigState { stride: usize, requested_plane: usize, active_plane: usize, + /// planes composed (0: one plane shown) + composed: usize, width: u32, height: u32, format: i32, @@ -61,15 +63,15 @@ struct PlaneConfigState { static LAST_PLANE_CONFIG: Mutex> = Mutex::new(None); -fn requested_plane_index() -> usize { - let request = std::env::var("XCL_PRESENT_PLANE") - .ok() - .and_then(|v| v.trim().parse::().ok()); - usize::from(request == Some(1)) +/// `XCL_PRESENT_PLANE=n`: the plane to show alone; unset or not a number: none (two planes or +/// more are composed – `present_x_frame`). +fn requested_plane_index() -> Option { + std::env::var("XCL_PRESENT_PLANE").ok().and_then(|v| v.trim().parse::().ok()) } +/// The plane shown: the one asked for when the title presents that many, else plane 0. fn selected_plane_index(requested: usize, plane_count: u32) -> usize { - if plane_count >= 2 { requested } else { 0 } + if requested < plane_count as usize { requested } else { 0 } } pub unsafe fn parse_plane(planes: *const u8, plane_index: usize, stride: usize) -> Option<(u64, usize)> { @@ -128,9 +130,11 @@ unsafe fn get_resource_desc(res: usize) -> Result i32 { + let _xcl_api = crate::waitwatch::api("present::present_x"); if plane_count == 0 || planes.is_null() || !crate::gpu::shader::readable(planes as usize, 0x18) { return 0; } @@ -162,10 +166,28 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u if !PRESENTX.swap(true, Ordering::Relaxed) { crate::xlog_info!("D3D12.X: PresentX – the title presents its own frames ({plane_count} plane(s))"); } + { + // a change in the number of planes (the console's display composes them – a UI + // plane over the game's): logged with the planes' raw words + static LAST: AtomicU64 = AtomicU64::new(1); + if LAST.swap(plane_count as u64, Ordering::Relaxed) != plane_count as u64 { + let n = 9 * plane_count as usize; + let words: Vec = if crate::gpu::shader::readable(planes as usize, 8 * n) { (0..n).map(|k| (planes as *const u64).add(k).read_unaligned()).collect() } else { Vec::new() }; + crate::xlog_info!("D3D12.X: PresentX now with {plane_count} plane(s): {words:x?}"); + for i in 0..plane_count.min(4) as usize { + crate::xlog_info!("D3D12.X: PresentX plane {i}: {}", describe_plane(planes.add(i * PLANE_STRIDE))); + } + } + } - let requested_plane = requested_plane_index(); + // `XCL_PRESENT_PLANE=n`: show plane n alone (what each plane holds); otherwise two planes or + // more are composed as the console's display does. A plane asked for that has no resource or + // one a swap chain cannot show falls back to plane 0. + let pick = requested_plane_index(); + let requested_plane = pick.unwrap_or(0); let chosen_plane = selected_plane_index(requested_plane, plane_count); let stride = RETAIL_PLANE_STRIDE; + let composed = if pick.is_none() && plane_count > 1 && enabled() { compose_planes(planes, plane_count) } else { Vec::new() }; let mut tokens = Vec::with_capacity(plane_count as usize); for i in 0..plane_count as usize { @@ -211,6 +233,7 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u stride, requested_plane, active_plane, + composed: composed.len(), width, height, format, @@ -226,7 +249,8 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u }; if config_changed { crate::xlog_info!( - "D3D12.X: PresentX plane configuration change: count={plane_count}, stride={stride}, requested_plane={requested_plane}, active_plane={active_plane}, width={width}, height={height}, format={format}, presentation_enabled={}", + "D3D12.X: PresentX plane configuration change: count={plane_count}, stride={stride}, requested_plane={requested_plane}, active_plane={active_plane}, composed={}, width={width}, height={height}, format={format}, presentation_enabled={}", + composed.len(), enabled() ); for i in 0..plane_count as usize { @@ -266,8 +290,10 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u let res = chosen_res; { let mut p = PRESENTED.lock().unwrap_or_else(|e| e.into_inner()); - if !p.contains(&res) { - p.push(res); + for r in std::iter::once(res).chain(composed.iter().map(|c| c.res.as_raw() as usize)) { + if !p.contains(&r) { + p.push(r); + } } } if trace_frame() { @@ -295,10 +321,89 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u crate::xlog_info!("frame trace: PresentX #{n} plane {active_plane} of {res:#x} {:?} – rt binds {}, UAV views {}, copy destination {}, clears {}; most used: {}", d, u[0], u[1], u[2], u[3], busiest.join("; ")); } } - present_now(Duration::ZERO, Some((queue as usize, res))); + present_now(Duration::ZERO, Some((queue as usize, res)), composed); tokens } +/// The planes of a PresentX to compose (`compose`): each plane's first resource with its source +/// rect and place on the screen, bottom first – none unless two or more can be shown. +unsafe fn compose_planes(planes: *const u8, plane_count: u32) -> Vec { + use super::compose::{destination, source_rect, Plane, MAX_PLANES}; + let readable = |p: usize, n: usize| crate::gpu::shader::readable(p, n); + let mut out = Vec::new(); + for i in 0..(plane_count as usize).min(MAX_PLANES) { + let plane = planes.add(i * PLANE_STRIDE); + if !readable(plane as usize, 0x30) { + continue; + } + let count = (plane.add(8) as *const u32).read_unaligned(); + let list = (plane.add(0x10) as *const usize).read_unaligned(); + if count == 0 || !readable(list, 8) { + continue; + } + let raw = (list as *const usize).read_unaligned() as *mut c_void; + // (upstream's guarded GetDesc: a plane whose object, vtable or GetDesc cannot be read is + // left out – the configuration line says why) + let Ok(d) = get_resource_desc(raw as usize) else { continue }; + let Some(res) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; + if d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || d.SampleDesc.Count != 1 || d.DepthOrArraySize != 1 || swap_format(d.Format).is_none() { + continue; + } + let src = (plane.add(0x18) as *const usize).read_unaligned(); + let dst = (plane.add(0x20) as *const usize).read_unaligned(); + let src = (src != 0 && readable(src, 16)).then(|| (src as *const [i32; 4]).read_unaligned()); + let dst = (dst != 0 && readable(dst, 16)).then(|| (dst as *const [f32; 4]).read_unaligned()); + out.push(Plane { res: res.clone(), src: source_rect(src, d.Width, d.Height as u64), dst: destination(dst) }); + } + if out.len() < 2 { + out.clear(); + } + out +} + +/// Bytes of one PresentX plane as GTA VI lays them out (token, resource count, resources, source +/// rects, destination placement, color space, flags, …) – its two planes sit 0x48 apart. +const PLANE_STRIDE: usize = RETAIL_PLANE_STRIDE; + +/// One plane, for the log: its resources (size, format), source rect, destination placement, +/// color space and flags. +unsafe fn describe_plane(plane: *const u8) -> String { + let read = |p: usize, n: usize| crate::gpu::shader::readable(p, n); + if !read(plane as usize, PLANE_STRIDE) { + return "unreadable".into(); + } + let count = (plane.add(8) as *const u32).read_unaligned(); + let list = (plane.add(0x10) as *const usize).read_unaligned(); + let src = (plane.add(0x18) as *const usize).read_unaligned(); + let dst = (plane.add(0x20) as *const usize).read_unaligned(); + let (space, flags) = ((plane.add(0x28) as *const u32).read_unaligned(), (plane.add(0x2C) as *const u32).read_unaligned()); + let mut out = format!("{count} resource(s)"); + if count > 0 && count <= 8 && read(list, 8 * count as usize) { + for k in 0..count as usize { + let r = (list as *const usize).add(k).read_unaligned(); + if r == 0 { + out += " [none]"; + continue; + } + // (through upstream's guarded GetDesc, as the plane shown alone is read) + match get_resource_desc(r) { + Ok(d) => out += &format!(" [{r:#x} {}x{} format {}]", d.Width, d.Height, d.Format.0), + Err(why) => out += &format!(" [{r:#x}: {why}]"), + } + } + } + if src != 0 && read(src, 16) { + let s = std::slice::from_raw_parts(src as *const i32, 4); + out += &format!("; source rect {s:?}"); + } + if dst != 0 && read(dst, 16) { + let f = std::slice::from_raw_parts(dst as *const f32, 4); + let i = std::slice::from_raw_parts(dst as *const i32, 4); + out += &format!("; destination {f:?} (as integers {i:?})"); + } + out + &format!("; color space {space}, flags {flags:#x}") +} + thread_local! { static IN_PRESENT: Cell = const { Cell::new(false) }; } @@ -312,6 +417,13 @@ pub fn counters() -> (u64, u64) { (PRESENTS.load(Ordering::Relaxed), BOUNDARIES.load(Ordering::Relaxed)) } +/// (tests) A frame boundary as the title's PresentX makes one (`present_x_frame`'s first step): +/// nothing presented. +#[cfg(test)] +pub(crate) fn boundary_for_test() { + BOUNDARIES.fetch_add(1, Ordering::Relaxed); +} + fn enabled() -> bool { !crate::state::config().present.eq_ignore_ascii_case("off") } @@ -470,7 +582,7 @@ pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { } // no console present call seen recently → present on submissions (rate limited) if now_ms().saturating_sub(LAST_BOUNDARY_MS.load(Ordering::Relaxed)) > 500 { - present_now(Duration::from_millis(15), None); + present_now(Duration::from_millis(15), None, Vec::new()); } } @@ -481,7 +593,7 @@ pub fn on_queue_console_method(_info: &StubInfo, _caller: usize) { } BOUNDARIES.fetch_add(1, Ordering::Relaxed); LAST_BOUNDARY_MS.store(now_ms(), Ordering::Relaxed); - unsafe { present_now(Duration::from_millis(4), None) }; + unsafe { present_now(Duration::from_millis(4), None, Vec::new()) }; } // --------------------------------------------------------------------------------------- @@ -729,6 +841,11 @@ struct Presenter { list: ID3D12GraphicsCommandList, fence: ID3D12Fence, copy_source: Option, + /// the planes of the last composed frame, kept until its fence is reached + composed: Vec, + composer: Option, + /// the composer could not be made: plane 0 alone is shown + compose_failed: bool, dumps: Vec, disabled: bool, value: u64, @@ -742,6 +859,9 @@ struct FrameDump { footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, format: DXGI_FORMAT, tag: String, + /// the presents so far when it was taken: its file's and its sample's number, also when it is + /// written at a later present (`write_late_dumps`) + frame: u64, } unsafe impl Send for Presenter {} @@ -776,7 +896,7 @@ unsafe fn new_presenter(queue: usize) -> Result { let event = CreateEventW(None, false, false, None).map_err(|err| format!("CreateEventW: {err}"))?; Ok(Presenter { queue, dev: dev.clone(), sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN, alloc, list, fence, - copy_source: None, dumps: Vec::new(), disabled: false, value: 0, event, + copy_source: None, composed: Vec::new(), composer: None, compose_failed: false, dumps: Vec::new(), disabled: false, value: 0, event, last: Instant::now() - Duration::from_secs(1), }) } @@ -827,7 +947,7 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D } } -unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { +unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>, planes: Vec) { if IN_PRESENT.with(|c| c.replace(true)) { return; } @@ -892,8 +1012,34 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { return; } p.copy_source = None; - p.dumps.clear(); - if !ensure_swapchain(p, hwnd, desc.Width as u32, desc.Height, fmt) { + p.composed.clear(); + // (dumps whose copy outlasted the last present's 2-s wait: done now) + write_late_dumps(&mut p.dumps); + // two planes or more: composed at the size of the largest, in its format + let compose_into = (planes.len() > 1) + .then(|| { + let big = planes.iter().max_by_key(|c| c.res.GetDesc().Width * c.res.GetDesc().Height as u64)?; + let bd = big.res.GetDesc(); + let fmt = swap_format(bd.Format)?; + let w = planes.iter().map(|c| c.res.GetDesc().Width).max()? as u32; + let h = planes.iter().map(|c| c.res.GetDesc().Height).max()?; + if p.composer.as_ref().is_none_or(|c| !c.fits(&p.dev, fmt)) && !p.compose_failed { + match super::compose::Composer::new(&p.dev, fmt) { + Ok(c) => { + crate::xlog_info!("present: the title's {} planes are composed into the XCL window ({w}x{h}, plane 0 at the bottom, premultiplied alpha)", planes.len()); + p.composer = Some(c); + } + Err(e) => { + p.compose_failed = true; + crate::xlog_warn!("present: the title's planes cannot be composed ({e}) – plane 0 alone is shown"); + } + } + } + p.composer.as_ref().is_some_and(|c| c.fits(&p.dev, fmt)).then_some((w, h, fmt)) + }) + .flatten(); + let (sw, sh, sfmt) = compose_into.unwrap_or((desc.Width as u32, desc.Height, fmt)); + if !ensure_swapchain(p, hwnd, sw, sh, sfmt) { return; } let Some(sc) = p.sc.clone() else { return }; @@ -901,15 +1047,41 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { if p.alloc.Reset().is_err() || p.list.Reset(&p.alloc, None).is_err() { return; } - let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; - p.list.ResourceBarrier(&b1); - p.list.CopyResource(&bb, &src); - let due = frame_dump_due(); + let (due_every, due_world) = frame_dump_due(); + let due = due_every || due_world; let mut dumps = Vec::new(); - if due { - if let Some((buffer, footprint)) = readback_copy(&p.list, &src, &desc) { - dumps.push(FrameDump { _source: src.clone(), buffer, footprint, format: desc.Format, tag: "frame".into() }); + let frame = PRESENTS.load(Ordering::Relaxed); + let after_copy = if compose_into.is_some() { + let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)]; + p.list.ResourceBarrier(&b1); + if let Some(c) = p.composer.as_ref() { + c.record(&p.dev, &p.list, &bb, sw, sh, &planes); + } + if due { + let b = [transition(&bb, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]; + p.list.ResourceBarrier(&b); + let bd = bb.GetDesc(); + if let Some((buffer, footprint)) = readback_copy(&p.list, &bb, &bd) { + dumps.push(FrameDump { _source: bb.clone(), buffer, footprint, format: bd.Format, tag: "frame".into(), frame }); + } + D3D12_RESOURCE_STATE_COPY_SOURCE + } else { + D3D12_RESOURCE_STATE_RENDER_TARGET } + } else { + let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)]; + p.list.ResourceBarrier(&b1); + p.list.CopyResource(&bb, &src); + if due { + if let Some((buffer, footprint)) = readback_copy(&p.list, &src, &desc) { + dumps.push(FrameDump { _source: src.clone(), buffer, footprint, format: desc.Format, tag: "frame".into(), frame }); + } + } + D3D12_RESOURCE_STATE_COPY_DEST + }; + // (a world dump counts toward XCL_FRAME_DUMP_WORLD's bound once its readback copy is recorded) + if due_world && !dumps.is_empty() { + WORLD.recorded(); } // with `XCL_TRACE_FRAME`: also the render target the title binds most (its scene / UI) // (and the targets the watched one's contents went on to: rt__) @@ -931,10 +1103,10 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { }); for (k, (res, buffer, footprint, format)) in targets.enumerate() { let tag = if k == 0 { "rt".into() } else { format!("rt{k}") }; - dumps.push(FrameDump { _source: res, buffer, footprint, format, tag }); + dumps.push(FrameDump { _source: res, buffer, footprint, format, tag, frame }); } } - let b2 = [transition(&bb, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT)]; + let b2 = [transition(&bb, after_copy, D3D12_RESOURCE_STATE_PRESENT)]; p.list.ResourceBarrier(&b2); if p.list.Close().is_err() { return; @@ -944,6 +1116,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { let Ok(cl) = p.list.cast::() else { return }; q.ExecuteCommandLists(&[Some(cl)]); p.copy_source = Some(src); + p.composed = planes.into_iter().map(|c| c.res).collect(); p.dumps = dumps; p.value += 1; if let Err(e) = q.Signal(&p.fence, p.value) { @@ -964,10 +1137,12 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { match fence::wait(&p.fence, p.value, &p.dev, Some(p.event), 2000) { Ok(()) => { for dump in p.dumps.drain(..) { - write_frame(&dump.buffer, &dump.footprint, dump.format, &dump.tag); + write_frame(&dump.buffer, &dump.footprint, dump.format, &dump.tag, dump.frame); } } Err(e) => { + // (the dumps stay: written at the next present, once its wait for this copy is + // over – `write_late_dumps`) p.disabled = matches!(&e, FenceError::Removed(_)); crate::xlog_error!("present: frame dump copy: {e}"); if p.disabled { @@ -978,7 +1153,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { } let n = PRESENTS.fetch_add(1, Ordering::Relaxed); if n == 0 { - crate::xlog_info!("present: first game frame shown ({}x{})", desc.Width, desc.Height); + crate::xlog_info!("present: first game frame shown ({sw}x{sh})"); } } @@ -988,13 +1163,12 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { /// `XCL_FRAME_DUMP_FROM=`: none before that frame (a retail game's presents have stopped /// at a dump in its first 500 frames on a Mac; where no window can be captured, the dumps of /// the frames after are the only picture). -fn frame_dump_due() -> bool { +/// (XCL_FRAME_DUMP's, the world's – `XCL_FRAME_DUMP_WORLD`): whether this present is dumped; the +/// two sets add up. +fn frame_dump_due() -> (bool, bool) { static EVERY: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); let (every, from) = *EVERY.get_or_init(|| { - let every = match std::env::var("XCL_FRAME_DUMP") { - Ok(v) => v.parse().ok().filter(|&n| n > 1).unwrap_or(120), - Err(_) => 0, - }; + let every = frame_dump_every_for(std::env::var("XCL_FRAME_DUMP").ok().as_deref()); let from = if crate::util::mac_host() { std::env::var("XCL_FRAME_DUMP_FROM").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0) } else { @@ -1002,11 +1176,194 @@ fn frame_dump_due() -> bool { }; (every, from) }); - // the first frames too: a title under bring-up may never reach its 20th let n = PRESENTS.load(Ordering::Relaxed); + (every_due(n, every, from), world_due(n)) +} + +/// `XCL_FRAME_DUMP`'s value → every how many presents a frame is dumped (0: none): a number over 1 +/// that; `1` or anything else 120; unset none. +fn frame_dump_every_for(v: Option<&str>) -> u64 { + match v { + Some(v) => v.parse().ok().filter(|&n| n > 1).unwrap_or(120), + None => 0, + } +} + +/// Whether XCL_FRAME_DUMP's dumps take present `n` (presents so far): from `from` on, the first 4 +/// (a title under bring-up may never reach its 20th), then each `every`-th at 20 (or `every` − 1). +fn every_due(n: u64, every: u64, from: u64) -> bool { every > 0 && n >= from && (n < 4 || n % every == 20.min(every - 1)) } +/// `XCL_FRAME_DUMP_WORLD=[,]`, read once (`host_main`, before the title runs): frames +/// dumped every `` presents from the world's first frame on, `` at most (1 – 1000; +/// default 20), as XCL_FRAME_DUMP's – `frame_.bmp` and its lines. The world's first frame is known +/// by the first skipped dispatch of a program XCL_SKIP_CS lists, built or not (`bind::skip_cs`, +/// `skipped_unbuilt_roots`): GTA VI's VFX defrag trio, skipped first inside its first world frame +/// (run 66: 148.919 s, about 2,318 presents – a count that differs from run to run, ~2,489 in run +/// 65). Without an XCL_SKIP_CS list there is no mark and no world dump. The title's +/// DeserializePipelineStateX is no mark: GTA VI calls it first ~4.6 s into its loading (runs 64-66), +/// long before its world, and the first source is the one kept. Each dump waits for its copy up to +/// 2 s on the present thread (one whose copy outlasts that is written at a later present, under its +/// own number: `write_late_dumps`), and run 66's world showed a frame every ~2.9 s: every 5 or more and +/// 20 at most keep that small. Unset, `0` or not a number: off. XCL_FRAME_DUMP and +/// XCL_FRAME_DUMP_FROM are unchanged – their dumps come as well; FROM does not hold these back. +pub fn world_dumps() -> Option<(u64, u64)> { + static WORLD_DUMPS: std::sync::OnceLock> = std::sync::OnceLock::new(); + *WORLD_DUMPS.get_or_init(|| { + let w = world_dumps_for(std::env::var("XCL_FRAME_DUMP_WORLD").ok().as_deref()); + if let Some((every, max)) = w { + let listed = super::stall::skip_list().len(); + if listed == 0 { + crate::xlog_warn!("present: XCL_FRAME_DUMP_WORLD={every},{max} without programs listed to be skipped: the world's first frame is never marked and no world frame is dumped"); + } else { + crate::xlog_info!("present: XCL_FRAME_DUMP_WORLD={every},{max}: from the first skipped dispatch of the {listed} programs listed (the world's first frame), a frame dumped every {every} presents, {max} at most"); + } + } + w + }) +} + +/// XCL_FRAME_DUMP_WORLD's dumps at most with no `` given. +const WORLD_DUMPS_MAX: u64 = 20; + +/// `XCL_FRAME_DUMP_WORLD`'s value → (every, max) – `world_dumps`. +fn world_dumps_for(v: Option<&str>) -> Option<(u64, u64)> { + let mut parts = v?.split(','); + let every = parts.next()?.trim().parse::().ok().filter(|&n| n > 0)?; + let max = parts.next().and_then(|m| m.trim().parse::().ok()).map_or(WORLD_DUMPS_MAX, |m| m.clamp(1, 1000)); + Some((every, max)) +} + +/// The world's first frame (`note_world_mark`): the program whose skipped dispatch marked it (0: not +/// marked yet), the presents so far then, the dumps recorded since, whether its line was said. +pub(super) struct WorldMark { + hash: AtomicU64, + at: AtomicU64, + dumps: AtomicU64, + said: std::sync::atomic::AtomicBool, +} + +impl WorldMark { + pub(super) const fn new() -> WorldMark { + WorldMark { hash: AtomicU64::new(0), at: AtomicU64::new(u64::MAX), dumps: AtomicU64::new(0), said: std::sync::atomic::AtomicBool::new(false) } + } + + /// Marked at `presents` by a skipped dispatch of `hash`: the first one is kept. True: this one + /// marked it. + fn note(&self, hash: u64, presents: u64) -> bool { + // (the program first: whoever sees `at` sees its program too) + if hash == 0 || self.hash.load(Ordering::Relaxed) != 0 || self.hash.compare_exchange(0, hash, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return false; + } + self.at.store(presents, Ordering::Release); + true + } + + /// Not marked yet. + fn open(&self) -> bool { + self.hash.load(Ordering::Relaxed) == 0 + } + + /// (presents so far when it was marked, its program), once marked. + fn at(&self) -> Option<(u64, u64)> { + let at = self.at.load(Ordering::Acquire); + (at != u64::MAX).then(|| (at, self.hash.load(Ordering::Relaxed))) + } + + /// Whether present `n` (presents so far) is dumped for the world: from the mark on, every + /// `every`-th, while fewer than `max` were recorded. + fn due(&self, n: u64, (every, max): (u64, u64)) -> bool { + self.at().is_some_and(|(at, _)| n >= at && (n - at) % every.max(1) == 0 && self.dumps.load(Ordering::Relaxed) < max) + } + + /// A world dump's readback copy was recorded – counted only then: a readback that could not be + /// made is no dump. + fn recorded(&self) { + self.dumps.fetch_add(1, Ordering::Relaxed); + } + + /// True once, after the mark: its line is to be said. + fn first_say(&self) -> bool { + self.at().is_some() && !self.said.swap(true, Ordering::Relaxed) + } +} + +/// The process's world mark (`note_world_mark`, `world_due`). +static WORLD: WorldMark = WorldMark::new(); + +#[cfg(test)] +thread_local! { + /// (tests) a world mark of this thread's own, which `note_world_mark` and `world_mark_open` use + /// instead of the process's + static TEST_WORLD: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// (tests) This thread's skipped dispatches mark a world of its own until the guard is dropped. +#[cfg(test)] +pub(super) fn world_mark_for_test() -> impl Drop { + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + TEST_WORLD.with(|w| *w.borrow_mut() = None); + } + } + TEST_WORLD.with(|w| *w.borrow_mut() = Some(WorldMark::new())); + Restore +} + +/// (tests) This thread's own world mark: (presents so far then, its program), once marked. +#[cfg(test)] +pub(super) fn test_world_mark() -> Option<(u64, u64)> { + TEST_WORLD.with(|w| w.borrow().as_ref().and_then(WorldMark::at)) +} + +/// Whether the world's first frame is marked at all: XCL_FRAME_DUMP_WORLD set and programs listed +/// in XCL_SKIP_CS (both read before the title runs). +fn world_marks() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| world_dumps().is_some() && !super::stall::skip_list().is_empty()) +} + +/// A dispatch of program `hash`, which XCL_SKIP_CS lists, was skipped (`bind::skip_cs`, or one not +/// built yet: `skipped_unbuilt_roots`): the world's first frame is near – the first one is kept +/// (`world_dumps`). On the title's threads: atomics only. +pub(super) fn note_world_mark(hash: u64) { + #[cfg(test)] + if TEST_WORLD.with(|w| w.borrow().as_ref().map(|m| m.note(hash, PRESENTS.load(Ordering::Relaxed))).is_some()) { + return; + } + if world_marks() { + WORLD.note(hash, PRESENTS.load(Ordering::Relaxed)); + } +} + +/// Whether the world's first frame is still to be marked: `skipped_unbuilt_roots` looks up a +/// stand-in's program only while it is (then one load per skip). +pub(super) fn world_mark_open() -> bool { + #[cfg(test)] + if let Some(open) = TEST_WORLD.with(|w| w.borrow().as_ref().map(WorldMark::open)) { + return open; + } + world_marks() && WORLD.open() +} + +/// Whether present `n` is dumped for the world (the present thread); the mark's line once, at the +/// first present after it. +fn world_due(n: u64) -> bool { + let Some(w) = world_dumps() else { return false }; + if WORLD.first_say() { + if let Some((at, hash)) = WORLD.at() { + crate::xlog_info!("{}", world_line(at, hash, w)); + } + } + WORLD.due(n, w) +} + +fn world_line(at: u64, hash: u64, (every, max): (u64, u64)) -> String { + format!("present: the world's first frame is near at present {at} (a dispatch of {hash:016x} skipped (XCL_SKIP_CS)): frames dumped every {every} presents from there, {max} at most (XCL_FRAME_DUMP_WORLD)") +} + /// Frames shown so far. pub fn presents() -> u64 { PRESENTS.load(Ordering::Relaxed) @@ -1143,7 +1500,28 @@ fn small_float(v: u32, mantissa_bits: u32) -> f32 { } } -unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, format: DXGI_FORMAT, tag: &str) { +/// The dumps a present kept because its 2-s wait for their copy ran out (`present_now`): their copy is +/// done – the caller waited for it – and each is written under the presents count it was taken at +/// (the file `frame_.bmp` of its own frame, not the next one's), with a line that says so. A world +/// dump counted toward XCL_FRAME_DUMP_WORLD's bound when it was recorded is written after all. The +/// number written. +unsafe fn write_late_dumps(dumps: &mut Vec) -> usize { + let n = dumps.len(); + for dump in dumps.drain(..) { + crate::xlog_info!("present: {} {}'s copy ended after its present's 2-s wait – written at a later present", dump.tag, dump.frame); + write_frame(&dump.buffer, &dump.footprint, dump.format, &dump.tag, dump.frame); + } + n +} + +#[cfg(test)] +thread_local! { + /// (tests) the sample of this thread's last frame dump written (any tag) + static LAST_WRITTEN: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// A frame dump of present `n` (presents so far when it was taken) written. +unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, format: DXGI_FORMAT, tag: &str, n: u64) { let mut p: *mut c_void = std::ptr::null_mut(); if rb.Map(0, None, Some(&mut p)).is_err() || p.is_null() { return; @@ -1183,19 +1561,21 @@ unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRI bmp.resize(start + row, 0); } rb.Unmap(0, None); - let n = PRESENTS.load(Ordering::Relaxed); + let sample = FrameDumpSample { + frame: n, + width: w as u32, + height: h as u32, + format: format.0, + sample_step: step as u32, + sampled_pixels: (ow * oh) as u64, + non_dark_samples: decoded.then_some(lit as u64), + }; + #[cfg(test)] + LAST_WRITTEN.with(|c| c.set(Some(sample))); // `XCL_TRACE_FRAME` also dumps intermediate targets; only the presented image belongs here. if tag == "frame" { if let Ok(mut last) = LAST_FRAME_DUMP.lock() { - *last = Some(FrameDumpSample { - frame: n, - width: w as u32, - height: h as u32, - format: format.0, - sample_step: step as u32, - sampled_pixels: (ow * oh) as u64, - non_dark_samples: decoded.then_some(lit as u64), - }); + *last = Some(sample); } } let Some(boot) = crate::state::boot() else { return }; @@ -1320,11 +1700,20 @@ mod tests { let dummy_obj_unmapped: *const usize = &unmapped_vtable; assert!(backbuffer_like(dummy_obj_unmapped as usize).is_none()); - // Readable vtable but truncated (less than 88 bytes, e.g. 64 bytes) - let truncated_vtable = [0usize; 8]; - let vtable_ptr: usize = truncated_vtable.as_ptr() as usize; - let dummy_obj_truncated: *const usize = &vtable_ptr; - assert!(backbuffer_like(dummy_obj_truncated as usize).is_none()); + // Readable vtable but truncated (less than 88 bytes, e.g. 64 bytes): the last 64 bytes of + // a page with no page after it – on the stack, the bytes past such an array are readable, + // and slot 10 was whatever the stack held there (a pointer into the stack, called) + { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + let pages = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(pages, 0); + assert_ne!(VirtualAlloc(pages as *const _, 0x1000, MEM_COMMIT, PAGE_READWRITE) as usize, 0); + let vtable_ptr: usize = pages + 0x1000 - 64; + let dummy_obj_truncated: *const usize = &vtable_ptr; + assert_eq!(check_resource_desc_slot(dummy_obj_truncated as usize), Err("resource vtable is misaligned or unreadable")); + assert!(backbuffer_like(dummy_obj_truncated as usize).is_none()); + VirtualFree(pages as *mut _, 0, MEM_RELEASE); + } // Readable vtable (>= 88 bytes) but null GetDesc function pointer at slot 10 let mut vtable_with_null_fn = [0usize; 15]; @@ -1335,6 +1724,38 @@ mod tests { } } + /// The composed planes and the planes' log line read their resources through the guarded + /// GetDesc too: planes whose first resource is an object with a null vtable, an unmapped one, + /// or a null GetDesc entry are left out of the composition (none to compose) and named with the + /// reason in the log line – nothing is called through them. + #[test] + fn composed_and_described_planes_guard_their_resources() { + unsafe { + let null_vtable: usize = 0; + let unmapped_vtable: usize = 0xDEAD_CAFE_0000; + let vtable_null_get_desc = [0usize; 15]; + let null_get_desc: usize = vtable_null_get_desc.as_ptr() as usize; + let objects = [&null_vtable as *const usize as usize, &unmapped_vtable as *const usize as usize, &null_get_desc as *const usize as usize]; + let lists: Vec> = objects.iter().map(|&o| Box::new(o)).collect(); + let mut planes = vec![0u8; RETAIL_PLANE_STRIDE * objects.len()]; + for (i, list) in lists.iter().enumerate() { + let p = planes.as_mut_ptr().add(i * RETAIL_PLANE_STRIDE); + *(p as *mut u64) = 1 + i as u64; + *(p.add(8) as *mut u32) = 1; + *(p.add(0x10) as *mut usize) = &**list as *const usize as usize; + } + assert!(compose_planes(planes.as_ptr(), objects.len() as u32).is_empty(), "no plane to compose"); + let reasons = ["resource vtable is misaligned or unreadable", "resource vtable is misaligned or unreadable", "GetDesc entry is null or unreadable"]; + for (i, (&o, why)) in objects.iter().zip(reasons).enumerate() { + let line = describe_plane(planes.as_ptr().add(i * RETAIL_PLANE_STRIDE)); + assert!(line.starts_with(&format!("1 resource(s) [{o:#x}: {why}]")), "plane {i}: {line}"); + } + // a plane without a resource says so + *(planes.as_mut_ptr().add(0x10) as *mut usize) = &0usize as *const usize as usize; + assert!(describe_plane(planes.as_ptr()).starts_with("1 resource(s) [none]")); + } + } + #[test] fn resource_desc_slot_accepts_unaligned_code_address() { // Exercise the slot check without calling through the test address. @@ -1474,21 +1895,173 @@ mod frame_dump_tests { buffer.Unmap(0, None); }; fill(30); - write_frame(&buffer, &fp, fp.Footprint.Format, "frame"); + write_frame(&buffer, &fp, fp.Footprint.Format, "frame", 0); let dark = last_frame_dump().unwrap(); assert_eq!((dark.width, dark.height, dark.format), (8, 8, 28)); assert_eq!(dark.sampled_pixels, (8 / dark.sample_step).pow(2) as u64); assert_eq!(dark.non_dark_samples, Some(0)); fill(31); - write_frame(&buffer, &fp, fp.Footprint.Format, "rt"); + write_frame(&buffer, &fp, fp.Footprint.Format, "rt", 0); assert_eq!(last_frame_dump(), Some(dark), "intermediate targets must not replace frame content"); - write_frame(&buffer, &fp, fp.Footprint.Format, "frame"); + write_frame(&buffer, &fp, fp.Footprint.Format, "frame", 0); let bright = last_frame_dump().unwrap(); assert_eq!(bright.non_dark_samples, Some(bright.sampled_pixels)); - write_frame(&buffer, &fp, DXGI_FORMAT_R32_FLOAT, "frame"); + write_frame(&buffer, &fp, DXGI_FORMAT_R32_FLOAT, "frame", 0); let json = serde_json::to_value(last_frame_dump().unwrap()).unwrap(); assert!(json["non_dark_samples"].is_null(), "undecoded is different from dark"); } } + + /// C-F1: a dump a present kept because its 2-s wait for the copy ran out is written at a later + /// present (`write_late_dumps`) – not dropped – under the presents count it was taken at, not the + /// later present's; nothing is kept again. On this process's device (an upload buffer laid out as + /// a readback's footprint); tag "late", so the frame sample the report shows is not touched. + #[test] + fn a_dump_whose_copy_outlasted_its_wait_is_written_later_under_its_own_frame() { + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let dev = dev.unwrap(); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 512 + 256 * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut buffer) + .expect("an upload buffer"); + let buffer = buffer.unwrap(); + let mut p: *mut c_void = std::ptr::null_mut(); + buffer.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, 0x80, desc.Width as usize); + buffer.Unmap(0, None); + let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 512, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R8G8B8A8_UNORM, Width: 8, Height: 8, Depth: 1, RowPitch: 256 }, + }; + let frame = 0x7A1E_F101u64; + let mut kept = vec![FrameDump { _source: buffer.clone(), buffer: buffer.clone(), footprint, format: DXGI_FORMAT_R8G8B8A8_UNORM, tag: "late".into(), frame }]; + let _ = LAST_WRITTEN.with(|c| c.take()); + assert_eq!(write_late_dumps(&mut kept), 1, "the kept dump is written"); + assert!(kept.is_empty(), "and not kept again"); + let s = LAST_WRITTEN.with(|c| c.take()).expect("written"); + assert_eq!((s.frame, s.width, s.height, s.non_dark_samples), (frame, 8, 8, Some(s.sampled_pixels)), "under the count it was taken at"); + assert_eq!(write_late_dumps(&mut kept), 0, "none left"); + assert_eq!(LAST_WRITTEN.with(|c| c.take()), None); + } + } +} + +#[cfg(test)] +mod world_dump_tests { + use super::*; + + /// `XCL_FRAME_DUMP_WORLD=[,]`: a number from 1, then dumps at most from 1 to 1000 + /// (20 with none given or not a number); unset, `0`, not a number or empty: off. This process's + /// switch as it was read. + #[test] + fn the_world_dump_switch_is_read_as_every_and_max() { + assert_eq!(world_dumps_for(Some("3")), Some((3, 20))); + assert_eq!(world_dumps_for(Some("3,40")), Some((3, 40))); + assert_eq!(world_dumps_for(Some(" 5 , 12 ")), Some((5, 12))); + assert_eq!(world_dumps_for(Some("5,5000")), Some((5, 1000))); + assert_eq!(world_dumps_for(Some("5,0")), Some((5, 1))); + assert_eq!(world_dumps_for(Some("5,x")), Some((5, 20))); + for off in [None, Some("0"), Some("x"), Some(""), Some(",40"), Some("0,40"), Some("-3")] { + assert_eq!(world_dumps_for(off), None, "{off:?}: off"); + } + let env = std::env::var("XCL_FRAME_DUMP_WORLD").ok(); + assert_eq!(world_dumps(), world_dumps_for(env.as_deref()), "this process's switch"); + } + + /// The world's dumps (`WorldMark::due`): none before the world's first frame is marked, then + /// every n-th present from the mark, the mark's present first, until `max` were recorded – one + /// whose readback copy was not recorded is not counted; the mark's line once, after the mark, + /// with its text. + #[test] + fn world_dumps_come_every_n_from_the_mark_up_to_max() { + let m = WorldMark::new(); + let w = (3, 4); + assert!((0..2318).all(|n| !m.due(n, w)), "no dump before the world's first frame"); + assert!(!m.first_say(), "no line before it"); + assert!(m.note(0x7A1E_0000_0000_7001, 2318)); + // (before any dump is recorded: the bound does not hide a due before the mark) + assert!(!m.due(2317, w), "nothing before the mark"); + assert!(m.first_say() && !m.first_say(), "its line once"); + let mut dumped = Vec::new(); + for n in 2318..2360 { + if m.due(n, w) { + dumped.push(n); + // (2324's readback could not be made: not counted) + if n != 2324 { + m.recorded(); + } + } + } + assert_eq!(dumped, [2318, 2321, 2324, 2327, 2330], "every 3rd from the mark, 4 recorded at most"); + assert!(!m.due(2333, w) && !m.due(2400, w), "the bound reached"); + // every 1: each present from the mark + let m = WorldMark::new(); + assert!(m.note(0x7A1E_0000_0000_7002, 10)); + assert_eq!((0..20).filter(|&n| m.due(n, (1, 20))).collect::>(), (10..20).collect::>()); + assert_eq!( + world_line(2318, 0x71f4_ac8a_d5eb_a33c, (5, 20)), + "present: the world's first frame is near at present 2318 (a dispatch of 71f4ac8ad5eba33c skipped (XCL_SKIP_CS)): frames dumped every 5 presents from there, 20 at most (XCL_FRAME_DUMP_WORLD)" + ); + } + + /// The mark keeps its first source (the design check's A1): the title's DeserializePipelineStateX + /// – GTA VI's first comes ~4.6 s into its loading, long before its world – is no mark; the first + /// skipped dispatch of a listed program is, and a later one of another program leaves it; no + /// program, no mark. Through the hook (`device_x::deserialize_pso_x`) and `note_world_mark` on a + /// world mark of this thread's own, and on a `WorldMark`. + #[test] + fn the_world_mark_keeps_its_first_source() { + let _world = world_mark_for_test(); + let mut out = 0x7A1E_7EEEusize as *mut c_void; + let hr = unsafe { super::super::device_x::deserialize_pso_x(std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), &mut out) }; + assert!(hr < 0 && out.is_null(), "the hook as before: a failure, no pipeline"); + assert!(world_mark_open() && test_world_mark().is_none(), "a DeserializePipelineStateX call is no mark"); + let before = presents(); + note_world_mark(0x7A1E_0000_0000_7101); + let after = presents(); + note_world_mark(0x7A1E_0000_0000_7102); + let (at, hash) = test_world_mark().expect("the skip marks the world"); + assert!(at >= before && at <= after, "marked at the presents so far"); + assert_eq!(hash, 0x7A1E_0000_0000_7101, "the first source kept"); + assert!(!world_mark_open()); + // a mark of its own + let m = WorldMark::new(); + assert!(!m.note(0, 5) && m.open(), "no program: no mark"); + assert!(m.note(0x7A1E_0000_0000_7103, 2318)); + assert!(!m.note(0x7A1E_0000_0000_7104, 2400) && !m.note(0x7A1E_0000_0000_7103, 2500), "a later skip leaves it"); + assert_eq!(m.at(), Some((2318, 0x7A1E_0000_0000_7103))); + assert!(!m.open()); + } + + /// XCL_FRAME_DUMP and XCL_FRAME_DUMP_FROM as before 0023.2 (`frame_dump_every_for`, `every_due`): + /// unset none; `1` or not a number every 120th; a number over 1 every n-th, at 20 (or n − 1), the + /// first 4 too; none before FROM. + #[test] + fn xcl_frame_dump_and_its_from_are_as_before() { + assert_eq!(frame_dump_every_for(None), 0); + assert_eq!(frame_dump_every_for(Some("1")), 120); + assert_eq!(frame_dump_every_for(Some("x")), 120); + assert_eq!(frame_dump_every_for(Some("300")), 300); + assert_eq!(frame_dump_every_for(Some("3")), 3); + assert!((0..1000).all(|n| !every_due(n, 0, 0)), "unset: none"); + assert_eq!((0..300).filter(|&n| every_due(n, 120, 0)).collect::>(), [0, 1, 2, 3, 20, 140, 260]); + assert_eq!((0..12).filter(|&n| every_due(n, 3, 0)).collect::>(), [0, 1, 2, 3, 5, 8, 11]); + assert_eq!((2190..2215).filter(|&n| every_due(n, 3, 2200)).collect::>(), [2201, 2204, 2207, 2210, 2213], "none before FROM"); + // PP4's XCL_FRAME_DUMP=10 from 2250: 2259, 2269 … (its verdict) + assert_eq!((2250..2290).filter(|&n| every_due(n, 10, 2250)).collect::>(), [2259, 2269, 2279, 2289]); + } } diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index c4db872..74ef4c1 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -3,23 +3,143 @@ //! 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 -//! for at its first bind (a skipped dispatch would corrupt what it computes). +//! as it is there. A pipeline is waited for at its first use – a compute one at its first bind, +//! a graphics one at its first draw (`bind::graphics_bound`) –: with `XCL_PSO_WAIT_MS` set, that +//! long at most (built on the workers), and a thread's waits with a limit between two Presents +//! `XCL_PSO_WAIT_FRAME_MS` at most in all (`frame`); with it unset or 0, until it is built (on +//! the binding thread when no worker has it), as before 0023.1 – no frame's budget asked. A compute +//! pipeline with 256 KB of DXIL or more that no run built yet (`built`) goes to a lane of its own +//! (`XCL_PSO_BIG_THREADS`) and is waited for `XCL_PSO_WAIT_BIG_MS` at most (0: not at all): its +//! work is skipped until it is built. GTA VI's first world frame (run 64) needed 415 compute +//! programs never built before; those of 256 KB or more took 687 s of the driver's 871, and one +//! of 29 MB never came back to the title thread that bound it. //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. -use std::collections::HashMap; -use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; -use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +use std::cell::RefCell; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; +#[cfg(test)] +use std::sync::mpsc; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError}; +use std::time::{Duration, Instant}; + +use crate::gpu::recomp::pso::Stage; const STATE_IDLE: u8 = 0; const STATE_QUEUED: u8 = 1; const STATE_DONE: u8 = 2; +/// DXIL from which a compute pipeline is big: the driver's compile takes seconds to minutes +/// (run 64's cold compiles of 256 KB or more: 1.6 s at the least, 3.4 s the median, 11 – 55 s +/// from 1 MB), one D3DMetal kept from an earlier run milliseconds (`built`). +/// (`real::BIG_DRIVER_COMPILE` is this.) +pub const BIG_DXIL: usize = 256 << 10; + +/// A console program's bytes times this is its DXIL's, roughly (the median over GTA VI's 2 733 +/// compute translations: 16.9): the size of one not translated yet (`Program::estimated`). +pub const DXIL_PER_CONSOLE_BYTE: usize = 16; + +/// Where a pipeline is built (`Pending::lane`). +const LANE_NONE: u8 = 0; // not sent yet +const LANE_WORKERS: u8 = 1; // the `xcl-pso-k` workers +const LANE_BIG: u8 = 2; // the big lane (`BigLane`) +const LANE_HERE: u8 = 3; // a binding thread +const LANE_AHEAD: u8 = 4; // the threads that build ahead (`preload`) + +/// The tiers of the workers' queue (`Workers`, `tier_of`; `Pending::tier`): tier 1 – what needs no +/// DXC: the ledger knows it, or its shaders' translations are on disk – before the cold ones. +const TIER_KNOWN: u8 = 0; +const TIER_TRANSLATED: u8 = 1; +const TIER_COLD: u8 = 2; + +/// What a pipeline is built from, as the logs and the waits watch name it (`real::program_of`). +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub struct Program { + /// fnv64 of the console program it is known by – its CS, VS or MS (0: none) + pub hash: u64, + /// b'C' compute, b'G' graphics (named by its VS), b'M' a pipeline stream (0: not known) + pub kind: u8, + /// bytes of DXIL, from the translation cache's header (0: not known) + pub dxil: u32, + /// `dxil` is `DXIL_PER_CONSOLE_BYTE` times the console program's (not translated yet) + pub estimated: bool, + /// the hash of its shaders (`real::key_of`) the built-pipelines ledger knows it by (0: none) + pub key: u64, + /// fnv64 of its CS (`[cs, 0]`), or of its VS and its console PS (`[vs, ps]`, 0: no console PS): + /// what `tier_of` looks their translations up by (0: none – not looked up) + pub shaders: [u64; 2], + /// the split flag its shaders are translated with (`real::wave_splits`): part of their + /// translations' names + pub split: bool, + /// its shaders' translations are on disk: Some(true) yes, found when it was made; Some(false) + /// a CS not found then (asked again when sent – a clone's build may have stored it since), a + /// graphics or mesh pipeline whose shaders are translated otherwise (never); None: not looked + /// up – `tier_of` asks the translation cache when it is sent + pub translated: Option, +} + +fn what(kind: u8) -> &'static str { + match kind { + b'C' => "CS", + b'G' => "VS", + b'M' => "MS", + _ => "pipeline", + } +} + +/// "29059 KB of DXIL", "~272 KB of DXIL (estimated)", "DXIL size not known" +fn size_text(dxil: u32, estimated: bool) -> String { + match (dxil, estimated) { + (0, _) => "DXIL size not known".into(), + (n, true) => format!("~{} KB of DXIL (estimated)", n >> 10), + (n, false) => format!("{} KB of DXIL", n >> 10), + } +} + +/// `XCL_PSO_BIG_THREADS` (default 2; 0: no big lane – big pipelines go to the other workers, +/// binds wait for them and `real::BIG_COMPILES`' one slot is taken as before 0023): the threads +/// that build big compute pipelines no run built yet. Two such compiles at once is what run 64 +/// ran for 383 s with 52 – 56 % of the Mac's memory free. +pub fn big_threads() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_PSO_BIG_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2).min(8)) +} + +/// `XCL_PSO_WAIT_BIG_MS` (default 0: not at all; at most 600000): how long a bind waits for a big +/// pipeline no run built yet, whatever `XCL_PSO_WAIT_MS` is – a wait with a limit, so within the +/// thread's frame budget too (`wait_frame`: 2000 ms by default), also with no `XCL_PSO_WAIT_MS`. +fn wait_big() -> Duration { + static B: OnceLock = OnceLock::new(); + *B.get_or_init(|| Duration::from_millis(std::env::var("XCL_PSO_WAIT_BIG_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0u64).min(600_000))) +} + +/// `XCL_PSO_BIG_LOW=0`: the big lane's threads at normal priority (else below normal: the +/// title's threads and the other workers go first). +fn big_low() -> bool { + static L: OnceLock = OnceLock::new(); + *L.get_or_init(|| std::env::var("XCL_PSO_BIG_LOW").map_or(true, |v| v.trim() != "0")) +} + +/// `XCL_PSO_STILL_BUILDING_S` (default 30; 0: no "still building" lines). +fn still_building_every() -> Option { + static S: OnceLock = OnceLock::new(); + let s = *S.get_or_init(|| std::env::var("XCL_PSO_STILL_BUILDING_S").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(30)); + (s > 0).then(|| Duration::from_secs(s)) +} + +/// `XCL_PSO_PRELOAD` (on unless `0`): read without starting the threads that build ahead. +fn preload_on() -> bool { + static P: OnceLock = OnceLock::new(); + *P.get_or_init(|| !std::env::var("XCL_PSO_PRELOAD").is_ok_and(|v| v.trim() == "0")) +} + struct Pending { - /// the build, until a worker – or a bind that cannot wait for the queue – takes it + /// the build, until a worker – or a bind that cannot wait for the queue – takes it (None from + /// the start: refused, never built) job: Mutex>, - /// the build went to the workers (a lazy one goes on its first `resolve`) - sent: std::sync::atomic::AtomicBool, + /// the build was sent – to the workers, the big lane (a lazy one on its first `resolve`) – or a + /// bind took it + sent: AtomicBool, queued: AtomicU8, /// the real pipeline state (raw pointer), 0 while building or when building failed real: AtomicUsize, @@ -29,20 +149,82 @@ struct Pending { /// of its shaders (`used`); 0 = none key: u64, /// it was used (`used::note` is told once) - used: std::sync::atomic::AtomicBool, + used: AtomicBool, /// the stand-in was released before the real pipeline was built - orphan: std::sync::atomic::AtomicBool, - /// a bind waited for it longer than `wait_budget`: binds go on without it until it is built - late: std::sync::atomic::AtomicBool, + orphan: AtomicBool, + /// a bind waited for it longer than `wait_budget`, or it is big and no run built it (`big`): + /// binds go on without it until it is built + late: AtomicBool, + /// the stand-in the title holds (the name of a pipeline without a program) + standin: usize, + /// what it is built from (`Program`) + prog: Program, + /// bytes of DXIL: `prog.dxil` until its translation says (`note_dxil`), and whether estimated + dxil: AtomicU32, + estimated: AtomicBool, + /// never built: refused (`real::refusal`) – when made, or by its build + refused: AtomicBool, + /// where it went (`LANE_*`) + lane: AtomicU8, + /// big, and sent where small ones go because the ledger knew it (`route`): its driver time + /// is judged (`note_driver_time`) + routed_known: AtomicBool, + /// ms its driver compile took (0: none yet) + driver_ms: AtomicU32, + /// its tier in the workers' queue (`TIER_*`, set when it is sent there: `Workers::push`) + tier: AtomicU8, + /// a bind got its real pipeline (MP4: told once, `note_built_use`) + first_use: AtomicBool, + /// when it was built (ms of the log's clock, `complete`; 0: not built) + built_ms: AtomicU64, } impl Pending { + /// The entry of stand-in `standin`, built by `job` (None: refused) from `prog`; `sent`: it + /// goes to be built now. + fn new(standin: usize, compute: bool, job: Option, sent: bool, key: u64, prog: Program) -> Pending { + let refused = job.is_none(); + Pending { + job: Mutex::new(job), + sent: AtomicBool::new(sent), + queued: AtomicU8::new(STATE_IDLE), + real: AtomicUsize::new(0), + done: Mutex::new(false), + cv: Condvar::new(), + compute, + key, + used: Default::default(), + orphan: Default::default(), + late: Default::default(), + standin, + prog, + dxil: AtomicU32::new(prog.dxil), + estimated: AtomicBool::new(prog.estimated), + refused: AtomicBool::new(refused), + lane: AtomicU8::new(LANE_NONE), + routed_known: Default::default(), + driver_ms: Default::default(), + tier: AtomicU8::new(TIER_COLD), + first_use: Default::default(), + built_ms: Default::default(), + } + } + fn note_use(&self) { if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { used::note(self.key); } } + /// (a resolve that gives a bind the real pipeline) The first time: MP4's record of it + /// (`note_first_use`) – one Relaxed load each later time, on the title's binds. + #[inline] + fn note_built_use(&self) { + if !self.first_use.load(Ordering::Relaxed) && !self.first_use.swap(true, Ordering::AcqRel) { + note_first_use(self); + } + } + fn note_queued(&self) { if self.queued.load(Ordering::Relaxed) != STATE_IDLE { return; @@ -61,16 +243,39 @@ impl Pending { } } +/// "56c0cd3b82a00c6e (CS, 29059 KB of DXIL)" – or "stand-in 0x7fa717d4b010" without a program +fn name(p: &Pending) -> String { + name_of(p.prog.hash, p.standin, p.prog.kind, p.dxil.load(Ordering::Relaxed), p.estimated.load(Ordering::Relaxed)) +} + +/// `name` of a pipeline by its parts: its program's hash (0: none), its stand-in, its program's +/// kind and DXIL +fn name_of(hash: u64, standin: usize, kind: u8, dxil: u32, estimated: bool) -> String { + if hash == 0 { + return format!("stand-in {standin:#x}"); + } + format!("{hash:016x} ({}, {})", what(kind), size_text(dxil, estimated)) +} + +fn big_by_size(p: &Pending) -> bool { + p.compute && p.dxil.load(Ordering::Relaxed) as usize >= BIG_DXIL +} + /// stand-in handed to the title → its real pipeline static PENDING: Mutex>>> = Mutex::new(None); -/// The build is done (`real`: its pipeline, 0 = failed). +/// The build is done (`real`: its pipeline, 0 = failed or refused). fn complete(p: &Pending, real: usize) { p.finish_queued(); if real == 0 { FAILED.fetch_add(1, Ordering::Relaxed); } else { BUILT.fetch_add(1, Ordering::Relaxed); + // D3DMetal has it now – also when the title released it meanwhile + built::note(p.prog.key); + // (before `real` is stored: a bind that gets it sees when it was built, `note_first_use`; + // 1 at least – 0 is "not built", and the log's clock reads 0 for its first millisecond) + p.built_ms.store(now_ms().max(1), Ordering::Relaxed); } let orphan = { let mut done = p.done.lock().unwrap(); @@ -91,6 +296,39 @@ static BUILT: AtomicUsize = AtomicUsize::new(0); static FAILED: AtomicUsize = AtomicUsize::new(0); static BUILDING: AtomicUsize = AtomicUsize::new(0); +/// pipelines that went late: small ones (a wait past `XCL_PSO_WAIT_MS`) and big ones no run built +static WENT_LATE: AtomicUsize = AtomicUsize::new(0); +static WENT_LATE_BIG: AtomicUsize = AtomicUsize::new(0); +/// binds that went on without their pipeline +static LATE_BINDS: AtomicUsize = AtomicUsize::new(0); +/// work skipped because its pipeline was not built (`note_skip`, from `bind`) +static SKIPPED: AtomicUsize = AtomicUsize::new(0); +/// programs refused (each once) +static REFUSED_PROGRAMS: AtomicUsize = AtomicUsize::new(0); +/// compute pipelines sized from the translation cache, and estimated (`note_sizing`) +static SIZED: AtomicUsize = AtomicUsize::new(0); +static ESTIMATED: AtomicUsize = AtomicUsize::new(0); +/// driver compiles running now, and the most at once so far (`DriverClock`) +static IN_DRIVER: AtomicUsize = AtomicUsize::new(0); +static IN_DRIVER_MOST: AtomicUsize = AtomicUsize::new(0); +/// ms the process stood still so far (`start_watch`) +static FROZEN_MS: AtomicU64 = AtomicU64::new(0); + +/// (real) A compute pipeline was sized from its translation (`sized`), else estimated. +pub fn note_sizing(sized: bool) { + (if sized { &SIZED } else { &ESTIMATED }).fetch_add(1, Ordering::Relaxed); +} + +/// ms the process stood still so far (0 in tests and before the first build) +pub fn frozen_ms() -> u64 { + FROZEN_MS.load(Ordering::Relaxed) +} + +/// ms of the log's clock (`log::uptime`): what a line's time says +fn now_ms() -> u64 { + (crate::log::uptime() * 1000.0) as u64 +} + pub fn enabled() -> bool { std::env::var("XCL_ASYNC_PSO").map_or(true, |v| v != "0") } @@ -98,27 +336,499 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; -fn queue() -> &'static Mutex>> { - static Q: OnceLock>>> = OnceLock::new(); - Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::>(); - let rx = Arc::new(Mutex::new(rx)); - // translation recurses deeply on big programs; DXC itself runs on its own pool - let n = crate::gpu::recomp::dxc::compile_threads(); +/// A compute pipeline of `BIG_DXIL` or more that no run built (the ledger, `built`): the big +/// lane's. D3DMetal keeps what it compiled between runs (2e0055c25f49848a: 14 166 ms in run 63, +/// 11 ms in run 64), so one the ledger knows is sent and waited for like a small one. +fn big(p: &Pending) -> bool { + big_threads() > 0 && big_by_size(p) && !built::known(p.prog.key) +} + +/// Where `p` is built – `LANE_BIG` for a big one no run built (`big`), else `other` – noted in +/// `lane`; a big one sent to `other` because the ledger knew it is `routed_known`. +fn route(p: &Pending, other: u8) -> u8 { + let lane = if big_threads() > 0 && big_by_size(p) { + if built::known(p.prog.key) { + p.routed_known.store(true, Ordering::Release); + other + } else { + LANE_BIG + } + } else { + other + }; + p.lane.store(lane, Ordering::Release); + lane +} + +/// A bind treats `p` as big: sent to the big lane; or not sent yet and one `route` sends there; +/// or found big since it went elsewhere (its translation's size, `note_dxil`) while the ledger +/// did not know it then. Such a pipeline is neither built on the binding thread nor waited for +/// longer than XCL_PSO_WAIT_BIG_MS – the decision sticks to `lane`, whatever the ledger says +/// later (a clone built meanwhile). +fn bind_as_big(p: &Pending) -> bool { + if big_threads() == 0 || !p.compute { + return false; + } + match p.lane.load(Ordering::Acquire) { + LANE_BIG => true, + LANE_NONE => big(p), + _ => big_by_size(p) && !p.routed_known.load(Ordering::Acquire), + } +} + +/// The workers' queue (`send`): what needs no DXC first – pipelines the ledger knows +/// (`TIER_KNOWN`: D3DMetal has them; their driver compiles took 1 ms – compute – and 3 ms – +/// graphics – at the median in run 66) and those whose shaders' translations are on disk +/// (`TIER_TRANSLATED`: the driver's compile only) –, the others (`TIER_COLD`: DXC compiles them, one +/// at a time under its memory gate while commit is short) after them; each tier in the order sent, +/// and all cold – one queue in that order, as before 0023.2 – with `XCL_PSO_TIERS=0` +/// (`tiers_on`). Run 66's one queue held three compute programs the ledger knew (36353c66, +/// bd968d88, 44ca55bf: milliseconds each) behind cold graphics builds of 3.5 – 10.2 s from 157 s to +/// its end: never built. The tiers are strict: a cold pipeline waits while tier 1 is not empty – +/// for good while tier 1's arrivals keep up with its builds; the queue line's cold count +/// (`queue_line`) shows it. `TIER_TRANSLATED` means a translation-cache file (translated/v2) for the +/// VS at sampler base 0 and for the PS at the VS's sampler count – a build's, or the compute +/// precompile's: `xcl shaders --precompile`'s VS and PS phases fill only the flat DXIL cache, so a +/// precompiled graphics pipeline whose translations are not on disk is cold though it needs no DXC +/// (its build is the translation, a DXIL cache hit and the driver). The queue line's DXC fields (cache +/// misses), not its cold count, say what DXC does. A big compute pipeline (`big_by_size`) is in tier 1 only when the +/// ledger knew it (`route`: else the big lane's), and with no driver blob – none on a Mac – its +/// build waits for 3 GiB of commit before the driver's compile, as long as that takes +/// (`real::wait_for_commit`): three of them would hold every worker there while commit is short +/// (run 66: 2.8 GB at 197.7 s). So one worker at a time builds such a one up to that wait and +/// through it (`Tiers::big_out`, given back past it: `commit_wait_over`); the others stay where +/// they are in tier 1, passed over, and the other workers build what comes after them. +struct Workers { + q: Mutex, + cv: Condvar, + /// threads started (0: none could be – `push` gives the pipeline up, as before 0023.2) + threads: AtomicUsize, + /// sent and not taken by a worker yet (the pipelines lines' `queued`, as before 0023.2), and by + /// tier and kind (`[tier][compute]`: the queue line) + depth: AtomicUsize, + by_tier: [[AtomicUsize; 2]; 3], +} + +#[derive(Default)] +struct Tiers { + /// tier 1 (`TIER_KNOWN`, `TIER_TRANSLATED`), and the cold ones: each in the order sent + first: VecDeque>, + rest: VecDeque>, + /// a worker's build of a big compute pipeline of tier 1 has not passed its wait for commit yet + /// (`BigTurn`, `commit_wait_over`) + big_out: bool, +} + +impl Tiers { + fn push(&mut self, p: Arc, tier: u8) { + if tier == TIER_COLD { + self.rest.push_back(p) + } else { + self.first.push_back(p) + } + } + + /// The next to build, and whether it is a big compute pipeline of tier 1 (its worker holds that + /// turn until its build is past its wait for commit, `BigTurn`): tier 1's first – a big compute + /// one only while no worker holds the turn (passed over meanwhile, where it is) –, else the + /// first cold one; None: nothing to take now. + fn take(&mut self) -> Option<(Arc, bool)> { + let out = self.big_out; + if let Some(i) = self.first.iter().position(|p| !(out && big_by_size(p))) { + let p = self.first.remove(i)?; + let big = big_by_size(&p); + self.big_out |= big; + return Some((p, big)); + } + self.rest.pop_front().map(|p| (p, false)) + } +} + +thread_local! { + /// (a worker) the queue whose turn at a big compute pipeline of tier 1 it holds now (`BigTurn`) + static TURN: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// A worker's turn at a big compute pipeline of tier 1 (`Tiers::take`), held from the take: given +/// back by its build once past its wait for commit (`commit_wait_over`) – else when dropped, at the +/// end of that pipeline's turn (refused, failed before, passed over, rerouted; also on unwind). +struct BigTurn; + +impl BigTurn { + fn hold(w: &'static Workers) -> BigTurn { + TURN.with(|t| t.set(Some(w))); + BigTurn + } +} + +impl Drop for BigTurn { + fn drop(&mut self) { + commit_wait_over(); + } +} + +/// (real: a compute pipeline's build past its wait for 3 GiB of commit, or where that wait would be) +/// The worker that builds it gives back its turn at a big compute pipeline of tier 1 – another may +/// wait for commit now – and the workers that wait look again. On any other thread, and once given +/// back: nothing. +pub fn commit_wait_over() { + // (`try_with`: it runs in the title's pipeline calls too – never a panic there) + if let Some(w) = TURN.try_with(|t| t.take()).ok().flatten() { + w.give_back(); + } +} + +impl Workers { + /// the turn at a big compute pipeline of tier 1 given back (`commit_wait_over`) + fn give_back(&self) { + self.lock().big_out = false; + self.cv.notify_all(); + } + + fn new() -> Workers { + Workers { q: Mutex::new(Tiers::default()), cv: Condvar::new(), threads: AtomicUsize::new(0), depth: AtomicUsize::new(0), by_tier: Default::default() } + } + + /// The queue (a leaf: nothing else is taken under it; a thread that panicked under it left + /// whole deques) + fn lock(&self) -> MutexGuard<'_, Tiers> { + self.q.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// `n` threads that build what is sent (`work`), named by `name`, with `stack` bytes each: the + /// threads there are now (`threads`). + fn start(&'static self, n: usize, name: impl Fn(usize) -> String, stack: usize) -> usize { + for k in 0..n { + if std::thread::Builder::new().name(name(k)).stack_size(stack).spawn(move || work(self)).is_ok() { + self.threads.fetch_add(1, Ordering::AcqRel); + } + } + self.threads.load(Ordering::Acquire) + } + + /// `p` (in tier `tier`) counted into the queue's depths – or out of them (`!into`) + fn count(&self, p: &Pending, tier: u8, into: bool) { + let by = &self.by_tier[(tier as usize).min(2)][p.compute as usize]; + if into { + self.depth.fetch_add(1, Ordering::Relaxed); + by.fetch_add(1, Ordering::Relaxed); + } else { + self.depth.fetch_sub(1, Ordering::Relaxed); + by.fetch_sub(1, Ordering::Relaxed); + } + } + + /// `p` to a worker, in tier `tier` (`tier_of`): counted, queued, a worker woken – or, with no + /// worker thread, given up as before 0023.2 (false): counted out again and its queued state + /// ended – a bind builds it, or goes on without it. + fn push(&self, p: &Arc, tier: u8) -> bool { + p.tier.store(tier, Ordering::Relaxed); + self.count(p, tier, true); + if self.threads.load(Ordering::Acquire) == 0 { + self.count(p, tier, false); + p.finish_queued(); + return false; + } + self.lock().push(p.clone(), tier); + // (after the push, outside the lock: a worker that found nothing waits by now – it looked + // and waited under the lock –, and one that has not looked yet will find it) + self.cv.notify_one(); + true + } + + /// The next pipeline to build (`Tiers::take`), waiting for one; counted out of the queue. + fn next(&self) -> (Arc, bool) { + let mut g = self.lock(); + let taken = loop { + if let Some(t) = g.take() { + break t; + } + g = self.cv.wait(g).unwrap_or_else(PoisonError::into_inner); + }; + drop(g); + self.count(&taken.0, taken.0.tier.load(Ordering::Relaxed), false); + taken + } + + /// (tests) `next` without waiting: None when nothing can be taken now + #[cfg(test)] + fn try_next(&self) -> Option<(Arc, bool)> { + let taken = self.lock().take()?; + self.count(&taken.0, taken.0.tier.load(Ordering::Relaxed), false); + Some(taken) + } + + /// (the queue line) waiting: `[tier][compute]` + fn depths(&self) -> [[usize; 2]; 3] { + self.by_tier.each_ref().map(|t| t.each_ref().map(|n| n.load(Ordering::Relaxed))) + } +} + +/// A worker: builds what the queue gives it, for good – as before 0023.2 once it has one: a big +/// one the ledger no longer trusts goes to the big lane (`rerouted`), one a bind took is passed over. +fn work(w: &'static Workers) { + loop { + let (p, big) = w.next(); + let _turn = big.then(|| BigTurn::hold(w)); + // a big one the ledger knew when it was sent, not trusted since: the big lane's + if rerouted(&p) { + continue; + } + // (None: a bind took it and builds it itself) + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + let _held = mark(crate::waitwatch::X_BUILD_WORKER, &p); + run(&p, job, Builder::Worker); + } + } +} + +static WORKERS: OnceLock = OnceLock::new(); + +/// The workers' queue, its threads started at the first call: `compile_threads()` of them, +/// `xcl-pso-k` (translation recurses deeply on big programs: 64 MiB stacks; DXC itself runs on its +/// own pool). +fn workers() -> &'static Workers { + let w = WORKERS.get_or_init(Workers::new); + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + w.start(crate::gpu::recomp::dxc::compile_threads(), |k| format!("xcl-pso-{k}"), 64 << 20); + }); + w +} + +/// `XCL_PSO_TIERS` (on unless `0`): the workers' queue in tiers (`Workers`); `0`: one queue in the +/// order sent, as before 0023.2 – and with it A3's one-at-a-time turn for big tier-1 pipelines goes +/// too (`Tiers::big_out`): every worker may again sit in `real::wait_for_commit`, as before. Read once, +/// by `host_main` before the title runs (no title call reads the environment for it). +pub fn tiers_on() -> bool { + static T: OnceLock = OnceLock::new(); + *T.get_or_init(|| std::env::var("XCL_PSO_TIERS").map_or(true, |v| v.trim() != "0")) +} + +/// `p`'s tier in the workers' queue, when it is sent (`send`, outside every lock: a translation's +/// header may be read): `tier_with` this run's switch, ledger and translation cache. A tier set at +/// send only orders builds – it never decides whether, by whom or how long a bind waits. +fn tier_of(p: &Pending) -> u8 { + tier_with(&p.prog, tiers_on(), built::known, crate::gpu::recomp::pso::translated_by_hash) +} + +/// (pure) The tier of a pipeline of `prog`, with `on` (`tiers_on`), the ledger's `known` and the +/// translation cache's static samplers by program hash (`by_hash`, `pso::translated_by_hash`): +/// `TIER_KNOWN` when the ledger knows it (D3DMetal has it – a graphics one's key is its shaders +/// only, so one with other fixed-function state may still be a full driver compile); else +/// `TIER_TRANSLATED` when its translations are on disk – said so when it was made, or found now: a +/// CS (also one not found when made), or a VS and its console PS, the PS by the sampler base its +/// VS's static samplers give it (as `real::translated_graphics_pso` translates it) –; else +/// `TIER_COLD`, as everything with `on` false and a pipeline with no program (`submit`: no disk +/// read). +fn tier_with(prog: &Program, on: bool, known: impl Fn(u64) -> bool, by_hash: impl Fn(u64, Stage, u32, bool) -> Option) -> u8 { + if !on { + return TIER_COLD; + } + if known(prog.key) { + return TIER_KNOWN; + } + let [a, b] = prog.shaders; + let on_disk = match (prog.kind, prog.translated) { + (_, Some(true)) => true, + (b'C', _) => a != 0 && by_hash(a, Stage::Compute, 0, prog.split).is_some(), + (b'G', None) => a != 0 && by_hash(a, Stage::Vertex, 0, prog.split).is_some_and(|n| b == 0 || by_hash(b, Stage::Pixel, n, prog.split).is_some()), + _ => false, + }; + if on_disk { + TIER_TRANSLATED + } else { + TIER_COLD + } +} + +/// (a worker, at `p`'s turn) `p` is big and went where small ones go because the ledger knew it +/// (`routed_known`), and the ledger knows it no more – not trusted since it was sent +/// (`built::distrust`: D3DMetal's cache was cleared): it goes to the big lane, whose binds do not +/// wait for it, instead of compiling cold on a worker. A first world frame queues dozens of such +/// pipelines on the workers before the first three cold compiles end the trust; built there, they +/// were up to 3 cold big compiles beside the big lane's 2 and held every small pipeline back. True: +/// it went there. A job a bind took meanwhile stays that bind's; with no thread of the big lane, it +/// is built here – as a big one no run built (`bind_as_big`: not waited for). +fn rerouted(p: &Arc) -> bool { + if !(p.routed_known.load(Ordering::Acquire) && big_threads() > 0 && big_by_size(p) && !built::known(p.prog.key)) { + return false; + } + { + // (a bind that takes the job notes it under this lock: its LANE_HERE stays) + let job = p.job.lock().unwrap(); + if job.is_none() { + return false; + } + p.routed_known.store(false, Ordering::Release); + p.lane.store(LANE_BIG, Ordering::Release); + } + if !big_lane().push(p, used::known(p.prog.key)) { + p.lane.store(LANE_WORKERS, Ordering::Release); + return false; + } + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + crate::xlog_info!("[pso] {} went to a worker as one an earlier run built – the ledger is not trusted since: built on the big lane instead (#{n})", name(p)); + } + true +} + +/// `p` to be built (its `sent` just set): the big lane for a big compute pipeline no run built +/// (`big`, one an earlier run used first), the workers for any other – or for a big one when the +/// big lane has no thread –, in its tier there (`tier_of`). +fn send(p: &Arc) { + // (None: a bind took it and builds it itself) + if p.job.lock().unwrap().is_none() { + return; + } + p.note_queued(); + if route(p, LANE_WORKERS) == LANE_BIG { + if big_lane().push(p, used::known(p.prog.key)) { + return; + } + p.lane.store(LANE_WORKERS, Ordering::Release); + } + // (outside every lock: its tier may read a translation's header) + let tier = tier_of(p); + workers().push(p, tier); +} + +/// The big lane: compute pipelines of `BIG_DXIL` or more that no run built (`big`), on +/// `big_threads()` threads `xcl-pso-big-k` of their own, below normal priority +/// (XCL_PSO_BIG_LOW=0: normal). One whose shaders an earlier run used goes first (D3DMetal may +/// have it: milliseconds). A clone of a program the lane builds now waits for that build, then +/// goes to the workers – D3DMetal has it by then (a retail title made 14 big compute pipelines +/// twice while loading). +struct BigLane { + q: Mutex, + cv: Condvar, + /// threads started (0: none could be – `send` uses the workers) + threads: AtomicUsize, +} + +#[derive(Default)] +struct BigQueue { + /// waiting: those an earlier run used, then the others + first: VecDeque>, + rest: VecDeque>, + /// the programs (`Program::key`) being built on the lane now, and clones waiting for them + building: HashSet, + parked: HashMap>>, + parked_n: usize, +} + +static BIG: OnceLock = OnceLock::new(); + +fn big_lane() -> &'static BigLane { + let lane = BIG.get_or_init(|| BigLane { q: Mutex::new(BigQueue::default()), cv: Condvar::new(), threads: AtomicUsize::new(0) }); + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let n = big_threads(); for k in 0..n { - let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { - let next = rx.lock().unwrap().recv(); - let Ok(p) = next else { return }; - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - complete(&p, job()); + // translation recurses deeply on big programs (as the workers') + if std::thread::Builder::new().name(format!("xcl-pso-big-{k}")).stack_size(64 << 20).spawn(move || big_worker(lane)).is_ok() { + lane.threads.fetch_add(1, Ordering::Relaxed); + } + } + match lane.threads.load(Ordering::Relaxed) { + 0 => crate::xlog_warn!("D3D12.X: no thread of the big lane could be started: big compute pipelines go to the other workers"), + m => crate::xlog_info!( + "D3D12.X: compute pipelines with {} KB of DXIL or more that no run built yet are built on {m} threads of their own (xcl-pso-big-k, XCL_PSO_BIG_THREADS){}; a bind waits {} ms for one (XCL_PSO_WAIT_BIG_MS) and goes on without it until it is built", + BIG_DXIL >> 10, + if big_low() { " below normal priority" } else { "" }, + wait_big().as_millis() + ), + } + }); + lane +} + +fn big_worker(lane: &'static BigLane) { + if big_low() { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL}; + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) }; + } + loop { + let p = lane.pop(); + // (None: taken meanwhile – a clone re-sent, say) + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + let _held = mark(crate::waitwatch::X_BUILD_BIG, &p); + run(&p, job, Builder::Big); + } + lane.done_with(&p); + } +} + +impl BigLane { + /// `p` queued (`first`: an earlier run used it); false when the lane has no thread. + fn push(&self, p: &Arc, first: bool) -> bool { + if self.threads.load(Ordering::Relaxed) == 0 { + return false; + } + { + let mut g = self.q.lock().unwrap(); + if first { + g.first.push_back(p.clone()) + } else { + g.rest.push_back(p.clone()) + } + } + self.cv.notify_one(); + true + } + + /// The next to build: an orphan (released by the title meanwhile) is not compiled for nobody + /// (`released` took it out of the building count); a clone of a program being built waits + /// for that build (`done_with`). + fn pop(&self) -> Arc { + let mut g = self.q.lock().unwrap(); + loop { + while let Some(p) = g.first.pop_front().or_else(|| g.rest.pop_front()) { + if p.orphan.load(Ordering::Acquire) { + continue; } - }); + let key = p.prog.key; + if key != 0 && g.building.contains(&key) { + g.parked.entry(key).or_default().push(p); + g.parked_n += 1; + continue; + } + if key != 0 { + g.building.insert(key); + } + return p; + } + g = self.cv.wait(g).unwrap(); } - Mutex::new(tx) - }) + } + + /// `p`'s build is over: the clones that waited for it go where `send` puts them – the + /// workers once it is built (the ledger knows it now), the big lane (first) when it failed. + fn done_with(&self, p: &Arc) { + let key = p.prog.key; + if key == 0 { + return; + } + let parked = { + let mut g = self.q.lock().unwrap(); + g.building.remove(&key); + let v = g.parked.remove(&key).unwrap_or_default(); + g.parked_n -= v.len(); + v + }; + for c in parked.into_iter().filter(|c| !c.orphan.load(Ordering::Acquire)) { + send(&c); + } + } + + fn depth(&self) -> usize { + let g = self.q.lock().unwrap(); + g.first.len() + g.rest.len() + g.parked_n + } } /// Release a pipeline state XCL owns (raw pointer, 0 = none). @@ -130,7 +840,7 @@ pub fn release(p: usize) { /// `standin` went to the title; `job` builds the real pipeline on a worker. pub fn submit(standin: usize, compute: bool, job: Job) { - submit_as(standin, compute, job, true, 0); + submit_as(standin, compute, Some(job), true, 0, Program::default()); } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get @@ -146,40 +856,49 @@ pub fn lazy() -> bool { /// `submit`, sent to the workers only on its first `resolve` (`lazy`) – or now, at a low /// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`). pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { - submit_as(standin, compute, job, false, key); -} - -fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { - let p = Arc::new(Pending { - job: Mutex::new(Some(job)), - sent: std::sync::atomic::AtomicBool::new(send), - queued: AtomicU8::new(STATE_IDLE), - real: AtomicUsize::new(0), - done: Mutex::new(false), - cv: Condvar::new(), - compute, - key, - used: Default::default(), - orphan: Default::default(), - late: Default::default(), - }); + submit_as(standin, compute, Some(job), false, key, Program::default()); +} + +/// `submit` (`lazy`: `submit_lazy` with `used_key`) of a pipeline built from `prog` +/// (`real::go_background`). +pub fn submit_program(standin: usize, compute: bool, job: Job, lazy: bool, used_key: u64, prog: Program) { + submit_as(standin, compute, Some(job), !lazy, used_key, prog); +} + +/// `standin` went to the title for a pipeline that is never built (`real::refusal`): its entry +/// is done at once with no real pipeline – never queued nor waited for, counted as failed (and +/// its program as refused) – and `bind` skips its work (its stand-in, not built). +pub fn submit_refused(standin: usize, compute: bool, used_key: u64, prog: Program) { + let p = submit_as(standin, compute, None, false, used_key, prog); + complete(&p, 0); +} + +fn submit_as(standin: usize, compute: bool, job: Option, now: bool, key: u64, prog: Program) -> Arc { + let refused = job.is_none(); + let p = Arc::new(Pending::new(standin, compute, job, now, key, prog)); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); + // (the ledger read now, on a creating thread: its line before the world loads) + built::touch(); }); - if send { - p.note_queued(); - if let Err(e) = queue().lock().unwrap().send(p) { - e.0.finish_queued(); - } - } else if used::known(key) { + if refused { + return p; + } + if now { + send(&p); + } else if used::known(key) && !big(&p) { + // a big one no run built is left to its first bind (the big lane): the threads that build + // ahead run at the lowest priority outside `real::BIG_COMPILES` if let Some(q) = preload() { + route(&p, LANE_AHEAD); p.note_queued(); - q.list.lock().unwrap().push_back(p); + q.list.lock().unwrap().push_back(p.clone()); q.cv.notify_one(); } } + p } /// The pipelines a title used, by a hash of their shaders, kept between runs @@ -193,7 +912,6 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { /// this and 94 – 150 with it. mod used { use std::collections::HashSet; - use std::io::Write; use std::sync::{Mutex, OnceLock, RwLock}; struct Used { @@ -216,7 +934,11 @@ mod used { let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); if !earlier.is_empty() { - crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); + if super::preload_on() { + crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); + } else { + crate::xlog_info!("D3D12.X: {} shader sets an earlier run used are known; none is built ahead (XCL_PSO_PRELOAD=0)", earlier.len()); + } } if let Some(dir) = path.parent() { let _ = std::fs::create_dir_all(dir); @@ -239,7 +961,7 @@ mod used { let mut g = get().now.lock().unwrap(); if g.0.insert(key) { if let Some(f) = g.1.as_mut() { - let _ = writeln!(f, "{key:016x}"); + super::built::append(f, key); } } } @@ -256,70 +978,318 @@ mod used { } } -/// The workers that build the pipelines of an earlier run ahead of their first use -/// (`XCL_PSO_PRELOAD=0`: off). Apart from the ones a bind sends to (`queue`) and at the lowest -/// priority: a pipeline that is bound is not held up by the ones made ahead (whoever takes -/// `job` first builds it), and the title's own threads are not either. -struct Preload { - list: Mutex>>, - cv: Condvar, -} +/// The pipelines built so far, by the hash of their shaders (`Program::key`), kept between runs +/// (`built-pipelines-.txt` beside the DXIL cache, a key a line). Not +/// `used`: a pipeline is used at its first bind and built when the driver's compile of it came +/// back – run 64 bound 56c0cd3b82a00c6e and b7a408ccdd229979 and never had them. A big compute +/// pipeline in here is sent and waited for like a small one (D3DMetal answers it from its own +/// cache, which survives the process: 2e0055c25f49848a 14 166 ms in run 63, 11 ms in run 64); one +/// not in here goes to the big lane. Another translator identity (other DXIL) has a ledger of its +/// own. `XCL_PSO_BUILT_SEED=` adds keys for this run, never written. Three big ones it knew +/// that took the driver 2 s or more (not counting the process frozen) mean D3DMetal's cache was +/// cleared (a macOS or CrossOver update): from then on only this run's builds count, and the file +/// starts again from them (the old one kept as `.stale`). `XCL_PSO_BUILT_LEDGER=0`: no ledger. +mod built { + use std::collections::HashSet; + use std::io::Write; + use std::path::{Path, PathBuf}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Mutex, OnceLock, RwLock}; -fn preload() -> Option<&'static Preload> { - static Q: OnceLock> = OnceLock::new(); - static STARTED: std::sync::Once = std::sync::Once::new(); - let q = Q - .get_or_init(|| { - if std::env::var("XCL_PSO_PRELOAD").is_ok_and(|v| v.trim() == "0") { - return None; - } - Some(Preload { list: Mutex::new(Default::default()), cv: Condvar::new() }) - }) - .as_ref()?; - STARTED.call_once(|| { - let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); - for k in 0..n { - let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { - unsafe { - use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + /// misses after which the ledger is not trusted for the run + pub(super) const MISS_LIMIT: usize = 3; + + pub(super) struct Ledger { + /// trusted: the file's keys and this run's builds + keys: RwLock>, + /// XCL_PSO_BUILT_SEED's keys (until the ledger is not trusted) + seed: HashSet, + seed_on: AtomicBool, + /// this run's builds and the file they go to + now: Mutex, + misses: AtomicUsize, + trusted: AtomicBool, + } + + struct Now { + keys: HashSet, + file: Option, + path: Option, + } + + /// The keys of a ledger: whole lines of 16 hexadecimal digits (a cut line, a stray one and 0 + /// are passed over). + pub(super) fn parse(text: &str) -> HashSet { + text.lines() + .map(str::trim) + .filter(|l| l.len() == 16) + .filter_map(|l| u64::from_str_radix(l, 16).ok()) + .filter(|&k| k != 0) + .collect() + } + + /// `key` as a line, in one write (a process ended meanwhile cuts no line in two) + pub(super) fn append(f: &mut std::fs::File, key: u64) { + let _ = f.write_all(format!("{key:016x}\n").as_bytes()); + } + + impl Ledger { + /// The ledger at `path` (None: no file), and `seed`. A last line without its end (a run + /// ended in a write) is ended first, so the next key is not glued to it. + pub(super) fn open_in(path: Option<&Path>, seed: HashSet) -> Ledger { + let text = path.and_then(|p| std::fs::read_to_string(p).ok()).unwrap_or_default(); + let keys = parse(&text); + let file = path.and_then(|p| { + if let Some(dir) = p.parent() { + let _ = std::fs::create_dir_all(dir); } - static DONE: AtomicUsize = AtomicUsize::new(0); - loop { - let p = { - let mut g = q.list.lock().unwrap(); - loop { - if let Some(p) = g.pop_front() { - break p; - } - g = q.cv.wait(g).unwrap(); - } - }; - // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { - p.finish_queued(); - continue; - } - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - let real = job(); - complete(&p, real); - let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); - } - } + let mut f = std::fs::OpenOptions::new().create(true).append(true).open(p).ok()?; + if !text.is_empty() && !text.ends_with('\n') { + let _ = f.write_all(b"\n"); } + Some(f) }); + Ledger { + keys: RwLock::new(keys), + seed, + seed_on: AtomicBool::new(true), + now: Mutex::new(Now { keys: HashSet::new(), file, path: path.map(Path::to_path_buf) }), + misses: AtomicUsize::new(0), + trusted: AtomicBool::new(true), + } } - }); - Some(q) -} -#[cfg(test)] -mod used_tests { - use super::*; + pub(super) fn known(&self, key: u64) -> bool { + key != 0 && (self.keys.read().unwrap().contains(&key) || (self.seed_on.load(Ordering::Relaxed) && self.seed.contains(&key))) + } + + /// `key` built in this run: in this run's set always (a rewrite when the ledger is not + /// trusted lists them all, `distrust`), and a line of the file only when the file's keys + /// do not hold it already – run 66 wrote 1,284 lines for 692 keys, every rebuild of a key + /// an earlier run built once more. (A seed key built now is written: the seed is apart.) + pub(super) fn note(&self, key: u64) { + if key == 0 { + return; + } + let mut now = self.now.lock().unwrap(); + if now.keys.insert(key) && self.keys.write().unwrap().insert(key) { + if let Some(f) = now.file.as_mut() { + append(f, key); + } + } + } + + pub(super) fn missed(&self, what: &str, took: std::time::Duration) { + let n = self.misses.fetch_add(1, Ordering::Relaxed) + 1; + crate::xlog_warn!("[pso] {what} took {} ms in the driver though a run built it before – not a D3DMetal cache hit ({n} of {MISS_LIMIT})", took.as_millis()); + if n == MISS_LIMIT { + self.distrust(); + } + } + + /// Only this run's builds count from now on; the file starts again from them. + fn distrust(&self) { + let mut now = self.now.lock().unwrap(); + *self.keys.write().unwrap() = now.keys.clone(); + self.seed_on.store(false, Ordering::Relaxed); + self.trusted.store(false, Ordering::Relaxed); + let mut kept = String::new(); + if let Some(path) = now.path.clone() { + now.file = None; + let stale = path.with_extension("txt.stale"); + let _ = std::fs::remove_file(&stale); + if std::fs::rename(&path, &stale).is_ok() { + kept = format!(" (the old one kept as {})", stale.file_name().unwrap_or_default().to_string_lossy()); + } + now.file = std::fs::OpenOptions::new().create(true).write(true).truncate(true).open(&path).ok(); + let lines: String = now.keys.iter().map(|k| format!("{k:016x}\n")).collect(); + if let Some(f) = now.file.as_mut() { + let _ = f.write_all(lines.as_bytes()); + } + } + crate::xlog_warn!( + "[pso] the built-pipelines ledger is not trusted for the rest of the run ({MISS_LIMIT} big pipelines it knew were not D3DMetal cache hits – its cache cleared?): only this run's {} builds count as built; the file starts again from them{kept}", + now.keys.len() + ); + } + + pub(super) fn len(&self) -> usize { + self.keys.read().unwrap().len() + if self.seed_on.load(Ordering::Relaxed) { self.seed.len() } else { 0 } + } + } + + /// `XCL_PSO_BUILT_LEDGER` (on unless `0`) + pub(super) fn enabled() -> bool { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("XCL_PSO_BUILT_LEDGER").map_or(true, |v| v.trim() != "0")) + } + + fn get() -> &'static Ledger { + static L: OnceLock = OnceLock::new(); + L.get_or_init(|| { + // (a test neither reads nor writes the user's file) + if cfg!(test) { + return Ledger::open_in(None, HashSet::new()); + } + if !enabled() { + crate::xlog_info!("D3D12.X: XCL_PSO_BUILT_LEDGER=0: no compute pipeline counts as built – every big one goes to the big lane"); + return Ledger::open_in(None, HashSet::new()); + } + let name = format!("built-pipelines-{:016x}.txt", crate::gpu::recomp::pso::translator_identity()); + let path = crate::gpu::recomp::dxc::cache_dir().join(&name); + let seed = match std::env::var("XCL_PSO_BUILT_SEED") { + Ok(p) if !p.trim().is_empty() => match std::fs::read_to_string(p.trim()) { + Ok(t) => { + let s = parse(&t); + crate::xlog_info!("D3D12.X: XCL_PSO_BUILT_SEED: {} pipelines counted as built for this run ({})", s.len(), p.trim()); + s + } + Err(e) => { + crate::xlog_warn!("D3D12.X: XCL_PSO_BUILT_SEED: {} not read ({e})", p.trim()); + HashSet::new() + } + }, + _ => HashSet::new(), + }; + let l = Ledger::open_in(Some(&path), seed); + let n = l.keys.read().unwrap().len(); + crate::xlog_info!("{}", ledger_line(&name, n, l.seed.len())); + l + }) + } + + /// The ledger's line (run65_events.sh reads its head, `D3D12.X: built-pipelines-.txt: `): + /// `n` keys in the file `name`, `seed` of XCL_PSO_BUILT_SEED – both count as built, so a big + /// compute pipeline of either is waited for like a small one and only the others go to the big + /// lane (a run with a seed and no file yet routes run 64's builds to the workers). + pub(super) fn ledger_line(name: &str, n: usize, seed: usize) -> String { + match (n, seed) { + (0, 0) => format!("D3D12.X: {name}: no pipeline an earlier run built yet – every big compute pipeline goes to the big lane until it is built (XCL_PSO_BUILT_LEDGER=0: no ledger)"), + (0, s) => format!("D3D12.X: {name}: no pipeline an earlier run built yet; XCL_PSO_BUILT_SEED's {s} count as built – a big compute one of them is waited for like a small one, any other goes to the big lane until it is built (XCL_PSO_BUILT_LEDGER=0: no ledger)"), + (n, 0) => format!("D3D12.X: {name}: {n} pipelines an earlier run built – a big compute one of them is waited for like a small one (XCL_PSO_BUILT_LEDGER=0: no ledger)"), + (n, s) => format!("D3D12.X: {name}: {n} pipelines an earlier run built, and XCL_PSO_BUILT_SEED's {s} count as built – a big compute one of them is waited for like a small one (XCL_PSO_BUILT_LEDGER=0: no ledger)"), + } + } + + /// (first pipeline) read now: the ledger's line early in the log + pub(super) fn touch() { + let _ = get(); + } + + pub(super) fn known(key: u64) -> bool { + enabled() && get().known(key) + } + + pub(super) fn note(key: u64) { + if enabled() { + get().note(key); + } + } + + pub(super) fn missed(what: &str, took: std::time::Duration) { + get().missed(what, took); + } + + /// (probe line) keys counted as built, and whether trusted + pub(super) fn state() -> (usize, bool) { + let l = get(); + (l.len(), l.trusted.load(Ordering::Relaxed)) + } + + #[cfg(test)] + pub(super) fn earlier_run_built(key: u64) { + get().keys.write().unwrap().insert(key); + } + + #[cfg(test)] + pub(super) fn misses() -> usize { + get().misses.load(Ordering::Relaxed) + } + + /// (tests) trusted again, no key, no miss + #[cfg(test)] + pub(super) fn reset_for_test() { + let l = get(); + let mut now = l.now.lock().unwrap(); + now.keys.clear(); + l.keys.write().unwrap().clear(); + l.misses.store(0, Ordering::Relaxed); + l.seed_on.store(true, Ordering::Relaxed); + l.trusted.store(true, Ordering::Relaxed); + } +} + +/// The workers that build the pipelines of an earlier run ahead of their first use +/// (`XCL_PSO_PRELOAD=0`: off). Apart from the ones a bind sends to (`queue`) and at the lowest +/// priority: a pipeline that is bound is not held up by the ones made ahead (whoever takes +/// `job` first builds it), and the title's own threads are not either. A big one no run built is +/// not theirs (`big`): it waits for its first bind, which sends it to the big lane. +struct Preload { + list: Mutex>>, + cv: Condvar, +} + +static PRELOAD: OnceLock> = OnceLock::new(); + +fn preload() -> Option<&'static Preload> { + static STARTED: std::sync::Once = std::sync::Once::new(); + let q = PRELOAD.get_or_init(|| preload_on().then(|| Preload { list: Mutex::new(Default::default()), cv: Condvar::new() })).as_ref()?; + STARTED.call_once(|| { + let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + for k in 0..n { + let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + } + static DONE: AtomicUsize = AtomicUsize::new(0); + loop { + let p = { + let mut g = q.list.lock().unwrap(); + loop { + if let Some(p) = g.pop_front() { + break p; + } + g = q.cv.wait(g).unwrap(); + } + }; + // (released by the title meanwhile) + if p.orphan.load(Ordering::Acquire) { + p.finish_queued(); + continue; + } + // big now (its size known since, or the ledger not trusted any more): the big lane's + if big(&p) { + if !p.sent.swap(true, Ordering::AcqRel) { + send(&p); + } + continue; + } + // (None: a bind took it and builds it itself) + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + let _held = mark(crate::waitwatch::X_BUILD_WORKER, &p); + run(&p, job, Builder::Ahead); + let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); + } + } + } + }); + } + }); + Some(q) +} + +/// Pipelines waiting to be built ahead (0 without preload: no threads are started to tell). +fn preload_depth() -> usize { + PRELOAD.get().and_then(|o| o.as_ref()).map_or(0, |q| q.list.lock().unwrap().len()) +} + +#[cfg(test)] +mod used_tests { + use super::*; /// A bind waits for a pipeline still being built no longer than its budget and goes on with /// the stand-in; later binds do not wait for it again; once built it is the real one. @@ -438,9 +1408,10 @@ mod used_tests { for i in 32..64 { assert_eq!(released(base + i), 0); } - if PENDING.lock().unwrap().as_ref().is_none_or(|m| m.is_empty()) { - assert_eq!(counts().2, 0); - } + // (no exact count of zero once this test's stand-ins are gone: the other tests – on 5 more + // threads – submit, queue and release theirs meanwhile, and `released` takes an entry out + // of PENDING before it takes it out of the count; an underflow shows above as 64 or more) + assert!(counts().2 < 64, "releasing every stand-in underflowed counts()"); } } @@ -454,16 +1425,16 @@ pub fn resolve(pso: usize) -> usize { p.note_use(); match p.real.load(Ordering::Acquire) { 0 => { - // a lazy one is wanted now: to the workers + // a lazy one is wanted now: to the workers (or the big lane) if p.queued.load(Ordering::Acquire) != STATE_DONE && !p.sent.swap(true, Ordering::AcqRel) { - p.note_queued(); - if let Err(e) = queue().lock().unwrap().send(p) { - e.0.finish_queued(); - } + send(&p); } pso } - r => r, + r => { + p.note_built_use(); + r + } } } @@ -473,69 +1444,478 @@ pub fn resolve_wait(pso: usize) -> usize { resolve_wait_for(pso, wait_budget()) } -/// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). -fn resolve_wait_for(pso: usize, budget: Option) -> usize { +/// `resolve_wait`, waiting at most `budget` and no longer than what is left of this thread's +/// frame (`resolve_within`, `frame`: `XCL_PSO_WAIT_FRAME_MS`) – or, with no budget (None: +/// `XCL_PSO_WAIT_MS` unset or 0), until the pipeline is built, built here when no worker has it, +/// as before 0023.1: the frame's budget neither cuts nor counts such a wait (a run without a limit +/// chose never to skip a draw for a pipeline). But a big one no run built `XCL_PSO_WAIT_BIG_MS` at +/// most (a wait with a limit: within the frame's budget too), and a late one not at all. +fn resolve_wait_for(pso: usize, budget: Option) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); + // built: no lock, no marker (every bind of a built pipeline comes here) + let real = p.real.load(Ordering::Acquire); + if real != 0 { + p.note_built_use(); + return real; + } + // big and no run built it: neither built here nor waited for longer than + // XCL_PSO_WAIT_BIG_MS, whatever the budget (run 64: thread 460 sat 434 s in one at its bind) + if bind_as_big(&p) { + return resolve_within(&p, pso, wait_big()); + } + // late: binds go on without it until it is built, whatever the budget (`bind` relies on it) + if p.late.load(Ordering::Acquire) && !*p.done.lock().unwrap() { + LATE_BINDS.fetch_add(1, Ordering::Relaxed); + return pso; + } if let Some(budget) = budget { return resolve_within(&p, pso, budget); } - let job = p.job.lock().unwrap().take(); + // no budget: built here, unless a worker has it already (a later bind does not send it again); + // waited for until built, whatever this thread's frame waited (`wait_frame`) + let job = { + let mut j = p.job.lock().unwrap(); + let job = j.take(); + if job.is_some() { + p.sent.store(true, Ordering::Release); + p.lane.store(LANE_HERE, Ordering::Release); + // (not `bind_as_big`: big by size means the ledger knew it) + if big_threads() > 0 && big_by_size(&p) { + p.routed_known.store(true, Ordering::Release); + } + } + job + }; if let Some(job) = job { p.note_queued(); - complete(&p, job()); + let _held = mark(crate::waitwatch::X_BUILD_HERE, &p); + run(&p, job, Builder::Here); } - let mut done = p.done.lock().unwrap(); - while !*done { - done = p.cv.wait(done).unwrap(); + if !*p.done.lock().unwrap() { + let _held = mark(crate::waitwatch::X_PIPELINE_WAIT, &p); + let mut done = p.done.lock().unwrap(); + while !*done { + done = p.cv.wait(done).unwrap(); + } } match p.real.load(Ordering::Acquire) { 0 => pso, - r => r, + r => { + p.note_built_use(); + r + } } } -/// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until -/// it is built). A retail game builds compute programs on its own threads: the driver takes up to -/// 30 s for the biggest translated ones, and the title's watchdog ends it when its main thread -/// has been held 30 s. -fn wait_budget() -> Option { - static B: OnceLock> = OnceLock::new(); - *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis)) +/// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: no limit +/// a wait – the binding thread builds the pipeline itself, or waits until a worker has built it). +/// A retail game builds compute programs on its own threads: the driver takes up to 30 s for the +/// biggest translated ones. The title's watchdog (GTA VI's, `eh::title_watchdog_resume`) does not +/// measure one wait but the render thread's frame: it ends the title when the heartbeat that +/// thread writes as it goes through a frame has not moved for 30 one-second checks – and a frame +/// binds many pipelines no run built one after another, each waited for up to this. All of a +/// thread's waits with this limit in a frame: `XCL_PSO_WAIT_FRAME_MS` (`frame`). With no limit a +/// bind waits until its pipeline is built, as before 0023.1: the frame's budget neither cuts nor +/// counts that wait (`resolve_wait_for`). +fn wait_budget() -> Option { + static B: OnceLock> = OnceLock::new(); + *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(Duration::from_millis)) +} + +/// `XCL_PSO_WAIT_FRAME_MS` (default 2000, at most 600000; 0: off): how long a thread's binds wait in +/// all between two Presents (`frame`) for pipelines they wait for with a limit – `XCL_PSO_WAIT_MS`'s +/// (`wait_budget`), a big one's (`wait_big`), a test's. Each such wait is bounded on its own, but a +/// frame binds many pipelines no run built one after another: in run 65's first world frame thread +/// 472 bound ~45 in a row, each waited for up to XCL_PSO_WAIT_MS=1500 – 27.5 s in all – and GTA VI's +/// watchdog, which ends the title when its render thread has not gone through a frame for 30 s, +/// fired. Once a thread's waits with a limit in a frame come to this, its binds that would wait +/// with a limit go on without a pipeline not built – it is sent to be built and goes late at once, +/// and stays skipped until it is built, in later frames too – and a wait that would pass it is cut +/// short. A bind with no limit (`XCL_PSO_WAIT_MS` unset or 0) still waits until its pipeline is +/// built: this budget neither cuts nor counts it, as before 0023.1. 2 s a recording thread stays +/// well under the watchdog's 30 s with several of them in a row. A frame ends where `frame::now` +/// moves: a title that never calls PresentX, run with XCL's window off (`present = "off"`), never +/// ends one – each of its threads has these 2 s once for the whole run. +fn wait_frame() -> Option { + static F: OnceLock> = OnceLock::new(); + *F.get_or_init(|| { + let ms = std::env::var("XCL_PSO_WAIT_FRAME_MS").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(2000).min(600_000); + (ms > 0).then(|| Duration::from_millis(ms)) + }) } -/// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a -/// pipeline not built by then is `late` – it and later binds of it get the stand-in (their -/// dispatches are skipped) until a worker has built it. -fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> usize { +/// `resolve_wait` for at most `budget` (zero: not at all) – a wait with a limit: `XCL_PSO_WAIT_MS`'s, +/// a big one's, a test's – and no longer than what is left of this thread's frame (`frame`), whose +/// budget the wait counts toward: the build goes to the workers or the big lane (not this thread), +/// and a pipeline not built by then is `late` – it and later binds of it get the stand-in (their +/// work is skipped) until it is built. +fn resolve_within(p: &Arc, pso: usize, budget: Duration) -> usize { let built = |p: &Pending| match p.real.load(Ordering::Acquire) { 0 => pso, - r => r, + r => { + p.note_built_use(); + r + } }; if *p.done.lock().unwrap() { return built(p); } if !p.sent.swap(true, Ordering::AcqRel) { - p.note_queued(); - if queue().lock().unwrap().send(p.clone()).is_err() { - p.finish_queued(); + send(p); + } + // (cut: the frame's budget left this wait shorter than `budget`, or none) + let (budget, cut) = frame::cap(budget); + if !p.late.load(Ordering::Acquire) && !budget.is_zero() { + let held = mark(crate::waitwatch::X_PIPELINE_WAIT, p); + let started = Instant::now(); + let (guard, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); + let done = *guard; + drop(guard); + drop(held); + frame::waited(started.elapsed()); + if done { + return built(p); } } - if p.late.load(Ordering::Acquire) { - return pso; + if !p.late.swap(true, Ordering::AcqRel) { + note_late(p, budget, cut); + frame::went_without(p, cut); } - let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); - if *done { - return built(p); + LATE_BINDS.fetch_add(1, Ordering::Relaxed); + pso +} + +/// What each thread's binds waited for pipelines with a limit in the frame it is in – at most +/// `XCL_PSO_WAIT_FRAME_MS` (`wait_frame`) – and, for the "no Present" line, the threads that +/// waited lately (`waits_since_present`). +mod frame { + use super::*; + + /// A thread's waits in one frame. + struct Waits { + /// the frame (`now`) the rest are of + frame: u64, + tid: u32, + /// waited in it, for so many pipelines (a wait each) + waited: Duration, + pipelines: u32, + /// pipelines its binds went on without in it (each when it went late), the first 4 named + without: u32, + named: Vec, + /// its budget spent: told (`went_without`) + told: bool, } - drop(done); - p.late.store(true, Ordering::Release); - 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: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far)", budget.as_millis(), n + 1); + + thread_local! { + static WAITS: RefCell = const { + RefCell::new(Waits { frame: 0, tid: 0, waited: Duration::ZERO, pipelines: 0, without: 0, named: Vec::new(), told: false }) + }; + } + + /// (tests) the frame a thread is in: the title's (`now`), one a test set (no other test's + /// Present moves it), or one a test moves from another thread + #[cfg(test)] + #[derive(Clone, Copy)] + enum TestFrame { + Title, + Fixed(u64), + Follow(&'static AtomicU64), + } + + #[cfg(test)] + thread_local! { + static TEST_FRAME: std::cell::Cell = const { std::cell::Cell::new(TestFrame::Title) }; + /// (tests) the line this thread's last spent budget was told with (logged or not) + static TOLD: RefCell> = const { RefCell::new(None) }; + /// (tests) each spent budget this thread told: its number (`SPENT`) and whether its line + /// was logged + static SPENT_TOLD: RefCell> = const { RefCell::new(Vec::new()) }; + } + + /// The frame a bind is in: the frame boundaries so far (`present::counters`: the title's PresentX + /// calls – and, before its first, the console queue methods XCL presents at when its window is + /// on) – or, while there are none, the frames XCL showed; the two kept apart (the top bit), so + /// that the first boundary always ends a frame. With XCL's window off (`present = "off"`) only + /// PresentX moves it. (Tests: a test's frame when it set one – `set_for_test`, `follow_for_test` + /// –, else this.) + pub(super) fn now() -> u64 { + #[cfg(test)] + match TEST_FRAME.with(|f| f.get()) { + TestFrame::Fixed(n) => return n, + TestFrame::Follow(epoch) => return epoch.load(Ordering::Acquire), + TestFrame::Title => {} + } + let (shown, boundaries) = super::super::present::counters(); + if boundaries > 0 { + boundaries | (1 << 63) + } else { + shown + } + } + + /// `f` on this thread's waits, those of an earlier frame let go first (None: the thread ends). + fn with(f: impl FnOnce(&mut Waits) -> R) -> Option { + let frame = now(); + WAITS + .try_with(|w| { + let mut w = w.try_borrow_mut().ok()?; + if w.frame != frame { + let tid = w.tid; + *w = Waits { frame, tid, waited: Duration::ZERO, pipelines: 0, without: 0, named: Vec::new(), told: false }; + } + if w.tid == 0 { + w.tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + } + Some(f(&mut w)) + }) + .ok() + .flatten() + } + + /// `budget` for a wait now: what is left of this thread's frame when that is less – and whether + /// it is (the frame cut the wait short, or left none). + pub(super) fn cap(budget: Duration) -> (Duration, bool) { + let Some(all) = wait_frame() else { return (budget, false) }; + with(|w| { + let left = all.saturating_sub(w.waited); + if budget > left { + (left, true) + } else { + (budget, false) + } + }) + .unwrap_or((budget, false)) + } + + /// A bind of this thread waited `d` for a pipeline (with a limit: `resolve_within`) – counted + /// for the frame it is in now: a wait a Present ended counts for the new frame. + pub(super) fn waited(d: Duration) { + with(|w| { + w.waited += d; + w.pipelines += 1; + publish(w); + }); + } + + /// A bind of this thread went on without `p`, late from now on; `cut`: because the frame's + /// budget was spent or cut its wait short. A thread's frame whose budget is spent is told once – + /// the first of all threads' such frames, then at powers of two (`SPENT`) –, and only when the + /// budget spent is this frame's: a cut wait a Present ended went to the new frame (`waited`), + /// whose budget it has not spent. + pub(super) fn went_without(p: &Pending, cut: bool) { + let line = with(|w| { + w.without += 1; + if w.named.len() < 4 { + w.named.push(name(p)); + } + publish(w); + if !cut || w.told || wait_frame().is_none_or(|all| w.waited < all) { + return None; + } + w.told = true; + static SPENT: AtomicUsize = AtomicUsize::new(0); + let n = SPENT.fetch_add(1, Ordering::Relaxed) + 1; + #[cfg(test)] + { + TOLD.with(|t| *t.borrow_mut() = Some(spent_line(w))); + SPENT_TOLD.with(|t| t.borrow_mut().push((n, false))); + } + spent_said(n).then(|| format!("{} (#{n})", spent_line(w))) + }) + .flatten(); + if let Some(l) = line { + crate::xlog_warn!("{l}"); + #[cfg(test)] + SPENT_TOLD.with(|t| { + if let Some(last) = t.borrow_mut().last_mut() { + last.1 = true; + } + }); + } + } + + /// The `n`th spent budget of all threads (from 1) is logged: the first, then at powers of two. + pub(super) fn spent_said(n: usize) -> bool { + n.is_power_of_two() + } + + /// "[pso] thread 472 waited 2001 ms for 2 pipelines since the last Present, + /// XCL_PSO_WAIT_FRAME_MS=2000: until the next Present its binds go on without a pipeline not + /// built, which stays skipped until it is built; without 2 so far: 8cfa1517f0f10047 (CS, 227 KB + /// of DXIL), …" (the run scripts read it up to "since the last Present") + fn spent_line(w: &Waits) -> String { + format!( + "[pso] thread {} waited {} ms for {} pipelines since the last Present, XCL_PSO_WAIT_FRAME_MS={}: until the next Present its binds go on without a pipeline not built, which stays skipped until it is built; without {} so far: {}{}", + w.tid, + w.waited.as_millis(), + w.pipelines, + wait_frame().map_or(0, |d| d.as_millis()), + w.without, + w.named.join(", "), + if w.without as usize > w.named.len() { ", …" } else { "" } + ) + } + + /// (thread, frame, waited, pipelines waited for, went on without) of the threads whose binds + /// waited lately, the 64 last (`publish`) + static LATELY: Mutex> = Mutex::new(Vec::new()); + + fn publish(w: &Waits) { + let e = (w.tid, w.frame, w.waited, w.pipelines, w.without); + keep(&mut LATELY.lock().unwrap_or_else(std::sync::PoisonError::into_inner), e); + } + + /// `e` in `lately` (`LATELY`'s rule): its thread's entry replaced, else added – 64 at most, the + /// thread that waited in the oldest frame let go for it. + pub(super) fn keep(lately: &mut Vec<(u32, u64, Duration, u32, u32)>, e: (u32, u64, Duration, u32, u32)) { + if let Some(x) = lately.iter_mut().find(|x| x.0 == e.0) { + *x = e; + return; + } + if lately.len() >= 64 { + // (the thread that waited in the oldest frame) + if let Some(i) = lately.iter().enumerate().min_by_key(|(_, x)| x.1).map(|(i, _)| i) { + lately.swap_remove(i); + } + } + lately.push(e); + } + + /// The threads whose binds waited for pipelines (or went on without one) in frame `frame`, the + /// `n` longest first: "thread 472 waited 27.5 s for 45 pipelines, thread 468 waited 2.0 s for + /// 3 pipelines and went on without 41" – "none" for none. + pub(super) fn waits_in(frame: u64, n: usize) -> String { + let mut v: Vec<(u32, Duration, u32, u32)> = LATELY + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .filter(|x| x.1 == frame && (x.3 > 0 || x.4 > 0)) + .map(|x| (x.0, x.2, x.3, x.4)) + .collect(); + v.sort_by(|a, b| b.1.cmp(&a.1)); + waits_text(&v[..v.len().min(n)]) + } + + /// (thread, waited, pipelines waited for, went on without) as `waits_in` says them + pub(super) fn waits_text(v: &[(u32, Duration, u32, u32)]) -> String { + if v.is_empty() { + return "none".into(); + } + let one = |&(tid, waited, pipelines, without): &(u32, Duration, u32, u32)| { + let also = if without > 0 { format!(" and went on without {without}") } else { String::new() }; + format!("thread {tid} waited {:.1} s for {pipelines} pipelines{also}", waited.as_secs_f64()) + }; + v.iter().map(one).collect::>().join(", ") + } + + /// (tests) this thread's frame is `n` from now on + #[cfg(test)] + pub(crate) fn set_for_test(n: u64) { + TEST_FRAME.with(|f| f.set(TestFrame::Fixed(n))); + } + + /// (tests) a Present: this thread's next frame + #[cfg(test)] + pub(crate) fn next_for_test() { + let n = now(); + TEST_FRAME.with(|f| f.set(TestFrame::Fixed(n + 1))); + } + + /// (tests) this thread's frame is `epoch`'s from now on: another thread moves it + #[cfg(test)] + pub(crate) fn follow_for_test(epoch: &'static AtomicU64) { + TEST_FRAME.with(|f| f.set(TestFrame::Follow(epoch))); + } + + /// (tests) each spent budget this thread told so far: its number and whether its line was logged + #[cfg(test)] + pub(crate) fn spent_told_for_test() -> Vec<(usize, bool)> { + SPENT_TOLD.with(|t| t.borrow().clone()) + } + + /// (tests) this thread's waits in its frame: (waited, pipelines waited for, went on without, its + /// budget's end told) + #[cfg(test)] + pub(crate) fn for_test() -> (Duration, u32, u32, bool) { + with(|w| (w.waited, w.pipelines, w.without, w.told)).unwrap() + } + + /// (tests) the thread id the waits are published under + #[cfg(test)] + pub(crate) fn tid_for_test() -> u32 { + with(|w| w.tid).unwrap() + } + + /// (tests) the line this thread's last spent budget was told with + #[cfg(test)] + pub(crate) fn told_for_test() -> Option { + TOLD.with(|t| t.borrow().clone()) + } +} + +/// (`host`'s "no Present" line) the threads whose binds waited for pipelines since the last +/// Present, the 4 longest: "thread 472 waited 27.5 s for 45 pipelines, …" – "none" for none. +pub fn waits_since_present() -> String { + frame::waits_in(frame::now(), 4) +} + +/// `p` went late (once): counted and named – a big one no run built in its own line (the first +/// 32, then every power of two), any other as before (the first 16, then powers of two), that +/// line ending with why when its thread's frame budget cut its wait (`cut`: `budget` is what the +/// frame left it). (The big one's line says nothing of the frame: with `XCL_PSO_WAIT_BIG_MS` 0, +/// the default, no frame cuts its wait.) +fn note_late(p: &Pending, budget: Duration, cut: bool) { + if bind_as_big(p) { + let n = WENT_LATE_BIG.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 32 || n.is_power_of_two() { + crate::xlog_info!("[pso] {} is big and no run built it ({}): its binds go on without it until it is built (#{n})", name(p), where_built(p)); + } + } else { + let n = WENT_LATE.fetch_add(1, Ordering::Relaxed); + // (one name for the line and the tests' record of it) + let named = late_name(p, cut); + if n < 16 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far) – {}", budget.as_millis(), n + 1, named); + } + #[cfg(test)] + LATE_NAMED.with(|l| *l.borrow_mut() = Some(named)); + } +} + +#[cfg(test)] +thread_local! { + /// (tests) what this thread's last `note_late` of a pipeline not big named (logged or not) + static LATE_NAMED: RefCell> = const { RefCell::new(None) }; +} + +/// (tests) what this thread's last `note_late` of a pipeline not big named, its why too – taken +#[cfg(test)] +pub(crate) fn late_named_for_test() -> Option { + LATE_NAMED.with(|l| l.borrow_mut().take()) +} + +/// The pipeline `note_late` names, and – when its thread's frame budget cut its wait – why +/// (after the name: what reads the line up to it reads it as before): "8cfa1517f0f10047 (CS, 227 +/// KB of DXIL) – its thread's frame budget (XCL_PSO_WAIT_FRAME_MS) cut the wait short". +fn late_name(p: &Pending, cut: bool) -> String { + let why = if cut { " – its thread's frame budget (XCL_PSO_WAIT_FRAME_MS) cut the wait short" } else { "" }; + format!("{}{why}", name(p)) +} + +fn where_built(p: &Pending) -> &'static str { + where_of(p.lane.load(Ordering::Acquire)) +} + +/// `where_built` of a pipeline sent to `lane` +fn where_of(lane: u8) -> &'static str { + match lane { + LANE_BIG => "on the big lane", + LANE_HERE => "on a binding thread", + LANE_WORKERS => "on a worker", + LANE_AHEAD => "ahead of its use", + _ => "not sent yet", } - pso } /// For binding: compute pipelines are waited for, graphics ones are not. @@ -568,7 +1948,2812 @@ pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) } -/// (built in the background, failed, still building) -pub fn counts() -> (usize, usize, usize) { - (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), BUILDING.load(Ordering::Relaxed)) +/// Who builds (`RUNNING`, the activity line's "building" counts). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[repr(u8)] +enum Builder { + Here = 0, + Worker = 1, + Big = 2, + Ahead = 3, +} + +impl Builder { + fn label(self) -> &'static str { + match self { + Builder::Here => "the binding thread", + Builder::Worker => "a worker", + Builder::Big => "the big lane", + Builder::Ahead => "building ahead", + } + } +} + +thread_local! { + /// the pipeline this thread builds now (`run`): `note_dxil`, `note_driver_time`, `note_refused` + static CURRENT: RefCell>> = const { RefCell::new(None) }; +} + +/// Builds `p` here with `job` (taken from it) as `who` – the caller holds the waits watch's +/// marker: in `RUNNING` while it runs, its result to `complete`. A panic in the build is a failed +/// build (a worker lives on; a binding thread does not unwind out of the title's call). +fn run(p: &Arc, job: Job, who: Builder) { + let started = Instant::now(); + running::add(p, who); + let before = CURRENT.with(|c| c.replace(Some(p.clone()))); + let real = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).unwrap_or_else(|_| { + crate::xlog_error!("[pso] the build of {} panicked: counted as failed", name(p)); + 0 + }); + CURRENT.with(|c| *c.borrow_mut() = before); + running::remove(p); + complete(p, real); + // (a refused one is never built: no failure – `FAILED` counts both) + if real == 0 && !p.refused.load(Ordering::Acquire) { + note_failed_build(p, who); + } + if who == Builder::Big { + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 256 || n % 16 == 0 { + crate::xlog_info!( + "[pso] {} {} on the big lane in {} ms ({} ms in the driver)", + name(p), + if real != 0 { "built" } else { "failed" }, + started.elapsed().as_millis(), + p.driver_ms.load(Ordering::Relaxed) + ); + } + } +} + +/// builds that ended with no pipeline though not refused (`note_failed_build`) +static FAILED_BUILDS: AtomicUsize = AtomicUsize::new(0); + +#[cfg(test)] +static FAILED_NAMED: Mutex> = Mutex::new(Vec::new()); + +/// `p`'s build by `who` ended with no pipeline, and it was not refused: a real failure – the +/// driver rejected it, its translation failed, it panicked –, named the first 16 times, then at +/// powers of two. `FAILED` also counts every refused stand-in (when the title makes it), and the +/// translation errors' own lines are full after 40 reasons (run 64: by 49 s): without this a +/// failure later in a run was named nowhere, and its work skipped as failed for the rest of it. +fn note_failed_build(p: &Pending, who: Builder) { + let line = failed_line(p, who); + #[cfg(test)] + FAILED_NAMED.lock().unwrap_or_else(|e| e.into_inner()).push((p.standin, line.clone())); + let n = FAILED_BUILDS.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + crate::xlog_warn!("{line} (#{n})"); + } +} + +/// "[pso] the build of 56c0cd3b82a00c6e (CS, 29059 KB of DXIL) failed (a worker)" +fn failed_line(p: &Pending, who: Builder) -> String { + format!("[pso] the build of {} failed ({})", name(p), who.label()) +} + +/// (tests) the failure line `note_failed_build` gave stand-in `standin`'s build (None: none) +#[cfg(test)] +fn failed_line_for_test(standin: usize) -> Option { + FAILED_NAMED.lock().unwrap_or_else(|e| e.into_inner()).iter().rev().find(|e| e.0 == standin).map(|e| e.1.clone()) +} + +/// The waits watch's marker for `kind`, naming `p`'s program (its stand-in when it has none). +/// (Inlined: the watch's frames start at the caller, as before 0023.) +#[inline(always)] +fn mark(kind: usize, p: &Pending) -> crate::waitwatch::Marker { + if p.prog.hash == 0 { + return crate::waitwatch::xcl(kind, p.standin as u64); + } + crate::waitwatch::xcl_program(kind, p.prog.hash, info(p)) +} + +fn info(p: &Pending) -> u64 { + crate::waitwatch::program_info(p.prog.kind, p.dxil.load(Ordering::Relaxed) >> 10, p.estimated.load(Ordering::Relaxed)) +} + +/// (real) The translation of the pipeline this thread builds has `len` bytes of DXIL: its size +/// from now on (later binds: `bind_as_big`; the names). Outside a build: nothing. +pub fn note_dxil(len: usize) { + CURRENT.with(|c| { + if let Some(p) = c.borrow().as_ref() { + p.dxil.store(len.min(u32::MAX as usize) as u32, Ordering::Relaxed); + p.estimated.store(false, Ordering::Relaxed); + // (a pipeline without a program is named by its stand-in there: `mark`) + if p.prog.hash != 0 { + crate::waitwatch::set_program_info(info(p)); + } + } + }); +} + +/// A driver compile under way, from `driver_clock` to its drop: counted (`IN_DRIVER`), timed. +pub struct DriverClock { + at: Instant, + frozen: u64, +} + +pub fn driver_clock() -> DriverClock { + let n = IN_DRIVER.fetch_add(1, Ordering::Relaxed) + 1; + IN_DRIVER_MOST.fetch_max(n, Ordering::Relaxed); + DriverClock { at: Instant::now(), frozen: frozen_ms() } +} + +impl Drop for DriverClock { + fn drop(&mut self) { + IN_DRIVER.fetch_sub(1, Ordering::Relaxed); + } +} + +#[cfg(test)] +impl DriverClock { + /// (tests) a compile that began `d` ago + pub fn ago(d: Duration) -> DriverClock { + let mut c = driver_clock(); + c.at = Instant::now().checked_sub(d).unwrap_or(c.at); + c + } +} + +/// driver time from which a big compile the ledger knew was not a D3DMetal cache hit (run 64: +/// hits 11 ms; 62 of the 67 cold compiles of 256 KB or more 2 s or longer) +const MISS_SLOW: Duration = Duration::from_secs(2); + +/// A routed-known compile to judge once the watch has counted any freeze meanwhile. +struct Judge { + name: String, + wall: Duration, + frozen_at: u64, +} + +static JUDGE: Mutex> = Mutex::new(Vec::new()); + +/// (real) The driver's compile of the pipeline this thread builds ended (`clock`: its start). +/// Its time is kept (the big lane's lines); a big one sent where small ones go because the +/// ledger knew it (`routed_known`; not one built ahead, at the lowest priority) is judged – +/// by the watch, after its next look, so that a freeze of the process during the compile is +/// counted out (run 64's sampler froze it 3 – 7 s every 15 s: an 11-ms hit would look slow). +pub fn note_driver_time(clock: &DriverClock) { + let wall = clock.at.elapsed(); + CURRENT.with(|c| { + let Some(p) = c.borrow().clone() else { return }; + p.driver_ms.store(wall.as_millis().min(u32::MAX as u128) as u32, Ordering::Relaxed); + if p.routed_known.load(Ordering::Acquire) && big_by_size(&p) && p.lane.load(Ordering::Acquire) != LANE_AHEAD { + let j = Judge { name: name(&p), wall, frozen_at: clock.frozen }; + if cfg!(test) { + judge(j, frozen_ms()); + } else { + JUDGE.lock().unwrap().push(j); + } + } + }); +} + +/// The driver time of `wall` with the process frozen `frozen` ms of it. +fn driver_time(wall: Duration, frozen: u64) -> Duration { + wall.saturating_sub(Duration::from_millis(frozen)) +} + +fn judge(j: Judge, frozen_now: u64) { + let took = driver_time(j.wall, frozen_now.saturating_sub(j.frozen_at)); + if took >= MISS_SLOW { + built::missed(&j.name, took); + } +} + +/// (real) Program `hash` (`what`: its stage) is refused (`why`): the entry this thread builds is +/// never built (not a failure); the first refusal of a program is logged. +pub fn note_refused(hash: u64, what: &str, why: &str) { + CURRENT.with(|c| { + if let Some(p) = c.borrow().as_ref() { + p.refused.store(true, Ordering::Release); + } + }); + { + let mut g = REFUSED.lock().unwrap(); + if g.contains(&hash) { + return; + } + g.push(hash); + } + REFUSED_PROGRAMS.fetch_add(1, Ordering::Relaxed); + crate::xlog_warn!("[pso] refused {hash:016x} ({why}, {what}): never built – its stand-in stays, what it does is not done"); +} + +static REFUSED: Mutex> = Mutex::new(Vec::new()); + +/// What a bind sees of stand-in `pso`, in one look (None: `pso` is no stand-in). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StandinState { + /// of a compute pipeline + pub compute: bool, + /// its real pipeline is there (`resolve` gives it from now on) + pub built: bool, + /// its build is over: built, failed or refused + pub done: bool, + /// binds go on without it until it is built (`late`) + pub late: bool, +} + +/// `StandinState` of `pso`: its entry is looked up once (PENDING is let go before `done` is +/// taken), so the fields belong together – a bind names why it holds a stand-in back by them. +pub fn standin_state(pso: usize) -> Option { + let p = entry(pso)?; + let done = *p.done.lock().unwrap(); + Some(StandinState { compute: p.compute, built: p.real.load(Ordering::Acquire) != 0, done, late: p.late.load(Ordering::Acquire) }) +} + +/// The console program stand-in `pso` was made for (None: not a stand-in, or one without a +/// program) – a look only: unlike `resolve`, it neither notes a use nor sends a lazy build. +pub fn program_hash(pso: usize) -> Option { + entry(pso).map(|p| p.prog.hash).filter(|&h| h != 0) +} + +/// (tests) Stand-in `standin`'s pipeline, sent to be built and never built while the test runs: +/// a bind with a budget waits for it the whole budget, then goes on without it – no worker is held +/// up for the other tests meanwhile. (A bind with no budget builds it here: no pipeline.) +#[cfg(test)] +pub(crate) fn submit_held_for_test(standin: usize, compute: bool, prog: Program) { + let p = Arc::new(Pending::new(standin, compute, Some(Box::new(|| 0)), true, 0, prog)); + PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p); +} + +/// (tests) `pso` is late, as after a wait past its budget. +#[cfg(test)] +pub(crate) fn make_late_for_test(pso: usize) { + if let Some(p) = entry(pso) { + p.late.store(true, Ordering::Release); + } +} + +/// The programs `note_skip` named (the first 32), with their skips. +struct Named { + seen: Vec<(u64, u64)>, +} + +impl Named { + /// `hash` skipped once more: its ordinal when it is one of the first 32 programs, named now. + fn first_time(&mut self, hash: u64) -> Option { + if let Some(e) = self.seen.iter_mut().find(|e| e.0 == hash) { + e.1 += 1; + return None; + } + (self.seen.len() < 32).then(|| { + self.seen.push((hash, 1)); + self.seen.len() + }) + } +} + +static SKIP_NAMES: Mutex = Mutex::new(Named { seen: Vec::new() }); + +/// Skips of every program (`note_skip`, PP3), by its hash – not only those of the first 32 named +/// (`Named`: all named by 150.7 s in run 66): `N` places, lock-free and allocation-free (the binds +/// that skip are the title's), a program in the place its hash gives or one of the next 64; one +/// that finds none free is counted apart (`others`). +struct SkipTable { + /// (hash, skips); hash 0: free + slots: [(AtomicU64, AtomicU64); N], + others: AtomicU64, +} + +impl SkipTable { + const fn new() -> Self { + SkipTable { slots: [const { (AtomicU64::new(0), AtomicU64::new(0)) }; N], others: AtomicU64::new(0) } + } + + /// `hash` skipped once more (0: no program – not counted). + fn note(&self, hash: u64) { + if hash == 0 { + return; + } + let at = (hash.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) as usize; + for k in 0..N.min(64) { + let (h, n) = &self.slots[(at + k) % N]; + let was = match h.load(Ordering::Acquire) { + 0 => h.compare_exchange(0, hash, Ordering::AcqRel, Ordering::Acquire).map_or_else(|other| other, |_| hash), + was => was, + }; + if was == hash { + n.fetch_add(1, Ordering::Relaxed); + return; + } + } + self.others.fetch_add(1, Ordering::Relaxed); + } + + /// The programs counted, and the `n` skipped most: (hash, skips), the most first (the same + /// number: the smaller hash first). + fn most(&self, n: usize) -> (usize, Vec<(u64, u64)>) { + let mut v: Vec<(u64, u64)> = self.slots.iter().map(|(h, k)| (h.load(Ordering::Acquire), k.load(Ordering::Relaxed))).filter(|&(h, k)| h != 0 && k > 0).collect(); + let programs = v.len(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + v.truncate(n); + (programs, v) + } + + /// "8cfa1517f0f10047 ×812, 0a1b… ×20 (2 programs)" – the `n` skipped most, of how many + /// programs (and the skips of those past the table's places when there are) – or "none". + fn text(&self, n: usize) -> String { + let (programs, v) = self.most(n); + let others = self.others.load(Ordering::Relaxed); + if v.is_empty() && others == 0 { + return "none".into(); + } + let list: Vec = v.iter().map(|(h, k)| format!("{h:016x} ×{k}")).collect(); + let past = if others > 0 { format!(", {others} skips of programs past its {N} places") } else { String::new() }; + format!("{} ({programs} programs{past})", list.join(", ")) + } +} + +/// Every program's skips (`SkipTable`): 4096 places (run 66 skipped the work of a few hundred +/// programs), 64 KiB. +static SKIPS: SkipTable<4096> = SkipTable::new(); + +/// The 8 programs skipped most of every program whose work was skipped (`SkipTable::text`) – the +/// `[waits]` pipelines line, the queue line and the end line say them. +fn skipped_most() -> String { + SKIPS.text(8) +} + +#[cfg(test)] +thread_local! { + /// (tests) the stand-in of this thread's last `note_skip` + static LAST_SKIP: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// (bind) Work of stand-in `pso` was skipped because its pipeline is not built – told at every +/// place `bind` skips such work, never for XCL's fallback pipelines (no stand-ins: they have no +/// entry here), so what is counted (`SKIPPED`) is `bind`'s skips less those of fallbacks. The +/// first 32 programs are named once each, with why; bind's tests read the stand-in of this +/// thread's last call (`take_last_skip`). +pub fn note_skip(pso: usize) { + #[cfg(test)] + LAST_SKIP.with(|c| c.set(Some(pso))); + SKIPPED.fetch_add(1, Ordering::Relaxed); + let Some(p) = entry(pso) else { return }; + if p.prog.hash == 0 { + return; + } + // (every program's, lock-free: PP3) + SKIPS.note(p.prog.hash); + let first = SKIP_NAMES.lock().unwrap().first_time(p.prog.hash); + if let Some(k) = first { + crate::xlog_info!("[pso] work of {} skipped: its pipeline {} (#{k} of the first 32 programs named)", name(&p), why_unbuilt(&p)); + } +} + +/// Work of a stand-in was skipped in this process (`note_skip`: its pipeline still building, late, +/// on the big lane, failed or refused): from then on GPU work may read what a skipped producer +/// left – `indirect::draw_check` checks translated draws' arguments in unified memory too then. +pub fn work_skipped() -> bool { + SKIPPED.load(Ordering::Relaxed) > 0 +} + +/// (tests) The stand-in this thread's `note_skip` was last told of, if told since the last call +/// (None: no skip, or a fallback's – those are not told). +#[cfg(test)] +pub(crate) fn take_last_skip() -> Option { + LAST_SKIP.with(|c| c.take()) +} + +fn why_unbuilt(p: &Pending) -> &'static str { + if p.refused.load(Ordering::Acquire) { + "was refused" + } else if *p.done.lock().unwrap() { + if p.real.load(Ordering::Acquire) != 0 { + "was built since" + } else { + "failed to build" + } + } else { + match p.lane.load(Ordering::Acquire) { + LANE_BIG => "is still being built on the big lane", + LANE_HERE => "is still being built on a binding thread", + _ if p.late.load(Ordering::Acquire) => "is still being built (late)", + _ => "is still being built", + } + } +} + +/// The `n` programs skipped most (of the first 32 named): "56c0cd3b82a00c6e ×812, …" (none: "none"). +pub fn most_skipped(n: usize) -> String { + let mut v = SKIP_NAMES.lock().unwrap().seen.clone(); + v.sort_by(|a, b| b.1.cmp(&a.1)); + let s: Vec = v.into_iter().take(n).map(|(h, k)| format!("{h:016x} ×{k}")).collect(); + if s.is_empty() { + "none".into() + } else { + s.join(", ") + } +} + +/// (tests) what the entry of `pso` is: (lane, sent, routed_known, refused) +#[cfg(test)] +pub(crate) fn state_for_test(pso: usize) -> Option<(u8, bool, bool, bool)> { + entry(pso).map(|p| (p.lane.load(Ordering::Acquire), p.sent.load(Ordering::Acquire), p.routed_known.load(Ordering::Acquire), p.refused.load(Ordering::Acquire))) +} + +struct Running { + p: Arc, + tid: u32, + since: Instant, + who: Builder, + /// `still_building_every()` steps logged + logged: u64, +} + +static RUNNING: Mutex> = Mutex::new(Vec::new()); + +mod running { + use super::*; + + pub(super) fn add(p: &Arc, who: Builder) { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + RUNNING.lock().unwrap().push(Running { p: p.clone(), tid, since: Instant::now(), who, logged: 0 }); + start_watch(); + } + + pub(super) fn remove(p: &Arc) { + let mut g = RUNNING.lock().unwrap(); + if let Some(i) = g.iter().position(|r| Arc::ptr_eq(&r.p, p)) { + g.swap_remove(i); + } + } +} + +/// the watch's tick, and how much later a look may come before the process counts as frozen +const WATCH_TICK: Duration = Duration::from_millis(250); +const FROZEN_SLACK: Duration = Duration::from_millis(500); + +/// ms the process stood still between two looks `gap` apart (a look 0.5 s late or more: +/// suspended from outside – run 64's sampler – or starved) +fn frozen_in(gap: Duration) -> u64 { + if gap > WATCH_TICK + FROZEN_SLACK { + (gap - WATCH_TICK).as_millis() as u64 + } else { + 0 + } +} + +/// The step of `every` a build that has run `elapsed` reached, when it is past `logged`. +fn due(elapsed: Duration, every: Duration, logged: u64) -> Option { + let steps = (elapsed.as_millis() / every.as_millis().max(1)) as u64; + (steps > logged).then_some(steps) +} + +fn still_building_line(p: &Pending, tid: u32, secs: u64, who: Builder) -> String { + if p.prog.hash == 0 { + return format!("[pso] still building {} on thread {tid} for {secs} s ({})", name(p), who.label()); + } + format!( + "[pso] still building {:016x} ({}, {}) on thread {tid} for {secs} s ({})", + p.prog.hash, + what(p.prog.kind), + size_text(p.dxil.load(Ordering::Relaxed), p.estimated.load(Ordering::Relaxed)), + who.label() + ) +} + +/// `xcl-pso-watch` (normal priority), every 250 ms: the time the process stood still +/// (`FROZEN_MS`); the driver times to judge (`JUDGE`); every 5 s, each build past another +/// XCL_PSO_STILL_BUILDING_S. Started at the first build when it has something to do; not in tests. +fn start_watch() { + if cfg!(test) || (still_building_every().is_none() && !(big_threads() > 0 && built::enabled())) { + return; + } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-pso-watch".into()).spawn(|| { + let mut last = Instant::now(); + for tick in 1u64.. { + std::thread::sleep(WATCH_TICK); + let gap = last.elapsed(); + last = Instant::now(); + FROZEN_MS.fetch_add(frozen_in(gap), Ordering::Relaxed); + // (after the freeze is counted: what a compile it overlapped really took) + let judge_now = std::mem::take(&mut *JUDGE.lock().unwrap()); + for j in judge_now { + judge(j, frozen_ms()); + } + let Some(every) = still_building_every().filter(|_| tick % 20 == 0) else { continue }; + let lines: Vec = { + let mut g = RUNNING.lock().unwrap(); + g.iter_mut() + .filter_map(|r| { + let el = r.since.elapsed(); + let steps = due(el, every, r.logged)?; + r.logged = steps; + Some(still_building_line(&r.p, r.tid, el.as_secs(), r.who)) + }) + .collect() + }; + for l in lines { + crate::xlog_warn!("{l}"); + } + } + }); + }); +} + +/// The builds running now, the longest first: "thread 460 building 56c0cd3b82a00c6e (CS, 29059 KB +/// of DXIL) for 25.3 s (the binding thread)" – the "no Present" line without the waits watch. +pub fn building() -> Vec { + let mut v: Vec<(Duration, String)> = RUNNING + .lock() + .unwrap() + .iter() + .map(|r| (r.since.elapsed(), format!("thread {} building {} for {:.1} s ({})", r.tid, name(&r.p), r.since.elapsed().as_secs_f64(), r.who.label()))) + .collect(); + v.sort_by(|a, b| b.0.cmp(&a.0)); + v.into_iter().map(|e| e.1).take(16).collect() +} + +/// (built in the background, failed, still building) +pub fn counts() -> (usize, usize, usize) { + (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), BUILDING.load(Ordering::Relaxed)) +} + +/// (diagnostics) the pipelines so far and now +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub struct Stats { + pub built: usize, + pub failed: usize, + /// programs refused (each once) + pub refused: usize, + pub went_late: usize, + pub went_late_big: usize, + pub late_binds: usize, + pub skipped: usize, + /// waiting: for the workers, on the big lane (clones parked there too), to be built ahead + pub queued: [usize; 3], + /// being built: on binding threads, by the workers, on the big lane, ahead (`Builder`) + pub building: [usize; 4], + /// compiles in the driver now, and the most at once so far + pub in_driver: usize, + pub in_driver_most: usize, +} + +pub fn stats() -> Stats { + let mut building = [0; 4]; + for r in RUNNING.lock().unwrap().iter() { + building[r.who as usize] += 1; + } + Stats { + built: BUILT.load(Ordering::Relaxed), + failed: FAILED.load(Ordering::Relaxed), + refused: REFUSED_PROGRAMS.load(Ordering::Relaxed), + went_late: WENT_LATE.load(Ordering::Relaxed), + went_late_big: WENT_LATE_BIG.load(Ordering::Relaxed), + late_binds: LATE_BINDS.load(Ordering::Relaxed), + skipped: SKIPPED.load(Ordering::Relaxed), + // (the workers' queue as it is: the activity thread never starts it) + queued: [WORKERS.get().map_or(0, |w| w.depth.load(Ordering::Relaxed)), BIG.get().map_or(0, BigLane::depth), preload_depth()], + building, + in_driver: IN_DRIVER.load(Ordering::Relaxed), + in_driver_most: IN_DRIVER_MOST.load(Ordering::Relaxed), + } +} + +/// (`host`'s activity thread, every 2 s) what the pipelines did since the last call – None when +/// nothing did and nothing waits or is being built. +pub fn activity_line() -> Option { + static LAST: Mutex> = Mutex::new(None); + let now = stats(); + let last = LAST.lock().unwrap().replace(now).unwrap_or_default(); + activity_text(&last, &now) +} + +fn activity_text(last: &Stats, now: &Stats) -> Option { + let d = |a: usize, b: usize| a.saturating_sub(b); + let (binds, skipped, built, failed) = (d(now.late_binds, last.late_binds), d(now.skipped, last.skipped), d(now.built, last.built), d(now.failed, last.failed)); + let late = d(now.went_late, last.went_late) + d(now.went_late_big, last.went_late_big); + if binds + skipped + built + failed + late == 0 && now.queued.iter().all(|&n| n == 0) && now.building.iter().all(|&n| n == 0) { + return None; + } + let [qw, qb, qa] = now.queued; + let [bh, bw, bb, ba] = now.building; + Some(format!( + "pipelines (2 s): {binds} late binds, {skipped} skipped (pipeline not built), {built} built, {failed} failed; queued {qw} + {qb} big + {qa} ahead; building {bw} + {bb} big + {bh} on binding threads + {ba} ahead, {} in the driver; so far {} built, {} failed, {} programs refused, {} + {} big late, {} skipped", + now.in_driver, now.built, now.failed, now.refused, now.went_late, now.went_late_big, now.skipped + )) +} + +/// (diagnostic `XCL_WATCH_WAITS`, the 30-s snapshot) – the prefix "pipelines: N built, N failed" +/// as before, every field as before; then the 8 programs skipped most of every one (PP3: `(most: +/// …)` names the first 32 programs only). +pub fn probe_line() -> String { + let sized = [SIZED.load(Ordering::Relaxed), ESTIMATED.load(Ordering::Relaxed)]; + probe_text(&stats(), built::state(), sized, frozen_ms() / 1000, &most_skipped(4), &skipped_most()) +} + +/// The `[waits]` pipelines line (`probe_line`) of `s`, the ledger's (keys, trusted), the pipelines +/// sized from the translation cache and estimated, the seconds the process stood still, the first 32 +/// named programs skipped most (`most4`) and the 8 programs skipped most of every one (`most`). +fn probe_text(s: &Stats, (keys, trusted): (usize, bool), [sized, estimated]: [usize; 2], frozen_s: u64, most4: &str, most: &str) -> String { + format!( + "pipelines: {} built, {} failed; {} programs refused, {} + {} big late ({} late binds), {} skipped (most: {}); queued {} + {} big + {} ahead, building {} + {} big + {} binding + {} ahead, {} in the driver (at most {} at once); sized from the translation cache {}, estimated {}; ledger {keys} keys{}; the process stood still {} s so far; skipped most of every program: {}", + s.built, + s.failed, + s.refused, + s.went_late, + s.went_late_big, + s.late_binds, + s.skipped, + most4, + s.queued[0], + s.queued[1], + s.queued[2], + s.building[1], + s.building[2], + s.building[0], + s.building[3], + s.in_driver, + s.in_driver_most, + sized, + estimated, + if trusted { "" } else { " (not trusted)" }, + frozen_s, + most + ) +} + +/// What the queue line (`queue_line`) counts, at one look. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +struct QueueStats { + /// the workers' queue: `[tier][compute]` (`Workers::depths`) + tiers: [[usize; 2]; 3], + /// DXC's compiles running now, and done so far (`dxc::compile_counts`: cache misses) + dxc: (usize, usize), + /// big compiles' waits for commit: [big lane, other pipeline threads] × (begun, ms, waiting + /// now) (`real::commit_waits`) + commit: [[u64; 3]; 2], + /// first uses of pipelines built in this run so far (MP4, `FIRST`) + first_uses: usize, +} + +fn queue_stats() -> QueueStats { + QueueStats { + tiers: WORKERS.get().map_or([[0; 2]; 3], Workers::depths), + dxc: crate::gpu::recomp::dxc::compile_counts(), + commit: super::real::commit_waits(), + first_uses: FIRST.n.load(Ordering::Relaxed), + } +} + +/// (`host`'s activity thread, right after the 2-s pipelines line and only when that is said – so +/// its deltas are since the last line said) the workers' queue by tier and kind, DXC's compiles, +/// big compiles' waits for commit, first uses, the programs skipped most (`queue_text`). +pub fn queue_line() -> String { + static LAST: Mutex> = Mutex::new(None); + let now = queue_stats(); + let last = LAST.lock().unwrap_or_else(PoisonError::into_inner).replace(now).unwrap_or_default(); + queue_text(&last, &now, &skipped_most()) +} + +/// "pipeline queue (2 s): workers' queue 3 known + 12 translated + 240 cold (230 graphics, 25 +/// compute); DXC compiles 1 running, 2 done (310 so far); big compiles waited for commit 0 ms on +/// the big lane (0 begun, 0 waiting now) and 1800 ms on the workers (1 begun, 1 waiting now), 31 +/// s so far; 4 first used with their built pipeline (688 so far); skipped most of every program: +/// …" – the queue as it is now, the rest since `last` (and so far), `most` the programs skipped +/// most. +fn queue_text(last: &QueueStats, now: &QueueStats, most: &str) -> String { + let d = |a: u64, b: u64| a.saturating_sub(b); + let [k, t, c] = now.tiers.map(|n| n[0] + n[1]); + let (g, u) = (now.tiers.iter().map(|n| n[0]).sum::(), now.tiers.iter().map(|n| n[1]).sum::()); + let [big, other] = now.commit; + let [lb, lo] = last.commit; + let all_ms = big[1] + other[1]; + format!( + "pipeline queue (2 s): workers' queue {k} known + {t} translated + {c} cold ({g} graphics, {u} compute); DXC compiles {} running, {} done ({} so far); big compiles waited for commit {} ms on the big lane ({} begun, {} waiting now) and {} ms on the workers ({} begun, {} waiting now), {} s so far; {} first used with their built pipeline ({} so far); skipped most of every program: {most}", + now.dxc.0, + now.dxc.1.saturating_sub(last.dxc.1), + now.dxc.1, + d(big[1], lb[1]), + d(big[0], lb[0]), + big[2], + d(other[1], lo[1]), + d(other[0], lo[0]), + other[2], + all_ms / 1000, + now.first_uses.saturating_sub(last.first_uses), + now.first_uses + ) +} + +/// (`real::end_title`, and when the title's entry point returns) "pipelines at the end: 689 built, +/// 12 failed, 20307 skipped (pipeline not built); skipped most of every program: …" – the counts +/// (atomics) and the skips' table (`SkipTable::text`: a copy, sorted and formatted on the heap). +pub fn end_line() -> String { + end_text(report_counts(), &skipped_most()) +} + +/// The end line (`end_line`) of `report_counts`' counts and the programs skipped most (`most`). +fn end_text(counts: [usize; 6], most: &str) -> String { + let [built, failed, _, _, _, skipped] = counts; + format!("pipelines at the end: {built} built, {failed} failed, {skipped} skipped (pipeline not built); skipped most of every program: {most}") +} + +/// A first use of a pipeline built in this run, as `note_first_use` records it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct FirstUse { + hash: u64, + standin: usize, + kind: u8, + dxil: u32, + estimated: bool, + /// where it was built (`LANE_*`) + lane: u8, + driver_ms: u32, + /// ms of the log's clock: when it was built, when used + built_ms: u64, + at_ms: u64, + /// the presents so far then (`present::counters`: the frames shown) + presents: u64, +} + +/// A place of `FirstUses`: written with atomics by the binding thread that claimed it, then `ready`. +struct Slot { + ready: AtomicBool, + hash: AtomicU64, + standin: AtomicUsize, + /// kind | lane << 8 | estimated << 16 | dxil << 32 + what: AtomicU64, + driver_ms: AtomicU32, + built_ms: AtomicU64, + at_ms: AtomicU64, + presents: AtomicU64, +} + +impl Slot { + const fn new() -> Slot { + Slot { + ready: AtomicBool::new(false), + hash: AtomicU64::new(0), + standin: AtomicUsize::new(0), + what: AtomicU64::new(0), + driver_ms: AtomicU32::new(0), + built_ms: AtomicU64::new(0), + at_ms: AtomicU64::new(0), + presents: AtomicU64::new(0), + } + } + + fn get(&self) -> FirstUse { + let w = self.what.load(Ordering::Relaxed); + FirstUse { + hash: self.hash.load(Ordering::Relaxed), + standin: self.standin.load(Ordering::Relaxed), + kind: w as u8, + lane: (w >> 8) as u8, + estimated: (w >> 16) & 1 != 0, + dxil: (w >> 32) as u32, + driver_ms: self.driver_ms.load(Ordering::Relaxed), + built_ms: self.built_ms.load(Ordering::Relaxed), + at_ms: self.at_ms.load(Ordering::Relaxed), + presents: self.presents.load(Ordering::Relaxed), + } + } +} + +/// The first uses of pipelines built in this run (MP4): the first `N` each in a place of its own, +/// the others counted only – what a memory sampler's look is set against (does a pipeline's +/// memory come with its build, or with its first run?). A use is told when a bind is first given +/// the real pipeline (`note_built_use`): in the frame whose submit runs it – a frame of run 66's +/// world took ~2.9 s, so the use may come that much before the GPU's – with no lock on the binding +/// thread (a submit-time record would need one on every list, and every resolve to know its list). +struct FirstUses { + /// first uses so far (those past `N` counted only) + n: AtomicUsize, + slots: [Slot; N], + /// (`lines`) places read so far, and whether the line of those past `N` was said + read: Mutex<(usize, bool)>, +} + +impl FirstUses { + const fn new() -> Self { + FirstUses { n: AtomicUsize::new(0), slots: [const { Slot::new() }; N], read: Mutex::new((0, false)) } + } + + /// `u` in the next place (past `N`: counted only) – written, then made ready. + fn note(&self, u: &FirstUse) { + let i = self.n.fetch_add(1, Ordering::AcqRel); + let Some(s) = self.slots.get(i) else { return }; + s.hash.store(u.hash, Ordering::Relaxed); + s.standin.store(u.standin, Ordering::Relaxed); + s.what.store(u.kind as u64 | (u.lane as u64) << 8 | (u.estimated as u64) << 16 | (u.dxil as u64) << 32, Ordering::Relaxed); + s.driver_ms.store(u.driver_ms, Ordering::Relaxed); + s.built_ms.store(u.built_ms, Ordering::Relaxed); + s.at_ms.store(u.at_ms, Ordering::Relaxed); + s.presents.store(u.presents, Ordering::Relaxed); + s.ready.store(true, Ordering::Release); + } + + /// The lines of the first uses not read yet, in their order – up to the first place claimed + /// and not ready yet (the next call goes on from there) – and, once all `N` are read, the one + /// that says those past them are counted only (when there are such). + fn lines(&self) -> Vec { + let mut r = self.read.lock().unwrap_or_else(PoisonError::into_inner); + let n = self.n.load(Ordering::Acquire); + let mut out = Vec::new(); + while r.0 < n.min(N) { + let s = &self.slots[r.0]; + if !s.ready.load(Ordering::Acquire) { + break; + } + r.0 += 1; + out.push(first_use_line(&s.get(), r.0)); + } + if n > N && r.0 == N && !r.1 { + r.1 = true; + out.push(format!("[pso] first uses of built pipelines past the first {N} are counted only (the pipeline queue line)")); + } + out + } + + /// (tests) the uses in the places so far, ready or not + #[cfg(test)] + fn recorded(&self) -> Vec { + self.slots[..self.n.load(Ordering::Acquire).min(N)].iter().map(Slot::get).collect() + } +} + +/// "[pso] first use of 8cfa1517f0f10047 (CS, 227 KB of DXIL) with its built pipeline at 152.371 s +/// (2321 presents so far): 2004 ms after its build (on a worker, 12 ms in the driver; #602)" +fn first_use_line(u: &FirstUse, n: usize) -> String { + format!( + "[pso] first use of {} with its built pipeline at {:.3} s ({} presents so far): {} ms after its build ({}, {} ms in the driver; #{n})", + name_of(u.hash, u.standin, u.kind, u.dxil, u.estimated), + u.at_ms as f64 / 1000.0, + u.presents, + u.at_ms.saturating_sub(u.built_ms), + where_of(u.lane), + u.driver_ms + ) +} + +/// This process's first uses (`FirstUses`): 1024 places – run 66 built 689 pipelines –, 64 KiB. +static FIRST: FirstUses<1024> = FirstUses::new(); + +#[cfg(test)] +thread_local! { + /// (tests) the stand-ins whose first use this thread told (`note_first_use`) + static FIRST_MINE: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// `p` was given to a bind built, the first time (`Pending::note_built_use`): recorded in `FIRST` +/// with atomics (a binding thread of the title's). +fn note_first_use(p: &Pending) { + FIRST.note(&FirstUse { + hash: p.prog.hash, + standin: p.standin, + kind: p.prog.kind, + dxil: p.dxil.load(Ordering::Relaxed), + estimated: p.estimated.load(Ordering::Relaxed), + lane: p.lane.load(Ordering::Acquire), + driver_ms: p.driver_ms.load(Ordering::Relaxed), + built_ms: p.built_ms.load(Ordering::Relaxed), + at_ms: now_ms(), + presents: super::present::counters().0, + }); + #[cfg(test)] + FIRST_MINE.with(|m| m.borrow_mut().push(p.standin)); +} + +/// (`host`'s activity thread, every 2 s, after the pipelines lines) the first uses of built +/// pipelines since the last call, a line each (1024 at most a process, then one that says the rest +/// are counted only). +pub fn first_use_lines() -> Vec { + FIRST.lines() +} + +/// (report.json, D's call: atomics only – the report is also written in the crash filter) +/// built, failed, programs refused, went late (small + big), late binds, skipped +pub fn report_counts() -> [usize; 6] { + [ + BUILT.load(Ordering::Relaxed), + FAILED.load(Ordering::Relaxed), + REFUSED_PROGRAMS.load(Ordering::Relaxed), + WENT_LATE.load(Ordering::Relaxed) + WENT_LATE_BIG.load(Ordering::Relaxed), + LATE_BINDS.load(Ordering::Relaxed), + SKIPPED.load(Ordering::Relaxed), + ] +} + +/// The big lane, the ledger, the lines. Fake stand-ins 0x7E57_A1xx – 0x7E57_AFxx (a block of 0x100 +/// a test; `real`'s refusal tests have 0x7E57_A0xx), keys 0x5EED_Axxx. A job that could outlive +/// its stand-in returns 0 (no Release of a fake pointer), and a stand-in is released only once it +/// is not pending. +#[cfg(test)] +pub(crate) mod lane_tests { + use super::*; + + /// tests that use the big lane or the global ledger: one at a time (they read the big lane's + /// depths and reset the ledger) + static LANES: Mutex<()> = Mutex::new(()); + + /// (lane tests, and any other test of the big lane or the ledger) `LANES`, held while the test + /// runs – None, with a SKIPPED line, when this run's switches leave the big lane out or change it + pub(crate) fn lanes() -> Option> { + if big_threads() == 0 || !wait_big().is_zero() || !lazy() || !built::enabled() { + crate::gpu::recomp::runner::skip_config("the big lane is off or changed (XCL_PSO_BIG_THREADS, XCL_PSO_WAIT_BIG_MS, XCL_LAZY_PSO, XCL_PSO_BUILT_LEDGER)"); + return None; + } + // (a failed lane test does not fail every later one) + Some(LANES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)) + } + + /// `built::reset_for_test` when dropped – also when an assertion unwinds + struct Fresh; + + impl Drop for Fresh { + fn drop(&mut self) { + built::reset_for_test(); + } + } + + /// A gate jobs wait at; opened when dropped – also when an assertion unwinds. + struct Gate(Arc<(Mutex, Condvar)>); + + impl Gate { + fn new() -> Gate { + Gate(Arc::new((Mutex::new(false), Condvar::new()))) + } + + /// waits until the gate is open, `limit` at most + fn waiter(&self, limit: Duration) -> impl Fn() + Send + 'static { + let g = self.0.clone(); + move || { + let (open, cv) = &*g; + let o = open.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _ = cv.wait_timeout_while(o, limit, |o| !*o); + } + } + + fn open(&self) { + let (open, cv) = &*self.0; + *open.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true; + cv.notify_all(); + } + } + + impl Drop for Gate { + fn drop(&mut self) { + self.open(); + } + } + + /// `cond` within `limit`, looked at every 5 ms + fn poll(limit: Duration, cond: impl Fn() -> bool) -> bool { + let start = Instant::now(); + loop { + if cond() { + return true; + } + if start.elapsed() >= limit { + return false; + } + std::thread::sleep(Duration::from_millis(5)); + } + } + + /// a big compute program of 1 MiB of DXIL + fn big_prog(hash: u64, key: u64) -> Program { + Program { hash, kind: b'C', dxil: 1 << 20, estimated: false, key, ..Default::default() } + } + + /// the name of the thread a job runs on + fn this_thread() -> String { + std::thread::current().name().unwrap_or("").to_string() + } + + /// one of the `xcl-pso-k` workers + fn is_worker(name: &str) -> bool { + name.starts_with("xcl-pso-") && !name.contains("-big-") && !name.contains("-pre-") + } + + fn state(compute: bool, built: bool, done: bool, late: bool) -> Option { + Some(StandinState { compute, built, done, late }) + } + + fn ms(n: u64) -> Duration { + Duration::from_millis(n) + } + + /// A big compute pipeline no run built is sent to the big lane and not waited for: the bind + /// goes on with its stand-in at once, a thread of the big lane builds it, and the ledger knows + /// it once built (run 64: thread 460 sat 434 s in such a build at its bind). + #[test] + fn a_big_pipeline_no_run_built_is_not_waited_for_and_comes_from_the_big_lane() { + let Some(_lanes) = lanes() else { return }; + let _fresh = Fresh; + let (s, k) = (0x7E57_A101usize, 0x5EED_A101u64); + let gate = Gate::new(); + let wait = gate.waiter(ms(3000)); + let (tx, rx) = mpsc::channel(); + let job: Job = Box::new(move || { + let _ = tx.send(this_thread()); + wait(); + 0x5252 + }); + submit_program(s, true, job, true, k, big_prog(0x7E57_A1A1, k)); + let t = Instant::now(); + assert_eq!(resolve_wait_for(s, None), s, "not waited for: the stand-in"); + assert!(t.elapsed() < ms(100), "waited {:?}", t.elapsed()); + assert_eq!(standin_state(s), state(true, false, false, true), "late, not built"); + assert!(!built::known(k)); + let on = rx.recv_timeout(ms(2000)).expect("its build started"); + assert!(on.starts_with("xcl-pso-big-"), "built on {on}"); + gate.open(); + assert!(poll(ms(5000), || !is_pending(s)), "built"); + assert_eq!(resolve_wait_for(s, None), 0x5252); + assert!(standin_state(s).is_some_and(|st| st.built) && built::known(k), "the ledger knows it once built"); + let _ = released(s); + } + + /// Big pipelines no run built hold the big lane's threads; a small one bound meanwhile is + /// built by the workers within its budget. + #[test] + fn small_pipelines_are_not_held_up_behind_big_ones() { + let Some(_lanes) = lanes() else { return }; + let n = crate::gpu::recomp::dxc::compile_threads() + 1; + let gate = Gate::new(); + let big: Vec = (0..n).map(|i| 0x7E57_A201 + i).collect(); + for (i, &s) in big.iter().enumerate() { + let wait = gate.waiter(ms(5000)); + let k = 0x5EED_A201 + i as u64; + submit_program( + s, + true, + Box::new(move || { + wait(); + 0 + }), + false, + k, + big_prog(0x7E57_A2A1 + i as u64, k), + ); + } + assert!(poll(ms(2000), || stats().building[Builder::Big as usize] == big_threads()), "the big lane's threads all build: {:?}", stats()); + assert_eq!(stats().queued[1], n - big_threads(), "the others wait on the big lane"); + let s0 = 0x7E57_A2F0usize; + submit(s0, true, Box::new(|| 0x6262)); + let t = Instant::now(); + // (a wait with a limit: the frame cap – XCL_PSO_WAIT_FRAME_MS, 2000 ms by default – cuts it + // to what this thread's frame has left) + assert_eq!(resolve_wait_for(s0, Some(ms(3000))), 0x6262, "a small one is built by the workers meanwhile"); + assert!(t.elapsed() < ms(3000)); + gate.open(); + assert!(poll(ms(10_000), || big.iter().all(|&s| !is_pending(s))), "the big ones are built once the gate opens"); + assert_eq!(stats().queued[1], 0); + for s in big.into_iter().chain([s0]) { + let _ = released(s); + } + } + + /// A big pipeline a run built (the ledger) is sent where small ones go and waited for – a + /// D3DMetal cache hit; one an earlier run only bound (`used`) goes to the big lane. + #[test] + fn a_big_pipeline_a_run_built_is_waited_for_and_one_only_bound_is_not() { + let Some(_lanes) = lanes() else { return }; + let _fresh = Fresh; + let (s1, k1, s2, k2) = (0x7E57_A301usize, 0x5EED_A301u64, 0x7E57_A302usize, 0x5EED_A302u64); + built::earlier_run_built(k1); + let (tx1, rx1) = mpsc::channel(); + let job1: Job = Box::new(move || { + std::thread::sleep(ms(50)); + let _ = tx1.send(this_thread()); + 0x5353 + }); + submit_program(s1, true, job1, true, k1, big_prog(0x7E57_A3A1, k1)); + assert_eq!(resolve_wait_for(s1, Some(ms(2000))), 0x5353, "a run built it: waited for"); + let on = rx1.recv_timeout(ms(1000)).expect("built"); + assert!(is_worker(&on), "built on {on}"); + assert!(state_for_test(s1).is_some_and(|st| st.2), "sent where small ones go because the ledger knew it"); + used::earlier_run_used(k2); + let gate = Gate::new(); + let wait = gate.waiter(ms(5000)); + let (tx2, rx2) = mpsc::channel(); + let job2: Job = Box::new(move || { + let _ = tx2.send(this_thread()); + wait(); + 0 + }); + submit_program(s2, true, job2, true, k2, big_prog(0x7E57_A3A2, k2)); + let t = Instant::now(); + assert_eq!(resolve_wait_for(s2, Some(ms(2000))), s2, "a run only bound it: not waited for"); + assert!(t.elapsed() < ms(100), "waited {:?}", t.elapsed()); + let on = rx2.recv_timeout(ms(2000)).expect("its build started"); + assert!(on.starts_with("xcl-pso-big-"), "built on {on}"); + gate.open(); + assert!(poll(ms(5000), || !is_pending(s1) && !is_pending(s2))); + let _ = released(s1); + let _ = released(s2); + } + + /// What a bind sees of a stand-in (`standin_state`): not built while building or late, done + /// and not built once failed or refused, built once built – `late` stays as it was set and + /// `done` tells it is over; nothing for a pipeline that is no stand-in. + #[test] + fn unbuilt_is_true_for_building_late_failed_and_refused_stand_ins_only() { + let Some(_lanes) = lanes() else { return }; + let _fresh = Fresh; + // lazy, never resolved + let idle = 0x7E57_A401usize; + submit_lazy(idle, true, Box::new(|| 0), 0); + assert_eq!(standin_state(idle), state(true, false, false, false)); + // failed: built here, with no pipeline + let (failed, kf) = (0x7E57_A402usize, 0x5EED_A402u64); + submit_program(failed, true, Box::new(|| 0), true, kf, Program { hash: 0x7E57_A4A2, kind: b'C', dxil: 4 << 10, estimated: false, key: kf, ..Default::default() }); + assert_eq!(resolve_wait_for(failed, None), failed); + assert_eq!(standin_state(failed), state(true, false, true, false), "failed: over, not built"); + assert!(!is_pending(failed) && !built::known(kf)); + // built + let built_s = 0x7E57_A403usize; + submit(built_s, true, Box::new(|| 0x5454)); + assert_eq!(resolve_wait_for(built_s, None), 0x5454); + assert_eq!(standin_state(built_s), state(true, true, true, false)); + // refused + let refused = 0x7E57_A404usize; + submit_refused(refused, true, 0, Program { hash: 0x7E57_A4A4, kind: b'C', dxil: 30 << 20, estimated: false, key: 0x5EED_A404, ..Default::default() }); + assert_eq!(standin_state(refused), state(true, false, true, false), "refused: over, not built"); + assert!(!is_pending(refused) && state_for_test(refused).is_some_and(|st| st.3)); + // no stand-in + assert_eq!(standin_state(0x7E57_A4FF), None); + // late: big and no run built it, its build held at a gate + let (late, kl) = (0x7E57_A405usize, 0x5EED_A405u64); + let gate = Gate::new(); + let wait = gate.waiter(ms(5000)); + let job: Job = Box::new(move || { + wait(); + 0x5455 + }); + submit_program(late, true, job, true, kl, big_prog(0x7E57_A4A5, kl)); + assert_eq!(resolve_wait_for(late, None), late); + assert_eq!(standin_state(late), state(true, false, false, true), "late: not built"); + gate.open(); + assert!(poll(ms(5000), || !is_pending(late))); + assert_eq!(standin_state(late), state(true, true, true, true), "built: over, `late` as it was"); + // late as after a wait past its budget + make_late_for_test(idle); + assert_eq!(standin_state(idle), state(true, false, false, true)); + for s in [idle, failed, built_s, refused, late] { + let _ = released(s); + } + } + + /// A refused stand-in's entry is done at once: never sent, never waited for, counted as failed. + #[test] + fn a_refused_stand_in_is_never_queued_nor_waited_for() { + let s = 0x7E57_A501usize; + let before = counts().1; + submit_refused(s, true, 0, Program { hash: 0x7E57_A5A1, kind: b'C', dxil: 30 << 20, estimated: false, key: 0x5EED_A501, ..Default::default() }); + assert!(!is_pending(s), "done at once"); + let t = Instant::now(); + assert_eq!(resolve_wait_for(s, Some(ms(200))), s); + assert!(t.elapsed() < ms(50), "not waited for ({:?})", t.elapsed()); + assert_eq!(resolve(s), s); + assert_eq!(state_for_test(s), Some((LANE_NONE, false, false, true)), "never sent, refused"); + assert!(counts().1 > before, "counted as failed"); + let _ = released(s); + } + + /// The threads that build ahead take a small pipeline an earlier run used, not a big one no + /// run built: that one waits for its first bind (the big lane). + #[test] + fn preload_leaves_big_pipelines_no_run_built_to_the_big_lane() { + let Some(_lanes) = lanes() else { return }; + if !preload_on() { + return crate::gpu::recomp::runner::skip_config("XCL_PSO_PRELOAD=0"); + } + let _fresh = Fresh; + let (sa, ka, sb, kb) = (0x7E57_A601usize, 0x5EED_A601u64, 0x7E57_A602usize, 0x5EED_A602u64); + used::earlier_run_used(ka); + used::earlier_run_used(kb); + let (a, b) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false))); + let (a2, b2) = (a.clone(), b.clone()); + let job_a: Job = Box::new(move || { + a2.store(true, Ordering::Release); + 0x5656 + }); + submit_program(sa, true, job_a, true, ka, Program { hash: 0x7E57_A6A1, kind: b'C', dxil: 16 << 10, estimated: false, key: ka, ..Default::default() }); + let job_b: Job = Box::new(move || { + b2.store(true, Ordering::Release); + 0 + }); + submit_program(sb, true, job_b, true, kb, big_prog(0x7E57_A6A2, kb)); + assert!(poll(ms(10_000), || a.load(Ordering::Acquire)), "the small one is built ahead"); + std::thread::sleep(ms(1000)); + assert!(!b.load(Ordering::Acquire), "a big one no run built is left to its first bind"); + assert!(is_pending(sb)); + assert_eq!(state_for_test(sb).map(|st| st.0), Some(LANE_NONE)); + assert!(poll(ms(5000), || !is_pending(sa))); + assert_eq!(resolve(sa), 0x5656); + let _ = released(sa); + // (never queued: its job goes with the entry, never run) + let _ = released(sb); + } + + /// A big pipeline released while it waits on the big lane is passed over, not compiled. + #[test] + fn a_released_big_pipeline_is_not_compiled_for_nobody() { + let Some(_lanes) = lanes() else { return }; + let n = big_threads(); + let gate = Gate::new(); + let held: Vec = (0..n).map(|i| 0x7E57_A701 + i).collect(); + for (i, &s) in held.iter().enumerate() { + let wait = gate.waiter(ms(5000)); + let k = 0x5EED_A701 + i as u64; + submit_program( + s, + true, + Box::new(move || { + wait(); + 0 + }), + false, + k, + big_prog(0x7E57_A7A1 + i as u64, k), + ); + } + assert!(poll(ms(2000), || stats().building[Builder::Big as usize] == n), "the big lane's threads all build: {:?}", stats()); + let c = Arc::new(AtomicBool::new(false)); + let c2 = c.clone(); + let s3 = 0x7E57_A7F0usize; + let job: Job = Box::new(move || { + c2.store(true, Ordering::Release); + 0 + }); + submit_program(s3, true, job, false, 0x5EED_A7F0, big_prog(0x7E57_A7F0, 0x5EED_A7F0)); + assert_eq!(stats().queued[1], 1, "waiting on the big lane"); + assert_eq!(released(s3), 0); + gate.open(); + // drained: nothing built or waiting there on two looks 50 ms apart + let drained = || { + let s = stats(); + s.building[Builder::Big as usize] == 0 && s.queued[1] == 0 + }; + assert!(poll(ms(5000), || drained() && { + std::thread::sleep(ms(50)); + drained() + })); + assert!(!c.load(Ordering::Acquire), "a released one is not built"); + for s in held { + let _ = released(s); + } + } + + /// A clone of a program the big lane builds waits for that build, then goes to the workers + /// (D3DMetal has it by then). + #[test] + fn clones_of_a_big_program_wait_for_its_first_build_then_go_to_the_workers() { + let Some(_lanes) = lanes() else { return }; + if big_threads() < 2 { + return crate::gpu::recomp::runner::skip_config("the big lane has one thread (XCL_PSO_BIG_THREADS=1)"); + } + let _fresh = Fresh; + let (s1, s2, k) = (0x7E57_A801usize, 0x7E57_A802usize, 0x5EED_A801u64); + let gate = Gate::new(); + let wait = gate.waiter(ms(5000)); + let (started_tx, started_rx) = mpsc::channel(); + let job1: Job = Box::new(move || { + let _ = started_tx.send(()); + wait(); + 0x5858 + }); + submit_program(s1, true, job1, false, k, big_prog(0x7E57_A8A1, k)); + started_rx.recv_timeout(ms(2000)).expect("the first build started"); + let (tx, rx) = mpsc::channel(); + let job2: Job = Box::new(move || { + let _ = tx.send(this_thread()); + 0x5859 + }); + submit_program(s2, true, job2, false, k, big_prog(0x7E57_A8A1, k)); + assert!(rx.recv_timeout(ms(300)).is_err(), "a clone waits for the first build"); + assert_eq!(stats().queued[1], 1, "parked on the big lane"); + gate.open(); + assert!(poll(ms(5000), || !is_pending(s1) && !is_pending(s2))); + let on = rx.recv_timeout(ms(1000)).expect("the clone was built"); + assert!(is_worker(&on), "the clone went to the workers: {on}"); + let _ = released(s1); + let _ = released(s2); + } + + /// A big pipeline sent where small ones go because the ledger knew it is judged by its driver + /// time with the process's freezes counted out: three slow ones end the ledger's trust (only + /// this run's builds count then); one sent as a small one (estimated) is never judged. + #[test] + fn a_big_pipeline_the_ledger_knew_is_judged_by_its_driver_time_and_three_misses_end_the_trust() { + // a freeze is not driver time + assert!(driver_time(ms(5000), 4_990) < MISS_SLOW); + assert!(driver_time(ms(5000), 0) >= MISS_SLOW); + let Some(_lanes) = lanes() else { return }; + let _fresh = Fresh; + built::reset_for_test(); + let ks = [0x5EED_A901u64, 0x5EED_A902, 0x5EED_A903, 0x5EED_A904]; + for k in ks { + built::earlier_run_built(k); + } + let mut done = Vec::new(); + for i in 0..3 { + let s = 0x7E57_A901 + i; + let real = 0x59a1 + i; + let job: Job = Box::new(move || { + note_driver_time(&DriverClock::ago(ms(3000))); + real + }); + submit_program(s, true, job, false, ks[i], big_prog(0x7E57_A9A1 + i as u64, ks[i])); + assert_eq!(resolve_wait_for(s, Some(ms(2000))), real, "a run built it: waited for"); + done.push(s); + } + assert_eq!(built::misses(), 3, "three slow driver compiles of pipelines a run built"); + assert!(!built::known(ks[3]), "not trusted: what an earlier run built no longer counts"); + assert!(built::known(ks[0]) && built::known(ks[2]), "this run's builds still do"); + // sent as a small one (an estimate); found big by its translation, and built meanwhile as + // a clone: not judged + built::reset_for_test(); + let (s5, k5) = (0x7E57_A905usize, 0x5EED_A905u64); + let (go_tx, go_rx) = mpsc::channel::<()>(); + let job: Job = Box::new(move || { + let _ = go_rx.recv_timeout(ms(5000)); + note_dxil(1 << 20); + note_driver_time(&DriverClock::ago(ms(5000))); + 0x59a5 + }); + submit_program(s5, true, job, false, k5, Program { hash: 0x7E57_A9A5, kind: b'C', dxil: 16 << 10, estimated: true, key: k5, ..Default::default() }); + built::note(k5); + go_tx.send(()).unwrap(); + // (cut by the frame cap – XCL_PSO_WAIT_FRAME_MS, 2000 ms by default – to what this thread's + // frame has left after the three waits above) + assert_eq!(resolve_wait_for(s5, Some(ms(5000))), 0x59a5); + assert_eq!(built::misses(), 0, "sent as a small one: not judged"); + for s in done.into_iter().chain([s5]) { + let _ = released(s); + } + } + + /// The ledger's file: whole keys a line, a cut last line ended before the next key, and a + /// ledger not trusted starts again from this run's builds (the old file kept as `.stale`). + #[test] + fn the_ledger_keeps_whole_keys_a_line_and_starts_again_when_not_trusted() { + let keys = built::parse("56c0cd3b82a00c6e\n56c0cd3b\nzz\n0000000000000000\n00000000000000ff\n56c0cd3b82a00c6e00000000000000ff\n"); + assert_eq!(keys, HashSet::from([0x56c0cd3b82a00c6e, 0xff])); + let dir = std::env::temp_dir().join(format!("xcl-built-ledger-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let p = dir.join("built-pipelines-test.txt"); + let one = built::Ledger::open_in(Some(&p), HashSet::from([0xabc])); + assert!(one.known(0xabc) && !one.known(1)); + one.note(1); + one.note(2); + one.note(1); + drop(one); + assert_eq!(std::fs::read_to_string(&p).unwrap(), "0000000000000001\n0000000000000002\n"); + // a run ended in a write: a cut last line + let mut f = std::fs::OpenOptions::new().append(true).open(&p).unwrap(); + std::io::Write::write_all(&mut f, b"00000000000000").unwrap(); + drop(f); + let two = built::Ledger::open_in(Some(&p), HashSet::new()); + assert!(two.known(1) && two.known(2)); + assert_eq!(two.len(), 2); + two.note(3); + { + let three = built::Ledger::open_in(Some(&p), HashSet::new()); + assert!(three.known(3), "a key after a cut line is a line of its own"); + } + for _ in 0..built::MISS_LIMIT { + two.missed("56c0cd3b82a00c6e (CS, 1024 KB of DXIL)", ms(3000)); + } + let stale = std::fs::read_to_string(p.with_extension("txt.stale")).expect("the old file kept"); + assert_eq!(built::parse(&stale), HashSet::from([1, 2, 3])); + assert_eq!(std::fs::read_to_string(&p).unwrap(), "0000000000000003\n", "the file starts again from this run's builds"); + assert!(!two.known(1) && two.known(3)); + drop(two); + let seeded = built::Ledger::open_in(None, HashSet::from([0xabc])); + assert!(seeded.known(0xabc)); + for _ in 0..built::MISS_LIMIT { + seeded.missed("a seeded one", ms(3000)); + } + assert!(!seeded.known(0xabc), "a seed is not trusted either"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The ledger's file gets a key once (PP6): one the file holds already, built again, is not + /// written again; a new one is written once; this run's set still gets every key – a rewrite + /// when the ledger is not trusted lists the one the file had too –; a seed key built now is + /// written (the seed is apart from the file). Keys 0x7A1E_40xx. + #[test] + fn the_ledger_file_gets_a_key_once_also_when_an_earlier_run_built_it() { + let dir = std::env::temp_dir().join(format!("xcl-built-once-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join("built-pipelines-test.txt"); + let read = |p: &std::path::Path| std::fs::read_to_string(p).unwrap(); + std::fs::write(&p, "000000007a1e4001\n000000007a1e4002\n").unwrap(); + let l = built::Ledger::open_in(Some(&p), HashSet::new()); + l.note(0x7A1E_4001); + assert_eq!(read(&p), "000000007a1e4001\n000000007a1e4002\n", "a key the file holds: not written again"); + l.note(0x7A1E_4003); + l.note(0x7A1E_4003); + assert_eq!(read(&p), "000000007a1e4001\n000000007a1e4002\n000000007a1e4003\n", "a new key: written once"); + for _ in 0..built::MISS_LIMIT { + l.missed("a test's big pipeline (CS, 1024 KB of DXIL)", ms(3000)); + } + assert_eq!(built::parse(&read(&p)), HashSet::from([0x7A1E_4001, 0x7A1E_4003]), "the rewrite lists this run's builds, the one the file had too"); + assert!(l.known(0x7A1E_4001) && l.known(0x7A1E_4003) && !l.known(0x7A1E_4002)); + l.note(0x7A1E_4004); + l.note(0x7A1E_4001); + assert_eq!(built::parse(&read(&p)), HashSet::from([0x7A1E_4001, 0x7A1E_4003, 0x7A1E_4004])); + assert_eq!(read(&p).lines().count(), 3, "each once after the rewrite too"); + drop(l); + let q = dir.join("built-pipelines-seeded.txt"); + let s = built::Ledger::open_in(Some(&q), HashSet::from([0x7A1E_4005])); + assert!(s.known(0x7A1E_4005)); + s.note(0x7A1E_4005); + s.note(0x7A1E_4005); + assert_eq!(read(&q), "000000007a1e4005\n", "a seed key built in this run is written, once"); + drop(s); + let _ = std::fs::remove_dir_all(&dir); + } + + /// PP2 (P3): with every worker held, two cold pipelines are sent and then two the ledger + /// knows; the one worker let go builds the known ones first, then the cold ones – each tier in + /// the order sent – and the pipelines lines count all four as queued until a worker takes them + /// (XCL_PSO_TIERS=0, its own process: the four in the order sent). Stand-ins 0x7A1E_3Axx and + /// 0x7A1E_3Bxx, keys 0x7A1E_4Axx and 0x7A1E_4Bxx. + #[test] + fn a_pipeline_the_ledger_knows_is_built_before_cold_ones_sent_earlier() { + let Some(_lanes) = lanes() else { return }; + let _fresh = Fresh; + let n = crate::gpu::recomp::dxc::compile_threads(); + let gates: Vec = (0..n).map(|_| Gate::new()).collect(); + let held: Vec = (0..n).map(|i| 0x7A1E_3A80 + i).collect(); + let started = Arc::new(AtomicUsize::new(0)); + for (g, &s) in gates.iter().zip(&held) { + let (wait, started) = (g.waiter(ms(10_000)), started.clone()); + submit( + s, + true, + Box::new(move || { + started.fetch_add(1, Ordering::AcqRel); + wait(); + 0 + }), + ); + } + assert!(poll(ms(8000), || started.load(Ordering::Acquire) == n), "every worker holds one: {} of {n}", started.load(Ordering::Acquire)); + let order = Arc::new(Mutex::new(Vec::new())); + let job = |name: &'static str| -> Job { + let order = order.clone(); + Box::new(move || { + order.lock().unwrap().push(name); + 0 + }) + }; + let prog = |hash: u64, key: u64| Program { hash, kind: b'C', dxil: 16 << 10, key, ..Default::default() }; + let (a1, a2, b1, b2) = (0x7A1E_3A01usize, 0x7A1E_3A02usize, 0x7A1E_3B01usize, 0x7A1E_3B02usize); + built::earlier_run_built(0x7A1E_4B01); + built::earlier_run_built(0x7A1E_4B02); + // (A1 not translated when made, and its CS on no disk: cold) + submit_program(a1, true, job("A1"), false, 0, Program { translated: Some(false), ..prog(0x7A1E_3AA1, 0x7A1E_4A01) }); + submit_program(a2, true, job("A2"), false, 0, prog(0x7A1E_3AA2, 0x7A1E_4A02)); + submit_program(b1, true, job("B1"), false, 0, prog(0x7A1E_3BA1, 0x7A1E_4B01)); + submit_program(b2, true, job("B2"), false, 0, prog(0x7A1E_3BA2, 0x7A1E_4B02)); + assert!(stats().queued[0] >= 4, "queued until a worker takes them: {:?}", stats()); + let depths = queue_stats().tiers; + if tiers_on() { + assert!(depths[TIER_KNOWN as usize][1] >= 2 && depths[TIER_COLD as usize][1] >= 2, "by tier and kind: {depths:?}"); + } else { + assert!(depths[TIER_COLD as usize][1] >= 4 && depths[TIER_KNOWN as usize][1] == 0, "all cold: {depths:?}"); + } + gates[0].open(); + assert!(poll(ms(5000), || order.lock().unwrap().len() == 4), "built by the one worker let go: {:?}", order.lock().unwrap()); + let want = if tiers_on() { ["B1", "B2", "A1", "A2"] } else { ["A1", "A2", "B1", "B2"] }; + assert_eq!(*order.lock().unwrap(), want, "XCL_PSO_TIERS on: {}", tiers_on()); + drop(gates); + let all: Vec = held.iter().copied().chain([a1, a2, b1, b2]).collect(); + assert!(poll(ms(10_000), || all.iter().all(|&s| !is_pending(s)))); + for s in all { + let _ = released(s); + } + } + + /// A build running is said every XCL_PSO_STILL_BUILDING_S by its program. + #[test] + fn a_build_is_said_still_building_every_30_s_by_its_program() { + let s = Duration::from_secs; + assert_eq!(due(ms(29_999), s(30), 0), None); + assert_eq!(due(s(30), s(30), 0), Some(1)); + assert_eq!(due(s(59), s(30), 1), None); + assert_eq!(due(s(95), s(30), 1), Some(3)); + let p = Pending::new(0x7E57_AB01, true, None, false, 0, Program { hash: 0x56c0cd3b82a00c6e, kind: b'C', dxil: 29_756_576, estimated: false, key: 0, ..Default::default() }); + assert_eq!(still_building_line(&p, 460, 30, Builder::Here), "[pso] still building 56c0cd3b82a00c6e (CS, 29059 KB of DXIL) on thread 460 for 30 s (the binding thread)"); + let q = Pending::new(0x7E57_AB02, true, None, false, 0, Program::default()); + assert_eq!(still_building_line(&q, 7, 60, Builder::Big), "[pso] still building stand-in 0x7e57ab02 on thread 7 for 60 s (the big lane)"); + } + + /// The programs whose work was skipped are named once each, the first 32 only. + #[test] + fn skipped_programs_are_named_once_and_only_the_first_32() { + let mut n = Named { seen: Vec::new() }; + for i in 0..40u64 { + assert_eq!(n.first_time(0x1000 + i), (i < 32).then_some(i as usize + 1), "program {i}"); + } + assert_eq!(n.first_time(0x1000), None, "named once"); + assert_eq!(n.seen.iter().find(|e| e.0 == 0x1000).map(|e| e.1), Some(2), "its skips counted"); + } + + /// The 2-s pipelines line: nothing when nothing happened and nothing waits or builds; its + /// counts first, then the queues and the builds, the run's totals last. + #[test] + fn the_activity_line_says_nothing_when_nothing_happens_and_its_fields_first() { + let idle = Stats { built: 10, failed: 2, refused: 1, ..Default::default() }; + assert_eq!(activity_text(&idle, &idle), None); + let queued = Stats { queued: [0, 3, 0], ..idle }; + let l = activity_text(&idle, &queued).expect("something waits"); + assert!(l.contains("queued 0 + 3 big + 0 ahead"), "{l}"); + let busy = Stats { late_binds: 5, skipped: 7, ..idle }; + let l = activity_text(&idle, &busy).expect("binds went on without their pipelines"); + assert!(l.starts_with("pipelines (2 s): 5 late binds, 7 skipped (pipeline not built)"), "{l}"); + let head: String = l.chars().take(200).collect(); + assert!(head.contains("queued") && head.contains("building"), "{head}"); + // (whatever the numbers: a game's totals before the queues would push them out of the + // 200 characters E's status keeps) + let at = |field: &str| l.find(field).unwrap_or(usize::MAX); + assert!(at("queued") < at("building") && at("building") < at("so far"), "{l}"); + } + + /// A look 0.5 s late or more is time the process stood still; a compile caught in it is + /// judged without it. + #[test] + fn the_time_the_process_stood_still_is_counted_from_late_looks() { + assert_eq!(frozen_in(ms(250)), 0); + assert_eq!(frozen_in(ms(700)), 0); + assert_eq!(frozen_in(ms(800)), 550); + assert_eq!(frozen_in(ms(5_250)), 5_000); + // an 11-ms compile caught in that freeze is a D3DMetal hit + assert!(driver_time(ms(5_011), 5_000) < MISS_SLOW); + } + + /// A build that panics is a failed one; its worker builds the next. + #[test] + fn a_panicking_build_is_a_failed_one_and_its_worker_lives_on() { + let (s, s2) = (0x7E57_AC01usize, 0x7E57_AC02usize); + let before = counts().1; + // (resume_unwind: no panic hook, no noise in the output) + submit(s, true, Box::new(|| -> usize { std::panic::resume_unwind(Box::new(())) })); + assert_eq!(resolve_wait_for(s, Some(ms(2000))), s); + assert!(poll(ms(2000), || !is_pending(s)), "a failed build"); + assert!(counts().1 > before, "counted as failed"); + submit(s2, true, Box::new(|| 0x6565)); + assert_eq!(resolve_wait_for(s2, Some(ms(2000))), 0x6565, "the workers live on"); + let _ = released(s); + let _ = released(s2); + } + + /// A pipeline sized small that its translation finds big while a bind builds it on its own + /// thread: the binds after that do not wait for it. + #[test] + fn a_pipeline_found_big_by_its_translation_is_not_waited_for_by_later_binds() { + let Some(_lanes) = lanes() else { return }; + let _fresh = Fresh; + let (s, k) = (0x7E57_AD01usize, 0x5EED_AD01u64); + let gate = Gate::new(); + let wait = gate.waiter(ms(3000)); + let (tx, rx) = mpsc::channel(); + let job: Job = Box::new(move || { + note_dxil(1 << 20); + let _ = tx.send(()); + wait(); + 0x6666 + }); + submit_program(s, true, job, true, k, Program { hash: 0x7E57_ADA1, kind: b'C', dxil: 16 << 10, estimated: true, key: k, ..Default::default() }); + let binder = std::thread::spawn(move || resolve_wait_for(s, None)); + rx.recv_timeout(ms(2000)).expect("built on the binding thread"); + let t = Instant::now(); + assert_eq!(resolve_wait_for(s, None), s, "found big: not waited for"); + assert!(t.elapsed() < ms(100), "waited {:?}", t.elapsed()); + assert!(standin_state(s).is_some_and(|st| st.late && !st.done), "late"); + assert_eq!(state_for_test(s).map(|st| st.0), Some(LANE_HERE)); + gate.open(); + assert_eq!(binder.join().unwrap(), 0x6666, "the binding thread built it"); + assert_eq!(resolve_wait_for(s, None), 0x6666); + let _ = released(s); + } + + /// A big pipeline sent where small ones go because the ledger knew it, still waiting for a + /// worker when the ledger stops being trusted (three misses: D3DMetal's cache was cleared), is + /// built on the big lane – not cold on a worker (CV-M1, PB-1). Stand-ins 0x7A0C_10xx. + #[test] + fn a_big_pipeline_the_ledger_knew_goes_to_the_big_lane_once_the_ledger_is_not_trusted() { + let Some(_lanes) = lanes() else { return }; + let _fresh = Fresh; + // every worker held at a gate: the pipeline waits in their queue + let n = crate::gpu::recomp::dxc::compile_threads(); + let gate = Gate::new(); + let waiting = Arc::new(AtomicUsize::new(0)); + let held: Vec = (0..n).map(|i| 0x7A0C_1000 + i).collect(); + for &s in &held { + let (wait, waiting) = (gate.waiter(ms(10_000)), waiting.clone()); + submit( + s, + true, + Box::new(move || { + waiting.fetch_add(1, Ordering::AcqRel); + wait(); + waiting.fetch_sub(1, Ordering::AcqRel); + 0 + }), + ); + } + assert!(poll(ms(8000), || waiting.load(Ordering::Acquire) == n), "every worker holds one: {} of {n}", waiting.load(Ordering::Acquire)); + let (s, k) = (0x7A0C_10F0usize, 0x7A0C_5EED_10F0u64); + built::earlier_run_built(k); + let (tx, rx) = mpsc::channel(); + let job: Job = Box::new(move || { + let _ = tx.send(this_thread()); + 0x7A0C_10F1 + }); + submit_program(s, true, job, false, k, big_prog(0x7A0C_10FA, k)); + assert_eq!(state_for_test(s).map(|st| (st.0, st.2)), Some((LANE_WORKERS, true)), "sent where small ones go: the ledger knew it"); + for _ in 0..built::MISS_LIMIT { + built::missed("a test's big pipeline (CS, 1024 KB of DXIL)", ms(3000)); + } + assert!(!built::known(k), "the ledger is not trusted any more"); + gate.open(); + let on = rx.recv_timeout(ms(10_000)).expect("its build started"); + assert!(on.starts_with("xcl-pso-big-"), "built on {on}: a cold compile on a worker"); + assert_eq!(state_for_test(s).map(|st| (st.0, st.2)), Some((LANE_BIG, false)), "the big lane's now"); + assert!(poll(ms(10_000), || !is_pending(s) && held.iter().all(|&h| !is_pending(h)))); + for s in held.into_iter().chain([s]) { + let _ = released(s); + } + } + + /// The ledger's line counts XCL_PSO_BUILT_SEED: with a seed and no file yet (run 65 with + /// SEED=1), a big compute pipeline of the seed is waited for like a small one – the line must + /// not say every big one goes to the big lane (CV-M2). Its head is what run65_events.sh reads. + #[test] + fn the_ledger_line_counts_the_seed() { + let name = "built-pipelines-d5dae6d8d47683a5.txt"; + let head = format!("D3D12.X: {name}: "); + let none = built::ledger_line(name, 0, 0); + assert_eq!(none, format!("{head}no pipeline an earlier run built yet – every big compute pipeline goes to the big lane until it is built (XCL_PSO_BUILT_LEDGER=0: no ledger)")); + let seeded = built::ledger_line(name, 0, 426); + assert!(seeded.starts_with(&head) && seeded.contains("XCL_PSO_BUILT_SEED's 426 count as built") && seeded.contains("waited for like a small one"), "{seeded}"); + assert!(!seeded.contains("every big compute pipeline goes to the big lane"), "{seeded}"); + assert_eq!(built::ledger_line(name, 12, 0), format!("{head}12 pipelines an earlier run built – a big compute one of them is waited for like a small one (XCL_PSO_BUILT_LEDGER=0: no ledger)")); + let both = built::ledger_line(name, 12, 426); + assert!(both.starts_with(&format!("{head}12 pipelines an earlier run built")) && both.contains("XCL_PSO_BUILT_SEED's 426 count as built"), "{both}"); + } + + /// A build that ends with no pipeline is named, whoever builds it – a worker, a binding thread – + /// unless it was refused: when the title made it, or by its build (never built: no failure) + /// (M2); a build that gives a pipeline is not. Stand-ins 0x7A0C_20xx. + #[test] + fn a_failed_build_is_named_and_a_refused_one_is_not() { + let prog = |h: u64| Program { hash: h, kind: b'C', dxil: 16 << 10, estimated: false, key: 0, ..Default::default() }; + let (worker, here, refused, by_build) = (0x7A0C_2001usize, 0x7A0C_2002usize, 0x7A0C_2003usize, 0x7A0C_2004usize); + // on a worker: sent when made + submit_program(worker, true, Box::new(|| 0), false, 0, prog(0x7A0C_20A1)); + assert!(poll(ms(10_000), || !is_pending(worker)), "built by a worker"); + // on the binding thread: a bind with no budget builds it there + submit_program(here, true, Box::new(|| 0), true, 0, prog(0x7A0C_20A2)); + assert_eq!(resolve_wait_for(here, None), here); + // refused when made, and by its build + submit_refused(refused, true, 0, prog(0x7A0C_20A3)); + let job: Job = Box::new(|| { + note_refused(0x7A0C_20A4, "CS", "a test's refusal"); + 0 + }); + submit_program(by_build, true, job, true, 0, prog(0x7A0C_20A4)); + assert_eq!(resolve_wait_for(by_build, None), by_build); + // built (here): no failure + let built = 0x7A0C_2005usize; + submit_program(built, true, Box::new(|| 0x7A0C_20F5), true, 0, prog(0x7A0C_20A5)); + assert_eq!(resolve_wait_for(built, None), 0x7A0C_20F5); + assert_eq!(failed_line_for_test(worker).as_deref(), Some("[pso] the build of 000000007a0c20a1 (CS, 16 KB of DXIL) failed (a worker)")); + assert_eq!(failed_line_for_test(here).as_deref(), Some("[pso] the build of 000000007a0c20a2 (CS, 16 KB of DXIL) failed (the binding thread)")); + assert_eq!(failed_line_for_test(refused), None, "refused when made: never built"); + assert_eq!(failed_line_for_test(by_build), None, "refused by its build: never built"); + assert_eq!(failed_line_for_test(built), None, "built: no failure"); + // (built: no release of the test's fake pipeline) + for s in [worker, here, refused, by_build, built] { + let _ = released(s); + } + } +} + +/// `XCL_PSO_WAIT_FRAME_MS` (`frame`): stand-ins 0x7A1E_0xxx, each test's own block of 0x100 (and +/// 0x7A1E_1xxx), sent and never built while the test runs (`submit_held_for_test`: no worker held +/// up) – but two: 0x7A1E_01B1, sent at its bind (`submit_lazy`), holds a worker on its gate (under +/// 30 ms with the cap, about 300 ms without it), and 0x7A1E_0502 is built on the binding thread –, +/// in a frame of the test's own (no other test's Present moves it) – but one test's, which is the +/// title's, moved by the frame boundaries that test makes. Cap-off runs: XCL_PSO_WAIT_FRAME_MS=0, +/// its own process. +#[cfg(test)] +mod frame_tests { + use super::*; + + fn ms(n: u64) -> Duration { + Duration::from_millis(n) + } + + /// a small compute program not built (`n`: its hash's last part) + fn small(n: u64) -> Program { + Program { hash: 0x7A1E_0000 + n, kind: b'C', dxil: 16 << 10, ..Default::default() } + } + + fn late_not_built(pso: usize) -> bool { + standin_state(pso) == Some(StandinState { compute: true, built: false, done: false, late: true }) + } + + /// Ten pipelines whose builds do not end, bound one after another on one thread, each with a + /// budget of 300 ms: their waits come to XCL_PSO_WAIT_FRAME_MS (2000) at most and about that – + /// the wait that would pass it cut short, the binds after it going on at once (late) – where + /// without the cap (XCL_PSO_WAIT_FRAME_MS=0) each waits its 300 ms. The thread's waits are + /// published for the "no Present" line. After them a pipeline not sent yet (lazy: sent at its + /// first bind), its build held by a worker: its bind sends it to the workers and – the frame's + /// budget spent – goes on at once, late (without the cap: after its 300 ms). Stand-ins + /// 0x7A1E_01xx. + #[test] + fn a_threads_binds_wait_for_pipelines_no_longer_than_its_frames_budget() { + let each = ms(300); + let s: Vec = (0..10).map(|i| 0x7A1E_0101 + i).collect(); + for (i, &x) in s.iter().enumerate() { + submit_held_for_test(x, true, small(0x01A1 + i as u64)); + } + frame::set_for_test(0x7A1E_0100); + let mut took = Vec::new(); + for &x in &s { + let t = Instant::now(); + assert_eq!(resolve_wait_for(x, Some(each)), x, "not built: its stand-in"); + took.push(t.elapsed()); + } + let total: Duration = took.iter().sum(); + let (waited, pipelines, without, told) = frame::for_test(); + match wait_frame() { + Some(cap) => { + assert!(total <= cap + ms(50), "{total:?} in all: {took:?}"); + assert!(total + ms(50) >= cap && waited >= cap, "waited about the budget: {total:?} ({waited:?}): {took:?}"); + assert!(took[..5].iter().all(|&t| t + ms(5) >= each), "the first waited their budgets: {took:?}"); + assert!(took[7..].iter().all(|&t| t < ms(30)), "the last went on at once: {took:?}"); + assert!((6..=7).contains(&pipelines) && without == 10 && told, "({waited:?}, {pipelines}, {without}, {told})"); + } + None => { + assert!(took.iter().all(|&t| t + ms(5) >= each), "each waited its budget: {took:?}"); + assert!(pipelines == 10 && without == 10 && !told, "({waited:?}, {pipelines}, {without}, {told})"); + } + } + for &x in &s { + assert!(late_not_built(x), "{x:#x}: late, not built"); + } + // what the "no Present" line says of this thread + let said = frame::waits_in(0x7A1E_0100, 4); + let head = format!("thread {} waited {:.1} s for {pipelines} pipelines and went on without 10", frame::tid_for_test(), waited.as_secs_f64()); + assert_eq!(said, head, "only this thread waited in its frame"); + for &x in &s { + let _ = released(x); + } + // a pipeline not sent yet, its build held by the worker that takes it (until the gate opens) + let lazy = 0x7A1E_01B1usize; + let (open, gate) = mpsc::channel::<()>(); + let job: Job = Box::new(move || { + let _ = gate.recv_timeout(Duration::from_secs(5)); + 0 + }); + submit_lazy(lazy, true, job, 0); + assert_eq!(state_for_test(lazy).map(|st| st.1), Some(false), "not sent before its bind"); + let t = Instant::now(); + assert_eq!(resolve_wait_for(lazy, Some(each)), lazy, "its stand-in"); + let after = t.elapsed(); + assert_eq!(state_for_test(lazy).map(|st| (st.0, st.1)), Some((LANE_WORKERS, true)), "sent to the workers by its bind"); + assert!(late_not_built(lazy), "late, not built"); + match wait_frame() { + Some(_) => assert!(after < ms(30), "the frame's budget spent: at once ({after:?})"), + None => assert!(after + ms(5) >= each, "its budget waited ({after:?})"), + } + drop(open); + // (its build ends with no pipeline: no fake one to release) + let start = Instant::now(); + while is_pending(lazy) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(ms(5)); + } + let _ = released(lazy); + } + + /// A thread's frame budget spent, its next bind of a pipeline not built goes on at once; after + /// a Present it waits again – the budget is the new frame's. Stand-ins 0x7A1E_02xx. + #[test] + fn a_threads_frame_budget_starts_again_after_a_present() { + let Some(cap) = wait_frame() else { + crate::gpu::recomp::runner::skip_config("XCL_PSO_WAIT_FRAME_MS=0: no budget a frame"); + return; + }; + let (a, b, c) = (0x7A1E_0201usize, 0x7A1E_0202usize, 0x7A1E_0203usize); + for (i, x) in [a, b, c].into_iter().enumerate() { + submit_held_for_test(x, true, small(0x02A1 + i as u64)); + } + frame::set_for_test(0x7A1E_0200); + // the whole budget in one wait + let t = Instant::now(); + assert_eq!(resolve_wait_for(a, Some(cap + ms(500))), a); + let first = t.elapsed(); + assert!(first + ms(5) >= cap && first <= cap + ms(50), "cut to the frame's budget: {first:?}"); + let t = Instant::now(); + assert_eq!(resolve_wait_for(b, Some(ms(300))), b); + assert!(t.elapsed() < ms(30), "the budget spent: at once ({:?})", t.elapsed()); + assert!(frame::for_test().3, "told"); + frame::next_for_test(); + let t = Instant::now(); + assert_eq!(resolve_wait_for(c, Some(ms(300))), c); + let again = t.elapsed(); + assert!(again + ms(5) >= ms(300), "a new frame: waited again ({again:?})"); + let (waited, pipelines, without, told) = frame::for_test(); + assert!(waited + ms(5) >= ms(300) && waited < cap && (pipelines, without, told) == (1, 1, false), "({waited:?}, {pipelines}, {without}, {told})"); + assert!([a, b, c].into_iter().all(late_not_built)); + for x in [a, b, c] { + let _ = released(x); + } + } + + /// Two threads binding pipelines not built at the same time: each waits its own frame's budget – + /// one's waits do not use up the other's. Stand-ins 0x7A1E_03xx and 0x7A1E_04xx. + #[test] + fn two_threads_frame_budgets_are_their_own() { + let Some(cap) = wait_frame() else { + crate::gpu::recomp::runner::skip_config("XCL_PSO_WAIT_FRAME_MS=0: no budget a frame"); + return; + }; + let both = Arc::new(std::sync::Barrier::new(2)); + let binder = |base: usize| { + let both = both.clone(); + std::thread::spawn(move || { + let s: Vec = (1..=10).map(|i| base + i).collect(); + for &x in &s { + submit_held_for_test(x, true, small((base & 0xFFFF) as u64 + 0xA0)); + } + frame::set_for_test(base as u64); + both.wait(); + let t = Instant::now(); + for &x in &s { + assert_eq!(resolve_wait_for(x, Some(ms(300))), x); + } + let took = t.elapsed(); + let (waited, ..) = frame::for_test(); + for &x in &s { + let _ = released(x); + } + (took, waited) + }) + }; + let t = Instant::now(); + let (one, two) = (binder(0x7A1E_0300), binder(0x7A1E_0400)); + let (one, two) = (one.join().unwrap(), two.join().unwrap()); + for (took, waited) in [one, two] { + assert!(took + ms(50) >= cap && took <= cap + ms(50) && waited >= cap, "each thread its own budget: {took:?} ({waited:?})"); + } + assert!(t.elapsed() < cap + cap / 2, "at the same time: {:?}", t.elapsed()); + } + + /// With no limit a wait (XCL_PSO_WAIT_MS unset or 0) a bind waits until its pipeline is built, + /// as before 0023.1 – also once this thread's waits with a limit spent its frame's budget: the + /// pipeline built on the binding thread (however long that takes), not late, and neither the + /// build nor the wait counted for the frame (without the cap too). Stand-ins 0x7A1E_05xx. + #[test] + fn a_bind_with_no_limit_waits_until_built_also_once_its_frame_is_spent() { + let (held, slow) = (0x7A1E_0501usize, 0x7A1E_0502usize); + submit_held_for_test(held, true, small(0x05A1)); + frame::set_for_test(0x7A1E_0500); + // a wait with a limit: the frame's whole budget (without the cap its own 300 ms) + let cap = wait_frame(); + assert_eq!(resolve_wait_for(held, Some(cap.map_or(ms(300), |c| c + ms(500)))), held); + let spent = frame::for_test(); + if let Some(cap) = cap { + assert!(spent.0 >= cap && spent.3, "the frame's budget spent and told: {spent:?}"); + } + // a pipeline no worker has, bound with no limit: built here however long that takes + let long = ms(300); + submit_lazy( + slow, + true, + Box::new(move || { + std::thread::sleep(long); + 0x7A1E_05F1 + }), + 0, + ); + let t = Instant::now(); + assert_eq!(resolve_wait_for(slow, None), 0x7A1E_05F1, "built here"); + assert!(t.elapsed() >= long, "however long that took ({:?})", t.elapsed()); + assert_eq!(state_for_test(slow).map(|st| st.0), Some(LANE_HERE)); + assert_eq!(standin_state(slow).map(|st| (st.built, st.late)), Some((true, false)), "built, not late"); + assert_eq!(frame::for_test(), spent, "the frame's waits as they were: the build and its wait not counted"); + let _ = released(held); + // (built: no release of the test's fake pipeline) + let _ = released(slow); + } + + /// What the "no Present" line says of the threads that waited in a frame: those of that frame + /// only, the longest first, at most `n` (4 in the line's clause, `waits_since_present`), "and went + /// on without" only when they did; "none" for none; the line a thread's spent budget is told with + /// names the pipelines it went on without; a pipeline's late line names it, with why when the + /// frame's budget cut its wait. + #[test] + fn the_waits_of_a_frame_are_said_the_longest_first() { + let v = [(472u32, ms(27_500), 45u32, 0u32), (468, ms(2_000), 3, 41)]; + assert_eq!(frame::waits_text(&v), "thread 472 waited 27.5 s for 45 pipelines, thread 468 waited 2.0 s for 3 pipelines and went on without 41"); + assert_eq!(frame::waits_text(&[]), "none"); + assert_eq!(frame::waits_in(0x7A1E_0600, 4), "none", "nobody waited in this frame"); + // the line of a spent budget, with five pipelines gone on without (four named) + frame::set_for_test(0x7A1E_0600); + let s: Vec = (1..=5).map(|i| 0x7A1E_0600 + i).collect(); + for (i, &x) in s.iter().enumerate() { + submit_held_for_test(x, true, small(0x06A1 + i as u64)); + } + if let Some(cap) = wait_frame() { + // the whole budget in the first wait; the next four at once – the second the first the + // frame's budget made go on without its pipeline (its late line says so, the first's not) + assert_eq!(resolve_wait_for(s[0], Some(cap)), s[0]); + assert_eq!(late_named_for_test().as_deref(), Some("000000007a1e06a1 (CS, 16 KB of DXIL)"), "its own budget waited: no why"); + for (k, &x) in s[1..].iter().enumerate() { + assert_eq!(resolve_wait_for(x, Some(ms(300))), x); + assert_eq!( + late_named_for_test(), + Some(format!("000000007a1e06a{} (CS, 16 KB of DXIL) – its thread's frame budget (XCL_PSO_WAIT_FRAME_MS) cut the wait short", k + 2)), + "the frame's budget left it no wait: why" + ); + } + let (waited, pipelines, without, told) = frame::for_test(); + assert!(waited >= cap && (pipelines, without, told) == (1, 5, true), "({waited:?}, {pipelines}, {without}, {told})"); + let tid = frame::tid_for_test(); + assert_eq!( + frame::told_for_test().as_deref(), + Some(format!( + "[pso] thread {tid} waited {} ms for 1 pipelines since the last Present, XCL_PSO_WAIT_FRAME_MS={}: until the next Present its binds go on without a pipeline not built, which stays skipped until it is built; without 2 so far: 000000007a1e06a1 (CS, 16 KB of DXIL), 000000007a1e06a2 (CS, 16 KB of DXIL)", + waited.as_millis(), + cap.as_millis() + )) + .as_deref() + ); + let said = frame::waits_in(0x7A1E_0600, 4); + assert_eq!(said, format!("thread {tid} waited {:.1} s for 1 pipelines and went on without 5", waited.as_secs_f64())); + } + // a late line itself – the log's text, kept on this thread (`log::kept`) – names what the + // record names, the why at its end when the frame's budget cut the wait. It is logged for + // the first 16 pipelines gone late of all threads, then at powers of two: made again until + // one of this thread's is. + let p = entry(s[1]).unwrap(); + for (cut, why) in [(false, ""), (true, " – its thread's frame budget (XCL_PSO_WAIT_FRAME_MS) cut the wait short")] { + let kept = crate::log::kept::keep(); + let line = (0..4096) + .find_map(|_| { + note_late(&p, ms(300), cut); + kept.take().into_iter().find(|l| l.starts_with("D3D12.X: a pipeline still being built after ")) + }) + .expect("a late line due within 4096"); + let head = "D3D12.X: a pipeline still being built after 300 ms: its binds go on without it until it is built ("; + let tail = format!(" so far) – 000000007a1e06a2 (CS, 16 KB of DXIL){why}"); + let n = line.strip_prefix(head).and_then(|l| l.strip_suffix(tail.as_str())).and_then(|n| n.parse::().ok()); + assert!(n.is_some_and(|n| n <= 16 || (n - 1).is_power_of_two()), "the late line, cut {cut}: {line}"); + assert_eq!(late_named_for_test(), Some(format!("000000007a1e06a2 (CS, 16 KB of DXIL){why}")), "the record names what the line names"); + } + drop(p); + for &x in &s { + let _ = released(x); + } + // only the threads of that frame, the longest first, at most n: six threads alive at once + // (their ids apart), five of them in frame 0x7A1E_0680 and the longest in the next + let all = Arc::new(std::sync::Barrier::new(7)); + let (tx, rx) = mpsc::channel(); + let threads: Vec<_> = [(0x7A1E_0680u64, 300u64), (0x7A1E_0680, 500), (0x7A1E_0680, 100), (0x7A1E_0680, 400), (0x7A1E_0680, 200), (0x7A1E_0681, 900)] + .into_iter() + .map(|(f, w)| { + let (all, tx) = (all.clone(), tx.clone()); + std::thread::spawn(move || { + frame::set_for_test(f); + frame::waited(ms(w)); + tx.send((w, frame::tid_for_test())).unwrap(); + // (published; then held until the look is done) + all.wait(); + all.wait(); + }) + }) + .collect(); + all.wait(); + let tids: HashMap = rx.iter().take(6).collect(); + let said = frame::waits_in(0x7A1E_0680, 4); + // (the "no Present" line's clause in that frame: its 4 longest too) + frame::set_for_test(0x7A1E_0680); + let since = waits_since_present(); + all.wait(); + for t in threads { + t.join().unwrap(); + } + let longest: Vec = [500u64, 400, 300, 200].iter().map(|w| format!("thread {} waited {:.1} s for 1 pipelines", tids[w], *w as f64 / 1000.0)).collect(); + assert_eq!(said, longest.join(", "), "that frame's threads only, the 4 longest, the longest first"); + assert_eq!(since, said, "waits_since_present in that frame: its 4 longest"); + } + + /// With no frame of the test's own a thread's frame is the title's (`frame::now`: the frame + /// boundaries, `present::counters`): its budget spent, a frame boundary as the title's PresentX + /// makes one starts it again. (No other test makes one; another's would only start this + /// thread's budget again sooner.) Stand-ins 0x7A1E_07xx. + #[test] + fn a_threads_frame_budget_starts_again_at_the_titles_next_frame_boundary() { + let Some(cap) = wait_frame() else { + crate::gpu::recomp::runner::skip_config("XCL_PSO_WAIT_FRAME_MS=0: no budget a frame"); + return; + }; + let (a, b, c) = (0x7A1E_0701usize, 0x7A1E_0702usize, 0x7A1E_0703usize); + for (i, x) in [a, b, c].into_iter().enumerate() { + submit_held_for_test(x, true, small(0x07A1 + i as u64)); + } + // (a boundary first: from then on the frame is the boundaries', not the frames shown) + super::super::present::boundary_for_test(); + let first_frame = frame::now(); + assert_eq!(first_frame >> 63, 1, "a frame of the boundaries: {first_frame:#x}"); + let t = Instant::now(); + assert_eq!(resolve_wait_for(a, Some(cap + ms(500))), a); + let first = t.elapsed(); + assert!(first + ms(5) >= cap && first <= cap + ms(50), "cut to the frame's budget: {first:?}"); + let t = Instant::now(); + assert_eq!(resolve_wait_for(b, Some(ms(300))), b); + assert!(t.elapsed() < ms(30), "the budget spent: at once ({:?})", t.elapsed()); + assert!(frame::for_test().3, "told"); + super::super::present::boundary_for_test(); + assert_ne!(frame::now(), first_frame, "the boundary ended the frame"); + let t = Instant::now(); + assert_eq!(resolve_wait_for(c, Some(ms(300))), c); + let again = t.elapsed(); + assert!(again + ms(5) >= ms(300), "the next frame: waited again ({again:?})"); + let (waited, pipelines, without, told) = frame::for_test(); + assert!(waited + ms(5) >= ms(300) && waited < cap && (pipelines, without, told) == (1, 1, false), "({waited:?}, {pipelines}, {without}, {told})"); + assert!([a, b, c].into_iter().all(late_not_built)); + for x in [a, b, c] { + let _ = released(x); + } + } + + /// A wait cut to what is left of the frame's budget, during which the frame ends (a Present, on + /// another thread), counts for the new frame: there the budget is not spent – no spent line, + /// not told, the frame's waits that one wait – and the new frame's own budget, once spent, is + /// told with its waits. Stand-ins 0x7A1E_08xx. + #[test] + fn a_cut_wait_a_present_ends_counts_for_the_new_frame_and_tells_nothing() { + let Some(cap) = wait_frame() else { + crate::gpu::recomp::runner::skip_config("XCL_PSO_WAIT_FRAME_MS=0: no budget a frame"); + return; + }; + static EPOCH: AtomicU64 = AtomicU64::new(0x7A1E_0800); + frame::follow_for_test(&EPOCH); + let (a, b, c) = (0x7A1E_0801usize, 0x7A1E_0802usize, 0x7A1E_0803usize); + for (i, x) in [a, b, c].into_iter().enumerate() { + submit_held_for_test(x, true, small(0x08A1 + i as u64)); + } + // most of the budget in one wait; the next cut to the 600 ms left, 150 ms into which a + // Present ends the frame + let rest = ms(600); + assert_eq!(resolve_wait_for(a, Some(cap - rest)), a); + assert!(!frame::for_test().3, "not spent yet"); + let (go, went) = mpsc::channel::<()>(); + let presenter = std::thread::spawn(move || { + went.recv().unwrap(); + std::thread::sleep(ms(150)); + EPOCH.fetch_add(1, Ordering::AcqRel); + Instant::now() + }); + go.send(()).unwrap(); + let t = Instant::now(); + assert_eq!(resolve_wait_for(b, Some(ms(1000))), b); + let end = Instant::now(); + let took = end - t; + let presented = presenter.join().unwrap(); + assert!(presented > t && presented < end, "the Present came during the cut wait ({:?} into it, which took {took:?})", presented.saturating_duration_since(t)); + assert!(took + ms(50) >= rest && took <= rest + ms(50), "cut to what was left: {took:?}"); + let (waited, pipelines, without, told) = frame::for_test(); + assert!(waited + ms(50) >= rest && waited < cap && (pipelines, without, told) == (1, 1, false), "the new frame: that wait only, not told ({waited:?}, {pipelines}, {without}, {told})"); + assert_eq!(frame::told_for_test(), None, "no spent line"); + // the new frame's own budget, spent, is told + assert_eq!(resolve_wait_for(c, Some(cap + ms(500))), c); + let (waited, pipelines, without, told) = frame::for_test(); + assert!(waited >= cap && (pipelines, without, told) == (2, 2, true), "({waited:?}, {pipelines}, {without}, {told})"); + let line = frame::told_for_test().unwrap_or_default(); + assert!(line.contains(&format!(" waited {} ms for 2 pipelines since the last Present", waited.as_millis())), "{line}"); + for x in [a, b, c] { + let _ = released(x); + } + } + + /// The line a spent budget is told with is logged the first time of all and from then on at + /// powers of two (`frame::spent_said`; the numbers are shared with the other tests' threads): + /// this thread's budgets spent frame after frame are each told once, and each told one is logged + /// exactly when its number is due – written, not only recorded: with the log file held, another + /// thread whose spent budget's line is due waits for the file. Stand-ins and frames 0x7A1E_1xxx. + #[test] + fn a_spent_budget_is_logged_the_first_time_then_at_powers_of_two() { + assert!(frame::spent_said(1) && frame::spent_said(2) && !frame::spent_said(3) && frame::spent_said(4), "the first, the second, the fourth"); + assert!((5..8).chain(9..16).chain(17..32).all(|n| !frame::spent_said(n)) && [8, 16, 32, 1024].into_iter().all(frame::spent_said)); + let Some(cap) = wait_frame() else { + crate::gpu::recomp::runner::skip_config("XCL_PSO_WAIT_FRAME_MS=0: no budget a frame"); + return; + }; + // each frame: its budget waited, then a bind that goes on at once – told – until one told + // line was logged and one not + let mut s = Vec::new(); + for i in 0..0x400u64 { + let x = 0x7A1E_1000 + i as usize; + submit_held_for_test(x, true, small(0x1000 + i)); + s.push(x); + frame::set_for_test(0x7A1E_1000 + i); + frame::waited(cap); + assert_eq!(resolve_wait_for(x, Some(ms(300))), x); + let told = frame::spent_told_for_test(); + if told.iter().any(|t| t.1) && told.iter().any(|t| !t.1) { + break; + } + } + let told = frame::spent_told_for_test(); + assert_eq!(told.len(), s.len(), "each frame's budget told once: {told:?}"); + assert!(told.windows(2).all(|w| w[0].0 < w[1].0), "numbered one after another: {told:?}"); + assert!(told.iter().any(|t| t.1) && told.iter().any(|t| !t.1), "logged and not logged both seen: {told:?}"); + for &(n, logged) in &told { + assert_eq!(logged, frame::spent_said(n), "#{n}: logged when due, only then"); + } + // a due line is written, not only recorded (`SPENT_TOLD` is set next to the write): with the + // log file held by this thread, another thread's spent budget whose line is due waits for the + // file in went_without until it is let go (~10 ms) – a budget not due goes on, and is not + // looked at (a thread put off by the system would look the same) + let p = entry(*s.last().unwrap()).unwrap(); + let (ask, asked) = mpsc::channel::(); + let (back, came) = mpsc::channel::>(); + let teller = std::thread::spawn(move || { + while let Ok(i) = asked.recv() { + frame::set_for_test(0x7A1E_1800 + i); + frame::waited(cap); + frame::went_without(&p, true); + let _ = back.send(frame::spent_told_for_test().last().copied()); + } + }); + let mut due = None; + for i in 0..0x800u64 { + let file = crate::log::soon_test::hold_file(); + ask.send(i).unwrap(); + let at_once = came.recv_timeout(ms(10)).ok(); + drop(file); + let waited = at_once.is_none(); + if let Some((n, true)) = at_once.unwrap_or_else(|| came.recv().unwrap()) { + due = Some((n, waited)); + break; + } + } + drop(ask); + teller.join().unwrap(); + let (n, waited) = due.expect("a spent budget's line due within 0x800 frames"); + assert!(waited, "#{n}: its line written – its went_without waited for the log file"); + for x in s { + let _ = released(x); + } + } + + /// The "no Present" line's clause (`waits_since_present`) names the threads that waited in + /// the frame its caller is in: none yet, then this thread after its wait – and nobody after a + /// Present. Frame 0x7A1E_0B00. + #[test] + fn waits_since_present_names_who_waited_in_the_frame_now() { + frame::set_for_test(0x7A1E_0B00); + assert_eq!(waits_since_present(), "none", "nobody waited in this frame yet"); + frame::waited(ms(300)); + assert_eq!(waits_since_present(), format!("thread {} waited 0.3 s for 1 pipelines", frame::tid_for_test())); + frame::next_for_test(); + assert_eq!(waits_since_present(), "none", "a Present: nobody waited since"); + } + + /// The threads the "no Present" line can name are kept 64 at most (`frame::keep`, `LATELY`'s + /// rule), the oldest frame's let go: 65 threads waiting one after another, each in a frame after + /// the one before's – 64 kept, among them the newest frame's, not the oldest's; a thread kept that + /// waits again has its entry replaced. (On a table of the test's own: the 65 in `LATELY` itself + /// let go the other frame tests' threads while those looked – their frames are older.) + #[test] + fn the_threads_kept_for_the_no_present_line_are_64_the_oldest_frame_let_go() { + let mut lately = Vec::new(); + let entry = |i: u64| (0x7A1E_0D00 + i as u32, 0x7A1E_0C00 + i, ms(i), 1u32, 0u32); + for i in 0..65 { + frame::keep(&mut lately, entry(i)); + } + assert_eq!(lately.len(), 64, "64 kept"); + assert!(lately.contains(&entry(64)), "the newest frame's thread kept"); + assert!(!lately.iter().any(|e| e.0 == entry(0).0), "the oldest frame's thread let go"); + assert!((1..65).all(|i| lately.contains(&entry(i))), "the others kept"); + // a thread kept waits again: its entry replaced, none let go + let again = (entry(1).0, 0x7A1E_0C41, ms(7), 2, 1); + frame::keep(&mut lately, again); + assert_eq!(lately.len(), 64); + assert!(lately.contains(&again) && !lately.contains(&entry(1)) && lately.contains(&entry(2)), "replaced in place"); + // a new one lets go the oldest frame's now (thread 2's) + frame::keep(&mut lately, entry(65)); + assert!(lately.contains(&entry(65)) && !lately.iter().any(|e| e.0 == entry(2).0) && lately.contains(&again), "the oldest let go"); + } +} + +/// PP2's tiers (`Workers`): what needs no DXC first. Stand-ins 0x7A1E_3xxx (a block of 0x100 a +/// test; the one with the process's workers is in `lane_tests`), programs 0x7A1E_3xAx. A test's +/// own workers (`own_workers`: a queue no other test sends to) count exactly what it did; their +/// pipelines are in no table – nobody binds or releases them, so a job may give a fake pipeline. +#[cfg(test)] +mod tier_tests { + use super::*; + + fn ms(n: u64) -> Duration { + Duration::from_millis(n) + } + + /// `cond` within `limit`, looked at every 5 ms + fn poll(limit: Duration, cond: impl Fn() -> bool) -> bool { + let start = Instant::now(); + while !cond() { + if start.elapsed() >= limit { + return false; + } + std::thread::sleep(ms(5)); + } + true + } + + /// a pipeline of the test's own, built by `job` (None: never) + fn pending(standin: usize, compute: bool, job: Option, prog: Program) -> Arc { + Arc::new(Pending::new(standin, compute, job, true, 0, prog)) + } + + fn small(hash: u64) -> Program { + Program { hash, kind: b'C', dxil: 16 << 10, ..Default::default() } + } + + fn big(hash: u64) -> Program { + Program { hash, kind: b'C', dxil: 1 << 20, ..Default::default() } + } + + fn graphics(hash: u64) -> Program { + Program { hash, kind: b'G', ..Default::default() } + } + + /// a workers' queue of the test's own with `n` threads of its own (0: none – `threads` is set + /// by the test then) + fn own_workers(n: usize) -> &'static Workers { + let w: &'static Workers = Box::leak(Box::new(Workers::new())); + if n > 0 { + assert_eq!(w.start(n, |k| format!("xcl-tier-test-{k}"), 2 << 20), n, "its threads started"); + } + w + } + + /// Pipelines sent in four tiers' mix come out tier 1 first – the known and the translated + /// ones in one queue, in the order sent – then the cold ones in the order sent; the depths + /// count each from its push to its take, by tier and kind (P1; M-P1, M-P6). + #[test] + fn tiers_give_tier_one_first_and_each_tier_in_order() { + let w = own_workers(0); + // (no thread: as if one were there, so that `push` queues; the takes are the test's) + w.threads.store(1, Ordering::Release); + let a = pending(0x7A1E_3001, true, None, small(0x7A1E_30A1)); + let b = pending(0x7A1E_3002, true, None, small(0x7A1E_30A2)); + let c = pending(0x7A1E_3003, false, None, graphics(0x7A1E_30A3)); + let d = pending(0x7A1E_3004, false, None, graphics(0x7A1E_30A4)); + let e = pending(0x7A1E_3005, true, None, small(0x7A1E_30A5)); + for (p, t) in [(&a, TIER_COLD), (&b, TIER_KNOWN), (&c, TIER_COLD), (&d, TIER_TRANSLATED), (&e, TIER_KNOWN)] { + assert!(w.push(p, t)); + assert_eq!(p.tier.load(Ordering::Relaxed), t); + } + assert_eq!(w.depth.load(Ordering::Relaxed), 5); + assert_eq!(w.depths(), [[0, 2], [1, 0], [1, 1]], "[tier][graphics, compute]"); + let mut order = Vec::new(); + while let Some((p, big)) = w.try_next() { + assert!(!big); + order.push(p.standin); + } + assert_eq!(order, [0x7A1E_3002, 0x7A1E_3004, 0x7A1E_3005, 0x7A1E_3001, 0x7A1E_3003], "tier 1 first, each tier in the order sent"); + assert_eq!((w.depth.load(Ordering::Relaxed), w.depths()), (0, [[0; 2]; 3]), "counted out when taken"); + } + + /// A big compute pipeline of tier 1 is taken only while no worker holds the turn of such a one: + /// the next such one is passed over where it is – the tier's others and the cold ones are taken + /// – until the turn is given back (`commit_wait_over`, its holder's thread: also when its turn + /// ends – `BigTurn`); a big one of the cold tier is not held (A3). + #[test] + fn a_big_pipeline_of_tier_one_waits_for_the_turn_of_the_one_before() { + let w = own_workers(0); + w.threads.store(1, Ordering::Release); + let x1 = pending(0x7A1E_3101, true, None, big(0x7A1E_31A1)); + let x2 = pending(0x7A1E_3102, true, None, big(0x7A1E_31A2)); + let s = pending(0x7A1E_3103, true, None, small(0x7A1E_31A3)); + let cb = pending(0x7A1E_3104, true, None, big(0x7A1E_31A4)); + for (p, t) in [(&x1, TIER_KNOWN), (&x2, TIER_TRANSLATED), (&s, TIER_KNOWN), (&cb, TIER_COLD)] { + assert!(w.push(p, t)); + } + let take = || w.try_next().map(|(p, big)| (p.standin, big)); + assert_eq!(take(), Some((0x7A1E_3101, true)), "the first big one: its turn"); + let turn = BigTurn::hold(w); + assert_eq!(take(), Some((0x7A1E_3103, false)), "the second passed over: the next of tier 1"); + assert_eq!(take(), Some((0x7A1E_3104, false)), "a cold big one is not held"); + assert_eq!(take(), None, "only the held one left"); + assert_eq!(w.depth.load(Ordering::Relaxed), 1); + // (past its wait for commit; another thread's give-back gives nothing back) + std::thread::spawn(commit_wait_over).join().unwrap(); + assert_eq!(take(), None, "the turn is its holder's"); + commit_wait_over(); + assert_eq!(take(), Some((0x7A1E_3102, true)), "the turn given back: the second big one"); + assert_eq!((take(), w.depth.load(Ordering::Relaxed)), (None, 0)); + // the end of the first's turn, given back already: nothing; the end of the second's + // (never past a wait for commit – refused, say): given back + drop(turn); + assert!(w.lock().big_out, "the second's turn is held"); + let second = BigTurn::hold(w); + drop(second); + assert!(!w.lock().big_out, "the end of the second's turn gave it back"); + } + + /// A worker waiting for work wakes for a push (P2; M-P2). + #[test] + fn a_waiting_worker_wakes_for_a_push() { + let w = own_workers(0); + w.threads.store(1, Ordering::Release); + let (tx, rx) = mpsc::channel(); + let waiter = std::thread::spawn(move || { + let (p, _) = w.next(); + tx.send(p.standin).unwrap(); + }); + // (waiting by now) + std::thread::sleep(ms(100)); + assert!(rx.try_recv().is_err(), "nothing to take yet"); + assert!(w.push(&pending(0x7A1E_3201, false, None, graphics(0x7A1E_32A1)), TIER_COLD)); + assert_eq!(rx.recv_timeout(ms(5000)), Ok(0x7A1E_3201), "woken by the push"); + waiter.join().unwrap(); + } + + /// Four workers, four threads sending 100 pipelines each of every tier – some big compute ones + /// of tier 1 –: every one built within 10 s (no lost wakeup), the depths back to zero, and no + /// two big ones of tier 1 in their waits for commit at once (A3). Stand-ins 0x7A1E_33xx – + /// 0x7A1E_34xx. + #[test] + fn workers_build_everything_sent_from_many_threads() { + let w = own_workers(4); + let (built, big_now, big_most) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let senders: Vec<_> = (0..4usize) + .map(|s| { + let (built, big_now, big_most) = (built.clone(), big_now.clone(), big_most.clone()); + std::thread::spawn(move || { + for i in 0..100usize { + let tier = [TIER_KNOWN, TIER_TRANSLATED, TIER_COLD][i % 3]; + let is_big = i % 10 == 0 && tier != TIER_COLD; + let (built, big_now, big_most) = (built.clone(), big_now.clone(), big_most.clone()); + let job: Job = Box::new(move || { + if is_big { + // its wait for commit (one at a time), then its driver compile + big_most.fetch_max(big_now.fetch_add(1, Ordering::AcqRel) + 1, Ordering::AcqRel); + std::thread::sleep(ms(2)); + big_now.fetch_sub(1, Ordering::AcqRel); + commit_wait_over(); + std::thread::sleep(ms(1)); + } + built.fetch_add(1, Ordering::AcqRel); + 0x7A1E_3FF1 + }); + let k = 0x7A1E_3300 + s * 100 + i; + let prog = if is_big { big(k as u64) } else { small(k as u64) }; + assert!(w.push(&pending(k, true, Some(job), prog), tier)); + } + }) + }) + .collect(); + for s in senders { + s.join().unwrap(); + } + assert!(poll(ms(10_000), || built.load(Ordering::Acquire) == 400), "built {} of 400", built.load(Ordering::Acquire)); + assert!(poll(ms(1000), || w.depth.load(Ordering::Relaxed) == 0), "depth {}", w.depth.load(Ordering::Relaxed)); + assert_eq!(w.depths(), [[0; 2]; 3]); + assert_eq!(big_most.load(Ordering::Acquire), 1, "one big pipeline of tier 1 in its wait at a time"); + assert!(!w.lock().big_out, "every turn given back"); + } + + /// With no worker thread a pipeline sent is given up as before 0023.2: counted out again, its + /// queued state over, its job left for a bind, nothing queued (P6; M-P5). + #[test] + fn with_no_worker_a_sent_pipeline_is_given_up_as_before() { + let w = own_workers(0); + let p = pending(0x7A1E_3601, true, Some(Box::new(|| 0)), small(0x7A1E_36A1)); + // (as `send` does before) + p.note_queued(); + assert!(!w.push(&p, TIER_KNOWN), "no thread: given up"); + assert_eq!((w.depth.load(Ordering::Relaxed), w.depths()), (0, [[0; 2]; 3])); + assert_eq!(p.queued.load(Ordering::Acquire), STATE_DONE, "not counted as building"); + assert!(p.job.lock().unwrap().is_some(), "its job left for a bind"); + assert!(w.try_next().is_none(), "nothing queued"); + } + + /// A pipeline whose job a bind took while it waited in the queue is passed over by the worker + /// that takes it – counted out of the queue then, as before 0023.2 – and the worker goes on. + #[test] + fn a_pipeline_whose_job_a_bind_took_is_passed_over_and_counted_out() { + let w = own_workers(1); + let (started_tx, started) = mpsc::channel(); + let (open, gate) = mpsc::channel::<()>(); + let held: Job = Box::new(move || { + let _ = started_tx.send(()); + let _ = gate.recv_timeout(Duration::from_secs(5)); + 0x7A1E_3FF2 + }); + assert!(w.push(&pending(0x7A1E_3701, true, Some(held), small(0x7A1E_37A1)), TIER_COLD)); + started.recv_timeout(ms(5000)).expect("its one thread holds a build"); + let ran = Arc::new(AtomicUsize::new(0)); + let r2 = ran.clone(); + let x = pending( + 0x7A1E_3702, + true, + Some(Box::new(move || { + r2.fetch_add(1, Ordering::AcqRel); + 0x7A1E_3FF3 + })), + small(0x7A1E_37A2), + ); + assert!(w.push(&x, TIER_KNOWN)); + assert_eq!(w.depth.load(Ordering::Relaxed), 1, "queued"); + // a bind takes its job and builds it on its own thread (`resolve_wait_for` with no limit) + let job = x.job.lock().unwrap().take().unwrap(); + run(&x, job, Builder::Here); + assert_eq!((ran.load(Ordering::Acquire), x.real.load(Ordering::Acquire)), (1, 0x7A1E_3FF3)); + assert_eq!(w.depth.load(Ordering::Relaxed), 1, "still counted: no worker took it yet"); + drop(open); + assert!(poll(ms(5000), || w.depth.load(Ordering::Relaxed) == 0), "taken by the worker"); + let (tx, rx) = mpsc::channel(); + let next: Job = Box::new(move || { + let _ = tx.send(()); + 0x7A1E_3FF4 + }); + assert!(w.push(&pending(0x7A1E_3703, true, Some(next), small(0x7A1E_37A3)), TIER_COLD)); + rx.recv_timeout(ms(5000)).expect("the worker went on"); + assert_eq!(ran.load(Ordering::Acquire), 1, "passed over: not built again"); + } + + /// One worker at a time waits for commit for a big compute pipeline of tier 1 (A3: three such + /// builds would hold every worker in the wait): while the first's build waits (an injected look: + /// 2 GiB available, then 4) the second is not taken – the tier's small one and a cold one are, by + /// the other two workers –; once the first is past its wait, as `real::translated_compute_pso` + /// is (`commit_wait_over`), the second is taken while the first still builds. Stand-ins + /// 0x7A1E_38xx. + #[test] + fn one_worker_at_a_time_waits_for_commit_for_a_big_pipeline_of_tier_one() { + let w = own_workers(3); + static AVAILABLE: AtomicU64 = AtomicU64::new(2 << 30); + let counts: &'static [AtomicU64; 3] = Box::leak(Box::default()); + let seen = Arc::new(Mutex::new(Vec::new())); + let (open, gate) = mpsc::channel::<()>(); + let gate = Arc::new(Mutex::new(gate)); + // a big one's build: its wait for commit, the turn given back past it, then the driver's + // compile – the first's held at a gate until the test opens it + let big_job = |name: [&'static str; 3], held: bool| -> Job { + let (seen, gate) = (seen.clone(), gate.clone()); + Box::new(move || { + seen.lock().unwrap().push(name[0]); + super::super::real::wait_for_commit_in(counts, || Some(AVAILABLE.load(Ordering::Acquire)), ms(20)); + commit_wait_over(); + seen.lock().unwrap().push(name[1]); + if held { + let _ = gate.lock().unwrap().recv_timeout(Duration::from_secs(5)); + } + seen.lock().unwrap().push(name[2]); + 0x7A1E_3FF5 + }) + }; + let small_job = |name: &'static str| -> Job { + let seen = seen.clone(); + Box::new(move || { + seen.lock().unwrap().push(name); + 0x7A1E_3FF6 + }) + }; + let has = |what: &str| seen.lock().unwrap().contains(&what); + assert!(w.push(&pending(0x7A1E_3801, true, Some(big_job(["X1", "X1 past", "X1 done"], true)), big(0x7A1E_38A1)), TIER_KNOWN)); + assert!(w.push(&pending(0x7A1E_3802, true, Some(big_job(["X2", "X2 past", "X2 done"], false)), big(0x7A1E_38A2)), TIER_KNOWN)); + assert!(w.push(&pending(0x7A1E_3803, true, Some(small_job("S")), small(0x7A1E_38A3)), TIER_KNOWN)); + assert!(w.push(&pending(0x7A1E_3804, false, Some(small_job("C")), graphics(0x7A1E_38A4)), TIER_COLD)); + assert!(poll(ms(5000), || has("X1") && has("S") && has("C")), "the first big one waits for commit, the others are built: {:?}", seen.lock().unwrap()); + std::thread::sleep(ms(200)); + assert!(!has("X2"), "the second big one waits for the first's wait: {:?}", seen.lock().unwrap()); + assert_eq!(counts[2].load(Ordering::Acquire), 1, "one build waits for commit"); + assert_eq!(w.depth.load(Ordering::Relaxed), 1, "the second still queued"); + AVAILABLE.store(4 << 30, Ordering::Release); + assert!(poll(ms(5000), || has("X2 done")), "commit there: the second built: {:?}", seen.lock().unwrap()); + assert!(has("X1 past") && !has("X1 done"), "while the first still builds: {:?}", seen.lock().unwrap()); + drop(open); + assert!(poll(ms(5000), || has("X1 done")), "{:?}", seen.lock().unwrap()); + let seen = seen.lock().unwrap().clone(); + let at = |what: &str| seen.iter().position(|&s| s == what).unwrap(); + assert!(at("X1 past") < at("X2"), "the second taken once the first was past its wait: {seen:?}"); + assert_eq!(counts[2].load(Ordering::Acquire), 0); + assert_eq!(w.depth.load(Ordering::Relaxed), 0); + assert!(poll(ms(1000), || !w.lock().big_out), "every turn given back"); + } + + /// A translation lookup by its programs' hashes and translation parameters. + struct Disk { + /// (hash, stage, sampler base) → static samplers + on: Vec<(u64, Stage, u32, u32)>, + asked: RefCell>, + } + + impl Disk { + fn by(&self, h: u64, stage: Stage, base: u32, split: bool) -> Option { + self.asked.borrow_mut().push((h, stage, base, split)); + self.on.iter().find(|f| (f.0, f.1, f.2) == (h, stage, base)).map(|f| f.3) + } + + fn asked(&self) -> Vec<(u64, Stage, u32, bool)> { + self.asked.take() + } + } + + /// A pipeline's tier (`tier_with`, P4): known to the ledger – first; its shaders' translations + /// on disk – said so when made, or found by their hashes now: a CS (also one not found when + /// made, A2), a VS and its console PS, the PS at the sampler base the VS's static samplers give + /// it, with the program's split flag –; else, and with the switch off, cold; a pipeline with no + /// program, or whose shaders are translated otherwise, is cold with no look at the disk. + #[test] + fn the_tier_comes_from_the_ledger_and_the_shaders_translations() { + let disk = Disk { on: vec![(0xC5, Stage::Compute, 0, 0), (0x55, Stage::Vertex, 0, 3), (0xB5, Stage::Pixel, 3, 1), (0xB6, Stage::Pixel, 0, 1)], asked: RefCell::default() }; + let by = |h, st, base, split| disk.by(h, st, base, split); + let known = |k: u64| k == 0x7A1E_4C01; + let tier = |p: &Program| tier_with(p, true, known, by); + let cs = |h: u64, translated: Option| Program { kind: b'C', shaders: [h, 0], split: true, translated, ..small(0x7A1E_39A1) }; + let gs = |vs: u64, ps: u64, translated: Option| Program { shaders: [vs, ps], split: true, translated, ..graphics(0x7A1E_39A2) }; + // the ledger first, whatever the disk + assert_eq!(tier(&Program { key: 0x7A1E_4C01, ..cs(0xC6, None) }), TIER_KNOWN); + assert!(disk.asked().is_empty()); + // compute + assert_eq!(tier(&cs(0xC6, Some(true))), TIER_TRANSLATED, "found when made"); + assert!(disk.asked().is_empty()); + assert_eq!(tier(&cs(0xC5, None)), TIER_TRANSLATED); + assert_eq!(disk.asked(), [(0xC5, Stage::Compute, 0, true)]); + assert_eq!(tier(&cs(0xC5, Some(false))), TIER_TRANSLATED, "not found when made, found now (A2)"); + assert_eq!(tier(&cs(0xC6, Some(false))), TIER_COLD); + assert_eq!(tier(&cs(0xC6, None)), TIER_COLD); + assert_eq!(tier(&cs(0, None)), TIER_COLD, "no CS"); + disk.asked(); + // graphics + assert_eq!(tier(&gs(0x55, 0xB5, None)), TIER_TRANSLATED); + assert_eq!(disk.asked(), [(0x55, Stage::Vertex, 0, true), (0xB5, Stage::Pixel, 3, true)], "the PS at the VS's sampler count"); + assert_eq!(tier(&gs(0x55, 0xB6, None)), TIER_COLD, "the PS on disk at another sampler base only"); + assert_eq!(tier(&gs(0x55, 0, None)), TIER_TRANSLATED, "no console PS"); + disk.asked(); + assert_eq!(tier(&gs(0x56, 0xB5, None)), TIER_COLD); + assert_eq!(disk.asked(), [(0x56, Stage::Vertex, 0, true)], "the PS not asked without its VS"); + assert_eq!(tier(&gs(0x55, 0xB5, Some(false))), TIER_COLD, "a console HS, DS or GS"); + assert_eq!(tier(&Program { kind: b'M', translated: Some(false), shaders: [0x55, 0], ..Default::default() }), TIER_COLD, "a mesh stream"); + assert_eq!(tier(&Program::default()), TIER_COLD, "no program (`submit`)"); + assert!(disk.asked().is_empty(), "none of those looked up"); + // the switch off: all cold + for p in [Program { key: 0x7A1E_4C01, ..cs(0xC5, None) }, cs(0xC5, Some(true)), gs(0x55, 0xB5, None)] { + assert_eq!(tier_with(&p, false, known, by), TIER_COLD); + } + // this run's switch (XCL_PSO_TIERS=0: its own process) + let p = pending(0x7A1E_3901, true, None, cs(0xC5, Some(true))); + assert_eq!(tier_of(&p), if tiers_on() { TIER_TRANSLATED } else { TIER_COLD }, "XCL_PSO_TIERS on: {}", tiers_on()); + let env = std::env::var("XCL_PSO_TIERS").ok(); + assert_eq!(tiers_on(), env.as_deref().map(str::trim) != Some("0"), "XCL_PSO_TIERS={env:?}: on unless 0"); + } + + /// A pipeline whose shader another pipeline's build translated after it was made is tier 1 when + /// sent (A2): a compute one not translated when made, and a graphics one whose PS was not on disk + /// when the first pipeline of that PS was sent – through the translation cache as a build stores + /// it (a folder of the test's own: the user's cache is never written). + #[test] + fn a_pipeline_whose_shader_a_build_stored_since_is_tier_one_when_sent() { + use crate::gpu::recomp::pso::{translate_for_test, translated_by_hash_in, Compiled}; + let dir = std::env::temp_dir().join(format!("xcl-tier-a2-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let by = |h, st, base, split| translated_by_hash_in(&dir, 42, h, st, base, 4, split); + let (cs, vs, ps) = (b"a console CS (A2)".as_slice(), b"a console VS (A2)".as_slice(), b"a console PS (A2)".as_slice()); + let fnv = crate::gpu::shader::fnv64; + let compiled = |samplers: usize| Compiled { dxil: vec![1; 8], samplers: vec![([0; 4], false); samplers] }; + // compute: not on disk when made + let c = Program { kind: b'C', shaders: [fnv(cs), 0], split: true, translated: Some(false), ..small(fnv(cs)) }; + assert_eq!(tier_with(&c, true, |_| false, by), TIER_COLD, "not translated yet"); + translate_for_test(&dir, 42, cs, Stage::Compute, 0, 4, true, compiled(0)); + assert_eq!(tier_with(&c, true, |_| false, by), TIER_TRANSLATED, "a clone's build stored it since"); + // graphics: G1 and G2 share their PS; its translation comes with G1's build + translate_for_test(&dir, 42, vs, Stage::Vertex, 0, 4, true, compiled(2)); + let g = Program { shaders: [fnv(vs), fnv(ps)], split: true, ..graphics(fnv(vs)) }; + assert_eq!(tier_with(&g, true, |_| false, by), TIER_COLD, "G1: its PS not translated yet"); + translate_for_test(&dir, 42, ps, Stage::Pixel, 2, 4, true, compiled(1)); + assert_eq!(tier_with(&g, true, |_| false, by), TIER_TRANSLATED, "G2, after G1's build"); + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// PP3's lines: the queue line, every program's skips, the `[waits]` and end lines. Programs +/// 0x7A1E_3Cxx – 0x7A1E_3Dxx. +#[cfg(test)] +mod queue_line_tests { + use super::*; + + /// The queue line: its prefix (no tool's: not "pipelines (2 s)"), the queue now by tier and + /// kind, the rest since the last line said and so far, in this order (Q1). + #[test] + fn the_queue_line_says_its_fields_in_order() { + let last = QueueStats { tiers: [[0; 2]; 3], dxc: (0, 300), commit: [[2, 4000, 0], [1, 1000, 1]], first_uses: 684 }; + let now = QueueStats { tiers: [[1, 2], [10, 2], [230, 10]], dxc: (1, 302), commit: [[5, 4500, 2], [3, 2800, 1]], first_uses: 688 }; + let l = queue_text(&last, &now, "8cfa1517f0f10047 ×812 (1 programs)"); + assert_eq!( + l, + "pipeline queue (2 s): workers' queue 3 known + 12 translated + 240 cold (241 graphics, 14 compute); DXC compiles 1 running, 2 done (302 so far); big compiles waited for commit 500 ms on the big lane (3 begun, 2 waiting now) and 1800 ms on the workers (2 begun, 1 waiting now), 7 s so far; 4 first used with their built pipeline (688 so far); skipped most of every program: 8cfa1517f0f10047 ×812 (1 programs)" + ); + assert!(!l.contains("pipelines (2 s)") && !l.contains("XCL_SKIP_CS") && !l.contains("took "), "no tool's pattern: {l}"); + let idle = queue_text(&QueueStats::default(), &QueueStats::default(), "none"); + assert!(idle.starts_with("pipeline queue (2 s): workers' queue 0 known + 0 translated + 0 cold (0 graphics, 0 compute); DXC compiles 0 running, 0 done (0 so far)") && idle.ends_with("skipped most of every program: none"), "{idle}"); + } + + /// Every program's skips are counted, not only the first 32 named (Q2): of 40 programs the 40th, + /// skipped most, comes first – the naming of the first 32 as before –; a full table counts the + /// rest apart; hash 0 is not a program. + #[test] + fn skips_are_counted_for_every_program_not_only_the_first_32() { + let t = SkipTable::<64>::new(); + let mut named = Named { seen: Vec::new() }; + for i in 0..40u64 { + for _ in 0..=i { + t.note(0x7A1E_3C00 + i); + let _ = named.first_time(0x7A1E_3C00 + i); + } + } + let (programs, most) = t.most(8); + assert_eq!(programs, 40); + assert_eq!(most, (0..8u64).map(|k| (0x7A1E_3C27 - k, 40 - k)).collect::>(), "the most skipped first – the 40th program's"); + assert_eq!(named.seen.len(), 32, "named: the first 32, as before"); + assert!(!named.seen.iter().any(|e| e.0 == 0x7A1E_3C27)); + assert_eq!(t.text(2), "000000007a1e3c27 ×40, 000000007a1e3c26 ×39 (40 programs)"); + let full = SkipTable::<4>::new(); + for h in 1..=6u64 { + full.note(h); + } + full.note(0); + assert_eq!(full.most(8).0, 4, "4 places"); + assert_eq!(full.most(8).1.iter().map(|e| e.0).collect::>(), [1, 2, 3, 4], "4's own place is 1's: it is counted in one of the next"); + assert_eq!(full.others.load(Ordering::Relaxed), 2, "2 counted apart"); + assert!(full.text(8).ends_with("(4 programs, 2 skips of programs past its 4 places)"), "{}", full.text(8)); + assert_eq!(SkipTable::<4>::new().text(8), "none"); + } + + /// A skip told to `note_skip` is counted for its program in every program's table; the + /// `[waits]` line keeps every field before 0023.2 in their place and ends with the programs + /// skipped most; the end line says them too (atomics only). + #[test] + fn the_waits_and_end_lines_name_the_programs_skipped_most() { + let s = 0x7A1E_3D01usize; + submit_held_for_test(s, true, Program { hash: 0x7A1E_3DA1, kind: b'C', dxil: 16 << 10, ..Default::default() }); + for _ in 0..3 { + note_skip(s); + } + let (_, all) = SKIPS.most(4096); + assert_eq!(all.iter().find(|e| e.0 == 0x7A1E_3DA1).map(|e| e.1), Some(3), "three skips of its program"); + let l = probe_line(); + assert!(l.starts_with("pipelines: ") && l.contains(" skipped (most: "), "{l}"); + let (still, most) = (l.find("; the process stood still ").expect("its last field before 0023.2"), l.find(" s so far; skipped most of every program: ").expect("the clause")); + assert!(still < most && l[most..].contains("×"), "after every field before 0023.2: {l}"); + let e = end_line(); + assert!(e.starts_with("pipelines at the end: ") && e.contains(" skipped (pipeline not built); skipped most of every program: ") && e.contains("×"), "{e}"); + let _ = released(s); + } + + /// B50: the end line's fields in their places – built, failed and skipped from `report_counts`' + /// order (0, 1, 5) – and the `[waits]` line's (`probe_text`): every field before 0023.2 where it + /// was, the ledger's note only when it is not trusted, the programs skipped most of every one last. + #[test] + fn the_end_and_waits_lines_say_each_field_in_its_place() { + assert_eq!( + end_text([689, 12, 3, 4, 5, 20307], "000000007a1e3da1 ×3"), + "pipelines at the end: 689 built, 12 failed, 20307 skipped (pipeline not built); skipped most of every program: 000000007a1e3da1 ×3" + ); + let s = Stats { built: 1, failed: 2, refused: 3, went_late: 4, went_late_big: 5, late_binds: 6, skipped: 7, queued: [8, 9, 10], building: [11, 12, 13, 14], in_driver: 15, in_driver_most: 16 }; + assert_eq!( + probe_text(&s, (17, false), [18, 19], 20, "a ×1", "b ×2"), + "pipelines: 1 built, 2 failed; 3 programs refused, 4 + 5 big late (6 late binds), 7 skipped (most: a ×1); queued 8 + 9 big + 10 ahead, building 12 + 13 big + 11 binding + 14 ahead, 15 in the driver (at most 16 at once); sized from the translation cache 18, estimated 19; ledger 17 keys (not trusted); the process stood still 20 s so far; skipped most of every program: b ×2" + ); + assert!(probe_text(&s, (17, true), [18, 19], 20, "a", "b").contains("; ledger 17 keys; the process stood still 20 s so far; skipped most of every program: b"), "trusted: no note"); + } +} + +/// MP4: the first use of each pipeline built in this run. Stand-ins 0x7A1E_5xxx. +#[cfg(test)] +mod first_use_tests { + use super::*; + + /// A pipeline built by a worker and then bound three times – `resolve` twice, `resolve_wait` + /// once – is told once, at its first bind, with its program, where it was built and when (F1); + /// a first use through `resolve_wait`, and through a wait with a limit that sees its build end, + /// is told as well (each place a resolve gives the real pipeline). + #[test] + fn the_first_use_of_a_built_pipeline_is_recorded_once() { + let (s, s2, s3) = (0x7A1E_5001usize, 0x7A1E_5002usize, 0x7A1E_5003usize); + let mine = |s: usize| FIRST_MINE.with(|m| m.borrow().iter().filter(|&&x| x == s).count()); + let prog = |hash: u64| Program { hash, kind: b'C', dxil: 16 << 10, ..Default::default() }; + submit_program(s, true, Box::new(|| 0x7A1E_5F01), false, 0, prog(0x7A1E_50A1)); + submit_program(s2, true, Box::new(|| 0x7A1E_5F02), false, 0, prog(0x7A1E_50A2)); + let built = |s: usize| { + let t = Instant::now(); + while is_pending(s) { + assert!(t.elapsed() < Duration::from_secs(10), "its build did not end"); + std::thread::sleep(Duration::from_millis(5)); + } + }; + built(s); + assert_eq!(mine(s), 0, "built, not used yet"); + assert_eq!(resolve(s), 0x7A1E_5F01); + assert_eq!(mine(s), 1, "told at its first bind"); + assert_eq!(resolve(s), 0x7A1E_5F01); + assert_eq!(resolve_wait(s), 0x7A1E_5F01); + assert_eq!(mine(s), 1, "told once"); + if FIRST.n.load(Ordering::Acquire) <= 1024 { + let found: Vec = FIRST.recorded().into_iter().filter(|u| u.hash == 0x7A1E_50A1).collect(); + assert_eq!(found.len(), 1, "one place: {found:?}"); + let u = found[0]; + assert_eq!((u.standin, u.kind, u.dxil, u.lane), (s, b'C', 16 << 10, LANE_WORKERS)); + assert!(u.built_ms > 0 && u.at_ms >= u.built_ms, "{u:?}"); + } else { + crate::gpu::recomp::runner::skip_config("the first uses' 1024 places are full: its place not looked for"); + } + // first used through `resolve_wait`, built already + built(s2); + assert_eq!(resolve_wait(s2), 0x7A1E_5F02); + assert_eq!(mine(s2), 1, "told by resolve_wait"); + // first used through a wait with a limit that sees its build end – while no lane test holds + // the process's workers at its gates (its wait is cut at the frame's cap, 2 s) + let _lanes = super::lane_tests::lanes(); + submit_program( + s3, + true, + Box::new(|| { + std::thread::sleep(Duration::from_millis(100)); + 0x7A1E_5F03 + }), + false, + 0, + prog(0x7A1E_50A3), + ); + assert_eq!(resolve_wait_for(s3, Some(Duration::from_millis(3000))), 0x7A1E_5F03, "waited for"); + assert_eq!(mine(s3), 1, "told by the wait"); + // (their fake pipelines handed back, not released) + for s in [s, s2, s3] { + let _ = released(s); + } + } + + /// The places' protocol (F2): a use is read once, when ready; a place claimed and not written + /// yet stops the reader until it is; those past the places are counted, said once. + #[test] + fn a_first_use_place_is_read_only_once_it_is_ready() { + let f = FirstUses::<2>::new(); + let u = FirstUse { hash: 0x7A1E_50A2, standin: 0x7A1E_5002, kind: b'C', dxil: 16 << 10, estimated: false, lane: LANE_WORKERS, driver_ms: 12, built_ms: 1000, at_ms: 1250, presents: 77 }; + f.note(&u); + assert_eq!(f.lines(), ["[pso] first use of 000000007a1e50a2 (CS, 16 KB of DXIL) with its built pipeline at 1.250 s (77 presents so far): 250 ms after its build (on a worker, 12 ms in the driver; #1)"]); + assert!(f.lines().is_empty(), "read once"); + // claimed, not written yet: the reader stops there + assert_eq!(f.n.fetch_add(1, Ordering::AcqRel), 1); + assert!(f.lines().is_empty(), "not ready"); + let s = &f.slots[1]; + s.hash.store(0, Ordering::Relaxed); + s.standin.store(0x7A1E_5003, Ordering::Relaxed); + s.what.store(b'G' as u64 | (LANE_HERE as u64) << 8, Ordering::Relaxed); + s.built_ms.store(2000, Ordering::Relaxed); + s.at_ms.store(2000, Ordering::Relaxed); + s.ready.store(true, Ordering::Release); + assert_eq!(f.lines(), ["[pso] first use of stand-in 0x7a1e5003 with its built pipeline at 2.000 s (0 presents so far): 0 ms after its build (on a binding thread, 0 ms in the driver; #2)"]); + // past the places + f.note(&FirstUse { hash: 0x7A1E_50A4, ..u }); + f.note(&FirstUse { hash: 0x7A1E_50A5, ..u }); + assert_eq!(f.lines(), ["[pso] first uses of built pipelines past the first 2 are counted only (the pipeline queue line)"]); + assert!(f.lines().is_empty(), "said once"); + assert_eq!(f.n.load(Ordering::Acquire), 4, "counted"); + // (no tool's pattern: `[pso] … took N ms in the driver`, `refused`, `still building`, `work of`) + let l = first_use_line(&u, 1); + assert!(!l.contains("took ") && !l.starts_with("[pso] refused") && !l.starts_with("[pso] still") && !l.starts_with("[pso] work of"), "{l}"); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 94f4434..cd7256a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -208,6 +208,10 @@ pub fn uma_gpu_va() -> u64 { /// GPU virtual addresses of the UMA window buffers (`u2`, `u3`.. of the shader ABI). pub fn uma_window_vas() -> Vec { + #[cfg(test)] + if let Some(v) = TEST_WINDOW_VAS.with(|t| t.borrow().clone()) { + return v; + } UMA_BUFFER.lock().map(|g| g.iter().map(|b| b.1).collect()).unwrap_or_default() } @@ -816,6 +820,9 @@ pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { if obj.is_null() { return; } + // (the deferred releases' switches are settled on this thread, before any hook of the + // object's can ask for them on one of the host's) + super::late_release::init(); let v = vt(obj) as usize; if is_ext(v) { return; @@ -1051,6 +1058,9 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (8, x::create_command_queue_x as usize), (25, x::get_resource_allocation_info_x as usize), (26, x::get_custom_heap_properties_x as usize), + // MakeResident / Evict: a lazy title texture stays resident (`lazy_tex::residency`) + (34, dev_make_resident_x as usize), + (35, dev_evict_x as usize), (29, dev_create_placed_resource_x as usize), // CreateCommittedResource at its PC index too (XDefiant): console code uses the // buffer's GPU address as a CPU pointer – it goes into unified memory @@ -1300,6 +1310,18 @@ unsafe fn view_shape(res: &ID3D12Resource, format: windows::Win32::Graphics::Dxg Some((fmt, ty, w, h, depth, mips)) } +/// `view_shape`, with a view of a shape XCL cannot describe counted (`outside`; `uav`: a UAV) – +/// and for a buffer's (a NULL desc: a view XCL could have made raw) whether the buffer is in +/// unified memory. +unsafe fn shape_or_count(r: &ID3D12Resource, uav: bool, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, dim: i32, array: u32, mips: u32) -> Option<(u32, crate::gpu::desc::ImageType, u32, u32, u32, u32)> { + let s = view_shape(r, format, dim, array, mips); + if s.is_none() { + let buffer = (r.GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER).then(|| console_buffer(r.as_raw() as usize).is_some()); + super::outside::note_empty_view(if uav { super::outside::EmptyView::UavShape } else { super::outside::EmptyView::SrvShape }, None, buffer); + } + s +} + fn resource_dim_to_view(r: &D3D12_RESOURCE_DESC) -> i32 { match r.Dimension { D3D12_RESOURCE_DIMENSION_TEXTURE1D => { @@ -1321,13 +1343,43 @@ fn resource_dim_to_view(r: &D3D12_RESOURCE_DESC) -> i32 { } } -static NON_UMA_BUFFER_VIEWS: AtomicU64 = AtomicU64::new(0); +/// acceleration structure SRVs outside unified memory (an empty BVH descriptor each) +static RTAS_OUTSIDE_UMA: AtomicU64 = AtomicU64::new(0); + +/// Views made of title memory outside unified memory so far: (views given an empty descriptor – +/// all kinds, `outside` –, acceleration structures – an empty BVH descriptor each). +pub fn outside_uma_views() -> (u64, u64) { + (super::outside::empty_views(), RTAS_OUTSIDE_UMA.load(Ordering::Relaxed)) +} /// V# of a buffer view (raw: 4-byte elements, num_records in bytes; structured / typed: /// stride = element size, num_records in elements); empty when the buffer is not in UMA. -fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> [u32; 4] { - let Some((at, bytes)) = console_buffer(res) else { - note_buffer_view(); +fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool, uav: bool) -> [u32; 4] { + // local fix: a read-only view of the title's buffer outside unified memory reads a mirror + let mirrored = (!uav).then(|| title_address(res)).flatten().and_then(|ta| { + let p = res as *mut c_void; + let r = unsafe { ID3D12Resource::from_raw_borrowed(&p) }?; + let width = (unsafe { r.GetDesc() }.Width as usize).saturating_sub(buffer_delta(res) as usize); + unsafe { super::list_x::view_mirror(ta as u64, width, "buffer view") }.map(|m| (m, width)) + }); + let Some((at, bytes)) = console_buffer(res).or(mirrored) else { + let ta = title_address(res); + // the title memory it views, its elements as its V# would have them (`outside`: the + // count by kind, the pages) + let elem = u64::from(if raw { + 4 + } else if stride > 0 { + stride + } else { + crate::gpu::desc::format_bytes(crate::gpu::desc::gfx10_format(format).unwrap_or(22)) + }); + super::outside::note_empty_view( + if uav { super::outside::EmptyView::BufferUav } else { super::outside::EmptyView::BufferSrv }, + ta.map(|t| (t.saturating_add(first.saturating_mul(elem) as usize), u64::from(n).saturating_mul(elem))), + None, + ); + // ([diag] as before: its addresses compare with runs 62-64's) + note_empty_view_at(if raw { "raw buffer view" } else { "buffer view" }, ta.unwrap_or(0).saturating_add((first as usize).saturating_mul(stride.max(if raw { 4 } else { 1 }) as usize)), n as u64 * stride.max(4) as u64); return [0; 4]; }; let fmt = crate::gpu::desc::gfx10_format(format).unwrap_or(22); @@ -1345,6 +1397,27 @@ fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_ crate::gpu::desc::buffer_words(base, stride, records as u32, fmt) } +/// The title memory a buffer view of `res` names – its first element's address and the bytes of +/// its elements, as `buffer_view` counts an empty one (`outside`) – for XCL's record of the views +/// it writes (`console_heap::write_view`; None: no title address). +fn view_memory(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> Option<(usize, u64)> { + let elem = u64::from(if raw { + 4 + } else if stride > 0 { + stride + } else { + crate::gpu::desc::format_bytes(crate::gpu::desc::gfx10_format(format).unwrap_or(22)) + }); + title_address(res).map(|t| (t.saturating_add(first.saturating_mul(elem) as usize), u64::from(n).saturating_mul(elem))) +} + +/// The title address of a texture of a view (`title_textures`, a placed one), for XCL's record of +/// the views it writes (its bytes not counted: 0) – looked up when a line names the view's slot +/// (`console_heap::write_texture_view`): key lookups, `res` is never touched. +pub(super) fn texture_address(res: usize) -> Option<(usize, u64)> { + super::title_textures::address(res).or_else(|| title_address(res)).map(|a| (a, 0)) +} + /// Console buffer → a placed resource in the unified memory heap, so its console address is /// what the recompiled shaders read through `mem`. None: not placed (fall back to committed). /// A committed texture of console code: on the console its memory is unified memory too – @@ -1385,10 +1458,24 @@ unsafe fn place_console_texture(this: *mut c_void, desc: usize, state: usize, cl let align = (align as usize).max(0x1_0000); let bytes = (size as usize).div_ceil(align) * align; if u.size().saturating_sub(u.used()) < bytes + COHERENT_KEPT { + // (refused for the window's headroom: the caller makes a PC texture of its own, whose texels + // the title's CPU writes do not reach – with 0023.2's 256-MiB window a refusal from 128 MiB + // in use less the texture's size; the first 8 said, then at 16, 32, …) + static REFUSED: AtomicU64 = AtomicU64::new(0); + let n = REFUSED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: a committed texture of {} KB not placed in the coherent window ({} of {} MB in use, {} MB kept for readback heaps): a PC texture of its own, which the title's CPU writes do not reach (#{n})", + bytes >> 10, + u.used() >> 20, + u.size() >> 20, + COHERENT_KEPT >> 20 + ); + } return None; } let p = u.alloc(bytes, align)? as usize; - let hr = super::device_x::create_placed_resource_x(this, p as u64, desc as *const u8, state as u32, clear as *const c_void, riid, ppv); + let hr = super::device_x::with_source(super::device_x::Source::Committed, || super::device_x::create_placed_resource_x(this, p as u64, desc as *const u8, state as u32, clear as *const c_void, riid, ppv)); if hr < 0 || (*ppv).is_null() { u.free(p); return None; @@ -1613,11 +1700,45 @@ pub(super) fn set_test_buffer_delta(res: usize, delta: Option) { } } +#[cfg(test)] +pub(super) fn set_test_title_address(res: usize, va: Option) { + let mut g = TITLE_ADDRESS.lock().unwrap(); + match va { + Some(v) => { + g.get_or_insert_with(HashMap::new).insert(res, v); + } + None => { + if let Some(m) = g.as_mut() { + m.remove(&res); + } + } + } +} + +/// `res` as a console buffer in unified memory at `at` (not XCL's memory: nothing is freed with it) +#[cfg(test)] +pub(super) fn set_test_console_buffer(res: usize, at: Option<(usize, usize)>) { + let mut g = UMA_BUFFERS.lock().unwrap(); + match at { + Some((p, n)) => { + g.get_or_insert_with(HashMap::new).insert(res, (p, n, false)); + } + None => { + if let Some(m) = g.as_mut() { + m.remove(&res); + } + } + } +} + /// resource Release (every caller): a console buffer's unified memory goes with it /// Map: on the console every resource is CPU-visible memory. One in unified memory that the /// PC cannot map (a texture XCL keeps in step with it) gives its unified-memory address – what /// the console gives; the CPU's writes there reach the texture (`title_textures`). unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_void, data: *mut *mut c_void) -> HRESULT { + if let Some(a) = traced_res(this as usize) { + crate::xlog_info!("[trace] Map of the resource at {a:#x} ({this:p}), subresource {sub}; from {}", crate::hle::kernelx::callers(1)); + } // a resource in unified memory: its console address (no PC mapping – the PC's would be // the start of the PC resource, before the address for a buffer placed below it) if let Some((p, bytes)) = console_buffer(this as usize) { @@ -1668,6 +1789,10 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v /// WriteToSubresource(subresource, box, data, row pitch, depth pitch): the CPU writing texels. /// Every console resource is CPU-visible memory, a PC texture only in a CPU-visible heap. unsafe extern "system" fn res_write_to_subresource(this: *mut c_void, sub: u32, dst_box: *const D3D12_BOX, data: *const c_void, row_pitch: u32, depth_pitch: u32) -> HRESULT { + let _xcl_api = crate::waitwatch::api("real::res_write_to_subresource"); + if let Some(a) = traced_res(this as usize) { + crate::xlog_info!("[trace] WriteToSubresource into the resource at {a:#x} ({this:p}), subresource {sub}, row pitch {row_pitch}; from {}", crate::hle::kernelx::callers(1)); + } type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_BOX, *const c_void, u32, u32) -> HRESULT; let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "WriteToSubresource"))); let hr = f(this, sub, dst_box, data, row_pitch, depth_pitch); @@ -1695,6 +1820,50 @@ pub(super) fn title_address(res: usize) -> Option { console_buffer(res).map(|b| b.0).or_else(|| TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied())) } +/// Local fix: the PC buffer resource that stands for title memory `[va, va + len)` – a buffer +/// the title placed at its own address that got a PC resource of its own (`TITLE_ADDRESS`) – +/// and the PC offset of `va` in it. GPU work on that buffer (ResolveQueryData, copies, UAV +/// writes) lands in the PC resource, not in the title's memory. +/// The resource comes with a reference of the caller's (taken while it is still registered), +/// so a copy recorded from it keeps it until the copy ran. +pub(super) unsafe fn title_buffer_at(va: usize, len: usize) -> Option<(ID3D12Resource, u64)> { + let end = va.checked_add(len)?; + let g = TITLE_ADDRESS.lock().unwrap(); + let m = g.as_ref()?; + for (&res, &at) in m.iter() { + if va < at || res == 0 { + continue; + } + let p = res as *mut c_void; + let Some(r) = ID3D12Resource::from_raw_borrowed(&p) else { continue }; + let d = r.GetDesc(); + if d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER { + continue; + } + let delta = buffer_delta(res); + let size = (d.Width as usize).saturating_sub(delta as usize); + if end <= at.saturating_add(size) { + return Some((r.clone(), (va - at) as u64 + delta)); + } + } + None +} + +/// Local diagnostic: the placed title resources nearest to `va` (res, address, PC width, delta). +pub(super) unsafe fn describe_near(va: usize) -> String { + let g = TITLE_ADDRESS.lock().unwrap(); + let Some(m) = g.as_ref() else { return "no placed resources".into() }; + let mut v: Vec<(usize, usize, usize)> = m.iter().map(|(&r, &a)| (a.abs_diff(va), r, a)).collect(); + v.sort_unstable(); + let total = v.len(); + let near: Vec = v.iter().take(4).map(|&(dist, r, a)| { + let p = r as *mut c_void; + let (dim, w) = ID3D12Resource::from_raw_borrowed(&p).map_or((0, 0), |x| { let d = x.GetDesc(); (d.Dimension.0, d.Width) }); + format!("{a:#x} (dist {dist:#x}, dim {dim}, width {w:#x}, delta {:#x})", buffer_delta(r)) + }).collect(); + format!("{total} placed resources; nearest: {}", near.join("; ")) +} + pub(super) fn note_title_address(res: usize, va: usize) { TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, va); } @@ -1713,41 +1882,140 @@ unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c } unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { - let mac = crate::util::mac_host(); - let _releasing = mac.then(|| super::title_textures::ResourceRelease::begin(this as usize)); - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - // The last reference: kept until the queues are past the work in flight (`late_release`). - // (Two last-but-one releases at once can miss each other here; the object then goes at - // once, as before.) - let mut held = false; - let n = if super::late_release::enabled() { - let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); - if add(this) == 2 { - f(this); - held = true; - 0 + hooked_release(this, Kind::Resource) +} + +/// The Release of an adopted object of `kind` (every caller: the title, XCL, the host's own +/// calls through the object's table – D3DMetal's on threads of its own too, which have no TEB: +/// what runs here before the object is held touches atomics only, `late_release` says how). With `late_release::defers(kind)` its last reference is +/// held until every queue is past the work submitted so far, and what XCL keeps by the +/// object's address goes with its real end (`release_held`); on the Mac the object's memory +/// (its backing, its pins) stays as long as the object. +/// +/// The test for the last reference (AddRef, compare with 2, Release) runs under the object's +/// stripe: two last-but-one releases at once otherwise both missed it, and the object went at +/// once, inside the hook – possibly from inside D3DMetal's ExecuteCommandLists, while the +/// command buffer that had just used it was being committed. The hook takes no lock but the +/// stripe and the ledger's leaf lock, and ends nothing itself (D3DMetal calls it re-entrantly). +pub(super) unsafe fn hooked_release(this: *mut c_void, kind: Kind) -> u32 { + let release: RefFn = std::mem::transmute(orig_fn(this, 2)); + if !super::late_release::defers(kind) { + let n = release(this); + if n == 0 { + gone(this as usize, kind); + } + return n; + } + let add_ref: RefFn = std::mem::transmute(orig_fn(this, 1)); + let left = { + let _one = super::late_release::stripe(this as usize); + // (held only when AddRef and Release both say so: a count that does not add up – not + // a COM count, or a release not through this table meanwhile – goes as it is) + let a = add_ref(this); + let r = release(this); + if a == 2 && r == 1 { + // the caller's reference, the last, is the ledger's now + None } else { - f(this); - f(this) + Some(release(this)) } - } else { - f(this) }; - // Keep the backing and its pins alive together with the resource on D3DMetal. - if n == 0 && !(held && mac) { - forget_resource(this as usize); + match left { + None => { + // elsewhere than on the Mac what XCL keeps by its address goes now, as it did + if !super::late_release::mac() { + gone(this as usize, kind); + } + super::late_release::hold(this as usize, kind); + 0 + } + Some(0) => { + // a release that is not through this table ended it meanwhile + gone(this as usize, kind); + 0 + } + Some(n) => { + // one reference left: maybe the ledger's, after work of XCL's own on the object + // (an upload into a texture the title let go of) – that work is waited for too + if n == 1 { + super::late_release::touched(this as usize, kind); + } + n + } } - if held { - super::late_release::hold(this as usize); +} + +/// The ledger lets a held reference go (`late_release`, outside every lock of XCL's). When it is +/// the object's last, what XCL keeps by the object's address goes first (on the Mac: lookups, +/// backing memory, pins), the object being still alive, and its end comes outside the stripe +/// (its destructor can release other objects, whose hooks take locks of their own). When XCL +/// took another reference meanwhile, only the ledger's goes: the other one's Release is the +/// last then, and is held in turn. Objects that are not adopted (a sparse pool made before the +/// device was) go through their own table. +pub(super) unsafe fn release_held(ptr: usize, kind: Kind) { + let this = ptr as *mut c_void; + let (add_ref, release): (RefFn, RefFn) = if is_adopted(this) { + (std::mem::transmute(orig_fn(this, 1)), std::mem::transmute(orig_fn(this, 2))) + } else { + (std::mem::transmute(*vt(this).add(1)), std::mem::transmute(*vt(this).add(2))) + }; + let left = { + let _one = super::late_release::stripe(ptr); + let a = add_ref(this); + let r = release(this); + if a == 2 && r == 1 { + None + } else { + Some(release(this)) + } + }; + let mac = crate::util::mac_host(); + match left { + None => { + // local fix (kept): what XCL keeps of it goes BEFORE the final Release. Forgetting + // a resource after it left a window in which `title_textures::poll_unwatched` + // (present thread, under the TEXTURES lock) found the entry and AddRef'd a + // destroyed object (access violation reading 0x8 in IUnknown::clone). (The + // ledger's reference keeps it alive meanwhile: one taken through a lookup before + // it went is the last then, and is held in turn.) + if mac { + gone(ptr, kind); + } + release(this); + } + // (a count that did not add up and the object ended: what XCL keeps goes after all) + Some(0) if mac => gone(ptr, kind), + Some(_) => {} } - n } -pub(super) unsafe fn release_held_resource(this: *mut c_void, mac: bool) { - let _releasing = mac.then(|| super::title_textures::ResourceRelease::begin(this as usize)); - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - if f(this) == 0 && mac { - forget_resource(this as usize); +/// An object of `kind` goes for good: what XCL keeps by its address goes with it (a later +/// object may get the same address). +unsafe fn gone(ptr: usize, kind: Kind) { + match kind { + Kind::Resource => forget_resource(ptr), + Kind::PipelineState => { + // a stand-in pipeline takes its background-built real pipeline with it + forget_pso(ptr); + super::pso_async::release(super::pso_async::released(ptr)); + } + // a console heap's slots go with it + Kind::DescriptorHeap => super::console_heap::unregister(ptr), + Kind::Heap => heap_gone(ptr), + Kind::CommandList | Kind::DmaList => { + super::list_x::on_release(ptr); + super::bind::forget(ptr as *mut c_void); + } + Kind::CommandAllocator => { + super::alloc_pool::forget(ptr); + super::list_x::on_allocator_release(ptr); + // (its recordings are done: what `indirect` held for them is let go) + if crate::util::mac_host() { + super::indirect::allocator_reset(ptr); + } + } + Kind::CommandSignature => super::bind::forget_mac_signatures(ptr), + _ => {} } } @@ -1761,12 +2029,16 @@ unsafe fn forget_resource(res: usize) { if let Some(m) = BUFFER_DELTA.lock().unwrap().as_mut() { m.remove(&res); } - if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() { - m.remove(&res); + // (a resource the title placed at its address: its census entry goes too, when it has one – + // `outside`; the other releases never look at the census's lock) + let placed = TITLE_ADDRESS.lock().unwrap().as_mut().is_some_and(|m| m.remove(&res).is_some()); + if placed { + super::outside::forget(res); } super::sparse::forget_buffer(res); super::present::forget(res); super::vram::forget(res); + super::lazy_tex::forget(res); super::title_textures::forget(res); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&res)); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { @@ -1778,15 +2050,10 @@ unsafe fn forget_resource(res: usize) { } } -/// A stand-in pipeline released for good takes its background-built real pipeline with it. +/// A stand-in pipeline released for good takes its background-built real pipeline with it +/// (`gone`). unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - forget_pso(this as usize); - super::pso_async::release(super::pso_async::released(this as usize)); - } - n + hooked_release(this, Kind::PipelineState) } /// A pipeline state is gone: drop what XCL keeps by its address (a later pipeline may get the @@ -1839,6 +2106,32 @@ pub fn is_translated_compute(pso: usize) -> bool { pso != 0 && TRANSLATED_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } +/// pipelines the title got with XCL's fallback shaders – its own console shaders have no +/// translation, or the driver refused its shaders – → whether they compute: they draw and compute +/// nothing, and no bind gives them to the PC (`bind::unbuilt`) +static FALLBACK_PSOS: Mutex>> = Mutex::new(None); + +unsafe fn note_fallback_pso(ppv: *mut *mut c_void, compute: bool) { + if !ppv.is_null() && !(*ppv).is_null() { + FALLBACK_PSOS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, compute); + } +} + +/// Whether `pso` is a pipeline of XCL's fallback shaders: Some(it computes). +pub fn fallback_kind(pso: usize) -> Option { + if pso == 0 { + return None; + } + FALLBACK_PSOS.lock().unwrap().as_ref()?.get(&pso).copied() +} + +#[cfg(test)] +pub(super) fn register_fallback_for_test(pso: usize, compute: bool) { + if pso != 0 { + FALLBACK_PSOS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, compute); + } +} + #[cfg(test)] pub(super) fn register_translated_compute_for_test(pso: usize) { if pso != 0 { @@ -1846,6 +2139,13 @@ pub(super) fn register_translated_compute_for_test(pso: usize) { } } +/// (tests) `pso` runs the console compute program `hash` (`threads` in a group), as a translated +/// pipeline does (`pso_console_cs`). +#[cfg(test)] +pub(super) fn register_console_cs_for_test(pso: usize, hash: u64, threads: u32) { + PSO_CS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, (hash, threads)); +} + #[cfg(test)] pub(super) fn register_rect_list_gs_for_test(pso: usize) { if pso != 0 { @@ -1881,6 +2181,12 @@ fn forget_pso(pso: usize) { if let Some(m) = PSO_USER_SGPRS.lock().unwrap().as_mut() { m.remove(&pso); } + if let Some(m) = PSO_CS.lock().unwrap().as_mut() { + m.remove(&pso); + } + if let Some(m) = FALLBACK_PSOS.lock().unwrap().as_mut() { + m.remove(&pso); + } super::device_x::forget_base(pso); // the compute pass goes with the last user of its entry (`Drop for TwoPassPso`) let gone = TWO_PASS.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)); @@ -1956,9 +2262,65 @@ unsafe fn texture_memory(res: *mut c_void) -> Option { Some(p) } -fn note_buffer_view() { - if NON_UMA_BUFFER_VIEWS.fetch_add(1, Ordering::Relaxed) == 0 { - crate::xlog_warn!("buffer view in the console heap: the buffer is not in UMA – the shader gets an empty V# (num_records 0)"); +/// local diagnostic: an empty V# for a view of title memory at `va` (`kind`), logged once per +/// address for the first 64 addresses (which memory shaders lose their access to) +fn note_empty_view_at(kind: &str, va: usize, bytes: u64) { + static SEEN: Mutex>> = Mutex::new(None); + let mut g = SEEN.lock().unwrap(); + let s = g.get_or_insert_with(HashSet::new); + if s.len() < 64 && s.insert(va) { + crate::xlog_info!("[diag] empty V# #{}: {kind} at {va:#x} ({bytes:#x} bytes) – outside unified memory", s.len()); + } +} + +/// (diagnostic `XCL_TRACE_PAGES`) The title address of `res` if it lies over a traced page. +pub(super) fn traced_res(res: usize) -> Option { + if res == 0 || !crate::hle::kernelx::tracing() { + return None; + } + let a = title_address(res).or_else(|| super::title_textures::address(res))?; + crate::hle::kernelx::traced_range(a, 1).then_some(a) +} + +/// local diagnostic (`XCL_TRACE_PAGES`): a view of a resource over a traced page – what it is +/// and who made it. +unsafe fn note_traced_view(kind: &str, res: *mut c_void, extra: &str) { + if !crate::hle::kernelx::tracing() { + return; + } + let Some(ta) = title_address(res as usize) else { return }; + let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { return }; + let d = r.GetDesc(); + let len = if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { (d.Width as usize).saturating_sub(buffer_delta(res as usize) as usize) } else { 0x1_0000 }; + let textures = super::title_textures::overlapping(ta, len.max(1)); + if !crate::hle::kernelx::traced_range(ta, len) && !textures.iter().any(|&(_, va)| crate::hle::kernelx::traced_range(va, 1)) { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 48 { + crate::xlog_info!( + "[trace] {kind} of a resource at {ta:#x} over a traced page: dimension {}, {}x{}x{}, format {}, flags {:#x}{extra}; from {}", + d.Dimension.0, + d.Width, + d.Height, + d.DepthOrArraySize, + d.Format.0, + d.Flags.0, + crate::hle::kernelx::callers(2) + ); + } +} + +/// local diagnostic: a view of a small title texture (data-sized: at most 256x16) – where +/// console code writes results it reads back +unsafe fn note_small_view(kind: &str, res: *mut c_void) { + let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { return }; + let d = r.GetDesc(); + if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && d.Width <= 256 && d.Height <= 16 { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 32 { + crate::xlog_info!("[diag] {kind} of a small texture {}x{} format {} at title address {:x?} (res {:#x})", d.Width, d.Height, d.Format.0, title_address(res as usize), res as usize); + } } } @@ -1966,17 +2328,29 @@ fn note_buffer_view() { /// (`desc::cbv_words`; unified memory, anything else gets an empty V#). No PC CBV: translated /// shaders read buffers through `mem`. unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, cpu: u64) { + let _xcl_api = crate::waitwatch::api("real::dev_create_cbv_x"); let Some(slot) = super::console_heap::slot(cpu).filter(|s| !s.sampler) else { let f: unsafe extern "system" fn(*mut c_void, *const D3D12_CONSTANT_BUFFER_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 17)); return f(this, desc, cpu); }; let (va, size) = desc.as_ref().map_or((0, 0), |d| (d.BufferLocation, d.SizeInBytes)); + if crate::hle::kernelx::traced_range(va as usize, size as usize) { + crate::xlog_info!("[trace] CBV at {va:#x} ({size} bytes) over a traced page; from {}", crate::hle::kernelx::callers(1)); + } + super::console_heap::write_view(&slot, &cbv_view(va, size), "CBV", || (va != 0).then_some((va as usize, u64::from(size)))); +} + +/// The V# of a CBV of `size` bytes at `va` (`desc::cbv_words`): of unified memory, of a view +/// mirror, else empty – counted (`outside`) and its first 64 addresses logged (`note_empty_view_at`). +unsafe fn cbv_view(va: u64, size: u32) -> [u32; 4] { let in_uma = crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); - if !in_uma { - note_buffer_view(); + let mirror = if in_uma { None } else { super::list_x::view_mirror(va, size as usize, "constant buffer view") }; + if !in_uma && mirror.is_none() { + super::outside::note_empty_view(super::outside::EmptyView::Cbv, (va != 0).then_some((va as usize, u64::from(size))), None); + note_empty_view_at("CBV", va as usize, size as u64); } - let (va, size) = if in_uma { (va, size) } else { (0, 0) }; - super::console_heap::write(&slot, &crate::gpu::desc::cbv_words(va, size)); + let (va, size) = if in_uma { (va, size) } else if let Some(m) = mirror { (m as u64, size) } else { (0, 0) }; + crate::gpu::desc::cbv_words(va, size) } /// #22 CreateSampler: the PC sampler at the slot's index, the S# in XCL ABI form (word 3 @@ -1985,7 +2359,7 @@ pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, des let f: unsafe extern "system" fn(*mut c_void, *const D3D12_SAMPLER_DESC, u64) = std::mem::transmute(orig_fn(this, 22)); let Some(slot) = super::console_heap::slot(cpu).filter(|s| s.sampler) else { return f(this, desc, cpu) }; f(this, desc, slot.pc_srv); - super::console_heap::write(&slot, &[0, 0, 0, slot.index & 0xFFF]); + super::console_heap::write_view(&slot, &[0, 0, 0, slot.index & 0xFFF], "sampler", || None); } /// Copy `n` console slots from `src` to `dst` (both in console heaps of one kind): the PC @@ -2004,13 +2378,28 @@ unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: } let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64; for k in 0..n as u64 { - if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) { + let (d, s) = (slot(dst + k * step), slot(src + k * step)); + if let (Some(d), Some(s)) = (d, s) { copy_words(&s, &d); } + // (the view census: both PC descriptors of the slot were copied above, in the title's heap + // and then in the shared heap) + if let Some(d) = d { + super::console_heap::note_copied_view(&d, s.as_ref()); + } } true } +/// Descriptors of `n` ranges of `sizes` (null: one each) – the view census's count of copies +/// outside the console heaps. +unsafe fn descriptors_in(n: u32, sizes: *const u32) -> u64 { + if sizes.is_null() { + return u64::from(n); + } + (0..n as usize).map(|r| u64::from(*sizes.add(r))).sum() +} + /// `XCL_TRACE_FRAME`: the device's descriptor copies (first few, and a count) fn note_copy_call(what: &str, n: u32, dst: u64, src: u64) { static N: AtomicU64 = AtomicU64::new(0); @@ -2030,6 +2419,7 @@ fn note_mixed_copy() { /// #24 CopyDescriptorsSimple(n, dst, src, type) unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) { + let _xcl_api = crate::waitwatch::api("real::dev_copy_descriptors_simple_x"); let ty = pc_heap_type(ty); note_copy_call("CopyDescriptorsSimple", n, dst, src); if copy_console_slots(this, n, dst, src, ty) { @@ -2041,11 +2431,15 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 } let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, n, dst, src, ty); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 { + super::view_census::note_outside(u64::from(n)); + } } /// #23 CopyDescriptors(dst ranges, src ranges, type): range by range over console slots. #[allow(clippy::too_many_arguments)] unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32, ty: u32) { + let _xcl_api = crate::waitwatch::api("real::dev_copy_descriptors_x"); let ty = pc_heap_type(ty); note_copy_call("CopyDescriptors", nd, if dsts.is_null() { 0 } else { *dsts }, if srcs.is_null() { 0 } else { *srcs }); use super::console_heap::{slot, SAMPLER_SLOT, SLOT}; @@ -2057,7 +2451,12 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst } type F = unsafe extern "system" fn(*mut c_void, u32, *const u64, *const u32, u32, *const u64, *const u32, u32); let f: F = std::mem::transmute(orig_fn(this, 23)); - return f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); + f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); + // (a copy between PC heaps that are not console heaps: outside the view census's map) + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 && super::view_census::names().is_some() { + super::view_census::note_outside(descriptors_in(nd, dsizes)); + } + return; } // every descriptor as (dst, src) handle, ranges walked in step let step = if ty == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32 { SAMPLER_SLOT } else { SLOT } as u64; @@ -2076,18 +2475,15 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst } } -/// descriptor heap Release (every caller): a console heap's slots go with it +/// descriptor heap Release (every caller): a console heap's slots go with it (`gone`) unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - super::console_heap::unregister(this as usize); - } - n + hooked_release(this, Kind::DescriptorHeap) } /// #21 CreateDepthStencilView: the console's view formats as the PC's (`pc_view_format`). unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, cpu: u64) { + let _xcl_api = crate::waitwatch::api("real::dev_create_dsv_x"); + note_traced_view("DSV", res, ""); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 21)); let mut copy = desc.as_ref().copied(); if let Some(c) = copy.as_mut() { @@ -2200,6 +2596,9 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) } unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, cpu: u64) { + let _xcl_api = crate::waitwatch::api("real::dev_create_srv_x"); + note_small_view("SRV", res); + note_traced_view("SRV", res, ""); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); let mut copy = desc.as_ref().copied(); if let Some(c) = copy.as_mut() { @@ -2216,7 +2615,11 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } } let desc = copy.as_ref().map_or(desc, |c| c as *const _); - let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; + let Some(slot) = super::console_heap::slot(cpu) else { + f(this, res, desc, cpu); + // (a PC heap that is not a console heap: outside the view census's map) + return super::view_census::note_outside(1); + }; // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): // translated shaders read BVH nodes from UMA (`bvh_intersect`), never from a PC DXR SRV, // so write the RDNA2 BVH descriptor directly and skip forwarding the console VA to PC. @@ -2225,20 +2628,27 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, let in_uma = va != 0 && crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); if in_uma { let w = crate::gpu::desc::bvh_words(va, true); - return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); + return super::console_heap::write_view(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0], "acceleration structure SRV", || Some((va as usize, 0))); } - static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { + if RTAS_OUTSIDE_UMA.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: CreateShaderResourceView(RAYTRACING_ACCELERATION_STRUCTURE) at {va:#x} is not in unified memory – writing empty BVH descriptor"); } - return super::console_heap::write(&slot, &[0; 8]); + return super::console_heap::write_view(&slot, &[0; 8], "acceleration structure SRV", || (va != 0).then_some((va as usize, 0))); } // translated shaders declare every cube T# as a TextureCubeArray: a title's TEXTURECUBE // view becomes the cube array of that one cube (a dimension mismatch is undefined in D3D12) let cube = desc.as_ref().and_then(cube_as_cube_array); let desc = cube.as_ref().map_or(desc, |v| v as *const _); - f(this, res, desc, slot.pc_srv); - super::console_heap::publish(&slot, false); + { + let _xcl_api = crate::waitwatch::api("real::dev_create_srv_x: the PC's CreateShaderResourceView"); + f(this, res, desc, slot.pc_srv); + // (the view census: what the SRV just made names – a buffer, or none for a null view) + super::console_heap::note_pc_view(&slot, false, res as usize); + } + { + let _xcl_api = crate::waitwatch::api("real::dev_create_srv_x: console_heap::publish"); + super::console_heap::publish(&slot, false); + } super::console_heap::note_resource(&slot, res as usize); if super::present::trace_frame() && super::title_textures::address(res as usize).is_some() { static N: AtomicU64 = AtomicU64::new(0); @@ -2252,12 +2662,13 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } } let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { - return super::console_heap::write(&slot, &[0; 8]); + return super::console_heap::write_view(&slot, &[0; 8], "SRV of no resource", || None); }; if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + let named = || view_memory(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + return super::console_heap::write_view(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, false), "buffer SRV", named); } let (format, dim, array, mips) = match desc.as_ref() { Some(v) => { @@ -2280,12 +2691,9 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, (d.Format, resource_dim_to_view(&d), d.DepthOrArraySize as u32, d.MipLevels as u32) } }; - match view_shape(r, format, dim, array, mips) { - Some((fmt, ty, w, h, d, m)) => super::console_heap::write(&slot, &crate::gpu::desc::xcl_image_for_view(slot.index, fmt, ty, w, h, d, m)), - None => { - note_buffer_view(); - super::console_heap::write(&slot, &[0; 8]); - } + match shape_or_count(r, false, format, dim, array, mips) { + Some((fmt, ty, w, h, d, m)) => super::console_heap::write_texture_view(&slot, &crate::gpu::desc::xcl_image_for_view(slot.index, fmt, ty, w, h, d, m), "texture SRV", res as usize), + None => super::console_heap::write_texture_view(&slot, &[0; 8], "SRV of a shape XCL cannot describe", res as usize), } } @@ -2311,22 +2719,43 @@ fn cube_as_cube_array(v: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> Option, +} + +/// (address, the PC part of a resource desc) of a view by address +type MadeKey = (u64, [u8; 0x38]); +/// the textures views by address named (`resource_at`): MADE holds the only reference to each +static MADE: Mutex>> = Mutex::new(None); +/// inserts into MADE that replaced a texture another thread made for the same view at the same +/// time (`resource_at`'s look-up and insert are two lock sections): that one lives on outside MADE +static MADE_REPLACED: AtomicU64 = AtomicU64::new(0); + /// The texture a view by address describes: `desc` (a resource desc) placed at `va`, made once /// per address and desc – titles make views of the same memory again and again. unsafe fn resource_at(this: *mut c_void, desc: *const u8, va: u64) -> *mut c_void { - type Key = (u64, [u8; 0x38]); - static MADE: Mutex>> = Mutex::new(None); if desc.is_null() || va == 0 || !crate::gpu::shader::readable(desc as usize, 0x38) { return std::ptr::null_mut(); } // the PC part of the desc; the flags (@0x30) are its last dword, padding follows let mut x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); x[0x34..].fill(0); - if let Some(&r) = MADE.lock().unwrap().get_or_insert_with(HashMap::new).get(&(va, x)) { - return r as *mut c_void; + if let Some(v) = MADE.lock().unwrap().get_or_insert_with(HashMap::new).get(&(va, x)) { + return v.res as *mut c_void; } let mut r = std::ptr::null_mut(); - let hr = super::device_x::create_placed_resource_x(this, va, x.as_ptr(), 0, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const GUID, &mut r); + // (the view census: how the creation made it – none left from an earlier one on this thread) + let census = super::view_census::on(); + if census { + let _ = super::device_x::take_last_made(); + } + let hr = super::device_x::with_source(super::device_x::Source::ViewAt, || super::device_x::create_placed_resource_x(this, va, x.as_ptr(), 0, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const GUID, &mut r)); + let made = if census { super::device_x::take_last_made() } else { None }; if hr < 0 || r.is_null() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 8 { @@ -2334,13 +2763,91 @@ unsafe fn resource_at(this: *mut c_void, desc: *const u8, va: u64) -> *mut c_voi } r = std::ptr::null_mut(); } - MADE.lock().unwrap().get_or_insert_with(HashMap::new).insert((va, x), r as usize); + if insert_made(MADE.lock().unwrap().get_or_insert_with(HashMap::new), (va, x), ViewTexture { res: r as usize, made }) { + MADE_REPLACED.fetch_add(1, Ordering::Relaxed); + } r } +/// A views-by-address texture `v` put in MADE (`m`) at `key` (`resource_at`): whether it replaced one +/// that another thread made for the same view at the same time – one that could be made (`res` not +/// 0), alive outside MADE from then on (`MADE_REPLACED`). +fn insert_made(m: &mut HashMap, key: MadeKey, v: ViewTexture) -> bool { + m.insert(key, v).is_some_and(|w| w.res != 0) +} + +/// (tests) `resource_at`: the texture a view by address of `desc` at `va` describes, made once +#[cfg(test)] +pub(super) unsafe fn resource_at_for_test(this: *mut c_void, desc: *const u8, va: u64) -> *mut c_void { + resource_at(this, desc, va) +} + +/// (tests) MADE's entry for a view by address at `va` of `desc` (its PC part: bytes 0x34.. zero) +#[cfg(test)] +pub(super) fn made_for_test(va: u64, desc: &[u8; 0x38]) -> Option { + MADE.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(&(va, *desc)).copied()) +} + +/// The views-by-address textures (MADE's values) into `out`, copied under MADE's lock (the view +/// census, off the title's threads). +pub(super) fn view_textures(out: &mut Vec) { + if let Some(m) = MADE.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + out.extend(m.values().copied()); + } +} + +/// Textures made for views by address that a second thread's insert for the same view replaced in +/// MADE (alive, outside it) so far. +pub(super) fn made_replaced() -> u64 { + MADE_REPLACED.load(Ordering::Relaxed) +} + +/// (tests) MADE's entry for a view by address at `va` of `desc` (its PC part: bytes 0x34.. zero) +/// set – None: taken out. +#[cfg(test)] +pub(super) fn set_made_for_test(va: u64, desc: &[u8; 0x38], v: Option) { + let mut g = MADE.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + match v { + Some(v) => m.insert((va, *desc), v), + None => m.remove(&(va, *desc)), + }; +} + +/// device #34 MakeResident(count, objects) as the PC's (counted; lazy title textures left out). +unsafe extern "system" fn dev_make_resident_x(this: *mut c_void, n: u32, objects: *const *mut c_void) -> HRESULT { + residency_x(this, false, n, objects) +} + +/// device #35 Evict(count, objects) as the PC's: a lazy title texture is a reserved resource of +/// its own in Metal's residency set on D3DMetal – evicted, the next use of it would be of a +/// texture that is not resident (`lazy_tex::residency`). +unsafe extern "system" fn dev_evict_x(this: *mut c_void, n: u32, objects: *const *mut c_void) -> HRESULT { + residency_x(this, true, n, objects) +} + +unsafe fn residency_x(this: *mut c_void, evict: bool, n: u32, objects: *const *mut c_void) -> HRESULT { + let _xcl_api = crate::waitwatch::api(if evict { "real::dev_evict_x" } else { "real::dev_make_resident_x" }); + type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, if evict { 35 } else { 34 })); + if n == 0 || objects.is_null() || n > 1 << 20 || !crate::gpu::shader::readable(objects as usize, n as usize * 8) { + return f(this, n, objects); + } + let all = std::slice::from_raw_parts(objects, n as usize); + let kept = super::lazy_tex::residency(evict, all); + if kept.len() == all.len() { + return f(this, n, objects); + } + if kept.is_empty() { + return S_OK; + } + f(this, kept.len() as u32, kept.as_ptr()) +} + /// device #70 (a retail game): a shader resource view of memory, without a resource object: /// (resource desc, { the PC's SRV desc; GPU address @0x28; … }, destination). unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u8, view: *const u8, cpu: u64) { + let _xcl_api = crate::waitwatch::api("real::dev_create_srv_at_x"); if view.is_null() || !crate::gpu::shader::readable(view as usize, 0x40) { return; } @@ -2351,14 +2858,21 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); - return super::console_heap::write(&slot, &words); + // (its V# names the memory itself) + return super::console_heap::write_view(&slot, &words, "buffer SRV by address", || None); } - dev_create_srv_x(this, resource_at(this, rdesc, va), &v, cpu); + let r = resource_at(this, rdesc, va); + // (no texture XCL could make for it: the slot gets an empty descriptor – counted, `outside`) + if r.is_null() && va != 0 { + super::outside::note_no_texture(); + } + dev_create_srv_x(this, r, &v, cpu); } /// device #71: the same for an unordered access view ({ the PC's UAV desc; GPU address @0x28; /// the counter's address @0x30; … }). unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u8, view: *const u8, cpu: u64) { + let _xcl_api = crate::waitwatch::api("real::dev_create_uav_at_x"); if view.is_null() || !crate::gpu::shader::readable(view as usize, 0x40) { return; } @@ -2369,9 +2883,15 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); - return super::console_heap::write(&slot, &words); + // (its V# names the memory itself) + return super::console_heap::write_view(&slot, &words, "buffer UAV by address", || None); + } + let r = resource_at(this, rdesc, va); + // (no texture XCL could make for it: the slot gets an empty descriptor – counted, `outside`) + if r.is_null() && va != 0 { + super::outside::note_no_texture(); } - dev_create_uav_x(this, resource_at(this, rdesc, va), std::ptr::null_mut(), &v, cpu); + dev_create_uav_x(this, r, std::ptr::null_mut(), &v, cpu); } /// V# of `n` elements from element `first` of the buffer at `va`. @@ -2386,10 +2906,17 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI (false, s) => (s, s), }; let records = if stride == 0 { n.saturating_mul(4) } else { n }; - crate::gpu::desc::buffer_words(va + first * elem as u64, stride, records, fmt) + let base = va + first * elem as u64; + // (outside unified memory: counted – translated programs read 0 there, below 4 GiB window 0's + // bytes, and write nowhere) + super::outside::note_view_by_address(va, base); + crate::gpu::desc::buffer_words(base, stride, records, fmt) } unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { + let _xcl_api = crate::waitwatch::api("real::dev_create_uav_x"); + note_small_view("UAV", res); + note_traced_view("UAV", res, ""); // the view's format as the PC's for the resource (B5G5R5A1 of a target made R8G8B8A8, // `device_x::pc_resource_desc`: an invalid call, the device removed) let mut copy = desc.as_ref().copied(); @@ -2425,18 +2952,25 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, f(this, res, counter, desc, at) } }; - let Some(slot) = super::console_heap::slot(cpu) else { return pc_uav(cpu) }; + let Some(slot) = super::console_heap::slot(cpu) else { + pc_uav(cpu); + // (a PC heap that is not a console heap: outside the view census's map) + return super::view_census::note_outside(1); + }; pc_uav(slot.pc_uav); + // (the view census: what the UAV just made names – none for the null view) + super::console_heap::note_pc_view(&slot, true, if no_uav { 0 } else { res as usize }); super::console_heap::publish(&slot, true); super::console_heap::note_resource(&slot, res as usize); let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { - return super::console_heap::write(&slot, &[0; 8]); + return super::console_heap::write_view(&slot, &[0; 8], "UAV of no resource", || None); }; let rd = r.GetDesc(); if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; - return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + let named = || view_memory(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + return super::console_heap::write_view(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true), "buffer UAV", named); } // UAV dimensions: 1 buffer, 2 tex1d, 3 tex1d array, 4 tex2d, 5 tex2d array, 8 tex3d let (format, dim, array, mip) = match desc.as_ref() { @@ -2454,9 +2988,8 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } None => (rd.Format, resource_dim_to_view(&rd), rd.DepthOrArraySize as u32, 0), }; - let Some((fmt, ty, w, h, d, _)) = view_shape(r, format, dim, array, 1) else { - note_buffer_view(); - return super::console_heap::write(&slot, &[0; 8]); + let Some((fmt, ty, w, h, d, _)) = shape_or_count(r, true, format, dim, array, 1) else { + return super::console_heap::write_texture_view(&slot, &[0; 8], "UAV of a shape XCL cannot describe", res as usize); }; // RDNA images have no SRV / UAV distinction: console shaders may read this slot too if dim == 4 { @@ -2471,10 +3004,11 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); g(this, res, &srv, slot.pc_srv); + super::console_heap::note_pc_view(&slot, false, res as usize); super::console_heap::publish(&slot, false); } let (w, h) = ((w >> mip).max(1), (h >> mip).max(1)); - super::console_heap::write(&slot, &crate::gpu::desc::xcl_image_for_view(slot.index, fmt, ty, w, h, d, 1)); + super::console_heap::write_texture_view(&slot, &crate::gpu::desc::xcl_image_for_view(slot.index, fmt, ty, w, h, d, 1), "texture UAV", res as usize); } /// device #127 (a retail game): CreateCommittedResource with a barrier layout in the initial state's place @@ -2597,6 +3131,7 @@ pub(super) unsafe extern "system" fn dev_create_command_list_x(this: *mut c_void } unsafe extern "system" fn dev_create_compute_pso_x(this: *mut c_void, desc: *const c_void, a: usize, b: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _xcl_api = crate::waitwatch::api("real::dev_create_compute_pso_x"); if a != 0 || b != 0 { crate::xlog_warn!("CreateComputePipelineState (console, slot 62): unknown parameters {a:#x} {b:#x} ignored"); } @@ -2671,6 +3206,8 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::Heap => v.push(("Release", mem_heap_release as usize)), Kind::Fence => v.push(("Signal", fence_signal as usize)), Kind::CommandSignature if crate::util::mac_host() => v.push(("Release", signature_release as usize)), + Kind::QueryHeap if super::late_release::defers(Kind::QueryHeap) => v.push(("Release", query_heap_release as usize)), + Kind::RootSignature if super::late_release::defers(Kind::RootSignature) => v.push(("Release", root_signature_release as usize)), _ => {} } v @@ -2733,6 +3270,7 @@ macro_rules! as_usize { /// command list's vtable pointer on Close; adopt the runtime's new state vtable so /// subsequent Reset and console calls dispatch through the current native table. unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { + let _xcl_api = crate::waitwatch::api("real::cl_close"); super::list_x::before_close(this); let ext = *(this as *const usize); let f: RefFn = std::mem::transmute(orig_fn(this, slot_of(this, "Close"))); @@ -2907,8 +3445,26 @@ macro_rules! creator { }; } -creator!(dev_create_command_queue, "CreateCommandQueue", Kind::CommandQueue, [a1]); -creator!(dev_create_command_queue1, "CreateCommandQueue1", Kind::CommandQueue, [a1, a2]); +creator!(dev_create_command_queue_made, "CreateCommandQueue", Kind::CommandQueue, [a1]); +creator!(dev_create_command_queue1_made, "CreateCommandQueue1", Kind::CommandQueue, [a1, a2]); + +/// CreateCommandQueue: the queue gets its clock for deferred releases (`late_release`) before +/// anything is submitted to it (a queue only `KickoffX` submits to included). +pub(super) unsafe extern "system" fn dev_create_command_queue(this: *mut c_void, a1: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = dev_create_command_queue_made(this, a1, riid, ppv); + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::late_release::register_queue(*ppv); + } + hr +} + +pub(super) unsafe extern "system" fn dev_create_command_queue1(this: *mut c_void, a1: usize, a2: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = dev_create_command_queue1_made(this, a1, a2, riid, ppv); + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::late_release::register_queue(*ppv); + } + hr +} creator!(dev_create_command_allocator, "CreateCommandAllocator", Kind::CommandAllocator, [a1]); creator!(dev_create_command_list, "CreateCommandList", Kind::CommandList, [a1, a2, a3, a4]); creator!(dev_create_command_list1, "CreateCommandList1", Kind::CommandList, [a1, a2, a3]); @@ -3078,6 +3634,24 @@ unsafe fn pc_heap_desc(heap: usize) -> Option { Some(h) } +/// `pc_allocation_size`, asked once per device and description (textures the title streams +/// come in a few hundred shapes). +pub(super) unsafe fn pc_size(device: *mut c_void, d: &[u8; 0x38]) -> u64 { + static SIZES: Mutex>> = Mutex::new(None); + let key = (device as usize, *d); + if let Some(&n) = SIZES.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { + return n; + } + let n = pc_allocation_size(device, d); + let n = if n == u64::MAX { 0 } else { n }; + let mut g = SIZES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if m.len() < 1 << 16 { + m.insert(key, n); + } + n +} + /// The PC driver's size for a (PC) resource description (GetResourceAllocationInfo, slot 25). unsafe fn pc_allocation_size(device: *mut c_void, d: &[u8; 0x38]) -> u64 { type F = unsafe extern "system" fn(*mut c_void, *mut [u64; 2], u32, u32, *const [u8; 0x38]) -> *mut [u64; 2]; @@ -3252,21 +3826,21 @@ fn heap_block(heap: usize) -> Option<(usize, bool)> { Some((p, cpu_readback)) } -/// ID3D12Heap::Release: its block of unified memory goes with it. +/// ID3D12Heap::Release: its block of unified memory goes with it (`heap_gone`). unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - let gone = HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block); - if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); - } + hooked_release(this, Kind::Heap) +} + +/// A heap went for good: its block of unified memory goes too. +unsafe fn heap_gone(heap: usize) { + let gone = HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&heap)).and_then(|e| e.block); + if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { + if u.is_sparse(p) { + super::sparse::free(p); + } else { + u.free(p); } } - n } creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]); @@ -3309,6 +3883,10 @@ pub fn end_title(code: u32) -> ! { windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), code); }); let watchdog = rx.recv_timeout(std::time::Duration::from_secs(1)).unwrap_or(0); + // what the pipelines came to, and the programs whose work was skipped most (the counts and + // a sorted copy of the skips' table, on the heap: said once the watchdog is armed, so a log + // write that blocks is covered too) + crate::xlog_info!("{}", super::pso_async::end_line()); crate::log::flush(); // the title's threads stop first: with its fences at the maximum a running title thinks // the GPU is done and resets command allocators the GPU still runs (Fortnite: a device @@ -3718,7 +4296,44 @@ 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; +#[cfg(test)] +thread_local! { + /// (tests) the next `finish_pso` on this thread fails as a driver refusing the shaders would + static REJECT_NEXT_PSO: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// (tests) this thread's windows' GPU addresses (`uma_window_vas`): a test of a bind needs open + /// windows, which only XCL's device creation opens + static TEST_WINDOW_VAS: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +#[cfg(test)] +pub(super) fn reject_next_pso_for_test() { + REJECT_NEXT_PSO.with(|r| r.set(true)); +} + +/// (tests) `uma_window_vas` gives `vas` on this thread until the guard goes. +#[cfg(test)] +pub(super) fn window_vas_for_test(vas: Vec) -> impl Drop { + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + TEST_WINDOW_VAS.with(|t| *t.borrow_mut() = None); + } + } + TEST_WINDOW_VAS.with(|t| *t.borrow_mut() = Some(vas)); + Restore +} + +/// (tests) `pso` was made with root signature `rs`, as a translated pipeline is (`note_pso_rs`). +#[cfg(test)] +pub(super) fn set_pso_root_signature_for_test(pso: usize, rs: usize) { + PSO_RS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, rs); +} + unsafe fn finish_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + #[cfg(test)] + if REJECT_NEXT_PSO.with(|r| r.replace(false)) { + return E_INVALIDARG; + } let mut hr = f(this, desc, riid, ppv); if hr == E_NOINTERFACE { let iid = pc_iid(Kind::PipelineState); @@ -3794,6 +4409,16 @@ fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { /// user SGPRs of the console CS of a translated compute pipeline static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); +/// the console CS of a translated compute pipeline: fnv64 of its blob (the translation cache's +/// name for it), threads in a group +static PSO_CS: Mutex>> = Mutex::new(None); + +/// The console compute program of a translated pipeline: (fnv64 of its blob, threads in a +/// group); None: not known. +pub fn pso_console_cs(pso: usize) -> Option<(u64, u32)> { + let pso = super::pso_async::resolve(pso); + PSO_CS.lock().unwrap().as_ref()?.get(&pso).copied() +} /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). @@ -3868,7 +4493,7 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// shader the recompiler could not take, `Some(Ok(hr))` = translated pipeline created (or the /// driver's verdict on it). /// DXIL size from which a compute pipeline's driver compile goes to the background -const BIG_DRIVER_COMPILE: usize = 256 << 10; +const BIG_DRIVER_COMPILE: usize = super::pso_async::BIG_DXIL; /// A counting semaphore: background driver compiles of big programs at once. struct Slots { @@ -3901,20 +4526,177 @@ static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::n /// Before a big driver compile in the background: until 3 GB of commit are free (each takes /// ~1.5 GB; the title loading next to it must not run out – no minute's grace as for DXC). +/// (Wine's commit figures on a Mac: 7.5 GB available at GTA VI's world load, run 64.) Its waits +/// are counted by lane (`COMMIT_WAITS`): the big lane's threads or the other pipeline threads – +/// workers and those building ahead, whose big compiles (ones the ledger knew) wait here too. fn wait_for_commit() { + let big_lane = std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso-big-")); + wait_for_commit_in(&COMMIT_WAITS[usize::from(!big_lane)], available_commit, std::time::Duration::from_millis(200)); +} + +/// Big compiles' waits for commit (`wait_for_commit`), [the big lane's, the other pipeline +/// threads'] – each: waits begun, ms waited (nap by nap: a wait under way counts what it slept +/// so far), waiting now. Run 66 had no line of them (PP3: the queue line, `commit_waits`). +static COMMIT_WAITS: [[AtomicU64; 3]; 2] = [const { [const { AtomicU64::new(0) }; 3] }; 2]; + +/// (`pso_async`'s queue line) `COMMIT_WAITS`: [big lane, other pipeline threads] × (waits begun, +/// ms waited, waiting now) +pub(super) fn commit_waits() -> [[u64; 3]; 2] { + COMMIT_WAITS.each_ref().map(|w| w.each_ref().map(|n| n.load(Ordering::Relaxed))) +} + +/// Wine's commit available now (None: not told). +fn available_commit() -> Option { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; - loop { - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - if unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= 3 << 30 { - return; - } - std::thread::sleep(std::time::Duration::from_millis(200)); - } + 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) } -unsafe fn translated_compute_pso(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}; +/// `wait_for_commit` with the commit available from `available` (None: not told – no wait) and +/// naps of `nap`, counted in `counts` (`COMMIT_WAITS`' layout): back at once with 3 GiB or more, +/// else a wait begun, nap after nap until there is. +pub(super) fn wait_for_commit_in(counts: &[AtomicU64; 3], mut available: impl FnMut() -> Option, nap: std::time::Duration) { + let enough = |n: Option| n.is_none_or(|n| n >= 3 << 30); + if enough(available()) { + return; + } + counts[0].fetch_add(1, Ordering::Relaxed); + counts[2].fetch_add(1, Ordering::Relaxed); + loop { + let t = std::time::Instant::now(); + std::thread::sleep(nap); + counts[1].fetch_add(t.elapsed().as_millis() as u64, Ordering::Relaxed); + if enough(available()) { + break; + } + } + counts[2].fetch_sub(1, Ordering::Relaxed); +} + +/// Whether a driver compile of a big program (`big`, no blob of an earlier build: `uncached`) on +/// this thread (`pool`: a pipeline worker's, `xcl-pso*`) takes a `BIG_COMPILES` slot, and whether +/// it waits for commit first. Without a big lane every worker's takes the one slot, one at a time +/// as before 0023; with one none does – the big lane's threads are the bound, and no worker waits +/// behind a compile that does not end (run 64: 56c0cd3b82a00c6e's held the one slot for good) – +/// and every worker's still waits for commit. +fn big_compile_gate(big: bool, uncached: bool, pool: bool, big_lane: bool) -> (bool, bool) { + let gated = big && uncached && pool; + (gated && !big_lane, gated) +} + +/// Why a translated program is never handed to the driver (`refusal`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Refusal { + /// `XCL_NO_BUILD_CS` names it + Listed, + /// its DXIL is over `XCL_PSO_MAX_DXIL_KB` + TooBig, +} + +/// `XCL_PSO_MAX_DXIL_KB` (default 4096; 0: no limit). GTA VI's only programs over it are the six +/// whose HLSL went over 8 MiB (DXC -O0: 5.4 – 29.8 MB of DXIL; the next is 2.1 MB): the driver's +/// compile of the biggest had not ended after 7 min (run 64). +fn max_dxil_kb() -> u64 { + static C: OnceLock = OnceLock::new(); + *C.get_or_init(|| std::env::var("XCL_PSO_MAX_DXIL_KB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4096)) +} + +/// `XCL_NO_BUILD_CS=,…` (`stall::parse_hashes`): console compute programs never built – +/// their stand-ins stay and their work is skipped (`bind`). Logged once when not empty. +fn no_build_list() -> &'static [u64] { + static L: OnceLock> = OnceLock::new(); + L.get_or_init(|| { + let v = super::stall::parse_hashes(&std::env::var("XCL_NO_BUILD_CS").unwrap_or_default()); + if !v.is_empty() { + let names: Vec = v.iter().map(|h| format!("{h:016x}")).collect(); + crate::xlog_warn!("XCL_NO_BUILD_CS: {} are never built (their stand-ins stay; their work is skipped)", names.join(", ")); + } + v + }) +} + +#[cfg(test)] +thread_local! { + /// (tests) the refusal switches of this thread's calls: (XCL_PSO_MAX_DXIL_KB, XCL_NO_BUILD_CS) + static TEST_REFUSAL: std::cell::RefCell)>> = const { std::cell::RefCell::new(None) }; + /// (tests) what the translation cache says of a compute program's DXIL (`translated_size`): + /// Some(None) nothing, Some(Some(n)) n bytes + static TEST_DXIL: std::cell::Cell>> = const { std::cell::Cell::new(None) }; +} + +fn refusal_switches() -> (u64, std::borrow::Cow<'static, [u64]>) { + #[cfg(test)] + if let Some((cap, list)) = TEST_REFUSAL.with(|t| t.borrow().clone()) { + return (cap, std::borrow::Cow::Owned(list)); + } + (max_dxil_kb(), std::borrow::Cow::Borrowed(no_build_list())) +} + +/// More DXIL than `cap_kb` KB (0: no limit). +fn over_cap(dxil: usize, cap_kb: u64) -> bool { + cap_kb != 0 && dxil as u64 > cap_kb << 10 +} + +/// (pure) Why program `hash` of stage `what` with `dxil` bytes of DXIL (None: not known – an +/// estimate is never given) is refused, with these switches. +fn refusal_by(what: &str, hash: u64, dxil: Option, cap_kb: u64, no_build: &[u64]) -> Option { + if what == "CS" && hash != 0 && no_build.contains(&hash) { + return Some(Refusal::Listed); + } + dxil.filter(|&n| over_cap(n, cap_kb)).map(|_| Refusal::TooBig) +} + +/// `refusal_by` with this run's switches. A refused program is logged once +/// (`pso_async::note_refused`: "[pso] refused …") and noted as a translation error (one reason per +/// stage and cause; run 64's list was full by 49 s, so the `[pso]` line is the evidence). +fn refusal(what: &'static str, hash: u64, dxil: Option) -> Option { + let (cap, list) = refusal_switches(); + let why = refusal_by(what, hash, dxil, cap, &list)?; + let text = match why { + Refusal::Listed => "XCL_NO_BUILD_CS".to_string(), + Refusal::TooBig => format!("{} KB of DXIL over XCL_PSO_MAX_DXIL_KB={cap}", dxil.unwrap_or(0) >> 10), + }; + super::pso_async::note_refused(hash, what, &text); + note_translation_error(match why { + Refusal::Listed => format!("a {what} refused (XCL_NO_BUILD_CS)"), + Refusal::TooBig => format!("a {what} refused (its DXIL over XCL_PSO_MAX_DXIL_KB={cap})"), + }); + Some(why) +} + +/// A graphics or mesh path's result for a refused program: never given to the title – its two +/// callers (`graphics_pso`, `dev_create_pipeline_state`) give the title XCL's dummy shaders +/// instead, never its console bytecode nor a failed call. HRESULT_FROM_WIN32(ERROR_CANCELLED): +/// no driver's answer to a pipeline creation. +const E_REFUSED: HRESULT = 0x8007_04C7u32 as i32; + +/// What a call does with a pipeline it did not translate: the title's description to the driver +/// – unless its program was refused (`refused`) or no PC driver compiles one of its shaders on a +/// Mac host (`mac_refused`): XCL's dummy shaders then. +fn untranslated_to_driver(refused: bool, mac_refused: bool) -> bool { + !refused && !mac_refused +} + +/// How a compute pipeline's CS is translated – stage, sampler base, split flag: what +/// `console_to_dxil_for` gets in `translated_compute_pso`, and the file `program_of` sizes it by. +fn compute_translation(this: *mut c_void) -> (crate::gpu::recomp::pso::Stage, u32, bool) { + (crate::gpu::recomp::pso::Stage::Compute, 0, wave32_only(this)) +} + +/// The bytes of DXIL the translation cache holds for console CS `cs` (None: not translated yet, +/// or the cache off). +fn translated_size(this: *mut c_void, cs: &[u8]) -> Option { + #[cfg(test)] + if let Some(t) = TEST_DXIL.with(|t| t.get()) { + return t; + } + let (stage, sampler_base, split) = compute_translation(this); + crate::gpu::recomp::pso::translated_dxil_len(cs, stage, sampler_base, split) +} + +unsafe fn translated_compute_pso(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}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; } @@ -3927,7 +4709,16 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return Some(Err(())); } - let compiled = match console_to_dxil_for(cs, Stage::Compute, 0, wave32_only(this)) { + // (the program's name from here on) + let cs_hash = crate::gpu::shader::fnv64(cs); + // never handed to the driver: listed, or its translation over the cap – known from the + // translation cache's header before anything is loaded (29 MB for the biggest) + if refusal("CS", cs_hash, translated_size(this, cs)).is_some() { + let _ = crate::gpu::recomp::dxc::defer(); + return Some(Err(())); + } + let (stage, sampler_base, split) = compute_translation(this); + let compiled = match console_to_dxil_for(cs, stage, sampler_base, split) { Ok(b) => b, Err(e) => { note_translation_error(format!("CS: {e}")); @@ -3935,6 +4726,13 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } }; let dxil = compiled.dxil; + super::pso_async::note_dxil(dxil.len()); + // … and one not in the translation cache before, once translated (DXC's -O0 output of HLSL + // over 8 MiB: 5 – 30 MB; 56c0cd3b82a00c6e's compile had not ended after 7 min, run 64) + if refusal("CS", cs_hash, Some(dxil.len())).is_some() { + let _ = crate::gpu::recomp::dxc::defer(); + return Some(Err(())); + } // a big program: the driver's compile takes it seconds to a minute (a retail game's 1 MB // ray-tracing resolve programs ~30 s each, ~600 of them): built in the background like one // whose DXIL is missing – the title's loading does not wait for it, its first bind does @@ -3962,12 +4760,18 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } let started = std::time::Instant::now(); - // in the background, one at a time and within the commit left (each ~1.5 GB in the driver) - let _slot = (big && cached.is_none() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso"))).then(|| { - let slot = BIG_COMPILES.acquire(); + // a big compile in the background: within the commit left (each ~1.5 GB in the driver), and + // one at a time when there is no big lane (`big_compile_gate`) + let pool = std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let (slot, commit) = big_compile_gate(big, cached.is_none(), pool, super::pso_async::big_threads() > 0); + let _slot = slot.then(|| BIG_COMPILES.acquire()); + if commit { wait_for_commit(); - slot - }); + } + // (a worker's turn at a big compute pipeline of the queue's first tier ends past the wait: one + // worker at a time waits for commit, `pso_async::Workers`) + super::pso_async::commit_wait_over(); + let clock = super::pso_async::driver_clock(); let mut hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); if hr < 0 && cached.is_some() { // a blob the driver does not take (another root signature at the same address…): compiled @@ -3978,6 +4782,8 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); } + super::pso_async::note_driver_time(&clock); + drop(clock); let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { keep_compute_blob(key, *ppv, dxil.len()); @@ -3996,12 +4802,14 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } + let threads = crate::gpu::recomp::pso::compute_threads(cs).map_or(0, |t| t.iter().product()); + PSO_CS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (cs_hash, threads)); note_translated_compute(hr, ppv); if super::list_x::trace_gpu_stall() { crate::xlog_info!("D3D12.X: stall capture PSO {:p}: compute shader {:016x}", *ppv, crate::gpu::shader::fnv64(cs)); } crate::xlog_info!( - "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", + "D3D12.X: compute PSO with the translated console CS {cs_hash:016x} ({threads} threads, {} B DXIL, {} ms{})", dxil.len(), started.elapsed().as_millis(), if reused { ", the driver's blob of an earlier build" } else { "" } @@ -4249,6 +5057,8 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return None; } + // (the build's times, `note_pipeline_build`) + let started = std::time::Instant::now(); // a GPU that can run 32-lane waves may run a wave64 VS / PS in waves of 32 (the driver // picks; RDNA2 does for pixel shaders): the lanes 32..63 it reads come from `upper_lanes` // (split_wave64) @@ -4276,6 +5086,16 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo Some(p) => Some(p.to_vec()), None => None, }; + let translating = started.elapsed(); + super::pso_async::note_dxil(vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len)); + // a program the driver does not get through is never handed to it (`refusal`) + let ps_console = shader_bytes(&d.PS).filter(|p| is_console(p)); + if refusal("VS", crate::gpu::shader::fnv64(vs), Some(vs_dxil.len())).is_some() + || ps_console.zip(ps_dxil.as_ref()).is_some_and(|(p, x)| refusal("PS", crate::gpu::shader::fnv64(p), Some(x.len())).is_some()) + { + let _ = crate::gpu::recomp::dxc::defer(); + return Some(E_REFUSED); + } let rs = abi_rs_for(this, &samplers)?; let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); @@ -4300,7 +5120,12 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } + let clock = super::pso_async::driver_clock(); + let driving = std::time::Instant::now(); let hr = retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv)); + let driver = driving.elapsed(); + super::pso_async::note_driver_time(&clock); + drop(clock); if hr < 0 { note_translation_error(format!( "the driver rejected the PSO with the translated shaders ({hr:#x}; topology type {}, {} render targets, DSV format {}, HS {}, GS {})", @@ -4372,9 +5197,89 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: graphics PSO from translated console shaders (#{})", n + 1); } + let dxil = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len); + // (where its times are taken here is checked only by compiling: no suite test builds a + // translated graphics pipeline) + note_pipeline_build("graphics", [("vs", crate::gpu::shader::fnv64(vs)), ("ps", ps_hash)], dxil, started, translating, driver); Some(hr) } +/// "D3D12.X: graphics pipeline vs 0e2ef8da75753f92 ps c1cffdc3f13a4f2f built in 14612 ms on +/// xcl-pso-2: 5523 ms translating its shaders, 9078 ms in the driver (634136 B DXIL, #577)" – a +/// shader of hash 0 (none) left out. +#[allow(clippy::too_many_arguments)] +fn pipeline_build_line(kind: &str, shaders: [(&str, u64); 2], dxil: usize, took: std::time::Duration, translating: std::time::Duration, driver: std::time::Duration, on: &str, n: u64) -> String { + let named: String = shaders.iter().filter(|s| s.1 != 0).map(|(what, hash)| format!(" {what} {hash:016x}")).collect(); + format!( + "D3D12.X: {kind} pipeline{named} built in {} ms on {on}: {} ms translating its shaders, {} ms in the driver ({dxil} B DXIL, #{n})", + took.as_millis(), + translating.as_millis(), + driver.as_millis() + ) +} + +/// The build of a `kind` pipeline of `shaders` (`dxil` bytes of DXIL) begun at `started` ended: +/// `translating` went to its shaders' translation (the translation cache, DXC, a compile of the +/// same shader another worker runs waited for), `driver` to the driver's compile. Every graphics, +/// VS+GS and mesh build is named with its times, as every compute one is (run 65 made ~135 of +/// them, ~30 KB of log: its first world frame had three graphics builds of 11 – 15 s sharing a new +/// 608 KB pixel shader – translating it took ~5.5 s, the driver ~9.1 s – that no line named, and +/// the build chains of a frame are read from these lines). (Its three callers – the success paths +/// of `translated_graphics_pso`, `translated_gs_pso` and `translated_mesh_stream` – are checked +/// only by compiling: no test of the suite builds a translated graphics pipeline.) +fn note_pipeline_build(kind: &str, shaders: [(&str, u64); 2], dxil: usize, started: std::time::Instant, translating: std::time::Duration, driver: std::time::Duration) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + let took = started.elapsed(); + let on = std::thread::current().name().map_or_else(|| format!("thread {}", unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }), str::to_string); + crate::xlog_info!("{}", pipeline_build_line(kind, shaders, dxil, took, translating, driver, &on, n)); +} + +#[cfg(test)] +mod pipeline_build_tests { + use std::time::Duration; + + /// A graphics or mesh build's line: its shaders (one of hash 0 left out), the thread, the + /// times – whatever its number and however short it was (every build has one: past the first 16 + /// builds a build of 0 ms still writes its line – with the log file held, its note waits for it). + #[test] + fn graphics_and_mesh_builds_are_named_with_their_times() { + let ms = Duration::from_millis; + assert_eq!( + super::pipeline_build_line("VS+GS", [("vs", 0xab), ("gs", 0xcd)], 1_000, ms(0), ms(0), ms(0), "thread 9", 5000), + "D3D12.X: VS+GS pipeline vs 00000000000000ab gs 00000000000000cd built in 0 ms on thread 9: 0 ms translating its shaders, 0 ms in the driver (1000 B DXIL, #5000)" + ); + assert_eq!( + super::pipeline_build_line("graphics", [("vs", 0x0e2e_f8da_7575_3f92), ("ps", 0xc1cf_fdc3_f13a_4f2f)], 634_136, ms(14_612), ms(5_523), ms(9_078), "xcl-pso-2", 577), + "D3D12.X: graphics pipeline vs 0e2ef8da75753f92 ps c1cffdc3f13a4f2f built in 14612 ms on xcl-pso-2: 5523 ms translating its shaders, 9078 ms in the driver (634136 B DXIL, #577)" + ); + assert_eq!( + super::pipeline_build_line("mesh", [("ms", 0x1234), ("ps", 0)], 70_000, ms(612), ms(12), ms(600), "thread 472", 3), + "D3D12.X: mesh pipeline ms 0000000000001234 built in 612 ms on thread 472: 12 ms translating its shaders, 600 ms in the driver (70000 B DXIL, #3)" + ); + // every build's note writes its line: 16 builds first (no other test notes one), then a 17th + // of 0 ms with the log file held by this thread – its note waits for the file until it is let + // go (~10 ms), where one that wrote nothing would be back at once + let note = move |kind: &'static str| super::note_pipeline_build(kind, [("vs", 0x7A1E_0E01), ("ps", 0)], 0, std::time::Instant::now(), ms(0), ms(0)); + for _ in 0..16 { + note("graphics"); + } + let (go, went) = std::sync::mpsc::channel::<()>(); + let (back, came) = std::sync::mpsc::channel::<()>(); + let noter = std::thread::spawn(move || { + went.recv().unwrap(); + note("VS+GS"); + back.send(()).unwrap(); + }); + let file = crate::log::soon_test::hold_file(); + go.send(()).unwrap(); + let waited = came.recv_timeout(ms(10)).is_err(); + drop(file); + noter.join().unwrap(); + assert!(waited, "a 17th build of 0 ms writes its line: its note waited for the log file"); + } +} + // --------------------------------------------------------------------------------------- // non-blocking pipeline creation (see `pso_async`) // --------------------------------------------------------------------------------------- @@ -4386,21 +5291,35 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo enum OwnedDesc { Compute(Box, Vec>), Graphics(Box, Vec>, Vec, Vec), - Stream(Box<[usize; 2]>, Vec, Vec>), + /// (the stream, its bytes, the shaders' copies, which of them is its MS) + Stream(Box<[usize; 2]>, Vec, Vec>, Option), } unsafe impl Send for OwnedDesc {} -/// A hash of a pipeline's shaders in their order (never 0): what `pso_async` knows a used -/// pipeline by in the next run. -fn shaders_key(blobs: &[Vec]) -> u64 { +/// `fnv64` of each of a pipeline's shaders, in their order: the parts of its key (`key_of`), and +/// what `program_of` names its VS and PS by (each shader hashed once: a title makes tens of +/// thousands of pipelines while it loads, a pixel shader of 16 – 24 KB each). +fn shader_hashes(blobs: &[Vec]) -> Vec { + blobs.iter().map(|b| crate::gpu::shader::fnv64(b)).collect() +} + +/// A hash of a pipeline's shaders in their order (never 0), from their `shader_hashes`: what +/// `pso_async` knows a used pipeline by in the next run. +fn key_of(hashes: &[u64]) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; - for b in blobs { - h = (h ^ crate::gpu::shader::fnv64(b)).wrapping_mul(0x0000_0100_0000_01b3); + for &x in hashes { + h = (h ^ x).wrapping_mul(0x0000_0100_0000_01b3); } h | 1 } +/// (tests) `key_of` the shaders `blobs` +#[cfg(test)] +fn shaders_key(blobs: &[Vec]) -> u64 { + key_of(&shader_hashes(blobs)) +} + #[cfg(test)] mod shaders_key_tests { #[test] @@ -4413,15 +5332,35 @@ mod shaders_key_tests { assert_ne!(key, super::shaders_key(&[a, vec![4u8, 6]])); assert_ne!(super::shaders_key(&[]), 0); } + + /// The key of a pipeline's shaders is what it was before 0023.2 (the files `used-pipelines.txt` + /// and `built-pipelines-*.txt` of earlier runs hold such keys): the fold over the shaders' + /// `fnv64`s as it was written then. + #[test] + fn the_key_of_a_pipelines_shaders_is_the_one_earlier_runs_wrote() { + let before = |blobs: &[Vec]| { + let mut h = 0xcbf2_9ce4_8422_2325u64; + for b in blobs { + h = (h ^ crate::gpu::shader::fnv64(b)).wrapping_mul(0x0000_0100_0000_01b3); + } + h | 1 + }; + let sets: [Vec>; 4] = [vec![], vec![vec![7u8; 3020]], vec![vec![1u8, 2, 3], vec![9u8; 20_000]], vec![vec![0u8], vec![1u8], vec![2u8; 5]]]; + for blobs in &sets { + assert_eq!(super::key_of(&super::shader_hashes(blobs)), before(blobs)); + assert_eq!(super::shaders_key(blobs), before(blobs)); + } + } } impl OwnedDesc { - fn shaders_key(&self) -> u64 { - shaders_key(match self { + /// its shaders' copies, in their order + fn blobs(&self) -> &[Vec] { + match self { OwnedDesc::Compute(_, b) => b, OwnedDesc::Graphics(_, b, ..) => b, - OwnedDesc::Stream(_, _, b) => b, - }) + OwnedDesc::Stream(_, _, b, _) => b, + } } fn ptr(&self) -> *const c_void { @@ -4486,6 +5425,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { } let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); let mut blobs: Vec> = Vec::new(); + let mut ms = None; let mut off = 0usize; while off + 8 <= size { let ty = u32::from_le_bytes(buf[off..off + 4].try_into().ok()?); @@ -4498,6 +5438,9 @@ unsafe fn own_stream(desc: *const c_void) -> Option { if p != 0 && n != 0 && crate::gpu::shader::readable(p, n) { blobs.push(std::slice::from_raw_parts(p as *const u8, n).to_vec()); buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().as_ptr() as u64).to_le_bytes()); + if ty == 25 { + ms = Some(blobs.len() - 1); + } } } 7 | 12 | 22 if buf[at..at + psize].iter().any(|&b| b != 0) => return None, @@ -4507,7 +5450,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { off += ((at - off) + psize + 7) & !7; } let d = Box::new([buf.len(), buf.as_ptr() as usize]); - Some(OwnedDesc::Stream(d, buf, blobs)) + Some(OwnedDesc::Stream(d, buf, blobs, ms)) } /// Raw pointers a worker needs (the device lives for the process). @@ -4544,7 +5487,91 @@ unsafe fn standin_stream(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: finish_pso(this, f, new_desc.as_ptr() as *const c_void, riid, ppv) } -/// Hand the title `standin`'s result now and build the real pipeline with `build` on a worker. +/// The split flags of the translations of `this`'s pipelines – (compute: `wave32_only`, graphics: +/// `graphics_wave32`) – asked of the driver once a device: `program_of` names every pipeline's +/// translations by them, and a title makes tens of thousands of pipelines on one device. Unknown +/// device: assume so (both, as the two do). +fn wave_splits(this: *mut c_void) -> (bool, bool) { + if this.is_null() { + return (true, true); + } + // the device's address with bit 0 (asked), bit 1 (compute) and bit 2 (graphics): a device is + // at least 8-byte aligned (one that were not would be asked every time) + static LAST: AtomicU64 = AtomicU64::new(0); + let v = LAST.load(Ordering::Acquire); + if v & !7 == this as u64 && v & 1 != 0 { + return (v & 2 != 0, v & 4 != 0); + } + let (compute, graphics) = (wave32_only(this), graphics_wave32(this)); + LAST.store((this as u64 & !7) | 1 | (compute as u64) << 1 | (graphics as u64) << 2, Ordering::Release); + (compute, graphics) +} + +/// The index of the blob of `blobs` that `b` points at (None: none, no shader). +fn blob_at(blobs: &[Vec], b: &D3D12_SHADER_BYTECODE) -> Option { + blobs.iter().position(|x| !b.pShaderBytecode.is_null() && x.as_ptr() as *const c_void == b.pShaderBytecode && x.len() == b.BytecodeLength) +} + +/// What `owned` is built from (`pso_async::Program`): its console program's hash; a compute one's +/// DXIL from the translation cache's header – the file `translated_compute_pso` loads +/// (`compute_translation`) – when the cap or the big lane needs it, else `DXIL_PER_CONSOLE_BYTE` +/// times the program's bytes (names only); and what the workers' queue looks its translations up +/// by (`pso_async::tier_of`): its CS, or its VS and – a console one only – PS, by their hashes +/// (`hashes`: `shader_hashes` of its blobs, in their order), the split flag they are translated +/// with (`wave_splits`), and whether they are on disk (a CS: as its size was looked up – None when +/// it was not, and one not found is looked up again when sent: a clone's build may store it +/// meanwhile; a graphics one: not looked up here – a title makes tens of thousands while it loads – +/// but with a console HS, DS or GS, or a mesh stream: never, their shaders are translated otherwise). +unsafe fn program_of(this: *mut c_void, owned: &OwnedDesc, key: u64, hashes: &[u64]) -> super::pso_async::Program { + use super::pso_async::{Program, DXIL_PER_CONSOLE_BYTE}; + use crate::gpu::recomp::pso::is_console; + let hash_of = |blobs: &[Vec], i: usize| hashes.get(i).copied().filter(|_| hashes.len() == blobs.len()).unwrap_or_else(|| crate::gpu::shader::fnv64(&blobs[i])); + match owned { + OwnedDesc::Compute(_, blobs) => { + let Some(cs) = blobs.first() else { return Program { kind: b'C', key, ..Default::default() } }; + let hash = hash_of(blobs, 0); + let asked = max_dxil_kb() != 0 || super::pso_async::big_threads() > 0; + let sized = asked.then(|| translated_size(this, cs)).flatten(); + super::pso_async::note_sizing(sized.is_some()); + let (dxil, estimated) = match sized { + Some(n) => (n, false), + None => (cs.len().saturating_mul(DXIL_PER_CONSOLE_BYTE), true), + }; + Program { + hash, + kind: b'C', + dxil: dxil.min(u32::MAX as usize) as u32, + estimated, + key, + shaders: [hash, 0], + split: wave_splits(this).0, + translated: asked.then_some(sized.is_some()), + } + } + OwnedDesc::Graphics(d, blobs, ..) => { + // (the copies `own_graphics` pointed the description at: no look at the title's memory) + let shader = |b: &D3D12_SHADER_BYTECODE| blob_at(blobs, b).map(|i| (i, &blobs[i][..])); + let vs = shader(&d.VS).map_or(0, |(i, _)| hash_of(blobs, i)); + let ps = shader(&d.PS).filter(|(_, x)| is_console(x)).map_or(0, |(i, _)| hash_of(blobs, i)); + let never = shader(&d.HS).is_some() || shader(&d.DS).is_some() || shader(&d.GS).is_some_and(|(_, x)| is_console(x)); + Program { + hash: if blobs.is_empty() { 0 } else { hash_of(blobs, 0) }, + kind: b'G', + key, + shaders: [vs, ps], + split: wave_splits(this).1, + translated: never.then_some(false), + ..Default::default() + } + } + OwnedDesc::Stream(_, _, blobs, ms) => { + Program { hash: (*ms).filter(|&i| i < blobs.len()).map_or(0, |i| hash_of(blobs, i)), kind: b'M', key, translated: Some(false), ..Default::default() } + } + } +} + +/// Hand the title `standin`'s result now and build the real pipeline with `build` on a worker – +/// or never, for a refused program (`refusal`). unsafe fn go_background( this: *mut c_void, f: PsoFn, @@ -4565,7 +5592,18 @@ unsafe fn go_background( return None; } let dev = Dev(this as usize, f as usize); - let key = owned.shaders_key(); + let hashes = shader_hashes(owned.blobs()); + let key = key_of(&hashes); + let prog = program_of(this, &owned, key, &hashes); + let lazy = super::pso_async::lazy(); + // `used` knows lazy pipelines only, as before + let used_key = if lazy { key } else { 0 }; + // a refused program (XCL_NO_BUILD_CS; XCL_PSO_MAX_DXIL_KB by the translation cache's header – + // an estimate never refuses): the stand-in stays, nothing is queued, no bind waits for it + if compute && refusal("CS", prog.hash, (!prog.estimated).then_some(prog.dxil as usize)).is_some() { + super::pso_async::submit_refused(*ppv as usize, compute, used_key, prog); + return Some(hr); + } let job: super::pso_async::Job = Box::new(move || { let mut out: *mut c_void = std::ptr::null_mut(); if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { @@ -4574,11 +5612,7 @@ unsafe fn go_background( 0 } }); - if super::pso_async::lazy() { - super::pso_async::submit_lazy(*ppv as usize, compute, job, key); - } else { - super::pso_async::submit(*ppv as usize, compute, job); - } + super::pso_async::submit_program(*ppv as usize, compute, job, lazy, used_key, prog); Some(hr) } @@ -4606,19 +5640,25 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID super::null::capture_graphics_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv)) } else { (translated_graphics_pso(this, f, desc, riid, ppv), false) }; - if missed { + let translated = if missed { if let Some(hr) = own_graphics(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_graphics, build_graphics)) { return hr; } - if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv) { - return hr; - } - } else if let Some(hr) = translated { - return hr; + translated_graphics_pso(this, f, desc, riid, ppv) + } else { + translated + }; + // a refused program (`refusal`): XCL's dummy shaders below – never the title's console bytecode + let mut refused = false; + match translated { + Some(E_REFUSED) => refused = true, + Some(hr) => return hr, + None => {} } let pc = untranslated_stream_desc(desc, stream); let readable = crate::gpu::shader::readable(desc as usize, std::mem::size_of::()); - let hr = if readable && refused_on_mac_host(pc.as_ref().unwrap_or(&*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC))) { + let mac_refused = readable && refused_on_mac_host(pc.as_ref().unwrap_or(&*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC))); + let hr = if readable && !untranslated_to_driver(refused, mac_refused) { E_INVALIDARG } else { finish_pso(this, f, pc.as_ref().map_or(desc, |g| g as *const _ as *const c_void), riid, ppv) @@ -4638,6 +5678,9 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); pc_topology_type(&mut copy); let hr2 = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); + if hr2 >= 0 { + note_fallback_pso(ppv, false); + } note_fallback("graphics PSO", hr, hr2 >= 0); if hr2 >= 0 { hr2 @@ -4682,6 +5725,9 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const copy.CS = bytecode(&dummy().cs); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let hr2 = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); + if hr2 >= 0 { + note_fallback_pso(ppv, true); + } note_fallback("compute PSO", hr, hr2 >= 0); if hr2 >= 0 { hr2 @@ -4859,6 +5905,20 @@ fn mesh_shader_slots<'a>(ms_slot: Option<&'a [u8]>, as_slot: Option<&'a [u8]>) - } } +/// `XCL_MS_IN_AS_SLOT=0`: a console MS container alone in the AS slot is refused (E_INVALIDARG, +/// `translated_mesh_stream`), as before upstream 5bff7bd, for a run that compares the two; +/// otherwise (unset, or anything but "0") it is translated as the mesh shader it is +/// (`mesh_shader_slots`). Read once. +fn ms_in_as_slot_translated() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| ms_in_as_slot_switch(std::env::var("XCL_MS_IN_AS_SLOT").ok().as_deref())) +} + +/// `XCL_MS_IN_AS_SLOT`'s value → whether such a shader is translated: on unless "0". +fn ms_in_as_slot_switch(v: Option<&str>) -> bool { + v.map_or(true, |v| v.trim() != "0") +} + #[cfg(test)] mod mesh_slot_tests { use super::{console_ms_in_as_slot, fallback_stream, mesh_shader_slots}; @@ -4949,6 +6009,14 @@ mod mesh_slot_tests { // nothing: nothing assert!(mesh_shader_slots(None, None) == (None, None)); } + + /// `XCL_MS_IN_AS_SLOT`: such a shader is translated unless the switch is "0", which refuses + /// its pipeline as before upstream 5bff7bd (for a run that compares the two). + #[test] + fn the_ms_in_as_slot_switch_is_on_unless_0() { + assert!(super::ms_in_as_slot_switch(None) && super::ms_in_as_slot_switch(Some("1")) && super::ms_in_as_slot_switch(Some(""))); + assert!(!super::ms_in_as_slot_switch(Some("0")) && !super::ms_in_as_slot_switch(Some(" 0\n"))); + } } /// CreatePipelineState with a console MS: Some(hr) when it was a console mesh pipeline @@ -4965,6 +6033,13 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * let subs = stream_subobjects(std::slice::from_raw_parts(base as *const u8, size))?; let as_slot = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32).and_then(|s| payload_shader(s.1)); let ms_slot = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32).and_then(|s| payload_shader(s.1)); + // `XCL_MS_IN_AS_SLOT=0`: refused, as before upstream 5bff7bd (`ms_in_as_slot_translated`) + if !ms_in_as_slot_translated() && console_ms_in_as_slot(&subs) { + if let Some(a) = as_slot { + note_translation_error(format!("mesh pipeline with its MS {:016x} in the AS slot – refused (XCL_MS_IN_AS_SLOT=0)", crate::gpu::shader::fnv64(a))); + return Some(E_INVALIDARG); + } + } let (ms, as_slot) = mesh_shader_slots(ms_slot, as_slot); let Some(ms) = ms else { return None }; if !is_console(ms) { @@ -4980,6 +6055,8 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * return Some(E_INVALIDARG); } let ps = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32).and_then(|s| payload_shader(s.1)); + // (the build's times, `note_pipeline_build`) + let (started, ps_hash) = (std::time::Instant::now(), ps.map_or(0, crate::gpu::shader::fnv64)); let (tp, (ps, ps_samplers)) = match (console_mesh(ms, ps, wave32_only(this)), two_pass_ps(ps, graphics_wave32(this))) { (Ok(tp), Ok(ps)) => (tp, ps), (Err(e), _) => { @@ -4991,6 +6068,11 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * return Some(E_INVALIDARG); } }; + let translating = started.elapsed(); + if refusal("MS", crate::gpu::shader::fnv64(ms), Some(tp.cs.len().max(tp.ms.len()))).is_some() { + let _ = crate::gpu::recomp::dxc::defer(); + return Some(E_REFUSED); + } let Some(rs) = abi_rs_for(this, &ps_samplers) else { return Some(E_INVALIDARG) }; // the title's state (blend, rasteriser, depth, formats …) with XCL's RS and shaders let mut out = StreamOut::default(); @@ -5016,12 +6098,21 @@ 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)) + let dxil = tp.cs.len() + tp.ms.len() + ps.as_ref().map_or(0, Vec::len); + let driving = std::time::Instant::now(); + let hr = finish_two_pass(this, &out, tp, rs, "MS", riid, ppv); + if hr >= 0 { + // (checked only by compiling, as the graphics build's: no suite test builds one) + note_pipeline_build("mesh", [("ms", crate::gpu::shader::fnv64(ms)), ("ps", ps_hash)], dxil, started, translating, driving.elapsed()); + } + Some(hr) } /// A graphics PSO with a console VS + GS: the GS pipeline in two passes, as a mesh pipeline /// with the description's state. unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8], gs: &[u8], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + // (the build's times, `note_pipeline_build`) + let started = std::time::Instant::now(); let (tp, (ps, ps_samplers)) = match ( crate::gpu::recomp::pso::console_geometry(vs, gs, shader_bytes(&d.PS), wave32_only(this)), two_pass_ps(shader_bytes(&d.PS), graphics_wave32(this)), @@ -5067,6 +6158,11 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE return E_INVALIDARG; } }; + let translating = started.elapsed(); + if refusal("GS", crate::gpu::shader::fnv64(gs), Some(tp.cs.len().max(tp.ms.len()))).is_some() { + let _ = crate::gpu::recomp::dxc::defer(); + return E_REFUSED; + } let Some(rs) = abi_rs_for(this, &ps_samplers) else { return E_INVALIDARG }; let mut out = StreamOut::default(); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &rs); @@ -5087,7 +6183,14 @@ 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) + let dxil = tp.cs.len() + tp.ms.len() + ps.as_ref().map_or(0, Vec::len); + let driving = std::time::Instant::now(); + let hr = finish_two_pass(this, &out, tp, rs, "GS", riid, ppv); + if hr >= 0 { + // (checked only by compiling, as the graphics build's: no suite test builds one) + note_pipeline_build("VS+GS", [("vs", crate::gpu::shader::fnv64(vs)), ("gs", crate::gpu::shader::fnv64(gs))], dxil, started, translating, driving.elapsed()); + } + hr } /// A console MS container in the stream's AS subobject and no MS subobject (`mesh_shader_slots`). @@ -5357,15 +6460,19 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void super::null::capture_stream_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_mesh_stream(this, desc, riid, ppv)) } else { (translated_mesh_stream(this, desc, riid, ppv), false) }; - if missed { + let translated = if missed { if let Some(hr) = own_stream(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_stream, build_stream)) { return hr; } - if let Some(hr) = translated_mesh_stream(this, desc, riid, ppv) { - return hr; - } - } else if let Some(hr) = translated { - return hr; + translated_mesh_stream(this, desc, riid, ppv) + } else { + translated + }; + match translated { + // a refused program: XCL's dummy stream, never the console MS nor a failed call + Some(E_REFUSED) => return fallback_stream_pso(this, f, desc, riid, ppv, E_INVALIDARG), + Some(hr) => return hr, + None => {} } match stream_pipeline(desc) { StreamPipeline::Graphics(d) => return graphics_pso(this, &*d as *const _ as *const c_void, riid, ppv, true), @@ -5376,17 +6483,26 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void if hr >= 0 || !crate::gpu::shader::readable(desc as usize, 16) { return hr; } + fallback_stream_pso(this, f, desc, riid, ppv, hr) +} + +/// XCL's dummy shaders in the title's stream (`fallback_stream`), known as a fallback +/// (`note_fallback_pso`); `failed` when there is none. +unsafe fn fallback_stream_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, failed: HRESULT) -> HRESULT { let Some((buf, _)) = fallback_stream(desc as *const u8) else { - note_fallback("PSO stream", hr, false); - return hr; + note_fallback("PSO stream", failed, false); + return failed; }; let new_desc: [usize; 2] = [buf.len(), buf.as_ptr() as usize]; let hr2 = finish_pso(this, f, new_desc.as_ptr() as *const c_void, riid, ppv); - note_fallback("PSO stream", hr, hr2 >= 0); + if hr2 >= 0 { + note_fallback_pso(ppv, false); + } + note_fallback("PSO stream", failed, hr2 >= 0); if hr2 >= 0 { hr2 } else { - hr + failed } } @@ -5431,6 +6547,9 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 // --------------------------------------------------------------------------------------- unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { + let _xcl_api = crate::waitwatch::api("real::dev_create_rtv"); + note_small_view("RTV", res); + note_traced_view("RTV", res, ""); type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); // a view in a console-only format, or of a target made R8G8B8A8 (`device_x::pc_resource_desc`) @@ -5544,13 +6663,7 @@ unsafe extern "system" fn cl_execute_indirect( } unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - super::list_x::on_release(this as usize); - super::bind::forget(this); - } - n + hooked_release(this, Kind::CommandList) } unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { @@ -5563,13 +6676,7 @@ unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { } unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - super::alloc_pool::forget(this as usize); - super::list_x::on_allocator_release(this as usize); - } - n + hooked_release(this, Kind::CommandAllocator) } /// Reset the (adopted) PC allocator `raw` itself. @@ -5600,12 +6707,16 @@ unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { } unsafe extern "system" fn signature_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - super::bind::forget_mac_signatures(this as usize); - } - n + hooked_release(this, Kind::CommandSignature) +} + +/// Query heaps and root signatures: only their last Release is held (nothing of theirs is kept). +unsafe extern "system" fn query_heap_release(this: *mut c_void) -> u32 { + hooked_release(this, Kind::QueryHeap) +} + +unsafe extern "system" fn root_signature_release(this: *mut c_void) -> u32 { + hooked_release(this, Kind::RootSignature) } // --------------------------------------------------------------------------------------- @@ -5672,6 +6783,12 @@ fn is_fence(p: usize) -> bool { p != 0 && FENCES.read().unwrap_or_else(|e| e.into_inner()).contains(&p) } +/// Whether `p` is a fence the title created through the device – one XCL holds a reference to +/// for good (`dev_create_fence`). +pub(super) fn is_title_fence(p: usize) -> bool { + is_fence(p) +} + /// first queue slot `queue_dispatch` handles const QUEUE_FIRST: usize = 14; @@ -5704,10 +6821,12 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a if hr >= 0 { if older == 14 { super::fence_x::note_queue_signal(a1, a2 as u64); + super::stall::note_signal(this, a1, a2 as u64); super::list_x::note_title_queue_signal(this as usize, a1, a2 as u64); } else { super::fence_x::note_queue_wait(a1, a2 as u64); super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); + crate::waitwatch::note_gpu_wait_raw("title queue Wait", this as usize, a1, a2 as u64); } } hr as u32 as usize @@ -5805,6 +6924,7 @@ unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, valu let hr = f(this, fence, value); if hr >= 0 { super::fence_x::note_queue_signal(fence as usize, value); + super::stall::note_signal(this, fence as usize, value); super::list_x::note_title_queue_signal(this as usize, fence as usize, value); } hr @@ -5813,12 +6933,17 @@ unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, valu /// Fence::Signal (CPU) unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT { let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Signal"))); + // (the value before: a Signal below it is a rewind – `fence_x::note_cpu_signal`) + let before = ID3D12Fence::from_raw_borrowed(&this).map_or(0, |f| f.GetCompletedValue()); let hr = f(this, value); - super::fence_x::note_cpu_signal(this as usize); + if hr >= 0 { + super::fence_x::note_cpu_signal(this as usize, value, before); + } hr } unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) { + let _xcl_api = crate::waitwatch::api("real::q_execute_command_lists"); type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists"))); if n == 0 || lists.is_null() { @@ -5826,11 +6951,6 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis stop_if_device_removed(); return; } - // textures in title memory the CPU wrote since: uploaded again first - super::title_textures::refresh(this); - if crate::util::mac_host() { - super::console_heap::resync_title_writes(); - } // console-shaped lists run as the PC lists they were translated into (split title lists expand // into all of their recorded PC segments in exact chronological order) let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); @@ -5841,9 +6961,29 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis mapped.push(l); } } + // recordings run again: their dispatch blocks start afresh (before the CPU's writes go up) + if !super::title_textures::is_own_work() { + super::bind::before_submit(&mapped); + } + // (local fix) mirrors of buffer views outside unified memory: what the CPU wrote since + super::list_x::sync_view_mirrors(); + // textures in title memory the CPU wrote since: uploaded again first + super::title_textures::refresh(this); + if crate::util::mac_host() { + super::console_heap::resync_title_writes(); + } super::list_x::note_queue_for_lists(this as usize, &mapped); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { - f(this, chunk.len() as u32, chunk.as_ptr()); + { + let _ops = super::d3d_ops(); + // (XCL's own uploads and readbacks on its queues are not the title's work) + if !super::title_textures::is_own_work() { + super::stall::submitted(this, chunk); + } + // (a value reserved before, signalled right after: what D3DMetal releases from + // inside waits for this chunk – `late_release`) + super::late_release::submit(this, || f(this, chunk.len() as u32, chunk.as_ptr())); + } super::alloc_pool::executed(this, chunk); super::list_x::signal_write64_fences(this, chunk); super::list_x::readback_sparse_writes(this, chunk); @@ -6178,6 +7318,383 @@ mod standin_tests { } } +#[cfg(test)] +mod fallback_tests { + use super::*; + + /// A compute pipeline whose shader the driver refused is made with XCL's fallback shader and + /// is known as a fallback (`fallback_kind`: binds skip its work) until it is forgotten, as + /// `gone` forgets it when it is released – a later pipeline at its address is none. + #[test] + fn a_compute_fallback_is_known_until_forgotten() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let dev = dev.unwrap(); + // (XCL's device: `dev_create_compute_pso` calls the driver through its table) + adopt(dev.as_raw(), Kind::Device); + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).expect("serialize RS"); + let ser = ser.unwrap(); + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())) + .expect("CreateRootSignature"); + // a PC program, not a console one: no translation is tried, the driver gets it + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: bytecode(dummy_cs_bytecode()), + ..Default::default() + }; + let iid = pc_iid(Kind::PipelineState); + let mut out: *mut c_void = std::ptr::null_mut(); + // refused as a driver refusing its shader would; the fallback with XCL's shader is + // then made by the driver + reject_next_pso_for_test(); + let hr = dev_create_compute_pso(dev.as_raw(), &desc as *const _ as *const c_void, &iid, &mut out); + std::mem::ManuallyDrop::drop(&mut desc.pRootSignature); + assert!(hr >= 0 && !out.is_null(), "the fallback is made: {hr:#x}"); + assert_eq!(fallback_kind(out as usize), Some(true), "a compute fallback"); + forget_pso_for_test(out as usize); + assert_eq!(fallback_kind(out as usize), None, "forgotten with its pipeline"); + drop(ID3D12PipelineState::from_raw(out)); + } + } +} + +#[cfg(test)] +mod big_compile_tests { + use super::*; + + /// With a big lane no thread takes the one `BIG_COMPILES` slot (no worker waits behind a + /// compile that does not end), and every pipeline worker still waits for commit before a big + /// compile; without one the slot is taken as before 0023. + #[test] + fn the_slot_is_taken_only_without_a_big_lane() { + // (big, uncached, on a pipeline worker, big lane) → (slot, commit) + assert_eq!(big_compile_gate(true, true, true, true), (false, true)); + assert_eq!(big_compile_gate(true, true, true, false), (true, true)); + assert_eq!(big_compile_gate(true, true, false, true), (false, false)); + assert_eq!(big_compile_gate(true, false, true, false), (false, false)); + assert_eq!(big_compile_gate(false, true, true, false), (false, false)); + } + + /// A big compile's wait for commit is counted (PP3's queue line): with 1 GiB, 1 GiB, then 4 GiB + /// available – three looks – one wait begun, two naps of 200 ms counted (400 ms or more), and + /// none waiting once it is over; one waiting while it naps; with 3 GiB or more, or nothing told, + /// no wait at all. (Counts of the test's own: other tests' big compiles move the process's.) + #[test] + fn a_commit_wait_is_counted_with_its_time() { + let ms = std::time::Duration::from_millis; + let counts: [AtomicU64; 3] = Default::default(); + let now = |c: &[AtomicU64; 3]| c.each_ref().map(|n| n.load(Ordering::Acquire)); + let mut looks = [1u64 << 30, 1 << 30, 4 << 30].into_iter(); + let mut asked = 0; + let t = std::time::Instant::now(); + wait_for_commit_in( + &counts, + || { + asked += 1; + looks.next() + }, + ms(200), + ); + let took = t.elapsed(); + assert_eq!(asked, 3, "three looks"); + assert!(took >= ms(400), "two naps: {took:?}"); + let [begun, waited, waiting] = now(&counts); + assert_eq!((begun, waiting), (1, 0), "one wait begun, over"); + assert!((400..took.as_millis() as u64 + 1).contains(&waited), "its naps counted: {waited} ms of {took:?}"); + wait_for_commit_in(&counts, || Some(3 << 30), ms(200)); + wait_for_commit_in(&counts, || None, ms(200)); + assert_eq!(now(&counts), [1, waited, 0], "enough, or not told: no wait"); + // one waiting while it naps + let (counts, go) = (std::sync::Arc::new(counts), std::sync::Arc::new(AtomicBool::new(false))); + let (c2, g2) = (counts.clone(), go.clone()); + let waiter = std::thread::spawn(move || wait_for_commit_in(&c2, || Some(if g2.load(Ordering::Acquire) { 8 << 30 } else { 0 }), ms(10))); + let t = std::time::Instant::now(); + while now(&counts)[2] == 0 && t.elapsed() < ms(5000) { + std::thread::sleep(ms(5)); + } + assert_eq!(now(&counts)[0], 2, "a second wait begun"); + assert_eq!(now(&counts)[2], 1, "waiting now"); + go.store(true, Ordering::Release); + waiter.join().unwrap(); + assert_eq!(now(&counts)[2], 0, "over"); + } +} + +#[cfg(test)] +mod refusal_tests { + use super::*; + + /// The refusal switches and what the translation cache says of a CS, for this thread's calls + /// until dropped. + struct Switches; + + impl Switches { + fn set(cap_kb: u64, list: Vec, dxil: Option>) -> Switches { + TEST_REFUSAL.with(|t| *t.borrow_mut() = Some((cap_kb, list))); + TEST_DXIL.with(|t| t.set(dxil)); + Switches + } + } + + impl Drop for Switches { + fn drop(&mut self) { + TEST_REFUSAL.with(|t| *t.borrow_mut() = None); + TEST_DXIL.with(|t| t.set(None)); + } + } + + thread_local! { + /// the stand-in the fake stand-in function gives next + static NEXT_STANDIN: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// the fake driver's creations on this thread + static PSO_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + static BUILT_FAKE: AtomicBool = AtomicBool::new(false); + + unsafe fn fake_standin(_: *mut c_void, _: PsoFn, _: *const c_void, _: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + *ppv = NEXT_STANDIN.with(|n| n.get()) as *mut c_void; + S_OK + } + + unsafe fn fake_build(_: Dev, _: &OwnedDesc, _: *mut *mut c_void) -> bool { + BUILT_FAKE.store(true, Ordering::Release); + false + } + + unsafe extern "system" fn fake_driver(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { + PSO_CALLS.with(|n| n.set(n.get() + 1)); + E_FAIL + } + + /// `go_background` of a compute pipeline of `blob` on `this`, the stand-in `standin`. + unsafe fn background(this: *mut c_void, blob: &[u8], standin: usize) -> (Option, usize) { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { CS: bytecode(blob), ..Default::default() }; + let owned = own_compute(&desc as *const _ as *const c_void).unwrap(); + NEXT_STANDIN.with(|n| n.set(standin)); + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = go_background(this, fake_driver, &desc as *const _ as *const c_void, std::ptr::null(), &mut out, true, owned, fake_standin, fake_build); + (hr, out as usize) + } + + #[test] + fn dxil_over_the_cap_only_and_none_with_the_cap_off() { + assert!(!over_cap(4 << 20, 4096)); + assert!(over_cap((4 << 20) + 1, 4096)); + assert!(over_cap(29_756_576, 4096), "GTA VI's biggest (run 64)"); + assert!(!over_cap(2_097_444, 4096), "the next one, 2.1 MB"); + assert!(!over_cap(usize::MAX, 0), "0: no cap"); + } + + #[test] + fn a_listed_or_too_big_program_is_refused_and_an_estimate_never() { + let (h, h2) = (0x56c0cd3b82a00c6e, 0x958400d2caf07244); + assert_eq!(refusal_by("CS", h, None, 4096, &[h]), Some(Refusal::Listed)); + assert_eq!(refusal_by("VS", h, None, 4096, &[h]), None, "XCL_NO_BUILD_CS lists compute programs"); + assert_eq!(refusal_by("CS", h2, Some(30 << 20), 4096, &[]), Some(Refusal::TooBig)); + assert_eq!(refusal_by("CS", h2, Some(2 << 20), 4096, &[]), None); + assert_eq!(refusal_by("CS", h2, None, 1, &[]), None, "a size not known is never refused"); + } + + /// A compute pipeline whose program is refused – listed, or over the cap by the translation + /// cache's header – gets its stand-in and an entry that is over with no pipeline: never queued, + /// never waited for, never built. A program sized by an estimate is never refused. + #[test] + fn a_refused_compute_pipeline_gets_its_stand_in_and_is_never_queued() { + use super::super::pso_async::{self, StandinState}; + if !pso_async::lazy() || (max_dxil_kb() == 0 && pso_async::big_threads() == 0) { + return crate::gpu::recomp::runner::skip_config("pipelines are not lazy, or not sized (XCL_LAZY_PSO, XCL_ASYNC_PSO, XCL_PSO_MAX_DXIL_KB=0 with XCL_PSO_BIG_THREADS=0)"); + } + let refused = Some(StandinState { compute: true, built: false, done: true, late: false }); + unsafe { + // (1) listed + let blob = vec![0x5Au8; 64]; + let switches = Switches::set(4096, vec![crate::gpu::shader::fnv64(&blob)], Some(None)); + let (hr, out) = background(std::ptr::null_mut(), &blob, 0x7E57_A001); + assert_eq!((hr, out), (Some(S_OK), 0x7E57_A001), "the title gets its stand-in"); + assert!(!pso_async::is_pending(out)); + assert_eq!(pso_async::standin_state(out), refused, "over, not built"); + assert_eq!(pso_async::state_for_test(out).map(|s| s.3), Some(true), "refused"); + assert_eq!(pso_async::resolve_wait(out), out, "not waited for"); + drop(switches); + // (2) over the cap by the translation cache's header + let blob = vec![0x5Bu8; 64]; + let switches = Switches::set(4096, Vec::new(), Some(Some(30 << 20))); + let (hr, out2) = background(std::ptr::null_mut(), &blob, 0x7E57_A002); + assert_eq!((hr, out2), (Some(S_OK), 0x7E57_A002)); + assert_eq!(pso_async::standin_state(out2), refused); + assert_eq!(pso_async::state_for_test(out2).map(|s| s.3), Some(true), "refused"); + drop(switches); + // (3) under it: built when first bound + let blob = vec![0x5Cu8; 64]; + let switches = Switches::set(4096, Vec::new(), Some(Some(2 << 20))); + let (_, out3) = background(std::ptr::null_mut(), &blob, 0x7E57_A003); + assert!(pso_async::is_pending(out3), "a lazy entry"); + assert_eq!(pso_async::state_for_test(out3).map(|s| s.3), Some(false)); + drop(switches); + // (4) not translated yet: 300 KB of console code, ~4.8 MB of DXIL by the estimate + let blob = vec![0x5Du8; 300 << 10]; + let switches = Switches::set(4096, Vec::new(), Some(None)); + let (_, out4) = background(std::ptr::null_mut(), &blob, 0x7E57_A004); + assert!(pso_async::is_pending(out4), "an estimate never refuses"); + drop(switches); + assert!(!BUILT_FAKE.load(Ordering::Acquire), "nothing was built"); + for s in [out, out2, out3, out4] { + assert_eq!(pso_async::released(s), 0); + } + } + } + + /// (GPU and DXC) A translated compute program over the cap never reaches the driver: refused + /// once translated, and from the translation cache's header when made – sized by the file its + /// translation is (`compute_translation` on both sides). Its own fresh `XCL_DXIL_CACHE`: the + /// user's caches stay untouched, and a warm folder would let a mutation pass. + #[test] + #[ignore] + fn gpu_translated_compute_over_the_cap_never_reaches_the_driver() { + use crate::gpu::recomp::pso::{console_to_dxil_for, Stage}; + use crate::gpu::xbox::tests::{fssm, sample, CODE}; + use super::super::pso_async; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + if std::env::var_os("XCL_DXIL_CACHE").is_none() || std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { + return crate::gpu::recomp::runner::skip_config("XCL_DXIL_CACHE (a fresh folder of its own) not set, or the translation cache off"); + } + // pso.rs's bench program: 256 times two instructions, then its end + let mut code = Vec::new(); + for _ in 0..256 { + code.extend_from_slice(&CODE[..8]); + } + code.extend_from_slice(&CODE[8..]); + 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 blob = sample(5, &[f]); + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let dev = dev.unwrap(); + // (XCL's device: its root signatures are made through its table) + adopt(dev.as_raw(), Kind::Device); + let this = dev.as_raw(); + let (stage, sampler_base, split) = compute_translation(this); + assert!(crate::gpu::recomp::pso::translated_dxil_len(&blob, stage, sampler_base, split).is_none(), "XCL_DXIL_CACHE must be a fresh folder: this program is translated there already"); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { CS: bytecode(&blob), ..Default::default() }; + let iid = pc_iid(Kind::PipelineState); + let mut out: *mut c_void = std::ptr::null_mut(); + // (1) refused once translated: the driver never sees it + let switches = Switches::set(1, Vec::new(), None); + PSO_CALLS.with(|n| n.set(0)); + let r = translated_compute_pso(this, fake_driver, &desc as *const _ as *const c_void, &iid, &mut out); + assert!(matches!(r, Some(Err(()))), "refused"); + assert_eq!(PSO_CALLS.with(|n| n.get()), 0, "the driver never got it"); + // (2) sized by its translation's file + let dxil = console_to_dxil_for(&blob, Stage::Compute, 0, wave32_only(this)).expect("translated").dxil; + assert!(dxil.len() > 1 << 10, "more DXIL than the cap of (1): {} B", dxil.len()); + let owned = own_compute(&desc as *const _ as *const c_void).unwrap(); + let prog = program_of(this, &owned, 1, &shader_hashes(owned.blobs())); + assert!(!prog.estimated && prog.dxil as usize == dxil.len(), "sized from the translation cache: {prog:?}, {} B", dxil.len()); + // (3) refused from the header when made + let (hr, standin) = background(this, &blob, 0x7E57_A011); + assert_eq!(hr, Some(S_OK)); + assert!(!pso_async::is_pending(standin) && pso_async::state_for_test(standin).is_some_and(|s| s.3), "a refused entry"); + assert_eq!(PSO_CALLS.with(|n| n.get()), 0); + drop(switches); + // (4) no cap: the driver gets it (and the fake one refuses it) + let switches = Switches::set(0, Vec::new(), None); + let r = translated_compute_pso(this, fake_driver, &desc as *const _ as *const c_void, &iid, &mut out); + assert!(matches!(r, Some(Err(())))); + assert_eq!(PSO_CALLS.with(|n| n.get()), 1, "one driver call"); + drop(switches); + assert_eq!(pso_async::released(standin), 0); + } + } + + /// A refused graphics or mesh program gets XCL's dummy shaders: never its console bytecode + /// in the driver, never a failed call. + #[test] + fn a_refused_graphics_or_mesh_program_never_gives_the_driver_its_console_shaders() { + assert!(!untranslated_to_driver(true, false)); + assert!(!untranslated_to_driver(false, true)); + assert!(untranslated_to_driver(false, false)); + assert!(![S_OK, E_FAIL, E_INVALIDARG, E_NOINTERFACE].contains(&E_REFUSED)); + assert!(E_REFUSED < 0, "a failure code: no caller takes it for a pipeline"); + } + + /// What the workers' queue looks a pipeline's translations up by (`program_of`, PP2): a compute + /// one's CS by its hash, on disk as its size was found (not found: Some(false), asked again when + /// sent – A2); a graphics one's VS and console PS by their hashes – a PS that is not console + /// code by none – with nothing looked up when made, and never with a console HS, DS or GS; a mesh + /// stream never; the split flags as the device gives them (none: assumed, both); the key and the + /// program's hash as before. + #[test] + fn a_pipelines_program_names_its_shaders_for_the_workers_queue() { + use crate::gpu::xbox::tests::{fssm, sample, CODE}; + let console = |kind: u32, n: u8| { + let mut code = CODE.to_vec(); + code[0] = n; + sample(kind, &[fssm(&code, &[(0, 0)])]) + }; + let fnv = crate::gpu::shader::fnv64; + unsafe { + // compute + let cs = console(5, 1); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { CS: bytecode(&cs), ..Default::default() }; + let owned = own_compute(&desc as *const _ as *const c_void).unwrap(); + let hashes = shader_hashes(owned.blobs()); + assert_eq!(hashes, [fnv(&cs)]); + let sized = max_dxil_kb() != 0 || super::super::pso_async::big_threads() > 0; + for (found, translated) in [(Some(300 << 10), Some(true)), (None, Some(false))] { + let _s = Switches::set(4096, Vec::new(), Some(found)); + let p = program_of(std::ptr::null_mut(), &owned, key_of(&hashes), &hashes); + assert_eq!((p.hash, p.kind, p.key, p.shaders, p.split), (fnv(&cs), b'C', key_of(&hashes), [fnv(&cs), 0], true)); + assert_eq!(p.translated, sized.then_some(translated.unwrap()), "{found:?}"); + } + // graphics: a console VS and PS + let (vs, ps) = (console(1, 2), console(0, 3)); + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC { VS: bytecode(&vs), PS: bytecode(&ps), ..Default::default() }; + let owned = own_graphics(&d as *const _ as *const c_void).unwrap(); + let hashes = shader_hashes(owned.blobs()); + let p = program_of(std::ptr::null_mut(), &owned, key_of(&hashes), &hashes); + assert_eq!((p.hash, p.kind, p.shaders, p.split, p.translated), (fnv(&vs), b'G', [fnv(&vs), fnv(&ps)], true, None), "nothing looked up when made"); + assert_eq!(key_of(&hashes), shaders_key(&[vs.clone(), ps.clone()]), "its key as before"); + // a PS that is not console code: not looked up + let pc_ps = vec![0x44u8; 64]; + d.PS = bytecode(&pc_ps); + let owned = own_graphics(&d as *const _ as *const c_void).unwrap(); + let p = program_of(std::ptr::null_mut(), &owned, 7, &shader_hashes(owned.blobs())); + assert_eq!((p.shaders, p.translated), ([fnv(&vs), 0], None)); + // a console GS (or an HS, a DS): never + let gs = console(2, 4); + d.PS = bytecode(&ps); + d.GS = bytecode(&gs); + let owned = own_graphics(&d as *const _ as *const c_void).unwrap(); + let p = program_of(std::ptr::null_mut(), &owned, 7, &shader_hashes(owned.blobs())); + assert_eq!((p.shaders, p.translated), ([fnv(&vs), fnv(&ps)], Some(false)), "the GS's"); + d.GS = D3D12_SHADER_BYTECODE::default(); + d.HS = bytecode(&gs); + let owned = own_graphics(&d as *const _ as *const c_void).unwrap(); + assert_eq!(program_of(std::ptr::null_mut(), &owned, 7, &shader_hashes(owned.blobs())).translated, Some(false), "the HS's"); + // a mesh stream: never + let ms = console(1, 5); + let owned = OwnedDesc::Stream(Box::new([0, 0]), Vec::new(), vec![ms.clone()], Some(0)); + let p = program_of(std::ptr::null_mut(), &owned, 7, &shader_hashes(owned.blobs())); + assert_eq!((p.hash, p.kind, p.translated), (fnv(&ms), b'M', Some(false))); + // hashes not given (or not the blobs'): the program's hashed as before + let p = program_of(std::ptr::null_mut(), &owned, 7, &[]); + assert_eq!(p.hash, fnv(&ms)); + } + } +} + #[cfg(test)] mod cache_report_tests { use super::*; @@ -6399,6 +7916,12 @@ mod readback_routing_tests { // Invoke Release through the adopted vtable slot 2. let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vt(raw).add(2)); assert_eq!(release(raw), 0); + // (where the last Release of a list is held until the queues are past its work, its + // state goes when the list really does – `late_release`) + let t = std::time::Instant::now(); + while super::super::list_x::has_list_state(key) && t.elapsed().as_secs() < 10 { + std::thread::sleep(std::time::Duration::from_millis(5)); + } assert!(!super::super::list_x::has_list_state(key), "releasing DMA list must remove its list_x::LISTS entry"); } } @@ -6441,6 +7964,8 @@ mod queue_tests { FENCES.write().unwrap().push(fence); queue_dispatch(14, this, fence, 1, 0, 0); FENCES.write().unwrap().retain(|&f| f != fence); + // (a stand-in: no other thread may ask its value) + super::super::fence_x::forget_for_test(fence); assert!(QUEUE_OLDER.load(Ordering::Acquire) && !QUEUE_SHIFTED.load(Ordering::Acquire)); let mut out = [0xAAAA_AAAAu32; 4]; queue_dispatch(18, this, out.as_mut_ptr() as usize, 0, 0, 0); @@ -6675,3 +8200,712 @@ mod console_format_query_tests { } } } + +#[cfg(test)] +mod release_tests { + use super::*; + + /// A fake adopted COM object: its own AddRef / Release count in `refs` (AddRef spins a + /// little, which widens the window between the steps of the last-reference test); its end + /// is counted in `ended`. + #[repr(C)] + struct Fake { + vt: *const usize, + refs: AtomicU32, + ended: AtomicU32, + } + + // SAFETY: `vt` points at a table leaked for the process and never written + unsafe impl Sync for Fake {} + + unsafe extern "system" fn fake_qi(_this: *mut c_void, _iid: *const GUID, out: *mut *mut c_void) -> HRESULT { + *out = std::ptr::null_mut(); + E_NOINTERFACE + } + + unsafe extern "system" fn fake_add_ref(this: *mut c_void) -> u32 { + let f = &*(this as *const Fake); + for _ in 0..64 { + std::hint::spin_loop(); + } + f.refs.fetch_add(1, Ordering::SeqCst) + 1 + } + + unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 { + let f = &*(this as *const Fake); + let n = f.refs.fetch_sub(1, Ordering::SeqCst) - 1; + if n == 0 { + f.ended.fetch_add(1, Ordering::SeqCst); + } + n + } + + /// The extended table of the fakes (kept for the process: the ledger may let them go late). + fn table() -> *const usize { + static T: OnceLock = OnceLock::new(); + *T.get_or_init(|| { + let orig: &'static [usize] = Box::leak(vec![fake_qi as usize, fake_add_ref as usize, fake_release as usize].into_boxed_slice()); + let (storage, table) = test_ext_table(orig); + std::mem::forget(storage); + table as usize + }) as *const usize + } + + /// A fake with `refs` references, for the rest of the process. + fn fake(refs: u32) -> &'static Fake { + Box::leak(Box::new(Fake { vt: table(), refs: AtomicU32::new(refs), ended: AtomicU32::new(0) })) + } + + /// Two last-but-one releases of one object at once: exactly one of them finds the last + /// reference and the ledger holds it – never both missing it and the object ending inside + /// the hook (which they did, without the stripe). + #[test] + fn concurrent_last_but_one_releases_always_hold() { + super::super::late_release::init(); + if !super::super::late_release::defers(Kind::Resource) { + return; + } + let _one = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + const N: usize = 10_000; + let objs: &'static [&'static Fake] = Box::leak((0..N).map(|_| fake(2)).collect::>().into_boxed_slice()); + let ready: &'static [AtomicUsize] = Box::leak((0..N).map(|_| AtomicUsize::new(0)).collect::>().into_boxed_slice()); + let returns: &'static [[AtomicU32; 2]] = Box::leak((0..N).map(|_| [AtomicU32::new(9), AtomicU32::new(9)]).collect::>().into_boxed_slice()); + let threads: Vec<_> = (0..2) + .map(|k| { + std::thread::spawn(move || { + for i in 0..N { + // both threads at the same object at once + ready[i].fetch_add(1, Ordering::SeqCst); + while ready[i].load(Ordering::SeqCst) < 2 { + std::hint::spin_loop(); + } + let p = objs[i] as *const Fake as *mut c_void; + let n = unsafe { hooked_release(p, Kind::Resource) }; + returns[i][k].store(n, Ordering::SeqCst); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + for (i, r) in returns.iter().enumerate() { + let mut got = [r[0].load(Ordering::SeqCst), r[1].load(Ordering::SeqCst)]; + got.sort_unstable(); + assert_eq!(got, [0, 1], "object {i}: one release sees another reference, the other is the last and is held"); + } + if crate::util::mac_host() { + // (they end on the ledger's thread, after the grace) + let t = std::time::Instant::now(); + while objs.iter().any(|o| o.ended.load(Ordering::SeqCst) == 0) { + assert!(t.elapsed().as_secs() < 20, "the ledger lets them all go"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } + assert!(objs.iter().all(|o| o.ended.load(Ordering::SeqCst) == 1 && o.refs.load(Ordering::SeqCst) == 0), "each ends once"); + } + + /// On the host's D3D12 (GPU-gated): AddRef and Release of every kind whose last Release is + /// held give COM counts – what the last-reference test reads (an object whose counts did + /// not add up would just go as it is, never held). + #[test] + fn every_held_kind_counts_its_references() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let counts = |raw: *mut c_void, what: &str| { + let add: RefFn = std::mem::transmute(*vt(raw).add(1)); + let rel: RefFn = std::mem::transmute(*vt(raw).add(2)); + let a = add(raw); + let b = add(raw); + let r = rel(raw); + let r2 = rel(raw); + assert_eq!(b, a + 1, "{what}: AddRef counts"); + assert_eq!(r, a, "{what}: Release counts"); + assert_eq!(r2 + 1, a, "{what}: back where it was"); + }; + let mut res: Option = None; + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 65536, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut res).unwrap(); + counts(res.as_ref().unwrap().as_raw(), "resource"); + let mut heap: Option = None; + let hd = D3D12_HEAP_DESC { SizeInBytes: 1 << 20, Properties: hp, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; + dev.CreateHeap(&hd, &mut heap).unwrap(); + counts(heap.as_ref().unwrap().as_raw(), "heap"); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 16, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .unwrap(); + counts(dh.as_raw(), "descriptor heap"); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + counts(alloc.as_raw(), "command allocator"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + counts(list.as_raw(), "command list"); + let mut qh: Option = None; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_OCCLUSION, Count: 4, NodeMask: 0 }, &mut qh).unwrap(); + counts(qh.as_ref().unwrap().as_raw(), "query heap"); + let rs_desc = D3D12_ROOT_SIGNATURE_DESC { Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, ..Default::default() }; + let mut blob: Option = None; + D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).unwrap(); + let blob = blob.unwrap(); + let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, bytes).unwrap(); + counts(rs.as_raw(), "root signature"); + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() }; + let cs_desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }; + let mut sig: Option = None; + dev.CreateCommandSignature(&cs_desc, None, &mut sig).unwrap(); + counts(sig.as_ref().unwrap().as_raw(), "command signature"); + match crate::gpu::recomp::dxc::compile("[numthreads(1,1,1)] void main() {}", "main", "cs_6_0", &[]) { + Ok(cs) => { + let pd = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, + ..Default::default() + }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&pd).unwrap(); + counts(pso.as_raw(), "pipeline state"); + } + Err(e) => crate::xlog_warn!("(no compute pipeline to count: {e})"), + } + } + } + + /// A held object XCL keeps looking at (a texture kept in step: a clone, then its Release, + /// every frame while it is registered) still goes, soon after its grace: with the touch on, + /// each look moved it back before its grace was up, and GTA VI's world load piled up 8 GB. + #[test] + fn a_held_reference_xcl_keeps_looking_at_still_goes() { + super::super::late_release::init(); + if !super::super::late_release::defers(Kind::Resource) || !crate::util::mac_host() { + return; + } + let _one = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + let f = fake(1); + let p = f as *const Fake as usize; + TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(p, 0x7_5678_0000); + assert_eq!(unsafe { hooked_release(p as *mut c_void, Kind::Resource) }, 0, "the title's last Release is held"); + // XCL looks at it every 10 ms while it is registered (as title_textures does under its + // lock: once forgotten, it is not looked at again) + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let looker = { + let stop = stop.clone(); + std::thread::spawn(move || { + let mut looks = 0u32; + while !stop.load(Ordering::SeqCst) { + let cloned = { + let g = TITLE_ADDRESS.lock().unwrap(); + let registered = g.as_ref().is_some_and(|m| m.contains_key(&p)); + if registered { + unsafe { fake_add_ref(p as *mut c_void) }; + } + registered + }; + if cloned { + looks += 1; + std::thread::sleep(std::time::Duration::from_millis(1)); + unsafe { hooked_release(p as *mut c_void, Kind::Resource) }; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + looks + }) + }; + let t = std::time::Instant::now(); + while f.ended.load(Ordering::SeqCst) == 0 && t.elapsed().as_secs() < 5 { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + stop.store(true, Ordering::SeqCst); + let looks = looker.join().unwrap(); + assert!(looks > 0, "it was looked at while held"); + assert_eq!(f.ended.load(Ordering::SeqCst), 1, "let go once, while still being looked at, within 5 s (took {:?})", t.elapsed()); + assert_eq!(f.refs.load(Ordering::SeqCst), 0); + } + + /// The ledger's reference goes as the last one only when no other is left: with one more + /// (an XCL clone), only the ledger's goes and what XCL keeps by the object's address stays; + /// the clone's Release is then the last, held in turn, and the object ends once. + #[test] + fn a_held_reference_is_the_last_only_when_no_other_is_left() { + super::super::late_release::init(); + if !super::super::late_release::defers(Kind::Resource) || !crate::util::mac_host() { + return; + } + let _one = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + let f = fake(2); + let p = f as *const Fake as usize; + TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(p, 0x7_1234_0000); + let kept = || TITLE_ADDRESS.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&p)); + unsafe { release_held(p, Kind::Resource) }; + assert_eq!(f.refs.load(Ordering::SeqCst), 1, "only the ledger's reference went"); + assert_eq!(f.ended.load(Ordering::SeqCst), 0); + assert!(kept(), "what XCL keeps of it stays while it lives"); + assert_eq!(unsafe { hooked_release(p as *mut c_void, Kind::Resource) }, 0, "the clone's Release is the last"); + assert_eq!(f.ended.load(Ordering::SeqCst), 0, "held, not ended in the hook"); + assert!(kept()); + let t = std::time::Instant::now(); + while f.ended.load(Ordering::SeqCst) == 0 { + assert!(t.elapsed().as_secs() < 10, "let go"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(f.ended.load(Ordering::SeqCst), 1, "ended once"); + assert!(!kept(), "forgotten before its end"); + } + + /// A buffer the title placed that got a PC resource of its own leaves the census of such + /// buffers with its last Release: on the Mac when the ledger lets it go (on its worker, where + /// a test's `outside::on` is not), elsewhere inside the hook. + #[test] + fn a_placed_buffer_leaves_the_census_with_its_release() { + use super::super::outside; + super::super::late_release::init(); + let _census = outside::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _one = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + let f = fake(1); + let p = f as *const Fake as usize; + set_test_title_address(p, Some(0x7_6543_0000)); + outside::note_for_test(p, 0x7_6543_0000, 4096); + assert!(outside::in_census_for_test(p)); + assert_eq!(unsafe { hooked_release(p as *mut c_void, Kind::Resource) }, 0, "the title's last Release"); + let t = std::time::Instant::now(); + while outside::in_census_for_test(p) || f.ended.load(Ordering::SeqCst) == 0 { + assert!(t.elapsed().as_secs() < 10, "its census entry went with its release (in the census: {})", outside::in_census_for_test(p)); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(f.ended.load(Ordering::SeqCst), 1, "ended once"); + assert!(!outside::in_census_for_test(p)); + } +} + +#[cfg(test)] +mod outside_view_tests { + use super::super::outside::{self, EmptyView, Noted}; + use super::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS}; + + unsafe extern "system" fn no_srv(_this: *mut c_void, _res: *mut c_void, _desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, _cpu: u64) {} + + unsafe extern "system" fn no_uav(_this: *mut c_void, _res: *mut c_void, _counter: *mut c_void, _desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, _cpu: u64) {} + + /// A view by address as devices #70 and #71 take it: the PC's view desc, the GPU address at 0x28. + fn view_at(desc: &T, va: u64) -> [u8; 0x40] { + let mut b = [0u8; 0x40]; + let n = std::mem::size_of::().min(0x28); + unsafe { std::ptr::copy_nonoverlapping(desc as *const T as *const u8, b.as_mut_ptr(), n) }; + b[0x28..0x30].copy_from_slice(&va.to_le_bytes()); + b + } + + /// Each view given an empty descriptor is noted with its kind – buffer SRV or UAV, CBV – and + /// the title memory its V# would have named (its elements as the V# has them, none without a + /// title address); views by address of buffers outside unified memory with their V#'s base, + /// and texture views by address XCL could make no texture for. Views of unified memory, null + /// views and views at address 0 are not. + #[test] + fn empty_views_are_noted_by_kind_with_their_title_memory() { + let _g = outside::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(u) = crate::gpu::uma::get() else { return }; + let Some(inside) = (0..u.windows()).map(|k| u.window(k)).find(|w| w.1 > 0x20_0000).map(|w| w.0 + 0x10_0000) else { return }; + if u.contains(0x8470_0000) { + return crate::gpu::recomp::runner::skip_config("a window over 0x84700000"); + } + unsafe { + let out = VirtualAlloc(std::ptr::null(), 1 << 20, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert_ne!(out, 0, "a reservation outside the windows"); + // (a stand-in resource with a title address – a UAV view never looks at its resource – + // and one without – an SRV view looks at it only when it has one) + let (with_ta, without) = (0x7D0D_1000usize, 0x7D0D_2000usize); + struct Undo(usize, usize); + impl Drop for Undo { + fn drop(&mut self) { + set_test_title_address(self.0, None); + unsafe { VirtualFree(self.1 as *mut c_void, 0, MEM_RELEASE) }; + } + } + let _undo = Undo(with_ta, out); + set_test_title_address(with_ta, Some(out)); + // a device whose CreateShaderResourceView and CreateUnorderedAccessView do nothing + let mut orig = vec![0usize; 20]; + orig[18] = no_srv as usize; + orig[19] = no_uav as usize; + let (_table, vt) = test_ext_table(&orig); + let mut object = vt as usize; + let dev = &mut object as *mut usize as *mut c_void; + let _ = outside::take_noted_for_test(); + let before = outside::views().by_address; + assert_eq!(buffer_view(with_ta, DXGI_FORMAT_R32_TYPELESS, 4, 16, 0, true, true), [0; 4]); + assert_eq!(buffer_view(with_ta, DXGI_FORMAT_R16G16B16A16_FLOAT, 4, 3, 0, false, true), [0; 4], "a typed view: 8-byte elements"); + assert_eq!(buffer_view(without, DXGI_FORMAT_UNKNOWN, 0, 8, 16, false, false), [0; 4]); + assert_eq!(cbv_view(out as u64 + 0x100, 256), crate::gpu::desc::cbv_words(0, 0)); + assert_eq!(cbv_view(inside as u64, 256), crate::gpu::desc::cbv_words(inside as u64, 256), "a CBV of unified memory"); + let _ = buffer_words_at(0x8470_0000, DXGI_FORMAT_R32_TYPELESS, 0, 16, 0, true); + let _ = buffer_words_at(out as u64 + 0x4000, DXGI_FORMAT_R32_TYPELESS, 2, 16, 0, true); + let _ = buffer_words_at(inside as u64, DXGI_FORMAT_R32_TYPELESS, 0, 16, 0, true); + let _ = buffer_words_at(0, DXGI_FORMAT_R32_TYPELESS, 5, 16, 0, true); + let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }, + }; + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R8G8B8A8_UNORM, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, ..Default::default() }; + // (no resource desc: no texture can be made at the address) + for va in [out as u64 + 0x2_0000, 0] { + dev_create_srv_at_x(dev, std::ptr::null(), view_at(&srv, va).as_ptr(), 0); + dev_create_uav_at_x(dev, std::ptr::null(), view_at(&uav, va).as_ptr(), 0); + } + let after = outside::views().by_address; + assert_eq!( + outside::take_noted_for_test(), + vec![ + Noted::Empty(EmptyView::BufferUav, Some((out + 0x10, 64)), None), + Noted::Empty(EmptyView::BufferUav, Some((out + 0x20, 24)), None), + Noted::Empty(EmptyView::BufferSrv, None, None), + Noted::Empty(EmptyView::Cbv, Some((out + 0x100, 256)), None), + Noted::ByAddress(0x8470_0000), + Noted::ByAddress(out as u64 + 0x4008), + Noted::NoTexture, + Noted::NoTexture, + ] + ); + let low = u64::from(out as u64 + 0x4008 < 1 << 32); + assert_eq!(std::array::from_fn::(|k| after[k] - before[k]), [2, 1 + low, 2], "views by address counted (no other test makes them)"); + } + } + + /// XCL's record of the views it writes names a buffer view's memory as an empty one of it is + /// counted (`view_memory`, `buffer_view`'s element sizes: raw, typed, structured); none without + /// a title address. + #[test] + fn a_buffer_view_s_recorded_memory_is_what_its_empty_view_names() { + let _g = outside::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + // (a stand-in resource: a UAV view never looks at it; an address no window holds) + let res = 0x7F0F_7000usize; + if crate::gpu::uma::get().is_some_and(|u| u.contains(0x5F_0000_0000)) { + return crate::gpu::recomp::runner::skip_config("a window over 0x5f00000000"); + } + set_test_title_address(res, Some(0x5F_0000_0000)); + let _ = outside::take_noted_for_test(); + for (format, first, n, stride, raw) in [(DXGI_FORMAT_R32_TYPELESS, 4, 16, 0, true), (DXGI_FORMAT_R16G16B16A16_FLOAT, 4, 3, 0, false), (DXGI_FORMAT_UNKNOWN, 2, 8, 24, false)] { + assert_eq!(buffer_view(res, format, first, n, stride, raw, true), [0; 4]); + let named = view_memory(res, format, first, n, stride, raw); + assert!(named.is_some()); + assert_eq!(outside::take_noted_for_test(), vec![Noted::Empty(EmptyView::BufferUav, named, None)], "{format:?}"); + } + assert_eq!(view_memory(res, DXGI_FORMAT_UNKNOWN, 2, 8, 24, false), Some((0x5F_0000_0030, 192))); + set_test_title_address(res, None); + assert_eq!(view_memory(res, DXGI_FORMAT_R32_TYPELESS, 0, 16, 0, true), None, "no title address"); + } + + /// A view of a shape XCL cannot describe is noted with whether its resource is a buffer – a + /// NULL desc of one – and whether that buffer is in unified memory; a view with a shape is not. + #[test] + fn views_of_shapes_xcl_cannot_describe_are_noted_with_their_resource() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let make = |d: &D3D12_RESOURCE_DESC| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, d, D3D12_RESOURCE_STATE_COMMON, None, &mut r).expect("a committed resource"); + r.unwrap() + }; + let sample = DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }; + let buffer = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: 65536, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: sample, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() + }; + let texture = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 4, Height: 4, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: sample, ..Default::default() + }; + let (buf, buf2, tex) = (make(&buffer), make(&buffer), make(&texture)); + // (`buf2` a console buffer in unified memory until the test ends – before the buffers go) + struct Undo(usize); + impl Drop for Undo { + fn drop(&mut self) { + set_test_console_buffer(self.0, None); + } + } + set_test_console_buffer(buf2.as_raw() as usize, Some((0x1000, 65536))); + let _undo = Undo(buf2.as_raw() as usize); + let _ = outside::take_noted_for_test(); + assert!(shape_or_count(&buf, false, DXGI_FORMAT_UNKNOWN, resource_dim_to_view(&buf.GetDesc()), 1, 1).is_none(), "a NULL desc of a buffer"); + assert!(shape_or_count(&buf2, true, DXGI_FORMAT_UNKNOWN, 1, 1, 1).is_none()); + assert!(shape_or_count(&tex, true, DXGI_FORMAT_UNKNOWN, 4, 1, 1).is_some(), "a 2D texture's view has a shape"); + assert!(shape_or_count(&tex, false, DXGI_FORMAT_UNKNOWN, 0, 1, 1).is_none(), "a dimension XCL does not know"); + assert_eq!( + outside::take_noted_for_test(), + vec![ + Noted::Empty(EmptyView::SrvShape, None, Some(false)), + Noted::Empty(EmptyView::UavShape, None, Some(true)), + Noted::Empty(EmptyView::SrvShape, None, None), + ] + ); + } + } +} + +#[cfg(test)] +mod view_census_tests { + use super::super::{console_heap, outside, view_census}; + use super::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + + unsafe extern "system" fn no_srv(_this: *mut c_void, _res: *mut c_void, _desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, _cpu: u64) {} + + unsafe extern "system" fn no_uav(_this: *mut c_void, _res: *mut c_void, _counter: *mut c_void, _desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, _cpu: u64) {} + + unsafe extern "system" fn no_copy(_this: *mut c_void, _n: u32, _dst: u64, _src: u64, _ty: u32) {} + + #[allow(clippy::too_many_arguments)] + unsafe extern "system" fn no_copies(_this: *mut c_void, _nd: u32, _dsts: *const u64, _dsizes: *const u32, _ns: u32, _srcs: *const u64, _ssizes: *const u32, _ty: u32) {} + + /// A view by address as devices #70 and #71 take it: the PC's view desc, the GPU address at 0x28. + fn view_at(desc: &T, va: u64) -> [u8; 0x40] { + let mut b = [0u8; 0x40]; + let n = std::mem::size_of::().min(0x28); + unsafe { std::ptr::copy_nonoverlapping(desc as *const T as *const u8, b.as_mut_ptr(), n) }; + b[0x28..0x30].copy_from_slice(&va.to_le_bytes()); + b + } + + /// Views made through the device's hooks name their texture in the view census's map: an SRV + /// and a UAV of views-by-address textures (MADE's) counted named; a CopyDescriptorsSimple of a + /// slot (the PC's copy, the shared heap's and the slot's words) names it in the copy; a slot + /// overwritten with another texture, a null view or a buffer's: the old texture named no more; + /// a 2D UAV of a texture that cannot have one: the null view, and the SRV beside it; views and + /// copies into a heap that is not a console heap: counted; the heap unregistered: its slots name + /// nothing in the title's heaps, the shared heap's only in a released range (M3, M13-M16). A + /// device whose PC view and copy calls do nothing; the shared heap's real copies from a CPU-only + /// heap of null SRVs; this thread's map (`names_for_test`). + #[test] + fn views_made_through_the_device_name_their_texture_in_the_map() { + let _one = console_heap::SHARED_RANGES.lock().unwrap_or_else(|e| e.into_inner()); + // (views by address and empty views: `outside`'s exact counts are its own tests') + let _views = outside::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if crate::gpu::uma::get().is_none() { + return; + } + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + if !console_heap::shared_heap(dev.as_ref().expect("D3D12 device")) { + return crate::gpu::recomp::runner::skip_config("no shared shader-visible heap"); + } + let dev = console_heap::shared_device_for_test().expect("the shared heap's device"); + let sample = DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }; + let texture = |flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: sample, + Flags: flags, + ..Default::default() + }; + let buffer = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 65536, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: sample, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let make = |d: &D3D12_RESOURCE_DESC| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, d, D3D12_RESOURCE_STATE_COMMON, None, &mut r).expect("a committed resource"); + r.unwrap() + }; + // V and U: views-by-address textures (U can have a UAV); W: one that cannot; a buffer + let (tv, tu, tw, tb) = (make(&texture(D3D12_RESOURCE_FLAG_NONE)), make(&texture(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)), make(&texture(D3D12_RESOURCE_FLAG_NONE)), make(&buffer)); + let (v, u, w, b) = (tv.as_raw() as usize, tu.as_raw() as usize, tw.as_raw() as usize, tb.as_raw() as usize); + // the title's PC heap: CPU-only, 2 descriptors a slot, null SRVs in all (what the shared + // heap's copies read) + let pc: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 16, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0 }).expect("a CPU-only heap"); + let cpu = pc.GetCPUDescriptorHandleForHeapStart().ptr as u64; + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + let null = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Buffer: D3D12_BUFFER_SRV { FirstElement: 0, NumElements: 0, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW } }, + }; + for k in 0..16u64 { + dev.CreateShaderResourceView(None, Some(&null), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + k * inc as u64) as usize }); + } + let obj = 0x7A1E_2900usize; + assert!(console_heap::register(obj, 8, cpu, 0, inc, false, true, false)); + let start = console_heap::start(obj).unwrap(); + let at = |k: u64| start + k * console_heap::SLOT as u64; + let s: Vec = (0..4).map(|k| console_heap::slot(at(k)).unwrap()).collect(); + if s.iter().any(|x| x.shared_srv == 0) { + console_heap::unregister(obj); + return crate::gpu::recomp::runner::skip_config("the heap's slots have no place in the shared heap"); + } + let first = s[0].index; + let (m, window) = view_census::names_for_test(first, 16); + // a device whose PC views and copies do nothing (the console heap's slots are what count) + let mut orig = vec![0usize; 32]; + orig[18] = no_srv as usize; + orig[19] = no_uav as usize; + orig[23] = no_copies as usize; + orig[24] = no_copy as usize; + let (_table, vt) = test_ext_table(&orig); + let mut object = vt as usize; + let fake = &mut object as *mut usize as *mut c_void; + let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: 0, ResourceMinLODClamp: 0.0 } }, + }; + let uav_array = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: 0, FirstArraySlice: 0, ArraySize: 1, PlaneSlice: 0 } }, + }; + let uav_2d = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R8G8B8A8_UNORM, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, ..Default::default() }; + let buffer_uav = 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: 16, StructureByteStride: 0, CounterOffsetInBytes: 0, Flags: D3D12_BUFFER_UAV_FLAG_RAW } }, + }; + // MADE's textures for two views by address (an address and a resource desc each) + let rdesc = { + let mut x = [0u8; 0x38]; + x[0] = 3; + x[0x10] = 4; + x + }; + let (va_v, va_u) = (0x7A1E_2000_0000u64, 0x7A1E_2001_0000u64); + let made = |res: usize| ViewTexture { res, made: Some(super::super::device_x::MadeAs { how: super::super::device_x::Made::Committed, pc: 0x1_0000, kept: false }) }; + set_made_for_test(va_v, &rdesc, Some(made(v))); + set_made_for_test(va_u, &rdesc, Some(made(u))); + let views = [made(v), made(u), made(w)]; + let unnamed = |free: &[(u32, u32)]| view_census::unnamed_for_test(m, first + 16, free, &views); + let sorted = |mut x: Vec| { + x.sort_unstable(); + x + }; + + // an SRV by address in slot 0, a UAV (2D array) by address in slot 1 + let (view_v, view_u) = (view_at(&srv, va_v), view_at(&uav_array, va_u)); + dev_create_srv_at_x(fake, rdesc.as_ptr(), view_v.as_ptr(), at(0)); + dev_create_uav_at_x(fake, rdesc.as_ptr(), view_u.as_ptr(), at(1)); + assert_eq!(m.at(s[0].index), (v, v), "the SRV by address names MADE's texture in both heaps"); + assert_eq!((m.at(s[1].index), m.at(s[1].index + 1)), ((0, 0), (u, u)), "the UAV at the place after the slot's SRV"); + assert_eq!(unnamed(&[]), (sorted(vec![w]), 0), "both views by address named: only W (not viewed yet) unnamed"); + + // slot 1 copied to slot 3 (CopyDescriptorsSimple: the PC's copy, the shared heap's, the words) + dev_copy_descriptors_simple_x(fake, 1, at(3), at(1), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32); + assert_eq!((m.at(s[3].index), m.at(s[3].index + 1)), ((0, 0), (u, u)), "the copy names U"); + let words = std::ptr::read(s[3].at as *const [u32; 8]); + assert_eq!(words[0], s[3].index, "the slot's T# copied, renumbered for the copy"); + + // slot 0 overwritten with W, slot 1's UAV with a null view, slot 3's with a buffer's + dev_create_srv_x(fake, w as *mut c_void, &srv, at(0)); + dev_create_uav_x(fake, std::ptr::null_mut(), std::ptr::null_mut(), &uav_array, at(1)); + dev_create_uav_x(fake, b as *mut c_void, std::ptr::null_mut(), &buffer_uav, at(3)); + assert_eq!((m.at(s[0].index), m.at(s[1].index + 1), m.at(s[3].index + 1)), ((w, w), (0, 0), (b, b))); + assert_eq!(unnamed(&[]), (sorted(vec![v, u]), 0), "V and U named no more, W named"); + + // a 2D UAV of W (no UAV flag): a null UAV, and the SRV beside it names W; slot 0's SRV null + dev_create_uav_x(fake, w as *mut c_void, std::ptr::null_mut(), &uav_2d, at(2)); + assert_eq!((m.at(s[2].index), m.at(s[2].index + 1)), ((w, w), (0, 0))); + dev_create_srv_x(fake, std::ptr::null_mut(), std::ptr::null(), at(0)); + assert_eq!(m.at(s[0].index), (0, 0), "a null SRV"); + + // views and a copy into a heap that is not a console heap: counted, not mapped + dev_create_srv_x(fake, v as *mut c_void, &srv, cpu); + dev_create_uav_x(fake, u as *mut c_void, std::ptr::null_mut(), &uav_array, cpu + inc as u64); + dev_copy_descriptors_simple_x(fake, 2, cpu + 2 * inc as u64, cpu, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32); + // CopyDescriptors (#23) there: a range of 2, then 3 ranges of one each (no sizes) + let (dsts, srcs, two) = ([cpu + 4 * inc as u64], [cpu], [2u32]); + dev_copy_descriptors_x(fake, 1, dsts.as_ptr(), two.as_ptr(), 1, srcs.as_ptr(), two.as_ptr(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32); + let (dsts, srcs) = ([cpu + 6 * inc as u64, cpu + 7 * inc as u64, cpu + 8 * inc as u64], [cpu; 3]); + dev_copy_descriptors_x(fake, 3, dsts.as_ptr(), std::ptr::null(), 3, srcs.as_ptr(), std::ptr::null(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32); + assert_eq!(m.counts(), (0, 9), "2 views and copies of 2, 2 and 3 outside the console heaps"); + assert_eq!(unnamed(&[]), (sorted(vec![v, u]), 0)); + + // the heap unregistered: its title heap's descriptors go, the shared heap's stay in a + // released range + console_heap::unregister(obj); + assert!((first..first + 16).all(|i| m.at(i).0 == 0), "the heap's slots name nothing in the title's heaps"); + assert_eq!(m.at(s[2].index).1, w); + assert_eq!(unnamed(&[(first, 16)]), (sorted(vec![v, u]), 1), "W only in a released range"); + drop(window); + set_made_for_test(va_v, &rdesc, None); + set_made_for_test(va_u, &rdesc, None); + } + } + + /// A view by address finds the texture MADE holds for its (address, desc) – its resource, as + /// before MADE kept how each was made –, the desc's bytes past its flags left out; no texture + /// for no desc or address 0. + #[test] + fn a_view_by_address_finds_made_s_texture() { + let mut x = [0u8; 0x38]; + x[0] = 3; + x[0x10] = 8; + let va = 0x7A1E_2002_0000u64; + set_made_for_test(va, &x, Some(ViewTexture { res: 0x7A1E_2E01, made: None })); + let mut padded = x; + padded[0x34..].fill(0xAB); + // (an entry under the bytes as given: a key that kept them finds it instead of making a + // texture on no device) + set_made_for_test(va, &padded, Some(ViewTexture { res: 0x7A1E_2E02, made: None })); + unsafe { + let fake = std::ptr::null_mut(); + assert_eq!(resource_at(fake, x.as_ptr(), va) as usize, 0x7A1E_2E01); + assert_eq!(resource_at(fake, padded.as_ptr(), va) as usize, 0x7A1E_2E01, "the bytes past the flags are not the key's"); + assert!(resource_at(fake, std::ptr::null(), va).is_null()); + assert!(resource_at(fake, x.as_ptr(), 0).is_null()); + } + set_made_for_test(va, &padded, None); + set_made_for_test(va, &x, None); + let mut all = Vec::new(); + view_textures(&mut all); + assert!(!all.iter().any(|t| t.res == 0x7A1E_2E01), "taken out"); + } + + /// E14 (A8's counting rule): `resource_at`'s insert into MADE says it replaced an entry only when + /// that one held a texture (another thread's of the same view) – not for a new key, nor over a + /// creation that failed (res 0); the record it is given is what MADE keeps. On a map of its own. + #[test] + fn made_s_insert_counts_only_a_texture_it_replaced() { + use super::super::device_x::{Made, MadeAs}; + let mut m = HashMap::new(); + let mut desc = [0u8; 0x38]; + desc[0] = 3; + let (k1, k2) = ((0x7A1E_E101_0000u64, desc), (0x7A1E_E102_0000u64, desc)); + let made = Some(MadeAs { how: Made::Committed, pc: 0x1_0000, kept: true }); + assert!(!insert_made(&mut m, k1, ViewTexture { res: 0, made: None }), "a new key"); + assert!(!insert_made(&mut m, k1, ViewTexture { res: 0x7A1E_E1A1, made }), "over a failed creation: nothing replaced"); + assert_eq!(m.get(&k1), Some(&ViewTexture { res: 0x7A1E_E1A1, made }), "the creation's record kept"); + assert!(insert_made(&mut m, k1, ViewTexture { res: 0x7A1E_E1A2, made: None }), "over a texture: replaced"); + assert!(!insert_made(&mut m, k2, ViewTexture { res: 0x7A1E_E1A3, made }), "another key"); + assert_eq!(m.len(), 2); + } +} diff --git a/crates/xcl/src/hle/d3d12x/skip_roots.rs b/crates/xcl/src/hle/d3d12x/skip_roots.rs new file mode 100644 index 0000000..4292807 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/skip_roots.rs @@ -0,0 +1,1246 @@ +//! The root views of the console programs `XCL_SKIP_CS` skips: where the memory they name lives +//! (diagnostics – nothing here changes what the GPU is given). +//! +//! Run 65 keeps the VFX heap defrag trio skipped (`bind::skip_cs`): in runs 61-62 they hung the +//! GPU. On a Mac the title's GPU heaps are plain memory, not unified memory: views of buffers there +//! get an empty V#, translated stores there are dropped, and an ExecuteIndirect reads its arguments +//! from a PC buffer nobody fills. A later patch places the title's GPU-used allocations at addresses +//! in unified memory's windows, and must know where these programs' views live. +//! +//! So at a listed program's first 2 skips – 16 in the process – its root arguments are logged as +//! `bind::trace_fullscreen` reads them: the constants, each root descriptor and the first 8 slots +//! of each descriptor table (`TABLE_SLOTS`: XCL keeps no record of the slots a translated program +//! reads). Each view: its descriptor decoded (`desc::buffer`, `desc::image`), where its memory is +//! (`Where`: a window of unified memory, a buffer the title placed with a PC resource of its own, +//! GPU-visible title memory kernelx knows, other memory as VirtualQuery sees it, no title address), +//! who wrote it (`console_heap::peek`: a view XCL made in that slot – an empty V# with the memory it +//! would have named –, or the title's own bytes: its own descriptors, its copies of slots) and, for +//! memory outside unified memory, the first 16 bytes the CPU sees there (`cpu_bytes`: a copy by +//! ReadProcessMemory – title memory is never read here). Every line starts +//! `D3D12.X: XCL_SKIP_CS: ` – run65_events.sh shows each line holding `XCL_SKIP_CS` – and +//! stays under 480 bytes (`LINE_MAX`). +//! +//! On whenever `XCL_SKIP_CS` lists programs; `XCL_SKIP_CS_ROOTS=0`: off, and so is XCL's record +//! of the views it writes (`console_heap::write_view`), kept only for these lines – until the last +//! of them is logged (`recording`). A listed program whose stand-in is not built yet is logged at +//! its skips as unbuilt too (`Pipeline::Unbuilt`: B-1 skips its work before `skip_cs` sees it). +//! `skip_cs` runs inside the title's command list calls: nothing here panics on what it reads, +//! holds a lock across a D3D12 or Wine call, or costs more than a look past a program's first skips. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, OnceLock}; + +use super::console_heap::Writer; +use super::console_list::{Layout, Param}; +use crate::hle::kernelx::PlainGpu; + +/// bytes a line holds at most: run65_events.sh prints 500 bytes of each log line, 26 of which are +/// the log's own prefix (`[time][thread][LEVEL] `) +const LINE_MAX: usize = 470; +/// skips logged of one program, and of all of them in the process +const PER_PROGRAM: u32 = 2; +const IN_ALL: u32 = 16; +/// the slots of a descriptor table looked at, a slot's bytes +const TABLE_SLOTS: usize = 8; +const SLOT: usize = 32; +/// constants shown of a root parameter +const CONSTANTS_SHOWN: usize = 16; +/// lines of one skip at most +const LINES_MAX: usize = 48; +/// VirtualQuery calls of one skip and of the process (it sizes a region by walking it: 20-25 ms +/// in a title's 2 GB block – `shader::readable`) +const QUERIES_PER_SKIP: u32 = 2; +const QUERIES_IN_ALL: u32 = 16; + +/// `XCL_SKIP_CS_ROOTS` (read once): not `0` – the root views are logged. +fn switch() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SKIP_CS_ROOTS").map_or(true, |v| v.trim() != "0")) +} + +/// The skips logged (None: off – `XCL_SKIP_CS` lists nothing, or `XCL_SKIP_CS_ROOTS=0`). +static BUDGET: OnceLock> = OnceLock::new(); + +fn budget() -> Option<&'static Budget> { + BUDGET + .get_or_init(|| { + let list = super::stall::skip_list(); + (!list.is_empty() && switch()).then(|| Budget::new(list, PER_PROGRAM, IN_ALL)) + }) + .as_ref() +} + +/// Whether the root views of skipped programs are logged – read before the title runs +/// (`host_main`): from then on XCL records the views it writes (`recording`) without reading the +/// environment inside the title's calls. +pub(crate) fn on() -> bool { + budget().is_some() +} + +/// Whether XCL records the views it writes into console slots now (`console_heap::write_view`): +/// while root views are still to be logged – once `on` was asked (never by a look here), until the +/// skips' budget is spent (`Budget::spent`). Past it nothing reads the record: XCL's views cost +/// one look, not a lock and a map insert each, for the rest of the run. +pub(super) fn recording() -> bool { + #[cfg(test)] + if let Some(r) = TEST_BUDGET.with(|b| b.borrow().as_ref().map(|b| switch() && !b.spent())) { + return r; + } + BUDGET.get().and_then(Option::as_ref).is_some_and(|b| !b.spent()) +} + +/// Whether XCL kept a record of the views it wrote (`console_heap::peek`'s writers): once `on` was +/// asked – also once the budget is spent, which its last skip's lines read the record after. +pub(super) fn recorded() -> bool { + #[cfg(test)] + if TEST_BUDGET.with(|b| b.borrow().is_some()) { + return switch(); + } + BUDGET.get().is_some_and(Option::is_some) +} + +/// Which skips are logged: each listed program's first `per`, and `in_all` in the process. +pub(super) struct Budget { + programs: Vec<(u64, AtomicU32)>, + logged: AtomicU32, + per: u32, + in_all: u32, +} + +impl Budget { + pub(super) fn new(hashes: &[u64], per: u32, in_all: u32) -> Budget { + Budget { programs: hashes.iter().map(|&h| (h, AtomicU32::new(0))).collect(), logged: AtomicU32::new(0), per, in_all } + } + + /// A skip of `hash` is logged: (its number for the program, its number in the process). None: + /// not a listed program, or past either bound – past the program's, after one atomic look. + pub(super) fn admit(&self, hash: u64) -> Option<(u32, u32)> { + let (_, seen) = self.programs.iter().find(|(h, _)| *h == hash)?; + if seen.load(Ordering::Relaxed) >= self.per { + return None; + } + let n = seen.fetch_add(1, Ordering::Relaxed).saturating_add(1); + if n > self.per { + return None; + } + let m = self.logged.fetch_add(1, Ordering::Relaxed).saturating_add(1); + (m <= self.in_all).then_some((n, m)) + } + + /// No skip is logged any more: `in_all` were, or every listed program had its `per` (a list of + /// none – a test's – never runs out that way). + pub(super) fn spent(&self) -> bool { + self.logged.load(Ordering::Relaxed) >= self.in_all || (!self.programs.is_empty() && self.programs.iter().all(|(_, s)| s.load(Ordering::Relaxed) >= self.per)) + } +} + +fn admit(hash: u64) -> Option<(u32, u32)> { + #[cfg(test)] + if let Some(r) = TEST_BUDGET.with(|b| b.borrow().as_ref().map(|b| b.admit(hash))) { + return r; + } + budget()?.admit(hash) +} + +/// The call a skipped dispatch came with. +#[derive(Clone, Copy, Debug)] +pub(super) enum Call { + /// Dispatch – DispatchX with its flags + Dispatch { groups: [u32; 3], flags: Option }, + /// ExecuteIndirect: its signature, max count, the title's arguments and count buffer + /// (resource, the title's offset; resource 0: none) + Indirect { sig: usize, max: u32, args: (usize, u64), count: (usize, u64) }, +} + +/// The pipeline of a skipped dispatch: the translated one of a program XCL_SKIP_CS skips (`threads` +/// in a group), or a stand-in not built yet (`bind::unbuilt`: why, as `bind` logs it) – its work is +/// skipped as unbuilt, and B-1 drops it before XCL_SKIP_CS ever sees it. +#[derive(Clone, Copy, Debug)] +pub(super) enum Pipeline<'a> { + Built { threads: u32 }, + Unbuilt(&'a str), +} + +/// A dispatch of `hash` was not recorded on `list` (`bind::skip_cs`; one of a stand-in not built, +/// `bind::dispatch_call` and `execute_indirect` – `pipeline`): at the program's first skips its root +/// views are logged – `roots` (the list's compute root signature and arguments) asked only then. +/// The resources of an ExecuteIndirect are the title's, alive for the call this comes from. +pub(super) unsafe fn note_skip(list: *mut c_void, hash: u64, pipeline: Pipeline, call: Call, roots: impl FnOnce() -> (Option>, Vec)) { + if !switch() { + return; + } + let Some((n, m)) = admit(hash) else { return }; + let (layout, args) = roots(); + for line in skip_lines(list as usize, hash, pipeline, (n, m), &call, layout.as_deref(), &args) { + emit(&line); + } +} + +fn emit(line: &str) { + crate::xlog_info!("{line}"); + #[cfg(test)] + LINES.with(|l| l.borrow_mut().push(line.to_string())); +} + +/// The lines of one skip (`(n, m)`: its number for the program and in the process): the head, +/// then each root parameter's – `LINES_MAX` at most. +unsafe fn skip_lines(list: usize, hash: u64, pipeline: Pipeline, (n, m): (u32, u32), call: &Call, layout: Option<&Layout>, args: &[u8]) -> Vec { + let prefix = format!("D3D12.X: XCL_SKIP_CS: {hash:016x}"); + let head = match pipeline { + Pipeline::Built { threads } => format!("root views at its skip #{n} (#{m} logged in the process): {} on list {list:#x}, {threads} threads", call_text(call)), + Pipeline::Unbuilt(why) => { + format!("root views at its skip #{n} (#{m} logged in the process): {} on list {list:#x}, its pipeline not built yet – its work skipped as unbuilt ({why})", call_text(call)) + } + }; + let params = layout.map_or_else(|| "no compute root signature bound".to_string(), params_text); + let mut out = pack(&prefix, &[head, params]); + let mut queries = QUERIES_PER_SKIP; + for (i, p) in layout.map_or(&[][..], |l| &l.params[..]).iter().enumerate() { + if out.len() >= LINES_MAX { + break; + } + match *p { + Param::Constants { at, count } => { + let words: Vec = (0..count as usize).take(CONSTANTS_SHOWN).map_while(|k| word(args, (at as usize).checked_add(4 * k)?)).collect(); + out.push(constants_line(&prefix, i, count, &words)); + } + Param::Descriptor { at } => { + let va = qword(args, at as usize).unwrap_or(0); + let w = where_is(va, &mut queries); + let mut parts = vec![format!("p{i}: root descriptor {va:#x}: {}", w.text()), "the title's (its root argument)".to_string()]; + parts.extend(outside_parts(va, &w)); + out.extend(pack(&prefix, &parts)); + } + Param::Table { at } => out.extend(table_lines(&prefix, i, word(args, at as usize).unwrap_or(0), &mut queries)), + } + } + if out.len() > LINES_MAX { + let more = out.len() - (LINES_MAX - 1); + out.truncate(LINES_MAX - 1); + out.push(format!("{prefix} … {more} more line(s) not logged")); + } + out +} + +/// The call: "Dispatch 3×2×1", "DispatchX 3×2×1 (flags 0x20)", "ExecuteIndirect of up to …" with +/// where its arguments and count are (`indirect::classify`, `outside::args_at`). +unsafe fn call_text(c: &Call) -> String { + match *c { + Call::Dispatch { groups, flags } => dispatch_text(groups, flags), + Call::Indirect { sig, max, args, count } => { + let place = super::indirect::classify(args.0, args.1).short(); + let at = super::outside::args_at(args.0, args.1, count); + let count_place = (count.0 != 0).then(|| super::indirect::classify(count.0, count.1).short()); + indirect_text(max, sig, super::indirect::lookup(sig).is_some(), &place, &at, count_place.as_deref()) + } + } +} + +fn dispatch_text(g: [u32; 3], flags: Option) -> String { + match flags { + Some(f) => format!("DispatchX {}×{}×{} (flags {f:#x})", g[0], g[1], g[2]), + None => format!("Dispatch {}×{}×{}", g[0], g[1], g[2]), + } +} + +/// `at`: `outside::args_at`'s text (", at 0x… (…)…"); `count`: where its count's buffer is. +fn indirect_text(max: u32, sig: usize, root_changing: bool, place: &str, at: &str, count: Option<&str>) -> String { + format!( + "ExecuteIndirect of up to {max} command(s) with signature {sig:#x}{}: arguments {place}{at}{}", + if root_changing { " (its commands change root arguments: the list's are below)" } else { "" }, + count.map_or_else(String::new, |c| format!(", its count's buffer {c}")) + ) +} + +fn params_text(l: &Layout) -> String { + let (mut c, mut d, mut t) = (0, 0, 0); + for p in &l.params { + match p { + Param::Constants { .. } => c += 1, + Param::Descriptor { .. } => d += 1, + Param::Table { .. } => t += 1, + } + } + format!("{} root parameters ({c} constants, {d} root descriptors, {t} tables)", l.params.len()) +} + +fn constants_line(prefix: &str, i: usize, count: u32, words: &[u32]) -> String { + let shown: Vec = words.iter().map(|w| format!("{w:#x}")).collect(); + let more = if (count as usize) > words.len() { ", …" } else { "" }; + fit(format!("{prefix} p{i}: {count} constants [{}{more}]", shown.join(", "))) +} + +fn word(args: &[u8], at: usize) -> Option { + let b = args.get(at..at.checked_add(4)?)?; + Some(u32::from_le_bytes(b.try_into().ok()?)) +} + +fn qword(args: &[u8], at: usize) -> Option { + Some(u64::from(word(args, at)?) | u64::from(word(args, at.checked_add(4)?)?) << 32) +} + +/// A descriptor table's lines: a head (the heap its slots are in; those that are empty with no +/// view of XCL's – zeros the title wrote, or never wrote –, and those that cannot be read), then +/// one view a line (two when long). +unsafe fn table_lines(prefix: &str, i: usize, t: u32, queries: &mut u32) -> Vec { + let Some(u) = crate::gpu::uma::get() else { return vec![fit(format!("{prefix} p{i}: table {t:#x}: no unified memory"))] }; + let Some(base) = u.base().checked_add(t as usize).filter(|_| t != 0) else { return vec![fit(format!("{prefix} p{i}: table {t:#x}: not set"))] }; + let mut heap: Option = None; + let (mut empty, mut unreadable): (Vec, Vec) = (Vec::new(), Vec::new()); + // (empty slots whose writer is not known – XCL's record is full, say: XCL's view, the title's + // zeros or its copy, by the record alone – and why) + let mut unknown: Vec = Vec::new(); + let mut unknown_why: Option<&'static str> = None; + let mut views: Vec = Vec::new(); + for k in 0..TABLE_SLOTS { + let Some(at) = base.checked_add(SLOT * k) else { break }; + let (words, writer) = match super::console_heap::peek(at) { + Some(p) if p.sampler => { + heap = Some(format!("sampler slots of heap {:#x} from #{}", p.heap, p.k)); + break; + } + Some(p) => { + if heap.is_none() { + let mem = if p.title_memory { "the title's memory" } else { "XCL's memory" }; + heap = Some(format!("slots of heap {:#x} from #{} ({mem}, {})", p.heap, p.k, if p.visible { "shader visible" } else { "CPU only" })); + } + (p.words, Some(p.writer)) + } + None => match read_words(at) { + Some(w) => (w, None), + None => { + unreadable.push(k); + continue; + } + }, + }; + let view = view_of(&words); + if view == View::Empty { + match writer { + Some(Writer::Xcl(..) | Writer::Over(..)) => {} + Some(Writer::Unknown(why)) => { + unknown.push(k); + unknown_why.get_or_insert(why); + continue; + } + Some(Writer::Title) | None => { + empty.push(k); + continue; + } + } + } + views.extend(slot_lines(prefix, i, k, view, writer, queries)); + } + let mut head = format!("{prefix} p{i}: table {t:#x}: {}", heap.unwrap_or_else(|| "not in a heap of XCL's".to_string())); + if !empty.is_empty() { + head.push_str(&format!("; empty, no view of XCL's made there (zeros of the title's, or its copy of an empty V#): {empty:?}")); + } + if let Some(why) = unknown_why { + head.push_str(&format!("; empty, writer unknown ({why}): {unknown:?}")); + } + if !unreadable.is_empty() { + head.push_str(&format!("; unreadable, in no heap of XCL's: {unreadable:?}")); + } + let mut out = vec![fit(head)]; + out.extend(views); + out +} + +/// A view's line(s): what it is, where its memory is, who wrote it (None: not a slot of XCL's +/// heaps), what the CPU sees there when that is outside unified memory. +unsafe fn slot_lines(prefix: &str, i: usize, k: usize, view: View, writer: Option, queries: &mut u32) -> Vec { + // (a view of XCL's whose descriptor names no memory itself – an empty V#, a PC view's index, + // XCL's CBV of memory outside unified memory, `desc::cbv_words(0, 0)` –: the memory XCL's + // record says it named) + let named = match writer { + Some(Writer::Xcl(_, at)) if view.address().is_none() => at, + _ => None, + }; + let mut first = format!("p{i}[{k}]: {}", view.text()); + match (view, named, writer) { + // (an empty V#'s 4 zero words are every empty V#'s: the title's copy of another over XCL's + // reads the same – the memory is not certain) + (View::Empty, Some((va, bytes)), Some(Writer::Xcl(what, _))) => first.push_str(&format!(" (XCL's {what} named {va:#x}, {bytes} bytes, or a copy of an empty V# over it: the same bytes)")), + (View::Image { .. }, Some((va, _)), _) => first.push_str(&format!(" (XCL's view of the texture at {va:#x})")), + (_, Some((va, bytes)), _) => first.push_str(&format!(" (XCL's view names {va:#x}, {bytes} bytes)")), + _ => {} + } + let who = match (view, writer) { + (View::Empty, Some(Writer::Xcl(what, _))) => format!("XCL's {what} or a copy of an empty V# over it (the same bytes)"), + (_, Some(w)) => writer_text(&w), + (_, None) => "the title's bytes (not a slot of XCL's heaps)".to_string(), + }; + let mut parts = vec![first]; + match view.address().or(named.map(|n| n.0 as u64)) { + Some(a) => { + let w = where_is(a, queries); + parts.push(w.text()); + parts.push(who); + parts.extend(outside_parts(a, &w)); + } + None => { + // (a PC view's index: translated programs read that view – a live texture, whatever + // title memory it is of) + parts.push(if matches!(view, View::Image { index: true, .. }) { + "a PC view's index (its memory is the PC view's; no title address known)".to_string() + } else { + "no memory (an empty descriptor: reads give 0, writes go nowhere)".to_string() + }); + parts.push(who); + } + } + pack(prefix, &parts) +} + +fn writer_text(w: &Writer) -> String { + match *w { + Writer::Xcl(what, _) => format!("XCL's {what}"), + Writer::Over(what) => format!("the title's bytes (over XCL's {what})"), + Writer::Title => "the title's bytes (no view of XCL's made in this slot: its own descriptor or a copy)".to_string(), + Writer::Unknown(why) => format!("writer unknown ({why})"), + } +} + +/// A slot's 32 bytes outside XCL's heaps, copied (`cpu_bytes`). +fn read_words(at: usize) -> Option<[u32; 8]> { + let mut b = [0u8; SLOT]; + if !copy_out(at, &mut b) { + return None; + } + let mut w = [0u32; 8]; + for (k, c) in b.chunks_exact(4).enumerate() { + if let (Some(x), Ok(v)) = (w.get_mut(k), <[u8; 4]>::try_from(c)) { + *x = u32::from_le_bytes(v); + } + } + Some(w) +} + +/// A descriptor as a slot holds it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum View { + /// a buffer V# whose first 4 words are zero: XCL's for memory outside unified memory, a null view + Empty, + /// a buffer V#: its base, its bytes (records × stride; a raw one's records are bytes) + Buffer { base: u64, bytes: u64, stride: u32, records: u32, format: u32 }, + /// a T#; `index`: word 0 is small enough to be the index of a PC view (XCL's T#s name their view + /// so – `desc::xcl_image_words` –, not an address) + Image { ty: crate::gpu::desc::ImageType, w: u32, h: u32, d: u32, format: u32, address: u64, word0: u32, index: bool }, + /// an RDNA2 BVH descriptor (`desc::bvh_words`) + Bvh { address: u64 }, +} + +/// descriptors of the shared heap at most (`console_heap::GLOBAL_MAX`): a T#'s word 0 below it is +/// taken for the index of a PC view +const PC_VIEWS: u32 = 1 << 21; + +pub(super) fn view_of(w: &[u32; 8]) -> View { + if w[3] >> 28 >= 8 { + if let Some(t) = crate::gpu::desc::image(w) { + return View::Image { ty: t.ty, w: t.width, h: t.height, d: t.depth, format: t.format, address: t.address, word0: w[0], index: w[0] < PC_VIEWS }; + } + } + if w[..4] == [0; 4] { + return View::Empty; + } + if w[3] == 0 && w[2] == u32::MAX { + return View::Bvh { address: (u64::from(w[0]) | u64::from(w[1] & 0xFF) << 32) << 8 }; + } + let b = crate::gpu::desc::buffer(&[w[0], w[1], w[2], w[3]]); + let bytes = if b.stride == 0 { u64::from(b.num_records) } else { u64::from(b.num_records) * u64::from(b.stride) }; + View::Buffer { base: b.address, bytes, stride: b.stride, records: b.num_records, format: b.format } +} + +impl View { + fn text(&self) -> String { + match *self { + View::Empty => "empty V#".to_string(), + View::Buffer { base, bytes, stride, records, format } => format!("V# {base:#x}, {bytes} bytes (stride {stride}, {records} records, format {format})"), + View::Image { ty, w, h, d, format, address, word0, index } => { + if index { + format!("T# {ty:?} {w}×{h}×{d}, format {format} (word 0 {word0:#x}: a PC view's index, no address)") + } else { + format!("T# {ty:?} {w}×{h}×{d}, format {format} at {address:#x}") + } + } + View::Bvh { address } => format!("BVH descriptor {address:#x}"), + } + } + + /// The memory the descriptor itself names (None: none – empty, a PC view's index, or a buffer of + /// no bytes at 0: XCL's CBV of memory outside unified memory, `desc::cbv_words(0, 0)`). + fn address(&self) -> Option { + match *self { + View::Buffer { base: 0, records: 0, .. } => None, + View::Buffer { base, .. } => Some(base), + View::Image { address, index: false, .. } | View::Bvh { address } => Some(address), + _ => None, + } + } +} + +/// Where title memory at an address is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Where { + /// address 0 + Nowhere, + /// unified memory, window `k`; `block`: a block is handed out there (`uma::is_title_address`; + /// else the address lies in the window's range by number only – a PC GPU address?) + Window { k: usize, block: bool }, + /// outside unified memory: in a buffer the title placed there that got a PC resource of its own + /// (`outside`'s census: the resource, its address, bytes, unordered access), and the GPU-visible + /// title memory it lies in + Placed { res: usize, at: usize, bytes: u64, uav: bool, plain: Option }, + /// outside unified memory: GPU-visible title memory kernelx knows + Plain(PlainGpu), + /// outside unified memory, in no allocation XCL knows – what VirtualQuery says (None: not + /// asked, its budget spent, or no answer) + Other(Option), +} + +/// VirtualQuery's answer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Region { + alloc: usize, + alloc_protect: u32, + base: usize, + size: usize, + state: u32, + protect: u32, + ty: u32, +} + +/// Where `va` is: unified memory's windows, then the census of placed buffers and kernelx's +/// record of GPU-visible title memory (each a leaf lock, taken one after the other), then +/// VirtualQuery (`queries` left of this skip's budget; no lock held). +pub(super) fn where_is(va: u64, queries: &mut u32) -> Where { + if va == 0 { + return Where::Nowhere; + } + let Ok(p) = usize::try_from(va) else { return Where::Other(None) }; + if let Some(u) = crate::gpu::uma::get() { + if let Some(k) = u.window_of(p) { + return Where::Window { k, block: u.is_title_address(p) }; + } + } + let plain = crate::hle::kernelx::plain_gpu_info(p); + if let Some((res, at, bytes, uav)) = super::outside::placed_at(p) { + return Where::Placed { res, at, bytes, uav, plain }; + } + match plain { + Some(pl) => Where::Plain(pl), + None => Where::Other(query(p, queries)), + } +} + +fn query(p: usize, left: &mut u32) -> Option { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION}; + static IN_ALL: AtomicU32 = AtomicU32::new(0); + if *left == 0 || IN_ALL.fetch_add(1, Ordering::Relaxed) >= QUERIES_IN_ALL { + return None; + } + *left -= 1; + // SAFETY: a plain struct of integers and pointers, all-zero valid; VirtualQuery reads no memory + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let n = unsafe { VirtualQuery(p as *const c_void, &mut m, std::mem::size_of::()) }; + (n != 0).then(|| Region { + alloc: m.AllocationBase as usize, + alloc_protect: m.AllocationProtect, + base: m.BaseAddress as usize, + size: m.RegionSize, + state: m.State, + protect: m.Protect, + ty: m.Type, + }) +} + +impl Where { + pub(super) fn text(&self) -> String { + match *self { + Where::Nowhere => "no title address".to_string(), + Where::Window { k, block: true } => format!("unified memory, window {k}"), + Where::Window { k, block: false } => format!("unified memory, window {k} by number only (no block handed out there: a PC GPU address?)"), + Where::Placed { res, at, bytes, uav, plain } => format!( + "outside unified memory: in a buffer the title placed at {at:#x} ({bytes} bytes{}) with a PC resource of its own ({res:#x}){}", + if uav { ", unordered access" } else { "" }, + plain.map_or_else(String::new, |p| format!(", in {}", plain_text(&p))) + ), + Where::Plain(p) => format!("outside unified memory: in {}", plain_text(&p)), + Where::Other(None) => "outside unified memory, in no allocation XCL knows".to_string(), + Where::Other(Some(r)) => format!("outside unified memory, in no allocation XCL knows: {}", region_text(&r)), + } + } + + /// Outside unified memory: what the CPU sees there is not what translated programs see. + pub(super) fn outside(&self) -> bool { + matches!(self, Where::Placed { .. } | Where::Plain(_) | Where::Other(_)) + } +} + +fn plain_text(p: &PlainGpu) -> String { + format!("GPU-visible title memory at {:#x} of {} ({}, flags {:#x}, protection {:#x})", p.base, size_text(p.bytes), p.by, p.flags, p.protect) +} + +/// "2048 MB", "64 KB" (under 1 MB), "512 bytes" (under 1 KB). +fn size_text(bytes: usize) -> String { + match bytes { + b if b >= 1 << 20 => format!("{} MB", b >> 20), + b if b >= 1 << 10 => format!("{} KB", b >> 10), + b => format!("{b} bytes"), + } +} + +fn region_text(r: &Region) -> String { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEM_PRIVATE, MEM_RESERVE}; + let state = match r.state { + MEM_FREE => return "free address space (no memory of the process: a PC GPU address?)".to_string(), + MEM_COMMIT => "committed", + MEM_RESERVE => "reserved", + _ => "?", + }; + let ty = match r.ty { + MEM_PRIVATE => "private", + MEM_MAPPED => "mapped", + MEM_IMAGE => "image", + _ => "?", + }; + format!("{state} {ty} memory, allocation at {:#x} (protection {:#x}), region {:#x}+{:#x} (protection {:#x})", r.alloc, r.alloc_protect, r.base, r.size, r.protect) +} + +/// `out.len()` bytes at `at` – a copy by ReadProcessMemory: memory that is not there, or goes +/// meanwhile, fails the copy; nothing here faults (title memory is never read directly). +fn copy_out(at: usize, out: &mut [u8]) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if at < 0x1_0000 || out.is_empty() || at.checked_add(out.len()).is_none() { + return false; + } + let mut done = 0usize; + // SAFETY: the copy goes into `out`, of `out.len()` bytes; the source is only read by the call + let ok = unsafe { ReadProcessMemory(GetCurrentProcess(), at as *const c_void, out.as_mut_ptr().cast(), out.len(), &mut done) }; + ok != 0 && done == out.len() +} + +/// The first 16 bytes the CPU sees at `va` (None: unreadable). +pub(super) fn cpu_bytes(va: u64) -> Option<[u8; 16]> { + let at = usize::try_from(va).ok()?; + let mut b = [0u8; 16]; + copy_out(at, &mut b).then_some(b) +} + +/// What memory at `a` outside unified memory (`w`) is to translated programs and to the CPU: the +/// window 0 note of an address below 4 GiB (`low_note`), the CPU's first 16 bytes. Nothing for +/// memory in unified memory, or no address. +fn outside_parts(a: u64, w: &Where) -> Vec { + if !w.outside() { + return Vec::new(); + } + low_note(a, w).map(str::to_string).into_iter().chain([cpu_text(cpu_bytes(a))]).collect() +} + +/// An address outside unified memory below 4 GiB: its high dword is 0, which translated programs' +/// reads take for window 0 (`emit::window_read`) – they read window 0's bytes at it – and their +/// writes for no window (`emit::window_write`). +fn low_note(a: u64, w: &Where) -> Option<&'static str> { + (w.outside() && a < 1 << 32).then_some("below 4 GiB: translated programs read window 0's bytes there and write nowhere") +} + +/// "on the CPU: 0000002a 00000001 00000001 00000000 (dwords)", "on the CPU: unreadable". +pub(super) fn cpu_text(b: Option<[u8; 16]>) -> String { + let Some(b) = b else { return "on the CPU: unreadable".to_string() }; + let d: Vec = b.chunks_exact(4).filter_map(|c| <[u8; 4]>::try_from(c).ok()).map(|c| format!("{:08x}", u32::from_le_bytes(c))).collect(); + format!("on the CPU: {} (dwords)", d.join(" ")) +} + +/// `parts` on lines of at most `LINE_MAX` bytes, joined by "; ", each line starting with `prefix` +/// (a line that goes on: "prefix … part"); a part too long for a line of its own is cut. +fn pack(prefix: &str, parts: &[String]) -> Vec { + let mut out = Vec::new(); + let mut line = String::new(); + for p in parts { + if !line.is_empty() && line.len() + 2 + p.len() > LINE_MAX { + out.push(fit(std::mem::take(&mut line))); + } + if line.is_empty() { + line = if out.is_empty() { format!("{prefix} {p}") } else { format!("{prefix} … {p}") }; + } else { + line.push_str("; "); + line.push_str(p); + } + } + if !line.is_empty() { + out.push(fit(line)); + } + out +} + +/// `s` cut to `LINE_MAX` bytes (at a character's boundary, with "…"). +fn fit(mut s: String) -> String { + if s.len() <= LINE_MAX { + return s; + } + let mut end = LINE_MAX - '…'.len_utf8(); + while end > 0 && !s.is_char_boundary(end) { + end -= 1; + } + s.truncate(end); + s.push('…'); + s +} + +#[cfg(test)] +thread_local! { + /// (tests) this thread's budget instead of the process's (`budget_for_test`) + static TEST_BUDGET: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// (tests) the lines this thread logged + static LINES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// (tests) skips of `hashes` are logged on this thread as the process's budget would log them +/// (`per` a program, `in_all` in all) – and XCL's views it writes recorded – until the guard goes. +#[cfg(test)] +pub(super) fn budget_for_test(hashes: &[u64], per: u32, in_all: u32) -> impl Drop { + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + TEST_BUDGET.with(|b| *b.borrow_mut() = None); + } + } + TEST_BUDGET.with(|b| *b.borrow_mut() = Some(Budget::new(hashes, per, in_all))); + Restore +} + +/// (tests) the lines this thread logged since the last call. +#[cfg(test)] +pub(super) fn take_lines_for_test() -> Vec { + LINES.with(|l| std::mem::take(&mut *l.borrow_mut())) +} + +/// (tests) whether the root views are logged in this process (`XCL_SKIP_CS_ROOTS`). +#[cfg(test)] +pub(super) fn switch_for_test() -> bool { + switch() +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + + /// A listed program's first 2 skips are logged, 16 in the process (the process's bounds); a + /// program not listed never. + #[test] + fn a_program_s_first_two_skips_are_logged_and_sixteen_in_all() { + let hashes: Vec = (1..=10).map(|k| 0x7F0F_0000_0000_0000 + k).collect(); + let b = Budget::new(&hashes, PER_PROGRAM, IN_ALL); + assert_eq!(b.admit(0x7F0F_0000_0000_00FF), None, "not listed"); + assert_eq!(b.admit(hashes[0]), Some((1, 1))); + assert_eq!(b.admit(hashes[0]), Some((2, 2))); + assert_eq!(b.admit(hashes[0]), None, "a program's third skip"); + assert_eq!(b.admit(0x7F0F_0000_0000_00FF), None, "not listed"); + let mut logged = 2; + for &h in &hashes[1..] { + for _ in 0..3 { + if b.admit(h).is_some() { + logged += 1; + } + } + } + assert_eq!(logged, 16, "16 in all"); + assert_eq!(b.admit(hashes[9]), None); + // the bounds hold for skips on several threads at once: 6 threads let go together, 100 + // rounds of a fresh budget (in each, every thread spins until all 6 are up) – a skip that + // passed the first look while the others were counted is not logged. (The same 6 threads + // throughout: threads made and gone by the hundred move where later tests' memory lands.) + const ROUNDS: usize = 100; + let h0 = hashes[0]; + let budgets: std::sync::Arc> = std::sync::Arc::new((0..ROUNDS).map(|_| Budget::new(&[h0], PER_PROGRAM, IN_ALL)).collect()); + let up: std::sync::Arc> = std::sync::Arc::new((0..ROUNDS).map(|_| AtomicU32::new(0)).collect()); + let go = std::sync::Arc::new(AtomicU32::new(0)); + let threads: Vec<_> = (0..6) + .map(|_| { + let (budgets, up, go) = (budgets.clone(), up.clone(), go.clone()); + std::thread::spawn(move || { + let mut admitted = [0u32; ROUNDS]; + for (r, b) in budgets.iter().enumerate() { + up[r].fetch_add(1, Ordering::Release); + while go.load(Ordering::Acquire) <= r as u32 { + std::hint::spin_loop(); + } + admitted[r] = (0..3).filter(|_| b.admit(h0).is_some()).count() as u32; + } + admitted + }) + }) + .collect(); + for (r, n) in up.iter().enumerate() { + while n.load(Ordering::Acquire) < 6 { + std::hint::spin_loop(); + } + go.store(r as u32 + 1, Ordering::Release); + } + let admitted: Vec<[u32; ROUNDS]> = threads.into_iter().map(|t| t.join().unwrap()).collect(); + for r in 0..ROUNDS { + assert_eq!(admitted.iter().map(|a| a[r]).sum::(), 2, "round {r}: a program's first 2, whichever thread skips them"); + } + } + + /// Lines start with the program's prefix and stay under 480 bytes – a part too long is cut at a + /// character's boundary, parts that do not fit a line go on the next. + #[test] + fn every_line_starts_with_the_hash_and_stays_under_480_bytes() { + let prefix = "D3D12.X: XCL_SKIP_CS: 7f0f00000000aaaa"; + let long = "×".repeat(400) + &"a".repeat(300); + let lines = pack(prefix, &["head".to_string(), long.clone(), "x".repeat(200), "tail".to_string()]); + assert!(lines.len() >= 3, "{lines:?}"); + for l in &lines { + assert!(l.starts_with(&format!("{prefix} ")), "{l}"); + assert!(l.len() < 480 && l.len() <= LINE_MAX, "{} bytes", l.len()); + } + assert!(lines[0].ends_with(" head"), "{}", lines[0]); + assert!(lines[1].starts_with(&format!("{prefix} … ××")) && lines[1].ends_with('…'), "{}", lines[1]); + assert!(lines.last().unwrap().ends_with("; tail"), "{lines:?}"); + assert_eq!(pack(prefix, &["a".to_string(), "b".to_string()]), vec![format!("{prefix} a; b")]); + // a cut inside a character goes back to the character's start + let odd = fit(format!("{prefix} a{}", "×".repeat(300))); + assert!(odd.len() <= LINE_MAX && odd.ends_with("××…"), "{odd}"); + // the call and the parameters + assert_eq!(dispatch_text([3, 2, 1], None), "Dispatch 3×2×1"); + assert_eq!(dispatch_text([4, 1, 1], Some(0x20)), "DispatchX 4×1×1 (flags 0x20)"); + assert_eq!( + indirect_text(1, 0x7F0F_00A0, false, "outside unified memory", ", at 0x195322640 (0x40 into a buffer of 64 bytes at 0x195322600)", Some("upload")), + "ExecuteIndirect of up to 1 command(s) with signature 0x7f0f00a0: arguments outside unified memory, at 0x195322640 (0x40 into a buffer of 64 bytes at 0x195322600), its count's buffer upload" + ); + assert!(indirect_text(1, 1, true, "unknown", "", None).contains("(its commands change root arguments: the list's are below): arguments unknown")); + let l = Layout { params: vec![Param::Constants { at: 0, count: 20 }, Param::Descriptor { at: 80 }, Param::Table { at: 88 }], size: 92, ..Default::default() }; + assert_eq!(params_text(&l), "3 root parameters (1 constants, 1 root descriptors, 1 tables)"); + assert_eq!((size_text(4 << 30), size_text(0x1_0000), size_text(512)), ("4096 MB".to_string(), "64 KB".to_string(), "512 bytes".to_string())); + if let Some(u) = crate::gpu::uma::get() { + assert_eq!(unsafe { table_lines(prefix, 3, 0, &mut 0) }, vec![format!("{prefix} p3: table 0x0: not set")], "no table: one line"); + // a table in window 0's last 64 KiB, where no heap is and nothing is committed: its + // unreadable slots on the head line + let t = 0xFFFF_0000u32; + let at = u.base() + t as usize; + if u.window(0).1 >= 1 << 32 && super::super::console_heap::peek(at).is_none() && cpu_bytes(at as u64).is_none() { + assert_eq!( + unsafe { table_lines(prefix, 3, t, &mut 0) }, + vec![format!("{prefix} p3: table 0xffff0000: not in a heap of XCL's; unreadable, in no heap of XCL's: [0, 1, 2, 3, 4, 5, 6, 7]")] + ); + } + } + let words: Vec = (0..16).map(|k| 0xFFFF_FF00 + k).collect(); + let c = constants_line(prefix, 0, 20, &words); + assert!(c.starts_with(&format!("{prefix} p0: 20 constants [0xffffff00, ")) && c.ends_with(", 0xffffff0f, …]"), "{c}"); + assert!(c.len() <= LINE_MAX); + // a skip's own lines: the hash in its 16 digits, the skip's numbers, 16 of 20 constants + let twenty = Layout { params: vec![Param::Constants { at: 0, count: 20 }], size: 80, ..Default::default() }; + let args: Vec = (0..20u32).flat_map(|w| w.to_le_bytes()).collect(); + let shown: Vec = (0..16).map(|w| format!("{w:#x}")).collect(); + assert_eq!( + unsafe { skip_lines(0x7F0F_1100, 0x7F0F_0001, Pipeline::Built { threads: 64 }, (1, 3), &Call::Dispatch { groups: [1, 1, 1], flags: None }, Some(&twenty), &args) }, + vec![ + "D3D12.X: XCL_SKIP_CS: 000000007f0f0001 root views at its skip #1 (#3 logged in the process): Dispatch 1×1×1 on list 0x7f0f1100, 64 threads; 1 root parameters (1 constants, 0 root descriptors, 0 tables)".to_string(), + format!("D3D12.X: XCL_SKIP_CS: 000000007f0f0001 p0: 20 constants [{}, …]", shown.join(", ")), + ] + ); + assert_eq!(qword(&0x5F_0000_0100u64.to_le_bytes(), 0), Some(0x5F_0000_0100), "a root descriptor's 8 bytes"); + // every Where, in its longest form, with the longest view and writer, on lines of its own + let plain = PlainGpu { base: 0x7FFF_FFFF_0000, bytes: 1 << 40, by: "VirtualAlloc, GPU-visible", flags: u64::MAX, protect: u32::MAX }; + let r = Region { alloc: usize::MAX, alloc_protect: u32::MAX, base: usize::MAX, size: usize::MAX, state: 0x1000, protect: u32::MAX, ty: 0x2_0000 }; + for w in [Where::Placed { res: usize::MAX, at: usize::MAX, bytes: u64::MAX, uav: true, plain: Some(plain) }, Where::Other(Some(r)), Where::Plain(plain)] { + let v = View::Buffer { base: u64::MAX, bytes: u64::MAX, stride: 0x3FFF, records: u32::MAX, format: 0x7F }; + let parts = [format!("p99[7]: {}", v.text()), w.text(), writer_text(&Writer::Over("SRV of a shape XCL cannot describe")), cpu_text(Some([0xFF; 16]))]; + for l in pack(prefix, &parts) { + assert!(l.starts_with(&format!("{prefix} ")) && l.len() <= LINE_MAX, "{} bytes: {l}", l.len()); + } + } + } + + /// Descriptors as slots hold them: an empty V#, a raw and a structured buffer V#, a CBV's, a T# + /// of XCL's (word 0 the index of a PC view) and one of the title's (word 0 an address), a BVH's. + #[test] + fn views_are_decoded_from_their_words() { + let v = |w: [u32; 4]| view_of(&[w[0], w[1], w[2], w[3], 0x1234, 0, 0, 0]); + assert_eq!(v([0; 4]), View::Empty, "an empty V# (the slot's other words do not count)"); + let raw = crate::gpu::desc::buffer_words(0x1_9532_2600, 0, 4096, 22); + assert_eq!(v(raw), View::Buffer { base: 0x1_9532_2600, bytes: 4096, stride: 0, records: 4096, format: 22 }); + let structured = crate::gpu::desc::buffer_words(0x5F_0000_1000, 24, 10, 22); + assert_eq!(v(structured), View::Buffer { base: 0x5F_0000_1000, bytes: 240, stride: 24, records: 10, format: 22 }); + assert_eq!(v(crate::gpu::desc::cbv_words(0x5F_0000_2000, 0x600)), View::Buffer { base: 0x5F_0000_2000, bytes: 0x600, stride: 16, records: 0x60, format: 77 }); + assert_eq!(v(crate::gpu::desc::cbv_words(0, 0)).address(), None, "XCL's CBV of no memory names none itself (F-4: the memory its record names)"); + let xcl = crate::gpu::desc::xcl_image_for_view(41, 56, crate::gpu::desc::ImageType::D2, 256, 128, 1, 1); + let t = view_of(&xcl); + assert!(matches!(t, View::Image { w: 256, h: 128, word0: 41, index: true, .. }), "{t:?}"); + assert_eq!(t.address(), None); + assert!(t.text().ends_with("(word 0 0x29: a PC view's index, no address)"), "{}", t.text()); + let mut title = xcl; + title[0] = (0x5F_0010_0000u64 >> 8) as u32; + title[1] = (title[1] & !0xFF) | ((0x5F_0010_0000u64 >> 40) as u32 & 0xFF); + let t = view_of(&title); + assert_eq!(t.address(), Some(0x5F_0010_0000), "{t:?}"); + let b = crate::gpu::desc::bvh_words(0x5F_0020_0000, true); + assert_eq!(view_of(&[b[0], b[1], b[2], b[3], 0, 0, 0, 0]), View::Bvh { address: 0x5F_0020_0000 }); + // (an address from 1 TiB on: its bits 40-47 in word 1) + let b = crate::gpu::desc::bvh_words(0x7F0F_0020_0000, true); + assert_eq!(view_of(&[b[0], b[1], b[2], b[3], 0, 0, 0, 0]), View::Bvh { address: 0x7F0F_0020_0000 }); + // a view of XCL's whose descriptor names no memory: the memory its view names, or none + let prefix = "D3D12.X: XCL_SKIP_CS: 7f0f00000000bbbb"; + let tex = 0x5F_0010_0000u64; + assert_eq!( + unsafe { slot_lines(prefix, 2, 3, view_of(&xcl), Some(Writer::Xcl("texture SRV", Some((tex as usize, 0)))), &mut 0) }, + vec![format!( + "{prefix} p2[3]: T# D2 256×128×1, format 56 (word 0 0x29: a PC view's index, no address) (XCL's view of the texture at {tex:#x}); outside unified memory, in no allocation XCL knows; XCL's texture SRV; {}", + cpu_text(cpu_bytes(tex)) + )] + ); + assert_eq!( + unsafe { slot_lines(prefix, 2, 4, View::Empty, Some(Writer::Xcl("SRV of no resource", None)), &mut 0) }, + vec![format!("{prefix} p2[4]: empty V#; no memory (an empty descriptor: reads give 0, writes go nowhere); XCL's SRV of no resource or a copy of an empty V# over it (the same bytes)")] + ); + // (F-4) a PC view's index with no memory known – the title's copy of XCL's T#, or one whose + // texture has no title address –: the PC view's memory, never "an empty descriptor" + for w in [Some(Writer::Title), Some(Writer::Xcl("texture SRV", None)), Some(Writer::Over("texture SRV")), None] { + let l = unsafe { slot_lines(prefix, 2, 5, view_of(&xcl), w, &mut 0) }.join("\n"); + assert!(!l.contains("empty descriptor") && l.contains("a PC view's index (its memory is the PC view's; no title address known)"), "{w:?}: {l}"); + } + // (F-4) XCL's CBV of memory outside unified memory names no memory itself: the memory XCL's + // record names + let va = 0x5A_0000_1000usize; + let cbv = crate::gpu::desc::cbv_words(0, 0); + let l = unsafe { slot_lines(prefix, 2, 6, view_of(&[cbv[0], cbv[1], cbv[2], cbv[3], 0, 0, 0, 0]), Some(Writer::Xcl("CBV", Some((va, 256)))), &mut 0) }.join("\n"); + assert!(l.contains(&format!("(XCL's view names {va:#x}, 256 bytes); outside unified memory")) && l.contains("XCL's CBV"), "{l}"); + // (F-5) an empty V# of XCL's: any empty V# copied over it reads the same – the memory hedged + let l = unsafe { slot_lines(prefix, 2, 7, View::Empty, Some(Writer::Xcl("buffer UAV", Some((va, 64)))), &mut 0) }.join("\n"); + assert!( + l.starts_with(&format!("{prefix} p2[7]: empty V# (XCL's buffer UAV named {va:#x}, 64 bytes, or a copy of an empty V# over it: the same bytes); ")) + && l.contains("XCL's buffer UAV or a copy of an empty V# over it (the same bytes)"), + "{l}" + ); + } + + /// Memory is placed where it is: a window of unified memory (a block handed out there, or the + /// window's range by number only), a buffer the title placed with a PC resource of its own, GPU- + /// visible title memory kernelx gave (with the call, flags and protection the title asked for), + /// memory XCL knows nothing of (as VirtualQuery sees it, within its budget), address 0. + #[test] + fn addresses_are_placed_where_they_are() { + let _g = super::super::outside::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let mut q = 2; + assert_eq!(where_is(0, &mut q), Where::Nowhere); + assert_eq!(Where::Nowhere.text(), "no title address"); + // outside unified memory below 4 GiB: window 0's bytes are what translated programs read + let low = Some("below 4 GiB: translated programs read window 0's bytes there and write nowhere"); + assert_eq!((low_note(0x8470_0000, &Where::Other(None)), low_note(0x5F_0000_0000, &Where::Other(None))), (low, None)); + assert_eq!(low_note(0x8470_0000, &Where::Window { k: 0, block: true }), None, "not outside unified memory"); + assert_eq!(outside_parts(0x8470_0000, &Where::Other(None)), vec![low.unwrap().to_string(), cpu_text(cpu_bytes(0x8470_0000))]); + assert_eq!(outside_parts(0, &Where::Nowhere), Vec::::new()); + assert_eq!(Where::Window { k: 3, block: true }.text(), "unified memory, window 3"); + assert_eq!(Where::Window { k: 0, block: false }.text(), "unified memory, window 0 by number only (no block handed out there: a PC GPU address?)"); + if let Some(u) = crate::gpu::uma::get() { + if let Some(p) = u.alloc(0x1_0000, 0x1_0000) { + let k = u.window_of(p as usize).unwrap(); + assert_eq!(where_is(p as u64 + 0x40, &mut q), Where::Window { k, block: true }); + assert!(!Where::Window { k, block: true }.outside()); + u.free(p as usize); + } + let (w0, len) = u.window(0); + if len > 0x8000_0000 && !u.is_title_address(w0 + len - 0x100) { + assert_eq!(where_is((w0 + len - 0x100) as u64, &mut q), Where::Window { k: 0, block: false }); + } + } + unsafe { + // GPU-visible title memory as kernelx gives it (a graphics protection), with the census on + let _on = super::super::outside::test_on(true); + let heap = crate::hle::kernelx::VirtualAlloc(std::ptr::null(), 0x10_0000, MEM_RESERVE, 0x2004) as usize; + assert_ne!(heap, 0, "a GPU-visible reservation"); + let w = where_is(heap as u64 + 0x1234, &mut q); + assert_eq!(w, Where::Plain(PlainGpu { base: heap, bytes: 0x10_0000, by: "VirtualAlloc, GPU-visible", flags: 0x2000, protect: 0x2004 })); + assert!(w.outside()); + assert_eq!(w.text(), format!("outside unified memory: in GPU-visible title memory at {heap:#x} of 1 MB (VirtualAlloc, GPU-visible, flags 0x2000, protection 0x2004)")); + // a buffer the title placed there with a PC resource of its own (the census) + let res = 0x7F0F_3000usize; + super::super::outside::note_for_test(res, heap + 0x1000, 0x800); + let w = where_is(heap as u64 + 0x1100, &mut q); + assert!(matches!(w, Where::Placed { res: r, at, bytes: 0x800, uav: false, plain: Some(p) } if r == res && at == heap + 0x1000 && p.base == heap), "{w:?}"); + assert!(w.text().starts_with(&format!("outside unified memory: in a buffer the title placed at {:#x} (2048 bytes) with a PC resource of its own ({res:#x}), in GPU-visible title memory at {heap:#x}", heap + 0x1000)), "{}", w.text()); + assert!(matches!(where_is(heap as u64 + 0x1800, &mut q), Where::Plain(_)), "the buffer's end is not in it"); + super::super::outside::forget(res); + assert_eq!(crate::hle::kernelx::VirtualFree(heap as *mut c_void, 0, MEM_RELEASE), 1); + // memory XCL knows nothing of: VirtualQuery's answer, twice a skip at most + let other = VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert_ne!(other, 0); + let mut q = 2; + // (the process's 16 queries: no other test asks any) + match where_is(other as u64 + 0x10, &mut q) { + Where::Other(Some(r)) => { + assert_eq!((r.alloc, r.base, r.state), (other, other, MEM_RESERVE), "{r:?}"); + assert!(Where::Other(Some(r)).text().starts_with(&format!("outside unified memory, in no allocation XCL knows: reserved private memory, allocation at {other:#x}"))); + assert_eq!(q, 1, "one query of the skip's two"); + } + w => panic!("VirtualQuery's answer: {w:?}"), + } + let mut none_left = 0; + assert_eq!(where_is(other as u64 + 0x10, &mut none_left), Where::Other(None), "no query left: not asked"); + VirtualFree(other as *mut c_void, 0, MEM_RELEASE); + } + } + + /// The CPU's bytes are read by a copy that cannot fault: memory not committed, without access, + /// below 64 KiB, past the address space's end or crossing into a reserved page is unreadable – + /// committed memory reads as it is. + #[test] + fn the_cpu_bytes_of_memory_that_is_not_there_are_unreadable() { + unsafe { + let p = VirtualAlloc(std::ptr::null(), 0x2_0000, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert_ne!(p, 0); + assert_eq!(cpu_bytes(p as u64), None, "reserved"); + assert_eq!(cpu_text(cpu_bytes(p as u64 + 0x8)), "on the CPU: unreadable"); + assert!(!VirtualAlloc(p as *const c_void, 0x1_0000, MEM_COMMIT, PAGE_READWRITE).is_null()); + let at = p as *mut u32; + for (k, v) in [0x2a, 1, 1, 0].into_iter().enumerate() { + at.add(k).write(v); + } + assert_eq!(cpu_text(cpu_bytes(p as u64)), "on the CPU: 0000002a 00000001 00000001 00000000 (dwords)"); + assert_eq!(cpu_bytes(p as u64 + 0x1_0000 - 8), None, "the last 8 bytes before a reserved page, and 8 of it"); + let mut old = 0; + assert_ne!(windows_sys::Win32::System::Memory::VirtualProtect(p as *const c_void, 0x1_0000, PAGE_NOACCESS, &mut old), 0); + assert_eq!(cpu_bytes(p as u64), None, "no access"); + // (not asked once released: another test's memory may be there by then) + VirtualFree(p as *mut c_void, 0, MEM_RELEASE); + assert_eq!(cpu_bytes(0), None); + assert_eq!(cpu_bytes(0x8000), None, "below 64 KiB"); + assert_eq!(cpu_bytes(u64::MAX - 4), None); + } + } + + /// Who wrote a slot, as XCL's record of its views tells it: XCL (the memory its view names – + /// an empty V#'s too –, a copy XCL made of its view: that view), the title over a view of + /// XCL's, the title where XCL wrote nothing; without the record (the root views off) not known. + #[test] + fn who_wrote_a_slot_is_told_by_xcl_s_record() { + use super::super::console_heap::{self, Writer}; + if crate::gpu::uma::get().is_none() { + return; + } + let obj = 0x7F0F_4E00usize; + assert!(console_heap::register(obj, 4, 0x7F0F_5000, 0, 32, false, false, true)); + let v = console_heap::start(obj).unwrap() as usize; + let s: Vec = (0..4).map(|k| console_heap::slot((v + 32 * k) as u64).unwrap()).collect(); + let recorded = { + let _roots = budget_for_test(&[], 2, 16); + console_heap::write_view(&s[0], &[0; 4], "buffer SRV", || Some((0x5F_0000_4000, 4096))); + let w = crate::gpu::desc::buffer_words(0x5F_0000_5000, 0, 64, 22); + console_heap::write_view(&s[1], &w, "buffer UAV by address", || None); + // the title's own bytes in slot 2 (where XCL wrote nothing), then over slot 1's + let peek1 = console_heap::peek(v + 32 + 4).unwrap(); + let mine = crate::gpu::desc::cbv_words(0x5F_0000_6000, 256); + // (the slots' memory: the heap's, registered until the end of the test) + unsafe { std::ptr::copy_nonoverlapping(mine.as_ptr(), (v + 64) as *mut u32, 4) }; + let peek2 = console_heap::peek(v + 64).unwrap(); + let peek0 = console_heap::peek(v).unwrap(); + unsafe { std::ptr::copy_nonoverlapping(mine.as_ptr(), (v + 32) as *mut u32, 4) }; + let over = console_heap::peek(v + 32).unwrap(); + // slot 0 copied into slot 3 by CopyDescriptors (`copy_words`) + console_heap::copy_words(&s[0], &s[3]); + let copy = console_heap::peek(v + 96).unwrap(); + (recording(), peek0, peek1, peek2, over, copy) + }; + let off = console_heap::peek(v).unwrap(); + console_heap::unregister(obj); + let (on, peek0, peek1, peek2, over, copy) = recorded; + assert_eq!((peek0.heap, peek0.k, peek0.at, peek1.k, peek1.at), (obj, 0, v, 1, v + 32), "a slot's number and first byte"); + assert_eq!(off.writer, Writer::Unknown("XCL's views are not recorded"), "without the root views nothing is recorded"); + if !on { + // XCL_SKIP_CS_ROOTS=0: XCL's views are not recorded at all + assert_eq!(peek0.writer, Writer::Unknown("XCL's views are not recorded")); + return; + } + assert_eq!(peek0.writer, Writer::Xcl("buffer SRV", Some((0x5F_0000_4000, 4096)))); + assert_eq!(peek1.writer, Writer::Xcl("buffer UAV by address", None)); + assert_eq!(peek2.writer, Writer::Title); + assert_eq!(over.writer, Writer::Over("buffer UAV by address")); + assert_eq!(copy.writer, Writer::Xcl("buffer SRV", Some((0x5F_0000_4000, 4096))), "a copy of XCL's view: that view, its memory"); + assert_eq!(writer_text(&over.writer), "the title's bytes (over XCL's buffer UAV by address)"); + assert_eq!(writer_text(&peek0.writer), "XCL's buffer SRV"); + } + + /// XCL's record tells a slot's writer by all 8 of its words (F-5): the title's bytes that differ + /// only in the words XCL's V# left are the title's; 32 zero bytes stay XCL's empty V# – or a copy + /// of one, the same bytes (the line hedges: `slot_lines`). A CopyDescriptors copy gets the + /// source's record only while the source holds XCL's bytes (F-7) – as XCL wrote them: a T# + /// renumbered for its new slot is still XCL's view. Heaps and title memory 0x7A0C_5xxx, + /// 0x5A_xxxx. + #[test] + fn a_slot_s_record_holds_only_while_its_bytes_are_xcl_s() { + use super::super::console_heap::{self, Writer}; + if crate::gpu::uma::get().is_none() { + return; + } + let obj = 0x7A0C_5E00usize; + assert!(console_heap::register(obj, 4, 0x7A0C_5000, 0, 32, false, false, true)); + let v = console_heap::start(obj).unwrap() as usize; + unsafe { std::ptr::write_bytes(v as *mut u8, 0, 4 * 32) }; + let s: Vec = (0..4).map(|k| console_heap::slot((v + 32 * k) as u64).unwrap()).collect(); + let (a, b) = (0x5A_0000_2000usize, 0x5A_0000_3000u64); + let got = { + let _roots = budget_for_test(&[], 2, 16); + // an empty V# of XCL's, then the title's bytes that differ in words 4-7 only, then zeros + console_heap::write_view(&s[0], &[0; 4], "buffer UAV", || Some((a, 64))); + let mine = [0u32, 0, 0, 0, 1, 2, 3, 4]; + unsafe { std::ptr::copy_nonoverlapping(mine.as_ptr(), v as *mut u32, 8) }; + let differs = console_heap::peek(v).unwrap().writer; + unsafe { std::ptr::write_bytes(v as *mut u8, 0, 32) }; + let zeros = console_heap::peek(v).unwrap().writer; + // XCL's V# in slot 1, the title's CBV over it, then slot 1 copied to slot 2 by CopyDescriptors + let xcl = crate::gpu::desc::buffer_words(a as u64, 0, 64, 22); + console_heap::write_view(&s[1], &xcl, "buffer SRV", || Some((a, 64))); + let title = crate::gpu::desc::cbv_words(b, 256); + unsafe { std::ptr::copy_nonoverlapping(title.as_ptr(), (v + 32) as *mut u32, 4) }; + console_heap::copy_words(&s[1], &s[2]); + let stale = console_heap::peek(v + 64).unwrap().writer; + // XCL's V# in slot 1 again: its copy in slot 3 is that view + console_heap::write_view(&s[1], &xcl, "buffer SRV", || Some((a, 64))); + console_heap::copy_words(&s[1], &s[3]); + let fresh = console_heap::peek(v + 96).unwrap().writer; + // XCL's T# in slot 0, copied to slot 2: its word 0 renumbered for slot 2 (its PC view's + // index) – the source still holds XCL's bytes + let t = crate::gpu::desc::xcl_image_for_view(s[0].index, 56, crate::gpu::desc::ImageType::D2, 64, 64, 1, 1); + console_heap::write_view(&s[0], &t, "texture SRV", || Some((a, 0))); + console_heap::copy_words(&s[0], &s[2]); + let image = (console_heap::peek(v + 64).unwrap().writer, s[0].index != s[2].index); + (recording(), differs, zeros, stale, fresh, image) + }; + console_heap::unregister(obj); + let (on, differs, zeros, stale, fresh, image) = got; + if !on { + // XCL_SKIP_CS_ROOTS=0: XCL's views are not recorded at all + assert_eq!(differs, Writer::Unknown("XCL's views are not recorded")); + return; + } + assert_eq!(differs, Writer::Over("buffer UAV"), "the title's bytes in the words XCL's empty V# left as they were"); + assert_eq!(zeros, Writer::Xcl("buffer UAV", Some((a, 64))), "32 zero bytes: XCL's empty V#, or a copy of one"); + assert_eq!(stale, Writer::Xcl("view copied by CopyDescriptors", None), "a copy of the title's bytes over XCL's view names no memory of XCL's"); + assert_eq!(fresh, Writer::Xcl("buffer SRV", Some((a, 64))), "a copy of XCL's view: that view, its memory"); + assert_eq!(image, (Writer::Xcl("texture SRV", Some((a, 0))), true), "a copy of XCL's T#, renumbered: that view"); + } + + /// XCL's views are recorded only while skips are left to log (F-2): a listed program's 2, or + /// 16 in all, spend the budget – past it XCL's views are not recorded (nothing reads the record + /// any more). Heaps and title memory 0x7A0C_6xxx, 0x5A_xxxx. + #[test] + fn xcl_s_views_are_not_recorded_once_the_budget_is_spent() { + use super::super::console_heap::{self, Writer}; + let h = 0x7A0C_0000_0000_6001u64; + let one = Budget::new(&[h], 2, 16); + assert!(!one.spent()); + assert!(one.admit(h).is_some() && !one.spent(), "one skip of its 2"); + assert!(one.admit(h).is_some() && one.spent(), "its 2: none left to log"); + let all = Budget::new(&[h, h + 1], 2, 3); + for g in [h, h, h + 1] { + assert!(all.admit(g).is_some()); + } + assert!(all.spent(), "3 in all"); + assert!(!Budget::new(&[], 2, 16).spent(), "a list of none never runs out by its programs"); + if crate::gpu::uma::get().is_none() { + return; + } + let obj = 0x7A0C_6E00usize; + assert!(console_heap::register(obj, 2, 0x7A0C_6000, 0, 32, false, false, true)); + let v = console_heap::start(obj).unwrap() as usize; + unsafe { std::ptr::write_bytes(v as *mut u8, 0, 2 * 32) }; + let s: Vec = (0..2).map(|k| console_heap::slot((v + 32 * k) as u64).unwrap()).collect(); + let got = { + let _roots = budget_for_test(&[h], 2, 16); + let before = recording(); + console_heap::write_view(&s[0], &[0; 4], "buffer SRV", || Some((0x5A_0000_6000, 64))); + let (first, second) = (admit(h), admit(h)); + let after = recording(); + console_heap::write_view(&s[1], &[0; 4], "buffer SRV", || Some((0x5A_0000_6100, 64))); + (before, (first, second), after, console_heap::peek(v).unwrap().writer, console_heap::peek(v + 32).unwrap().writer) + }; + console_heap::unregister(obj); + let (before, admitted, after, recorded, past) = got; + if !switch() { + assert!(!before && !after, "XCL_SKIP_CS_ROOTS=0: never recorded"); + return; + } + assert_eq!(admitted, (Some((1, 1)), Some((2, 2)))); + assert!(before && !after, "recorded until the budget is spent"); + assert_eq!(recorded, Writer::Xcl("buffer SRV", Some((0x5A_0000_6000, 64))), "recorded while skips were left to log – and still read"); + assert!(!matches!(past, Writer::Xcl(..)), "not recorded past the budget: {past:?}"); + } + + /// XCL's T# names its texture by the resource, its address looked up when a line names the + /// slot – not in the title's view call (F-2: `title_textures`' lock stays off the view path); a + /// texture without a title address by then names none. Heap and resource 0x7A0C_7xxx. + #[test] + fn a_texture_view_s_address_is_looked_up_when_its_slot_is_named() { + use super::super::console_heap::{self, Writer}; + if crate::gpu::uma::get().is_none() { + return; + } + let res = 0x7A0C_7000usize; + let (a1, a2) = (0x5A_0001_0000usize, 0x5A_0002_0000usize); + let obj = 0x7A0C_7E00usize; + assert!(console_heap::register(obj, 1, 0x7A0C_7100, 0, 32, false, false, true)); + let v = console_heap::start(obj).unwrap() as usize; + let s = console_heap::slot(v as u64).unwrap(); + let t = crate::gpu::desc::xcl_image_for_view(s.index, 56, crate::gpu::desc::ImageType::D2, 64, 64, 1, 1); + super::super::real::set_test_title_address(res, Some(a1)); + let got = { + let _roots = budget_for_test(&[], 2, 16); + console_heap::write_texture_view(&s, &t, "texture SRV", res); + // (the texture placed elsewhere since the view was made, then gone) + super::super::real::set_test_title_address(res, Some(a2)); + let moved = console_heap::peek(v).unwrap().writer; + super::super::real::set_test_title_address(res, None); + let gone = console_heap::peek(v).unwrap().writer; + let words = console_heap::peek(v).unwrap().words; + let line = unsafe { slot_lines("D3D12.X: XCL_SKIP_CS: 000000007a0c7000", 0, 0, view_of(&words), Some(gone), &mut 0) }.join("\n"); + (recording(), moved, gone, line) + }; + console_heap::unregister(obj); + let (on, moved, gone, line) = got; + if !on { + return; + } + assert_eq!(moved, Writer::Xcl("texture SRV", Some((a2, 0))), "looked up when the slot is named, not when the view was made"); + assert_eq!(gone, Writer::Xcl("texture SRV", None), "a texture with no title address now names none"); + assert!(line.contains("a PC view's index (its memory is the PC view's; no title address known); XCL's texture SRV"), "{line}"); + } + + /// Once XCL's record of its views is full, an empty slot it has no record of is "writer + /// unknown" – never "no view of XCL's made there" (F-1): XCL may have made one there after the + /// record filled. (A record of 1 slot of this thread's own; the process's is shared.) Heap + /// 0x7A0C_8xxx. + #[test] + fn an_empty_slot_is_writer_unknown_once_the_record_is_full() { + use super::super::console_heap; + let Some(u) = crate::gpu::uma::get() else { return }; + let obj = 0x7A0C_8E00usize; + assert!(console_heap::register(obj, 8, 0x7A0C_8000, 0, 32, false, false, true)); + let v = console_heap::start(obj).unwrap() as usize; + unsafe { std::ptr::write_bytes(v as *mut u8, 0, 8 * 32) }; + let prefix = "D3D12.X: XCL_SKIP_CS: 000000007a0c8e00"; + let _ = console_heap::take_full_lines_for_test(); + let (lines, full) = { + let _roots = budget_for_test(&[], 2, 16); + let _record = console_heap::record_for_test(1); + // slot 0: XCL's empty V#, recorded; slots 1 and 2: XCL's empty V#s with the record full + console_heap::write_view(&console_heap::slot(v as u64).unwrap(), &[0; 4], "buffer SRV", || Some((0x5A_0000_8000, 64))); + console_heap::write_view(&console_heap::slot((v + 32) as u64).unwrap(), &[0; 4], "buffer UAV", || Some((0x5A_0000_8100, 64))); + console_heap::write_view(&console_heap::slot((v + 64) as u64).unwrap(), &[0; 4], "buffer UAV", || Some((0x5A_0000_8200, 64))); + (unsafe { table_lines(prefix, 2, (v - u.base()) as u32, &mut 0) }, console_heap::take_full_lines_for_test()) + }; + console_heap::unregister(obj); + if !switch() { + return; + } + assert_eq!(full, vec!["D3D12.X: XCL_SKIP_CS: XCL's record of the views it writes is full (1 slots): later slots' writers are unknown".to_string()], "said once, when it filled"); + let head = &lines[0]; + assert!(head.contains("; empty, writer unknown (XCL's record of its views is full): [1, 2, 3, 4, 5, 6, 7]"), "{head}"); + assert!(!head.contains("no view of XCL's made there"), "{head}"); + assert!(lines.iter().any(|l| l.starts_with(&format!("{prefix} p2[0]: empty V# (XCL's buffer SRV named 0x5a00008000, 64 bytes"))), "{lines:?}"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 029660d..d560861 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use windows::core::Interface; use windows::Win32::Foundation::{CloseHandle, HANDLE}; @@ -34,9 +34,14 @@ use windows_sys::Win32::System::Memory::{ const TILE: usize = 0x1_0000; /// tiles of a video-memory pool heap (64 MiB) const POOL_TILES: u32 = 1024; -/// tiles decommitted while no title work was submitted that stay mapped (`State::parked`) before -/// they are unmapped together: 256 MB of video memory +/// parked tiles (`State::parked`) past which a decommit looks for those it can unmap at once +/// (else that is done before the next title submit): 256 MB of video memory const PARKED_MAX: usize = 4096; +/// how long a pool all of whose tiles came free stays (taken back first) before its heap goes, +/// and how many such pools stay whatever their age: a load that frees and takes tiles in turn +/// made and destroyed a 64 MiB heap each time +const RETIRED_FOR: std::time::Duration = std::time::Duration::from_secs(30); +const RETIRED_KEEP: usize = 2; /// bytes of the ring-buffered upload staging buffer const STAGING: usize = 64 << 20; /// alignment of sub-allocations inside the upload staging ring (write-combined cacheline) @@ -215,20 +220,25 @@ struct State { /// video-memory pool heaps (None: given back, its index free for the next one) pools: Vec>, free: Vec<(u32, u32)>, - /// pools all of whose tiles came free: released once the GPU is past `value` and a moment - /// went by (titles' queues may still read what was mapped there) + /// pools all of whose tiles came free, the newest last: taken back first when tiles run + /// out; past `RETIRED_FOR` (but the newest `RETIRED_KEEP`) handed to `late_release`, which + /// lets the heap go once every queue is past the work submitted so far retired: Vec<(ID3D12Heap, u64, std::time::Instant)>, /// tile address → pool tile + uncommitted page hole mask + per-page sent chunk hashes mapped: FxHashMap, /// pool tiles also used by placed buffers (not freed while they are) pinned: FxHashMap<(u32, u32), u32>, - /// tile address → pool tile of tiles decommitted since the last title submit, still mapped - /// in their window: unmapped together (`flush_parked`) before the next submit, when the free - /// list runs out, or past `PARKED_MAX`; a commit there before that takes its tile back with - /// no new mapping. (A retail title moving physical pages one at a time while it loads - /// decommits and commits again thousands of tiles a second, and each `UpdateTileMappings` - /// took ~0.15 ms.) - parked: FxHashMap, + /// tile address → pool tile of tiles decommitted, still mapped in their window, with the + /// mark of their decommit: unmapped together (`flush_parked`) once every queue is past the + /// work submitted before it (that work may still read there: an unmapping under it changed + /// a buffer's mappings under committed command buffers – three kernel panics on a Mac); + /// a commit there before that takes its tile back with no new mapping. (A retail title + /// moving physical pages one at a time while it loads decommits and commits again + /// thousands of tiles a second, and each `UpdateTileMappings` took ~0.15 ms.) + parked: FxHashMap)>, + /// what the next `signal` signals, published before each call on `queue` it follows: a + /// mark taken meanwhile waits for that call (`late_release`) + reserved: &'static AtomicU64, /// placed buffers → the pool tiles they use buffers: FxHashMap>, /// reused tiles / decommitted partial pages to clear: (address, bytes) @@ -485,6 +495,12 @@ fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC { } } +/// The sparse queue's clock for deferred releases: its work (tile mappings, uploads) is waited +/// for by every mark taken while it was submitted (`late_release`). +unsafe fn register_clock(s: &State) { + super::late_release::register_external(s.queue.as_raw() as usize, &s.fence, s.reserved); +} + /// XCL's queue, fences and upload lists on `dev` for `windows` (window start, its buffer). unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) -> windows::core::Result { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; @@ -516,6 +532,7 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + reserved: Box::leak(Box::new(AtomicU64::new(0))), buffers: FxHashMap::default(), to_zero: Vec::new(), staging: None, @@ -551,7 +568,10 @@ pub unsafe fn shadow_window(dev: &ID3D12Device, base: usize, size: usize, buf: & if g.is_none() { // no sparse window was made (`init`): the copies still need the queue and the lists match new_state(dev, Vec::new()) { - Ok(s) => *g = Some(s), + Ok(s) => { + register_clock(&s); + *g = Some(s) + } Err(e) => { crate::xlog_warn!("shadowed window at {base:#x}: {e}"); return false; @@ -626,6 +646,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + reserved: Box::leak(Box::new(AtomicU64::new(0))), buffers: FxHashMap::default(), to_zero: Vec::new(), staging: None, @@ -650,6 +671,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len()); // a state this replaces (the windows set up again) goes after the lock: the release of // its last buffers reaches `forget_buffer`, which takes the lock (#344) + register_clock(&s); let old = STATE.lock().unwrap().replace(s); drop(old); for (a, b) in std::mem::take(&mut *EARLY.lock().unwrap()) { @@ -671,6 +693,8 @@ impl State { } unsafe fn take_tile(&mut self) -> Option<((u32, u32), bool)> { + // (parked tiles whose work is done only: one the GPU may still read is never taken – + // a retired pool or a new one instead) if self.free.is_empty() { self.flush_parked(); } @@ -723,8 +747,21 @@ impl State { /// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled. fn retire_free_pools(&mut self) { let now = std::time::Instant::now(); - let done = unsafe { self.fence.GetCompletedValue() }; - self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); + // the oldest past `RETIRED_FOR` go to `late_release` (not dropped here, under the state + // lock, on a title thread): a title list committed before their last tiles were unmapped + // can still be queued behind GPU waits much later, and its command buffer names the heap + let n = self.retired.len(); + if n > RETIRED_KEEP && self.retired.first().is_some_and(|(_, _, at)| now.duration_since(*at) >= RETIRED_FOR) { + let mut kept = Vec::with_capacity(n); + for (k, (heap, v, at)) in std::mem::take(&mut self.retired).into_iter().enumerate() { + if k + RETIRED_KEEP < n && now.duration_since(at) >= RETIRED_FOR { + unsafe { super::late_release::defer(heap.into_raw() as usize, super::real::Kind::Heap) }; + } else { + kept.push((heap, v, at)); + } + } + self.retired = kept; + } if self.free.len() < POOL_TILES as usize { return; } @@ -747,9 +784,11 @@ impl State { /// Map `tiles` (tile addresses) of `res` (starting at `res_base`) onto pool tiles, /// batched per pool heap with contiguous runs merged into single regions. unsafe fn map_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[(usize, (u32, u32))]) { + let _ops = super::d3d_ops(); if tiles.is_empty() { return; } + self.reserve(); let mut by_heap: FxHashMap> = FxHashMap::default(); for &(a, (h, t)) in tiles { by_heap.entry(h).or_default().push((((a - res_base) / TILE) as u32, t)); @@ -796,9 +835,11 @@ impl State { } unsafe fn unmap_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[usize]) { + let _ops = super::d3d_ops(); if tiles.is_empty() { return; } + self.reserve(); let mut xs: Vec = tiles.iter().map(|&a| ((a - res_base) / TILE) as u32).collect(); xs.sort_unstable(); let mut coords: Vec = Vec::with_capacity(xs.len()); @@ -846,7 +887,7 @@ impl State { while t < end { if !self.mapped.contains_key(&t) && self.window_index(t).is_some() { // still mapped there: no new mapping, what it held is cleared - if let Some(tile) = self.parked.remove(&t) { + if let Some((tile, _)) = self.parked.remove(&t) { self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); self.runs = None; self.to_zero.push((t, TILE)); @@ -893,13 +934,23 @@ impl State { let _ = self.queue.Signal(&self.fence, self.value); } + /// Before a call on `queue` that the next `signal` follows: what it will signal is published + /// (`late_release`: a mark taken from now on waits for that call's work). + #[inline] + fn reserve(&self) { + self.reserved.store(self.value + 1, Ordering::SeqCst); + } + #[inline] unsafe fn wait_for(&self, target: u64) { if target == 0 || self.fence.GetCompletedValue() >= target { return; } let _ = self.fence.SetEventOnCompletion(target, self.event); - windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); + { + let _held = crate::waitwatch::xcl(crate::waitwatch::X_SPARSE, target); + windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); + } if self.fence.GetCompletedValue() < target { crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue()); } @@ -940,15 +991,18 @@ impl State { /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work /// via `queue.Wait(&self.fence, self.value)`). unsafe fn submit_slot(&mut self, idx: usize) { + let ops = super::d3d_ops(); let closed = self.slots[idx].list.Close().is_ok(); if closed { if let Ok(l) = self.slots[idx].list.cast::() { + self.reserve(); super::title_textures::own_work(|| { self.queue.ExecuteCommandLists(&[Some(l)]); }); } } self.signal(); + drop(ops); self.slots[idx].fence_val = self.value; if self.ring_write > self.ring_submitted { self.inflight.push_back((self.value, self.ring_write)); @@ -1092,14 +1146,17 @@ impl State { let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| { if *open { *open = false; + let ops = super::d3d_ops(); if s.rb_list.Close().is_ok() { if let Ok(l) = s.rb_list.cast::() { + s.reserve(); super::title_textures::own_work(|| { s.queue.ExecuteCommandLists(&[Some(l)]); }); } } s.signal(); + drop(ops); s.rb_last_fence = s.value; s.wait_for(s.value); s.reclaim_ring(); @@ -1147,11 +1204,15 @@ impl State { let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); if !open { self.wait_for(self.rb_last_fence); + let _ops = super::d3d_ops(); let _ = self.rb_alloc.Reset(); let _ = self.rb_list.Reset(&self.rb_alloc, None); open = true; } - self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); + { + let _ops = super::d3d_ops(); + self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); + } pending.push((cur, used, chunk)); used += chunk; done += chunk; @@ -1341,13 +1402,6 @@ pub fn queue() -> Option { STATE.lock().unwrap().as_ref().map(|s| s.queue.clone()) } -/// The queue to include in a D3DMetal late-release fence batch. On contention the batch -/// must wait for another pass, including when the current thread holds STATE. -pub(super) fn try_queue() -> Result, ()> { - let state = STATE.try_lock().map_err(|_| ())?; - Ok(state.as_ref().map(|s| s.queue.clone())) -} - pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { if ranges.is_empty() { return; @@ -1371,8 +1425,11 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz } s.rb_value += 1; let v = s.rb_value; - if queue.Signal(&s.rb_fence, v).is_ok() && s.queue.Wait(&s.rb_fence, v).is_ok() && super::list_x::trace_gpu_stall() { - super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback", &s.rb_fence, v); + if queue.Signal(&s.rb_fence, v).is_ok() { + crate::waitwatch::note_gpu_wait("sparse readback", s.queue.as_raw() as usize, &s.rb_fence, v); + if s.queue.Wait(&s.rb_fence, v).is_ok() && super::list_x::trace_gpu_stall() { + super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback", &s.rb_fence, v); + } } s.readback_ranges(&merged); } @@ -1517,15 +1574,20 @@ impl State { return; } self.runs = None; + // the work submitted so far may still read there (one mark for them all: lock-free) + let mark = super::late_release::mark(); + let before = self.parked.len(); for &t in &tiles { if let Ok(i) = pools.binary_search_by_key(&t, |p| p.0) { if pools[i].1.0 != SHADOW_POOL { - self.parked.insert(t, pools[i].1); + self.parked.insert(t, (pools[i].1, Arc::clone(&mark))); } } } MAPPED_GEN.fetch_add(1, Ordering::Release); - if self.parked.len() >= PARKED_MAX && self.flush_parked() { + // (past PARKED_MAX, looked at again every 512 tiles: those still in use stay) + let after = self.parked.len(); + if after >= PARKED_MAX && (before < PARKED_MAX || before / 512 != after / 512) && self.flush_parked() { self.retire_free_pools(); } } @@ -1535,20 +1597,35 @@ impl State { if tile.0 == SHADOW_POOL { return; } - if !self.pinned.contains_key(&tile) && !self.mapped.values().any(|e| e.pool == tile) && !self.parked.values().any(|&p| p == tile) { + if !self.pinned.contains_key(&tile) && !self.mapped.values().any(|e| e.pool == tile) && !self.parked.values().any(|(p, _)| *p == tile) { self.free.push(tile); } } - /// The parked tiles unmapped from their windows (one call per window) and their pool tiles - /// free (but those of placed buffers). Pools left all free are not retired here: callers do - /// that (`retire_free_pools`) unless they take a tile right away. + /// The parked tiles every queue is past the work of (submitted before their decommit) + /// unmapped from their windows (one call per window) and their pool tiles free (but those + /// of placed buffers); the others stay parked, mapped. True: some went. Pools left all free + /// are not retired here: callers do that (`retire_free_pools`) unless they take a tile + /// right away. unsafe fn flush_parked(&mut self) -> bool { if self.parked.is_empty() { return false; } + let progress = super::late_release::progress(); + // (one look per mark: a decommit's tiles share theirs) + let mut looked: FxHashMap<*const super::late_release::Mark, bool> = FxHashMap::default(); + let done: Vec = self + .parked + .iter() + .filter(|(_, (_, m))| *looked.entry(Arc::as_ptr(m)).or_insert_with(|| progress.passed(m))) + .map(|(&t, _)| t) + .collect(); + if done.is_empty() { + return false; + } let mut by_window: FxHashMap> = FxHashMap::default(); - for (t, tile) in std::mem::take(&mut self.parked) { + for t in done { + let Some((tile, _)) = self.parked.remove(&t) else { continue }; if tile.0 == SHADOW_POOL { continue; } @@ -1691,6 +1768,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: s.scratch_runs = dirty_runs; let q = queue.as_raw() as usize; if s.value > 0 && s.waited.get(&q).copied().unwrap_or(0) < s.value { + crate::waitwatch::note_gpu_wait("sparse uploads", q, &s.fence, s.value); if queue.Wait(&s.fence, s.value).is_ok() && super::list_x::trace_gpu_stall() { super::list_x::note_internal_wait(q, "sparse uploads", &s.fence, s.value); } @@ -1811,12 +1889,6 @@ mod tests { assert!(to_zero.is_empty()); } - #[test] - fn a_reentrant_release_can_check_the_queue_without_waiting_for_sparse_state() { - let _state = STATE.lock().unwrap(); - assert!(try_queue().is_err()); - } - /// A block freed on one thread while another allocates: its address goes back to the /// windows only once it is decommitted (released first, the decommit came after another /// thread had the same address again: that thread's writes faulted). @@ -1878,6 +1950,7 @@ mod tests { free: Vec::new(), retired: Vec::new(), parked: FxHashMap::default(), + reserved: Box::leak(Box::new(AtomicU64::new(0))), mapped: FxHashMap::default(), pinned: FxHashMap::default(), buffers: FxHashMap::default(), @@ -1912,6 +1985,52 @@ mod tests { assert_eq!(s.retired.len(), 1, "round {round}: the retired pool was taken back, not a new one made"); assert_eq!(s.pools.iter().filter(|p| p.is_some()).count(), 0, "round {round}"); } + + // retired pools past RETIRED_FOR go to the ledger (not dropped here), but the newest + // RETIRED_KEEP; the heap lives until every queue is past the work submitted so far + let _one = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + let desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_TILES as u64 * TILE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, + }; + let old = std::time::Instant::now().checked_sub(RETIRED_FOR + std::time::Duration::from_secs(1)).expect("an instant 31 s ago"); + s.retired.clear(); + let mut watched = None; + for k in 0..RETIRED_KEEP + 1 { + let mut heap: Option = None; + s.dev.CreateHeap(&desc, &mut heap).expect("a pool heap"); + let heap = heap.unwrap(); + if k == 0 { + watched = Some(heap.clone()); + } + s.retired.push((heap, 0, old)); + } + let watched = watched.unwrap(); + let raw = watched.as_raw(); + let count = || { + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw as *const *const usize)).add(1)); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw as *const *const usize)).add(2)); + let n = add(raw); + rel(raw); + n - 1 + }; + let (_, work) = super::super::late_release::test_mark_in_flight(); + s.retire_free_pools(); + assert_eq!(s.retired.len(), RETIRED_KEEP, "the oldest went, the newest stay whatever their age"); + assert!(s.retired.iter().all(|(h, _, _)| h.as_raw() != raw), "the oldest is the one handed over"); + std::thread::sleep(std::time::Duration::from_millis(250)); + assert_eq!(count(), 2, "the ledger holds it while work submitted before is in flight"); + work.done(); + let t = std::time::Instant::now(); + while count() != 1 { + if !crate::util::mac_host() { + super::super::late_release::drain_known(false); + } + assert!(t.elapsed().as_secs() < 10, "let go once the work is done"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } } } @@ -2086,6 +2205,7 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + reserved: Box::leak(Box::new(AtomicU64::new(0))), buffers: FxHashMap::default(), to_zero: Vec::new(), staging: None, @@ -2144,6 +2264,8 @@ mod tests { use windows::Win32::Graphics::Dxgi::*; use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + // (marks of the process's clocks: no other test's work in flight meanwhile) + let _one = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); let mut dev: Option = None; @@ -2181,6 +2303,7 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + reserved: Box::leak(Box::new(AtomicU64::new(0))), buffers: FxHashMap::default(), to_zero: Vec::new(), staging: None, @@ -2208,7 +2331,7 @@ mod tests { // decommitted: parked, still mapped, nothing sent to the GPU s.decommit_range(base, TILE); assert!(!s.mapped.contains_key(&base)); - assert_eq!(s.parked.get(&base), Some(&tile)); + assert_eq!(s.parked.get(&base).map(|p| p.0), Some(tile)); assert!(!s.free.contains(&tile)); assert_eq!(s.value, v, "no tile mapping changed"); s.release_if_unused(tile); @@ -2243,6 +2366,29 @@ mod tests { assert_eq!(s.mapped[&(base + TILE)].pool, tile); assert!(!s.mapped.contains_key(&base)); + // decommitted while work submitted before is in flight: the tile stays parked and + // mapped through flushes, and a commit with no free tile left takes a tile of a + // new pool instead – once the work is done it is unmapped and free + s.decommit_range(base + TILE, TILE); + assert!(s.flush_parked()); + s.commit_range(base, TILE); + let tile = s.mapped[&base].pool; + let (_, work) = super::super::late_release::test_mark_in_flight(); + s.decommit_range(base, TILE); + let v = s.value; + assert!(!s.flush_parked(), "the work before the decommit is in flight: nothing unmapped"); + assert_eq!(s.value, v, "no tile mapping changed"); + assert_eq!(s.parked.get(&base).map(|p| p.0), Some(tile)); + s.free.clear(); + s.commit_range(base + TILE, TILE); + assert_ne!(s.mapped[&(base + TILE)].pool, tile, "a parked tile the GPU may still read is not taken"); + assert!(s.parked.contains_key(&base), "still parked, still mapped"); + assert!(!s.free.contains(&tile)); + work.done(); + assert!(s.flush_parked(), "past the work: unmapped"); + assert!(s.parked.is_empty()); + assert!(s.free.contains(&tile)); + s.wait_for(s.value); drop(s); assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); diff --git a/crates/xcl/src/hle/d3d12x/stall.rs b/crates/xcl/src/hle/d3d12x/stall.rs new file mode 100644 index 0000000..5e637e0 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/stall.rs @@ -0,0 +1,939 @@ +//! The GPU stopped: what it had been given, and a way out. +//! +//! Each translated dispatch is noted for its command list (`note`): the console program (the +//! hash of its blob – the name the translation cache gives it), its groups, or for an +//! ExecuteIndirect where its arguments are and whether XCL checked their group counts first +//! (`indirect::sanitize`). ExecuteCommandLists and KickoffX hand what their lists noted since +//! their last submission to the queue's history (`submitted`: the last 16 submissions of each +//! queue, with the fence values the queue was told to signal after each). +//! +//! A thread looks at the title's fences every second (`watch`). One that stays short of what a +//! queue was told to signal for 10 s, while no queue waits for a value nobody was told to signal +//! yet, is a GPU that makes no progress: the submissions still in flight on each queue are +//! logged (`[stall]`), again every 30 s while it lasts. With `XCL_GPU_STALL_EXIT=` the title +//! is ended once that has lasted s seconds (`real::end_title`: its threads stopped, its fences +//! signalled, the GPU drained for up to 10 s, the process ended within 15 s). +//! +//! GTA VI 1.0.2.1 on a Mac (run 61): at its first world frame the GPU stayed 100 % busy in +//! compute for minutes – no Metal error, nothing in XCL's log, a title fence one value short – +//! until the process was killed; macOS freed the GPU about 10 s later. +//! `XCL_GPU_STALL_WATCH=0`: neither the notes nor the watch. Not covered: lists of console code +//! (`XCL_CONSOLE_LISTS=1`, `console_list`), and a fence two queues signal out of order. +//! +//! A list also counts its ExecuteIndirect of translated pipelines – compute and draws – by where +//! their arguments are, and each submission adds what it runs of them (`indirect_counts`: the +//! `GPU work so far` line sets them against those recorded; `[stall]` lines name the draws in +//! flight). `XCL_INDIRECT_SUBMITTED=0`: not counted. + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +/// Where an ExecuteIndirect's arguments are. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(super) enum Args { + /// a title buffer in unified memory (window k): what translated programs write is there + Window(u8), + /// an upload buffer (the CPU wrote them) + Upload, + /// a PC resource of its own: title memory outside unified memory – what translated + /// programs write at the title's address does not reach it + Own, + /// not a buffer XCL knows + Unknown, +} + +impl Args { + pub(super) fn describe(self) -> String { + match self { + Args::Window(k) => format!("in unified memory (window {k})"), + Args::Upload => "in an upload buffer".into(), + Args::Own => "outside unified memory (a PC resource of its own: what translated programs write at the title's address does not reach it)".into(), + Args::Unknown => "in a resource XCL does not know".into(), + } + } + + pub(super) fn short(self) -> String { + match self { + Args::Window(k) => format!("window {k}"), + Args::Upload => "upload".into(), + Args::Own => "outside unified memory".into(), + Args::Unknown => "unknown".into(), + } + } + + /// Its row in the counts by place: window, upload, own, unknown (B's census uses it too). + pub(super) fn index(self) -> usize { + match self { + Args::Window(_) => 0, + Args::Upload => 1, + Args::Own => 2, + Args::Unknown => 3, + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum What { + /// Dispatch(x, y, z) + Groups([u32; 3]), + /// ExecuteIndirect of up to `max` commands (`count`: with a count buffer); `checked`: their + /// group counts went through XCL's check first (`indirect::sanitize`) + Indirect { max: u32, args: Args, checked: bool, count: bool }, + /// not recorded (`XCL_SKIP_CS`) + Skipped, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) struct Rec { + /// the console program (fnv64 of its blob); 0: not known + pub(super) hash: u64, + /// threads in a group of it (0: not known) + pub(super) threads: u32, + pub(super) what: What, +} + +/// translated compute ExecuteIndirect calls, those of them whose group counts were checked, +/// dispatches not recorded for `XCL_SKIP_CS` +static COUNTS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +pub(super) fn count_indirect(checked: bool) { + COUNTS[0].fetch_add(1, Ordering::Relaxed); + if checked { + COUNTS[1].fetch_add(1, Ordering::Relaxed); + } +} + +pub(super) fn count_skipped() { + COUNTS[2].fetch_add(1, Ordering::Relaxed); +} + +/// (translated compute ExecuteIndirect, checked, skipped for `XCL_SKIP_CS`) so far +pub(super) fn counts() -> [u64; 3] { + std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) +} + +/// Whether dispatches are noted and the fences watched (`XCL_GPU_STALL_WATCH=0`: not). +pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GPU_STALL_WATCH").map_or(true, |v| v.trim() != "0")) +} + +/// records kept for a list (more are counted) +const LIST_RECS: usize = 512; +/// records kept for a submission (its last ones: the work a stopped GPU most likely was at) +const SUB_RECS: usize = 2048; +/// submissions kept for a queue +const QUEUE_SUBS: usize = 16; + +#[derive(Default)] +struct Ledger { + /// the newest records (up to LIST_RECS: the oldest go first) + recs: VecDeque, + /// records noted since the list began to record (`recs` holds the last of them) + total: u64, + /// how many of them a submission took already (a list KickoffX submits records on) + taken: u64, + /// ExecuteIndirect of translated pipelines noted since the list began to record, by kind + /// (compute, draws) and place (`Args::index`) – draws have no records + indirect: [[u64; 4]; 2], + /// how many of them a submission took already + indirect_taken: [[u64; 4]; 2], +} + +impl Ledger { + /// What a submission of the list runs of its ExecuteIndirect: those noted since its last + /// submission (`fresh`) – or, a closed list run again, all of them. + fn take_indirect(&mut self, fresh: bool) -> [[u64; 4]; 2] { + let run = std::array::from_fn(|g| std::array::from_fn(|p| if fresh { self.indirect[g][p] - self.indirect_taken[g][p] } else { self.indirect[g][p] })); + self.indirect_taken = self.indirect; + run + } +} + +static LEDGERS: Mutex>> = Mutex::new(None); + +/// ExecuteIndirect of translated pipelines by kind (compute, draws) and place of their +/// arguments (`Args::index`), counted in each submission of the list that recorded them +/// (`submitted`: a list run again runs them again; one never submitted, never). Those recorded +/// are the census's (`indirect::census`: checked first or sent as they were). +static SUBMITTED: [[AtomicU64; 4]; 2] = [const { [const { AtomicU64::new(0) }; 4] }; 2]; + +/// Whether the ExecuteIndirect of translated pipelines are counted by place for their lists, and +/// as run with each submission (`XCL_INDIRECT_SUBMITTED=0`, or `XCL_GPU_STALL_WATCH=0`: not). +pub(super) fn indirect_on() -> bool { + static ON: OnceLock = OnceLock::new(); + on() && *ON.get_or_init(|| std::env::var("XCL_INDIRECT_SUBMITTED").map_or(true, |v| v.trim() != "0")) +} + +/// ExecuteIndirect in lists submitted so far by kind and place – Err: not counted (the switch). +pub(super) fn indirect_counts() -> Result<[[u64; 4]; 2], &'static str> { + if !on() { + return Err("XCL_GPU_STALL_WATCH=0"); + } + if !indirect_on() { + return Err("XCL_INDIRECT_SUBMITTED=0"); + } + Ok(std::array::from_fn(|g| std::array::from_fn(|p| SUBMITTED[g][p].load(Ordering::Relaxed)))) +} + +/// An ExecuteIndirect of a translated draw pipeline recorded on `list` with its arguments in +/// `args` (no record: the stall ledger names compute programs): counted for the list, and as run +/// in each submission of it. +pub(super) fn note_indirect_draw(list: *mut c_void, args: Args) { + if !indirect_on() { + return; + } + let mut g = LEDGERS.lock().unwrap_or_else(|e| e.into_inner()); + g.get_or_insert_with(HashMap::new).entry(list as usize).or_default().indirect[1][args.index()] += 1; +} + +/// A translated dispatch recorded on `list`. +pub(super) fn note(list: *mut c_void, rec: Rec) { + if !on() { + return; + } + // (a compute ExecuteIndirect: by place for the list, and as run with each submission of it) + let place = match rec.what { + What::Indirect { args, .. } if indirect_on() => Some(args.index()), + _ => None, + }; + let mut g = LEDGERS.lock().unwrap_or_else(|e| e.into_inner()); + let l = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + if l.recs.len() == LIST_RECS { + l.recs.pop_front(); + } + l.recs.push_back(rec); + l.total += 1; + if let Some(p) = place { + l.indirect[0][p] += 1; + } +} + +/// `list` records anew (Reset, a split's new segment) or is gone. +pub(super) fn list_reset(list: *mut c_void) { + if !on() { + return; + } + if let Some(m) = LEDGERS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + m.remove(&(list as usize)); + } +} + +struct Sub { + serial: u64, + /// seconds into the run (the log's clock) + at: f64, + lists: usize, + recs: Vec, + /// dispatches not kept + more: u64, + /// lists run again with nothing noted since their last submission: what they recorded + again: bool, + /// the submission's ExecuteIndirect by kind and place + indirect: [[u64; 4]; 2], + /// fence values the queue was told to signal after it + signals: Vec<(usize, u64)>, +} + +static QUEUES: Mutex>>> = Mutex::new(None); +static SERIAL: AtomicU64 = AtomicU64::new(0); + +/// `lists` go to `queue` now (ExecuteCommandLists, KickoffX). +pub(super) fn submitted(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || lists.is_empty() { + return; + } + watch(); + let (mut recs, mut more, mut again) = (Vec::new(), 0u64, false); + let mut share = [[0u64; 4]; 2]; + if let Some(m) = LEDGERS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + for &l in lists { + let Some(led) = m.get_mut(&(l as usize)) else { continue }; + // what was noted since its last submission – or, a closed list run again, all of it + let new = led.total - led.taken; + // its ExecuteIndirect as they run: those noted since its last submission – or, a closed + // list run again, all (a draw's note has no record: either kind of note makes it fresh) + let fresh = new > 0 || led.indirect != led.indirect_taken; + let run = led.take_indirect(fresh); + for g in 0..2 { + for p in 0..4 { + share[g][p] += run[g][p]; + } + } + let (n, all) = if new > 0 { (new, false) } else { (led.total, true) }; + let kept = (n as usize).min(led.recs.len()); + recs.extend(led.recs.iter().skip(led.recs.len() - kept).copied()); + more += n - kept as u64; + again |= all && n > 0; + led.taken = led.total; + } + } + if recs.len() > SUB_RECS { + let cut = recs.len() - SUB_RECS; + more += cut as u64; + recs.drain(..cut); + } + for g in 0..2 { + for p in 0..4 { + if share[g][p] > 0 { + SUBMITTED[g][p].fetch_add(share[g][p], Ordering::Relaxed); + } + } + } + let sub = Sub { serial: SERIAL.fetch_add(1, Ordering::Relaxed) + 1, at: crate::log::uptime(), lists: lists.len(), recs, more, again, indirect: share, signals: Vec::new() }; + let mut g = QUEUES.lock().unwrap_or_else(|e| e.into_inner()); + let q = g.get_or_insert_with(HashMap::new).entry(queue as usize).or_default(); + if q.len() >= QUEUE_SUBS { + q.pop_front(); + } + q.push_back(sub); +} + +/// `queue` was told to signal `fence` with `value` (after what it was given so far). +pub(super) fn note_signal(queue: *mut c_void, fence: usize, value: u64) { + if !on() { + return; + } + let mut g = QUEUES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(queue as usize))).and_then(|q| q.back_mut()) { + if s.signals.len() < 8 { + s.signals.push((fence, value)); + } + } +} + +/// no progress this long: logged +const REPORT_AFTER: u64 = 10_000; +/// and again this often while it lasts +const REPORT_EVERY: u64 = 30_000; + +/// a look is due every second; a longer gap (the process stopped – a debugger, a memory +/// sampler –, the Mac asleep) is time the GPU may not have had +const LOOK: u64 = 1_000; +const GAP: u64 = 3_000; + +/// What the watch keeps between its looks. +#[derive(Default)] +struct Watch { + /// fence → (completed value, since when it is short of its signal without moving – ms) + seen: HashMap, + /// when this stall was last logged (None: none is going on) + logged: Option, + /// the last look + last: Option, +} + +/// Title fences short of what their queue was told to signal: (fence, completed, signalled, +/// for how long – ms), and the longest. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Stuck { + fences: Vec<(usize, u64, u64, u64)>, + longest: u64, +} + +#[derive(Debug, PartialEq, Eq)] +enum Verdict { + Fine, + Report(Stuck), + Exit(Stuck), +} + +impl Watch { + /// One look at `fences` (`fence_x::snapshot`: fence, completed, signalled, waited) at `now` + /// (ms); `exit_after` (ms): `XCL_GPU_STALL_EXIT`. + fn look(&mut self, now: u64, fences: &[(usize, u64, u64, u64)], exit_after: Option) -> Verdict { + // a gap between looks counts as one look: the clocks move on by what is over + if let Some(last) = self.last { + let gap = now.saturating_sub(last); + if gap > GAP { + let skip = gap - LOOK; + for e in self.seen.values_mut() { + e.1 = (e.1 + skip).min(now); + } + if let Some(t) = self.logged.as_mut() { + *t = (*t + skip).min(now); + } + } + } + self.last = Some(now); + // a fence's clock runs while it is short of its signal and does not move: one complete + // (an idle fence) or one that moved starts again – a fence idle for minutes and then + // signalled is not short for minutes + for &(f, done, sig, _) in fences { + let e = self.seen.entry(f).or_insert((done, now)); + if e.0 != done || done >= sig { + *e = (done, now); + } + } + // a queue told to wait for a value no queue was told to signal yet: it waits for the + // title (a Signal still to come, or the CPU's), and so may every fence behind it – their + // clocks start again when that wait can be satisfied + let held = fences.iter().any(|&(_, done, sig, wait)| done < wait && sig < wait); + if held { + for e in self.seen.values_mut() { + e.1 = now; + } + self.logged = None; + return Verdict::Fine; + } + let fences: Vec<(usize, u64, u64, u64)> = fences + .iter() + .filter(|&&(_, done, sig, _)| done < sig) + .map(|&(f, done, sig, _)| (f, done, sig, now.saturating_sub(self.seen.get(&f).map_or(now, |e| e.1)))) + .collect(); + let longest = fences.iter().map(|s| s.3).max().unwrap_or(0); + if fences.is_empty() { + self.logged = None; + return Verdict::Fine; + } + let stuck = Stuck { fences, longest }; + if exit_after.is_some_and(|e| longest >= e) { + return Verdict::Exit(stuck); + } + if longest < REPORT_AFTER { + self.logged = None; + return Verdict::Fine; + } + if self.logged.is_some_and(|t| now.saturating_sub(t) < REPORT_EVERY) { + return Verdict::Fine; + } + self.logged = Some(now); + Verdict::Report(stuck) + } +} + +/// `XCL_GPU_STALL_EXIT=` in ms (None: not set, or 0) +fn exit_after() -> Option { + static V: OnceLock> = OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_GPU_STALL_EXIT").ok().and_then(|v| v.trim().parse::().ok()).filter(|&s| s > 0).map(|s| s.saturating_mul(1000))) +} + +/// The process ends with this code when `XCL_GPU_STALL_EXIT` ends it. +pub const STALL_EXIT_CODE: u32 = 0x5741_11ED; + +/// The watch's thread (started with the first submission; not in unit tests – they test +/// `Watch::look` – whose fences come and go). +fn watch() { + if cfg!(test) { + return; + } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let exit_after = exit_after(); + if let Some(ms) = exit_after { + crate::xlog_info!("[stall] XCL_GPU_STALL_EXIT: the title is ended when the GPU makes no progress for {} s", ms / 1000); + } + let spawned = std::thread::Builder::new().name("xcl-stallwatch".into()).spawn(move || { + let mut w = Watch::default(); + let t0 = std::time::Instant::now(); + loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + let now = t0.elapsed().as_millis() as u64; + let fences = super::fence_x::snapshot(); + match w.look(now, &fences, exit_after) { + Verdict::Fine => {} + Verdict::Report(s) => report(&s, &fences), + Verdict::Exit(s) => { + report(&s, &fences); + crate::xlog_error!("[stall] XCL_GPU_STALL_EXIT: no GPU progress for {:.0} s – ending the title", s.longest as f64 / 1000.0); + crate::report::write_final(None); + crate::log::flush(); + super::real::end_title(STALL_EXIT_CODE); + } + } + } + }); + if let Err(e) = spawned { + crate::xlog_warn!("[stall] no thread to watch the GPU's progress: {e}"); + } + }); +} + +fn report(s: &Stuck, fences: &[(usize, u64, u64, u64)]) { + let parts: Vec = s.fences.iter().map(|&(f, done, sig, ms)| format!("fence {f:#x} at {done:#x} of {sig:#x} for {:.0} s", ms as f64 / 1000.0)).collect(); + crate::xlog_warn!("[stall] the GPU has made no progress: {}; no queue waits for a value nobody was told to signal", parts.join(", ")); + for line in in_flight(fences) { + crate::xlog_warn!("[stall] {line}"); + } + crate::log::flush(); +} + +/// Each queue's submissions after the last one whose fence signals all completed (up to 6 of +/// them, the latest). +fn in_flight(fences: &[(usize, u64, u64, u64)]) -> Vec { + let done_of = |f: usize| fences.iter().find(|e| e.0 == f).map_or(u64::MAX, |e| e.1); + let g = QUEUES.lock().unwrap_or_else(|e| e.into_inner()); + let Some(m) = g.as_ref() else { return vec!["no submission noted".into()] }; + let mut queues: Vec<(&usize, &VecDeque)> = m.iter().collect(); + queues.sort_by_key(|(q, _)| **q); + let mut out = Vec::new(); + for (q, subs) in queues { + let last_done = subs.iter().rposition(|s| !s.signals.is_empty() && s.signals.iter().all(|&(f, v)| done_of(f) >= v)); + let flight: Vec<&Sub> = subs.iter().skip(last_done.map_or(0, |i| i + 1)).collect(); + if flight.is_empty() { + continue; + } + out.push(format!( + "queue {q:#x}: {} submission(s) not known to be finished{}", + flight.len(), + if flight.len() > 6 { " (the last 6)" } else { "" } + )); + for s in flight.iter().skip(flight.len().saturating_sub(6)) { + out.push(format!(" {}", describe(s, &done_of))); + } + } + out +} + +/// One submission: its dispatches by program (in the order first recorded), then its signals. +fn describe(s: &Sub, done_of: &dyn Fn(usize) -> u64) -> String { + #[derive(Default)] + struct P { + hash: u64, + threads: u32, + direct: u64, + groups: u64, + largest: [u32; 3], + indirect: u64, + max: u32, + args: Vec, + checked: u64, + count: bool, + skipped: u64, + } + let mut ps: Vec

= Vec::new(); + for r in &s.recs { + let i = match ps.iter().position(|p| p.hash == r.hash) { + Some(i) => i, + None => { + ps.push(P { hash: r.hash, threads: r.threads, ..Default::default() }); + ps.len() - 1 + } + }; + let p = &mut ps[i]; + match r.what { + What::Groups(g) => { + p.direct += 1; + let n = u64::from(g[0]) * u64::from(g[1]) * u64::from(g[2]); + p.groups = p.groups.saturating_add(n); + if n > u64::from(p.largest[0]) * u64::from(p.largest[1]) * u64::from(p.largest[2]) { + p.largest = g; + } + } + What::Indirect { max, args, checked, count } => { + p.indirect += 1; + p.max = p.max.max(max); + if !p.args.contains(&args) { + p.args.push(args); + } + p.checked += u64::from(checked); + p.count |= count; + } + What::Skipped => p.skipped += 1, + } + } + let dispatches = s.recs.len() as u64 + s.more; + let mut line = format!( + "#{} at {:.3} s, {} list(s){}, {dispatches} dispatch(es)", + s.serial, + s.at, + s.lists, + if s.again { " run again as recorded" } else { "" } + ); + if s.more > 0 { + line.push_str(&format!(" ({} not kept)", s.more)); + } + // (draws have no records: their count, and how many have their arguments outside unified memory) + let draws: u64 = s.indirect[1].iter().sum(); + if draws > 0 { + line.push_str(&format!(", {draws} draw ExecuteIndirect ({} with arguments outside unified memory)", s.indirect[1][Args::Own.index()])); + } + let shown = ps.len().min(16); + for p in &ps[..shown] { + let name = if p.hash == 0 { "an unknown program".to_string() } else { format!("{:016x}", p.hash) }; + line.push_str(&format!("; {name}")); + if p.threads != 0 { + line.push_str(&format!(" ({} threads)", p.threads)); + } + if p.direct > 0 { + line.push_str(&format!( + ": {} × Dispatch, {} groups (largest {}×{}×{})", + p.direct, p.groups, p.largest[0], p.largest[1], p.largest[2] + )); + } + if p.indirect > 0 { + let args: Vec = p.args.iter().map(|a| a.short()).collect(); + line.push_str(&format!( + ": {} × ExecuteIndirect (up to {} command(s){}, arguments {}, {} checked)", + p.indirect, + p.max, + if p.count { ", a count buffer" } else { "" }, + args.join(" / "), + p.checked + )); + } + if p.skipped > 0 { + line.push_str(&format!(": {} skipped (XCL_SKIP_CS)", p.skipped)); + } + } + if ps.len() > shown { + line.push_str(&format!("; … {} more program(s)", ps.len() - shown)); + } + for &(f, v) in &s.signals { + let done = done_of(f) >= v; + line.push_str(&format!(" – then fence {f:#x} = {v:#x} ({})", if done { "done" } else { "not done" })); + } + line +} + +/// `XCL_SKIP_CS=,…`: translated console compute programs (fnv64 of the blob, hex – the +/// translation cache's file name and the `[stall]` lines) whose dispatches are not recorded at +/// all (a lever for a test run; the title's work that depends on them is not done). The program +/// is still translated and built – its hash is known from its pipeline –, and lists of console +/// code (`XCL_CONSOLE_LISTS=1`) are not covered. +pub(super) fn skipped(hash: u64) -> bool { + #[cfg(test)] + if hash != 0 && TEST_SKIP.with(|s| s.borrow().contains(&hash)) { + return true; + } + hash != 0 && skip_list().contains(&hash) +} + +/// The programs `XCL_SKIP_CS` lists (read once; `skip_roots` builds its budget from them). +pub(super) fn skip_list() -> &'static [u64] { + static SKIP: OnceLock> = OnceLock::new(); + SKIP.get_or_init(|| { + let v = parse_hashes(&std::env::var("XCL_SKIP_CS").unwrap_or_default()); + if !v.is_empty() { + let names: Vec = v.iter().map(|h| format!("{h:016x}")).collect(); + crate::xlog_warn!("XCL_SKIP_CS: dispatches of {} are not recorded", names.join(", ")); + } + v + }) +} + +#[cfg(test)] +thread_local! { + /// (tests) programs this thread's binds skip as if `XCL_SKIP_CS` listed them + static TEST_SKIP: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// (tests) `hashes` are skipped on this thread until the guard goes (`skipped`; the process's +/// list is a OnceLock of the environment's). +#[cfg(test)] +pub(super) fn skip_for_test(hashes: &[u64]) -> impl Drop { + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + TEST_SKIP.with(|s| s.borrow_mut().clear()); + } + } + TEST_SKIP.with(|s| *s.borrow_mut() = hashes.to_vec()); + Restore +} + +pub(super) fn parse_hashes(s: &str) -> Vec { + s.split(|c: char| c == ',' || c == ';' || c.is_whitespace()) + .map(|t| t.trim()) + .filter(|t| !t.is_empty()) + .filter_map(|t| u64::from_str_radix(t.trim_start_matches("0x").trim_start_matches("0X"), 16).ok()) + .collect() +} + +/// `list`'s ExecuteIndirect noted since it began to record, by kind and place (none: zeros). +#[cfg(test)] +pub(super) fn ledger_indirect_for_test(list: *mut c_void) -> [[u64; 4]; 2] { + LEDGERS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(&(list as usize))).map_or([[0; 4]; 2], |l| l.indirect) +} + +#[cfg(test)] +mod tests { + use super::*; + + const F: usize = 0x7fba_f98b_6610; + + #[test] + fn a_fence_that_keeps_moving_is_never_a_stall() { + let mut w = Watch::default(); + for t in 0..120u64 { + // always one value behind, but moving + let v = (w.look(t * 1000, &[(F, t, t + 1, 0)], Some(30_000)), t); + assert_eq!(v.0, Verdict::Fine, "at {t} s"); + } + } + + #[test] + fn a_fence_stuck_short_of_its_signal_is_reported_after_10_s_then_every_30_s() { + let mut w = Watch::default(); + let mut reports = Vec::new(); + for t in 0..=75u64 { + match w.look(t * 1000, &[(F, 0x1324, 0x1325, 0), (0x1000, 7, 7, 7)], None) { + Verdict::Report(s) => { + assert_eq!(s.fences, vec![(F, 0x1324, 0x1325, t * 1000)]); + reports.push(t); + } + Verdict::Exit(_) => panic!("no XCL_GPU_STALL_EXIT"), + Verdict::Fine => {} + } + } + assert_eq!(reports, vec![10, 40, 70]); + } + + #[test] + fn the_exit_comes_after_its_seconds_and_not_before() { + let mut w = Watch::default(); + let mut exit = None; + for t in 0..=40u64 { + if let Verdict::Exit(s) = w.look(t * 1000, &[(F, 5, 6, 0)], Some(30_000)) { + assert_eq!(s.longest, t * 1000); + exit = Some(t); + break; + } + } + assert_eq!(exit, Some(30)); + // an exit shorter than the report's 10 s comes first + let mut w = Watch::default(); + let first = (0..20u64).find(|&t| matches!(w.look(t * 1000, &[(F, 5, 6, 0)], Some(5_000)), Verdict::Exit(_))); + assert_eq!(first, Some(5)); + } + + #[test] + fn a_queue_held_by_a_wait_nobody_signals_is_not_a_gpu_stall() { + let mut w = Watch::default(); + let g = 0x2000; + for t in 0..60u64 { + // F short of its signal; another queue waits on g for 9, signalled only up to 8 + let v = w.look(t * 1000, &[(F, 5, 6, 0), (g, 8, 8, 9)], Some(30_000)); + assert_eq!(v, Verdict::Fine, "at {t} s"); + } + // the title signals g (seen at 60 s): F's clock runs from the last look that saw the + // wait held (59 s) – a queue let go needs a moment + let first = (60..120u64).find(|&t| matches!(w.look(t * 1000, &[(F, 5, 6, 0), (g, 9, 9, 9)], Some(30_000)), Verdict::Report(_))); + assert_eq!(first, Some(69)); + let exit = (70..120u64).find(|&t| matches!(w.look(t * 1000, &[(F, 5, 6, 0), (g, 9, 9, 9)], Some(30_000)), Verdict::Exit(_))); + assert_eq!(exit, Some(89)); + } + + #[test] + fn a_stall_that_ends_is_forgotten() { + let mut w = Watch::default(); + for t in 0..=10u64 { + w.look(t * 1000, &[(F, 5, 6, 0)], None); + } + assert!(w.logged.is_some()); + assert_eq!(w.look(11_000, &[(F, 6, 6, 0)], None), Verdict::Fine); + assert!(w.logged.is_none()); + // a new one is reported 10 s after the fence last moved (to 6, at 11 s) + let first = (12..40u64).find(|&t| matches!(w.look(t * 1000, &[(F, 6, 7, 0)], None), Verdict::Report(_))); + assert_eq!(first, Some(21)); + } + + fn rec(hash: u64, what: What) -> Rec { + Rec { hash, threads: 64, what } + } + + #[test] + fn a_fence_idle_for_long_then_signalled_is_not_a_stall() { + let mut w = Watch::default(); + for t in 0..=40u64 { + assert_eq!(w.look(t * 1000, &[(F, 7, 7, 0)], Some(30_000)), Verdict::Fine, "idle at {t} s"); + } + // the next frame is in flight at the next look, and again at the one after + assert_eq!(w.look(41_000, &[(F, 7, 8, 0)], Some(30_000)), Verdict::Fine); + assert_eq!(w.look(42_000, &[(F, 7, 8, 0)], Some(30_000)), Verdict::Fine); + // a real hang from there still ends the title 30 s after it began (at 40 s) + let exit = (43..120u64).find(|&t| matches!(w.look(t * 1000, &[(F, 7, 8, 0)], Some(30_000)), Verdict::Exit(_))); + assert_eq!(exit, Some(70)); + } + + #[test] + fn a_gap_between_looks_is_not_counted() { + // the process stopped (or the Mac slept) for 40 s with a frame in flight + let mut w = Watch::default(); + assert_eq!(w.look(0, &[(F, 5, 6, 0)], Some(30_000)), Verdict::Fine); + assert_eq!(w.look(40_000, &[(F, 5, 6, 0)], Some(30_000)), Verdict::Fine); + // a real hang from there: its clock stood at 1 s after the gap + let exit = (41..120u64).find(|&t| matches!(w.look(t * 1000, &[(F, 5, 6, 0)], Some(30_000)), Verdict::Exit(_))); + assert_eq!(exit, Some(69)); + // a memory sampler stopping the process 5 s every 16 s: the hang still ends the title + let mut w = Watch::default(); + let (mut t, mut looks) = (0u64, 0u32); + let exit = loop { + if let Verdict::Exit(s) = w.look(t, &[(F, 5, 6, 0)], Some(30_000)) { + break (t, s.longest); + } + looks += 1; + t += if looks % 12 == 0 { 5_500 } else { 1_000 }; + assert!(t < 120_000, "no exit"); + }; + assert!(exit.0 >= 30_000 && exit.0 <= 50_000 && exit.1 >= 30_000, "{exit:?}"); + } + + #[test] + fn submissions_take_what_their_lists_noted_since_the_last_one() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if !on() { + return; + } + let (list, other) = (0x51_0000usize as *mut c_void, 0x51_1000usize as *mut c_void); + let queue = 0x51_2000usize as *mut c_void; + list_reset(list); + list_reset(other); + note(list, rec(1, What::Groups([2, 3, 1]))); + note(list, rec(2, What::Indirect { max: 1, args: Args::Own, checked: true, count: false })); + note(other, rec(3, What::Skipped)); + submitted(queue, &[list, other]); + // a list submitted and recording on + note(list, rec(4, What::Groups([1, 1, 1]))); + submitted(queue, &[list]); + // a closed list run again: what it recorded + submitted(queue, &[list]); + note_signal(queue, F, 0x1325); + let g = QUEUES.lock().unwrap_or_else(|e| e.into_inner()); + let q = &g.as_ref().unwrap()[&(queue as usize)]; + let n = q.len(); + let hashes = |s: &Sub| s.recs.iter().map(|r| r.hash).collect::>(); + assert_eq!(hashes(&q[n - 3]), vec![1, 2, 3]); + assert!(!q[n - 3].again); + assert_eq!(hashes(&q[n - 2]), vec![4]); + assert!(!q[n - 2].again); + assert_eq!(hashes(&q[n - 1]), vec![1, 2, 4]); + assert!(q[n - 1].again); + assert_eq!(q[n - 1].signals, vec![(F, 0x1325)]); + let line = describe(&q[n - 3], &|_| 0); + assert!(line.contains("0000000000000001 (64 threads): 1 × Dispatch, 6 groups (largest 2×3×1)"), "{line}"); + assert!(line.contains("0000000000000002 (64 threads): 1 × ExecuteIndirect (up to 1 command(s), arguments outside unified memory, 1 checked)"), "{line}"); + assert!(line.contains("0000000000000003 (64 threads): 1 skipped"), "{line}"); + drop(g); + // in flight: everything after the last submission whose signals completed + let lines = in_flight(&[(F, 0x1324, 0x1325, 0)]); + assert!(lines.iter().any(|l| l.contains(&format!("queue {:#x}", queue as usize))), "{lines:?}"); + assert!(lines.iter().any(|l| l.contains("– then fence") && l.contains("(not done)")), "{lines:?}"); + list_reset(list); + list_reset(other); + } + + #[test] + fn a_queue_keeps_its_last_16_submissions() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if !on() { + return; + } + let list = 0x52_0000usize as *mut c_void; + let queue = 0x52_2000usize as *mut c_void; + for k in 0..40u64 { + list_reset(list); + note(list, rec(k + 1, What::Groups([1, 1, 1]))); + submitted(queue, &[list]); + } + let g = QUEUES.lock().unwrap_or_else(|e| e.into_inner()); + let q = &g.as_ref().unwrap()[&(queue as usize)]; + assert_eq!(q.len(), QUEUE_SUBS); + assert_eq!(q.back().unwrap().recs[0].hash, 40); + assert_eq!(q.front().unwrap().recs[0].hash, 25); + drop(g); + list_reset(list); + } + + #[test] + fn a_list_keeps_its_newest_512_records_and_counts_the_rest() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if !on() { + return; + } + let list = 0x53_0000usize as *mut c_void; + let queue = 0x53_2000usize as *mut c_void; + list_reset(list); + for k in 0..600u64 { + note(list, rec(k, What::Groups([1, 1, 1]))); + } + submitted(queue, &[list]); + let g = QUEUES.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.as_ref().unwrap()[&(queue as usize)].back().unwrap(); + assert_eq!((s.recs.len(), s.more), (LIST_RECS, 88)); + // the newest are kept: the work a stopped GPU most likely was at + assert_eq!((s.recs[0].hash, s.recs[LIST_RECS - 1].hash), (88, 599)); + assert!(describe(s, &|_| 0).contains("600 dispatch(es) (88 not kept)")); + drop(g); + list_reset(list); + } + + /// A submission of a list runs the ExecuteIndirect noted since its last one; a closed list run + /// again runs all it recorded once more. + #[test] + fn a_lists_indirect_run_once_per_submission_and_all_again_when_run_again() { + let mut l = Ledger { indirect: [[1, 0, 2, 0], [0, 0, 1, 0]], ..Default::default() }; + assert_eq!(l.take_indirect(true), [[1, 0, 2, 0], [0, 0, 1, 0]], "its first submission: all of it"); + assert_eq!(l.take_indirect(false), [[1, 0, 2, 0], [0, 0, 1, 0]], "run again: all of it again"); + l.indirect[0][2] += 3; + assert_eq!(l.take_indirect(true), [[0, 0, 3, 0], [0; 4]], "recording on: what came since"); + assert_eq!(l.take_indirect(false), [[1, 0, 5, 0], [0, 0, 1, 0]], "run again: all of it"); + } + + /// The ExecuteIndirect counts by place follow the lists to their queue: a submission adds what + /// its lists run (a list run again: all again; one that records on: what is new; one reset or + /// never submitted: nothing), its `[stall]` line names the draws, and the process's counts + /// grow by what was submitted. + #[test] + fn indirect_counts_follow_the_lists_that_go_to_a_queue() { + let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if !indirect_on() { + return; + } + let (compute, draws, never) = (0x5D_0000usize as *mut c_void, 0x5D_1000usize as *mut c_void, 0x5D_2000usize as *mut c_void); + let queue = 0x5D_3000usize as *mut c_void; + for l in [compute, draws, never] { + list_reset(l); + } + let s0 = indirect_counts().unwrap(); + let ei = |args: Args| rec(7, What::Indirect { max: 1, args, checked: true, count: false }); + note(compute, ei(Args::Own)); + note(compute, ei(Args::Own)); + note(compute, ei(Args::Window(1))); + note_indirect_draw(draws, Args::Own); + for _ in 0..5 { + note(never, ei(Args::Own)); + } + assert_eq!(ledger_indirect_for_test(never), [[0, 0, 5, 0], [0; 4]]); + submitted(queue, &[compute, draws]); + // run again: what it recorded + submitted(queue, &[compute]); + // recording on: what came since (no ExecuteIndirect) + note(compute, rec(9, What::Groups([1, 1, 1]))); + submitted(queue, &[compute]); + // reset: nothing of what it recorded before + list_reset(compute); + submitted(queue, &[compute]); + let g = QUEUES.lock().unwrap_or_else(|e| e.into_inner()); + let q = &g.as_ref().unwrap()[&(queue as usize)]; + let n = q.len(); + assert_eq!(q[n - 4].indirect, [[1, 0, 2, 0], [0, 0, 1, 0]], "compute's and the draw's"); + assert!(describe(&q[n - 4], &|_| 0).contains(", 1 draw ExecuteIndirect (1 with arguments outside unified memory); "), "{}", describe(&q[n - 4], &|_| 0)); + assert_eq!(q[n - 3].indirect, [[1, 0, 2, 0], [0; 4]], "a closed list run again"); + assert!(!describe(&q[n - 3], &|_| 0).contains("draw ExecuteIndirect"), "no draws, no clause"); + assert_eq!(q[n - 2].indirect, [[0; 4]; 2], "recording on with no new ExecuteIndirect"); + assert_eq!(q[n - 1].indirect, [[0; 4]; 2], "a reset list"); + drop(g); + let s = indirect_counts().unwrap(); + let own = Args::Own.index(); + assert!(s[0][own] >= s0[0][own] + 4, "compute outside unified memory: {} → {}", s0[0][own], s[0][own]); + assert!(s[0][0] >= s0[0][0] + 2, "compute in a window: {} → {}", s0[0][0], s[0][0]); + assert!(s[1][own] >= s0[1][own] + 1, "draws outside unified memory: {} → {}", s0[1][own], s[1][own]); + for l in [compute, draws, never] { + list_reset(l); + } + } + + #[test] + fn skip_lists_take_commas_spaces_prefixes_and_either_case() { + assert_eq!( + parse_hashes("71f4ac8ad5eba33c, 0xDF231D75EE930B98;36204a134ee59578 zz,"), + vec![0x71f4_ac8a_d5eb_a33c, 0xdf23_1d75_ee93_0b98, 0x3620_4a13_4ee5_9578] + ); + assert!(parse_hashes("").is_empty()); + } + + static TEST_LOCK: Mutex<()> = Mutex::new(()); +} diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index dc5a539..610f05f 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -38,9 +38,21 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, the title's address – its bytes are read through `TitleMemory` –, layout, states) -/// of an upload -type Upload = (usize, usize, Arc, Vec); +/// (device, the title's address – its bytes are read through `TitleMemory` –, layout, states, +/// `Lazy`) of an upload +type Upload = (usize, usize, Arc, Vec, Lazy); + +/// What an upload of a lazy texture (`lazy_tex`) copies. +#[derive(Clone, Copy, Default)] +struct Lazy { + /// it is one + lazy: bool, + /// only what has no copy in its tiles yet: its memory is as at its last upload (what its + /// tiles have holds it), or the title's GPU work wrote it (what they have holds that) + fresh_only: bool, + /// the title's GPU work writes it in this submit (`Entry::writes_now`) + written: bool, +} struct Entry { device: usize, @@ -92,6 +104,21 @@ struct Entry { mapped: bool, /// the present count when it was made (unwatched: young textures have a turn of their own) made: u64, + /// a reserved texture with tiles only where the title's memory is (`lazy_tex`) + lazy: bool, + /// the PC's committed size of it (lazy: what it would take committed) – `census` + pc_bytes: u64, + /// a lazy one the title's GPU work writes in the submit it is uploaded for (a copy or a + /// resolve recorded since the last refresh): what that work writes is its content + writes_now: bool, + /// its console format (the desc's 0x20) – the view census's same-range aliases by format + format: u32, + /// it was made pending once after an upload whose run was never submitted (`Table::later`): a + /// second such upload leaves it as it is – a texture whose own run fails before its submit at + /// every try (an upload buffer of its own that cannot be made) would otherwise be detiled and + /// tried again at every submit, with those behind it in its batch, and said only for the first + /// failures + later: bool, } /// textures waiting for their first upload @@ -218,6 +245,7 @@ impl Table { self.shadowed_by_va.remove(&(old.va, res)); } for (ova, ores, oend) in self.active_overlaps(va, end) { + note_overlap(va, end, ova, oend); if !entry.placed && ova == va && oend == end && self.by_res.get(&ores).is_some_and(|e| !e.placed) { continue; } @@ -310,73 +338,132 @@ impl Table { by_res.get_mut(&res).or_else(|| shadowed.get_mut(&res)) } + /// `upload_later`'s part for texture `res` (active or shadowed), whose upload's run was never + /// submitted: pending – uploaded at the next submit, a shadowed one when it comes back (counted + /// then, `remove`) –, unless the title's GPU work wrote it (`note_gpu_write`: its CPU view is + /// stale, and uploaded now it would land over what that work wrote – such a texture is not + /// uploaded again from its memory, as `remove`'s remap keeps it), it is pending already (its turn + /// kept), or it had this turn once (`Entry::later`). The change to `PENDING`: an active one is + /// counted. + fn later(&mut self, res: usize) -> isize { + let active = self.by_res.contains_key(&res); + let Some(e) = self.get_mut(res) else { return 0 }; + if e.gpu_written || e.pending || e.later { + return 0; + } + e.later = true; + e.pending = true; + isize::from(active) + } + fn overlapping(&self, va: usize, len: usize) -> Vec<(usize, usize)> { self.active_overlaps(va, va.saturating_add(len)).into_iter().take(4).map(|(ova, ores, _)| (ores, ova)).collect() } -} -fn adjust_pending(delta: isize) { - if delta > 0 { - PENDING.fetch_add(delta as usize, Ordering::Relaxed); - } else if delta < 0 { - PENDING.fetch_sub((-delta) as usize, Ordering::Relaxed); + /// Every entry, active and shadowed, as the view census reads it. + fn snapshot(&self, out: &mut Vec) { + let kept = |(&res, e): (&usize, &Entry), shadowed: bool| Kept { res, va: e.va, size: e.tex.size(), pc: e.pc_bytes, lazy: e.lazy, shadowed }; + out.extend(self.by_res.iter().map(|x| kept(x, false))); + out.extend(self.shadowed.iter().map(|x| kept(x, true))); + } + + /// Same-range aliases of active entries (beyond the first at a range, as `census` counts them) + /// by (the first's console format, the alias's): (aliases, their PC bytes). + fn alias_pairs(&self) -> Vec<((u32, u32), u64, u64)> { + let mut pairs: std::collections::HashMap<(u32, u32), (u64, u64)> = std::collections::HashMap::new(); + let mut first: Option<((usize, usize), u32)> = None; + for (&(va, res), &end) in self.by_va.iter() { + let Some(e) = self.by_res.get(&res) else { continue }; + match first { + Some((range, format)) if range == (va, end) => { + let p = pairs.entry((format, e.format)).or_default(); + p.0 += 1; + p.1 += e.pc_bytes; + } + _ => first = Some(((va, end), e.format)), + } + } + pairs.into_iter().map(|(k, (n, b))| (k, n, b)).collect() } } -// Both immediate and deferred releases can reach the host before `forget` takes TEXTURES. -static RELEASING: Mutex> = Mutex::new(BTreeMap::new()); +/// A texture kept in step as the view census reads it (`snapshot`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Kept { + pub res: usize, + /// its title address and console bytes + pub va: usize, + pub size: u64, + /// the PC's committed size of it (a lazy one's too) + pub pc: u64, + pub lazy: bool, + /// shadowed (an older one under a newer texture at its memory), not active + pub shadowed: bool, +} -pub(super) struct ResourceRelease(usize); +/// The textures kept in step now, active and shadowed, into `out` – one walk under the table's +/// lock (the view census, every 10 s off the title's threads; `census` makes the same walk). +pub(super) fn snapshot(out: &mut Vec) { + TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).snapshot(out); +} -impl ResourceRelease { - pub(super) fn begin(res: usize) -> Self { - *RELEASING.lock().unwrap().entry(res).or_default() += 1; - Self(res) - } +/// Same-range aliases of the active textures by console format pair (`Table::alias_pairs`). +pub(super) fn alias_pairs() -> Vec<((u32, u32), u64, u64)> { + TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).alias_pairs() } -impl Drop for ResourceRelease { - fn drop(&mut self) { - let mut releasing = RELEASING.lock().unwrap(); - let count = releasing.get_mut(&self.0).unwrap(); - *count -= 1; - if *count == 0 { - releasing.remove(&self.0); - } - } +/// placements over an active texture kept in step, by how they overlap it: the same range, +/// the new one covers the old, the old covers the new, partly (`census`) +static OVERLAPS: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +fn note_overlap(va: usize, end: usize, ova: usize, oend: usize) { + let k = if (ova, oend) == (va, end) { + 0 + } else if va <= ova && oend <= end { + 1 + } else if ova <= va && end <= oend { + 2 + } else { + 3 + }; + OVERLAPS[k].fetch_add(1, Ordering::Relaxed); } -fn with_resource_reference(res: usize, add_ref: impl FnOnce() -> Option) -> Option { - let releasing = RELEASING.lock().unwrap(); - if releasing.contains_key(&res) { - return None; +fn adjust_pending(delta: isize) { + #[cfg(test)] + TEST_PENDING.with(|d| d.set(d.get() + delta)); + if delta > 0 { + PENDING.fetch_add(delta as usize, Ordering::Relaxed); + } else if delta < 0 { + PENDING.fetch_sub((-delta) as usize, Ordering::Relaxed); } - // Keep the release gate through AddRef. Native Release and cleanup run outside it. - add_ref() } -/// Acquire an owned reference while the caller holds TEXTURES. A release already in -/// progress can have destroyed the object even though its tracking entry is still present. +// Tests: this thread's changes to `PENDING` through `adjust_pending` (other tests move `PENDING` +// from their own threads). +#[cfg(test)] +thread_local! { + static TEST_PENDING: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// An owned reference to a texture of `TEXTURES`, taken while the caller holds it. On the Mac +/// (`mac`) only one whose vtable is XCL's (an adopted resource, read under Wine's guard – upstream +/// f7bcad5): none otherwise, said with `XCL_TRACE_UNWATCHED`. (A texture there is alive: what XCL +/// keeps by address is forgotten before the resource's final Release, under the deferred +/// releases' reference – `real::hooked_release`, `late_release`.) unsafe fn clone_resource(res: usize, mac: bool) -> Option { let p = res as *mut c_void; - let borrow = || ID3D12Resource::from_raw_borrowed(&p).cloned(); - if mac { - with_resource_reference(res, || { - if !super::real::is_adopted_mac_texture(p) { - if trace_unwatched() { - static REJECTS: AtomicU64 = AtomicU64::new(0); - let n = REJECTS.fetch_add(1, Ordering::Relaxed) + 1; - if n <= 4 || n.is_power_of_two() { - crate::xlog_info!("title texture trace: reference #{n} rejected for {res:#x}: no readable XCL vtable"); - } - } - return None; + if mac && !super::real::is_adopted_mac_texture(p) { + if trace_unwatched() { + static REJECTS: AtomicU64 = AtomicU64::new(0); + let n = REJECTS.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("title texture trace: reference #{n} rejected for {res:#x}: no readable XCL vtable"); } - borrow() - }) - } else { - borrow() + } + return None; } + ID3D12Resource::from_raw_borrowed(&p).cloned() } unsafe fn clone_resources(ptrs: &[usize], mac: bool) -> Vec { @@ -402,8 +489,9 @@ pub fn counts() -> (usize, u64) { (TEXTURES.lock().unwrap().by_res.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> { +/// A texture the title placed at `va` (its console desc `desc`; `pc_bytes` the PC's committed +/// size of it, 0: not known): 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, pc_bytes: u64) -> Result<(), String> { // (a new texture object, or the address of an old one again: its first upload is not left out) LAST_CONTENT.lock().unwrap().remove(&(res as usize)); let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?; @@ -450,6 +538,9 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); let size = tex.size() as usize; + if in_gpu_view && census_on() { + note_presence(va, size); + } let unwatched = crate::util::mac_host() && !is_watched(src, size); if unwatched { note_unwatched(res, src, size); @@ -478,6 +569,11 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, cpu_unmapped: false, mapped: false, made: frame_now(), + lazy: super::lazy_tex::is_lazy(res as usize), + pc_bytes, + writes_now: false, + format: u32::from_le_bytes(desc[0x20..0x24].try_into().unwrap()), + later: false, }; let to_unmap = { let mut t = TEXTURES.lock().unwrap(); @@ -517,11 +613,26 @@ fn recheck_gpu_view_sources() { return; } let mut changed = false; - // (the shadowed textures too: one comes back when the texture over it goes) + // (the shadowed textures too: one comes back when the texture over it goes – pending then, + // counted in `PENDING` as it comes back, `Table::remove`) let mut g = TEXTURES.lock().unwrap(); let t = &mut *g; - for e in t.by_res.values_mut().chain(t.shadowed.values_mut()) { - changed |= recheck_source(e); + // (a lazy texture's tiles all get the new place's bytes: `lazy_tex::resend`) + for (&res, e) in t.by_res.iter_mut() { + if recheck_source(e, true) { + changed = true; + if e.lazy { + super::lazy_tex::resend(res); + } + } + } + for (&res, e) in t.shadowed.iter_mut() { + if recheck_source(e, false) { + changed = true; + if e.lazy { + super::lazy_tex::resend(res); + } + } } drop(g); if changed { @@ -530,8 +641,9 @@ fn recheck_gpu_view_sources() { } /// `e`'s source again (a texture in a GPU view): when it changed, `e` reads the new one and is -/// uploaded at the next submit. Whether it changed. -fn recheck_source(e: &mut Entry) -> bool { +/// uploaded at the next submit (`active`: it is counted in `PENDING`; a shadowed one is when it +/// comes back). Whether it changed. +fn recheck_source(e: &mut Entry, active: bool) -> bool { if !e.in_gpu_view { return false; } @@ -543,7 +655,9 @@ fn recheck_source(e: &mut Entry) -> bool { e.unwatched = crate::util::mac_host() && !is_watched(src, e.tex.size() as usize); if !e.pending { e.pending = true; - PENDING.fetch_add(1, Ordering::Relaxed); + if active { + PENDING.fetch_add(1, Ordering::Relaxed); + } } true } @@ -556,15 +670,56 @@ fn recheck_source(e: &mut Entry) -> bool { /// that copies. pub fn note_gpu_write(res: usize) { let mut t = TEXTURES.lock().unwrap(); + let active = t.by_res.contains_key(&res); if let Some(e) = t.get_mut(res) { if !e.gpu_written { e.gpu_written = true; GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); } + if e.lazy { + back_whole(e, res, active); + } + } +} + +/// The title's GPU work writes texture `res` without making it GPU-written (a resolve into it): +/// a lazy one gets tiles for all of it first. +pub fn note_gpu_write_lazy(res: usize) { + if !super::lazy_tex::any() { + return; + } + let mut t = TEXTURES.lock().unwrap(); + let active = t.by_res.contains_key(&res); + if let Some(e) = t.get_mut(res) { + if e.lazy { + back_whole(e, res, active); + } + } +} + +/// Lazy texture `e` (`res`) is written by the title's GPU work: what has no tiles gets them, +/// and the title's memory goes up into it, at the next submit – the one of that work at the +/// latest (`active`: it is counted in `PENDING`; a shadowed one is not uploaded until it comes +/// back – its write goes nowhere, counted). +fn back_whole(e: &mut Entry, res: usize, active: bool) { + if !super::lazy_tex::force_all(res) { + return; + } + e.writes_now = true; + if !active { + SHADOWED_LAZY_WRITES.fetch_add(1, Ordering::Relaxed); + } + if !e.pending { + e.pending = true; + if active { + PENDING.fetch_add(1, Ordering::Relaxed); + } } } static GPU_WRITTEN: AtomicU64 = AtomicU64::new(0); +/// GPU writes into lazy textures that were shadowed (`back_whole`) +static SHADOWED_LAZY_WRITES: AtomicU64 = AtomicU64::new(0); /// The title unmapped texture `res` (`Map` gave it the texture's place in its memory, /// `real::res_map`): one it means to write. In memory that is not write-watched it is compared @@ -624,8 +779,8 @@ pub fn forget(res: usize) { t.deferred_remaps.remove(&res); to_remap.push(r); } else if mac { - // A non-final Release can overlap the remap too. Retry before the next - // submit if the placement is still active and has the same identity. + // no reference to take (`clone_resource`): again before the next submit while + // the placement is still active with the same identity let seq = t.by_res[&res].seq; t.deferred_remaps.insert(res, seq); } @@ -843,6 +998,14 @@ unsafe fn refresh_once(queue: *mut c_void) { } retry_deferred_remaps(); recheck_gpu_view_sources(); + // lazy textures some of whose groups got no tiles, that their pool can serve now (uploaded + // first, below); one not uploaded now is not tried again for them + let woken = super::lazy_tex::retries(); + for &res in &woken { + if !make_pending(res) { + super::lazy_tex::forget_short(res); + } + } let watch_t0 = std::time::Instant::now(); let mut page = 0x1000u32; let ranges = cached_watch_ranges(u); @@ -930,24 +1093,39 @@ unsafe fn refresh_once(queue: *mut c_void) { dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) }) .filter_map(|(&res, e)| { - // A pending unwatched texture can retry next submit if a Release is in flight. + // (a texture no reference can be taken of – `clone_resource` – stays pending for the + // next submit; upstream 692d902) let r = clone_resource(res, on_mac && e.unwatched)?; + // (its memory as at its last upload: a lazy texture's tiles hold it – only what has + // none, or no copy yet, is copied) + let mut unchanged = false; if e.pending { e.pending = false; PENDING.fetch_sub(1, Ordering::Relaxed); if e.unwatched { // what goes up now is what later looks compare with - e.sent = memory_hash(e.va, e.tex.size() as usize); + let h = memory_hash(e.va, e.tex.size() as usize); + unchanged = h == e.sent; + e.sent = h; + } else { + let i = dirty.partition_point(|&p| p + page as usize <= e.src); + unchanged = !dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize); } } + let lazy = Lazy { lazy: e.lazy, fresh_only: e.lazy && (e.gpu_written || unchanged), written: e.lazy && std::mem::take(&mut e.writes_now) }; let source = if on_mac { e.va } else { e.src }; - Some((r, (e.device, source, Arc::clone(&e.tex), e.states.clone()))) + Some((r, (e.device, source, Arc::clone(&e.tex), e.states.clone(), lazy))) }) .collect() }); // (a texture in both lists goes once) todo.retain(|(r, _)| !first.iter().any(|(f, _)| f.as_raw() == r.as_raw())); todo.extend(first); + // the woken lazy textures first, oldest first: the free tiles were counted out for them + if !woken.is_empty() { + let rank: std::collections::HashMap = woken.iter().enumerate().map(|(k, &r)| (r, k)).collect(); + todo.sort_by_key(|(r, _)| rank.get(&(r.as_raw() as usize)).copied().unwrap_or(usize::MAX)); + } upload_all(todo); } @@ -1282,29 +1460,44 @@ unsafe fn poll_unwatched() -> Vec<(ID3D12Resource, Upload)> { let d = r.GetDesc(); crate::xlog_info!("title texture trace: content of the texture at {:#x} ({}x{} format {}, {} bytes) changed – upload #{k}, frame {frame}", e.va, d.Width, d.Height, d.Format.0, e.tex.size()); } - Some((r, (e.device, e.va, Arc::clone(&e.tex), e.states.clone()))) + Some((r, (e.device, e.va, Arc::clone(&e.tex), e.states.clone(), Lazy { lazy: e.lazy, ..Lazy::default() }))) }) .collect() } -/// Cap both the staging bytes and the number of copies in a single upload list. -const BATCH_BYTES: usize = 32 << 20; +/// Textures of one upload list at most (upstream: a list holds a bounded number of copies); its +/// bytes are bounded by `texture::batch_bytes()`. const BATCH_ITEMS: usize = 256; -/// An empty batch accepts its first texture even if it exceeds the byte cap. -fn batch_fits(count: usize, bytes: usize, device: usize, next_device: usize, next_bytes: usize) -> bool { - count == 0 - || (count < BATCH_ITEMS - && device == next_device - && bytes.saturating_add(next_bytes) <= BATCH_BYTES) +/// Whether a texture of `next_bytes` on `next_device` joins a batch of `count` textures and `bytes` +/// on `device`: at most `BATCH_ITEMS` textures of one device and `cap` bytes – an empty batch takes +/// its first texture even past the cap. +fn batch_fits(count: usize, bytes: usize, device: usize, next_device: usize, next_bytes: usize, cap: usize) -> bool { + count == 0 || (count < BATCH_ITEMS && device == next_device && bytes.saturating_add(next_bytes) <= cap) } -/// The uploads `todo`, in bounded batches with one list and one wait each. +/// The uploads `todo`, in batches of up to `texture::batch_bytes()` of console memory – the upload +/// staging cap, 128 MiB (`XCL_UPLOAD_STAGING_MB`; 256 MiB before 0023.2) – and `BATCH_ITEMS` +/// textures, each in runs of at most the cap on the PC (one list and one wait each: +/// `texture::upload_batch_masked_run`). unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { static N: AtomicU64 = AtomicU64::new(0); if todo.is_empty() { return; } + for (r, u) in &todo { + if crate::hle::kernelx::traced_range(u.1, 1) { + let (data, all) = read_memory(u.1, (u.2.size() as usize).min(0x1_0000)); + crate::xlog_info!( + "[trace] title texture upload into {:p} from {:#x} ({} bytes): {} non-zero in its first {} (all there {all})", + r.as_raw(), + u.1, + u.2.size(), + data.iter().filter(|&&b| b != 0).count(), + data.len() + ); + } + } let t0 = std::time::Instant::now(); UPLOAD_BYTES.fetch_add(todo.iter().map(|(_, u)| u.2.size()).sum::(), Ordering::Relaxed); upload_batches(todo, &N); @@ -1322,21 +1515,39 @@ unsafe fn upload_batches(todo: Vec<(ID3D12Resource, Upload)>, warned: &AtomicU64 crate::xlog_warn!("title texture: upload failed: {e}"); } }; + // where the title's memory has pages (lazy textures: which of their groups get tiles) + let mut presence = TitleMemory::quiet(); + // console bytes of one batch at most (the upload staging cap: a batch's PC bytes can be more, + // and its upload goes in runs of at most the cap) + let batch_bytes = texture::batch_bytes(); let mut todo = todo.into_iter().peekable(); while todo.peek().is_some() { - let mut picked = Vec::new(); + let mut picked: Vec = Vec::new(); + // a lazy texture's groups to have tiles, and what it copies + let mut wants: Vec<(Option>, Lazy)> = Vec::new(); let mut bytes = 0usize; let mut device = 0usize; - while let Some((_, (dev, _, tex, _))) = todo.peek() { - if !batch_fits(picked.len(), bytes, device, *dev, tex.size() as usize) { + while let Some((_, (dev, _, tex, _, _))) = todo.peek() { + if !batch_fits(picked.len(), bytes, device, *dev, tex.size() as usize, batch_bytes) { break; } - let (r, (dev, va, tex, states)) = todo.next().unwrap(); + let (r, (dev, va, tex, states, lazy)) = todo.next().unwrap(); + // a lazy texture: which groups are to have tiles – none (nothing of its memory is + // there), or it is no longer one (released meanwhile, `lazy_tex::forget`: its tiles + // may be another texture's already): nothing to upload + let want = if lazy.lazy { super::lazy_tex::wanted(r.as_raw() as usize, va, &mut |p| presence.has_memory(p)) } else { None }; + if lazy.lazy && want.as_ref().is_none_or(|w| !w.iter().any(|&b| b)) { + super::lazy_tex::note_left_out(tex.size()); + super::lazy_tex::forget_short(r.as_raw() as usize); + continue; + } // The same bytes as at this texture's last upload: nothing to do. The write watch is // per page and a title writes next to its textures (and rewrites what it wrote): a // retail title's video planes and UI targets went up again for every submit, ~25 MB - // a presented frame where ~3 MB had changed, and the submits waited here. - if unchanged_skip() { + // a presented frame where ~3 MB had changed, and the submits waited here. (Not a + // lazy one: its upload may be to give tiles to what has none – the title's GPU work + // writes it, or tiles came short last time – with its memory as it was.) + if !lazy.lazy && unchanged_skip() { let h = content_hash(&title_bytes(va, tex.size() as usize)); if same_as_last_upload(r.as_raw() as usize, h) { let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; @@ -1349,18 +1560,11 @@ unsafe fn upload_batches(todo: Vec<(ID3D12Resource, Upload)>, warned: &AtomicU64 device = dev; bytes += tex.size() as usize; picked.push((r, va, tex, states)); + wants.push((want, lazy)); } if picked.is_empty() { continue; } - let subs = subresources_of_all(&picked, bytes); - let mut batch = Vec::with_capacity(picked.len()); - for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { - if super::present::trace_frame() { - note_content(va, &r, &subs); - } - batch.push((r, subs, states)); - } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; let queue = match upload_queue(dev, device) { @@ -1370,21 +1574,188 @@ unsafe fn upload_batches(todo: Vec<(ID3D12Resource, Upload)>, warned: &AtomicU64 continue; } }; - match own_work(|| { - super::vram::before_execute(&queue); - texture::upload_batch(dev, &queue, &batch) - }) { - Ok(failed) => { - for (_, e) in failed { - warn(&e); + // lazy textures: tiles for what is to have them, mapped on this queue before the copies + // (on the same queue: they see them) + let backed = own_work(|| { + let lazy: Vec<(&ID3D12Resource, Option<&[bool]>)> = picked.iter().zip(&wants).map(|((r, _, _, _), (w, _))| (r, w.as_deref())).collect(); + super::lazy_tex::back(dev, &queue, &lazy) + }); + // what each copies: all of it; a lazy one what has tiles – what has no copy yet when its + // memory is as at its last upload or the title's GPU work wrote it; nothing to copy: not + // detiled, staged nor waited for + let mut items: Vec<(Picked, Option>, Lazy)> = Vec::with_capacity(picked.len()); + for ((p, (_, lazy)), b) in picked.into_iter().zip(wants).zip(backed) { + let mask = if lazy.fresh_only { b.fresh } else { b.subs }; + if mask.as_ref().is_some_and(|m| !m.iter().any(|&x| x)) { + continue; + } + items.push((p, mask, lazy)); + } + if !items.is_empty() { + upload_items(dev, &queue, items, &warn, true); + } + } +} + +/// A texture picked for an upload: (resource, the title's address, layout, states). +type Picked = (ID3D12Resource, usize, Arc, Vec); + +/// One batch of uploads (`items`: texture, subresources to copy – None: all –, what it is). A +/// lazy texture whose copy failed is tried once more at once (`again`): its new tiles hold what +/// textures before it left there, and the title's GPU work may write into it after this submit; +/// one that fails twice is uploaded at the next submit (twice at most) – one the title's GPU work +/// writes is not (its memory would go over what that work wrote). One that is not lazy, of a run +/// never submitted, is uploaded at the next submit, once – not one the title's GPU work wrote +/// (`upload_later`). +unsafe fn upload_items(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: Vec<(Picked, Option>, Lazy)>, warn: &dyn Fn(&str), again: bool) { + let bytes: usize = items.iter().map(|((_, _, tex, _), _, _)| tex.size() as usize).sum(); + let masks: Vec>> = items.iter().map(|(_, m, _)| m.clone()).collect(); + let picked: Vec<&Picked> = items.iter().map(|(p, _, _)| p).collect(); + let subs = subresources_of_all(&picked, &masks, bytes); + let mut batch = Vec::with_capacity(items.len()); + for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { + if super::present::trace_frame() { + note_content(*va, r, &subs); + } + batch.push((r.clone(), subs, states.clone())); + } + // (`executed` with an error: the copies were submitted – a wait that timed out, a Signal that + // failed, in the batch's last run: they land in the queue's order, before any later upload; + // nothing is tried again. Such a failure in a run before the last gives the textures of the + // runs after it – never submitted – as failed: `texture::upload_batch_masked_run`) + let mut executed = false; + // (those of the failed whose run was never submitted: `after_upload`) + let mut unsent = Vec::new(); + let failed: Vec = match own_work(|| { + super::vram::before_execute(queue); + texture::upload_batch_masked_run(dev, queue, &batch, &masks, &mut executed) + }) { + Ok(failed) => { + for (_, e) in &failed { + warn(e); + } + UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); + unsent = failed.iter().filter(|(_, e)| texture::never_submitted(e)).map(|&(k, _)| k).collect(); + failed.into_iter().map(|(k, _)| k).collect() + } + Err(e) if executed => { + warn(&e); + Vec::new() + } + Err(e) => { + warn(&e); + (0..batch.len()).collect() + } + }; + let mut retry = Vec::new(); + let mut mapped_uncopied = false; + for (k, item) in items.into_iter().enumerate() { + let res = item.0 .0.as_raw() as usize; + let lazy = item.2; + let what = after_upload(failed.contains(&k), unsent.contains(&k), lazy, item.1.is_some(), again); + if matches!(what, AfterUpload::Retry | AfterUpload::DropUncopied | AfterUpload::FailedUpload) { + mapped_uncopied = true; + } + match what { + AfterUpload::Copied => { + #[cfg(test)] + note_test_upload(res); + if lazy.lazy { + super::lazy_tex::copied(res); + } + } + AfterUpload::Retry => retry.push(item), + AfterUpload::DropUncopied => super::lazy_tex::drop_uncopied(res), + AfterUpload::FailedUpload => { + if super::lazy_tex::failed_upload(res, !lazy.fresh_only) { + make_pending(res); } - UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); } - Err(e) => warn(&e), + AfterUpload::Later => upload_later(res), + AfterUpload::Nothing => {} } } + if !retry.is_empty() { + upload_items(dev, queue, retry, warn, false); + } else if mapped_uncopied && !again { + // (tiles were mapped on this queue with no copy after them that was waited for: the + // title's work after this submit is to see them mapped) + let _ = own_work(|| texture::wait(dev, queue)); + } +} + +/// What becomes of an item of an upload batch after it (`upload_items`): `failed` – its copy failed, +/// `never_submitted` – because its run was never submitted (`texture::never_submitted`), `masked` – it +/// had a mask of what to copy, `again` – a failed lazy one may be tried once more at once. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum AfterUpload { + /// copied (a lazy one's tiles hold its copy) + Copied, + /// a lazy one tried again at once, on a fresh uploader + Retry, + /// a lazy one the title's GPU work writes: its uncopied tiles let go + DropUncopied, + /// a lazy one: `lazy_tex::failed_upload`, and pending again if it says so + FailedUpload, + /// not a lazy one, of a run never submitted: uploaded at the next submit (`upload_later`) – at + /// HEAD its copies were in the one list submitted and landed; with nothing done it would keep + /// stale texels until the title wrote its memory again (its pending flag was cleared when it was + /// picked, and on a Mac the unwatched look brings it back only when its bytes change). Once, and + /// not one the title's GPU work wrote: that one keeps what the GPU wrote (`Table::later`) + Later, + /// nothing (a layout failure: it would fail again at every submit) + Nothing, +} + +fn after_upload(failed: bool, never_submitted: bool, lazy: Lazy, masked: bool, again: bool) -> AfterUpload { + match () { + _ if !failed => AfterUpload::Copied, + _ if lazy.lazy && masked && again => AfterUpload::Retry, + _ if lazy.lazy && masked && lazy.written => AfterUpload::DropUncopied, + _ if lazy.lazy && masked => AfterUpload::FailedUpload, + _ if !lazy.lazy && never_submitted => AfterUpload::Later, + _ => AfterUpload::Nothing, + } } +/// Texture `res`, whose upload's run was never submitted, uploaded at the next submit: pending – +/// once, and not one the title's GPU work wrote, which keeps what that work wrote (`Table::later`) +/// –, and its last upload's content forgotten (off a Mac the unchanged-content skip would take the +/// failed attempt's hash for an upload done). +fn upload_later(res: usize) { + LAST_CONTENT.lock().unwrap().remove(&res); + let delta = TEXTURES.lock().unwrap().later(res); + adjust_pending(delta); +} + +/// Texture `res` (if kept in step) is uploaded at the next submit – a shadowed one when it comes +/// back (`PENDING` counts it then, `Table::remove`). Whether it is active (uploaded now). +fn make_pending(res: usize) -> bool { + let mut t = TEXTURES.lock().unwrap(); + let active = t.by_res.contains_key(&res); + let Some(e) = t.get_mut(res) else { return false }; + if !e.pending { + e.pending = true; + if active { + PENDING.fetch_add(1, Ordering::Relaxed); + } + } + active +} + +/// Tests: uploads done per texture. +#[cfg(test)] +static TEST_UPLOADS: Mutex> = Mutex::new(BTreeMap::new()); + +#[cfg(test)] +fn note_test_upload(res: usize) { + *TEST_UPLOADS.lock().unwrap().entry(res).or_default() += 1; +} + +#[cfg(test)] +fn test_uploads(res: usize) -> u32 { + TEST_UPLOADS.lock().unwrap().get(&res).copied().unwrap_or(0) +} /// `XCL_TRACE_FRAME`: how much of a title texture's top level is not zero, each time it is /// uploaded (the first 48 uploads of textures of 64x64 and more). fn note_content(va: usize, r: &ID3D12Resource, subs: &[texture::Subresource]) { @@ -1420,7 +1791,7 @@ pub unsafe fn probe_gpu_content(res: usize) { let d = device as *mut c_void; let r = res as *mut c_void; let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&d), ID3D12Resource::from_raw_borrowed(&r)) else { return }; - let rd = r.GetDesc(); + let rd = texture::copyable_desc(r); let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); dev.GetCopyableFootprints(&rd, 0, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); @@ -1494,11 +1865,6 @@ pub unsafe fn probe_gpu_content(res: usize) { } } -/// XCL's upload queues made so far. -pub(super) fn upload_queues() -> Vec { - QUEUES.lock().unwrap().values().cloned().collect() -} - /// XCL's queue for uploads on `dev`. unsafe fn upload_queue(dev: &ID3D12Device, device: usize) -> Result { let mut q = QUEUES.lock().unwrap(); @@ -1624,17 +1990,17 @@ const PARALLEL_BYTES: usize = 1 << 20; /// `subresources` of every texture of a batch (`bytes` of them), in order: on several threads /// when the batch is big. They were read and detiled one after another in the title's own /// submit – most of a retail game's render thread while it streamed textures the CPU writes. -unsafe fn subresources_of_all(picked: &[(ID3D12Resource, usize, Arc, Vec)], bytes: usize) -> Vec> { - let picked: Vec<(usize, &xg::Texture)> = picked.iter().map(|(_, va, tex, _)| (*va, &**tex)).collect(); +unsafe fn subresources_of_all(picked: &[&Picked], masks: &[Option>], bytes: usize) -> Vec> { + let picked: Vec<(usize, &xg::Texture, Option<&[bool]>)> = picked.iter().enumerate().map(|(k, (_, va, tex, _))| (*va, &**tex, masks.get(k).and_then(|m| m.as_deref()))).collect(); let threads = if bytes < PARALLEL_BYTES { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8) }; subresources_on(&picked, threads) } -/// `subresources` of each (address, texture), in order, on up to `threads` threads. -unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> Vec> { +/// `subresources_masked` of each (address, texture, mask), in order, on up to `threads` threads. +unsafe fn subresources_on(picked: &[(usize, &xg::Texture, Option<&[bool]>)], threads: usize) -> Vec> { let threads = threads.min(picked.len()); if threads <= 1 { - return picked.iter().map(|&(va, tex)| subresources(va, tex)).collect(); + return picked.iter().map(|&(va, tex, mask)| subresources_masked(va, tex, mask)).collect(); } // the next texture to take; each thread hands back (index, subresources) let next = std::sync::atomic::AtomicUsize::new(0); @@ -1646,9 +2012,9 @@ unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> V let mut mine = Vec::new(); loop { let k = next.fetch_add(1, Ordering::Relaxed); - let Some(&(va, tex)) = picked.get(k) else { break }; + let Some(&(va, tex, mask)) = picked.get(k) else { break }; // SAFETY: as in the serial path – the title's memory is only read - mine.push((k, unsafe { subresources(va, tex) })); + mine.push((k, unsafe { subresources_masked(va, tex, mask) })); } mine }) @@ -1683,6 +2049,22 @@ pub(super) unsafe fn read_memory(at: usize, len: usize) -> (Vec, bool) { (out, all) } +/// Local fix: the title texture whose console memory covers all of `[va, va + len)` – its PC +/// resource, the title's address of it and its console layout – for a copy out of it that has +/// to see what the GPU drew there (render targets and UAVs are not marked `gpu_written`). +pub(super) fn covering(va: usize, len: usize) -> Option<(ID3D12Resource, usize, Arc)> { + let end = va.checked_add(len)?; + let t = TEXTURES.lock().unwrap(); + for (&res, e) in t.by_res.iter() { + if e.va <= va && end <= e.va.saturating_add(e.tex.size() as usize) { + let p = res as *mut c_void; + let r = unsafe { ID3D12Resource::from_raw_borrowed(&p) }?.clone(); + return Some((r, e.va, Arc::clone(&e.tex))); + } + } + None +} + /// Whether a title texture the GPU wrote lies over `[va, va + len)`: the memory there is stale. pub(super) fn gpu_written_over(va: usize, len: usize) -> bool { TEXTURES.lock().unwrap().by_res.values().any(|e| e.gpu_written && e.va < va + len && va < e.va + e.tex.size() as usize) @@ -1732,6 +2114,122 @@ pub fn view_sources() -> Option { )) } +/// Whether the census is kept (`XCL_ACTIVITY`, which logs it): what it alone needs is not done +/// otherwise (a walk of a new texture's pages, the PC's size of it). +pub(super) fn census_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("XCL_ACTIVITY").is_some()) +} + +/// GPU-view textures by how much of their memory had pages when they were made – none, some, +/// all –: (count, console bytes) each (`census`) +static PRESENCE: [[AtomicU64; 2]; 3] = [const { [const { AtomicU64::new(0) }; 2] }; 3]; + +fn note_presence(va: usize, size: usize) { + let (with, all) = pages_present(va, size); + let k = if with == 0 { + 0 + } else if with < all { + 1 + } else { + 2 + }; + PRESENCE[k][0].fetch_add(1, Ordering::Relaxed); + PRESENCE[k][1].fetch_add(size as u64, Ordering::Relaxed); +} + +/// (64 KiB pages of `[va, va + len)` with memory – an upload reads something there –, its +/// pages) +pub(super) fn pages_present(va: usize, len: usize) -> (usize, usize) { + let mut m = TitleMemory::quiet(); + let (mut with, mut all) = (0, 0); + let end = va.saturating_add(len); + let mut p = va & !(TitleMemory::PAGE - 1); + while p < end { + all += 1; + if unsafe { m.has_memory(p) } { + with += 1; + } + p += TitleMemory::PAGE; + } + (with, all) +} + +/// The textures kept in step now, as text (`XCL_ACTIVITY`): active and shadowed ones (count, +/// MB on the console, MB the PC commits for them – a lazy one's committed size too), the lazy +/// among them, same-range aliases beyond the first, GPU-written, pending (and `PENDING`); how +/// much memory GPU-view textures had when they were made; how placements overlapped. +pub fn census() -> String { + let mb = |b: u64| b >> 20; + let mut active = [0u64; 3]; + let mut shadowed = [0u64; 3]; + let (mut lazy, mut lazy_pc, mut gpu_written, mut pending, mut extra, mut extra_pc) = (0u64, 0u64, 0u64, 0u64, 0u64, 0u64); + { + let t = TEXTURES.lock().unwrap(); + for e in t.by_res.values() { + active[0] += 1; + active[1] += e.tex.size(); + active[2] += e.pc_bytes; + if e.pending { + pending += 1; + } + if e.lazy { + lazy += 1; + lazy_pc += e.pc_bytes; + } + if e.gpu_written { + gpu_written += 1; + } + } + for e in t.shadowed.values() { + shadowed[0] += 1; + shadowed[1] += e.tex.size(); + shadowed[2] += e.pc_bytes; + if e.lazy { + lazy += 1; + lazy_pc += e.pc_bytes; + } + if e.gpu_written { + gpu_written += 1; + } + } + // (active entries at one address all end alike: active ranges are disjoint but for + // same-range aliases) + let mut last = None; + for (&(va, res), &end) in t.by_va.iter() { + if last == Some((va, end)) { + extra += 1; + extra_pc += t.by_res.get(&res).map_or(0, |e| e.pc_bytes); + } + last = Some((va, end)); + } + } + let l = |a: &AtomicU64| a.load(Ordering::Relaxed); + format!( + "title textures: {} active ({} MB on the console, {} MB on the PC), {} shadowed ({} MB, {} MB), {lazy} lazy ({} MB committed), {extra} same-range aliases beyond the first ({} MB), {gpu_written} GPU-written, {pending} pending ({} counted); made in GPU views with memory for none of it {} ({} MB), some {} ({} MB), all {} ({} MB); placed over another: same range {}, covering it {}, inside it {}, partly {}; GPU writes into shadowed lazy ones {}", + active[0], + mb(active[1]), + mb(active[2]), + shadowed[0], + mb(shadowed[1]), + mb(shadowed[2]), + mb(lazy_pc), + mb(extra_pc), + PENDING.load(Ordering::Relaxed), + l(&PRESENCE[0][0]), + mb(l(&PRESENCE[0][1])), + l(&PRESENCE[1][0]), + mb(l(&PRESENCE[1][1])), + l(&PRESENCE[2][0]), + mb(l(&PRESENCE[2][1])), + l(&OVERLAPS[0]), + l(&OVERLAPS[1]), + l(&OVERLAPS[2]), + l(&OVERLAPS[3]), + l(&SHADOWED_LAZY_WRITES), + ) +} + /// Bytes of the title's memory for an upload or a comparison. In a GPU view of the title's /// memory (addresses the CPU never has anything at: a retail game places its streamed textures /// and video planes there) a 64 KiB page is read @@ -1751,13 +2249,31 @@ struct TitleMemory { direct: (usize, usize, bool), /// the same for the place of a view's page source: (usize, usize, bool), + /// the pages' places are not counted (`view_sources`: what uploads read) + quiet: bool, } impl TitleMemory { const PAGE: usize = crate::hle::kernelx::PHYS_PAGE_SIZE; fn new() -> TitleMemory { - TitleMemory { page: (usize::MAX, Place::Own), direct: (0, 0, false), source: (0, 0, false) } + TitleMemory { page: (usize::MAX, Place::Own), direct: (0, 0, false), source: (0, 0, false), quiet: false } + } + + /// One that only looks (presence of pages for `lazy_tex`, the census). + fn quiet() -> TitleMemory { + TitleMemory { quiet: true, ..TitleMemory::new() } + } + + /// Whether the 64 KiB page at `page` has memory anywhere – an upload reads something there + /// (a GPU view's page nowhere reads as zero). + unsafe fn has_memory(&mut self, page: usize) -> bool { + let page = page & !(Self::PAGE - 1); + match self.place(page) { + Place::At(_) => true, + Place::Nowhere => false, + Place::Own => Self::region(&mut self.direct, page).1, + } } /// The region around `a` (kept in `cache`): its end and whether it can be read. @@ -1796,8 +2312,10 @@ impl TitleMemory { _ => (Place::Nowhere, BY_NONE), }, }; - VIEW_READS[how].fetch_add(1, Ordering::Relaxed); - VIEW_PAGES.lock().unwrap().insert(page, how as u8); + if !self.quiet { + VIEW_READS[how].fetch_add(1, Ordering::Relaxed); + VIEW_PAGES.lock().unwrap().insert(page, how as u8); + } place } @@ -1843,6 +2361,12 @@ impl TitleMemory { /// Every subresource (D3D12 order) of a texture from the title's memory at `va`. unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { + subresources_masked(va, tex, None) +} + +/// `subresources`, those `mask` leaves out (a 2D texture's) with no texels – not read nor +/// detiled: the upload does not copy them (`texture::upload_batch_masked`). +unsafe fn subresources_masked(va: usize, tex: &xg::Texture, mask: Option<&[bool]>) -> Vec { let Some(tex) = tex.texels() else { return Vec::new() }; let c = &tex.chain; let bpe = tex.bpe as usize; @@ -1850,11 +2374,17 @@ unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { let mem = title_bytes(va, tex.size() as usize); return c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(&mem, i) }).collect(); } - let mut out = Vec::with_capacity(tex.array as usize * c.levels.len()); + let n = c.levels.len(); + let wanted = |k: usize| mask.is_none_or(|m| m.get(k).copied().unwrap_or(false)); + let mut out = Vec::with_capacity(tex.array as usize * n); for s in 0..tex.array as usize { - let slice = title_bytes(va + s * c.slice_bytes, c.slice_bytes); + let slice = (0..n).any(|i| wanted(s * n + i)).then(|| title_bytes(va + s * c.slice_bytes, c.slice_bytes)); for (i, l) in c.levels.iter().enumerate() { - out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(&slice, i, s) }); + let data = match &slice { + Some(slice) if wanted(s * n + i) => c.detile_level(slice, i, s), + _ => Vec::new(), + }; + out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data }); } } out @@ -1865,25 +2395,6 @@ unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { mod tests { use super::*; - #[test] - fn uploads_do_not_acquire_references_during_resource_release() { - let res = 0x5445_5800usize; - let other = res + 8; - assert_eq!(with_resource_reference(res, || { - assert!(matches!(RELEASING.try_lock(), Err(std::sync::TryLockError::WouldBlock))); - Some(1) - }), Some(1)); - let title = ResourceRelease::begin(res); - let worker = ResourceRelease::begin(res); - let reject = || with_resource_reference::<()>(res, || panic!("AddRef during Release")); - assert_eq!(reject(), None); - assert_eq!(with_resource_reference(other, || Some(2)), Some(2)); - drop(title); - assert_eq!(reject(), None); - drop(worker); - assert_eq!(with_resource_reference(res, || Some(3)), Some(3)); - } - /// A texture is left out only when its memory hashes as at its own last upload, and a /// texture that was forgotten (released, or its address registered again) is uploaded again. #[test] @@ -1913,6 +2424,210 @@ mod tests { forget(b); } + /// C-F3: what becomes of an upload batch's items (`after_upload`): the copied ones are; a failed + /// lazy one with a mask is tried again at once (`again`), else let go of (written) or handed to + /// lazy_tex, as before; a failed one that is not lazy is uploaded at the next submit when its run + /// was never submitted – not after a layout failure, which would fail again. `upload_later` + /// forgets its last upload's content (the unchanged-content skip off a Mac would take the failed + /// attempt for an upload done). Texture 0x7A1E_C301 (no entry: only the content is looked at). + #[test] + fn items_of_runs_never_submitted_are_uploaded_at_the_next_submit() { + use AfterUpload::*; + let plain = Lazy::default(); + let lazy = Lazy { lazy: true, ..Default::default() }; + let written = Lazy { lazy: true, written: true, ..Default::default() }; + for unsent in [false, true] { + for again in [false, true] { + assert_eq!(after_upload(false, unsent, plain, false, again), Copied); + assert_eq!(after_upload(false, unsent, lazy, true, again), Copied); + assert_eq!(after_upload(true, unsent, lazy, true, again), if again { Retry } else { FailedUpload }, "lazy"); + assert_eq!(after_upload(true, unsent, written, true, again), if again { Retry } else { DropUncopied }, "lazy, written"); + assert_eq!(after_upload(true, unsent, plain, false, again), if unsent { Later } else { Nothing }, "not lazy"); + assert_eq!(after_upload(true, unsent, plain, true, again), if unsent { Later } else { Nothing }, "not lazy, with a mask"); + assert_eq!(after_upload(true, unsent, lazy, false, again), Nothing, "lazy without a mask: as before"); + } + } + let res = 0x7A1E_C301usize; + let h = content_hash(&[7u8; 64]); + assert!(!same_as_last_upload(res, h) && same_as_last_upload(res, h), "its upload's content remembered"); + upload_later(res); + assert!(!same_as_last_upload(res, h), "forgotten: the next upload is not left out"); + forget(res); + } + + /// R2-F1: `upload_later`'s part (`Table::later`). A texture of an upload run never submitted is + /// pending for the next submit – counted when active; shadowed, counted only when it comes back + /// (`remove`) – once: after its pick, a second such upload leaves it as it is. One pending already + /// stays as it is and keeps its turn; one the title's GPU work wrote is never made pending (its CPU + /// view would go up over what that work wrote) and keeps its turn too; one not kept in step is + /// nothing. First on a table of the test's own; then through `upload_later` on the process's: a + /// GPU-written texture and a CPU-filled one, held there under REFRESH (no refresh picks the + /// stand-ins – never dereferenced – while one is pending) and forgotten before it is let go, the + /// assertions after it (one failing under REFRESH would poison it for the other tests' submits); + /// `PENDING` by this thread's changes (`TEST_PENDING`: other tests move it from theirs). + /// Stand-ins 0x7A1E_C302 to 0x7A1E_C309 at 0x7A1E_C302_0000 and up. + #[test] + fn a_texture_of_a_run_never_submitted_is_pending_once_and_never_over_what_the_gpu_wrote() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + assert_eq!(tex.size(), 0x4000); + let entry = |va: usize, gpu_written: bool| Entry { device: 0, va, src: va, in_gpu_view: false, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written, placed: false, unmapped: false, seq: 0, unwatched: false, sent: 0, changed: 0, dynamic: false, cpu_unmapped: false, mapped: false, made: 0, lazy: false, pc_bytes: 0, writes_now: false, format: 0, later: false }; + let flags = |t: &Table, r: usize| t.by_res.get(&r).or_else(|| t.shadowed.get(&r)).map(|e| (e.pending, e.later)); + let base = 0x7A1E_C302_0000usize; + let (a, b, g, s, over, none) = (0x7A1E_C302usize, 0x7A1E_C303usize, 0x7A1E_C304usize, 0x7A1E_C305usize, 0x7A1E_C306usize, 0x7A1E_C307usize); + let mut t = Table::new(); + // a CPU-filled active one: pending, counted, its turn taken + assert_eq!(t.insert(a, entry(base, false)).0, 0); + assert_eq!(t.later(a), 1, "active: counted"); + assert_eq!(flags(&t, a), Some((true, true)), "active: pending, its turn taken"); + assert_eq!(t.later(a), 0, "pending already: as it is"); + assert_eq!(flags(&t, a), Some((true, true))); + // picked (the refresh clears pending), and its run again never submitted: left as it is + t.by_res.get_mut(&a).unwrap().pending = false; + assert_eq!(t.later(a), 0, "once"); + assert_eq!(flags(&t, a), Some((false, true)), "once: not pending again"); + // one pending already (made since the last submit): as it is, its turn kept for after its pick + let mut fresh = entry(base + 0x1_0000, false); + fresh.pending = true; + assert_eq!(t.insert(b, fresh).0, 1); + assert_eq!(t.later(b), 0, "pending already"); + assert_eq!(flags(&t, b), Some((true, false)), "pending already: its turn kept"); + t.by_res.get_mut(&b).unwrap().pending = false; + assert_eq!(t.later(b), 1, "its turn after its pick"); + assert_eq!(flags(&t, b), Some((true, true))); + // one the title's GPU work wrote: never pending, its turn not taken + assert_eq!(t.insert(g, entry(base + 0x2_0000, true)).0, 0); + assert_eq!(t.later(g), 0, "GPU-written: not counted"); + assert_eq!(flags(&t, g), Some((false, false)), "GPU-written: what the GPU wrote kept"); + // a shadowed one (a texture over part of it): pending, not counted – counted when it comes back + assert_eq!(t.insert(s, entry(base + 0x3_0000, false)).0, 0); + assert_eq!(t.insert(over, entry(base + 0x3_0800, true)).0, 0); + assert!(t.shadowed.contains_key(&s), "shadowed"); + assert_eq!(t.later(s), 0, "shadowed: not counted"); + assert_eq!(flags(&t, s), Some((true, true)), "shadowed: pending"); + assert_eq!(t.remove(over).1, 1, "counted when it comes back"); + assert!(t.by_res.contains_key(&s), "back"); + // not kept in step: nothing + assert_eq!(t.later(none), 0); + assert_eq!(flags(&t, none), None, "not kept: no entry made"); + // through `upload_later`, on the process's table + let (gw, cpu) = (0x7A1E_C308usize, 0x7A1E_C309usize); + let mine = || TEST_PENDING.with(|d| d.get()); + let now = |r: usize| flags(&TEXTURES.lock().unwrap(), r); + let seen = { + let _refresh = REFRESH.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut tt = TEXTURES.lock().unwrap(); + tt.insert(gw, entry(base + 0x4_0000, true)); + tt.insert(cpu, entry(base + 0x5_0000, false)); + TEXTURES_LEN.store(tt.by_res.len(), Ordering::Relaxed); + } + let d0 = mine(); + upload_later(gw); + let (d1, f_gw) = (mine(), now(gw)); + upload_later(cpu); + let (d2, f_cpu) = (mine(), now(cpu)); + upload_later(cpu); + let d3 = mine(); + forget(gw); + forget(cpu); + (d1 - d0, f_gw, d2 - d1, f_cpu, d3 - d2, now(gw), now(cpu)) + }; + assert_eq!(seen.0, 0, "GPU-written: PENDING unchanged"); + assert_eq!(seen.1, Some((false, false)), "GPU-written: not pending, its turn not taken"); + assert_eq!(seen.2, 1, "CPU-filled: counted"); + assert_eq!(seen.3, Some((true, true)), "CPU-filled: pending, its turn taken"); + assert_eq!(seen.4, 0, "pending already: not counted again"); + assert_eq!((seen.5, seen.6), (None, None), "forgotten"); + } + + /// E14 and the creation's hand-overs (part A's review): a texture made for a view by address + /// (`real::resource_at`) is put in MADE with how `create_placed_resource_x` made it – the record + /// is there with the view census on (`XCL_ACTIVITY=1`, a process of its own; the default suite: + /// None) – and a second view of the same memory and desc finds it, with no new texture. (a) a + /// sampled 2D texture in unified memory: kept in step (in every env: its entry a new one, its + /// turn after an upload run never submitted not taken, `Entry::later`), its PC size known; (b) + /// console format 116 (half floats on the PC): not kept; (c) a render target at a 64 KiB-aligned + /// address: an arena (`vram::place`), not kept, no PC size (skipped where vram places none). On + /// this process's device, adopted as the title's; MADE's entries taken out, the textures + /// forgotten and released and the memory freed after. + #[test] + fn views_by_address_keep_how_their_texture_was_made() { + use super::super::device_x::{Made, MadeAs}; + use super::super::real::{made_for_test, resource_at_for_test, set_made_for_test}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + if super::super::backend() != super::super::Backend::Real { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let Some(uma) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_config("no unified memory") }; + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let dev = dev.unwrap(); + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let Some(base) = uma.alloc(3 << 16, 0x1_0000).map(|p| p as usize) else { return crate::gpu::recomp::runner::skip_config("unified memory is full") }; + let census = super::super::view_census::on(); + // (MADE's key: the desc's PC part, bytes 0x34.. zero) + let key = |d: &[u8; 0x38]| { + let mut k = *d; + k[0x34..].fill(0); + k + }; + let sampled = console_desc(3, 64, 64, 1, 1, 28, 0x105); + let half = console_desc(3, 64, 64, 1, 1, 116, 0x105); + let mut target = console_desc(3, 64, 64, 1, 1, 28, 0x105); + target[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); + let views = [(base, sampled), (base + 0x1_0000, half), (base + 0x2_0000, target)]; + let mut made = Vec::new(); + for (va, d) in &views { + let r = resource_at_for_test(dev.as_raw(), d.as_ptr(), *va as u64); + assert!(!r.is_null(), "a texture for the view at {va:#x}"); + let m = made_for_test(*va as u64, &key(d)).expect("in MADE"); + assert_eq!(m.res, r as usize, "MADE holds the texture made"); + assert_eq!(resource_at_for_test(dev.as_raw(), d.as_ptr(), *va as u64), r, "a second view finds it"); + assert_eq!(made_for_test(*va as u64, &key(d)), Some(m), "no new entry"); + made.push(m); + } + // (a) is kept in step (`register`) as a new texture: its turn after an upload run never + // submitted is not taken yet (`Entry::later`, R2-F1) + assert!(TEXTURES.lock().unwrap().by_res.get(&made[0].res).is_some_and(|e| !e.later), "(a) kept in step, its turn not taken"); + if census { + let [a, b, c] = [made[0].made, made[1].made, made[2].made].map(|m| m.expect("how it was made, with the census on")); + assert!(a.kept && a.pc > 0 && matches!(a.how, Made::Committed | Made::Lazy | Made::Pages), "(a) kept: {a:?}"); + assert!(!b.kept && matches!(b.how, Made::Committed | Made::Lazy | Made::Pages), "(b) 116 is not kept: {b:?}"); + // (an arena or not by vram's own record, not by the hand-over's) + let mut users = Vec::new(); + super::super::vram::arena_users(&mut users); + if users.iter().any(|&(r, _)| r == made[2].res) { + assert_eq!(c, MadeAs { how: Made::Arena, pc: 0, kept: false }, "(c) an arena"); + } else { + crate::gpu::recomp::runner::skip_config("(c) only: vram placed no arena for the render target here"); + assert!(!c.kept, "(c) a render target is not kept: {c:?}"); + } + } else { + assert!(made.iter().all(|m| m.made.is_none()), "the census off: no record"); + } + // (the render target's arena, if vram made one: let go before VRAM_TEST_LOCK is – the next + // vram test counts arena bytes) + let arena = super::super::vram::is_placed_texture(made[2].res).then_some(made[2].res); + for ((va, d), m) in views.iter().zip(&made) { + forget(m.res); + set_made_for_test(*va as u64, &key(d), None); + drop(ID3D12Resource::from_raw(m.res as *mut c_void)); + } + if let Some(r) = arena { + super::super::vram::let_go_of_arena_for_test(r); + } + assert!(uma.free(base)); + dev.GetDeviceRemovedReason().expect("the device is not removed"); + } + } + /// Real uploads, dirty-page detection and a source changing after registration: /// bookkeeping alone cannot show that the bytes the GPU sees follow the mirror. #[test] @@ -1921,8 +2636,8 @@ mod tests { use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; use windows_sys::Win32::System::Memory as mem; - let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); - let _guard = TEST_LOCK.lock().unwrap(); + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); if super::super::backend() != super::super::Backend::Real { crate::gpu::recomp::runner::skip_test("no GPU"); return; @@ -2033,7 +2748,7 @@ mod tests { ).unwrap(); let texture: ID3D12Resource = texture.unwrap(); let key = texture.as_raw() as usize; - register(raw_device, texture.as_raw(), va, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + register(raw_device, texture.as_raw(), va, &console, D3D12_RESOURCE_STATE_COMMON, 0).unwrap(); let _registered = RegisteredTexture(key); for value in [0x3D, 0x9A] { std::ptr::write_bytes(src as *mut u8, value, PAGE); @@ -2076,6 +2791,8 @@ mod tests { use crate::hle::kernelx; use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; const VIEW: usize = 16 << 20; + // (it moves PENDING: as every test that counts on it, under TEST_LOCK) + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); unsafe { let Some(_) = crate::gpu::uma::get() else { return }; let cpu = VirtualAlloc(std::ptr::null(), VIEW, MEM_RESERVE, PAGE_READWRITE) as usize; @@ -2097,12 +2814,12 @@ mod tests { d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); let tex = Arc::new(xg::Texture::new(&d).unwrap()); - let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, placed: false, unmapped: false, seq: 0, unwatched: false, sent: 0, changed: 0, dynamic: false, cpu_unmapped: false, mapped: false, made: 0 }; + let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, placed: false, unmapped: false, seq: 0, unwatched: false, sent: 0, changed: 0, dynamic: false, cpu_unmapped: false, mapped: false, made: 0, lazy: false, pc_bytes: 0, writes_now: false, format: 0, later: false }; assert_eq!(e.src, cpu + 0x2_0000); - assert!(!recheck_source(&mut e), "nothing changed yet"); + assert!(!recheck_source(&mut e, true), "nothing changed yet"); assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); // … and the page mapped under it later, uploaded again - assert!(recheck_source(&mut e)); + assert!(recheck_source(&mut e, true)); assert_eq!(e.src, at); assert!(e.pending); PENDING.fetch_sub(1, Ordering::Relaxed); @@ -2238,7 +2955,7 @@ mod tests { /// submission order, each time it is; a Reset forgets them; other resources are not noted. #[test] fn transitions_apply_when_their_list_is_submitted() { - let _guard = TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); // RGBA8 64×64, 3 mips, 2 slices (6 subresources), 4KB_S let mut d = [0u8; 0x38]; d[0..4].copy_from_slice(&3u32.to_le_bytes()); @@ -2253,7 +2970,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, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, placed: false, unmapped: false, seq: 0, unwatched: false, sent: 0, changed: 0, dynamic: false, cpu_unmapped: false, mapped: false, made: 0 }); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, placed: false, unmapped: false, seq: 0, unwatched: false, sent: 0, changed: 0, dynamic: false, cpu_unmapped: false, mapped: false, made: 0, lazy: false, pc_bytes: 0, writes_now: false, format: 0, later: false }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); @@ -2298,8 +3015,13 @@ mod tests { std::ptr::write_bytes((base + (page << 12)) as *mut u8, 0xA0 + page as u8, 1 << 12); } let whole = title_bytes(base, 1 << 12); - assert!(matches!(whole, std::borrow::Cow::Borrowed(_)), "a committed page is not copied"); - assert_eq!(whole.as_ptr() as usize, base); + if crate::util::mac_host() { + // (a Mac host always reads the title's bytes, `title_bytes`) + assert!(matches!(whole, std::borrow::Cow::Owned(_)), "a Mac host reads the bytes"); + } else { + assert!(matches!(whole, std::borrow::Cow::Borrowed(_)), "a committed page is not copied"); + assert_eq!(whole.as_ptr() as usize, base); + } assert!(whole.iter().all(|&b| b == 0xA0)); let holed = title_bytes(base, 3 << 12); assert!(matches!(holed, std::borrow::Cow::Owned(_)), "a range with a reserved page is read"); @@ -2470,13 +3192,31 @@ mod tests { let textures: Vec = descs.iter().map(|d| xg::Texture::new(d).unwrap()).collect(); // each texture's console memory: distinct bytes per texture let mems: Vec> = textures.iter().enumerate().map(|(t, x)| (0..x.size() as usize).map(|i| (i * 7 + t * 61) as u8).collect()).collect(); - let picked: Vec<(usize, &xg::Texture)> = mems.iter().zip(&textures).map(|(m, x)| (m.as_ptr() as usize, x)).collect(); + let picked: Vec<(usize, &xg::Texture, Option<&[bool]>)> = mems.iter().zip(&textures).map(|(m, x)| (m.as_ptr() as usize, x, None)).collect(); unsafe { let one = subresources_on(&picked, 1); assert!(one.iter().all(|s| !s.is_empty()), "a texture gave no subresources"); for threads in [2, 3, 8] { assert!(subresources_on(&picked, threads) == one, "{threads} threads differ from one"); } + // with masks (lazy textures, `upload_batch_masked`): what a mask has is as without; + // what it leaves out has its shape and no texels + let masks: Vec> = one.iter().map(|subs| (0..subs.len()).map(|k| k % 2 == 1).collect()).collect(); + let masked: Vec<(usize, &xg::Texture, Option<&[bool]>)> = picked.iter().zip(&masks).map(|(&(va, x, _), m)| (va, x, Some(m.as_slice()))).collect(); + for threads in [1, 3] { + let got = subresources_on(&masked, threads); + for (t, (subs, want)) in got.iter().zip(&one).enumerate() { + let is_3d = u32::from_le_bytes(descs[t][0..4].try_into().unwrap()) == 4; + for (k, (s, w)) in subs.iter().zip(want).enumerate() { + assert_eq!((s.rows, s.row_bytes, s.depth), (w.rows, w.row_bytes, w.depth), "texture {t} subresource {k}: shape"); + if k % 2 == 1 || is_3d { + assert!(s.data == w.data, "texture {t} subresource {k}: texels"); + } else { + assert!(s.data.is_empty(), "texture {t} subresource {k}: left out, no texels"); + } + } + } + } } } @@ -2493,6 +3233,83 @@ mod tests { d } + /// The view census's reads of the table: every entry, active and shadowed; same-range aliases by + /// console format pair; and a texture `retire_range` drops (a GPU-owned placement over its + /// memory) is gone from the census while – alive in MADE – it is counted live there, as retired + /// (`v.missed[0]`: the census's live bytes are a floor). + #[test] + fn the_census_reads_every_entry_and_a_retired_texture_stays_live_in_made() { + use super::super::device_x::{Made, MadeAs}; + use super::super::real::ViewTexture; + let tex = |format: u32| Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, format, 0x105)).unwrap()); + let entry = |va: usize, format: u32| Entry { + device: 0, + va, + src: va, + in_gpu_view: false, + tex: tex(format), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: false, + placed: false, + unmapped: false, + seq: 0, + unwatched: false, + sent: 0, + changed: 0, + dynamic: false, + cpu_unmapped: false, + mapped: false, + made: 0, + lazy: false, + pc_bytes: 0x1_0000, + writes_now: false, + format, + later: false, + }; + assert_eq!((tex(28).size(), tex(29).size()), (0x4000, 0x4000)); + let (a, b, c, d) = (0x7A1E_2D01usize, 0x7A1E_2D02usize, 0x7A1E_2D03usize, 0x7A1E_2D04usize); + let mut t = Table::new(); + t.insert(a, entry(0x10_0000, 28)); + // (a committed alias of the same range: both active) + t.insert(b, entry(0x10_0000, 29)); + t.insert(c, entry(0x20_0000, 28)); + // (over part of c: c shadowed) + t.insert(d, entry(0x20_2000, 28)); + let read = |t: &Table| { + let mut s = Vec::new(); + t.snapshot(&mut s); + s.sort_unstable_by_key(|k| k.res); + s + }; + let before = read(&t); + assert_eq!(before.iter().map(|k| (k.res, k.va, k.size, k.pc, k.shadowed)).collect::>(), vec![ + (a, 0x10_0000, 0x4000, 0x1_0000, false), + (b, 0x10_0000, 0x4000, 0x1_0000, false), + (c, 0x20_0000, 0x4000, 0x1_0000, true), + (d, 0x20_2000, 0x4000, 0x1_0000, false), + ]); + assert_eq!(t.alias_pairs(), vec![((28, 29), 1, 0x1_0000)], "b: an alias of a's range"); + // a GPU-owned texture placed over a's and b's memory retires them from the census + assert_eq!(t.retire_range(0x10_0000, 0x10_4000).1, 2); + let after = read(&t); + assert_eq!(after.iter().map(|k| k.res).collect::>(), vec![c, d]); + assert!(t.alias_pairs().is_empty()); + // three at one range: each alias with the first's format + let mut three = Table::new(); + for (res, format) in [(a, 28), (b, 29), (c, 30)] { + three.insert(res, entry(0x30_0000, format)); + } + let mut p = three.alias_pairs(); + p.sort_unstable(); + assert_eq!(p, vec![((28, 29), 1, 0x1_0000), ((28, 30), 1, 0x1_0000)]); + // MADE still holds a and b (views by address made them, kept in step then) + let made = |res: usize| ViewTexture { res, made: Some(MadeAs { how: Made::Committed, pc: 0x1_0000, kept: true }) }; + let views = [made(a), made(b), made(c)]; + assert_eq!(super::super::view_census::classes_for_test(&views, &before), ([2, 1, 0, 0], 3)); + assert_eq!(super::super::view_census::classes_for_test(&views, &after), ([0, 1, 2, 0], 3), "retired, still counted live"); + } + /// Overlapping textures shadow earlier ones so dead placements never re-upload over shared /// `vram::Pages` tiles; different-range overlaps request unmapping while exact same-range /// overlaps stay mapped; releasing a newer placement reactivates uncovered older ones. @@ -2520,6 +3337,11 @@ mod tests { cpu_unmapped: false, mapped: false, made: 0, + lazy: false, + pc_bytes: 0, + writes_now: false, + format: 0, + later: false, }; let mut tbl = Table::new(); // Two adjacent placed 16 KiB textures + one placed 64 KiB texture after them. @@ -2553,8 +3375,8 @@ mod tests { assert_eq!(tbl.insert(12, entry(0x20_0000, &tex_64k, true, false)), (-1, vec![])); assert!(!tbl.by_res.contains_key(&10) && !tbl.by_res.contains_key(&11) && tbl.by_res.contains_key(&12)); - // A superseded placement can still be in the table while Release is in flight. - // Use a synthetic COM object so an unguarded AddRef fails an assertion safely. + // A superseded placement no reference can be taken of on the Mac (`clone_resource`: a + // synthetic COM object, its vtable not XCL's) is not cloned there; elsewhere it is. #[repr(C)] struct FakeResource { vtable: *const usize, @@ -2571,11 +3393,9 @@ mod tests { let older_address = std::ptr::from_mut(&mut older) as usize; let mut overlap = Table::new(); overlap.insert(older_address, entry(0x30_0000, &tex_16k, true, true)); - let in_flight = ResourceRelease::begin(older_address); let (_, unmap) = overlap.insert(13, entry(0x30_0000, &tex_64k, true, true)); assert_eq!(unmap, vec![older_address]); assert!(unsafe { clone_resources(&unmap, true) }.is_empty()); - drop(in_flight); assert_eq!(older.refs.load(Ordering::Relaxed), 1); let refs = unsafe { clone_resources(&unmap, false) }; assert_eq!(older.refs.load(Ordering::Relaxed), 2); @@ -2589,8 +3409,8 @@ mod tests { /// chains (including packed mips), cubemap arrays (`extra_pages`) and 3D volumes upload intact. #[test] fn placed_title_textures_share_vram_and_preserve_pixels() { - let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); - let _guard = TEST_LOCK.lock().unwrap(); + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; use windows::Win32::Graphics::Dxgi::*; @@ -2639,7 +3459,7 @@ mod tests { return; }; if !super::super::vram::on_pages() { - println!("SKIPPED placed_title_textures_share_vram_and_preserve_pixels: title textures are not on shared pages on this host (XCL_VRAM_ARENAS)"); + crate::gpu::recomp::runner::skip_config("title textures are not on shared pages on this host (XCL_VRAM_ARENAS)"); return; } let pool_size = 16usize << 20; @@ -2955,15 +3775,698 @@ mod tests { } } + // --- lazy title textures (`lazy_tex`) --------------------------------------------------- + + const PAGE: usize = crate::hle::kernelx::PHYS_PAGE_SIZE; + + /// What a test of lazy textures needs: a device of its own adopted as the title's is, a + /// queue, a GPU view of title memory paired with a CPU view (`kernelx::mirrors`, a size of + /// its own so no other test's view pairs with it), and a pool of physical pages the title's + /// command queue #31 maps into the GPU view page by page (`gpu_views::update`) – a retail + /// game's streamed textures. Lazy textures in `mode` while it lives. + struct LazyWorld { + dev: ID3D12Device, + queue: ID3D12CommandQueue, + cpu: usize, + gpu: usize, + pool: usize, + pages: Vec, + } + + impl LazyWorld { + unsafe fn new(view: usize, pool_pages: usize, mode: u8) -> Option { + use crate::hle::kernelx; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + if super::super::backend() != super::super::Backend::Real || crate::gpu::uma::get().is_none() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter = factory.EnumAdapters1(0).ok()?; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 || String::from_utf16_lossy(&d.Description).contains("Basic Render Driver")) { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let dev = dev?; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + // (lazy textures are where sampled title textures are not on shared pages: a host's + // configuration, not a GPU's want) + if super::super::vram::on_pages() { + crate::gpu::recomp::runner::skip_config("title textures are on shared pages on this host"); + return None; + } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; + let mut n = pool_pages; + let mut pages = vec![0usize; pool_pages]; + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let pool = VirtualAlloc(std::ptr::null(), pool_pages * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_eq!(kernelx::MapTitlePhysicalPages(pool as *mut c_void, pool_pages, 0, 4, pages.as_mut_ptr()) as usize, pool); + let cpu = VirtualAlloc(std::ptr::null(), view, MEM_RESERVE, PAGE_READWRITE) as usize; + let gpu = VirtualAlloc(std::ptr::null(), view, MEM_RESERVE, PAGE_NOACCESS) as usize; + kernelx::mirrors::reserved(cpu, view, 0x2040_2000, 0x04); + kernelx::mirrors::reserved(gpu, view, 0x2040_2000, 0x801); + assert_eq!(kernelx::mirrors::source(gpu + PAGE), Some(cpu + PAGE)); + super::super::lazy_tex::test_mode(Some(mode)); + let w = LazyWorld { dev, queue, cpu, gpu, pool, pages }; + // (D3D12 gives every test the adapter's one device: an earlier test's lazy textures + // may still be on their way out through the deferred releases) + w.wait_for("an earlier test's tiles given back", || w.pool().3 == 0); + Some(w) + } + + /// The queue maps pool pages `first..first + n` at the GPU view's pages from `at`. + unsafe fn map(&self, at: usize, first: u32, n: u32) { + let ranges = [[1u32, first, n]]; + let batch: [usize; 3] = [at & !(PAGE - 1), 1, ranges.as_ptr() as usize]; + super::super::gpu_views::update(1, batch.as_ptr() as *const u8, self.pool, self.pages.len() as u32); + } + + /// The queue unmaps `n` pages of the GPU view from `at`. + unsafe fn unmap(&self, at: usize, n: u32) { + let ranges = [[2u32, 0, n]]; + let batch: [usize; 3] = [at & !(PAGE - 1), 1, ranges.as_ptr() as usize]; + super::super::gpu_views::update(1, batch.as_ptr() as *const u8, self.pool, self.pages.len() as u32); + } + + /// The bytes `image` of a texture at `va` that lie in the GPU view's page `page`, written + /// where pool page `p` is (the page the queue maps there). + unsafe fn fill(&self, va: usize, image: &[u8], page: usize, p: u32) { + let (a, b) = (va.max(page), (va + image.len()).min(page + PAGE)); + if a < b { + std::ptr::copy_nonoverlapping(image[a - va..].as_ptr(), (self.pool + p as usize * PAGE + (a - page)) as *mut u8, b - a); + } + } + + unsafe fn place(&self, va: usize, desc: &[u8; 0x38]) -> ID3D12Resource { + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(self.dev.as_raw(), va as u64, desc.as_ptr(), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "CreatePlacedResourceX failed: {hr:#x}"); + ID3D12Resource::from_raw(p) + } + + /// Subresource `sub` of `r` as the GPU has it. + unsafe fn read(&self, r: &ID3D12Resource, sub: u32) -> Vec { + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + let rd = texture::copyable_desc(r); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + self.dev.GetCopyableFootprints(&rd, sub, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + self.dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &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() }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = self.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = self.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + 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(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + own_work(|| { + self.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&self.dev, &self.queue).unwrap(); + }); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + rb.Unmap(0, None); + out + } + + /// Every subresource of `r` (placed at `va`) holds what the title's memory there holds – + /// zeros where it has nothing. + unsafe fn check(&self, r: &ID3D12Resource, va: usize, desc: &[u8; 0x38], what: &str) { + let want = subresources(va, &xg::Texture::new(desc).unwrap()); + for (k, w) in want.iter().enumerate() { + let got = self.read(r, k as u32); + assert!(got == w.data, "{what}: subresource {k} differs ({} of {} bytes)", got.iter().zip(&w.data).filter(|(a, b)| a != b).count(), w.data.len()); + } + self.dev.GetDeviceRemovedReason().expect("device removed"); + } + + /// Tiles each group of lazy texture `r` has. + fn tiles(&self, r: &ID3D12Resource) -> Vec { + super::super::lazy_tex::test_tiles(r.as_raw() as usize).expect("a lazy texture").0 + } + + /// The device's pool: (heaps, free, parked, used) tiles. + fn pool(&self) -> (usize, usize, usize, usize) { + super::super::lazy_tex::test_pool(self.dev.as_raw() as usize) + } + + /// Waits up to 20 s for `f` (deferred releases on a Mac: the ledger lets go after its grace). + fn wait_for(&self, what: &str, f: impl Fn() -> bool) { + let t0 = std::time::Instant::now(); + while !f() { + assert!(t0.elapsed() < std::time::Duration::from_secs(20), "{what}: not after 20 s"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + } + } + + impl Drop for LazyWorld { + fn drop(&mut self) { + use crate::hle::kernelx; + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + super::super::lazy_tex::test_mode(None); + unsafe { + let mut none = vec![0usize; self.pages.len()]; + kernelx::MapTitlePhysicalPages(self.pool as *mut c_void, self.pages.len(), 0, 4, none.as_mut_ptr()); + kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), self.pages.len(), self.pages.as_mut_ptr()); + kernelx::mirrors::released(self.cpu); + for r in [self.pool, self.cpu, self.gpu] { + VirtualFree(r as *mut c_void, 0, MEM_RELEASE); + } + } + } + } + + /// The tiled bytes of a texture (`desc`) whose texels are a pattern of `seed` (never zero). + fn tiled_image(desc: &[u8; 0x38], seed: u8) -> Vec { + let tex = xg::Texture::new(desc).unwrap(); + let s = tex.texels().unwrap(); + let mut bytes = vec![0u8; tex.size() as usize]; + for slice in 0..s.array as usize { + let dst = &mut bytes[slice * s.chain.slice_bytes..(slice + 1) * s.chain.slice_bytes]; + for (m, l) in s.chain.levels.iter().enumerate() { + let pat: Vec = (0..l.width * l.height * s.bpe as usize).map(|k| seed.wrapping_add((slice * 31 + m * 7) as u8).wrapping_add((k * 13) as u8) | 1).collect(); + s.chain.tile_level(dst, m, slice, &pat); + } + } + bytes + } + + /// A streamed texture placed over GPU-view pages with nothing mapped is a lazy one with no + /// tiles and reads as zero; when the queue maps the page of its mip tail, that group alone + /// gets tiles and holds the tail's texels; when the rest comes, all of it; released, its + /// tiles go back to the pool and serve the next texture; streaming many stays in one heap. + #[test] + fn lazy_texture_gets_tiles_when_its_memory_arrives() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Some(w) = LazyWorld::new(40 << 20, 64, 2) else { return }; + // BC7 1024² with 11 mips, 64 KB swizzle: on the console the tail block (levels 3 – + // 10) first, then levels 2, 1, 0; on the PC (Metal's tiles) 16 + 4 + 1 tiles and + // a packed tail of 1 + let desc = console_desc(3, 1024, 1024, 1, 11, 98, 0x109); + let tex = xg::Texture::new(&desc).unwrap(); + let size = tex.size() as usize; + let va = w.gpu + 4 * PAGE; + let heaps0 = w.pool().0; + let r = w.place(va, &desc); + let key = r.as_raw() as usize; + assert!(super::super::lazy_tex::is_lazy(key), "a sampled BC7 texture in a GPU view is lazy"); + // (what the view census reads of it: how it was made – with the census on, in a process of + // its own with `EXTRA_ENV=XCL_ACTIVITY=1` –, and its console format) + assert_eq!(super::super::device_x::take_last_made().map(|m| (m.how, m.kept)), super::super::view_census::on().then_some((super::super::device_x::Made::Lazy, true))); + assert_eq!(TEXTURES.lock().unwrap().by_res.get(&key).map(|e| e.format), Some(98)); + assert!(w.tiles(&r).iter().all(|&t| t == 0), "no tiles when made"); + refresh(w.queue.as_raw()); + assert!(w.tiles(&r).iter().all(|&t| t == 0), "nothing of its memory there: no tiles"); + w.check(&r, va, &desc, "no memory"); + // the tail's page + let image = tiled_image(&desc, 0x40); + w.map(va, 0, 1); + w.fill(va, &image, va, 0); + note_unmap(key); + refresh(w.queue.as_raw()); + let t = w.tiles(&r); + eprintln!("tail page mapped: tiles by group {t:?}"); + assert_eq!(t.iter().filter(|&&n| n > 0).count(), 1, "the tail's group alone ({t:?})"); + assert!(*t.last().unwrap() > 0, "the packed tail (the last group) has tiles ({t:?})"); + w.check(&r, va, &desc, "tail"); + // the rest of it + let pages = size.div_ceil(PAGE); + w.map(va + PAGE, 1, pages as u32 - 1); + for k in 1..pages { + w.fill(va, &image, va + k * PAGE, k as u32); + } + note_unmap(key); + refresh(w.queue.as_raw()); + assert!(w.tiles(&r).iter().all(|&n| n > 0), "all of it ({:?})", w.tiles(&r)); + w.check(&r, va, &desc, "whole"); + let mut by = Vec::new(); + super::super::lazy_tex::tiles_by_texture(&mut by); + assert_eq!(by.iter().find(|x| x.0 == key).map(|x| x.1 as usize), Some(w.tiles(&r).iter().sum()), "the view census's tiles of it"); + let (heaps, _, _, used) = w.pool(); + assert_eq!(used, 22, "22 tiles"); + assert!(heaps <= heaps0.max(1), "one pool heap at most ({heaps0} before, {heaps} now)"); + // released: its tiles wait for the GPU, then serve the next texture + drop(r); + w.wait_for("the tiles parked", || w.pool().3 == 0); + let r2 = w.place(va, &desc); + note_unmap(r2.as_raw() as usize); + refresh(w.queue.as_raw()); + assert!(w.tiles(&r2).iter().all(|&n| n > 0)); + assert_eq!(w.pool().0, heaps, "no new heap"); + w.check(&r2, va, &desc, "on the released one's tiles"); + drop(r2); + // streaming: 200 made, backed and released in turn stay within a few heaps + for k in 0..200usize { + let r = w.place(va, &desc); + note_unmap(r.as_raw() as usize); + refresh(w.queue.as_raw()); + assert!(w.tiles(&r).iter().all(|&n| n > 0), "streamed #{k}"); + } + let heaps = w.pool().0; + eprintln!("200 streamed: {heaps} heap(s), pool {:?}", w.pool()); + assert!(heaps <= heaps0.max(1) + 2, "{heaps} heaps ({heaps0} before) for 200 textures of 22 tiles one after another"); + w.unmap(va, pages as u32); + w.dev.GetDeviceRemovedReason().expect("device removed"); + } + } + + /// The title's GPU work copies into a lazy texture: it gets tiles for all of it at the + /// submit before the copy (`note_gpu_write`, then the submit's refresh), and the copy lands; + /// a resolve into one (`note_gpu_write_lazy`) the same. + #[test] + fn lazy_texture_gets_tiles_before_a_gpu_copy_into_it() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Some(w) = LazyWorld::new(44 << 20, 4, 2) else { return }; + let desc = console_desc(3, 512, 512, 1, 10, 98, 0x109); + let va = w.gpu + 2 * PAGE; + let r = w.place(va, &desc); + let key = r.as_raw() as usize; + assert!(super::super::lazy_tex::is_lazy(key)); + refresh(w.queue.as_raw()); + assert!(w.tiles(&r).iter().all(|&t| t == 0)); + // a committed texture of the same shape with texels of its own + let rd = texture::copyable_desc(&r); + let mut c: Option = None; + w.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut c).unwrap(); + let c = c.unwrap(); + let n = rd.MipLevels as usize; + let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; + let mut rows = vec![0u32; n]; + let mut row_bytes = vec![0u64; n]; + w.dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), None); + let subs: Vec = (0..n).map(|k| Subresource { rows: rows[k] as usize, row_bytes: row_bytes[k] as usize, depth: 1, data: (0..rows[k] as usize * row_bytes[k] as usize).map(|i| (i * 7 + k) as u8 | 0x80).collect() }).collect(); + own_work(|| texture::upload_batch(&w.dev, &w.queue, &[(c.clone(), subs.clone(), vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + // recorded by the title (the hook notes it), submitted (the hook refreshes first) + note_gpu_write(key); + refresh(w.queue.as_raw()); + assert!(w.tiles(&r).iter().all(|&t| t > 0), "all of it before the copy runs ({:?})", w.tiles(&r)); + let alloc: ID3D12CommandAllocator = w.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = w.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.CopyResource(&r, &c); + list.Close().unwrap(); + own_work(|| { + w.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&w.dev, &w.queue).unwrap(); + }); + for (k, s) in subs.iter().enumerate() { + assert!(w.read(&r, k as u32) == s.data, "copied subresource {k}"); + } + // a resolve's destination + let r2 = w.place(va + 8 * PAGE, &desc); + refresh(w.queue.as_raw()); + assert!(w.tiles(&r2).iter().all(|&t| t == 0)); + note_gpu_write_lazy(r2.as_raw() as usize); + refresh(w.queue.as_raw()); + assert!(w.tiles(&r2).iter().all(|&t| t > 0), "a resolve's destination has all its tiles"); + w.dev.GetDeviceRemovedReason().expect("device removed"); + } + } + + /// A full pool that cannot grow: a texture whose memory came gets the groups that fit and is + /// short of the others; nothing is uploaded again while the pool stays as it is; tiles coming + /// back wake the texture they are enough for, oldest first, and it gets what it lacked (only + /// that copied); a texture the title's GPU work wrote keeps what that work wrote when its other + /// groups get their tiles. + #[test] + fn lazy_texture_short_of_tiles_waits_for_the_pool() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + /// The pool as configured again, and the tiles taken out back, whatever happens. + struct Full { + device: usize, + held: Vec<(u32, u32)>, + } + impl Full { + fn give_back(&mut self, n: usize) { + let n = n.min(self.held.len()); + let back: Vec<(u32, u32)> = self.held.drain(..n).collect(); + super::super::lazy_tex::test_give_back(self.device, back); + } + } + impl Drop for Full { + fn drop(&mut self) { + super::super::lazy_tex::test_full_pool(self.device, None); + super::super::lazy_tex::test_give_back(self.device, std::mem::take(&mut self.held)); + } + } + unsafe { + let Some(w) = LazyWorld::new(56 << 20, 64, 2) else { return }; + let dev = w.dev.as_raw() as usize; + // BC7 1024², 11 mips: groups of 16 (mip 0), 4, 1 tiles and a packed tail of 1 + let desc = console_desc(3, 1024, 1024, 1, 11, 98, 0x109); + let size = xg::Texture::new(&desc).unwrap().size() as usize; + let pages = size.div_ceil(PAGE) as u32; + let image = tiled_image(&desc, 0x31); + let place_with_memory = |va: usize, first: u32| -> ID3D12Resource { + w.map(va, first, pages); + for k in 0..pages as usize { + w.fill(va, &image, va + k * PAGE, first + k as u32); + } + w.place(va, &desc) + }; + // (the device's pool has a heap; then nothing more of it is on its way back) + let warm = place_with_memory(w.gpu + 2 * PAGE, 0); + refresh(w.queue.as_raw()); + assert!(w.tiles(&warm).iter().all(|&n| n > 0)); + drop(warm); + w.unmap(w.gpu + 2 * PAGE, pages); + w.wait_for("the warm-up texture's tiles parked", || w.pool().3 == 0); + // the pool at its limit with 6 free tiles + let mut full = Full { device: dev, held: super::super::lazy_tex::test_full_pool(dev, Some(6)) }; + assert_eq!(w.pool().1, 6); + let (va_a, va_b) = (w.gpu + 2 * PAGE, w.gpu + 26 * PAGE); + let a = place_with_memory(va_a, 0); + refresh(w.queue.as_raw()); + assert_eq!(w.tiles(&a), vec![0, 4, 1, 1], "the groups that fit 6 tiles, mip 0 short"); + { + // mip 0 reads as zero (no tiles); the others hold the title's texels + let memory = subresources(va_a, &xg::Texture::new(&desc).unwrap()); + for (k, m) in memory.iter().enumerate() { + let got = w.read(&a, k as u32); + if k == 0 { + assert!(got.iter().all(|&x| x == 0), "A's mip 0: no tiles, zeros"); + } else { + assert!(got == m.data, "A's mip {k}"); + } + } + } + let b = place_with_memory(va_b, pages); + refresh(w.queue.as_raw()); + assert_eq!(w.tiles(&b), vec![0, 0, 0, 0], "no tile left"); + let (ua, ub) = (test_uploads(a.as_raw() as usize), test_uploads(b.as_raw() as usize)); + for _ in 0..10 { + note_unmap(a.as_raw() as usize); + note_unmap(b.as_raw() as usize); + refresh(w.queue.as_raw()); + } + assert_eq!((test_uploads(a.as_raw() as usize), test_uploads(b.as_raw() as usize)), (ua, ub), "nothing uploaded again while the pool is as it was"); + // 20 tiles back: A (the older one) gets the 16 it lacked, whatever the order of the + // two textures' addresses; B what is left that fits – its packed tail and mip 2 + full.give_back(20); + refresh(w.queue.as_raw()); + assert_eq!(w.tiles(&a), vec![16, 4, 1, 1], "A got what it lacked"); + assert_eq!(w.tiles(&b), vec![0, 0, 1, 1], "B the small groups that fit the 4 left"); + assert_eq!(test_uploads(a.as_raw() as usize), ua + 1); + assert_eq!(test_uploads(b.as_raw() as usize), ub + 1); + w.check(&a, va_a, &desc, "A after its mip 0 came"); + for _ in 0..4 { + refresh(w.queue.as_raw()); + } + assert_eq!(test_uploads(b.as_raw() as usize), ub + 1, "B waits again with nothing more to be had"); + // the rest back: B + full.give_back(usize::MAX); + refresh(w.queue.as_raw()); + assert!(w.tiles(&b).iter().all(|&n| n > 0), "B ({:?})", w.tiles(&b)); + w.check(&b, va_b, &desc, "B"); + // a texture the title's GPU work writes, short of tiles: what had them keeps the + // GPU's texels when the rest gets them + let va_c = w.gpu + 50 * PAGE; + w.map(va_c, 2 * pages, 1); + w.fill(va_c, &image, va_c, 2 * pages); + let c = w.place(va_c, &desc); + let key_c = c.as_raw() as usize; + refresh(w.queue.as_raw()); + assert_eq!(w.tiles(&c), vec![0, 0, 0, 1], "the tail's page: the tail"); + full.held = super::super::lazy_tex::test_full_pool(dev, Some(0)); + note_gpu_write(key_c); + refresh(w.queue.as_raw()); + assert_eq!(w.tiles(&c), vec![0, 0, 0, 1], "short of the rest"); + let rd = texture::copyable_desc(&c); + let mut gpu: Option = None; + w.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut gpu).unwrap(); + let gpu = gpu.unwrap(); + let n = rd.MipLevels as usize; + let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; + let mut rows = vec![0u32; n]; + let mut row_bytes = vec![0u64; n]; + w.dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), None); + let pattern: Vec = (0..n).map(|k| Subresource { rows: rows[k] as usize, row_bytes: row_bytes[k] as usize, depth: 1, data: (0..rows[k] as usize * row_bytes[k] as usize).map(|i| (i * 5 + k * 3) as u8 | 0x40).collect() }).collect(); + own_work(|| texture::upload_batch(&w.dev, &w.queue, &[(gpu.clone(), pattern.clone(), vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + let alloc: ID3D12CommandAllocator = w.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = w.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.CopyResource(&c, &gpu); + list.Close().unwrap(); + own_work(|| { + w.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&w.dev, &w.queue).unwrap(); + }); + full.give_back(usize::MAX); + refresh(w.queue.as_raw()); + assert!(w.tiles(&c).iter().all(|&n| n > 0), "C backed when tiles came back ({:?})", w.tiles(&c)); + let memory = subresources(va_c, &xg::Texture::new(&desc).unwrap()); + for k in 0..n { + let got = w.read(&c, k as u32); + if k >= 3 { + assert!(got == pattern[k].data, "C's packed mip {k}: what the GPU copied there"); + } else { + assert!(got == memory[k].data, "C's mip {k}: the title's memory (no tile when the GPU copied)"); + } + } + w.unmap(va_a, pages); + w.unmap(va_b, pages); + w.unmap(va_c, 1); + w.dev.GetDeviceRemovedReason().expect("device removed"); + } + } + + /// What is not to be lazy is committed as before, with the title's texels: a format left + /// out (RGBA8 with the default formats), a small texture, a 3D one, and (mode 1) one whose + /// memory is all there when it is made. + #[test] + fn lazy_texture_fallbacks_are_committed() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Some(w) = LazyWorld::new(48 << 20, 64, 1) else { return }; + let cases = [ + ("RGBA8 512² (format)", console_desc(3, 512, 512, 1, 10, 28, 0x109)), + ("BC1 256² (small)", console_desc(3, 256, 256, 1, 9, 71, 0x109)), + ("BC7 64³ volume (3D)", console_desc(4, 64, 64, 64, 1, 98, 0x109)), + ("BC7 512² (all there)", console_desc(3, 512, 512, 1, 10, 98, 0x109)), + ]; + let mut at = w.gpu + PAGE; + // (each case's pages from the pool's first: unmapped after it) + let page = 0u32; + for (what, desc) in cases { + let Ok(tex) = xg::Texture::new(&desc) else { + eprintln!("{what}: no console layout here – left out"); + continue; + }; + let n = (tex.size() as usize).div_ceil(PAGE) as u32; + let image = tiled_image_any(&desc, 0x21); + w.map(at, page, n); + for k in 0..n as usize { + w.fill(at, &image, at + k * PAGE, page + k as u32); + } + let r = w.place(at, &desc); + assert!(!super::super::lazy_tex::is_lazy(r.as_raw() as usize), "{what}: committed"); + refresh(w.queue.as_raw()); + if u32::from_le_bytes(desc[0..4].try_into().unwrap()) == 3 { + w.check(&r, at, &desc, what); + } + drop(r); + w.unmap(at, n); + at += (n as usize + 1) * PAGE; + } + } + } + + /// `tiled_image` for 2D textures, zeros for others. + fn tiled_image_any(desc: &[u8; 0x38], seed: u8) -> Vec { + if u32::from_le_bytes(desc[0..4].try_into().unwrap()) == 3 { + tiled_image(desc, seed) + } else { + vec![0; xg::Texture::new(desc).map_or(0, |t| t.size() as usize)] + } + } + + /// A streaming load as a retail game's: thousands of BC textures placed side by side at + /// 1 – 2 KiB-aligned GPU-view addresses, a quarter of them with the page of their mip tail + /// mapped (the rest with nothing yet), submits in between. Their tiles are a small fraction + /// of what committed textures would take; released and streamed again, they come from the + /// same heaps. + #[test] + fn lazy_textures_of_a_streaming_load_stay_bounded() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + const VIEW: usize = (5 << 29) + (3 << 20); + const N: usize = 2048; + let Some(w) = LazyWorld::new(VIEW, N / 2, 2) else { return }; + let shapes = [console_desc(3, 512, 512, 1, 10, 98, 0x109), console_desc(3, 1024, 1024, 1, 11, 71, 0x109), console_desc(3, 1024, 512, 1, 11, 77, 0x109), console_desc(3, 1024, 1024, 1, 11, 98, 0x109)]; + let images: Vec> = shapes.iter().map(|d| tiled_image(d, 0x77)).collect(); + let sizes: Vec = shapes.iter().map(|d| xg::Texture::new(d).unwrap().size() as usize).collect(); + // side by side, 1 or 2 KiB past a 4 KiB boundary + let mut places = Vec::with_capacity(N); + let mut at = w.gpu + PAGE; + for k in 0..N { + let s = (k * 7) % shapes.len(); + let va = at + if k % 2 == 0 { 0x400 } else { 0x800 }; + places.push((s, va)); + at = (va + sizes[s] + 0xFFF) & !0xFFF; + } + assert!(at < w.gpu + VIEW); + let pass = |round: usize| -> (u64, u64, usize, f64) { + let mut kept = Vec::with_capacity(N); + let (mut committed, mut mapped) = (0u64, 0u32); + let t0 = std::time::Instant::now(); + for (k, &(s, va)) in places.iter().enumerate() { + let r = w.place(va, &shapes[s]); + committed += real_pc_size(&w.dev, &r); + if (k + round) % 4 == 0 { + // the pages of its mip tail block (64 KiB from its address: two pages) + let p = mapped; + mapped += 2; + w.map(va, p, 2); + w.fill(va, &images[s], va & !(PAGE - 1), p); + w.fill(va, &images[s], (va & !(PAGE - 1)) + PAGE, p + 1); + note_unmap(r.as_raw() as usize); + } + kept.push(r); + if k % 32 == 31 { + refresh(w.queue.as_raw()); + } + } + refresh(w.queue.as_raw()); + let secs = t0.elapsed().as_secs_f64(); + let lazy = kept.iter().filter(|r| super::super::lazy_tex::is_lazy(r.as_raw() as usize)).count(); + let backed = kept.iter().filter(|r| super::super::lazy_tex::test_tiles(r.as_raw() as usize).is_some_and(|t| t.0.iter().any(|&n| n > 0))).count(); + // the tail texels of a few backed ones + for (k, r) in kept.iter().enumerate().filter(|(k, _)| (k + round) % 4 == 0).step_by(97) { + let (s, va) = places[k]; + let want = subresources(va, &xg::Texture::new(&shapes[s]).unwrap()); + let last = want.len() - 1; + assert!(w.read(r, last as u32) == want[last].data, "streamed #{k}: the smallest mip"); + } + let used = w.pool().3; + for (k, &(_, va)) in places.iter().enumerate() { + if (k + round) % 4 == 0 { + w.unmap(va, 2); + } + } + drop(kept); + assert_eq!(lazy, N, "every texture lazy"); + assert_eq!(backed, N / 4, "those with memory have tiles, the others none (not the texture before, whose end shares a page)"); + (committed, used as u64 * PAGE as u64, backed, secs) + }; + let (committed, tiles, backed, secs) = pass(0); + let heaps = w.pool().0; + eprintln!( + "{N} streamed textures ({backed} with their tail's page): {} MiB committed would be, {} MiB of tiles in {heaps} heap(s); {secs:.2} s ({:.0} µs a texture with its share of submits)", + committed >> 20, + tiles >> 20, + secs * 1e6 / N as f64 + ); + eprintln!("{}", super::super::lazy_tex::stats().unwrap_or_default()); + assert!(tiles * 10 < committed, "tiles {} MiB against {} MiB committed", tiles >> 20, committed >> 20); + w.wait_for("every tile parked", || w.pool().3 == 0); + let (_, tiles2, _, secs2) = pass(1); + let heaps2 = w.pool().0; + eprintln!("again: {} MiB of tiles in {heaps2} heap(s); {secs2:.2} s", tiles2 >> 20); + assert!(heaps2 <= heaps + 1, "the second pass took {heaps2} heaps after {heaps}"); + w.dev.GetDeviceRemovedReason().expect("device removed"); + } + } + + /// The PC's committed size of texture `r` (its description as a default-layout one). + unsafe fn real_pc_size(dev: &ID3D12Device, r: &ID3D12Resource) -> u64 { + dev.GetResourceAllocationInfo(0, &[texture::copyable_desc(r)]).SizeInBytes + } + + /// A shadowed texture whose source changes (`recheck_source`) is pending but not counted in + /// `PENDING` – it is when it comes back, once; released while shadowed, nothing is taken back. + /// (The count of shadowed ones kept the refresh's fast path, `PENDING == 0`, from ever being + /// taken.) + #[test] + fn a_shadowed_source_change_is_not_counted_pending() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let mut d = [0u8; 0x38]; + d[0..4].copy_from_slice(&3u32.to_le_bytes()); + d[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + d[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + d[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + d[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + d[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); + d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); + let tex = Arc::new(xg::Texture::new(&d).unwrap()); + // (an address in no GPU view: its source is itself – one said to be elsewhere changes) + let entry = |va: usize, in_gpu_view: bool, src: usize| Entry { device: 0, va, src, in_gpu_view, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, placed: false, unmapped: false, seq: 0, unwatched: false, sent: 0, changed: 0, dynamic: false, cpu_unmapped: false, mapped: false, made: 0, lazy: false, pc_bytes: 0, writes_now: false, format: 0, later: false }; + let mut t = Table::new(); + let counted = |t: &Table| t.by_res.values().filter(|e| e.pending).count() as isize; + let a_va = 0x7E57_0010_0000usize; + let mut pending = t.insert(1, entry(a_va, true, a_va + 0x1000)).0; + // B over part of A: A shadowed + pending += t.insert(2, entry(a_va + 0x800, false, a_va + 0x800)).0; + assert!(t.shadowed.contains_key(&1)); + // A's source changes while shadowed: pending, PENDING untouched + let before = PENDING.load(Ordering::Relaxed); + assert!(recheck_source(t.shadowed.get_mut(&1).unwrap(), false), "its source changed"); + assert!(t.shadowed[&1].pending); + assert_eq!(PENDING.load(Ordering::Relaxed), before, "a shadowed one is not counted"); + assert_eq!(pending, counted(&t)); + // B goes: A comes back, counted once + let (_, delta, _) = t.remove(2); + pending += delta; + assert_eq!(delta, 1); + assert_eq!(pending, counted(&t)); + // shadowed again by another range, its source changing again, and released while + // shadowed: nothing to take back + pending += t.insert(3, entry(a_va + 0x400, false, a_va + 0x400)).0; + assert!(t.shadowed.contains_key(&1)); + t.shadowed.get_mut(&1).unwrap().src = a_va + 0x2000; + t.shadowed.get_mut(&1).unwrap().pending = false; + assert!(recheck_source(t.shadowed.get_mut(&1).unwrap(), false)); + let (_, delta, _) = t.remove(1); + assert_eq!(delta, 0, "a shadowed pending texture released: no delta"); + pending += delta; + assert_eq!(pending, counted(&t)); + } + + /// (upstream) A batch holds at most `BATCH_ITEMS` textures of one device and `cap` bytes; an + /// empty one takes its first texture even past the cap. #[test] fn batch_fits_caps_items_bytes_and_device() { - assert!(batch_fits(0, 0, 0, 1, BATCH_BYTES + 4096)); - assert!(!batch_fits(1, BATCH_BYTES + 4096, 1, 1, 4096)); - assert!(batch_fits(BATCH_ITEMS - 1, (BATCH_ITEMS - 1) * 4096, 1, 1, 4096)); - assert!(!batch_fits(BATCH_ITEMS, BATCH_ITEMS * 4096, 1, 1, 4096)); - assert!(batch_fits(1, BATCH_BYTES - 4096, 1, 1, 4096)); - assert!(!batch_fits(1, BATCH_BYTES - 4096, 1, 1, 4097)); - assert!(!batch_fits(1, usize::MAX - 10, 1, 1, 100)); - assert!(!batch_fits(1, 4096, 1, 2, 4096)); + let cap = 32 << 20; + assert!(batch_fits(0, 0, 0, 1, cap + 4096, cap)); + assert!(!batch_fits(1, cap + 4096, 1, 1, 4096, cap)); + assert!(batch_fits(BATCH_ITEMS - 1, (BATCH_ITEMS - 1) * 4096, 1, 1, 4096, cap)); + assert!(!batch_fits(BATCH_ITEMS, BATCH_ITEMS * 4096, 1, 1, 4096, cap)); + assert!(batch_fits(1, cap - 4096, 1, 1, 4096, cap)); + assert!(!batch_fits(1, cap - 4096, 1, 1, 4097, cap)); + assert!(!batch_fits(1, usize::MAX - 10, 1, 1, 100, cap)); + assert!(!batch_fits(1, 4096, 1, 2, 4096, cap)); + // the cap the uploads go with (`XCL_UPLOAD_STAGING_MB`) + assert!(batch_fits(1, 0, 1, 1, texture::batch_bytes(), texture::batch_bytes())); + assert!(!batch_fits(1, 1, 1, 1, texture::batch_bytes(), texture::batch_bytes())); } } diff --git a/crates/xcl/src/hle/d3d12x/view_census.rs b/crates/xcl/src/hle/d3d12x/view_census.rs new file mode 100644 index 0000000..1c3a60e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/view_census.rs @@ -0,0 +1,1299 @@ +//! The views' census (with `XCL_ACTIVITY`; diagnostics only – nothing the title sees and nothing +//! XCL makes or releases changes): what each PC view descriptor XCL keeps names, and from it which +//! of the textures XCL made for views by address (`real::resource_at`, which keeps each for good: +//! the title holds no handle to one) no PC descriptor names any more – what releasing them (a later +//! patch) could free, with their PC bytes and lazy tiles. Beside it, from the census thread only: +//! the bytes lazy_tex committed instead of making lazy, by reason; the arenas' union and places; +//! same-range aliases by console format; the sparse tiles under the textures kept in step. +//! +//! The map (`Names`) holds two words per place of the shared heap (console_heap's `Global`): what +//! the shared heap's descriptor there names (`g`), and what the descriptor of the title's own heap +//! whose place it is names (`t`) – a resource's raw pointer, 0 for nothing (a null view), `UNKNOWN` +//! for one copied from descriptors the map does not see. Every path that writes, copies or clears +//! those PC descriptors stores into it right after the driver's call (`console_heap::note_pc_view`, +//! `publish`, `resync_slot`, `unregister`, `note_copied_view`): Relaxed atomics only – no lock, no +//! allocation, no thread-local outside tests (the device's hand-over of how a texture was made, +//! `device_x::take_last_made`, sits beside the thread-local `with_source` already reads) – so the +//! title's view calls pay one store a descriptor. The map has a word pair for every place the +//! shared heap can give out; what it costs is 16 bytes of resident memory per place given out (zero +//! pages until touched) – memory that also lowers the commit Wine reports as available, which the +//! DXC gate and the big lane's commit wait read. +//! +//! The census (`lines`: every 10 s on `xcl-view-census`, a thread of its own beside `xcl-activity`) +//! copies MADE, the textures kept in step, the lazy tiles and the shared heap's extent under their +//! own locks, one at a time and in that order (every texture a copy holds was made before the map is +//! read), then reads the map with no lock: a racy look, good for a level. +//! +//! "Named by no PC descriptor" is not "the GPU can no longer reach it" – what a release (a later +//! patch) has to close as well: +//! - work in flight may still read a descriptor overwritten since it was submitted: a release waits +//! for a `late_release` mark taken after the last overwrite to pass on every queue; +//! - slots the title wrote as memory since the last submit are mirrored only at the next submit's +//! resync, and descriptors the title builds in its own encoding name no PC resource at all; +//! - a later view by address of the same (address, desc) finds the texture in MADE and names it +//! again: a release takes it out of MADE under MADE's lock in the same step; +//! - writes the map does not see (`untracked`, `outside`, `UNKNOWN`, V1) make the unnamed counts +//! upper bounds while any is non-zero; +//! - XCL's own references (uploads, lazy tiles, arena users, present's planes), and releasing an +//! active texture reactivates the shadowed ones under it (shadowed first); +//! - the resync walks shader-visible heaps only: a CPU-only heap's shared descriptors keep naming +//! what XCL put there after the title wrote the slot over (a CBV, a buffer V#, a copy) – reachable +//! through any T# that still carries the place (V1's and V2's "CPU-only slots not holding their +//! own T#"); +//! - a pass can miss a name that moved while it ran (a copy into a place already read, then an +//! overwrite of its source): unnamed needs two passes in a row ("in the last census too"). +//! And `resource_at`'s look-up and insert are two lock sections: two threads that miss the same view +//! at once both make a texture, and the second insert replaces the first in MADE – the first lives +//! on outside MADE (named by its view), where no release could reach it. Those inserts are counted +//! (`real::made_replaced`, V2): MADE's count is a floor of what views by address made (compare +//! `device_x::creation_stats`' "views by address"). + +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock}; + +use super::device_x::Made; +use super::real::ViewTexture; +use super::title_textures::Kept; + +/// What each PC view descriptor XCL keeps names, by its place in the shared heap: `g[i - lo]` the +/// shared heap's descriptor `i`, `t[i - lo]` the title heap's descriptor whose place is `i` (a +/// slot's SRV at its place, its UAV at the place + 1) – a resource's raw pointer, 0 none, `UNKNOWN` +/// not known. Places outside `[lo, lo + g.len())` are not kept (a test's window). +pub(super) struct Names { + lo: u32, + g: &'static [AtomicUsize], + t: &'static [AtomicUsize], + /// view writes into console heaps without a place in the shared heap (not shared, or it is full) + untracked: AtomicU64, + /// view writes and copies into PC heaps that are not console heaps + outside: AtomicU64, +} + +/// A descriptor copied from one the map does not see. +pub(super) const UNKNOWN: usize = usize::MAX; + +/// bytes of a lazy texture's tile (`lazy_tex`) +const TILE: u64 = 0x1_0000; + +static NAMES: OnceLock = OnceLock::new(); + +impl Names { + /// The map of places from `lo` over `words`: the first half the shared heap's, the second the + /// title heaps'. + fn over(lo: u32, words: &'static [AtomicUsize]) -> Names { + let (g, t) = words.split_at(words.len() / 2); + Names { lo, g, t, untracked: AtomicU64::new(0), outside: AtomicU64::new(0) } + } + + #[inline] + fn cell(&self, of: &'static [AtomicUsize], i: u32) -> Option<&'static AtomicUsize> { + of.get(i.checked_sub(self.lo)? as usize) + } + + /// What `of` holds at place `i` (outside the window: not known). + #[inline] + fn load(&self, of: &'static [AtomicUsize], i: u32) -> usize { + self.cell(of, i).map_or(UNKNOWN, |c| c.load(Relaxed)) + } + + #[inline] + fn store(&self, of: &'static [AtomicUsize], i: u32, v: usize) { + if let Some(c) = self.cell(of, i) { + c.store(v, Relaxed); + } + } + + /// The title heap's SRV of the slot at place `i` (with `uav` its UAV, at `i + 1`) now names + /// `res` – 0: a null view. + #[inline] + pub(super) fn title_view(&self, i: u32, uav: bool, res: usize) { + if let Some(j) = i.checked_add(uav as u32) { + self.store(self.t, j, res); + } + } + + /// The shared heap's descriptor `i` was copied from the title heap's (`console_heap::publish`). + #[inline] + pub(super) fn published(&self, i: u32) { + if let Some(c) = self.cell(self.g, i) { + c.store(self.load(self.t, i), Relaxed); + } + } + + /// A device copy of a view slot (`real::copy_console_slots`): both PC descriptors of the slot + /// at place `s` went to the slot at place `d`, in the title's heap and then in the shared heap. + #[inline] + pub(super) fn copied(&self, d: u32, s: u32) { + for j in 0..2u32 { + let (Some(dj), Some(sj)) = (d.checked_add(j), s.checked_add(j)) else { continue }; + let v = self.load(self.t, sj); + self.store(self.t, dj, v); + self.store(self.g, dj, v); + } + } + + /// A device copy into the slot at place `d` from descriptors the map does not see (a source + /// slot with no place in the shared heap, or no console slot at all). + #[inline] + pub(super) fn copied_unknown(&self, d: u32) { + for j in 0..2u32 { + if let Some(dj) = d.checked_add(j) { + self.store(self.t, dj, UNKNOWN); + self.store(self.g, dj, UNKNOWN); + } + } + } + + /// The resync put a null SRV at the shared heap's descriptor `i` (the slot's words turned a + /// buffer V#, a CBV or zeros). The UAV after it and the title heap's stay as they are, as in + /// the PC heaps. + #[inline] + pub(super) fn shared_cleared(&self, i: u32) { + self.store(self.g, i, 0); + } + + /// The resync copied the shared heap's descriptor `s` to `d` (an image T# the title copied + /// from another slot). + #[inline] + pub(super) fn shared_copied(&self, d: u32, s: u32) { + let v = self.load(self.g, s); + self.store(self.g, d, v); + } + + /// A heap's places `[first, first + count)` went back (`console_heap::unregister`): its title + /// heap's descriptors go with it. The shared heap's stay – readable through any T# that still + /// carries their place – until a new heap's views overwrite them: the census counts them in + /// released ranges. + pub(super) fn heap_gone(&self, first: u32, count: u32) { + let from = first.max(self.lo) - self.lo; + let to = first.saturating_add(count).saturating_sub(self.lo).min(self.t.len() as u32); + for c in self.t.get(from as usize..to as usize).unwrap_or(&[]) { + c.store(0, Relaxed); + } + } + + #[inline] + pub(super) fn note_untracked(&self) { + self.untracked.fetch_add(1, Relaxed); + } + + #[inline] + pub(super) fn note_outside(&self, n: u64) { + self.outside.fetch_add(n, Relaxed); + } + + /// (tests) (the title heap's, the shared heap's) at place `i` + #[cfg(test)] + pub(super) fn at(&self, i: u32) -> (usize, usize) { + (self.load(self.t, i), self.load(self.g, i)) + } + + /// (tests) (untracked, outside) + #[cfg(test)] + pub(super) fn counts(&self) -> (u64, u64) { + (self.untracked.load(Relaxed), self.outside.load(Relaxed)) + } +} + +/// Whether the views' census is kept: with `XCL_ACTIVITY` (whose thread prints it), unless +/// `XCL_VIEW_CENSUS=0`. Off – the default, as XCL_ACTIVITY is off by default –: no map (a PC view +/// write costs one look that finds none), no hand-over of how views-by-address textures were made, +/// no V1-V3 lines (V4-V7 still print with XCL_ACTIVITY). Read once, before the title runs +/// (`host_main`), so no title call reads the environment. +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| super::title_textures::census_on() && std::env::var("XCL_VIEW_CENSUS").map_or(true, |v| v.trim() != "0")) +} + +/// The map of a shared heap of `cap` descriptors: made once, with the heap +/// (`console_heap::shared_heap`, under its lock – before any view goes there), when the census is +/// on, and kept for good as the heap is. One VirtualAlloc of 2 × `cap` words (32 MiB of address +/// space for 2^21 descriptors) whose zero pages cost nothing until a place is used; the slices are +/// `'static` over it, so nothing ever hands it to an allocator. No memory: no map, and no V1-V3. +pub(super) fn make(cap: u32) { + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE}; + if !on() || NAMES.get().is_some() || cap == 0 { + return; + } + let words = 2 * cap as usize; + let bytes = words * std::mem::size_of::(); + let p = unsafe { VirtualAlloc(std::ptr::null(), bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + if p.is_null() { + crate::xlog_warn!("view census: no memory for the map of the shared heap's {cap} places ({} MB): no view census", bytes >> 20); + return; + } + // (zeroed pages: an AtomicUsize has usize's layout, and 0 names nothing) + let all: &'static [AtomicUsize] = unsafe { std::slice::from_raw_parts(p as *const AtomicUsize, words) }; + if NAMES.set(Names::over(0, all)).is_ok() { + crate::xlog_info!("view census: a map of the shared heap's {cap} places ({} MB of address space; 16 bytes of memory for each place given out)", bytes >> 20); + } +} + +#[cfg(test)] +thread_local! { + /// (tests) this thread's window of the map instead of the process's (`names_for_test`) + static TEST_NAMES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The map – none while the census is off. (Tests: this thread's window while it has one.) +#[inline] +pub(super) fn names() -> Option<&'static Names> { + #[cfg(test)] + if let Some(n) = TEST_NAMES.with(|t| t.get()) { + return Some(n); + } + NAMES.get() +} + +/// View writes or copies of `n` descriptors into PC heaps that are not console heaps (counted while +/// the census is on). +#[inline] +pub(super) fn note_outside(n: u64) { + if let Some(m) = names() { + m.note_outside(n); + } +} + +/// (tests) a map of its own over places `[lo, lo + len)` – a small array that lives for good. +#[cfg(test)] +pub(super) fn window(lo: u32, len: u32) -> &'static Names { + let words: Vec = (0..2 * len as usize).map(|_| AtomicUsize::new(0)).collect(); + Box::leak(Box::new(Names::over(lo, Box::leak(words.into_boxed_slice())))) +} + +/// (tests) `window(lo, len)` stands in for the process's map on this thread – what the device hooks +/// this thread calls store into – until the guard goes (the suite's threads share the process's). +#[cfg(test)] +pub(super) fn names_for_test(lo: u32, len: u32) -> (&'static Names, impl Drop) { + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + TEST_NAMES.with(|t| t.set(None)); + } + } + let n = window(lo, len); + TEST_NAMES.with(|t| t.set(Some(n))); + (n, Restore) +} + +// ---- the census -------------------------------------------------------------------------------- + +/// Where the PC descriptors that name a texture are (a pass's flags): a shared-heap descriptor of a +/// place in use, one in a released range, a title heap's, a shared-heap descriptor of a CPU-only +/// heap's slot not holding its own T# (the title wrote it over). +const SHARED: u8 = 1; +const RELEASED: u8 = 2; +const TITLE: u8 = 4; +const STALE: u8 = 8; + +/// What a pass read in the map (V1). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Scan { + /// shared-heap descriptors naming a resource; of them in released ranges, at places of CPU-only + /// slots not holding their own T# + g: u64, + released: u64, + stale: u64, + /// title heaps' descriptors naming a resource + t: u64, + /// descriptors naming what the map cannot tell + unknown: u64, +} + +/// One pass over the map's places below `next`: each value that names a resource is counted and +/// its texture – `interest` (resource → index of `flags`) – flagged by where it is. `free`: the +/// released ranges (first, count), sorted; `stale`: a bit per place of a CPU-only slot not holding +/// its own T# (`console_heap::cpu_only_stale`). +fn scan(names: &Names, next: u32, free: &[(u32, u32)], stale: &[u64], interest: &HashMap, flags: &mut [u8]) -> Scan { + let mut s = Scan::default(); + // (the first released range that does not end at or before the place) + let mut r = 0usize; + // (the last value looked up and what it gave: a slot's SRV and UAV, a title heap's and the + // shared heap's descriptor of a place are mostly the same) + let mut last: (usize, Option) = (0, None); + let end = next.min(names.lo.saturating_add(names.g.len() as u32)); + for i in names.lo..end { + let k = (i - names.lo) as usize; + let (gv, tv) = (names.g[k].load(Relaxed), names.t[k].load(Relaxed)); + if gv == 0 && tv == 0 { + continue; + } + while r < free.len() && free[r].0.saturating_add(free[r].1) <= i { + r += 1; + } + let released = r < free.len() && free[r].0 <= i; + let at_stale = stale.get(i as usize / 64).is_some_and(|&w| (w >> (i % 64)) & 1 != 0); + for (v, title) in [(gv, false), (tv, true)] { + if v == 0 { + continue; + } + if v == UNKNOWN { + s.unknown += 1; + continue; + } + let flag = if title { + s.t += 1; + TITLE + } else { + s.g += 1; + if released { + s.released += 1; + RELEASED + } else if at_stale { + s.stale += 1; + STALE + } else { + SHARED + } + }; + if v != last.0 { + last = (v, interest.get(&v).copied()); + } + if let Some(x) = last.1 { + flags[x] |= flag; + } + } + } + s +} + +/// A count with its PC bytes and its lazy tiles' bytes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Tally { + n: u64, + pc: u64, + tiles: u64, +} + +impl Tally { + fn add(&mut self, pc: u64, tiles: u64) { + self.n += 1; + self.pc += pc; + self.tiles += tiles; + } +} + +/// How a texture is named, from its flags. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Naming { + /// by no PC descriptor + None, + /// only by a title heap's descriptor (a device copy from it can name it again) + TitleOnly, + /// only by shared-heap descriptors in released ranges + ReleasedOnly, + /// by no shared-heap descriptor in use but those of CPU-only slots not holding their own T# (and + /// maybe title heaps' or released ones) + StaleOnly, + Named, +} + +fn naming(f: u8) -> Naming { + match f { + 0 => Naming::None, + TITLE => Naming::TitleOnly, + RELEASED => Naming::ReleasedOnly, + f if f & SHARED == 0 && f & STALE != 0 => Naming::StaleOnly, + _ => Naming::Named, + } +} + +/// What a pass says about the textures (V2: MADE's; V3: the census's of every source). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct Census { + /// MADE's entries, of them no texture (it could not be made) + made: u64, + failed: u64, + /// MADE's textures: their PC bytes (committed ones: a lazy one's memory is its tiles) and + /// tiles; the lazy ones among them + all: Tally, + lazy: u64, + /// MADE's textures by where the census has them: active, shadowed, retired from it (kept in + /// step once – `retire_range`), never kept; of those in arenas + active: u64, + shadowed: u64, + retired: u64, + never: u64, + arenas: u64, + /// MADE's textures named by no PC descriptor, by the same four + unnamed: [Tally; 4], + /// MADE's textures named only by a title heap's descriptor, only in released ranges, only by + /// CPU-only slots not holding their own T# + title_only: Tally, + released_only: Tally, + stale_only: Tally, + /// MADE's textures unnamed in this pass and in the last + again: Tally, + /// the census's (every source): active, shadowed; of them named by no PC descriptor; named + /// only as above + kept: [Tally; 2], + kept_unnamed: [Tally; 2], + kept_title_only: Tally, + kept_released_only: Tally, + kept_stale_only: Tally, +} + +/// The textures' classes: `made` MADE's copy, `kept` the census's sorted by resource, `tiles` +/// (resource → its lazy tiles), `flag(res)` from the pass (0: named by no PC descriptor), `last` +/// MADE's textures unnamed in the last pass. Also this pass's unnamed MADE textures. PC bytes are +/// the census's (its entry's) if it has the texture, else how it was made; a lazy texture's are 0: +/// its memory is its tiles. +fn classify(made: &[ViewTexture], kept: &[Kept], tiles: &HashMap, flag: impl Fn(usize) -> u8, last: &HashSet) -> (Census, HashSet) { + let mut c = Census::default(); + let mut unnamed = HashSet::new(); + let tile_bytes = |res: usize| tiles.get(&res).copied().unwrap_or(0) * TILE; + for k in kept { + let (pc, t) = (if k.lazy { 0 } else { k.pc }, tile_bytes(k.res)); + let a = k.shadowed as usize; + c.kept[a].add(pc, t); + match naming(flag(k.res)) { + Naming::None => c.kept_unnamed[a].add(pc, t), + Naming::TitleOnly => c.kept_title_only.add(pc, t), + Naming::ReleasedOnly => c.kept_released_only.add(pc, t), + Naming::StaleOnly => c.kept_stale_only.add(pc, t), + Naming::Named => {} + } + } + for v in made { + c.made += 1; + if v.res == 0 { + c.failed += 1; + continue; + } + let k = kept.binary_search_by_key(&v.res, |k| k.res).ok().map(|i| &kept[i]); + let lazy = k.map_or_else(|| v.made.is_some_and(|m| m.how == Made::Lazy), |k| k.lazy); + let pc = if lazy { 0 } else { k.map_or_else(|| v.made.map_or(0, |m| m.pc), |k| k.pc) }; + let t = tile_bytes(v.res); + c.all.add(pc, t); + c.lazy += lazy as u64; + let class = match k { + Some(k) if !k.shadowed => { + c.active += 1; + 0 + } + Some(_) => { + c.shadowed += 1; + 1 + } + None if v.made.is_some_and(|m| m.kept) => { + c.retired += 1; + 2 + } + None => { + c.never += 1; + c.arenas += v.made.is_some_and(|m| m.how == Made::Arena) as u64; + 3 + } + }; + match naming(flag(v.res)) { + Naming::None => { + c.unnamed[class].add(pc, t); + if last.contains(&v.res) { + c.again.add(pc, t); + } + unnamed.insert(v.res); + } + Naming::TitleOnly => c.title_only.add(pc, t), + Naming::ReleasedOnly => c.released_only.add(pc, t), + Naming::StaleOnly => c.stale_only.add(pc, t), + Naming::Named => {} + } + } + (c, unnamed) +} + +/// (tests) A pass over `names` below `next` (`free`: released ranges, sorted) with MADE's textures +/// `made` and an empty census: those named by no PC descriptor (sorted), and how many are named +/// only in released ranges. +#[cfg(test)] +pub(super) fn unnamed_for_test(names: &Names, next: u32, free: &[(u32, u32)], made: &[ViewTexture]) -> (Vec, u64) { + let (_, c, unnamed) = pass(names, next, free, &[], made, &[], &HashMap::new(), &HashSet::new()); + let mut u: Vec = unnamed.into_iter().collect(); + u.sort_unstable(); + (u, c.released_only.n) +} + +/// (tests) MADE's textures by where the census `kept` has them – (active, shadowed, retired, never +/// kept) – and how many are counted live (all that are textures). +#[cfg(test)] +pub(super) fn classes_for_test(made: &[ViewTexture], kept: &[Kept]) -> ([u64; 4], u64) { + let mut k = kept.to_vec(); + k.sort_unstable_by_key(|k| k.res); + let (c, _) = classify(made, &k, &HashMap::new(), |_| 0, &HashSet::new()); + ([c.active, c.shadowed, c.retired, c.never], c.all.n) +} + +/// One pass over `names` (places below `next`; `free` and `stale` as `scan` has them): every +/// texture of `made` and `kept` (sorted by resource) flagged by what names it, then classified – +/// the pass's reading, its census and its unnamed MADE textures. +#[allow(clippy::too_many_arguments)] +fn pass(names: &Names, next: u32, free: &[(u32, u32)], stale: &[u64], made: &[ViewTexture], kept: &[Kept], tiles: &HashMap, last: &HashSet) -> (Scan, Census, HashSet) { + let mut interest: HashMap = HashMap::with_capacity(made.len() + kept.len()); + for r in made.iter().map(|v| v.res).chain(kept.iter().map(|k| k.res)).filter(|&r| r != 0 && r != UNKNOWN) { + let n = interest.len(); + interest.entry(r).or_insert(n); + } + let mut flags = vec![0u8; interest.len()]; + let s = scan(names, next, free, stale, &interest, &mut flags); + let (c, unnamed) = classify(made, kept, tiles, |r| interest.get(&r).map_or(0, |&x| flags[x]), last); + (s, c, unnamed) +} + +// ---- ranges of title addresses (arenas, textures, sparse tiles) --------------------------------- + +/// `r` (start, end) as sorted disjoint runs. +fn union(mut r: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + r.retain(|&(a, b)| a < b); + r.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(r.len()); + for (a, b) in r { + match out.last_mut() { + Some(l) if a <= l.1 => l.1 = l.1.max(b), + _ => out.push((a, b)), + } + } + out +} + +/// What two lists of sorted disjoint runs both cover. +fn intersect(a: &[(usize, usize)], b: &[(usize, usize)]) -> Vec<(usize, usize)> { + let (mut i, mut j, mut out) = (0, 0, Vec::new()); + while i < a.len() && j < b.len() { + let (lo, hi) = (a[i].0.max(b[j].0), a[i].1.min(b[j].1)); + if lo < hi { + out.push((lo, hi)); + } + if a[i].1 < b[j].1 { + i += 1; + } else { + j += 1; + } + } + out +} + +/// What sorted disjoint runs `a` cover and `b` do not. +fn minus(a: &[(usize, usize)], b: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let mut j = 0; + for &(start, end) in a { + while j < b.len() && b[j].1 <= start { + j += 1; + } + let mut lo = start; + let mut k = j; + while k < b.len() && b[k].0 < end && lo < end { + if b[k].0 > lo { + out.push((lo, b[k].0)); + } + lo = lo.max(b[k].1); + k += 1; + } + if lo < end { + out.push((lo, end)); + } + } + out +} + +fn bytes(r: &[(usize, usize)]) -> u64 { + r.iter().map(|&(a, b)| (b - a) as u64).sum() +} + +/// V5's numbers. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct ArenaFigures { + n: u64, + sum: u64, + /// their title addresses as runs + runs: Vec<(usize, usize)>, + /// bytes by where an arena's first address is: plain memory, windows 0-3 + by_place: [u64; 5], + /// sparse tiles mapped under them + under: u64, +} + +/// The arenas (id, first title address, bytes, users): their count, sum, union, places +/// (`window_of`: None plain memory) and the mapped sparse tiles (sorted runs) under them. +fn arena_figures(arenas: &[(u64, usize, usize, u32)], window_of: impl Fn(usize) -> Option, mapped: &[(usize, usize)]) -> ArenaFigures { + let mut f = ArenaFigures { n: arenas.len() as u64, ..Default::default() }; + for &(_, base, size, _) in arenas { + f.sum += size as u64; + f.by_place[window_of(base).map_or(0, |k| (k + 1).min(4))] += size as u64; + } + f.runs = union(arenas.iter().map(|&(_, base, size, _)| (base, base.saturating_add(size))).collect()); + f.under = bytes(&intersect(&f.runs, mapped)); + f +} + +/// Arenas whose every user is a views-by-address texture no PC descriptor names – what releasing +/// those would free whole (an arena goes 2 s after its last user, `vram`): (count, bytes). +/// `users` (resource, its arena), `unnamed` the unnamed MADE textures. +fn arenas_of_unnamed(arenas: &[(u64, usize, usize, u32)], users: &[(usize, u64)], unnamed: &HashSet) -> (u64, u64) { + let mut by_arena: HashMap = HashMap::new(); + for &(res, id) in users { + if unnamed.contains(&res) { + *by_arena.entry(id).or_default() += 1; + } + } + arenas + .iter() + .filter(|&&(id, _, _, users)| users > 0 && by_arena.get(&id).is_some_and(|&n| n >= users)) + .fold((0, 0), |(n, b), &(_, _, size, _)| (n + 1, b + size as u64)) +} + +/// V7's numbers: sparse tiles mapped; under the textures kept in step, under active ones, under +/// shadowed ones only; under both arenas (`arena_runs`) and textures kept in step. +fn tile_figures(kept: &[Kept], arena_runs: &[(usize, usize)], mapped: &[(usize, usize)]) -> [u64; 5] { + let runs = |shadowed: bool| union(kept.iter().filter(|k| k.shadowed == shadowed).map(|k| (k.va, k.va.saturating_add(k.size as usize))).collect()); + let (active, shadowed) = (runs(false), runs(true)); + let all = union(active.iter().chain(shadowed.iter()).copied().collect()); + [ + bytes(mapped), + bytes(&intersect(&all, mapped)), + bytes(&intersect(&active, mapped)), + bytes(&intersect(&minus(&shadowed, &active), mapped)), + bytes(&intersect(&intersect(arena_runs, &all), mapped)), + ] +} + +/// V6's list: up to 8 format pairs, most aliases first (`(first's, alias's) → (aliases, PC bytes)`), +/// or "none"; with the number of pairs and of aliases in all. +fn alias_list(mut pairs: Vec<((u32, u32), u64, u64)>) -> (String, usize, u64) { + pairs.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + let aliases = pairs.iter().map(|p| p.1).sum(); + let list: Vec = pairs.iter().take(8).map(|&((fa, fb), n, pc)| format!("{fa}/{fb} ×{n} ({} MB)", pc >> 20)).collect(); + (if list.is_empty() { "none".to_string() } else { list.join(", ") }, pairs.len(), aliases) +} + +// ---- the lines (`XCL_ACTIVITY`, every 10 s; MB = bytes >> 20) ------------------------------------ + +/// What V1 prints besides the pass's reading. +struct Extent { + next: u32, + cap: u32, + /// descriptors in released ranges, ranges + freed: u64, + ranges: usize, + untracked: u64, + outside: u64, + /// places of CPU-only slots not holding their own T# – the title wrote over them, zeroed them or + /// never wrote them, or XCL put a buffer V#, a CBV, a BVH or a zero T# there (#70 / #71 buffer + /// views, #17, a shape XCL cannot describe) + stale: u64, + ms: u64, +} + +fn mb(b: u64) -> u64 { + b >> 20 +} + +fn v1(e: &Extent, s: &Scan) -> String { + format!( + "view census: the shared heap gave out {} of {} descriptors ({} in {} released ranges); descriptors naming a resource: {} in the shared heap ({} of them in released ranges), {} in the title's heaps; {} naming what the map cannot tell; view writes outside the map: {} into console heaps without a place in the shared heap, {} into heaps that are not console heaps; this census took {} ms; places of CPU-only slots not holding their own T# {}, the shared heap's descriptors there naming a resource {}", + e.next, e.cap, e.freed, e.ranges, s.g, s.released, s.t, s.unknown, e.untracked, e.outside, e.ms, e.stale, s.stale + ) +} + +fn v2(c: &Census, replaced: u64) -> String { + let u = &c.unnamed; + format!( + "view census: views by address: {} textures made ({} could not be), {} MB on the PC, {} lazy with {} MB of tiles; kept in step {} active + {} shadowed, {} retired from the census, {} never kept ({} of them in arenas); named by no PC descriptor: {} active ({} MB, {} MB of tiles), {} shadowed ({} MB, {} MB of tiles), {} retired ({} MB, {} MB of tiles), {} never kept ({} MB, {} MB of tiles); named only by a title heap's descriptor {} ({} MB), only in released ranges {} ({} MB); named only by the shared descriptors of CPU-only slots not holding their own T# {} ({} MB); named by none in the last census too {} ({} MB, {} MB of tiles); made twice at once for one view {} (the first of each lives on outside this count)", + c.made, + c.failed, + mb(c.all.pc), + c.lazy, + mb(c.all.tiles), + c.active, + c.shadowed, + c.retired, + c.never, + c.arenas, + u[0].n, + mb(u[0].pc), + mb(u[0].tiles), + u[1].n, + mb(u[1].pc), + mb(u[1].tiles), + u[2].n, + mb(u[2].pc), + mb(u[2].tiles), + u[3].n, + mb(u[3].pc), + mb(u[3].tiles), + c.title_only.n, + mb(c.title_only.pc), + c.released_only.n, + mb(c.released_only.pc), + c.stale_only.n, + mb(c.stale_only.pc), + c.again.n, + mb(c.again.pc), + mb(c.again.tiles), + replaced + ) +} + +fn v3(c: &Census) -> String { + let (k, u) = (&c.kept, &c.kept_unnamed); + format!( + "view census: textures kept in step: {} active ({} MB on the PC, {} MB of tiles), {} shadowed ({} MB, {} MB of tiles); named by no PC descriptor: {} active ({} MB, {} MB of tiles), {} shadowed ({} MB, {} MB of tiles); named only by a title heap's descriptor {} ({} MB), only in released ranges {} ({} MB); named only by the shared descriptors of CPU-only slots not holding their own T# {} ({} MB)", + k[0].n, + mb(k[0].pc), + mb(k[0].tiles), + k[1].n, + mb(k[1].pc), + mb(k[1].tiles), + u[0].n, + mb(u[0].pc), + mb(u[0].tiles), + u[1].n, + mb(u[1].pc), + mb(u[1].tiles), + c.kept_title_only.n, + mb(c.kept_title_only.pc), + c.kept_released_only.n, + mb(c.kept_released_only.pc), + c.kept_stale_only.n, + mb(c.kept_stale_only.pc) + ) +} + +fn v4(b: &[u64; 7]) -> String { + format!( + "view census: lazy-eligible textures committed instead, MB on the PC: format {}, small {}, kind {}, present {}, overhead {}, failed {}, host {}", + mb(b[0]), + mb(b[1]), + mb(b[2]), + mb(b[3]), + mb(b[4]), + mb(b[5]), + mb(b[6]) + ) +} + +/// `of_unnamed`: arenas used only by unnamed views-by-address textures (count, bytes) – with the map. +fn v5(f: &ArenaFigures, of_unnamed: Option<(u64, u64)>) -> String { + let p = &f.by_place; + let mut l = format!( + "view census: arenas: {} ({} MB) over {} MB of title addresses; by place: plain memory {} MB, window 0 {} MB, window 1 {} MB, window 2 {} MB, window 3 {} MB; sparse tiles mapped under them {} MB", + f.n, + mb(f.sum), + mb(bytes(&f.runs)), + mb(p[0]), + mb(p[1]), + mb(p[2]), + mb(p[3]), + mb(p[4]), + mb(f.under) + ); + if let Some((n, b)) = of_unnamed { + l += &format!("; used only by views-by-address textures no PC descriptor names {n} ({} MB)", mb(b)); + } + l +} + +fn v6(list: &str, pairs: usize, aliases: u64) -> String { + format!("view census: same-range aliases by console format (the first's/the alias's: aliases, MB on the PC): {list} – {pairs} pairs of formats, {aliases} aliases in all") +} + +fn v7(t: &[u64; 5]) -> String { + format!( + "view census: sparse tiles mapped {} MB; under textures kept in step {} MB ({} MB under active ones, {} MB under shadowed ones only); under both arenas and textures kept in step {} MB", + mb(t[0]), + mb(t[1]), + mb(t[2]), + mb(t[3]), + mb(t[4]) + ) +} + +/// MADE's textures unnamed in the last pass (the census thread's) +static LAST: Mutex>> = Mutex::new(None); + +/// The census's lines (`host.rs`: every 10 s on `xcl-view-census` – 7 lines, none at any +/// other time): V1-V3 with the map (`on`, a shared heap and its map made), V4-V7 always. Every +/// table is copied under its own lock, one at a time, and worked on with none held. +pub(super) fn lines() -> Vec { + let t0 = std::time::Instant::now(); + // (in this order: every texture a copy holds was made before the map is read) + let map = names(); + let mut made = Vec::new(); + let mut replaced = 0; + if map.is_some() { + super::real::view_textures(&mut made); + replaced = super::real::made_replaced(); + } + let mut kept = Vec::new(); + super::title_textures::snapshot(&mut kept); + kept.sort_unstable_by_key(|k| k.res); + let mut first = None; + let mut unnamed = HashSet::new(); + if let Some(m) = map { + let mut lazy = Vec::new(); + super::lazy_tex::tiles_by_texture(&mut lazy); + let tiles: HashMap = lazy.into_iter().map(|(r, n)| (r, u64::from(n))).collect(); + if let Some((next, cap, free)) = super::console_heap::global_extent() { + let mut stale = vec![0u64; next as usize / 64 + 1]; + let mut stale_places = 0u64; + super::console_heap::cpu_only_stale(|i| { + if let Some(w) = stale.get_mut(i as usize / 64) { + if (*w >> (i % 64)) & 1 == 0 { + stale_places += 1; + } + *w |= 1 << (i % 64); + } + }); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + let none = HashSet::new(); + let (s, c, now) = pass(m, next, &free, &stale, &made, &kept, &tiles, last.as_ref().unwrap_or(&none)); + unnamed = now.clone(); + *last = Some(now); + let (untracked, outside) = (m.untracked.load(Relaxed), m.outside.load(Relaxed)); + let freed = free.iter().map(|f| u64::from(f.1)).sum(); + first = Some((Extent { next, cap, freed, ranges: free.len(), untracked, outside, stale: stale_places, ms: 0 }, s, c)); + } + } + // (b)-(e) + let skipped = super::lazy_tex::skip_bytes(); + let mut arenas = Vec::new(); + super::vram::arena_ranges(&mut arenas); + let mapped = super::sparse::mapped_ranges(); + // (`made`: the census never makes the window – the host's start-up report did, before the title) + let u = crate::gpu::uma::made(); + let af = arena_figures(&arenas, |a| u.and_then(|u| u.window_of(a)), &mapped); + let of_unnamed = first.as_ref().map(|_| { + let mut users = Vec::new(); + super::vram::arena_users(&mut users); + arenas_of_unnamed(&arenas, &users, &unnamed) + }); + let (list, pairs, aliases) = alias_list(super::title_textures::alias_pairs()); + let tf = tile_figures(&kept, &af.runs, &mapped); + let ms = t0.elapsed().as_millis() as u64; + let mut out = Vec::with_capacity(7); + if let Some((mut e, s, c)) = first { + e.ms = ms; + out.push(v1(&e, &s)); + out.push(v2(&c, replaced)); + out.push(v3(&c)); + } + out.push(v4(&skipped)); + out.push(v5(&af, of_unnamed)); + out.push(v6(&list, pairs, aliases)); + out.push(v7(&tf)); + out +} + +#[cfg(test)] +mod tests { + use super::super::device_x::MadeAs; + use super::*; + + const A: usize = 0x7A1E_2A01; + const B: usize = 0x7A1E_2A02; + const C: usize = 0x7A1E_2A03; + + fn kept(res: usize, va: usize, size: u64, pc: u64, lazy: bool, shadowed: bool) -> Kept { + Kept { res, va, size, pc, lazy, shadowed } + } + + fn made_as(how: Made, pc: u64, kept: bool) -> Option { + Some(MadeAs { how, pc, kept }) + } + + /// The flags `pass` gives one texture of interest (`res`) over `names` below `next`. + fn flags_of(names: &Names, next: u32, free: &[(u32, u32)], stale: &[u64], res: &[usize]) -> (Scan, Vec) { + let interest: HashMap = res.iter().enumerate().map(|(i, &r)| (r, i)).collect(); + let mut flags = vec![0u8; res.len()]; + let s = scan(names, next, free, stale, &interest, &mut flags); + (s, flags) + } + + /// A view made in a slot names its texture in the title heap's descriptor; its publication + /// copies that to the shared heap's; a later view replaces it there in turn (M1, M2). + #[test] + fn a_view_and_its_publication_name_the_texture_in_both_heaps() { + let m = window(0, 64); + m.title_view(4, false, A); + assert_eq!(m.at(4), (A, 0), "the title heap's descriptor first"); + m.published(4); + assert_eq!(m.at(4), (A, A), "then the shared heap's"); + m.title_view(4, false, B); + m.published(4); + assert_eq!(m.at(4), (B, B), "a later view replaces it"); + m.title_view(4, true, C); + assert_eq!((m.at(4), m.at(5)), ((B, B), (C, 0)), "a UAV goes at the place after the SRV's"); + let (_, f) = flags_of(m, 64, &[], &[], &[A, B, C]); + assert_eq!(f, vec![0, SHARED | TITLE, TITLE], "A unnamed; B in both heaps; C in the title's only"); + // places outside a window are not kept + let w = window(16, 4); + w.title_view(15, false, A); + w.title_view(19, true, A); + w.published(20); + assert_eq!((w.at(15), w.at(16), w.at(19), w.at(20)), ((UNKNOWN, UNKNOWN), (0, 0), (0, 0), (UNKNOWN, UNKNOWN))); + } + + /// A device copy carries both descriptors of a slot – the title heap's and, published, the + /// shared heap's; a copy from what the map does not see is not known, and counted (M3). + #[test] + fn a_device_copy_carries_both_descriptors_of_a_slot() { + let m = window(0, 64); + m.title_view(10, false, A); + m.title_view(10, true, B); + m.copied(20, 10); + assert_eq!((m.at(20), m.at(21)), ((A, A), (B, B))); + m.copied_unknown(30); + assert_eq!((m.at(30), m.at(31)), ((UNKNOWN, UNKNOWN), (UNKNOWN, UNKNOWN))); + let (s, f) = flags_of(m, 64, &[], &[], &[A, B]); + assert_eq!(f, vec![SHARED | TITLE, SHARED | TITLE]); + assert_eq!(s, Scan { g: 2, released: 0, stale: 0, t: 4, unknown: 4 }); + } + + /// A null view or a buffer's stores what it names: the texture it replaced is named no more + /// (M4). + #[test] + fn a_null_or_buffer_view_unnames_the_texture_it_replaces() { + let m = window(0, 64); + let buffer = 0x7A1E_2B00; + m.title_view(4, false, A); + m.published(4); + m.title_view(6, false, A); + m.published(6); + m.title_view(4, false, 0); + m.published(4); + m.title_view(6, false, buffer); + m.published(6); + assert_eq!((m.at(4), m.at(6)), ((0, 0), (buffer, buffer))); + let (s, f) = flags_of(m, 64, &[], &[], &[A]); + assert_eq!(f, vec![0], "A unnamed"); + assert_eq!((s.g, s.t), (1, 1), "the buffer's descriptors name a resource"); + } + + /// The resync changes the shared heap's descriptors only, as it does the PC heaps: a cleared + /// slot leaves its texture named by the title heap's descriptor; a mirrored one names the + /// source's (M5). + #[test] + fn the_resync_changes_the_shared_heap_only() { + let m = window(0, 64); + m.title_view(4, false, A); + m.published(4); + m.title_view(8, false, B); + m.published(8); + m.shared_cleared(4); + assert_eq!(m.at(4), (A, 0)); + m.shared_copied(12, 8); + assert_eq!(m.at(12), (0, B), "a T# copied as memory: the shared heap's only"); + let (_, f) = flags_of(m, 64, &[], &[], &[A, B]); + assert_eq!(f, vec![TITLE, SHARED | TITLE]); + assert_eq!(naming(f[0]), Naming::TitleOnly); + // (a source outside a window: not known) + let w = window(16, 8); + w.shared_copied(16, 40); + assert_eq!(w.at(16), (0, UNKNOWN)); + } + + /// A released heap's title heap's descriptors go; the shared heap's stay, counted in released + /// ranges until a new heap's views (SRV and UAV) overwrite them (M6, M7). + #[test] + fn a_released_heap_takes_its_title_descriptors_and_leaves_the_shared_ones_counted_as_released() { + let m = window(0, 64); + m.title_view(0, false, A); + m.published(0); + m.title_view(0, true, A); + m.published(1); + m.heap_gone(0, 16); + assert_eq!((m.at(0), m.at(1)), ((0, A), (0, A))); + let (s, f) = flags_of(m, 64, &[(0, 16)], &[], &[A]); + assert_eq!(f, vec![RELEASED]); + assert_eq!(naming(f[0]), Naming::ReleasedOnly); + assert_eq!((s.g, s.released, s.t), (2, 2, 0)); + // a new heap's views there + m.title_view(0, false, C); + m.published(0); + m.title_view(0, true, C); + m.published(1); + let (_, f) = flags_of(m, 64, &[], &[], &[A, C]); + assert_eq!(f, vec![0, SHARED | TITLE], "A unnamed, C named"); + // (a heap's places partly in a window) + let w = window(8, 8); + for i in 8..16 { + w.title_view(i, false, B); + } + w.heap_gone(4, 6); + w.heap_gone(14, 100); + assert_eq!((8..16).map(|i| w.at(i).0).collect::>(), [0, 0, B, B, B, B, 0, 0]); + } + + /// A pass flags each texture by where it is named: the ends of a released range, a place of a + /// CPU-only slot the title wrote over, runs of one value, values the map cannot tell; places + /// past `next` are not read (M8, M9). + #[test] + fn the_scan_flags_each_texture_once_and_knows_released_ranges_ends() { + let m = window(0, 64); + let put = |i: u32, g: usize, t: usize| { + m.title_view(i, false, g); + m.published(i); + m.title_view(i, false, t); + }; + put(15, A, 0); + put(16, B, 0); + put(23, B, 0); + put(24, C, 0); + // a run of one value (an SRV/UAV pair, T = G), then another texture, then the first again + for i in 30..34 { + put(i, C, C); + } + put(34, A, B); + put(35, C, 0); + put(40, UNKNOWN, UNKNOWN); + // places 48 and 49 of a CPU-only slot the title wrote over + put(48, A, A); + put(49, A, 0); + put(60, B, 0); + let mut stale = vec![0u64; 1]; + stale[0] |= 3 << 48; + let free = [(16, 8), (50, 2)]; + let (s, f) = flags_of(m, 60, &free, &stale, &[A, B, C]); + assert_eq!(f, vec![SHARED | STALE | TITLE, RELEASED | TITLE, SHARED | TITLE]); + assert_eq!(s, Scan { g: 12, released: 2, stale: 2, t: 6, unknown: 2 }); + // only the released range's ends + let (_, f) = flags_of(m, 64, &[(16, 8)], &[], &[B]); + assert_eq!(f, vec![SHARED | RELEASED | TITLE], "place 60 is read with next 64"); + let w = window(0, 64); + w.title_view(23, false, A); + w.published(23); + w.title_view(23, false, 0); + w.title_view(24, false, B); + w.published(24); + w.title_view(15, false, C); + w.published(15); + w.title_view(15, false, 0); + let (_, f) = flags_of(w, 64, &[(16, 8)], &[], &[A, B, C]); + assert_eq!(f, vec![RELEASED, SHARED | TITLE, SHARED]); + assert_eq!(naming(SHARED | STALE), Naming::Named); + assert_eq!(naming(STALE | TITLE), Naming::StaleOnly); + assert_eq!(naming(STALE | RELEASED), Naming::StaleOnly); + assert_eq!(naming(RELEASED | TITLE), Naming::Named); + } + + /// MADE's textures by where the census has them – active, shadowed, retired from it (dropped by + /// `retire_range`, alive in MADE), never kept, in arenas, failed – with the PC bytes from the + /// census's entry when it has one, else from how they were made, a lazy one's as its tiles; the + /// unnamed ones in this pass and the last (M10, M11). + #[test] + fn views_by_address_are_classified_active_shadowed_retired_and_never_kept() { + let (d, e, f, g, h) = (0x7A1E_2C01usize, 0x7A1E_2C02usize, 0x7A1E_2C03usize, 0x7A1E_2C04usize, 0x7A1E_2C05usize); + let made = vec![ + ViewTexture { res: A, made: made_as(Made::Committed, 0x10_0000, true) }, + ViewTexture { res: B, made: made_as(Made::Lazy, 0x40_0000, true) }, + ViewTexture { res: C, made: made_as(Made::Committed, 0x20_0000, true) }, + ViewTexture { res: d, made: made_as(Made::Committed, 0x30_0000, false) }, + ViewTexture { res: e, made: made_as(Made::Arena, 0, false) }, + ViewTexture { res: 0, made: None }, + ViewTexture { res: f, made: made_as(Made::Pages, 0, true) }, + ViewTexture { res: g, made: None }, + ]; + // the census: A active (its own bytes there), B shadowed and lazy, h a texture of the title's + let mut k = vec![kept(A, 0x1000, 0x1000, 0x50_0000, false, false), kept(B, 0x2000, 0x1000, 0x40_0000, true, true), kept(h, 0x3000, 0x1000, 0x60_0000, false, false)]; + k.sort_unstable_by_key(|k| k.res); + let tiles: HashMap = [(B, 3u64)].into_iter().collect(); + let flags: HashMap = [(f, TITLE), (g, SHARED)].into_iter().collect(); + let last: HashSet = [A, d].into_iter().collect(); + let (c, unnamed) = classify(&made, &k, &tiles, |r| flags.get(&r).copied().unwrap_or(0), &last); + assert_eq!((c.made, c.failed, c.all, c.lazy), (8, 1, Tally { n: 7, pc: 0x50_0000 + 0x20_0000 + 0x30_0000, tiles: 3 * TILE }, 1)); + assert_eq!((c.active, c.shadowed, c.retired, c.never, c.arenas), (1, 1, 2, 3, 1), "C and f retired (kept once), d, e and g never"); + assert_eq!( + c.unnamed, + [Tally { n: 1, pc: 0x50_0000, tiles: 0 }, Tally { n: 1, pc: 0, tiles: 3 * TILE }, Tally { n: 1, pc: 0x20_0000, tiles: 0 }, Tally { n: 2, pc: 0x30_0000, tiles: 0 }], + "a census entry's bytes are its own; a retired texture is live and unnamed" + ); + assert_eq!((c.title_only.n, c.released_only.n, c.stale_only.n), (1, 0, 0)); + assert_eq!(c.again, Tally { n: 2, pc: 0x50_0000 + 0x30_0000, tiles: 0 }, "A and d unnamed in the last pass too"); + assert_eq!(unnamed, [A, B, C, d, e].into_iter().collect()); + assert_eq!(c.kept, [Tally { n: 2, pc: 0x50_0000 + 0x60_0000, tiles: 0 }, Tally { n: 1, pc: 0, tiles: 3 * TILE }]); + assert_eq!(c.kept_unnamed, c.kept, "none of the census's is named"); + // the census's named only by a title heap's descriptor, only in a released range, only at + // CPU-only places + let flags: HashMap = [(A, TITLE), (B, RELEASED), (h, STALE | TITLE)].into_iter().collect(); + let (c, _) = classify(&made, &k, &tiles, |r| flags.get(&r).copied().unwrap_or(0), &last); + assert_eq!((c.kept_title_only, c.kept_released_only, c.kept_stale_only), (Tally { n: 1, pc: 0x50_0000, tiles: 0 }, Tally { n: 1, pc: 0, tiles: 3 * TILE }, Tally { n: 1, pc: 0x60_0000, tiles: 0 })); + assert_eq!(c.kept_unnamed, [Tally::default(); 2]); + } + + /// The pass over a window: what `pass` reads, flags and classifies, end to end. + #[test] + fn a_pass_reads_the_map_and_classifies_what_it_names() { + let m = window(100, 16); + m.title_view(100, false, A); + m.published(100); + m.title_view(102, true, B); + m.published(103); + m.heap_gone(102, 2); + let made = vec![ViewTexture { res: A, made: made_as(Made::Committed, 0x1000, false) }, ViewTexture { res: B, made: made_as(Made::Committed, 0x2000, false) }, ViewTexture { res: C, made: made_as(Made::Committed, 0x4000, false) }]; + let none = HashSet::new(); + let (s, c, unnamed) = pass(m, 116, &[(102, 2)], &[], &made, &[], &HashMap::new(), &none); + assert_eq!(s, Scan { g: 2, released: 1, stale: 0, t: 1, unknown: 0 }); + assert_eq!((c.unnamed[3].n, c.released_only.n), (1, 1), "C unnamed, B only in a released range"); + assert_eq!(unnamed, [C].into_iter().collect()); + } + + /// Arenas: their sum, the union of their title addresses, their places, the mapped sparse tiles + /// under them; those every user of which is an unnamed view-by-address texture. + #[test] + fn arena_ranges_give_their_union_their_places_and_the_tiles_under_them() { + const M: usize = 1 << 20; + let w = 1usize << 32; + let arenas = [(1u64, w, 100 * M, 2u32), (2, w + 50 * M, 100 * M, 1), (3, 5 * w + 10 * M, 100 * M, 0)]; + let window_of = |a: usize| (a >= w && a < 5 * w).then(|| (a - w) >> 32); + let mapped = [(w + 140 * M, w + 160 * M), (5 * w, 5 * w + 20 * M)]; + let f = arena_figures(&arenas, window_of, &mapped); + assert_eq!((f.n, f.sum, bytes(&f.runs)), (3, 300 * M as u64, 250 * M as u64)); + assert_eq!(f.runs, vec![(w, w + 150 * M), (5 * w + 10 * M, 5 * w + 110 * M)]); + assert_eq!(f.by_place, [100 * M as u64, 200 * M as u64, 0, 0, 0], "the third in plain memory"); + assert_eq!(f.under, 20 * M as u64, "10 MB under the first two, 10 under the third"); + let users = [(A, 1u64), (B, 1), (C, 2)]; + assert_eq!(arenas_of_unnamed(&arenas, &users, &[A, B, C].into_iter().collect()), (2, 200 * M as u64)); + assert_eq!(arenas_of_unnamed(&arenas, &users, &[A, C].into_iter().collect()), (1, 100 * M as u64), "the first still has B"); + assert_eq!(arenas_of_unnamed(&arenas, &[], &HashSet::new()), (0, 0), "an arena with no users is not counted"); + } + + /// Same-range aliases by console format pair: most aliases first, 8 at most, "none" without. + #[test] + fn same_range_aliases_are_counted_by_format_pair() { + let pairs: Vec<((u32, u32), u64, u64)> = (0..10u32).map(|i| ((i, i + 1), u64::from(i) + 1, u64::from(i) << 20)).collect(); + let (list, n, aliases) = alias_list(pairs); + assert_eq!(list, "9/10 ×10 (9 MB), 8/9 ×9 (8 MB), 7/8 ×8 (7 MB), 6/7 ×7 (6 MB), 5/6 ×6 (5 MB), 4/5 ×5 (4 MB), 3/4 ×4 (3 MB), 2/3 ×3 (2 MB)"); + assert_eq!((n, aliases), (10, 55)); + assert_eq!(alias_list(vec![((28, 29), 2, 0), ((28, 28), 2, 0)]).0, "28/28 ×2 (0 MB), 28/29 ×2 (0 MB)", "a tie in pair order"); + assert_eq!(alias_list(Vec::new()), ("none".to_string(), 0, 0)); + } + + /// Sparse tiles under textures kept in step: under active ones, under shadowed ones only, under + /// both arenas and textures; the runs' arithmetic. + #[test] + fn tiles_under_textures_split_active_and_shadowed_only() { + assert_eq!(union(vec![(5, 9), (0, 2), (2, 3), (8, 12), (20, 20)]), vec![(0, 3), (5, 12)]); + assert_eq!(intersect(&[(0, 10), (20, 30)], &[(5, 25), (28, 40)]), vec![(5, 10), (20, 25), (28, 30)]); + assert_eq!(minus(&[(0, 10), (20, 30)], &[(2, 4), (6, 22), (25, 26)]), vec![(0, 2), (4, 6), (22, 25), (26, 30)]); + assert!(minus(&[(0, 10)], &[(0, 10)]).is_empty()); + assert_eq!(minus(&[(0, 10), (12, 14)], &[(5, 13)]), vec![(0, 5), (13, 14)]); + const T: usize = 0x1_0000; + let k = [kept(A, 0, 4 * T as u64, 0, false, false), kept(B, 2 * T, 4 * T as u64, 0, false, true), kept(C, 10 * T, 2 * T as u64, 0, false, true)]; + let mapped = [(T, 7 * T), (10 * T, 11 * T)]; + let arena_runs = [(3 * T, 20 * T)]; + // (textures over [0, 6) and [10, 12) tiles: 6 of the 7 mapped tiles; [1, 4) active, [4, 6) + // and [10, 11) shadowed only; the arena over [3, 20): [3, 6) and [10, 11)) + let t = tile_figures(&k, &arena_runs, &mapped); + assert_eq!(t, [7 * T as u64, 6 * T as u64, 3 * T as u64, 3 * T as u64, 4 * T as u64]); + } + + /// The census's lines as they are printed (V1-V7). + #[test] + fn the_census_lines_say_what_they_count() { + let e = Extent { next: 4096, cap: 1 << 21, freed: 512, ranges: 2, untracked: 3, outside: 4, stale: 6, ms: 12 }; + let s = Scan { g: 1000, released: 10, stale: 5, t: 900, unknown: 7 }; + assert_eq!( + v1(&e, &s), + "view census: the shared heap gave out 4096 of 2097152 descriptors (512 in 2 released ranges); descriptors naming a resource: 1000 in the shared heap (10 of them in released ranges), 900 in the title's heaps; 7 naming what the map cannot tell; view writes outside the map: 3 into console heaps without a place in the shared heap, 4 into heaps that are not console heaps; this census took 12 ms; places of CPU-only slots not holding their own T# 6, the shared heap's descriptors there naming a resource 5" + ); + let t = |n: u64| Tally { n, pc: n << 20, tiles: n << 21 }; + let c = Census { + made: 50, + failed: 1, + all: t(49), + lazy: 9, + active: 10, + shadowed: 20, + retired: 8, + never: 11, + arenas: 2, + unnamed: [t(1), t(2), t(3), t(4)], + title_only: t(5), + released_only: t(6), + stale_only: t(7), + again: t(8), + kept: [t(30), t(40)], + kept_unnamed: [t(11), t(12)], + kept_title_only: t(13), + kept_released_only: t(14), + kept_stale_only: t(15), + }; + assert_eq!( + v2(&c, 3), + "view census: views by address: 50 textures made (1 could not be), 49 MB on the PC, 9 lazy with 98 MB of tiles; kept in step 10 active + 20 shadowed, 8 retired from the census, 11 never kept (2 of them in arenas); named by no PC descriptor: 1 active (1 MB, 2 MB of tiles), 2 shadowed (2 MB, 4 MB of tiles), 3 retired (3 MB, 6 MB of tiles), 4 never kept (4 MB, 8 MB of tiles); named only by a title heap's descriptor 5 (5 MB), only in released ranges 6 (6 MB); named only by the shared descriptors of CPU-only slots not holding their own T# 7 (7 MB); named by none in the last census too 8 (8 MB, 16 MB of tiles); made twice at once for one view 3 (the first of each lives on outside this count)" + ); + assert_eq!( + v3(&c), + "view census: textures kept in step: 30 active (30 MB on the PC, 60 MB of tiles), 40 shadowed (40 MB, 80 MB of tiles); named by no PC descriptor: 11 active (11 MB, 22 MB of tiles), 12 shadowed (12 MB, 24 MB of tiles); named only by a title heap's descriptor 13 (13 MB), only in released ranges 14 (14 MB); named only by the shared descriptors of CPU-only slots not holding their own T# 15 (15 MB)" + ); + assert_eq!( + v4(&[1 << 20, 2 << 20, 3 << 20, 4 << 20, 5 << 20, 6 << 20, 7 << 20]), + "view census: lazy-eligible textures committed instead, MB on the PC: format 1, small 2, kind 3, present 4, overhead 5, failed 6, host 7" + ); + let f = ArenaFigures { n: 3, sum: 300 << 20, runs: vec![(0, 250 << 20)], by_place: [1 << 20, 2 << 20, 3 << 20, 4 << 20, 5 << 20], under: 20 << 20 }; + let five = "view census: arenas: 3 (300 MB) over 250 MB of title addresses; by place: plain memory 1 MB, window 0 2 MB, window 1 3 MB, window 2 4 MB, window 3 5 MB; sparse tiles mapped under them 20 MB"; + assert_eq!(v5(&f, None), five); + assert_eq!(v5(&f, Some((2, 64 << 20))), format!("{five}; used only by views-by-address textures no PC descriptor names 2 (64 MB)")); + assert_eq!( + v6("28/29 ×2 (1 MB)", 1, 2), + "view census: same-range aliases by console format (the first's/the alias's: aliases, MB on the PC): 28/29 ×2 (1 MB) – 1 pairs of formats, 2 aliases in all" + ); + assert_eq!( + v7(&[5 << 20, 4 << 20, 3 << 20, 1 << 20, 2 << 20]), + "view census: sparse tiles mapped 5 MB; under textures kept in step 4 MB (3 MB under active ones, 1 MB under shadowed ones only); under both arenas and textures kept in step 2 MB" + ); + // no prefix of the tools' lines + for l in [v1(&e, &s), v2(&c, 0), v3(&c), v4(&[0; 7]), v5(&f, None), v6("none", 0, 0), v7(&[0; 5])] { + assert!(l.starts_with("view census: ") && !l.contains("XCL_SKIP_CS") && !l.contains("video memory:") && !l.contains("title textures made:"), "{l}"); + } + } + + /// The census's lines from the process's own tables: V4-V7 always, V1-V3 too with the map – the + /// shared heap made here makes it while the census is on (`EXTRA_ENV=XCL_ACTIVITY=1` in a + /// process of its own); each table is read under its own lock alone, and each line says what it + /// is. The census never makes the unified-memory window (`uma::made`): made by it, the window's + /// line would be on this thread – in a process where nothing made the window before. + #[test] + fn the_census_lines_come_from_the_process_s_tables() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::{D3D12CreateDevice, ID3D12Device}; + let shared = unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + super::super::console_heap::shared_heap(dev.as_ref().expect("D3D12 device")) + }; + assert_eq!(names().is_some(), on() && shared, "the map is made with the shared heap, and only while the census is on"); + let map = names().is_some() && super::super::console_heap::global_extent().is_some(); + let kept = crate::log::kept::keep(); + let l = lines(); + assert!(!kept.take().iter().any(|x| x.starts_with("UMA: ")), "the census made the window"); + drop(kept); + assert_eq!(l.len(), if map { 7 } else { 4 }, "{l:#?}"); + assert!(l.iter().all(|x| x.starts_with("view census: ")), "{l:#?}"); + if map { + assert!(l[0].starts_with("view census: the shared heap gave out ") && l[1].starts_with("view census: views by address: ") && l[2].starts_with("view census: textures kept in step: "), "{l:#?}"); + } + let v4 = l.len() - 4; + assert!(l[v4].starts_with("view census: lazy-eligible textures committed instead") && l[v4 + 1].starts_with("view census: arenas: ") && l[v4 + 2].starts_with("view census: same-range aliases") && l[v4 + 3].starts_with("view census: sparse tiles mapped"), "{l:#?}"); + } + + /// The switch: off without XCL_ACTIVITY; with it, on unless XCL_VIEW_CENSUS=0 (run in a process + /// of its own with `EXTRA_ENV` for the other cases). Off, the hooks find no map on threads + /// without a test window. + #[test] + fn the_census_switch_follows_xcl_activity_and_xcl_view_census() { + let activity = std::env::var_os("XCL_ACTIVITY").is_some(); + let zero = std::env::var("XCL_VIEW_CENSUS").is_ok_and(|v| v.trim() == "0"); + assert_eq!(on(), activity && !zero); + if !on() { + assert!(names().is_none(), "no map while the census is off"); + } + let (w, _guard) = names_for_test(0, 4); + assert!(names().is_some_and(|n| std::ptr::eq(n, w)), "a test window stands in on its thread"); + note_outside(5); + assert_eq!(w.counts(), (0, 5)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 7062502..05b186e 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -110,6 +110,19 @@ static MADE_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsi pub fn arena_bytes() -> (usize, usize) { (ARENAS.lock().unwrap().bytes(), MADE_BYTES.load(std::sync::atomic::Ordering::Relaxed)) } + +/// The arenas now – (id, first title address, bytes, resources placed in it) – into `out`, copied +/// under their lock (the view census, off the title's threads). +pub(super) fn arena_ranges(out: &mut Vec<(u64, usize, usize, u32)>) { + out.extend(ARENAS.lock().unwrap_or_else(|e| e.into_inner()).list.iter().map(|a| (a.id, a.base, a.size, a.users))); +} + +/// Every resource placed in an arena with its arena's id into `out` (the view census). +pub(super) fn arena_users(out: &mut Vec<(usize, u64)>) { + if let Some(m) = ARENA_OF.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + out.extend(m.iter().map(|(&res, &id)| (res, id))); + } +} static PLACED_TEXTURES: Mutex>> = Mutex::new(None); /// A texture backed by one of the aliasable D3D12 heaps. @@ -117,6 +130,19 @@ pub(super) fn is_placed_texture(resource: usize) -> bool { PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } +/// (tests) once `resource` left its arena (its last release done) and `IDLE` has passed, the arenas no +/// resource uses let go – as the next placement would: a test that made an arena leaves none for the +/// next one under `VRAM_TEST_LOCK` to count (`d32s8_targets_take_their_own_size_of_video_memory`). +#[cfg(test)] +pub(super) fn let_go_of_arena_for_test(resource: usize) { + let t = std::time::Instant::now(); + while ARENA_OF.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&resource)) && t.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + std::thread::sleep(IDLE + std::time::Duration::from_millis(100)); + ARENAS.lock().unwrap_or_else(|e| e.into_inner()).sweep(std::time::Instant::now()); +} + pub(super) fn forget(resource: usize) { let placed = PLACED_TEXTURES.lock().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); if placed { @@ -308,6 +334,7 @@ impl Pages { /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. unsafe fn map(&mut self, res: &ID3D12Resource, tiles: &[Tile]) { + let _ops = super::d3d_ops(); let mut heaps: Vec = tiles.iter().map(|t| t.0).collect(); heaps.sort_unstable(); heaps.dedup(); @@ -338,6 +365,7 @@ impl Pages { /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return /// to the pool even while the title keeps the COM object alive. unsafe fn unmap(&mut self, res: &ID3D12Resource, total: u32) { + let _ops = super::d3d_ops(); let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; let flag = D3D12_TILE_RANGE_FLAG_NULL; @@ -600,6 +628,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return }; let key = queue.as_raw() as usize; if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { + crate::waitwatch::note_gpu_wait("vram pages", key, &pages.fence, pages.value); if queue.Wait(&pages.fence, pages.value).is_ok() && super::list_x::trace_gpu_stall() { super::list_x::note_internal_wait(key, "texture page mappings", &pages.fence, pages.value); } @@ -885,7 +914,9 @@ mod tests { /// arenas no target uses go. Needs a hardware adapter (skips on WARP). #[test] fn d32s8_targets_take_their_own_size_of_video_memory() { - let _vram_guard = VRAM_TEST_LOCK.lock().unwrap(); + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + // (its targets' last releases wait for the GPU: no other test's work in flight meanwhile) + let _clocks = super::super::late_release::TEST_CLOCKS.lock().unwrap_or_else(|e| e.into_inner()); use windows::core::Interface; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::Common::*; @@ -978,7 +1009,8 @@ mod tests { drop((a, b)); // 2 s later the arenas no target uses are let go: one new target's is all that is left - std::thread::sleep(IDLE + Duration::from_millis(100)); + // (where last releases wait for the GPU and a grace, `late_release`, a moment more) + std::thread::sleep(IDLE + Duration::from_millis(500)); let last = place_at(0x50_0000_0000, &small); let small_size = dev.GetResourceAllocationInfo(0, &[small]).SizeInBytes as usize; assert_eq!(arena_bytes().0 - arenas0, small_size.next_multiple_of(PAGE)); diff --git a/crates/xcl/src/hle/dbghelp.rs b/crates/xcl/src/hle/dbghelp.rs new file mode 100644 index 0000000..26a8ec6 --- /dev/null +++ b/crates/xcl/src/hle/dbghelp.rs @@ -0,0 +1,241 @@ +//! dbghelp for the title's crash handler on a Mac host. +//! +//! GTA VI's crash handler loads dbghelp.dll and calls its MiniDumpWriteDump from a thread of its +//! own (game+0x1455e88dd, +0x1455e9714), with a dump type it was given at start. Under Wine, +//! dbghelp reads every module's debug information to describe the modules in the dump – XCL's own +//! DWARF too –, and Wine's DWARF expression evaluator divides by zero in it +//! (dbghelp.dll+0x157b1): the process ended with 0xc0000094 instead of the title's crash, its +//! handler unfinished (run 63). On a Mac host the title's MiniDumpWriteDump is Wine's, with +//! dbghelp kept to the modules' public symbols for the call (SYMOPT_PUBLICS_ONLY: no DWARF is +//! read), and without the kinds of dump that copy the process's memory wholesale (full memory, +//! private read-write and write-copy memory: tens of GB for a title here). +//! `XCL_TITLE_MINIDUMP=0`: none is written (the call fails with ERROR_NOT_SUPPORTED); +//! `XCL_TITLE_MINIDUMP=full`: the kind the title asked for. + +use std::ffi::c_void; +use std::sync::Mutex; + +use windows_sys::Win32::Foundation::{GetLastError, SetLastError, HANDLE}; + +use crate::pe::ImportName; + +/// The module the title's dbghelp.dll is routed to (`hle::build`): its MiniDumpWriteDump is +/// this one, every other name the system's dbghelp. +pub const DBGHELP: &str = "xcl-dbghelp.dll"; + +/// MINIDUMP_TYPE: MiniDumpWithFullMemory +const FULL_MEMORY: u32 = 0x2; +/// MINIDUMP_TYPE: MiniDumpWithPrivateReadWriteMemory +const PRIVATE_READ_WRITE_MEMORY: u32 = 0x200; +/// MINIDUMP_TYPE: MiniDumpWithPrivateWriteCopyMemory +const PRIVATE_WRITE_COPY_MEMORY: u32 = 0x1_0000; +/// The kinds of dump that copy the process's memory wholesale. +const WHOLESALE: u32 = FULL_MEMORY | PRIVATE_READ_WRITE_MEMORY | PRIVATE_WRITE_COPY_MEMORY; +const SYMOPT_PUBLICS_ONLY: u32 = 0x4000; +const ERROR_NOT_SUPPORTED: u32 = 50; + +/// Whether the title's dbghelp gets this MiniDumpWriteDump: on a Mac host (Wine's dbghelp). +pub fn enabled() -> bool { + crate::util::mac_host() +} + +pub fn exports() -> Vec<(&'static str, usize)> { + vec![("MiniDumpWriteDump", minidump_write_dump as *const () as usize)] +} + +/// What XCL_TITLE_MINIDUMP asks for. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Kind { + /// `0`: no dump + Nothing, + /// unset: the kind asked for, without the memory copied wholesale + Bounded, + /// `full`: the kind asked for + AsAsked, +} + +fn kind_from(v: Option<&str>) -> Kind { + match v.map(str::trim) { + Some("0") => Kind::Nothing, + Some(v) if v.eq_ignore_ascii_case("full") => Kind::AsAsked, + _ => Kind::Bounded, + } +} + +/// The MINIDUMP_TYPE written for one the title asked for (None: no dump). +fn written(asked: u32, kind: Kind) -> Option { + match kind { + Kind::Nothing => None, + Kind::Bounded => Some(asked & !WHOLESALE), + Kind::AsAsked => Some(asked), + } +} + +fn system(name: &str) -> Option { + crate::resolver::system_proc("dbghelp.dll", &ImportName::Name { hint: 0, name: name.into() }) +} + +/// Where a file handle leads, for the log. +unsafe fn file_path(file: HANDLE) -> String { + use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW; + let mut buf = [0u16; 520]; + let n = GetFinalPathNameByHandleW(file, buf.as_mut_ptr(), buf.len() as u32, 0) as usize; + if n == 0 || n > buf.len() { + return format!("file handle {:#x}", file as usize); + } + String::from_utf16_lossy(&buf[..n]) +} + +type MiniDumpWriteDump = unsafe extern "system" fn(HANDLE, u32, HANDLE, u32, *const c_void, *const c_void, *const c_void) -> i32; + +/// MiniDumpWriteDump as the title sees it on a Mac host (see the module's doc). +unsafe extern "system" fn minidump_write_dump( + process: HANDLE, + pid: u32, + file: HANDLE, + asked: u32, + exception: *const c_void, + user_streams: *const c_void, + callback: *const c_void, +) -> i32 { + let kind = kind_from(std::env::var("XCL_TITLE_MINIDUMP").ok().as_deref()); + write_minidump(kind, process, pid, file, asked, exception, user_streams, callback) +} + +/// `minidump_write_dump` with the kind of dump given. +#[allow(clippy::too_many_arguments)] +unsafe fn write_minidump( + kind: Kind, + process: HANDLE, + pid: u32, + file: HANDLE, + asked: u32, + exception: *const c_void, + user_streams: *const c_void, + callback: *const c_void, +) -> i32 { + // (dbghelp is not thread safe, and its options are the process's) + static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let path = file_path(file); + let write = system("MiniDumpWriteDump"); + let (Some(t), Some(write)) = (written(asked, kind), write) else { + crate::xlog_warn!( + "dbghelp: the title asks for a minidump (type {asked:#x}) into {path} – not written ({})", + if write.is_none() { "the system's dbghelp has no MiniDumpWriteDump" } else { "XCL_TITLE_MINIDUMP=0" } + ); + SetLastError(ERROR_NOT_SUPPORTED); + return 0; + }; + let write: MiniDumpWriteDump = std::mem::transmute(write); + // public symbols only for the call: the DWARF stays unread + let options = system("SymGetOptions").zip(system("SymSetOptions")).map(|(get, set)| { + let get: unsafe extern "system" fn() -> u32 = std::mem::transmute(get); + let set: unsafe extern "system" fn(u32) -> u32 = std::mem::transmute(set); + let was = get(); + set(was | SYMOPT_PUBLICS_ONLY); + (was, set) + }); + crate::xlog_warn!( + "dbghelp: the title writes a minidump (type {asked:#x}{}) into {path}", + if t != asked { format!(", written as {t:#x}: without the process's memory copied wholesale") } else { String::new() } + ); + let t0 = std::time::Instant::now(); + let ok = write(process, pid, file, t, exception, user_streams, callback); + let err = GetLastError(); + if let Some((was, set)) = options { + set(was); + } + let mut size = 0i64; + windows_sys::Win32::Storage::FileSystem::GetFileSizeEx(file, &mut size); + crate::xlog_warn!( + "dbghelp: the minidump {} ({size} bytes, {:.1} s){}", + if ok != 0 { "is written" } else { "failed" }, + t0.elapsed().as_secs_f64(), + if ok == 0 { format!(": error {err:#x}") } else { String::new() } + ); + SetLastError(err); + ok +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn what_xcl_title_minidump_asks_for() { + assert_eq!(kind_from(None), Kind::Bounded); + assert_eq!(kind_from(Some("1")), Kind::Bounded); + assert_eq!(kind_from(Some(" 0 ")), Kind::Nothing); + assert_eq!(kind_from(Some("FULL")), Kind::AsAsked); + // MiniDumpWithDataSegs | MiniDumpWithFullMemory | MiniDumpWithHandleData + assert_eq!(written(0x7, Kind::Bounded), Some(0x5)); + // … | MiniDumpWithPrivateReadWriteMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithThreadInfo + assert_eq!(written(0x1A01, Kind::Bounded), Some(0x1801)); + // MiniDumpWithPrivateWriteCopyMemory out; MiniDumpIgnoreInaccessibleMemory kept + assert_eq!(written(0x1_0841, Kind::Bounded), Some(0x841)); + assert_eq!(written(0x2_0002, Kind::Bounded), Some(0x2_0000)); + assert_eq!(WHOLESALE, (windows_sys::Win32::System::Diagnostics::Debug::MiniDumpWithFullMemory + | windows_sys::Win32::System::Diagnostics::Debug::MiniDumpWithPrivateReadWriteMemory + | windows_sys::Win32::System::Diagnostics::Debug::MiniDumpWithPrivateWriteCopyMemory) as u32); + assert_eq!(written(0x1_0843, Kind::AsAsked), Some(0x1_0843)); + assert_eq!(written(0x2, Kind::Nothing), None); + } + + /// The title's LoadLibrary("dbghelp.dll") is the system's dbghelp and GetProcAddress on it + /// finds the system's functions – but for MiniDumpWriteDump, which is XCL's. + #[test] + fn the_titles_dbghelp_is_the_systems_but_for_its_minidump() { + if !enabled() { + return; + } + let name = |s: &str| ImportName::Name { hint: 0, name: s.into() }; + let h = crate::resolver::load_library("dbghelp.dll").expect("LoadLibrary(dbghelp.dll)"); + assert_eq!(Some(h), crate::resolver::system_module("dbghelp.dll")); + assert_eq!(crate::resolver::get_proc_address(h, &name("MiniDumpWriteDump")), Some(minidump_write_dump as *const () as usize)); + let sym = crate::resolver::get_proc_address(h, &name("SymInitialize")); + assert!(sym.is_some() && sym == system("SymInitialize")); + // GetModuleHandle answers as the system does – the module, loaded now; NULL while it is + // not (kernelx's get_module_handle_of_a_real_dll_not_loaded_is_null) –, never XCL's + // pseudo handle, which knows only MiniDumpWriteDump + let wide = crate::util::wide("dbghelp.dll"); + let got = unsafe { crate::hle::kernelx::GetModuleHandleW(wide.as_ptr()) }; + assert_eq!(got, h); + assert_ne!(got, crate::modules::hle_handle(DBGHELP)); + } + + /// A minidump of this process – whose executable carries DWARF, as XCL's does – through the + /// title's MiniDumpWriteDump: written (Wine's dbghelp divided by zero reading that DWARF and + /// ended the process), without the process's memory, and dbghelp's options as they were. + #[test] + fn a_minidump_of_a_process_with_dwarf_is_written_without_its_memory() { + use windows_sys::Win32::Storage::FileSystem::{CreateFileW, DeleteFileW, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL}; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentProcessId}; + if !enabled() { + return; + } + let path = std::env::temp_dir().join(format!("xcl-minidump-test-{}.dmp", std::process::id())); + let wide = crate::util::wide(&path.to_string_lossy()); + unsafe { + let file = CreateFileW(wide.as_ptr(), 0xC000_0000, 0, std::ptr::null(), CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, std::ptr::null_mut()); + assert!(file != windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE); + let get: unsafe extern "system" fn() -> u32 = std::mem::transmute(system("SymGetOptions").unwrap()); + let before = get(); + // XCL_TITLE_MINIDUMP=0: nothing written, the call fails + let none = write_minidump(Kind::Nothing, GetCurrentProcess(), GetCurrentProcessId(), file, 0x3, std::ptr::null(), std::ptr::null(), std::ptr::null()); + let refused = windows_sys::Win32::Foundation::GetLastError(); + let mut empty = -1i64; + windows_sys::Win32::Storage::FileSystem::GetFileSizeEx(file, &mut empty); + // unset: MiniDumpWithDataSegs | MiniDumpWithFullMemory asked + let ok = write_minidump(Kind::Bounded, GetCurrentProcess(), GetCurrentProcessId(), file, 0x3, std::ptr::null(), std::ptr::null(), std::ptr::null()); + let mut size = 0i64; + windows_sys::Win32::Storage::FileSystem::GetFileSizeEx(file, &mut size); + windows_sys::Win32::Foundation::CloseHandle(file); + DeleteFileW(wide.as_ptr()); + assert_eq!((none, refused, empty), (0, ERROR_NOT_SUPPORTED, 0), "XCL_TITLE_MINIDUMP=0 writes nothing"); + assert_eq!(ok, 1, "the minidump is written"); + assert!(size > 0 && size < 64 << 20, "{size} bytes: the process's memory left out"); + assert_eq!(get(), before, "dbghelp's options as they were"); + } + } +} diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 04d33b2..582021d 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -35,19 +35,26 @@ use std::ffi::c_void; use std::os::windows::fs::FileExt; use std::os::windows::io::AsRawHandle; use std::collections::BTreeMap; -use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; use serde::{Deserialize, Serialize}; use windows_sys::core::GUID; use windows_sys::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE}; use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; -use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent}; +use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, GetCurrentThreadId, ResetEvent, SetEvent}; use crate::util::{HRESULT, S_OK}; const DLL: &str = "xcrdapi.dll"; +/// ms since the log began (`log::uptime`): the hold records +fn now_ms() -> u64 { + (crate::log::uptime() * 1000.0) as u64 +} + +const PAGE_BYTES: usize = crate::hle::kernelx::PHYS_PAGE_SIZE; + const E_NOTIMPL: HRESULT = 0x8000_4001u32 as i32; const E_NOINTERFACE: HRESULT = 0x8000_4002u32 as i32; const E_POINTER: HRESULT = 0x8000_4003u32 as i32; @@ -319,7 +326,7 @@ fn log_bcpack_refusal(r: &Request, k: u64, fill: bool, accept: bool) { warn_once( key, format_args!( - "mode {bc} unsupported (src={}, intermediate={}, dst={}, swizzle={}); {action}", + "mode {bc} unsupported or disabled (src={}, intermediate={}, dst={}, swizzle={}); {action}", r.source_size, r.intermediate_size, r.destination_size, @@ -478,11 +485,12 @@ impl std::ops::Deref for PageList { /// it named (snapshot at enqueue, as for a request that runs). enum FillTarget { Virtual, - Pages(PageList), + /// the pages at EnqueueRequest and the title's table (`Pages::table`) + Pages(PageList, Option), } /// Fill the title's destination of `r` (exactly `destination_size` bytes) with solid blocks. -unsafe fn bcpack_fill(r: &Request, target: &FillTarget) -> bool { +unsafe fn bcpack_fill(r: &Request, target: &FillTarget, counts: &Counts) -> bool { let Some((chunk_pattern, block_len)) = bcpack_fill_chunk(r.bcpack()) else { return false }; let n = r.destination_size as usize; let write = |dst: *mut u8, completed: usize, len: usize| { @@ -493,7 +501,10 @@ unsafe fn bcpack_fill(r: &Request, target: &FillTarget) -> bool { } }; let ok = match target { - FillTarget::Pages(pages) => crate::hle::kernelx::write_physical_pages_with(pages, r.destination_page_offset as usize, n, write), + FillTarget::Pages(pages, table) => { + let now = pages_now(&Pages { snapshot: pages.to_vec(), table: *table }, r, "destination", counts); + crate::hle::kernelx::write_physical_pages_with(&now, r.destination_page_offset as usize, n, write) + } FillTarget::Virtual => { if !writable(r.destination as usize, n) { return false; @@ -641,8 +652,9 @@ unsafe extern "system" fn factory_create_queue1(p: *mut c_void, desc: *const u8, static SEEN: AtomicBool = AtomicBool::new(false); if !SEEN.swap(true, Ordering::Relaxed) { crate::xlog_info!( - "DirectStorage: CreateQueue1 (0x20 desc), options = {extra:#x} (auto_submit_disabled = {})", - extra & QUEUE_OPT_AUTO_SUBMIT_DISABLED != 0 + "DirectStorage: CreateQueue1 (0x20 desc), options = {extra:#x} (auto_submit_disabled = {}{})", + extra & QUEUE_OPT_AUTO_SUBMIT_DISABLED != 0, + if extra & QUEUE_OPT_AUTO_SUBMIT_DISABLED != 0 && !honour_auto_submit_disabled() { ", ignored: XCL_DSTORAGE_AUTO_SUBMIT_DISABLED=0" } else { "" } ); } if extra & !QUEUE_OPT_AUTO_SUBMIT_DISABLED != 0 { @@ -780,7 +792,8 @@ unsafe extern "system" fn factory_create_status_array(_p: *mut c_void, capacity: if capacity == 0 || capacity > 1 << 20 { return E_INVALIDARG; } - let inner = Arc::new(StatusInner { slots: (0..capacity).map(|_| AtomicI32::new(E_PENDING)).collect() }); + // a slot nothing was enqueued into is complete (S_OK); EnqueueStatus makes it E_PENDING + let inner = Arc::new(StatusInner { slots: (0..capacity).map(|_| AtomicI32::new(S_OK)).collect() }); let o = new_object(status_vtbl(), inner); let hr = status_qi(o, riid, out); status_release(o); @@ -965,6 +978,299 @@ unsafe fn snapshot_page_array(ptr: u64, offset: u16, byte_len: u32) -> Result bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DSTORAGE_LATE_PAGES").map_or(true, |v| v.trim() != "0")) +} + +/// `XCL_DSTORAGE_AUTO_SUBMIT_DISABLED=0`: a queue made with AutoSubmitDisabled (CreateQueue1) +/// submits by itself at half full as every other queue does, as before upstream 5bff7bd – the +/// option is ignored, for a run that compares the two. Otherwise (unset, or anything but "0") +/// such a queue waits for the title's Submit and sends by itself only when full +/// (`QueueInner::submits_itself`). Read once. +fn honour_auto_submit_disabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| auto_submit_disabled_switch(std::env::var("XCL_DSTORAGE_AUTO_SUBMIT_DISABLED").ok().as_deref())) +} + +/// `XCL_DSTORAGE_AUTO_SUBMIT_DISABLED`'s value → whether the option is honoured: unless "0". +fn auto_submit_disabled_switch(v: Option<&str>) -> bool { + v.map_or(true, |v| v.trim() != "0") +} + +/// Whether `p` lies on the calling thread's stack: a page array there is gone by the request's +/// turn (titles pass arrays on the stack too), so its snapshot is all there is. +fn on_own_stack(p: u64) -> bool { + let (mut lo, mut hi) = (0usize, 0usize); + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits(&mut lo, &mut hi) }; + lo != 0 && (lo..hi).contains(&(p as usize)) +} + +/// A request's physical page array: the pages it named at EnqueueRequest, and where the title +/// keeps it – None for an array on the enqueuing thread's stack (or `XCL_DSTORAGE_LATE_PAGES=0`). +#[derive(Clone)] +struct Pages { + snapshot: Vec, + table: Option, +} + +impl Pages { + /// `byte_len` bytes at `offset` into the pages the array at `ptr` names. + unsafe fn take(ptr: u64, offset: u16, byte_len: u32) -> Result { + let snapshot = snapshot_page_array(ptr, offset, byte_len)?; + let table = (late_pages() && !on_own_stack(ptr)).then_some(ptr); + Ok(Pages { snapshot, table }) + } +} + +/// Entries of the title's page tables read again at their request's turn: (filled since +/// EnqueueRequest – 0 then –, moved to another page, cleared to 0); and requests that found an +/// entry still 0 there: (filled while XCL looked again, left 0). +static LATE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// (entries filled, moved to another page, cleared since EnqueueRequest; requests whose 0 entry +/// was filled while XCL looked again, requests whose entry stayed 0) +pub fn late_page_counts() -> [u64; 5] { + std::array::from_fn(|k| LATE[k].load(Ordering::Relaxed)) +} + +/// (diagnostic) What a queue's requests met beyond `LATE`, per queue (a test reads its own) and for +/// all queues (`COUNTS`, the probe line): +/// - the page a moved or cleared destination entry named at EnqueueRequest – where 0021 wrote – +/// by where it is at the request's turn (`class_old_pages`), and the ones not looked up; +/// - the entries the same at their turn as at EnqueueRequest; +/// - the tables not read at their turn (the EnqueueRequest copy used); +/// - the arrays on the enqueuing thread's stack (no table to read); +/// - CancelRequestsWithTag calls, the pending entries they took out, the requests the worker skipped. +const OLD_MAPPED: usize = 0; +const OLD_HOME: usize = 1; +const OLD_UNUSED: usize = 2; +const OLD_NOT_A_PAGE: usize = 3; +const OLD_IN_VIEW: usize = 4; +const OLD_NOT_LOOKED: usize = 5; +const UNCHANGED: usize = 6; +const UNREAD: usize = 7; +const ON_STACK: usize = 8; +const CANCELS: usize = 9; +const CANCELLED: usize = 10; +const SKIPPED: usize = 11; +const COUNT_KINDS: usize = 12; + +struct Counts([AtomicU64; COUNT_KINDS]); + +impl Counts { + const fn new() -> Counts { + Counts([const { AtomicU64::new(0) }; COUNT_KINDS]) + } + + /// `n` more of `k`, here and in `COUNTS`; how many all queues had before (the logs' caps) + fn add(&self, k: usize, n: u64) -> u64 { + self.0[k].fetch_add(n, Ordering::Relaxed); + COUNTS.0[k].fetch_add(n, Ordering::Relaxed) + } + + fn get(&self, k: usize) -> u64 { + self.0[k].load(Ordering::Relaxed) + } +} + +/// all queues' (never `add`ed to directly) +static COUNTS: Counts = Counts::new(); + +/// Looks at a page table still naming no page (an entry 0) at its request's turn, 1 ms apart: +/// the title may be filling it right now (a request a full queue sent before the title's +/// Submit). Requests in a row whose looks found nothing (`ZERO_IDLE`) stop the looks for a +/// second – a title that leaves an entry 0 on purpose must not slow its queue down by 8 ms a +/// request. +const ZERO_LOOKS: u32 = 8; +const ZERO_IDLE: u32 = 4; +static ZERO_FRUITLESS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); +static ZERO_QUIET_UNTIL_MS: AtomicU64 = AtomicU64::new(0); + +/// `now` (the table at `at`, `len` bytes) looked at again while an entry is 0 (`ZERO_LOOKS`). +unsafe fn look_again_while_zero(now: &mut [usize], at: u64, len: usize, r: &Request, what: &str) { + let ms = || (crate::log::uptime() * 1000.0) as u64; + if ms() < ZERO_QUIET_UNTIL_MS.load(Ordering::Relaxed) { + LATE[4].fetch_add(1, Ordering::Relaxed); + return; + } + let mut again = vec![0usize; now.len()]; + for _ in 0..ZERO_LOOKS { + std::thread::sleep(std::time::Duration::from_millis(1)); + if !read_own(at as usize, again.as_mut_ptr() as *mut u8, len) { + break; + } + now.copy_from_slice(&again); + if !now.contains(&0) { + LATE[3].fetch_add(1, Ordering::Relaxed); + ZERO_FRUITLESS.store(0, Ordering::Relaxed); + return; + } + } + let n = LATE[4].fetch_add(1, Ordering::Relaxed); + if n < 8 { + crate::xlog_info!( + "DirectStorage: {what} page table at {at:#x} still names no page (entry {} of {} is 0) after {ZERO_LOOKS} ms; {} bytes, file offset {:#x}", + now.iter().position(|&e| e == 0).unwrap_or(0), + now.len(), + r.destination_size, + r.offset + ); + } + if ZERO_FRUITLESS.fetch_add(1, Ordering::Relaxed) + 1 >= ZERO_IDLE { + ZERO_FRUITLESS.store(0, Ordering::Relaxed); + ZERO_QUIET_UNTIL_MS.store(ms() + 1000, Ordering::Relaxed); + } +} + +/// The pages a request's array names at its turn: the title's table read now (`late_pages`), or +/// the snapshot when there is no table to read or it cannot be read (counted, the first 8 logged). +/// With `XCL_DSTORAGE_LATE_PAGES=0`, the snapshot with its 0 entries read again (as before). +/// Entries the same then as now are counted; a destination entry that moved or was cleared has +/// the page it named before looked up (`class_old_pages`). +unsafe fn pages_now(p: &Pages, r: &Request, what: &str, counts: &Counts) -> Vec { + let Some(at) = p.table else { + return p.snapshot.clone(); + }; + let mut now = vec![0usize; p.snapshot.len()]; + let len = std::mem::size_of_val(&now[..]); + if !read_own(at as usize, now.as_mut_ptr() as *mut u8, len) { + // (the copy from EnqueueRequest is all there is: it may name a page the title freed since) + if counts.add(UNREAD, 1) < 8 { + crate::xlog_info!( + "DirectStorage: {what} page table at {at:#x} could not be read at its request's turn – the {} page(s) it named at EnqueueRequest are used; {} bytes, file offset {:#x}", + p.snapshot.len(), + r.destination_size, + r.offset + ); + } + return p.snapshot.clone(); + } + if now.contains(&0) { + look_again_while_zero(&mut now, at, len, r, what); + } + let mut unchanged = 0u64; + // (entry, the page it named at EnqueueRequest, the page it names now): a destination's moved + // and cleared entries + let mut changed: Vec<(usize, usize, usize)> = Vec::new(); + for (k, (&was, &is)) in p.snapshot.iter().zip(&now).enumerate() { + if was == is { + unchanged += u64::from(was != 0); + continue; + } + let class = if was == 0 { 0 } else if is == 0 { 2 } else { 1 }; + let n = LATE[class].fetch_add(1, Ordering::Relaxed); + if class != 0 && n < 8 { + crate::xlog_info!( + "DirectStorage: {what} page table entry {k} at {at:#x} changed after EnqueueRequest: {was:#x} -> {is:#x} (the page it named before: {}); {} bytes, file offset {:#x}", + crate::hle::kernelx::describe_physical_page(was), + r.destination_size, + r.offset + ); + } else if class == 0 && n.is_power_of_two() && n >= 1024 { + crate::xlog_info!("DirectStorage: {} page table entries filled in after EnqueueRequest so far", n + 1); + } + if class != 0 && what == "destination" { + changed.push((k, was, is)); + } + } + if unchanged != 0 { + counts.add(UNCHANGED, unchanged); + } + if !changed.is_empty() && old_pages() { + class_old_pages(&changed, at, r, counts); + } + now +} + +/// `XCL_DSTORAGE_OLD_PAGES=0`: the page a moved or cleared destination entry named at +/// EnqueueRequest is not looked up (`class_old_pages`: the kernel's lock, the GPU views'). +fn old_pages() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DSTORAGE_OLD_PAGES").map_or(true, |v| v.trim() != "0")) +} + +/// most old pages looked up for one request; µs of lookups in all, after which none is made +const OLD_PAGES_PER_REQUEST: usize = 16; +const OLD_PAGES_BUDGET_US: u64 = 2_000_000; +/// (probe line) requests whose old pages were looked up, µs in all, the longest (µs) +static OLD_LOOKS: AtomicU64 = AtomicU64::new(0); +static OLD_US: AtomicU64 = AtomicU64::new(0); +static OLD_US_MAX: AtomicU64 = AtomicU64::new(0); + +/// The pages moved or cleared destination entries named at EnqueueRequest – where 0021 wrote – +/// by where they are at the request's turn: mapped at a CPU address, at their home with memory, +/// at their home without (unused), no page; and whether a GPU view shows them. The kernel's lock +/// and the GPU views' are waited for (`describe_physical_page` only tries the kernel's: "at its +/// home" could be a lock it missed), one after the other, once a request; at most +/// `OLD_PAGES_PER_REQUEST` pages a request and `OLD_PAGES_BUDGET_US` in all (the rest counted as +/// not looked up). The first 4 of each kind are logged with the last write into that page. +fn class_old_pages(changed: &[(usize, usize, usize)], at: u64, r: &Request, counts: &Counts) { + use crate::hle::kernelx::PagePlace; + if OLD_US.load(Ordering::Relaxed) >= OLD_PAGES_BUDGET_US { + counts.add(OLD_NOT_LOOKED, changed.len() as u64); + return; + } + let (look, rest) = changed.split_at(changed.len().min(OLD_PAGES_PER_REQUEST)); + if !rest.is_empty() { + counts.add(OLD_NOT_LOOKED, rest.len() as u64); + } + let olds: Vec = look.iter().map(|c| c.1).collect(); + let t = std::time::Instant::now(); + // (one after the other, never one inside the other: the kernel's, the GPU views') + let places = crate::hle::kernelx::page_places(&olds); + let views = crate::hle::d3d12x::gpu_views::pages_in_views(&olds); + let us = t.elapsed().as_micros() as u64; + OLD_LOOKS.fetch_add(1, Ordering::Relaxed); + OLD_US_MAX.fetch_max(us, Ordering::Relaxed); + let before = OLD_US.fetch_add(us, Ordering::Relaxed); + if before < OLD_PAGES_BUDGET_US && before + us >= OLD_PAGES_BUDGET_US { + crate::xlog_info!("DirectStorage: old-page lookups took {} ms in all – none is made from now on (the probe line counts the pages not looked up)", (before + us) / 1000); + } + for ((&(k, was, is), place), &in_view) in look.iter().zip(&places).zip(&views) { + let kind = match place { + PagePlace::Mapped(_) => OLD_MAPPED, + PagePlace::Home(_) => OLD_HOME, + PagePlace::Unused => OLD_UNUSED, + PagePlace::NotAPage => OLD_NOT_A_PAGE, + }; + let n = counts.add(kind, 1); + if in_view { + counts.add(OLD_IN_VIEW, 1); + } + if n < 4 { + crate::xlog_info!( + "DirectStorage: destination page table entry {k} at {at:#x}: the page it named at EnqueueRequest, {was:#x}, is {}{} at the request's turn (its last DirectStorage write: {}); read at EnqueueRequest, its {} bytes (file offset {:#x}) went there – {}", + describe_place(place), + if in_view { " and in a GPU view" } else { "" }, + last_write_of_page(was), + r.destination_size, + r.offset, + if is == 0 { "the entry is 0 now".to_string() } else { format!("the entry names {is:#x} now") } + ); + } + } +} + +fn describe_place(p: &crate::hle::kernelx::PagePlace) -> String { + use crate::hle::kernelx::PagePlace; + match *p { + PagePlace::Mapped(a) => format!("mapped at {a:#x}"), + PagePlace::Home(h) => format!("at its home {h:#x}, which holds memory"), + PagePlace::Unused => "at its home, which holds no memory (never used, or given back)".into(), + PagePlace::NotAPage => "no page of a live allocation".into(), + } +} + unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; @@ -1016,10 +1322,538 @@ pub fn counters() -> (u64, u64, u64) { (REQUESTS.load(Ordering::Relaxed), BYTES.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed)) } +/// Local diagnostic: the DirectStorage writes into each 64 KiB page of title memory, so a copy out +/// of a GPU view can tell whether its source was ever streamed in, and a crash which request wrote +/// the byte it read (`last_write_at`). A write into a physical page – a page array's, or one at an +/// address where the title mapped a page (or that is a page's home while the page is there) – is +/// kept by that page: the title maps a page at one address, then another (GTA VI's pool: 63,632 +/// pages that go between their homes, the pool and its CPU view), and its bytes go with it. Any +/// other write is kept by the 64 KiB address it landed at, and the address a write into a page +/// landed at keeps that page (a crash's report with the page map busy). Each key keeps its newest +/// `WRITES` writes, and which bytes of the page each wrote. +#[derive(Clone, Copy, Default, Debug)] +struct PageWrite { + /// the request (its number in `execute`'s "request #k" lines), when (s since the log began) + seq: u64, + t: f32, + /// the request's destination size and options (their low 32 bits: the rest is reserved) + bytes: u32, + options: u32, + /// the bytes of the 64 KiB page it wrote: `from` to `last`, both included + from: u16, + last: u16, + /// the request's destination (a page array: the title's table) + dest: u64, +} + +const WRITES: usize = 4; + +/// The newest writes into one page (or at one address), newest last: a write over all the bytes +/// of one before it takes its place; past `WRITES`, the oldest goes. +#[derive(Clone, Copy, Default)] +struct Writes { + w: [PageWrite; WRITES], + n: u8, +} + +impl Writes { + fn add(&mut self, x: PageWrite) { + let mut kept = [PageWrite::default(); WRITES]; + let mut n = 0; + for e in self.all() { + if !(x.from <= e.from && e.last <= x.last) { + kept[n] = *e; + n += 1; + } + } + if n == WRITES { + kept.copy_within(1.., 0); + n -= 1; + } + kept[n] = x; + *self = Writes { w: kept, n: n as u8 + 1 }; + } + + fn all(&self) -> &[PageWrite] { + &self.w[..(self.n as usize).min(WRITES)] + } + + /// the newest write over byte `at` of the page + fn over(&self, at: u16) -> Option<&PageWrite> { + self.all().iter().rev().find(|e| e.from <= at && at <= e.last) + } + + fn newest(&self) -> Option<&PageWrite> { + self.all().last() + } + + fn by_seq(&self, seq: u64) -> Option<&PageWrite> { + self.all().iter().find(|e| e.seq == seq) + } +} + +/// A record by key that keeps its newest keys: at most `half` in `new`, the ones before in `old`; +/// when `new` is full it becomes `old` and what `old` held is forgotten (counted). A key written +/// again goes back to `new` with what it had. +struct Recent { + new: std::collections::HashMap, + old: std::collections::HashMap, + half: usize, + forgotten: u64, +} + +impl Recent { + fn new(half: usize) -> Recent { + Recent { new: Default::default(), old: Default::default(), half, forgotten: 0 } + } + + /// `k`'s value, made one of the newest + fn newest(&mut self, k: usize) -> &mut V { + if !self.new.contains_key(&k) { + let carried = self.old.remove(&k); + if self.new.len() >= self.half { + self.forgotten += self.old.len() as u64; + self.old = std::mem::take(&mut self.new); + } + self.new.insert(k, carried.unwrap_or_default()); + } + self.new.entry(k).or_default() + } + + fn get(&self, k: usize) -> Option<&V> { + self.new.get(&k).or_else(|| self.old.get(&k)) + } + + fn len(&self) -> usize { + self.new.len() + self.old.len() + } +} + +/// Where a write into a physical page landed for the CPU: that page, and the write +#[derive(Clone, Copy, Default)] +struct Landed { + page: usize, + seq: u64, +} + +/// Keys kept, at 7/8 of a power of two so a full map stays at that many buckets (std's HashMap +/// grows at 7/8): 114,688 physical pages (GTA VI has about 75,000) and landing addresses, 57,344 +/// other addresses (twice as many with `=address`, where every write is kept by address). +const PAGES_HALF: usize = 114_688; +const ADDRESSES_HALF: usize = 57_344; +const LANDED_HALF: usize = 114_688; + +struct WriteRecord { + /// writes into physical pages, by page + pages: Recent, + /// writes into memory with no page there, by 64 KiB address (with `=address`: every write) + addresses: Recent, + /// the page and the write that last landed at each 64 KiB address + landed: Recent, +} + +impl WriteRecord { + fn new(mode: PageLog) -> WriteRecord { + WriteRecord { + pages: Recent::new(PAGES_HALF), + addresses: Recent::new(if mode == PageLog::Address { PAGES_HALF } else { ADDRESSES_HALF }), + landed: Recent::new(LANDED_HALF), + } + } + + fn forgotten(&self) -> u64 { + self.pages.forgotten + self.addresses.forgotten + self.landed.forgotten + } +} + +static PAGE_WRITES: Mutex> = Mutex::new(None); +/// (probe line) the record's keys and the keys it forgot, set with each write +static RECORD_PAGES: AtomicU64 = AtomicU64::new(0); +static RECORD_ADDRESSES: AtomicU64 = AtomicU64::new(0); +static RECORD_LANDED: AtomicU64 = AtomicU64::new(0); +static RECORD_FORGOTTEN: AtomicU64 = AtomicU64::new(0); +static ROTATIONS: AtomicU64 = AtomicU64::new(0); +/// (probe line) virtual writes looked up in the page map: how many, µs in all, the longest (µs) +static WRITE_LOOKS: AtomicU64 = AtomicU64::new(0); +static WRITE_US: AtomicU64 = AtomicU64::new(0); +static WRITE_US_MAX: AtomicU64 = AtomicU64::new(0); + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum PageLog { + Off, + Address, + Page, +} + +/// `XCL_DSTORAGE_PAGE_LOG`: what `note_written` keeps for a crash's report (`eh`), the `[diag]` +/// copies and `XCL_TRACE_PAGES`. By default (`Page`) writes into physical pages by page, other +/// writes by address, and a look at an address finds its page first; `=address`: every write by +/// the address its bytes landed at, looked up by address alone (0022's record); `=0`: nothing. +fn page_log() -> PageLog { + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("XCL_DSTORAGE_PAGE_LOG").as_deref().map(str::trim) { + Ok("0") => PageLog::Off, + Ok("address") => PageLog::Address, + _ => PageLog::Page, + }) +} + +/// What a request wrote (`note_written`): through its page array – the pages, the address each +/// landed at for the CPU (`kernelx::write_physical_pages_at`), the first page's offset, the bytes – +/// or `n` bytes at an address. +enum Written<'a> { + Pages { pages: &'a [usize], landed: &'a [usize], offset: usize, n: usize }, + At { at: usize, n: usize }, +} + +/// The bytes `[start, start + n)` (n > 0) of a run of 64 KiB pages, page by page: (the page's +/// index – from 0 for a page array's offset, the address / 64 KiB for an address –, the first +/// and the last byte of it written). +fn page_spans(start: usize, n: usize) -> impl Iterator { + let end = start + n; + (start / PAGE_BYTES..end.div_ceil(PAGE_BYTES)).map(move |i| { + let lo = start.max(i * PAGE_BYTES) - i * PAGE_BYTES; + let hi = end.min((i + 1) * PAGE_BYTES) - i * PAGE_BYTES - 1; + (i, lo as u16, hi as u16) + }) +} + +/// Keep what request `seq` (`execute`'s number) wrote where (`XCL_DSTORAGE_PAGE_LOG`). +fn note_written(w: Written, r: &Request, seq: u64) { + use crate::hle::kernelx::PageHere; + let mode = page_log(); + if mode == PageLog::Off { + return; + } + // what went where: (the physical page it went into – None: the memory at the address –, the + // 64 KiB address it landed at, the first and the last byte of that page it wrote) + let mut parts: Vec<(Option, usize, u16, u16)> = Vec::new(); + match w { + Written::Pages { pages, landed, offset, n } if n > 0 => { + for (i, from, last) in page_spans(offset, n) { + let (Some(&p), Some(&a)) = (pages.get(i), landed.get(i)) else { break }; + parts.push((Some(p), a, from, last)); + } + } + Written::At { at, n } if n > 0 => { + let first = at / PAGE_BYTES; + // (the kernel's locks before the record's, never under it: a crash's report reads it) + let here = if mode == PageLog::Page { + let t = std::time::Instant::now(); + let h = crate::hle::kernelx::pages_here(first * PAGE_BYTES, (at + n).div_ceil(PAGE_BYTES) - first); + let us = t.elapsed().as_micros() as u64; + WRITE_LOOKS.fetch_add(1, Ordering::Relaxed); + WRITE_US.fetch_add(us, Ordering::Relaxed); + WRITE_US_MAX.fetch_max(us, Ordering::Relaxed); + h + } else { + Vec::new() + }; + for (i, from, last) in page_spans(at, n) { + // (a page mapped here, or at its home here, holds the bytes; the home of a page + // mapped elsewhere does not) + let page = match here.get(i - first) { + Some(Some(PageHere::Mapped(p) | PageHere::Home(p))) => Some(*p), + _ => None, + }; + parts.push((page, i * PAGE_BYTES, from, last)); + } + } + _ => return, + } + // (`XCL_TRACE_PAGES`: asked before the record's lock – the traced list has a lock of its own) + let traced: Vec<(Option, usize)> = if crate::hle::kernelx::tracing() { + parts + .iter() + .filter(|(p, a, ..)| crate::hle::kernelx::traced(*a) || p.is_some_and(crate::hle::kernelx::traced)) + .map(|&(p, a, ..)| (p, a)) + .collect() + } else { + Vec::new() + }; + let t = crate::log::uptime() as f32; + let x = |from: u16, last: u16| PageWrite { seq, t, bytes: r.destination_size, options: r.options as u32, from, last, dest: r.destination }; + let forgot = { + let mut g = PAGE_WRITES.lock().unwrap_or_else(|e| e.into_inner()); + let rec = g.get_or_insert_with(|| WriteRecord::new(mode)); + let before = rec.forgotten(); + for &(p, a, from, last) in &parts { + match (mode, p) { + (PageLog::Page, Some(p)) => { + rec.pages.newest(p).add(x(from, last)); + *rec.landed.newest(a) = Landed { page: p, seq }; + } + _ => rec.addresses.newest(a).add(x(from, last)), + } + } + RECORD_PAGES.store(rec.pages.len() as u64, Ordering::Relaxed); + RECORD_ADDRESSES.store(rec.addresses.len() as u64, Ordering::Relaxed); + RECORD_LANDED.store(rec.landed.len() as u64, Ordering::Relaxed); + RECORD_FORGOTTEN.store(rec.forgotten(), Ordering::Relaxed); + rec.forgotten() - before + }; + if forgot != 0 { + let n = ROTATIONS.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!( + "DirectStorage: the write record forgot {forgot} of its oldest keys ({} in all): it keeps the newest {PAGES_HALF} to {} pages, {ADDRESSES_HALF} to {} other addresses", + RECORD_FORGOTTEN.load(Ordering::Relaxed), + 2 * PAGES_HALF, + 2 * ADDRESSES_HALF + ); + } + } + for (page, a) in traced { + crate::xlog_info!( + "[trace] DirectStorage request #{seq} (options {:#x}{}) wrote {} bytes at {:#x} (page offset {}): page {a:#x}{} now {:?} non-zero bytes", + r.options, + if r.dest_physical_pages() { ", physical pages" } else { "" }, + r.destination_size, + r.destination, + r.destination_page_offset, + page.map_or(String::new(), |p| format!(" (physical page {p:#x})")), + crate::hle::kernelx::page_nonzero(a) + ); + } +} + +fn describe_write(w: &PageWrite) -> String { + format!("request #{} at {:.3} s (options {:#x}, destination {:#x}, {} bytes)", w.seq, w.t, w.options, w.dest, w.bytes) +} + +/// The record's answer for the byte at `addr`: what has its data there (`here` – None: not looked +/// up, `XCL_DSTORAGE_PAGE_LOG=address`; Err: the page map was busy), then the writes kept for it. +fn describe_writes(rec: Option<&WriteRecord>, addr: usize, here: Option, ()>>) -> String { + use crate::hle::kernelx::PageHere; + if page_log() == PageLog::Off { + return "not recorded (XCL_DSTORAGE_PAGE_LOG=0)".into(); + } + let (base, off) = (addr & !(PAGE_BYTES - 1), (addr & (PAGE_BYTES - 1)) as u16); + let span = |w: &PageWrite| format!("{} – bytes {:#x}-{:#x} of it", describe_write(w), w.from, w.last); + // what the address itself recorded (no page there then) + let at_address = || match rec.and_then(|r| r.addresses.get(base)) { + None => "no DirectStorage request".to_string(), + Some(ws) => match ws.over(off) { + Some(w) => format!("{} – bytes {:#x}-{:#x} of its 64 KiB page", describe_write(w), w.from, w.last), + None => format!("no DirectStorage write kept at this address covers byte {off:#x} of its 64 KiB page – its last: {}", ws.newest().map_or("none".into(), span)), + }, + }; + // where the last write that landed here went (a page that may have moved since) – `gone`: the + // page map was read and no page is here (the page is not; its bytes may be: a page freed + // where it was mapped leaves them, and so does a released block of committed unified memory) + let landed = |gone: bool| match rec.and_then(|r| r.landed.get(base)) { + None => String::new(), + Some(l) => { + let (now, kept) = if gone { + (", which is not mapped here now (this memory may still hold what that page left, or other memory", ")") + } else { + (" (which may be elsewhere now", ")") + }; + match rec.and_then(|r| r.pages.get(l.page)).and_then(|ws| ws.by_seq(l.seq)) { + Some(w) => format!( + "; the last DirectStorage write that landed here went into physical page {:#x}{now}{kept}: {}{}", + l.page, + span(w), + if w.from <= off && off <= w.last { String::new() } else { format!(", not byte {off:#x}") } + ), + None => format!("; the last DirectStorage write that landed here, request #{}, went into physical page {:#x}{now}; that write is no longer kept{kept}", l.seq, l.page), + } + } + }; + let page = |p: usize, place: &str| match rec.and_then(|r| r.pages.get(p)) { + None => format!("no DirectStorage request into physical page {p:#x}, {place}"), + Some(ws) => match ws.over(off) { + Some(w) => format!("{} into physical page {p:#x}, {place} – bytes {:#x}-{:#x} of it", describe_write(w), w.from, w.last), + None => format!("no DirectStorage write kept into physical page {p:#x}, {place}, covers byte {off:#x} – its last: {}", ws.newest().map_or("none".into(), span)), + }, + }; + match here { + None => at_address(), + Some(Ok(Some(PageHere::Mapped(p)))) => page(p, "mapped here"), + Some(Ok(Some(PageHere::Home(p)))) => page(p, "at its home here"), + Some(Ok(Some(PageHere::HomeOf(p, at)))) => format!("{}{}; this is the home of physical page {p:#x}, which is mapped at {at:#x} now", at_address(), landed(false)), + Some(Ok(None)) => format!("{}{}", at_address(), landed(true)), + Some(Err(())) => format!("unknown – the page map was busy; by this address: {}{}", at_address(), landed(false)), + } +} + +/// What the page map said of an address, as the crash line's part after "unknown (the record is +/// busy)" (`last_write_within`): the page found there is the fact that ties the address to the +/// DirectStorage and page lines, kept when the write record cannot be read. +fn page_here_text(here: Option, ()>>) -> String { + use crate::hle::kernelx::PageHere; + match here { + Some(Ok(Some(PageHere::Mapped(p)))) => format!("; physical page {p:#x} is mapped here"), + Some(Ok(Some(PageHere::Home(p)))) => format!("; physical page {p:#x} is at its home here"), + Some(Ok(Some(PageHere::HomeOf(p, at)))) => format!("; this is the home of physical page {p:#x}, mapped at {at:#x} now"), + Some(Ok(None)) => "; no physical page here".into(), + Some(Err(())) => "; the page map was busy too".into(), + None => String::new(), + } +} + +/// The DirectStorage write over the byte at `addr`, as text: the physical page there first, then +/// the address. The kernel's locks are waited for (not in a crash's report). +pub fn last_write_at(addr: usize) -> String { + if page_log() == PageLog::Off { + return "not recorded (XCL_DSTORAGE_PAGE_LOG=0)".into(); + } + let here = (page_log() == PageLog::Page).then(|| Ok(crate::hle::kernelx::page_of_address(addr))); + let g = PAGE_WRITES.lock().unwrap_or_else(|e| e.into_inner()); + describe_writes(g.as_ref(), addr, here) +} + +/// `last_write_at` for a crash's report: the page map and the record are only tried, within the +/// report's wait (`eh::crash_wait`: 100 ms in all, once – a thread stopped while it held one would +/// hold it for good, and the faulting thread may hold `AWAY` itself). The page first, the record +/// after: never one inside the other. +pub fn last_write_at_for_crash(addr: usize) -> String { + last_write_within(addr, crate::eh::crash_wait()) +} + +/// `last_write_at_for_crash` with a wait of its own (the tests: the report's is spent once) +fn last_write_within(addr: usize, left_ms: &AtomicU32) -> String { + if page_log() == PageLog::Off { + return "not recorded (XCL_DSTORAGE_PAGE_LOG=0)".into(); + } + let here = (page_log() == PageLog::Page).then(|| crate::hle::kernelx::page_of_address_within(addr, left_ms)); + match crate::eh::try_lock_within(&PAGE_WRITES, left_ms) { + Some(g) => describe_writes(g.as_ref(), addr, here), + // (0022's head; what the page map said after it) + None => format!("unknown (the record is busy){}", page_here_text(here)), + } +} + +/// (`class_old_pages`) the last DirectStorage write into physical page `page`, as text +fn last_write_of_page(page: usize) -> String { + match page_log() { + PageLog::Off => "not recorded (XCL_DSTORAGE_PAGE_LOG=0)".into(), + PageLog::Address => "not kept by page (XCL_DSTORAGE_PAGE_LOG=address)".into(), + PageLog::Page => { + let g = PAGE_WRITES.lock().unwrap_or_else(|e| e.into_inner()); + g.as_ref() + .and_then(|r| r.pages.get(page)) + .and_then(Writes::newest) + .map_or_else(|| "none".into(), |w| format!("{} – bytes {:#x}-{:#x} of it", describe_write(w), w.from, w.last)) + } + } +} + +/// Local diagnostic: every live queue – entries enqueued and not submitted, entries submitted +/// and not run, requests run – for telling a title waiting on a queue that never ran its work. +static QUEUES: Mutex>> = Mutex::new(Vec::new()); + +/// The queues and what DirectStorage met so far, one line (the `[waits]` snapshot, the watchdog's +/// probe file, `[diag]`). The session tools parse it up to `full queues sent N; `: new groups go +/// after that, before the queues' parts (`q{id}(kind, cap N): pending …, in flight …, run …`). +pub fn probe_line() -> String { + let now = now_ms(); + // (the queues first, then their parts with the list's lock let go: a queue whose last + // reference goes here is dropped with no lock held) + let queues: Vec> = { + let mut g = QUEUES.lock().unwrap_or_else(|e| e.into_inner()); + g.retain(|w| w.strong_count() > 0); + g.iter().filter_map(|w| w.upgrade()).collect() + }; + let parts: Vec = queues + .iter() + .map(|q| { + let (pending, most, holding) = match q.pending.try_lock() { + Ok(p) => ( + p.entries.len().to_string(), + p.most.to_string(), + p.hold.map_or(String::new(), |h| format!(", holding {:.1} s ({} entries)", now.saturating_sub(h.since_ms) as f64 / 1000.0, p.entries.len())), + ), + Err(_) => ("?".into(), "?".into(), String::new()), + }; + format!( + "q{}({}, cap {}{}): pending {pending}, in flight {}, run {}, most pending {most}{holding}", + q.id, + if q.source_memory { "memory" } else { "file" }, + q.capacity, + if q.closed.load(Ordering::Relaxed) { ", closed" } else { "" }, + q.sent.load(Ordering::Relaxed).saturating_sub(q.processed.load(Ordering::Relaxed)), + q.requests_run.load(Ordering::Relaxed) + ) + }) + .collect(); + drop(queues); + let (n, bytes, failed) = counters(); + let l = late_page_counts(); + let c = |k: usize| COUNTS.get(k); + let ms = |a: &AtomicU64| a.load(Ordering::Relaxed) / 1000; + let old = if old_pages() { + format!( + "{} mapped at a CPU address, {} at home, {} unused, {} not a page, {} in a GPU view, {} not looked up; looked up for {} requests in {} ms (the longest {} ms)", + c(OLD_MAPPED), + c(OLD_HOME), + c(OLD_UNUSED), + c(OLD_NOT_A_PAGE), + c(OLD_IN_VIEW), + c(OLD_NOT_LOOKED), + OLD_LOOKS.load(Ordering::Relaxed), + ms(&OLD_US), + ms(&OLD_US_MAX) + ) + } else { + "not looked up (XCL_DSTORAGE_OLD_PAGES=0)".into() + }; + let ends = |k: usize| HOLD_ENDS[k].load(Ordering::Relaxed); + let long = match hold_warn_ms() { + 0 => "long holds not watched (XCL_DSTORAGE_HOLD_WARN_MS=0)".to_string(), + w => format!("{} past {:.1} s", HOLDS_LONG.load(Ordering::Relaxed), w as f64 / 1000.0), + }; + let sizes: [u64; SUBMIT_BUCKETS] = std::array::from_fn(|k| SUBMIT_SIZES[k].load(Ordering::Relaxed)); + let record = match page_log() { + PageLog::Off => "off (XCL_DSTORAGE_PAGE_LOG=0)".to_string(), + PageLog::Address => format!("{} addresses ({} keys forgotten; XCL_DSTORAGE_PAGE_LOG=address)", RECORD_ADDRESSES.load(Ordering::Relaxed), RECORD_FORGOTTEN.load(Ordering::Relaxed)), + PageLog::Page => format!( + "{} physical pages, {} addresses, {} landing addresses ({} keys forgotten); page lookups for writes {} in {} ms (the longest {} ms)", + RECORD_PAGES.load(Ordering::Relaxed), + RECORD_ADDRESSES.load(Ordering::Relaxed), + RECORD_LANDED.load(Ordering::Relaxed), + RECORD_FORGOTTEN.load(Ordering::Relaxed), + WRITE_LOOKS.load(Ordering::Relaxed), + ms(&WRITE_US), + ms(&WRITE_US_MAX) + ), + }; + format!( + "DirectStorage: {n} requests, {} MB, {failed} failed; title page tables at their turn: {} entries filled, {} moved, {} cleared since EnqueueRequest, 0 entries filled while waiting {} / left 0 {}; batches held for Submit {}, full queues sent {}; \ + {} entries unchanged, {} tables not read at their turn (the EnqueueRequest copy used), {} arrays on the enqueuing thread's stack; \ + old pages of moved and cleared entries: {old}; \ + holds ended: Submit {}, Cancel {}, full queue {}, close {}, release {}, the longest {} ms, {long}; \ + cancels {} ({} pending entries taken out, {} requests skipped); entries per Submit: {}; write record: {record}; {}", + bytes >> 20, + l[0], + l[1], + l[2], + l[3], + l[4], + HELD.load(Ordering::Relaxed), + FULL_SENT.load(Ordering::Relaxed), + c(UNCHANGED), + c(UNREAD), + c(ON_STACK), + ends(0), + ends(1), + ends(2), + ends(3), + ends(4), + HOLD_MS_MAX.load(Ordering::Relaxed), + c(CANCELS), + c(CANCELLED), + c(SKIPPED), + submit_histogram(&sizes), + parts.join("; ") + ) +} + /// Run a request; the destination gets the bytes or nothing. -unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[usize]>, src_pages: Option<&[usize]>) -> Result<(), HRESULT> { +unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&Pages>, src_pages: Option<&Pages>, counts: &Counts) -> Result<(), HRESULT> { let n = r.destination_size as usize; - { + // (the request's number: its "request #k" line's, and the write record's) + let k = { // the first requests: where a title's data goes and how it is packed static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); let k = N.fetch_add(1, Ordering::Relaxed); @@ -1038,15 +1872,16 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us r.intermediate_size ); } - } + k + } as u64; if !r.dest_physical_pages() && !writable(r.destination as usize, n) { return Err(E_ACCESS_VIOLATION); } let src: Vec = if r.memory_source() { let mut b = vec![0u8; r.source_size as usize]; if r.source_physical_pages() { - let pages = src_pages.ok_or(E_ACCESS_VIOLATION)?; - if !crate::hle::kernelx::read_physical_pages(pages, r.source_page_offset as usize, &mut b) { + let pages = pages_now(src_pages.ok_or(E_ACCESS_VIOLATION)?, r, "source", counts); + if !crate::hle::kernelx::read_physical_pages(&pages, r.source_page_offset as usize, &mut b) { return Err(E_ACCESS_VIOLATION); } } else { @@ -1092,34 +1927,43 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us let payload = if bc != 0 { bcpack_unpack(r, &stage1, n)? } else { stage1 }; if r.dest_physical_pages() { - let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; - // A page number of 0 in the snapshot taken at enqueue (no page has it): the entry is - // read again now. A retail title keeps its page arrays in its own tables and fills an - // entry after EnqueueRequest – its streaming requests were refused by the thousand - // with page 0. An array that had its pages at enqueue stays as it was snapshotted - // (titles also pass arrays on the stack). + let dest = dest_pages.ok_or(E_ACCESS_VIOLATION)?; let late: Vec; - let pages = if pages.contains(&0) && crate::gpu::shader::readable(r.destination as usize, std::mem::size_of_val(pages)) { - late = (0..pages.len()).map(|k| if pages[k] != 0 { pages[k] } else { (r.destination as *const usize).add(k).read_unaligned() }).collect(); - &late[..] + let pages: &[usize] = if late_pages() { + // the title's table as it is now (`late_pages`) + late = pages_now(dest, r, "destination", counts); + &late + } else if dest.snapshot.contains(&0) && crate::gpu::shader::readable(r.destination as usize, std::mem::size_of_val(&dest.snapshot[..])) { + // (as before: an entry that was 0 at enqueue read again now) + let snap = &dest.snapshot; + late = (0..snap.len()).map(|k| if snap[k] != 0 { snap[k] } else { (r.destination as *const usize).add(k).read_unaligned() }).collect(); + &late } else { - pages + &dest.snapshot }; - if !crate::hle::kernelx::write_physical_pages(pages, r.destination_page_offset as usize, &payload[..n]) { - // (the pages as they were when the request was made: the title's array may hold others by now) + let landed = crate::hle::kernelx::write_physical_pages_at(pages, r.destination_page_offset as usize, &payload[..n]); + let Some(landed) = landed else { + // (the pages the request was given: the title's table at its turn, or the snapshot) static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 8 { + if N.fetch_add(1, Ordering::Relaxed) < 64 { crate::xlog_warn!( - "DirectStorage: {n} bytes (page offset {}) could not be written to its {} page(s) – the first: {}", + "DirectStorage: {n} bytes (page offset {}, file offset {:#x}) could not be written to its {} page(s) – the first not written: {}", r.destination_page_offset, + r.offset, pages.len(), - pages.first().map_or("none".to_string(), |&p| crate::hle::kernelx::describe_physical_page(p)) + pages + .iter() + .find(|&&p| crate::hle::kernelx::page_address(p).is_none()) + .or(pages.first()) + .map_or("none".to_string(), |&p| crate::hle::kernelx::describe_physical_page(p)) ); } return Err(E_ACCESS_VIOLATION); - } + }; + note_written(Written::Pages { pages, landed: &landed, offset: r.destination_page_offset as usize, n }, r, k); } else if n > 0 { std::ptr::copy_nonoverlapping(payload.as_ptr(), r.destination as *mut u8, n); + note_written(Written::At { at: r.destination as usize, n }, r, k); } Ok(()) } @@ -1155,11 +1999,12 @@ enum Entry { seq: u64, req: Request, file: Option>, - dest_pages: Option>, - src_pages: Option>, + dest_pages: Option, + src_pages: Option, }, - /// refused at enqueue: reported in queue order by the worker + /// refused at enqueue: reported in queue order by the worker (unless cancelled, as a request) Refused { + seq: u64, hr: HRESULT, req: Request, file: Option>, @@ -1174,9 +2019,109 @@ enum Entry { Gate(Arc), } +/// What ended a hold: the title's Submit, a Cancel that left no request waiting for the Submit, +/// the full queue's send, the queue's Close, its last Release without a Close. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum HoldCause { + Submit = 0, + Cancel = 1, + FullQueue = 2, + Close = 3, + Release = 4, +} + +impl HoldCause { + fn text(self) -> &'static str { + match self { + Self::Submit => "the title's Submit", + Self::Cancel => "a Cancel", + Self::FullQueue => "the full queue's send", + Self::Close => "the queue's Close", + Self::Release => "the queue's last Release", + } + } +} + +/// A hold now: when it began (`now_ms`), the entries it kept back then (those after the first +/// request that waits for the Submit), whether its long-hold warning and its near-full line were given. +#[derive(Clone, Copy, Debug)] +struct Hold { + since_ms: u64, + held: usize, + warned: bool, + near_full: bool, +} + +/// How a hold ended: by what, after how long, the entries it kept back when it began, the entries +/// that went to the worker with its end (Close, Release: dropped). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct HoldEnd { + cause: HoldCause, + ms: u64, + held: usize, + sent: usize, +} + +/// holds that ended, by `HoldCause`; the longest (ms); holds past `hold_warn_ms` (warned of); +/// end lines given for holds shorter than that / as long +static HOLD_ENDS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +static HOLD_MS_MAX: AtomicU64 = AtomicU64::new(0); +static HOLDS_LONG: AtomicU64 = AtomicU64::new(0); +static SHORT_ENDS: AtomicU64 = AtomicU64::new(0); +static LONG_ENDS: AtomicU64 = AtomicU64::new(0); + +/// `XCL_DSTORAGE_HOLD_WARN_MS` (default 2000; 0: not watched): a hold that lasts this long without +/// the title's Submit is warned of, once. +fn hold_warn_ms() -> u64 { + static MS: OnceLock = OnceLock::new(); + *MS.get_or_init(|| std::env::var("XCL_DSTORAGE_HOLD_WARN_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2000)) +} + +/// Whether a hold since `since` (ms) is past its warning at `now` (`warn` ms; 0: never) and was not +/// warned of yet – the auto-submit's look and the long-hold watch's. +fn past_warning(since: u64, now: u64, warn: u64, warned: bool) -> bool { + warn != 0 && !warned && now.saturating_sub(since) >= warn +} + struct Pending { entries: Vec, next_seq: u64, + /// (diagnostic) the hold now: Some exactly while `QueueInner::holding` is set – but after a + /// Close, where the flag stays set (Query answers as before) and this is None + hold: Option, + /// (diagnostic) how the last hold ended (`told_hold_end`) + last_end: Option, + /// (diagnostic) the most entries ever pending + most: usize, +} + +impl Pending { + fn new() -> Pending { + Pending { entries: Vec::new(), next_seq: 1, hold: None, last_end: None, most: 0 } + } + + /// (diagnostic) a hold begins, keeping back `held` entries + fn begin_hold(&mut self, held: usize) { + self.hold = Some(Hold { since_ms: now_ms(), held, warned: false, near_full: false }); + } + + /// (diagnostic) the hold, if one is on, ends by `cause` – `sent` is the caller's, from `send` + fn end_hold(&mut self, cause: HoldCause) -> Option { + let h = self.hold.take()?; + Some(HoldEnd { cause, ms: now_ms().saturating_sub(h.since_ms), held: h.held, sent: 0 }) + } + + /// (diagnostic) an entry was added: the most pending; the entries now when a held batch first + /// comes to 3/4 of the queue (a queue of 16 slots or more), once a hold + fn note_len(&mut self, capacity: usize) -> Option { + let n = self.entries.len(); + self.most = self.most.max(n); + let h = self.hold.as_mut()?; + (!h.near_full && capacity >= 16 && n >= capacity * 3 / 4).then(|| { + h.near_full = true; + n + }) + } } struct CancelRule { @@ -1196,9 +2141,10 @@ struct QueueInner { desc: [u8; 0x18], source_memory: bool, capacity: usize, + /// made with AutoSubmitDisabled (CreateQueue1), the option honoured + /// (`honour_auto_submit_disabled`): it submits by itself only when full (`submits_itself`) auto_submit_disabled: bool, pending: Mutex, - room: Condvar, cancels: Mutex>, worker: Mutex>>>, worker_active: (Mutex, Condvar), @@ -1209,8 +2155,26 @@ struct QueueInner { bcpack_fill: AtomicBool, /// `XCL_DSTORAGE_BCPACK_ACCEPT` when the queue was made bcpack_accept: AtomicBool, + /// (diagnostic `probe_line`) entries sent to the worker, entries it took, requests it ran + sent: AtomicU64, + processed: AtomicU64, + requests_run: AtomicU64, + /// (`submit_auto`) requests into the title's pages are held for its Submit now + holding: AtomicBool, + /// (`NEXT_QUEUE`) its number + id: usize, + /// (diagnostic) its worker's thread id once it runs (0: none yet) + worker_tid: AtomicU32, + /// (diagnostic) what its requests met beyond `LATE`, its cancels (`Counts`) + counts: Counts, + /// (diagnostic) the title's Submits by the entries they sent (`submit_bucket`) + submits: [AtomicU64; SUBMIT_BUCKETS], } +/// A queue's number in the order the title made them: `q{id}` in the log and the probe line, +/// its worker's thread name (`xcl-dstorage-q{id}`). +static NEXT_QUEUE: AtomicUsize = AtomicUsize::new(0); + impl QueueInner { fn fail(&self, hr: HRESULT, request: Request, file: Option<&FileInner>) { FAILED.fetch_add(1, Ordering::Relaxed); @@ -1242,10 +2206,39 @@ impl QueueInner { } } + // every failure (a title does not look at a request's result: a failed one is a model or + // a texture left as it was); past 4096, every 1024th + static LOGGED: AtomicU64 = AtomicU64::new(0); + let k = LOGGED.fetch_add(1, Ordering::Relaxed); + if k < 4096 || k % 1024 == 0 { + let source = if request.memory_source() { + format!( + "{} bytes from memory at {:#x}{}", + request.source_size, + request.source, + if request.source_physical_pages() { format!(" (a page array, page offset {})", request.source_page_offset) } else { String::new() } + ) + } else { + format!( + "{} bytes at file offset {:#x} of {}", + request.source_size, + request.offset, + // (a request refused at EnqueueRequest has no file of XCL's) + file.map(|f| String::from_utf16_lossy(&f.path)).unwrap_or_else(|| format!("file object {:#x} (refused at EnqueueRequest)", request.source)) + ) + }; + crate::xlog_warn!( + "DirectStorage: request failed ({hr:#x}, failure {}): options {:#x}, {} bytes into {:#x}{}, {source}", + k + 1, + request.options, + request.destination_size, + request.destination, + if request.dest_physical_pages() { format!(" (a page array, page offset {})", request.destination_page_offset) } else { String::new() }, + ); + } let mut e = self.errors.lock().unwrap(); e.0 += 1; if e.1.is_none() { - crate::xlog_warn!("DirectStorage: a request failed ({hr:#x}): {} bytes from {}", request.destination_size, file.map(|f| String::from_utf16_lossy(&f.path)).unwrap_or_default()); e.1 = Some(FirstError { hr, request, file: file.map(|f| f.path.clone()).unwrap_or_default() }); } unsafe { SetEvent(self.error_event as HANDLE) }; @@ -1259,42 +2252,177 @@ impl QueueInner { rules.iter().any(|r| tag & r.mask == r.value) } - fn submit(self: &Arc) { + /// The title's Submit (and, without `late_pages`, the auto-submit): all pending entries go, a hold + /// ends. The entries that went. + fn submit(self: &Arc) -> usize { + let mut ended = None; + let n = self.send(|p| { + ended = self.end(p, HoldCause::Submit); + std::mem::take(&mut p.entries) + }); + if let Some(mut e) = ended { + e.sent = n; + self.told_hold_end(e); + } + n + } + + /// A half-full queue submits by itself (as on the PC), but a request whose pages come from + /// the title's own table (`Pages::table`), and everything after it, waits for the title's + /// Submit: the title fills that table for the batch right before it (`late_pages`). In + /// order, so a status or signal behind such a request waits with it. A full queue (one slot + /// left, as the console counts them) sends all – the title cannot Submit while it waits for + /// room. + fn submit_auto(self: &Arc) { + if !late_pages() { + self.submit(); + return; + } + let capacity = self.capacity.max(2); + let warn = hold_warn_ms(); + let (mut full, mut began, mut ended, mut long) = (None, None, None, None); + let n = self.send(|p| { + let len = p.entries.len(); + if len + 1 >= capacity { + if p.entries.iter().any(waits_for_submit) { + full = Some((FULL_SENT.fetch_add(1, Ordering::Relaxed), len)); + } + ended = self.end(p, HoldCause::FullQueue); + return std::mem::take(&mut p.entries); + } + if len < (capacity / 2).max(1) { + // (half full when the title enqueued, no longer: a Submit took the entries meanwhile) + return Vec::new(); + } + let k = p.entries.iter().position(waits_for_submit).unwrap_or(len); + if k == len { + // (no request waits for the Submit any more: only a Cancel takes them out) + ended = self.end(p, HoldCause::Cancel); + } else if !self.holding.swap(true, Ordering::Relaxed) { + // (a batch held: counted once, however many entries the title adds after) + let batches = HELD.fetch_add(1, Ordering::Relaxed) + 1; + p.begin_hold(len - k); + began = Some((k, len, batches)); + } else if let Some(h) = p.hold.as_mut() { + let now = now_ms(); + if past_warning(h.since_ms, now, warn, h.warned) { + h.warned = true; + long = Some(LongHold { queue: self.id, ms: now.saturating_sub(h.since_ms), entries: len, first: first_held(&p.entries) }); + } + } + p.entries.drain(..k).collect() + }); + // (the lines with the queue's locks let go) + if let Some((before, len)) = full { + if before < 4 { + crate::xlog_warn!("DirectStorage: a full queue (q{}, {len} entries) runs requests into the title's pages before its Submit – with its page table as it is", self.id); + } + } + if let Some((k, len, batches)) = began { + if batches <= 32 || batches.is_power_of_two() { + crate::xlog_info!("DirectStorage: a half-full queue, q{}, submits {k} of its {len} entries; the requests into the title's pages wait for its Submit ({batches} batches so far)", self.id); + } + start_hold_watch(); + } + if let Some(mut e) = ended { + e.sent = n; + self.told_hold_end(e); + } + if let Some(h) = long { + told_long_hold(h); + } + } + + /// The entries `take` picks from the pending ones (with what goes with them: the hold), to the + /// worker; how many went (0: none, or the worker could not take them). + fn send(self: &Arc, take: impl FnOnce(&mut Pending) -> Vec) -> usize { // Lock `worker` before `pending` so concurrent `Submit()` calls always enqueue // batches to the channel in strict `seq` order. let mut w = self.worker.lock().unwrap(); if self.closed.load(Ordering::Acquire) { - return; + return 0; } - let batch = std::mem::take(&mut self.pending.lock().unwrap().entries); + let batch = take(&mut self.pending.lock().unwrap()); if batch.is_empty() { - return; - } - if self.auto_submit_disabled { - self.room.notify_all(); + return 0; } if w.is_none() { let (tx, rx) = mpsc::channel::>(); let q = Arc::clone(self); *self.worker_active.0.lock().unwrap() = true; - let started = std::thread::Builder::new().name("xcl-dstorage".into()).spawn(move || q.run(rx)); + // (named after its queue: the thread dump says which queue a worker serves) + let started = std::thread::Builder::new().name(format!("xcl-dstorage-q{}", self.id)).spawn(move || q.run(rx)); if started.is_err() { *self.worker_active.0.lock().unwrap() = false; self.worker_active.1.notify_all(); // Release `worker` before dropping `batch` so fence `Release` cannot re-enter under lock. drop(w); drop(batch); - return; + return 0; } *w = Some(tx); } + let entries = batch.len(); let sent = w.as_ref().unwrap().send(batch); + let ok = sent.is_ok(); + if ok { + self.sent.fetch_add(entries as u64, Ordering::Relaxed); + } // Release `worker` before dropping any unsent `batch` returned in `Err`. drop(w); drop(sent); + if ok { + entries + } else { + 0 + } } - fn run(&self, rx: mpsc::Receiver>) { + /// (under `pending`) the hold, if one is on, ends by `cause`: `holding` cleared + fn end(&self, p: &mut Pending, cause: HoldCause) -> Option { + if self.holding.swap(false, Ordering::Relaxed) { + p.end_hold(cause) + } else { + None + } + } + + /// A hold's end: kept (`last_end`), counted and logged – the first 32 ends of holds shorter + /// than `hold_warn_ms`, then powers of two; the first 16 as long, then powers of two. + fn told_hold_end(&self, e: HoldEnd) { + if let Ok(mut p) = self.pending.lock() { + p.last_end = Some(e); + } + HOLD_ENDS[e.cause as usize].fetch_add(1, Ordering::Relaxed); + let longest = HOLD_MS_MAX.fetch_max(e.ms, Ordering::Relaxed).max(e.ms); + let warn = hold_warn_ms(); + let shown = if warn != 0 && e.ms >= warn { + let n = LONG_ENDS.fetch_add(1, Ordering::Relaxed) + 1; + n <= 16 || n.is_power_of_two() + } else { + let n = SHORT_ENDS.fetch_add(1, Ordering::Relaxed) + 1; + n <= 32 || n.is_power_of_two() + }; + if shown { + let c = |k: usize| HOLD_ENDS[k].load(Ordering::Relaxed); + crate::xlog_info!( + "DirectStorage: q{}: the hold ended by {} after {} ms – {} entries {} ({} held when it began); holds ended so far: Submit {}, Cancel {}, full queue {}, close {}, release {} – the longest {longest} ms", + self.id, + e.cause.text(), + e.ms, + e.sent, + if matches!(e.cause, HoldCause::Close | HoldCause::Release) { "dropped" } else { "sent" }, + e.held, + c(0), + c(1), + c(2), + c(3), + c(4) + ); + } + } + + fn run(&self, rx: mpsc::Receiver>) { struct ActiveGuard<'a>(&'a QueueInner); impl Drop for ActiveGuard<'_> { fn drop(&mut self) { @@ -1303,10 +2431,18 @@ impl QueueInner { } } let _active = ActiveGuard(self); + let tid = unsafe { GetCurrentThreadId() }; + self.worker_tid.store(tid, Ordering::Relaxed); + if self.id < 64 || self.id.is_power_of_two() { + crate::xlog_info!("DirectStorage: q{}: worker thread {tid} started (xcl-dstorage-q{})", self.id, self.id); + } + // (`XCL_WATCH_WAITS`: the `[waits]` snapshot's line for this thread says which queue it serves) + let _xcl_api = crate::waitwatch::on().then(|| crate::waitwatch::api(Box::leak(format!("DirectStorage worker q{}", self.id).into_boxed_str()))); // the first failure of the requests since the last status entry let mut since_status = S_OK; for batch in rx { for e in batch { + self.processed.fetch_add(1, Ordering::Relaxed); if self.closed.load(Ordering::Acquire) { if let Entry::Status(s, i) = e { if let Some(slot) = s.slots.get(i as usize) { @@ -1319,19 +2455,26 @@ impl QueueInner { Entry::Request { seq, req, file, dest_pages, src_pages } => { if self.is_cancelled(seq, req.tag) { // Cancelled requests are skipped without affecting status or error record. + self.counts.add(SKIPPED, 1); continue; } - if let Err(hr) = unsafe { execute(&req, file.as_deref(), dest_pages.as_deref(), src_pages.as_deref()) } { + self.requests_run.fetch_add(1, Ordering::Relaxed); + if let Err(hr) = unsafe { execute(&req, file.as_deref(), dest_pages.as_ref(), src_pages.as_ref(), &self.counts) } { self.fail(hr, req, file.as_deref()); if since_status >= 0 { since_status = hr; } } } - Entry::Refused { hr, req, file, fill } => { + Entry::Refused { seq, hr, req, file, fill } => { + // a cancelled request is no failure, refused or not + if self.is_cancelled(seq, req.tag) { + self.counts.add(SKIPPED, 1); + continue; + } let mut ok = false; if let Some(t) = &fill { - let filled = unsafe { bcpack_fill(&req, t) }; + let filled = unsafe { bcpack_fill(&req, t, &self.counts) }; if filled && self.bcpack_accept.load(Ordering::Relaxed) && bcpack_placeholder_eligible(&req) { ok = true; REQUESTS.fetch_add(1, Ordering::Relaxed); @@ -1371,17 +2514,17 @@ impl QueueInner { } } - /// A manual queue holds a producer at capacity until entries leave or the queue closes. - fn pending_for_enqueue(&self) -> std::sync::MutexGuard<'_, Pending> { - let pending = self.pending.lock().unwrap(); - self.room.wait_while(pending, |p| { - self.auto_submit_disabled && p.entries.len() >= self.capacity && !self.closed.load(Ordering::Acquire) - }).unwrap() + /// Whether `n` entries pending send themselves (`submit_auto`): half full, as on the PC; a + /// queue made with AutoSubmitDisabled (upstream 5bff7bd) waits for the title's Submit – but a + /// full one (one slot left) sends all the same: its title cannot Submit while it waits for + /// room, and an enqueue that waited for room could wait for ever. + fn submits_itself(&self, n: usize) -> bool { + n >= (self.capacity / 2).max(1) && (!self.auto_submit_disabled || n + 1 >= self.capacity.max(2)) } fn enqueue(self: &Arc, e: Entry) { - let n = { - let mut p = self.pending_for_enqueue(); + let (n, near) = { + let mut p = self.pending.lock().unwrap(); if self.closed.load(Ordering::Acquire) { return; } @@ -1391,33 +2534,204 @@ impl QueueInner { } } p.entries.push(e); - p.entries.len() + (p.entries.len(), p.note_len(self.capacity)) }; - // as on PC: a half-full queue submits by itself, unless AutoSubmitDisabled was set in CreateQueue1 - if !self.auto_submit_disabled && n >= (self.capacity / 2).max(1) { - self.submit(); + if let Some(n) = near { + told_near_full(self.id, n, self.capacity); } + // as on PC: a half-full queue submits by itself – not one made with AutoSubmitDisabled + // but when it is full (`submits_itself`) + if self.submits_itself(n) { + self.submit_auto(); + } + } + + fn enqueue_request(self: &Arc, req: Request, file: Option>, dest_pages: Option, src_pages: Option) { + self.enqueue_numbered(|seq| Entry::Request { seq, req, file, dest_pages, src_pages }); } - fn enqueue_request(self: &Arc, req: Request, file: Option>, dest_pages: Option>, src_pages: Option>) { - let n = { - let mut p = self.pending_for_enqueue(); + /// A request refused at enqueue, numbered as a request so `CancelRequestsWithTag` covers it. + fn enqueue_refused(self: &Arc, hr: HRESULT, req: Request, file: Option>, fill: Option) { + self.enqueue_numbered(|seq| Entry::Refused { seq, hr, req, file, fill }); + } + + fn enqueue_numbered(self: &Arc, entry: impl FnOnce(u64) -> Entry) { + let (n, near) = { + let mut p = self.pending.lock().unwrap(); if self.closed.load(Ordering::Acquire) { return; } let seq = p.next_seq; p.next_seq += 1; - p.entries.push(Entry::Request { seq, req, file, dest_pages, src_pages }); - p.entries.len() + p.entries.push(entry(seq)); + (p.entries.len(), p.note_len(self.capacity)) }; - if !self.auto_submit_disabled && n >= (self.capacity / 2).max(1) { - self.submit(); + if let Some(n) = near { + told_near_full(self.id, n, self.capacity); + } + if self.submits_itself(n) { + self.submit_auto(); + } + } +} + +/// A held batch at 3/4 of its queue (the first 16, then powers of two) +fn told_near_full(id: usize, n: usize, capacity: usize) { + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed) + 1; + if k <= 16 || k.is_power_of_two() { + crate::xlog_info!("DirectStorage: q{id}: {n} of its {capacity} entries held for the title's Submit – at {} the full queue sends them with their page tables as they are", capacity - 1); + } +} + +/// A hold past `hold_warn_ms`: its queue, how long, the entries pending, its first request that +/// waits for the Submit (and that request's file). +struct LongHold { + queue: usize, + ms: u64, + entries: usize, + first: Option<(Request, Option>)>, +} + +fn first_held(entries: &[Entry]) -> Option<(Request, Option>)> { + entries.iter().find(|e| waits_for_submit(e)).and_then(|e| match e { + Entry::Request { req, file, .. } | Entry::Refused { req, file, .. } => Some((*req, file.clone())), + _ => None, + }) +} + +/// A request's source as text: a file and the offset in it, or memory. +fn describe_source(r: &Request, file: Option<&FileInner>) -> String { + if r.memory_source() { + format!("{} bytes from memory at {:#x}", r.source_size, r.source) + } else { + format!( + "{} bytes at file offset {:#x} of {}", + r.source_size, + r.offset, + file.map_or_else(|| "a file refused at EnqueueRequest".to_string(), |f| String::from_utf16_lossy(&f.path)) + ) + } +} + +/// The holds past `hold_warn_ms` not warned of yet (marked now), of every queue or of queue +/// `only` (a test's). Each queue's pending entries are only tried: a busy one is looked at next time. +fn holds_past(now: u64, only: Option) -> Vec { + let warn = hold_warn_ms(); + if warn == 0 { + return Vec::new(); + } + // (the queues first, the list's lock let go) + let queues: Vec> = QUEUES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter_map(|w| w.upgrade()) + .filter(|q| only.is_none_or(|id| q.id == id)) + .collect(); + let mut out = Vec::new(); + for q in &queues { + if !q.holding.load(Ordering::Relaxed) { + continue; + } + let Ok(mut g) = q.pending.try_lock() else { continue }; + // (through a plain `&mut Pending`: its fields borrowed apart) + let p = &mut *g; + let len = p.entries.len(); + let Some(h) = p.hold.as_mut() else { continue }; + if !past_warning(h.since_ms, now, warn, h.warned) { + continue; + } + h.warned = true; + out.push(LongHold { queue: q.id, ms: now.saturating_sub(h.since_ms), entries: len, first: first_held(&p.entries) }); + } + out +} + +/// Warn of the holds past `hold_warn_ms` (the long-hold watch). +#[cfg_attr(test, allow(dead_code))] +fn check_holds() { + for h in holds_past(now_ms(), None) { + told_long_hold(h); + } +} + +fn told_long_hold(h: LongHold) { + let n = HOLDS_LONG.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + crate::xlog_warn!( + "DirectStorage: q{}: a hold over {:.1} s – {} entries held for the title's Submit for {:.1} s; its first request into the title's pages waits ({})", + h.queue, + hold_warn_ms() as f64 / 1000.0, + h.entries, + h.ms as f64 / 1000.0, + h.first.as_ref().map_or_else(|| "none left".to_string(), |(r, f)| describe_source(r, f.as_deref())) + ); + } +} + +/// The long-hold watch (`XCL_DSTORAGE_HOLD_WARN_MS`), started with the first hold: it looks every +/// 500 ms. A title stuck between its EnqueueRequests and its Submit enqueues nothing, so the +/// auto-submit, which looks too, is not called. Not in tests: they look themselves (`holds_past`). +fn start_hold_watch() { + #[cfg(not(test))] + { + static ONCE: std::sync::Once = std::sync::Once::new(); + if hold_warn_ms() == 0 { + return; } + ONCE.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-dstorage-holds".into()).spawn(|| loop { + std::thread::sleep(std::time::Duration::from_millis(500)); + check_holds(); + }); + }); + } +} + +const SUBMIT_BUCKETS: usize = 14; +/// the title's Submits by the entries they sent, for all queues: 0, 1, 2-3, 4-7, … 2048-4095, 4096 and more +static SUBMIT_SIZES: [AtomicU64; SUBMIT_BUCKETS] = [const { AtomicU64::new(0) }; SUBMIT_BUCKETS]; +const SUBMIT_LABELS: [&str; SUBMIT_BUCKETS] = ["0", "1", "2-3", "4-7", "8-15", "16-31", "32-63", "64-127", "128-255", "256-511", "512-1023", "1024-2047", "2048-4095", "4096+"]; + +fn submit_bucket(n: usize) -> usize { + ((usize::BITS - n.leading_zeros()) as usize).min(SUBMIT_BUCKETS - 1) +} + +/// The histogram as text: its buckets with Submits ("none": no Submit yet) +fn submit_histogram(counts: &[u64; SUBMIT_BUCKETS]) -> String { + let parts: Vec = counts.iter().zip(SUBMIT_LABELS).filter(|(&c, _)| c != 0).map(|(c, l)| format!("{l}: {c}")).collect(); + if parts.is_empty() { + "none".into() + } else { + parts.join(", ") + } +} + +/// Whether `e` waits for the title's Submit when a half-full queue submits by itself +/// (`QueueInner::submit_auto`): a request whose pages come from the title's own table. +fn waits_for_submit(e: &Entry) -> bool { + match e { + Entry::Request { dest_pages, src_pages, .. } => [dest_pages, src_pages].into_iter().flatten().any(|p| p.table.is_some()), + Entry::Refused { fill: Some(FillTarget::Pages(_, table)), .. } => table.is_some(), + _ => false, } } +/// half-full queues that left requests for the title's Submit; full queues that sent them +static HELD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static FULL_SENT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + impl Drop for QueueInner { fn drop(&mut self) { + // (released while it holds, without a Close: its pending entries go with it, never run – + // as in 0022) + let p = self.pending.get_mut().unwrap_or_else(|e| e.into_inner()); + let n = p.entries.len(); + if let Some(mut e) = p.end_hold(HoldCause::Release) { + e.sent = n; + self.told_hold_end(e); + } unsafe { CloseHandle(self.error_event as HANDLE) }; } } @@ -1486,9 +2800,8 @@ unsafe fn factory_create_queue_with_options(_p: *mut c_void, desc: *const u8, op desc: raw, source_memory: source == 1, capacity, - auto_submit_disabled: options & QUEUE_OPT_AUTO_SUBMIT_DISABLED != 0, - pending: Mutex::new(Pending { entries: Vec::new(), next_seq: 1 }), - room: Condvar::new(), + auto_submit_disabled: options & QUEUE_OPT_AUTO_SUBMIT_DISABLED != 0 && honour_auto_submit_disabled(), + pending: Mutex::new(Pending::new()), cancels: Mutex::new(Vec::new()), worker: Mutex::new(None), worker_active: (Mutex::new(false), Condvar::new()), @@ -1497,13 +2810,52 @@ unsafe fn factory_create_queue_with_options(_p: *mut c_void, desc: *const u8, op errors: Mutex::new((0, None)), bcpack_fill: AtomicBool::new(bcpack_fill_from_env()), bcpack_accept: AtomicBool::new(bcpack_accept), + sent: AtomicU64::new(0), + processed: AtomicU64::new(0), + requests_run: AtomicU64::new(0), + holding: AtomicBool::new(false), + id: NEXT_QUEUE.fetch_add(1, Ordering::Relaxed), + worker_tid: AtomicU32::new(0), + counts: Counts::new(), + submits: [const { AtomicU64::new(0) }; SUBMIT_BUCKETS], }); + QUEUES.lock().unwrap().push(Arc::downgrade(&inner)); + if inner.id < 64 || inner.id.is_power_of_two() { + let name = queue_name(u64::from_le_bytes(raw[0x10..0x18].try_into().unwrap())); + crate::xlog_info!( + "DirectStorage: q{}: CreateQueue ({} source, capacity {capacity}, priority {priority}{})", + inner.id, + if source == 1 { "memory" } else { "file" }, + if name.is_empty() { String::new() } else { format!(", name \"{name}\"") } + ); + } let o = new_object(queue_vtbl(), inner); let hr = queue_qi(o, riid, out); queue_release(o); hr } +/// The name in a queue's desc (a C string, @0x10), when it is one: up to 64 printable characters, +/// read with `read_own` 8 bytes at a time (empty if there is none or it cannot be read). +unsafe fn queue_name(at: u64) -> String { + let mut out = Vec::new(); + let mut word = [0u8; 8]; + while at != 0 && out.len() < 64 && read_own(at as usize + out.len(), word.as_mut_ptr(), 8) { + match word.iter().position(|&b| b == 0) { + Some(end) => { + out.extend_from_slice(&word[..end]); + break; + } + None => out.extend_from_slice(&word), + } + } + if out.iter().all(|b| (0x20..0x7F).contains(b)) { + String::from_utf8_lossy(&out).into_owned() + } else { + String::new() + } +} + unsafe fn queue<'a>(p: *mut c_void) -> &'a Arc { inner::(p) } @@ -1549,11 +2901,15 @@ unsafe extern "system" fn queue_enqueue_request(p: *mut c_void, req: *const u8) fill = if !r.dest_physical_pages() { Some(FillTarget::Virtual) } else { - snapshot_page_list(r.destination, r.destination_page_offset, r.destination_size).ok().map(FillTarget::Pages) + let table = (late_pages() && !on_own_stack(r.destination)).then_some(r.destination); + if late_pages() && table.is_none() { + q.counts.add(ON_STACK, 1); // (its snapshot is all there is) + } + snapshot_page_list(r.destination, r.destination_page_offset, r.destination_size).ok().map(|l| FillTarget::Pages(l, table)) }; } } - return q.enqueue(Entry::Refused { hr, req: r, file: None, fill }); + return q.enqueue_refused(hr, r, None, fill); } let file = if r.memory_source() { None @@ -1562,25 +2918,35 @@ unsafe extern "system" fn queue_enqueue_request(p: *mut c_void, req: *const u8) let f = r.source as *mut c_void; let mut vt = 0usize; if !read_own(f as usize, &mut vt as *mut usize as *mut u8, 8) || vt != file_vtbl().as_ptr() as usize { - return q.enqueue(Entry::Refused { hr: E_FILE_HANDLE, req: r, file: None, fill: None }); + return q.enqueue_refused(E_FILE_HANDLE, r, None, None); } Some(Arc::clone(inner::(f))) }; let dest_pages = if r.dest_physical_pages() { - match snapshot_page_array(r.destination, r.destination_page_offset, r.destination_size) { - Ok(pages) => Some(pages), + match Pages::take(r.destination, r.destination_page_offset, r.destination_size) { + Ok(pages) => { + if late_pages() && pages.table.is_none() { + q.counts.add(ON_STACK, 1); // (its snapshot is all there is) + } + Some(pages) + } Err(hr) => { - return q.enqueue(Entry::Refused { hr, req: r, file, fill: None }); + return q.enqueue_refused(hr, r, file, None); } } } else { None }; let src_pages = if r.memory_source() && r.source_physical_pages() { - match snapshot_page_array(r.source, r.source_page_offset, r.source_size) { - Ok(pages) => Some(pages), + match Pages::take(r.source, r.source_page_offset, r.source_size) { + Ok(pages) => { + if late_pages() && pages.table.is_none() { + q.counts.add(ON_STACK, 1); // (its snapshot is all there is) + } + Some(pages) + } Err(hr) => { - return q.enqueue(Entry::Refused { hr, req: r, file, fill: None }); + return q.enqueue_refused(hr, r, file, None); } } } else { @@ -1619,7 +2985,9 @@ unsafe extern "system" fn queue_enqueue_signal(p: *mut c_void, fence: *mut c_voi unsafe extern "system" fn queue_submit(p: *mut c_void) { let q = queue(p); if !q.closed.load(Ordering::Acquire) { - q.submit(); + let b = submit_bucket(q.submit()); + q.submits[b].fetch_add(1, Ordering::Relaxed); + SUBMIT_SIZES[b].fetch_add(1, Ordering::Relaxed); } } @@ -1627,22 +2995,44 @@ unsafe extern "system" fn queue_submit(p: *mut c_void) { /// executed) whose tag matches (`tag & mask == value`) are skipped without error. unsafe extern "system" fn queue_cancel(p: *mut c_void, mask: u64, value: u64) { let q = queue(p); - let cutoff = { + let (cutoff, was_holding) = { let mut pend = q.pending.lock().unwrap(); - pend.entries.retain(|e| !matches!(e, Entry::Request { req, .. } if req.tag & mask == value)); - if q.auto_submit_disabled && pend.entries.len() < q.capacity { - q.room.notify_all(); - } - pend.next_seq.saturating_sub(1) + let was_holding = q.holding.load(Ordering::Relaxed); + let before = pend.entries.len(); + pend.entries.retain(|e| !matches!(e, Entry::Request { req, .. } | Entry::Refused { req, .. } if req.tag & mask == value)); + q.counts.add(CANCELS, 1); + q.counts.add(CANCELLED, (before - pend.entries.len()) as u64); + (pend.next_seq.saturating_sub(1), was_holding) }; - if cutoff == 0 { - return; + if cutoff != 0 { + let mut rules = q.cancels.lock().unwrap(); + if let Some(existing) = rules.iter_mut().find(|r| r.mask == mask && r.value == value) { + existing.up_to_seq = existing.up_to_seq.max(cutoff); + } else { + rules.push(CancelRule { up_to_seq: cutoff, mask, value }); + } } - let mut rules = q.cancels.lock().unwrap(); - if let Some(existing) = rules.iter_mut().find(|r| r.mask == mask && r.value == value) { - existing.up_to_seq = existing.up_to_seq.max(cutoff); - } else { - rules.push(CancelRule { up_to_seq: cutoff, mask, value }); + if was_holding { + // what a held batch kept back and nothing holds back now – the entries before the first + // request still waiting for the title's Submit, all of them when none is left (the hold + // ends) – goes: a queue that submits itself at half full had sent them (`submit_auto`) + let mut ended = None; + let n = q.send(|p| { + if !q.holding.load(Ordering::Relaxed) { + // (the hold ended meanwhile – a Submit, a full queue's send, another Cancel: what + // is pending now is the title's next batch, for its Submit) + return Vec::new(); + } + let k = p.entries.iter().position(waits_for_submit).unwrap_or(p.entries.len()); + if k == p.entries.len() { + ended = q.end(p, HoldCause::Cancel); + } + p.entries.drain(..k).collect() + }); + if let Some(mut e) = ended { + e.sent = n; + q.told_hold_end(e); + } } } @@ -1650,17 +3040,25 @@ unsafe extern "system" fn queue_close(p: *mut c_void) { let q = queue(p); // Lock `worker` then `pending` (same order as `submit`) so no racing enqueue or submit // can push new pending entries or spawn a new worker after `closed` is set. - let drained = { + let (drained, ended) = { let mut w = q.worker.lock().unwrap(); let mut pend = q.pending.lock().unwrap(); if q.closed.swap(true, Ordering::AcqRel) { - Vec::new() + (Vec::new(), None) } else { w.take(); - std::mem::take(&mut pend.entries) + // (the hold's record ends; `holding` stays set: Query on a closed queue answers as in 0022) + let mut ended = pend.end_hold(HoldCause::Close); + let drained = std::mem::take(&mut pend.entries); + if let Some(e) = ended.as_mut() { + e.sent = drained.len(); // (dropped, not run) + } + (drained, ended) } }; - q.room.notify_all(); + if let Some(e) = ended { + q.told_hold_end(e); + } for e in drained { if let Entry::Status(s, i) = e { if let Some(slot) = s.slots.get(i as usize) { @@ -1690,7 +3088,8 @@ unsafe extern "system" fn queue_get_error_event(p: *mut c_void) -> HANDLE { /// DSTORAGE_ERROR_RECORD (0x290): failure count u32 @0, then the first failure: HRESULT @8, /// command type @0xC (none: 0xFFFFFFFF), the request's options @0x10, destination @0x18 and -/// size @0x20, its file name @0x24 (0x104 UTF-16) or memory source @0x238 +/// size @0x20, its file name @0x24 (0x104 UTF-16) and file offset @0x230 or memory source @0x238, +/// source size @0x240, cancellation tag @0x248 (name @0x250 not kept) unsafe extern "system" fn queue_retrieve_error_record(p: *mut c_void, out: *mut u8) { if out.is_null() { return; @@ -1713,7 +3112,10 @@ unsafe extern "system" fn queue_retrieve_error_record(p: *mut c_void, out: *mut for (i, c) in f.file.iter().take(0x103).enumerate() { rec[0x24 + 2 * i..0x26 + 2 * i].copy_from_slice(&c.to_le_bytes()); } + rec[0x230..0x238].copy_from_slice(&f.request.offset.to_le_bytes()); } + rec[0x240..0x244].copy_from_slice(&f.request.source_size.to_le_bytes()); + rec[0x248..0x250].copy_from_slice(&f.request.tag.to_le_bytes()); } None => rec[0xC..0x10].copy_from_slice(&NO_COMMAND.to_le_bytes()), } @@ -1724,15 +3126,28 @@ unsafe extern "system" fn queue_retrieve_error_record(p: *mut c_void, out: *mut std::ptr::copy_nonoverlapping(rec.as_ptr(), out, ERROR_RECORD_BYTES); } -/// DSTORAGE_QUEUE_INFO (0x1C): the queue's desc, empty slots, requests until it submits by itself +/// DSTORAGE_QUEUE_INFO (0x1C): the queue's desc, empty slots, requests until it submits by +/// itself. While a batch is held for the title's Submit (`submit_auto`) its entries count as +/// sent – as a queue that submits itself at half full would have them – and the queue submits by +/// itself when it is full: a title that waits for room without a Submit must not wait on them. unsafe extern "system" fn queue_query(p: *mut c_void, out: *mut u8) { if out.is_null() { return; } let q = queue(p); - let pending = q.pending.lock().unwrap().entries.len(); - let empty = q.capacity.saturating_sub(pending) as u16; - let until = if q.auto_submit_disabled { u16::MAX } else { (q.capacity / 2).max(1).saturating_sub(pending).max(1) as u16 }; + let (pending, holding) = { + let p = q.pending.lock().unwrap(); + (p.entries.len(), q.holding.load(Ordering::Relaxed)) + }; + let (empty, until) = if holding { + (q.capacity, q.capacity.saturating_sub(1 + pending).max(1)) + } else if q.auto_submit_disabled { + // (it waits for the title's Submit: never by itself but full – upstream 5bff7bd) + (q.capacity.saturating_sub(pending), u16::MAX as usize) + } else { + (q.capacity.saturating_sub(pending), (q.capacity / 2).max(1).saturating_sub(pending).max(1)) + }; + let (empty, until) = (empty.min(u16::MAX as usize) as u16, until.min(u16::MAX as usize) as u16); let mut info = [0u8; 0x1C]; info[..0x18].copy_from_slice(&q.desc); info[0x18..0x1A].copy_from_slice(&empty.to_le_bytes()); @@ -1977,6 +3392,8 @@ mod tests { assert_eq!(fence.signalled.load(Ordering::Acquire), 42); assert_eq!(fence.refs.load(Ordering::Acquire), 1, "fence reference released after signal"); assert!(queue(q).cancels.lock().unwrap().is_empty(), "expired cancel rules are pruned"); + let c = &queue(q).counts; + assert_eq!((c.get(CANCELS), c.get(CANCELLED), c.get(SKIPPED)), (1, 1, 2), "one cancel, the pending request it took out, the two submitted ones skipped"); let mut rec = [0u8; ERROR_RECORD_BYTES]; record(q, rec.as_mut_ptr()); @@ -1995,6 +3412,75 @@ mod tests { } } + /// A request refused at enqueue (here a file source on a memory queue) and + /// then cancelled by tag – submitted or still pending – is no failure: "a cancelled request + /// is not counted as a failure in either IDStorageStatusArray or DSTORAGE_ERROR_RECORD". + /// One with a tag the cancel does not match, or enqueued after it, still fails. + #[test] + fn a_refused_request_that_is_cancelled_is_no_failure() { + 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()); // memory queue + 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, 3, 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 cancel: unsafe extern "system" fn(*mut c_void, u64, u64) = std::mem::transmute(*qv.add(7)); + let record: unsafe extern "system" fn(*mut c_void, *mut u8) = std::mem::transmute(*qv.add(10)); + 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)); + + // a file source on this memory queue: refused at enqueue with E_SOURCE_TYPE + let not_a_file = [0usize; 2]; + let mut dst = [0u8; 4]; + let dst_ptr = dst.as_mut_ptr() as u64; + let refused = |tag: u64| request_ex(0, dst_ptr, 0, 4, not_a_file.as_ptr() as u64, 0, 4, 0, tag); + + let gate = Arc::new(std::sync::Barrier::new(2)); + queue(q).enqueue(Entry::Gate(Arc::clone(&gate))); + enqueue(q, refused(0x1001).as_ptr()); // submitted, cancelled below + status(q, s, 0); + submit(q); + enqueue(q, refused(0x1002).as_ptr()); // pending, cancelled below + enqueue(q, refused(0x2001).as_ptr()); // pending, another tag: still fails + status(q, s, 1); + cancel(q, 0xF000, 0x1000); + enqueue(q, refused(0x1003).as_ptr()); // after the cancel: still fails + status(q, s, 2); + submit(q); + gate.wait(); + let t = std::time::Instant::now(); + while !complete(s, 2) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert!(complete(s, 0) && complete(s, 1) && complete(s, 2)); + assert_eq!(hresult(s, 0), S_OK, "the cancelled submitted request is no failure"); + assert_eq!(hresult(s, 1), E_SOURCE_TYPE, "the cancelled pending one is none; the other tag is one"); + assert_eq!(hresult(s, 2), E_SOURCE_TYPE, "enqueued after the cancel"); + let mut rec = [0u8; ERROR_RECORD_BYTES]; + record(q, rec.as_mut_ptr()); + assert_eq!(u32::from_le_bytes(rec[0..4].try_into().unwrap()), 2, "two failures: tag 0x2001 and the one after the cancel"); + let c = &queue(q).counts; + assert_eq!((c.get(CANCELS), c.get(CANCELLED), c.get(SKIPPED)), (1, 1, 1), "one cancel, the pending one it took out, the submitted one skipped"); + + queue_close(q); + queue_release(q); + status_release(s); + } + } + #[test] fn multi_stage_intermediate_size_validation_and_zlib() { // Validation matrix for Request::check @@ -2150,6 +3636,57 @@ mod tests { } } + /// The first failure carries the request's file offset, source size and cancellation tag + /// (DSTORAGE_ERROR_FIRST_FAILURE @0x230 / 0x240 / 0x248), not only its destination and file. + #[test] + fn error_record_has_the_failed_requests_offset_source_size_and_tag() { + unsafe { + let path = std::env::temp_dir().join(format!("xcl-dstorage-error-record-{}.bin", std::process::id())); + std::fs::write(&path, [0u8; 8]).unwrap(); + let wide: Vec = path.to_str().unwrap().encode_utf16().chain(Some(0)).collect(); + 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 open_file: unsafe extern "system" fn(*mut c_void, *const u16, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(4)); + 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[8..10].copy_from_slice(&8u16.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 file = std::ptr::null_mut(); + assert_eq!(open_file(f, wide.as_ptr(), &IID_FILE, &mut file), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 1, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + + // 16 bytes at 0x100 of an 8-byte file + let mut dst = [0u8; 16]; + queue_enqueue_request(q, request_ex(0, dst.as_mut_ptr() as u64, 0, 16, file as u64, 0x100, 16, 0, 0xABCD).as_ptr()); + queue_enqueue_status(q, s, 0); + queue_submit(q); + let start = std::time::Instant::now(); + while !status_is_complete(s, 0) && start.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_ne!(status_get_hresult(s, 0), S_OK); + + let mut rec = [0u8; ERROR_RECORD_BYTES]; + queue_retrieve_error_record(q, rec.as_mut_ptr()); + assert_eq!(u32::from_le_bytes(rec[0..4].try_into().unwrap()), 1); + assert_eq!(u32::from_le_bytes(rec[0x20..0x24].try_into().unwrap()), 16); + assert_eq!(u64::from_le_bytes(rec[0x230..0x238].try_into().unwrap()), 0x100, "FileOffset"); + assert_eq!(u32::from_le_bytes(rec[0x240..0x244].try_into().unwrap()), 16, "SourceSize"); + assert_eq!(u64::from_le_bytes(rec[0x248..0x250].try_into().unwrap()), 0xABCD, "CancellationTag"); + + queue_close(q); + queue_release(q); + status_release(s); + file_release(file); + let _ = std::fs::remove_file(&path); + } + } + #[test] fn queue_release_concurrent_breaks_worker_cycle() { unsafe { @@ -2242,6 +3779,23 @@ mod tests { } } + /// A slot nothing was enqueued into is complete with S_OK, so a title that waits for + /// IsComplete before (re)using a slot does not wait forever on its first use. + #[test] + fn a_new_status_array_slot_is_complete() { + 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_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 s = std::ptr::null_mut(); + assert_eq!(create_status(f, 4, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + assert!(status_is_complete(s, 3)); + assert_eq!(status_get_hresult(s, 3), S_OK); + status_release(s); + } + } + /// A destination page array whose entry is still 0 at EnqueueRequest and gets its page /// before the request's turn: the data arrives (a retail title's streaming). #[test] @@ -2317,6 +3871,1104 @@ mod tests { } } + /// (tests) A queue of `capacity` entries reading from memory, a status array, and the methods + /// the tests call. Dropped – an assertion that fails too – it is closed, which waits for its + /// worker, and released: declare the buffers its requests read before it. + struct TestQueue { + q: *mut c_void, + s: *mut c_void, + enqueue: unsafe extern "system" fn(*mut c_void, *const u8), + status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32), + submit: unsafe extern "system" fn(*mut c_void), + query: unsafe extern "system" fn(*mut c_void, *mut u8), + complete: unsafe extern "system" fn(*mut c_void, u32) -> bool, + hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT, + } + + unsafe fn test_queue(capacity: u16, statuses: u32) -> TestQueue { + 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(&capacity.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, statuses, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let (qv, sv) = (*(q as *const *const usize), *(s as *const *const usize)); + TestQueue { + q, + s, + enqueue: std::mem::transmute(*qv.add(3)), + status: std::mem::transmute(*qv.add(4)), + submit: std::mem::transmute(*qv.add(6)), + query: std::mem::transmute(*qv.add(11)), + complete: std::mem::transmute(*sv.add(3)), + hresult: std::mem::transmute(*sv.add(4)), + } + } + + impl TestQueue { + unsafe fn wait(&self, index: u32) -> HRESULT { + let t = std::time::Instant::now(); + while !(self.complete)(self.s, index) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert!((self.complete)(self.s, index), "status {index} never completed"); + (self.hresult)(self.s, index) + } + + /// DSTORAGE_QUEUE_INFO: (empty slots, requests until the queue submits by itself) + unsafe fn info(&self) -> (u16, u16) { + let mut info = [0u8; 0x1C]; + (self.query)(self.q, info.as_mut_ptr()); + (u16::from_le_bytes([info[0x18], info[0x19]]), u16::from_le_bytes([info[0x1A], info[0x1B]])) + } + + /// The queue's last reference let go without a Close (`Drop for QueueInner`), and its + /// status array's: what is pending is never run. + unsafe fn release_without_close(self) { + queue_release(self.q); + status_release(self.s); + std::mem::forget(self); + } + } + + /// (tests) The first of `why` that holds, said with `skip_config`: true if the test cannot run + /// with this host or these switches. + fn skips(why: &[(bool, &str)]) -> bool { + match why.iter().find(|w| w.0) { + Some(&(_, reason)) => { + crate::gpu::recomp::runner::skip_config(reason); + true + } + None => false, + } + } + + fn no_uma() -> bool { + crate::gpu::uma::get().is_none() + } + + /// (tests) Queue `q`'s hold now and how its last hold ended, copied out: an assertion on them + /// then fails with the queue's lock let go – one that failed under it would poison the lock, + /// and the queue's Close at the test's end (which cannot unwind) would abort the test process. + fn hold_now(q: &QueueInner) -> (Option, Option) { + let p = q.pending.lock().unwrap_or_else(|e| e.into_inner()); + (p.hold, p.last_end) + } + + /// (tests) Queue `id`'s part of the probe line, up to the next queue's or the end. Another + /// test's probe line may hold the queue's entries for a moment ("pending ?"): looked at again, + /// 50 times at most, 1 ms apart. + fn probe_part(id: usize) -> String { + let start = format!("; q{id}("); + let mut part = String::new(); + for _ in 0..50 { + let line = probe_line(); + let Some(at) = line.find(&start) else { return String::new() }; + let rest = &line[at + 2..]; + part = rest[..rest.find("; q").unwrap_or(rest.len())].to_string(); + if !part.contains("pending ?") { + break; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + part + } + + /// (tests) The numbers between the literals of `line` that start with `literals[0]`: the + /// digits between each literal and the next (None: the line does not read so). + fn numbers_between(line: &str, literals: &[&str]) -> Option> { + let mut rest = line.strip_prefix(literals[0])?; + let mut out = Vec::new(); + for lit in &literals[1..] { + let end = rest.find(lit)?; + out.push(rest[..end].parse().ok()?); + rest = &rest[end + lit.len()..]; + } + Some(out) + } + + /// (tests) One title physical page, never mapped: at its home (the caller frees it). + unsafe fn one_page() -> usize { + let (mut n, mut p) = (1usize, [0usize]); + assert_eq!(crate::hle::kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, p.as_mut_ptr()), 1); + p[0] + } + + /// (tests) 64 KiB of address space reserved (released by the caller). + unsafe fn reserve() -> usize { + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_RESERVE, PAGE_READWRITE}; + let r = VirtualAlloc(std::ptr::null(), crate::hle::kernelx::PHYS_PAGE_SIZE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(r, 0); + r + } + + unsafe fn unreserve(r: usize) { + windows_sys::Win32::System::Memory::VirtualFree(r as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE); + } + + impl Drop for TestQueue { + fn drop(&mut self) { + unsafe { + queue_close(self.q); + queue_release(self.q); + status_release(self.s); + } + } + } + + /// (tests) `n` title physical pages mapped side by side into a new reservation at `at`, each + /// filled with a byte; unmapped and freed when dropped. + struct Mapped { + pages: Vec, + at: *mut u8, + } + + unsafe fn mapped_pages(n: usize, fill: u8) -> Mapped { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; + let mut count = n; + let mut pages = vec![0usize; n]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + let reserved = windows_sys::Win32::System::Memory::VirtualAlloc( + std::ptr::null(), + n * PHYS_PAGE_SIZE, + windows_sys::Win32::System::Memory::MEM_RESERVE, + windows_sys::Win32::System::Memory::PAGE_READWRITE, + ); + assert!(!reserved.is_null()); + assert_eq!(MapTitlePhysicalPages(reserved, n, 0, 4, pages.as_mut_ptr()), reserved); + std::ptr::write_bytes(reserved as *mut u8, fill, n * PHYS_PAGE_SIZE); + Mapped { pages, at: reserved as *mut u8 } + } + + impl Drop for Mapped { + fn drop(&mut self) { + use crate::hle::kernelx::{FreeTitlePhysicalPages, MapTitlePhysicalPages}; + unsafe { + MapTitlePhysicalPages(self.at as *mut c_void, self.pages.len(), 0, 4, std::ptr::null_mut()); + windows_sys::Win32::System::Memory::VirtualFree(self.at as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE); + FreeTitlePhysicalPages(std::ptr::null_mut(), self.pages.len(), self.pages.as_mut_ptr()); + } + } + } + + /// An entry of the title's page table that names one page at EnqueueRequest and another by the + /// request's turn (a page the title freed and took again for the batch): the data goes to the + /// page the table names then, and the first page keeps what it held. (Read at EnqueueRequest, + /// a texture's blocks went over a live object's data in GTA VI's world – run 63.) + #[test] + fn a_page_table_entry_changed_after_enqueue_is_read_at_the_requests_turn() { + use crate::hle::kernelx::PHYS_PAGE_SIZE; + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0")]) { + return; + } + unsafe { + let m = mapped_pages(2, 0xAA); + let data: Vec = (0..0x400u32).map(|i| (i * 7 + 3) as u8).collect(); + let mut table = Box::new([m.pages[0]]); + let t = test_queue(16, 1); + let moved_before = late_page_counts()[1]; + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr() as u64, 0x100, data.len() as u32, data.as_ptr() as u64, 0, data.len() as u32, 0, 0).as_ptr()); + // the title's table names another page by the time it submits + std::ptr::write_volatile(&mut table[0], m.pages[1]); + (t.status)(t.q, t.s, 0); + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK); + let first = std::slice::from_raw_parts(m.at.add(0x100), data.len()); + let second = std::slice::from_raw_parts(m.at.add(PHYS_PAGE_SIZE + 0x100), data.len()); + assert_eq!(second, &data[..], "the data goes to the page the table names at the request's turn"); + assert!(first.iter().all(|&b| b == 0xAA), "the page the table named before keeps what it held"); + assert!(late_page_counts()[1] > moved_before); + if old_pages() { + // (where 0021 wrote: the page the entry named before, mapped where the title has it) + let c = &queue(t.q).counts; + assert_eq!((c.get(OLD_MAPPED), c.get(OLD_IN_VIEW)), (1, 0), "the old page is classed where it is"); + } + } + } + + /// A half-full queue submits by itself, but requests into the title's pages – whose table the + /// title fills right before its Submit – wait for that Submit: none runs with its entry still + /// naming the page it named before (a page the title freed: what ran early would write + /// there), and all run into the pages the title names when it submits. + #[test] + fn a_half_full_queue_leaves_requests_into_the_titles_pages_for_its_submit() { + use crate::hle::kernelx::PHYS_PAGE_SIZE; + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0")]) { + return; + } + unsafe { + // page 0: where the batch goes; page 1: what the table named before + let m = mapped_pages(2, 0xEE); + std::ptr::write_bytes(m.at.add(PHYS_PAGE_SIZE), 0xDD, PHYS_PAGE_SIZE); + let before = std::slice::from_raw_parts(m.at.add(PHYS_PAGE_SIZE), PHYS_PAGE_SIZE); + let data: Vec = (0..0x500u32).map(|i| (i * 11 + 1) as u8).collect(); + // one entry per request, all naming the old page when they are enqueued (half of 16 + // is 8: the queue submits by itself at the 8th) + let mut table = Box::new([m.pages[1]; 10]); + let t = test_queue(16, 1); + let held = HELD.load(Ordering::Relaxed); + for k in 0..10usize { + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr().add(k) as u64, (0x100 * k) as u16, 0x80, data.as_ptr().add(0x80 * k) as u64, 0, 0x80, 0, 0).as_ptr()); + } + (t.status)(t.q, t.s, 0); + std::thread::sleep(std::time::Duration::from_millis(200)); + assert!(!(t.complete)(t.s, 0), "nothing runs before the title's Submit"); + assert!(before.iter().all(|&b| b == 0xDD), "no request wrote into the page its table named before the title filled it"); + assert!(std::slice::from_raw_parts(m.at, 0x1000).iter().all(|&b| b == 0xEE)); + assert!(HELD.load(Ordering::Relaxed) > held, "the batch was held"); + let q = queue(t.q); + assert_eq!(hold_now(q).0.map(|h| h.held), Some(8), "8 entries kept back when it began"); + let part = probe_part(q.id); + assert!(part.starts_with(&format!("q{}(memory, cap 16): pending 11, in flight 0, run 0, most pending 11, holding ", q.id)), "{part}"); + for k in 0..10 { + std::ptr::write_volatile(&mut table[k], m.pages[0]); + } + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK, "every request ran with the table as the title filled it"); + let e = hold_now(q).1.expect("the Submit ended the hold"); + assert_eq!((e.cause, e.held, e.sent), (HoldCause::Submit, 8, 11)); + assert!(e.ms >= 150, "it lasted the test's 200 ms: {} ms", e.ms); + assert!(!probe_part(q.id).contains(", holding")); + for k in 0..10usize { + assert_eq!(std::slice::from_raw_parts(m.at.add(0x100 * k), 0x80), &data[0x80 * k..0x80 * (k + 1)], "request {k}"); + } + assert!(before.iter().all(|&b| b == 0xDD), "the page the table named before keeps what it held"); + } + } + + /// Query tells the queue as it is: entries pending before the half-full point count against + /// the empty slots and toward its own submit; while a batch is held for the title's Submit + /// its entries count as sent and the queue says it submits by itself when it is full – and it + /// does: a title that waits for room without a Submit gets its requests run by enqueueing on. + #[test] + fn query_tells_a_held_batch_as_it_is_and_the_full_queue_sends_it() { + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0")]) { + return; + } + unsafe { + let m = mapped_pages(1, 0x33); + let data: Vec = (0..0x780u32).map(|i| (i * 13 + 7) as u8).collect(); + let table = Box::new([m.pages[0]; 15]); + let t = test_queue(16, 1); + let request = |k: usize| request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr().add(k) as u64, (0x100 * k) as u16, 0x80, data.as_ptr().add(0x80 * k) as u64, 0, 0x80, 0, 0); + assert_eq!(t.info(), (16, 8), "an empty queue: all slots, half of them to its own submit"); + for k in 0..3 { + (t.enqueue)(t.q, request(k).as_ptr()); + } + assert_eq!(t.info(), (13, 5), "3 pending, nothing held yet"); + // 10 requests (held at the 8th) and a status: 11 entries, 4 to the full queue's send + for k in 3..10 { + (t.enqueue)(t.q, request(k).as_ptr()); + } + (t.status)(t.q, t.s, 0); + assert_eq!(t.info(), (16, 4)); + let q = queue(t.q); + let near_full = || q.pending.lock().unwrap().hold.map(|h| h.near_full); + assert_eq!(near_full(), Some(false), "11 entries: under 3/4 of the queue"); + for k in 10..13 { + (t.enqueue)(t.q, request(k).as_ptr()); + assert_eq!(t.info(), (16, (3 - (k - 10)) as u16), "request {k}"); + if k == 10 { + assert_eq!(near_full(), Some(true), "12 entries: 3/4 of the queue"); + } + } + assert!(!(t.complete)(t.s, 0), "held until the queue is full"); + (t.enqueue)(t.q, request(13).as_ptr()); + assert_eq!(t.wait(0), S_OK, "the full queue sent the held batch without a Submit"); + let (end, most) = { + let p = q.pending.lock().unwrap(); + (p.last_end, p.most) + }; + let e = end.expect("the full queue's send ended the hold"); + assert_eq!((e.cause, e.held, e.sent), (HoldCause::FullQueue, 8, 15)); + assert_eq!(most, 15); + for k in 0..10usize { + assert_eq!(std::slice::from_raw_parts(m.at.add(0x100 * k), 0x80), &data[0x80 * k..0x80 * (k + 1)], "request {k}"); + } + assert_eq!(t.info(), (16, 8), "nothing held, nothing pending"); + } + } + + /// Cancelling requests of a held batch: the hold lasts while a request waiting for the + /// title's Submit is left; once none is, the hold ends and what it kept back – a status here – + /// goes without a Submit, and Query tells an empty queue again. + #[test] + fn cancelling_a_held_batch_ends_the_hold_and_sends_what_it_kept_back() { + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0")]) { + return; + } + unsafe { + let m = mapped_pages(1, 0x44); + let data = vec![0x5Au8; 0x80 * 10]; + let table = Box::new([m.pages[0]; 10]); + let t = test_queue(16, 1); + // requests 0-4 tagged 0x10, 5-9 tagged 0x20 (held at the 8th), then a status + for k in 0..10usize { + let tag = if k < 5 { 0x10 } else { 0x20 }; + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr().add(k) as u64, (0x100 * k) as u16, 0x80, data.as_ptr().add(0x80 * k) as u64, 0, 0x80, 0, tag).as_ptr()); + } + (t.status)(t.q, t.s, 0); + let q = queue(t.q); + assert!(q.holding.load(Ordering::Relaxed), "held at the 8th"); + queue_cancel(t.q, 0xFF, 0x10); + assert!(q.holding.load(Ordering::Relaxed), "requests 5-9 still wait for the Submit"); + let (hold, end) = hold_now(q); + assert!(hold.is_some() && end.is_none(), "the hold goes on"); + assert_eq!(t.info(), (16, 9), "6 entries held: 9 more to the full queue's send"); + std::thread::sleep(std::time::Duration::from_millis(100)); + assert!(!(t.complete)(t.s, 0), "the status waits behind them"); + queue_cancel(t.q, 0xFF, 0x20); + assert!(!q.holding.load(Ordering::Relaxed), "no request waits for the Submit any more"); + assert_eq!(t.wait(0), S_OK, "what the hold kept back went without a Submit"); + assert_eq!(t.info(), (16, 8)); + let e = hold_now(q).1.expect("the Cancel ended the hold"); + assert_eq!((e.cause, e.held, e.sent), (HoldCause::Cancel, 8, 1), "the status went"); + assert_eq!((q.counts.get(CANCELS), q.counts.get(CANCELLED), q.counts.get(SKIPPED)), (2, 10, 0), "two cancels took out 10 pending requests"); + assert!(std::slice::from_raw_parts(m.at, 0x1000).iter().all(|&b| b == 0x44), "the cancelled requests wrote nothing"); + } + } + + /// A full queue (one slot left) sends all it holds, requests into the title's pages too: the + /// title cannot Submit while it waits for room. + #[test] + fn a_full_queue_sends_requests_into_the_titles_pages() { + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0")]) { + return; + } + unsafe { + let m = mapped_pages(1, 0x11); + let data: Vec = (0..0x180u32).map(|i| (i * 5 + 9) as u8).collect(); + let table = Box::new([m.pages[0]; 3]); + let t = test_queue(4, 1); + for k in 0..3usize { + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr().add(k) as u64, (0x100 * k) as u16, 0x80, data.as_ptr().add(0x80 * k) as u64, 0, 0x80, 0, 0).as_ptr()); + } + // 3 of 4 slots taken: sent without a Submit + let last = std::slice::from_raw_parts(m.at.add(0x200), 0x80); + let t0 = std::time::Instant::now(); + while last != &data[0x100..0x180] && t0.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!(last, &data[0x100..0x180], "the full queue ran its requests without a Submit"); + let e = hold_now(queue(t.q)).1.expect("the full queue's send ended the hold"); + assert_eq!((e.cause, e.held, e.sent), (HoldCause::FullQueue, 2, 3)); + (t.status)(t.q, t.s, 0); + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK); + } + } + + /// A page written through its page array at its home, then mapped by the title at one address, + /// at another, and home again: the look at the address where its data is names the write – + /// into that page, with the bytes it covered –, the crash's look with a wait of its own too; + /// the home it left names the page that went away and what landed there; the address it left + /// names nothing. A plain request is kept by its address. (0022 kept a write by the address it + /// landed at only: once the page moved, "no DirectStorage request".) + #[test] + fn a_page_written_at_its_home_is_named_where_the_title_maps_it_later() { + use crate::hle::kernelx::{FreeTitlePhysicalPages, MapTitlePhysicalPages}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE}; + if skips(&[(no_uma(), "no unified memory"), (page_log() != PageLog::Page, "XCL_DSTORAGE_PAGE_LOG is not the default")]) { + return; + } + unsafe { + let mut p = [one_page()]; + let table = Box::new([p[0]]); + let src = [0x5Au8; 0x80]; + let plain = VirtualAlloc(std::ptr::null(), crate::hle::kernelx::PHYS_PAGE_SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(plain, 0); + let bytes = [0xC3u8; 0x20]; + let t = test_queue(16, 2); + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr() as u64, 0x100, 0x80, src.as_ptr() as u64, 0, 0x80, 0, 0).as_ptr()); + (t.status)(t.q, t.s, 0); + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK); + let home = crate::hle::kernelx::page_address(p[0]).expect("written: its home holds memory"); + assert_eq!(std::slice::from_raw_parts((home + 0x100) as *const u8, 0x80), &src[..]); + let dest = format!("destination {:#x}", table.as_ptr() as u64); + let mapped = format!("into physical page {:#x}, mapped here – bytes 0x100-0x17f of it", p[0]); + // mapped at r1: the look there names the write into the page + let r1 = reserve(); + assert_eq!(MapTitlePhysicalPages(r1 as *mut c_void, 1, 0, 4, p.as_mut_ptr()) as usize, r1); + let at = last_write_at(r1 + 0x140); + assert!(at.contains(&dest) && at.contains(&mapped), "{at}"); + let within = last_write_within(r1 + 0x140, &AtomicU32::new(2000)); + assert!(within.contains(&dest) && within.contains(&mapped), "the crash's look: {within}"); + let left = last_write_at(home + 0x140); + assert!( + left.contains(&format!("this is the home of physical page {:#x}, which is mapped at {r1:#x} now", p[0])) + && left.contains(&format!("landed here went into physical page {:#x} (", p[0])) + && !left.contains("mapped here"), + "{left}" + ); + // moved to r2: the bytes go with the page, and so does the write + let r2 = reserve(); + assert_eq!(MapTitlePhysicalPages(r2 as *mut c_void, 1, 0, 4, p.as_mut_ptr()) as usize, r2); + let at2 = last_write_at(r2 + 0x140); + assert!(at2.contains(&dest) && at2.contains(&format!("into physical page {:#x}, mapped here", p[0])), "{at2}"); + // (the address it left names neither the page nor its write – r1 may have been another + // test's address before, and what landed there then is named: this page's number, + // never reused, is looked for whole) + let gone = last_write_at(r1 + 0x140); + let names_page = [",", " "].iter().any(|end| gone.contains(&format!("physical page {:#x}{end}", p[0]))); + assert!(!names_page && !gone.contains(&dest), "{gone}"); + // home again + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, p.as_mut_ptr()) as usize, home); + let back = last_write_at(home + 0x140); + assert!(back.contains(&format!("into physical page {:#x}, at its home here – bytes 0x100-0x17f of it", p[0])), "{back}"); + // a plain request: kept by its address, with the bytes it wrote + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT, (plain + 0x10) as u64, 0, 0x20, bytes.as_ptr() as u64, 0, 0x20, 0, 0).as_ptr()); + (t.status)(t.q, t.s, 1); + (t.submit)(t.q); + assert_eq!(t.wait(1), S_OK); + let by_address = last_write_at(plain + 0x18); + assert!(by_address.contains(&format!("destination {:#x}", plain + 0x10)) && by_address.contains("bytes 0x10-0x2f of its 64 KiB page"), "{by_address}"); + drop(t); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, p.as_mut_ptr()), 1); + for r in [r1, r2, plain] { + unreserve(r); + } + } + } + + /// A request into the title's own address space where it mapped a page (GTA VI streams into + /// its CPU view of the pool): the write is kept by that page, so where the title maps the page + /// next the look names it – the crash's look too –, and the address it was written at names + /// the page its bytes went into. + #[test] + fn a_write_into_a_mapped_page_is_named_where_the_page_goes() { + use crate::hle::kernelx::{FreeTitlePhysicalPages, MapTitlePhysicalPages}; + if skips(&[(no_uma(), "no unified memory"), (page_log() != PageLog::Page, "XCL_DSTORAGE_PAGE_LOG is not the default")]) { + return; + } + unsafe { + let mut p = [one_page()]; + let r1 = reserve(); + assert_eq!(MapTitlePhysicalPages(r1 as *mut c_void, 1, 0, 4, p.as_mut_ptr()) as usize, r1); + let src: Vec = (0..0x400u32).map(|i| (i * 3 + 1) as u8).collect(); + let t = test_queue(16, 1); + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT, (r1 + 0x100) as u64, 0, 0x400, src.as_ptr() as u64, 0, 0x400, 0, 0).as_ptr()); + (t.status)(t.q, t.s, 0); + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK); + let r2 = reserve(); + assert_eq!(MapTitlePhysicalPages(r2 as *mut c_void, 1, 0, 4, p.as_mut_ptr()) as usize, r2); + assert_eq!(std::slice::from_raw_parts((r2 + 0x100) as *const u8, 0x400), &src[..], "the bytes went with the page"); + let want = [format!("destination {:#x}", r1 + 0x100), format!("into physical page {:#x}, mapped here – bytes 0x100-0x4ff of it", p[0])]; + for text in [last_write_at(r2 + 0x140), last_write_within(r2 + 0x140, &AtomicU32::new(2000))] { + assert!(want.iter().all(|w| text.contains(w)), "{text}"); + } + // the page map read, no page at r1 now: the page is not there – its bytes may be (C-1) + let left = last_write_at(r1 + 0x140); + assert!( + left.contains(&format!("landed here went into physical page {:#x}, which is not mapped here now (this memory may still hold what that page left, or other memory): ", p[0])), + "{left}" + ); + // the page map busy: not read – the page may be anywhere + let busy = { + let _held = crate::hle::kernelx::hold_page_map(); + last_write_within(r1 + 0x140, &AtomicU32::new(5)) + }; + assert!(busy.starts_with("unknown – the page map was busy") && busy.contains(&format!("landed here went into physical page {:#x} (which may be elsewhere now)", p[0])), "{busy}"); + drop(t); + MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, p.as_mut_ptr()); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, p.as_mut_ptr()), 1); + unreserve(r1); + unreserve(r2); + } + } + + /// The write record held by another thread until this is dropped, 2 s at most: what a crash's + /// look meets while a worker notes a write. The helper never panics while it holds it. + struct RecordHold(Option>, Option>); + + fn hold_page_writes() -> RecordHold { + let (held, is_held) = std::sync::mpsc::channel(); + let (go, gone) = std::sync::mpsc::channel::<()>(); + let t = std::thread::spawn(move || { + let _g = PAGE_WRITES.lock().unwrap_or_else(|e| e.into_inner()); + let _ = held.send(()); + let _ = gone.recv_timeout(std::time::Duration::from_secs(2)); + }); + let _ = is_held.recv(); + RecordHold(Some(go), Some(t)) + } + + impl Drop for RecordHold { + fn drop(&mut self) { + drop(self.0.take()); // (its sender gone: the helper lets go at once) + if let Some(t) = self.1.take() { + let _ = t.join(); + } + } + } + + /// The write record busy at a crash's look: the line keeps 0022's head and what the page map + /// said of the address – here the page mapped there, the fact that ties it to the other lines + /// (C-2). The record is held a few ms (other tests' workers wait for it meanwhile). + #[test] + fn a_busy_write_record_keeps_what_the_page_map_said() { + use crate::hle::kernelx::{FreeTitlePhysicalPages, MapTitlePhysicalPages}; + assert_eq!(page_here_text(Some(Ok(None))), "; no physical page here"); + assert_eq!(page_here_text(Some(Err(()))), "; the page map was busy too"); + assert_eq!(page_here_text(None), "", "not looked up (XCL_DSTORAGE_PAGE_LOG=address)"); + { + use crate::hle::kernelx::PageHere; + assert_eq!(page_here_text(Some(Ok(Some(PageHere::Mapped(0x5A00))))), "; physical page 0x5a00 is mapped here"); + assert_eq!(page_here_text(Some(Ok(Some(PageHere::Home(0x5A00))))), "; physical page 0x5a00 is at its home here"); + assert_eq!(page_here_text(Some(Ok(Some(PageHere::HomeOf(0x5A00, 0x5A_0001_0000))))), "; this is the home of physical page 0x5a00, mapped at 0x5a00010000 now"); + } + if skips(&[(no_uma(), "no unified memory"), (page_log() != PageLog::Page, "XCL_DSTORAGE_PAGE_LOG is not the default")]) { + return; + } + unsafe { + let mut p = [one_page()]; + let r = reserve(); + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, p.as_mut_ptr()) as usize, r); + let busy = { + let _held = hold_page_writes(); + last_write_within(r + 0x10, &AtomicU32::new(5)) + }; + assert!(busy.starts_with("unknown (the record is busy)") && busy.contains(&format!("; physical page {:#x} is mapped here", p[0])), "{busy}"); + MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, p.as_mut_ptr()); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, p.as_mut_ptr()), 1); + unreserve(r); + } + } + + /// Two requests into one page, at bytes of their own: a look names the write over the byte it + /// reads – not the page's last writer –, and a byte neither wrote is said to be covered by none + /// kept, with the page's last write. + #[test] + fn a_read_is_named_by_the_write_over_its_byte() { + use crate::hle::kernelx::{FreeTitlePhysicalPages, MapTitlePhysicalPages}; + if skips(&[(no_uma(), "no unified memory"), (page_log() != PageLog::Page, "XCL_DSTORAGE_PAGE_LOG is not the default")]) { + return; + } + unsafe { + let mut p = [one_page()]; + let r = reserve(); + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, p.as_mut_ptr()) as usize, r); + let (ta, tb) = (Box::new([p[0]]), Box::new([p[0]])); + let (a, b) = ([0xA1u8; 0x80], [0xB2u8; 0x80]); + let t = test_queue(16, 1); + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, ta.as_ptr() as u64, 0x100, 0x80, a.as_ptr() as u64, 0, 0x80, 0, 0).as_ptr()); + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, tb.as_ptr() as u64, 0x8000, 0x80, b.as_ptr() as u64, 0, 0x80, 0, 0).as_ptr()); + (t.status)(t.q, t.s, 0); + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK); + let (da, db) = (format!("destination {:#x}", ta.as_ptr() as u64), format!("destination {:#x}", tb.as_ptr() as u64)); + let x = last_write_at(r + 0x140); + assert!(x.contains(&da) && x.contains("bytes 0x100-0x17f"), "{x}"); + let y = last_write_at(r + 0x8040); + assert!(y.contains(&db) && y.contains("bytes 0x8000-0x807f"), "{y}"); + let z = last_write_at(r + 0x4000); + assert!(z.contains("covers byte 0x4000 – its last:") && z.contains(&db), "{z}"); + drop(t); + MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, p.as_mut_ptr()); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, p.as_mut_ptr()), 1); + unreserve(r); + } + } + + /// `XCL_DSTORAGE_PAGE_LOG=address` (its own one.sh process; a skip otherwise): 0022's record – + /// every write by the address its bytes landed at, looked up by that address alone, so the + /// address the title mapped the page at next knows nothing (0022's blind spot, 0022's text). + #[test] + fn under_page_log_address_writes_are_kept_by_address_alone() { + use crate::hle::kernelx::{FreeTitlePhysicalPages, MapTitlePhysicalPages}; + if skips(&[(no_uma(), "no unified memory"), (page_log() != PageLog::Address, "XCL_DSTORAGE_PAGE_LOG is not address")]) { + return; + } + unsafe { + let mut p = [one_page()]; + let table = Box::new([p[0]]); + let src = [0x5Au8; 0x80]; + let t = test_queue(16, 2); + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr() as u64, 0x100, 0x80, src.as_ptr() as u64, 0, 0x80, 0, 0).as_ptr()); + (t.status)(t.q, t.s, 0); + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK); + let home = crate::hle::kernelx::page_address(p[0]).expect("written: its home holds memory"); + let r1 = reserve(); + assert_eq!(MapTitlePhysicalPages(r1 as *mut c_void, 1, 0, 4, p.as_mut_ptr()) as usize, r1); + let at_home = last_write_at(home + 0x140); + assert!(at_home.contains(&format!("destination {:#x}", table.as_ptr() as u64)) && at_home.contains("bytes 0x100-0x17f of its 64 KiB page"), "{at_home}"); + assert_eq!(last_write_at(r1 + 0x140), "no DirectStorage request"); + assert_eq!(last_write_of_page(p[0]), "not kept by page (XCL_DSTORAGE_PAGE_LOG=address)"); + drop(t); + MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, p.as_mut_ptr()); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, p.as_mut_ptr()), 1); + unreserve(r1); + } + } + + /// The record's parts, pure: the keys it keeps (the newest, in two halves; a key written again + /// carried back with what it had), the writes a key keeps (the newest 4, one over all of an + /// earlier one's bytes takes its place) and the bytes of each page a write covers. + #[test] + fn the_write_record_keeps_its_newest_keys_and_writes() { + let mut r: Recent = Recent::new(4); + for k in 1..=4 { + *r.newest(k) = k as u64; + } + assert!(r.get(1).is_some() && r.len() == 4); + *r.newest(5) = 5; + assert_eq!((r.get(1).copied(), r.forgotten, r.len()), (Some(1), 0, 5), "the first half kept as the old one"); + assert_eq!(*r.newest(1), 1, "a key in the old half is carried back with what it had"); + *r.newest(1) = 11; + assert_eq!((r.len(), r.get(1).copied()), (5, Some(11)), "and not kept twice"); + *r.newest(6) = 6; + *r.newest(7) = 7; + *r.newest(8) = 8; + assert_eq!(r.forgotten, 3, "the old half (2, 3, 4) forgotten"); + assert!((2..=4).all(|k| r.get(k).is_none())); + assert!([5, 1, 6, 7, 8].iter().all(|&k| r.get(k).is_some())); + for k in 100..150 { + *r.newest(k) = k as u64; + assert!(r.len() <= 8, "{} keys", r.len()); + } + + let w = |seq: u64, from: u16, last: u16| PageWrite { seq, from, last, ..Default::default() }; + let seqs = |ws: &Writes| ws.all().iter().map(|e| e.seq).collect::>(); + let mut ws = Writes::default(); + for s in 1..=5u64 { + ws.add(w(s, (s as u16) * 0x100, (s as u16) * 0x100 + 0xF)); + } + assert_eq!(seqs(&ws), [2, 3, 4, 5], "past 4 the oldest goes"); + assert_eq!(ws.over(0x208).map(|e| e.seq), Some(2)); + assert_eq!(ws.over(0x110).map(|e| e.seq), None); + ws.add(w(6, 0, 0xFFFF)); + assert_eq!(seqs(&ws), [6], "a write over the whole page takes every place"); + ws.add(w(7, 0x100, 0x1FF)); + ws.add(w(8, 0x180, 0x27F)); + assert_eq!(seqs(&ws), [6, 7, 8], "writes that cover part of another stay"); + assert_eq!(ws.over(0x1A0).map(|e| e.seq), Some(8), "the newest over the byte"); + assert_eq!(ws.over(0x120).map(|e| e.seq), Some(7)); + assert_eq!(ws.over(0x8000).map(|e| e.seq), Some(6)); + assert_eq!(ws.newest().map(|e| e.seq), Some(8)); + assert_eq!(ws.by_seq(7).map(|e| e.from), Some(0x100)); + + let spans = |start: usize, n: usize| page_spans(start, n).collect::>(); + assert_eq!(spans(0x100, 0x80), [(0, 0x100, 0x17f)]); + assert_eq!(spans(0xFF80, 0x100), [(0, 0xff80, 0xffff), (1, 0, 0x7f)]); + assert_eq!(spans(0xF800, 0x1800), [(0, 0xf800, 0xffff), (1, 0, 0xfff)]); + // (run 64's request #16864: 29,860 bytes at 0x77bb90000 + 0x100) + let a = 0x7_7bb9_0000usize; + assert_eq!(spans(a + 0x100, 29_860), [(a / PAGE_BYTES, 0x100, 0x75a3)]); + } + + /// Where the page a moved entry named at EnqueueRequest is at the request's turn – mapped by + /// the title, at its home with memory, at its home without, no page at all –, looked up with + /// the kernel's lock waited for while a title thread holds it (a try would say "at its home"). + #[test] + fn a_moved_entrys_old_page_is_classed_where_it_is() { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, PHYS_PAGE_SIZE}; + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0"), (!old_pages(), "XCL_DSTORAGE_OLD_PAGES=0")]) { + return; + } + unsafe { + // A mapped at m.at; B where the data goes + let m = mapped_pages(2, 0x22); + let (a, b) = (m.pages[0], m.pages[1]); + // C used at its home; D never used (unused at a home only reserved until used; a home + // in a window committed as a whole holds memory) + let (mut n, mut cd) = (2usize, [0usize; 2]); + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, cd.as_mut_ptr()), 1); + let (c, d) = (cd[0], cd[1]); + assert!(crate::hle::kernelx::write_physical_pages(&[c], 0, &[0x77])); + let d_kind = if crate::hle::kernelx::page_address(d).is_none() { OLD_UNUSED } else { OLD_HOME }; + // the last entry: a multiple of 16 in no block + let mut table = Box::new([a, c, d, usize::MAX & !0xF]); + let data: Vec = (0..0x200u32).map(|i| (i * 9 + 2) as u8).collect(); + let t = test_queue(16, 1); + for k in 0..4usize { + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr().add(k) as u64, (0x100 * k) as u16, 0x80, data.as_ptr().add(0x80 * k) as u64, 0, 0x80, 0, 0).as_ptr()); + } + for k in 0..4 { + std::ptr::write_volatile(&mut table[k], b); + } + (t.status)(t.q, t.s, 0); + // the page map busy while the worker looks (a title thread mapping pages) + let hold = crate::hle::kernelx::hold_page_map(); + (t.submit)(t.q); + std::thread::sleep(std::time::Duration::from_millis(150)); + drop(hold); + assert_eq!(t.wait(0), S_OK); + let q = queue(t.q); + let mut want = [1, 1, 0, 1]; + want[d_kind] += 1; + assert_eq!([OLD_MAPPED, OLD_HOME, OLD_UNUSED, OLD_NOT_A_PAGE].map(|k| q.counts.get(k)), want, "mapped, at home, unused, not a page"); + assert_eq!((q.counts.get(OLD_IN_VIEW), q.counts.get(OLD_NOT_LOOKED)), (0, 0)); + assert!(std::slice::from_raw_parts(m.at, 0x400).iter().all(|&x| x == 0x22), "A keeps what it held"); + for k in 0..4usize { + assert_eq!(std::slice::from_raw_parts(m.at.add(PHYS_PAGE_SIZE + 0x100 * k), 0x80), &data[0x80 * k..0x80 * (k + 1)], "request {k} went into B"); + } + drop(t); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, cd.as_mut_ptr()), 1); + } + } + + /// What 0022 counted nowhere: entries the same at their turn as at EnqueueRequest, a table that + /// cannot be read at its turn (the EnqueueRequest copy used, as before), an array on the + /// enqueuing thread's stack (its copy is all there is). + #[test] + fn the_silent_cases_of_a_page_table_are_counted() { + use crate::hle::kernelx::PHYS_PAGE_SIZE; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_DECOMMIT, PAGE_READWRITE}; + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0")]) { + return; + } + unsafe { + let m = mapped_pages(2, 0x55); + let data: Vec = (0..0x180u32).map(|i| (i * 5 + 3) as u8).collect(); + let same = Box::new([m.pages[0]]); + // a table in a reservation of its own: decommitted after EnqueueRequest, never committed + // by another test (the address stays reserved until the end) + let own = reserve(); + assert!(!VirtualAlloc(own as *const c_void, 0x1000, MEM_COMMIT, PAGE_READWRITE).is_null()); + *(own as *mut usize) = m.pages[1]; + let on_stack = [m.pages[1]]; + let t = test_queue(16, 1); + let request = |table: u64, k: usize| request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table, (0x100 * (k + 1)) as u16, 0x80, data.as_ptr().add(0x80 * k) as u64, 0, 0x80, 0, 0); + (t.enqueue)(t.q, request(same.as_ptr() as u64, 0).as_ptr()); + (t.enqueue)(t.q, request(own as u64, 1).as_ptr()); + VirtualFree(own as *mut c_void, 0x1000, MEM_DECOMMIT); + (t.enqueue)(t.q, request(on_stack.as_ptr() as u64, 2).as_ptr()); + (t.status)(t.q, t.s, 0); + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK); + let q = queue(t.q); + assert_eq!((q.counts.get(UNCHANGED), q.counts.get(UNREAD), q.counts.get(ON_STACK)), (1, 1, 1), "unchanged, not read, on the stack"); + assert_eq!(std::slice::from_raw_parts(m.at.add(0x100), 0x80), &data[..0x80]); + assert_eq!(std::slice::from_raw_parts(m.at.add(PHYS_PAGE_SIZE + 0x200), 0x80), &data[0x80..0x100], "the copy's page (as before)"); + assert_eq!(std::slice::from_raw_parts(m.at.add(PHYS_PAGE_SIZE + 0x300), 0x80), &data[0x100..]); + drop(t); + unreserve(own); + } + } + + /// A hold past `XCL_DSTORAGE_HOLD_WARN_MS` is warned of once (with clocks of the test's own), + /// with its queue, its entries and its first request that waits for the Submit; the queue's + /// next hold is watched again. A look at one queue passes over another queue's hold, even one + /// that began first. + #[test] + fn a_long_hold_is_warned_of_once() { + assert!(!past_warning(0, 1999, 2000, false)); + assert!(past_warning(0, 2000, 2000, false), "at the warning's ms"); + assert!(!past_warning(0, 5000, 2000, true), "once"); + assert!(!past_warning(0, 5000, 0, false), "0: never"); + assert!(!past_warning(100, 50, 2000, false), "a clock before the hold"); + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0"), (hold_warn_ms() == 0, "XCL_DSTORAGE_HOLD_WARN_MS=0")]) { + return; + } + unsafe { + let warn = hold_warn_ms(); + let m = mapped_pages(1, 0x66); + let data = vec![0x6Bu8; 0x80 * 16]; + let table = Box::new([m.pages[0]; 16]); + let t = test_queue(16, 2); + let q = queue(t.q); + let request = |k: usize| request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr().add(k) as u64, (0x100 * k) as u16, 0x80, data.as_ptr().add(0x80 * k) as u64, 0, 0x80, 0, 0); + // (a busy `pending` is passed over: looked at again) + let look = |now: u64| { + for _ in 0..50 { + let found = holds_past(now, Some(q.id)); + if !found.is_empty() { + return found; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + Vec::new() + }; + // (another queue's hold, begun before this one's: never this queue's look's) + let other = test_queue(16, 1); + for k in 0..8 { + (other.enqueue)(other.q, request(k).as_ptr()); + } + assert!(queue(other.q).holding.load(Ordering::Relaxed), "the other queue holds"); + for k in 0..8 { + (t.enqueue)(t.q, request(k).as_ptr()); + } + (t.status)(t.q, t.s, 0); + let hold = hold_now(q).0.expect("held at the 8th"); + assert_eq!(hold.held, 8); + assert!(holds_past(hold.since_ms + warn - 1, Some(q.id)).is_empty(), "not yet"); + let found = look(hold.since_ms + warn); + assert_eq!(found.len(), 1, "past the warning"); + assert_eq!((found[0].queue, found[0].entries), (q.id, 9)); + assert_eq!(found[0].first.as_ref().map(|f| f.0.destination), Some(table.as_ptr() as u64), "its first request"); + assert!(holds_past(hold.since_ms + 10 * warn, Some(q.id)).is_empty(), "once a hold"); + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK); + assert_eq!(hold_now(q).1.map(|e| e.cause), Some(HoldCause::Submit)); + // the queue's next hold + for k in 8..16 { + (t.enqueue)(t.q, request(k).as_ptr()); + } + (t.status)(t.q, t.s, 1); + let since = hold_now(q).0.expect("held again").since_ms; + assert_eq!(look(since + warn).len(), 1, "the next hold is watched again"); + (t.submit)(t.q); + assert_eq!(t.wait(1), S_OK); + (other.status)(other.q, other.s, 0); + (other.submit)(other.q); + assert_eq!(other.wait(0), S_OK); + } + } + + /// A queue closed while it holds a batch: the hold ends by the Close with what it held when it + /// began (not the plain request that went at its start) and what it dropped; the flag stays, so + /// Query on the closed queue answers as in 0022; the probe line shows no hold. + #[test] + fn closing_a_queue_that_holds_a_batch_ends_the_hold() { + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0")]) { + return; + } + unsafe { + let m = mapped_pages(1, 0x66); + let dst = vec![0u8; 0x80]; + let data: Vec = (0..0x400u32).map(|i| (i * 7 + 5) as u8).collect(); + let table = Box::new([m.pages[0]; 7]); + let t = test_queue(16, 1); + let q = queue(t.q); + // a plain request, then 7 into the title's pages: held at the 8th entry, the plain one sent + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT, dst.as_ptr() as u64, 0, 0x80, data.as_ptr() as u64, 0, 0x80, 0, 0).as_ptr()); + for k in 0..7usize { + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr().add(k) as u64, (0x100 * k) as u16, 0x80, data.as_ptr().add(0x80 * k) as u64, 0, 0x80, 0, 0).as_ptr()); + } + (t.status)(t.q, t.s, 0); + assert_eq!(hold_now(q).0.map(|h| h.held), Some(7), "the plain request went at the hold's start"); + // (the worker writes `dst`: read with volatile loads) + let ran = || (0..0x80).all(|i| std::ptr::read_volatile(dst.as_ptr().add(i)) == data[i]); + let t0 = std::time::Instant::now(); + while !ran() && t0.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert!(ran(), "the plain request ran"); + queue_close(t.q); + let e = hold_now(q).1.expect("the Close ended the hold"); + assert_eq!((e.cause, e.held, e.sent), (HoldCause::Close, 7, 8)); + assert_eq!((t.hresult)(t.s, 0), E_QUEUE_CLOSED); + assert_eq!(t.info(), (16, 15), "Query on a closed queue as in 0022: the flag stays"); + let part = probe_part(q.id); + assert!(part.starts_with(&format!("q{}(memory, cap 16, closed): pending 0, in flight 0, run 1, most pending 8", q.id)) && !part.contains(", holding"), "{part}"); + assert!(std::slice::from_raw_parts(m.at, crate::hle::kernelx::PHYS_PAGE_SIZE).iter().all(|&x| x == 0x66), "the held requests never ran"); + } + } + + /// A queue released while it holds a batch, without a Close: its last reference's `Drop` ends + /// the hold (the only path to a Release end). + #[test] + fn releasing_a_queue_that_holds_a_batch_ends_the_hold() { + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0")]) { + return; + } + unsafe { + let m = mapped_pages(1, 0x77); + let data = vec![0x7Cu8; 0x80 * 8]; + let table = Box::new([m.pages[0]; 8]); + let t = test_queue(16, 1); + for k in 0..8usize { + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr().add(k) as u64, (0x100 * k) as u16, 0x80, data.as_ptr().add(0x80 * k) as u64, 0, 0x80, 0, 0).as_ptr()); + } + assert!(queue(t.q).holding.load(Ordering::Relaxed) && queue(t.q).worker.lock().unwrap().is_none(), "held, nothing sent"); + let ends = || HOLD_ENDS[HoldCause::Release as usize].load(Ordering::Relaxed); + let before = ends(); + t.release_without_close(); + // (another test's probe line may hold the last reference for a moment) + let t0 = std::time::Instant::now(); + while ends() <= before && t0.elapsed().as_secs() < 1 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(ends() > before, "the last Release ended the hold"); + } + } + + /// The title's Submits by the entries they sent, in buckets of powers of two – per queue, and + /// as the probe line says them. + #[test] + fn entries_per_submit_are_counted_in_powers_of_two() { + assert_eq!([0, 1, 2, 3, 4, 7, 8, 2047, 2048, 4095, 4096, 100_000].map(submit_bucket), [0, 1, 2, 2, 3, 3, 4, 11, 12, 12, 13, 13]); + let mut c = [0u64; SUBMIT_BUCKETS]; + c[1] = 3; + c[12] = 1; + assert_eq!(submit_histogram(&c), "1: 3, 2048-4095: 1"); + assert_eq!(submit_histogram(&[0; SUBMIT_BUCKETS]), "none"); + unsafe { + let t = test_queue(8, 2); + let q = queue(t.q); + (t.status)(t.q, t.s, 0); + (t.status)(t.q, t.s, 1); + (t.submit)(t.q); + assert_eq!(q.submits[2].load(Ordering::Relaxed), 1, "a Submit of 2 entries"); + (t.submit)(t.q); + assert_eq!(q.submits[0].load(Ordering::Relaxed), 1, "a Submit with nothing pending"); + assert_eq!(t.wait(1), S_OK); + } + } + + /// A queue's worker carries the queue's number in its name (the thread dump says which queue a + /// thread serves). + #[test] + fn a_queue_worker_is_named_after_its_queue() { + unsafe { + let t = test_queue(8, 1); + (t.status)(t.q, t.s, 0); + (t.submit)(t.q); + assert_eq!(t.wait(0), S_OK); + let q = queue(t.q); + let tid = q.worker_tid.load(Ordering::Relaxed); + assert_ne!(tid, 0, "the worker ran"); + let name = crate::eh::thread_name_of(tid); + if name.is_empty() { + crate::gpu::recomp::runner::skip_config("no thread descriptions"); + return; + } + assert_eq!(name, format!("xcl-dstorage-q{}", q.id)); + } + } + + /// The probe line keeps what the session tools parse: the prefix through `full queues sent N; ` + /// (`run64_events.sh`'s sed, `parse_probes.py`'s `rx_head`: 10 numbers), the new groups in + /// their order before the first queue's part, and each part's start (`rx_q`). + #[test] + fn the_probe_line_keeps_what_the_tools_parse() { + unsafe { + let t = test_queue(8, 1); + let id = queue(t.q).id; + let line = probe_line(); + let head = [ + "DirectStorage: ", + " requests, ", + " MB, ", + " failed; title page tables at their turn: ", + " entries filled, ", + " moved, ", + " cleared since EnqueueRequest, 0 entries filled while waiting ", + " / left 0 ", + "; batches held for Submit ", + ", full queues sent ", + "; ", + ]; + assert_eq!(numbers_between(&line, &head).map(|n| n.len()), Some(10), "{line}"); + let marks = [" entries unchanged, ", "; old pages of moved and cleared entries: ", "; holds ended: Submit ", "; cancels ", "; entries per Submit: ", "; write record: "]; + let at: Vec = marks.iter().map(|m| line.find(m).unwrap_or_else(|| panic!("{m:?} in {line}"))).collect(); + assert!(at.windows(2).all(|w| w[0] < w[1]), "the groups in order: {line}"); + let first_part = line + .match_indices("; q") + .map(|(i, _)| i) + .find(|&i| { + let rest = &line.as_bytes()[i + 3..]; + let digits = rest.iter().take_while(|b| b.is_ascii_digit()).count(); + digits > 0 && rest.get(digits) == Some(&b'(') + }) + .unwrap_or_else(|| panic!("no queue part in {line}")); + assert!(first_part > at[at.len() - 1], "the queues' parts after the groups: {line}"); + assert_eq!(probe_part(id), format!("q{id}(memory, cap 8): pending 0, in flight 0, run 0, most pending 0")); + if !old_pages() { + assert!(line.contains("not looked up (XCL_DSTORAGE_OLD_PAGES=0)"), "{line}"); + } + if hold_warn_ms() == 0 { + assert!(line.contains("long holds not watched"), "{line}"); + } + } + } + + /// A queue of GTA VI's size (4,159 slots): it holds at half full (2,079), says so once at 3/4 + /// (3,119), and the full queue's send at 4,158 ends the hold with all it held; every request + /// ran in order. + #[test] + fn a_queue_of_gtas_size_holds_at_half_and_sends_when_full() { + const CAPACITY: usize = 4159; + const N: usize = CAPACITY - 1; + if skips(&[(no_uma(), "no unified memory"), (!late_pages(), "XCL_DSTORAGE_LATE_PAGES=0")]) { + return; + } + unsafe { + let m = mapped_pages(1, 0x5C); + let table = vec![m.pages[0]; N].into_boxed_slice(); + // request k's 16 bytes: k and !k + let data: Vec = (0..N as u64).flat_map(|k| [k.to_le_bytes(), (!k).to_le_bytes()].concat()).collect(); + let t = test_queue(CAPACITY as u16, 1); + let q = queue(t.q); + for k in 0..N { + (t.enqueue)(t.q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, table.as_ptr().add(k) as u64, ((k % 4096) * 16) as u16, 16, data.as_ptr().add(16 * k) as u64, 0, 16, 0, 0).as_ptr()); + let (held, near) = { + let p = q.pending.lock().unwrap(); + (p.hold.map(|h| h.held), p.hold.map(|h| h.near_full)) + }; + match k + 1 { + 2078 => assert_eq!(held, None, "no hold before half full"), + 2079 => assert_eq!(held, Some(2079), "held at half full"), + 3118 => assert_eq!(near, Some(false)), + 3119 => assert_eq!(near, Some(true), "3/4 of the queue"), + _ => {} + } + } + let (end, most) = { + let p = q.pending.lock().unwrap(); + (p.last_end, p.most) + }; + let e = end.expect("the full queue's send ended the hold"); + assert_eq!((e.cause, e.held, e.sent), (HoldCause::FullQueue, 2079, 4158)); + assert_eq!(most, 4158); + (t.status)(t.q, t.s, 0); + (t.submit)(t.q); + // (4,158 requests on one worker: more than `wait`'s 5 s under load is allowed for) + let t0 = std::time::Instant::now(); + while !(t.complete)(t.s, 0) && t0.elapsed().as_secs() < 60 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(t.wait(0), S_OK); + assert_eq!(std::slice::from_raw_parts(m.at, 16), &data[16 * 4096..16 * 4097], "offset 0: request 4096's bytes, the last there"); + assert_eq!(std::slice::from_raw_parts(m.at.add(4095 * 16), 16), &data[16 * 4095..16 * 4096], "request 4095's"); + } + } + + /// A page table naming no page at its request's turn is looked at again for a few ms: an + /// entry the title fills by then is used; one it leaves 0 stays 0, and after a few such + /// requests in a row the looks stop for a second. + #[test] + fn a_page_table_entry_still_0_at_its_turn_is_looked_at_again() { + unsafe { + ZERO_QUIET_UNTIL_MS.store(0, Ordering::Relaxed); + ZERO_FRUITLESS.store(0, Ordering::Relaxed); + let r = Request::default(); + // filled by the time of the first look + let filled_table = Box::new([0x1234usize, 0x5678]); + let mut now = vec![0x1234usize, 0]; + let filled = LATE[3].load(Ordering::Relaxed); + look_again_while_zero(&mut now, filled_table.as_ptr() as u64, 16, &r, "test"); + assert_eq!(now, [0x1234, 0x5678]); + assert!(LATE[3].load(Ordering::Relaxed) > filled); + // left 0: the looks end with the entry 0 + let empty = Box::new([0usize; 2]); + for _ in 0..ZERO_IDLE { + let mut now = vec![0usize; 2]; + let left = LATE[4].load(Ordering::Relaxed); + look_again_while_zero(&mut now, empty.as_ptr() as u64, 16, &r, "test"); + assert_eq!(now, [0, 0]); + assert!(LATE[4].load(Ordering::Relaxed) > left); + } + // … and after ZERO_IDLE such requests none looks for a second: a filled table is not + // read again + let mut now = vec![0usize; 2]; + look_again_while_zero(&mut now, filled_table.as_ptr() as u64, 16, &r, "test"); + assert_eq!(now, [0, 0], "no look while the looks rest"); + std::thread::sleep(std::time::Duration::from_millis(1100)); + look_again_while_zero(&mut now, filled_table.as_ptr() as u64, 16, &r, "test"); + assert_eq!(now, [0x1234, 0x5678], "looks again a second later"); + } + } + #[test] fn physical_page_destinations_and_sources() { use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; @@ -2775,56 +5427,13 @@ mod tests { } } + /// `XCL_DSTORAGE_AUTO_SUBMIT_DISABLED`: the queue option is honoured unless the switch is "0", + /// which lets such a queue submit by itself at half full as before upstream 5bff7bd (for a run + /// that compares the two). #[test] - fn full_manual_queue_waits_for_submit_cancel_or_close() { - use std::time::Duration; - - enum Wake { Submit, Cancel, Close } - for wake in [Wake::Submit, Wake::Cancel, Wake::Close] { - unsafe { - let mut desc = [0u8; 0x20]; - desc[0] = 1; // memory source - desc[8] = 2; // capacity - desc[10] = 2; // priority - desc[0x18] = QUEUE_OPT_AUTO_SUBMIT_DISABLED as u8; - let mut q = std::ptr::null_mut(); - let mut s = std::ptr::null_mut(); - assert_eq!(factory_create_queue1(std::ptr::null_mut(), desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); - assert_eq!(factory_create_status_array(std::ptr::null_mut(), 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); - let mut destination = [0u8; 1]; - let req = request(SOURCE_MEMORY_BIT, destination.as_mut_ptr() as u64, 1, b"x".as_ptr() as u64, 0, 1); - queue_enqueue_request(q, req.as_ptr()); - queue_enqueue_status(q, s, 0); - - let (ready, started) = mpsc::channel(); - let (done, finished) = mpsc::channel(); - let (qp, sp) = (q as usize, s as usize); - let enqueue_status = matches!(wake, Wake::Cancel); - let producer = std::thread::spawn(move || { - ready.send(()).unwrap(); - if enqueue_status { - queue_enqueue_status(qp as *mut c_void, sp as *mut c_void, 1); - } else { - queue_enqueue_request(qp as *mut c_void, req.as_ptr()); - } - done.send(()).unwrap(); - }); - started.recv_timeout(Duration::from_secs(5)).unwrap(); - assert_eq!(finished.recv_timeout(Duration::from_millis(150)), Err(mpsc::RecvTimeoutError::Timeout), "an enqueue into a full manual queue must wait"); - match wake { - Wake::Submit => queue_submit(q), - Wake::Cancel => queue_cancel(q, 0, 0), - Wake::Close => queue_close(q), - } - finished.recv_timeout(Duration::from_secs(5)).expect("the waiting producer must wake"); - producer.join().unwrap(); - let pending = queue(q).pending.lock().unwrap().entries.len(); - assert_eq!(pending, match wake { Wake::Submit => 1, Wake::Cancel => 2, Wake::Close => 0 }); - queue_close(q); - queue_release(q); - status_release(s); - } - } + fn auto_submit_disabled_is_honoured_unless_switched_off() { + assert!(auto_submit_disabled_switch(None) && auto_submit_disabled_switch(Some("1")) && auto_submit_disabled_switch(Some(""))); + assert!(!auto_submit_disabled_switch(Some("0")) && !auto_submit_disabled_switch(Some(" 0\n"))); } #[test] diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 413e0c2..f1111ff 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -74,6 +74,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { SetThreadpoolAffinityMask, SetThreadAffinityMask, SetThreadGroupAffinity, + SetThreadPriority, QueryProcessorSchedulingStatistics, GetConsoleType, OutputDebugStringA, @@ -226,6 +227,34 @@ pub mod mirrors { /// pages – GPU-visible on the console like all title memory. const MEM_64K_PAGES: u32 = 0x2040_0000; +/// `XCL_SPARSE_64K_MAX_MB` (per title; unset: no limit): a reservation of 64 KiB pages made with no +/// commit, and a block of physical pages (`AllocateTitlePhysicalPages`), of more than this many MB +/// are plain memory, outside the sparse windows. GTA VI on Series S reserves its physical-page +/// pool so (one 3.9 GB reservation; its pages' homes one block): in the windows each page of it got +/// a 64 KiB tile of video memory the GPU never reads there – its streamed textures are kept in step +/// from the CPU view – about 4 GB of Metal private memory, and a tile mapping and a clear for each +/// page that moved while it loaded. On Series X the same pool lies outside the windows already. +fn sparse_64k_max() -> usize { + #[cfg(test)] + if let Some(m) = TEST_SPARSE_64K_MAX.with(|c| c.get()) { + return m; + } + static MAX: std::sync::OnceLock = std::sync::OnceLock::new(); + *MAX.get_or_init(|| { + let max = std::env::var("XCL_SPARSE_64K_MAX_MB").ok().and_then(|v| v.trim().parse::().ok()).map_or(usize::MAX, |mb| mb.saturating_mul(1 << 20)); + if max != usize::MAX { + crate::xlog_info!("kernelx: reservations of 64 KiB pages and blocks of physical pages over {} MB are plain memory, outside the sparse windows (XCL_SPARSE_64K_MAX_MB)", max >> 20); + } + max + }) +} + +#[cfg(test)] +thread_local! { + /// `sparse_64k_max` for this test thread + static TEST_SPARSE_64K_MAX: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + /// Commit `[a, a + n)` of a sparse window (the title's reservations there) and give it video /// memory (`d3d12x::sparse`). unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { @@ -248,8 +277,13 @@ 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 { + // the title's own reservations of 64 KiB pages: in a sparse window, so the GPU sees them – + // but one made with no commit over `sparse_64k_max`, which is plain memory below + let over = t & 0x1000 == 0 && size > sparse_64k_max(); + if over && addr.is_null() && t & MEM_64K_PAGES == MEM_64K_PAGES { + crate::xlog_info!("kernelx: a reservation of {size:#x} bytes of 64 KiB pages is plain memory, outside the sparse windows (XCL_SPARSE_64K_MAX_MB)"); + } + if addr.is_null() && t & 0x2000 != 0 && t & MEM_64K_PAGES == MEM_64K_PAGES && !over { if let Some(q) = uma.and_then(|u| u.sparse_reserve(size)) { if t & 0x1000 != 0 && commit_sparse(q, size, p).is_null() { uma.map(|u| u.sparse_release(q)); @@ -303,6 +337,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size); GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); } + note_plain_gpu(PlainGpu { base: q as usize, bytes: size, by: "VirtualAlloc, a graphics reservation", flags: u64::from(t), protect: p }); return q; } } @@ -341,6 +376,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: let q = if watched { reserve_watched(size, t, p) } else { mem::VirtualAlloc(std::ptr::null(), size, sanitize_alloc_type(t) & !MEM_WRITE_WATCH, sanitize_protect(p)) }; if !q.is_null() { mirrors::reserved(q as usize, size, t, p); + note_plain_gpu(PlainGpu { base: q as usize, bytes: size, by: "VirtualAlloc, GPU-visible", flags: u64::from(t), protect: p }); trace_mem(if watched { "VirtualAlloc (GPU-visible, write-watched)" } else { "VirtualAlloc (GPU-visible, plain)" }, addr as usize, size, t as u64, p, q as usize); return q; } @@ -369,6 +405,80 @@ unsafe fn reserve_watched(size: usize, t: u32, p: u32) -> *mut c_void { q } +/// GPU-visible title memory outside unified memory's windows – the plain-memory fallbacks of +/// VirtualAlloc (`gpu_visible_fallback`, a graphics reservation the windows had no room for) and +/// of XMem's graphics memory: base → what it is. What the census of placed buffers outside unified +/// memory groups them by (`d3d12x::outside`), and what XCL_SKIP_CS's root views say of memory there +/// (`d3d12x::skip_roots`); kept while the census is on (`XCL_ACTIVITY`), each entry gone with its +/// MEM_RELEASE. +static PLAIN_GPU: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +/// its entries (a release looks at the lock only when there are some) +static PLAIN_GPU_N: AtomicUsize = AtomicUsize::new(0); + +/// GPU-visible title memory outside the windows, as the title asked for it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PlainGpu { + pub(crate) base: usize, + pub(crate) bytes: usize, + /// the call that made it + pub(crate) by: &'static str, + /// the title's allocation type (VirtualAlloc: MEM_GRAPHICS, 64 KiB or large pages …) or its + /// XALLOC attributes (XMemAlloc) + pub(crate) flags: u64, + /// the title's protection (VirtualAlloc: a PAGE_GRAPHICS_* one …; XMemAlloc: the + /// PAGE_READWRITE XCL gave it) + pub(crate) protect: u32, +} + +/// `p` is GPU-visible title memory outside the windows (the title's last error as it was: this +/// runs inside its VirtualAlloc). +fn note_plain_gpu(p: PlainGpu) { + keep_last_error(|| { + if crate::hle::d3d12x::outside::on() { + let mut g = PLAIN_GPU.lock().unwrap_or_else(|e| e.into_inner()); + g.insert(p.base, p); + PLAIN_GPU_N.store(g.len(), Ordering::Release); + } + }) +} + +fn forget_plain_gpu(base: usize) { + if PLAIN_GPU_N.load(Ordering::Acquire) == 0 { + return; + } + let mut g = PLAIN_GPU.lock().unwrap_or_else(|e| e.into_inner()); + g.remove(&base); + PLAIN_GPU_N.store(g.len(), Ordering::Release); +} + +/// The GPU-visible title memory outside the windows `va` lies in: (base, bytes). Blocks on a leaf +/// lock – not for a crash's report (there: `eh::try_lock_within`). +pub(crate) fn plain_gpu_at(va: usize) -> Option<(usize, usize)> { + plain_gpu_info(va).map(|p| (p.base, p.bytes)) +} + +/// `plain_gpu_at` with what the title asked for (the call, its flags, its protection). +pub(crate) fn plain_gpu_info(va: usize) -> Option { + if PLAIN_GPU_N.load(Ordering::Acquire) == 0 { + return None; + } + let g = PLAIN_GPU.lock().unwrap_or_else(|e| e.into_inner()); + let (&b, &p) = g.range(..=va).next_back()?; + (va - b < p.bytes).then_some(p) +} + +#[cfg(test)] +pub(crate) fn note_plain_gpu_for_test(base: usize, size: usize) { + let mut g = PLAIN_GPU.lock().unwrap_or_else(|e| e.into_inner()); + g.insert(base, PlainGpu { base, bytes: size, by: "a test", flags: 0, protect: 0 }); + PLAIN_GPU_N.store(g.len(), Ordering::Release); +} + +#[cfg(test)] +pub(crate) fn forget_plain_gpu_for_test(base: usize) { + forget_plain_gpu(base) +} + /// Whether GPU-visible title memory that reaches the plain-memory fallback is write-watched: /// Always on native Windows, opt-in with `XCL_WATCHED_FALLBACK=1` on a Mac. The title's /// heaps and its 24 GB of 64 KiB pages are in that memory, written with AVX2 masked stores, @@ -492,6 +602,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 if watched || crate::util::mac_host() { mirrors::released(addr as usize); } + forget_plain_gpu(addr as usize); } ok } @@ -505,7 +616,11 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si return VirtualFree(addr, size, t); } } - mem::VirtualFreeEx(proc_, addr, size, t) + let ok = mem::VirtualFreeEx(proc_, addr, size, t); + if ok != 0 && t & 0x8000 != 0 && proc_ == thr::GetCurrentProcess() { + forget_plain_gpu(addr as usize); + } + ok } pub unsafe extern "system" fn VirtualAllocEx(proc_: HANDLE, addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { @@ -611,7 +726,11 @@ pub unsafe extern "system" fn XMemAllocDefault(size: usize, attrs: u64) -> *mut 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() { + note_plain_gpu(PlainGpu { base: q as usize, bytes: rounded, by: "XMemAlloc, graphics memory", flags: attrs, protect: mem::PAGE_READWRITE }); + } + q } pub unsafe extern "system" fn XMemFreeDefault(p: *mut c_void, attrs: u64) { @@ -621,7 +740,9 @@ pub unsafe extern "system" fn XMemFreeDefault(p: *mut c_void, attrs: u64) { if XAllocAttrs::decode(attrs).memory_type == 0 { aligned_heap_free(p); } else if !crate::hle::d3d12x::sparse::free(p as usize) && !crate::gpu::uma::get().is_some_and(|u| u.free(p as usize)) { - mem::VirtualFree(p, 0, mem::MEM_RELEASE); + if mem::VirtualFree(p, 0, mem::MEM_RELEASE) != 0 { + forget_plain_gpu(p as usize); + } } } @@ -883,6 +1004,77 @@ struct Away { } static AWAY: std::sync::Mutex> = std::sync::Mutex::new(None); +/// Local diagnostic `XCL_TRACE_PAGES=a,b,…` (hex): every mapping, unmapping, move, allocation and +/// free of these 64 KiB pages, and the DirectStorage writes and GPU-view mappings that reach +/// them, is logged with what the page holds – an entry above 4 GiB is an address, any other a +/// physical page number. Pages the GPU view of a traced address shows are traced too. +static TRACE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static TRACED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +fn trace_init() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let l: Vec = std::env::var("XCL_TRACE_PAGES").ok().map(|v| v.split(',').filter_map(|s| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok()).collect()).unwrap_or_default(); + if !l.is_empty() { + crate::xlog_info!("[trace] pages traced: {l:x?}"); + *TRACED.lock().unwrap() = l; + TRACE_ON.store(true, Ordering::Release); + } + }); +} + +/// Whether `XCL_TRACE_PAGES` is on (every trace hook returns at once when it is not). +pub fn tracing() -> bool { + trace_init(); + TRACE_ON.load(Ordering::Acquire) +} + +/// Whether `x` (an address above 4 GiB, or a physical page number) is traced. +pub fn traced(x: usize) -> bool { + trace_init(); + if !TRACE_ON.load(Ordering::Acquire) || x == 0 { + return false; + } + let va = x > 0xFFFF_FFFF; + TRACED.lock().unwrap().iter().any(|&t| if va { t > 0xFFFF_FFFF && t & !(PHYS_PAGE - 1) == x & !(PHYS_PAGE - 1) } else { t <= 0xFFFF_FFFF && t == x }) +} + +/// Whether `[va, va + len)` touches a traced address's 64 KiB page. +pub fn traced_range(va: usize, len: usize) -> bool { + trace_init(); + if !TRACE_ON.load(Ordering::Acquire) || va == 0 { + return false; + } + let end = va.saturating_add(len.max(1)); + TRACED.lock().unwrap().iter().any(|&t| t > 0xFFFF_FFFF && t < end && va < (t & !(PHYS_PAGE - 1)) + PHYS_PAGE) +} + +/// (diagnostic) The return addresses above the caller, as `module+offset`. +pub fn callers(skip: u32) -> String { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + let mut frames = [std::ptr::null_mut::(); 10]; + let n = unsafe { RtlCaptureStackBackTrace(skip, frames.len() as u32, frames.as_mut_ptr(), std::ptr::null_mut()) }; + frames[..n as usize].iter().map(|&f| crate::modules::describe_address(f as usize)).collect::>().join(" < ") +} + +/// `x` traced from now on (while tracing is on). +pub fn trace_add(x: usize) { + if x != 0 && TRACE_ON.load(Ordering::Acquire) && !traced(x) { + TRACED.lock().unwrap().push(if x > 0xFFFF_FFFF { x & !(PHYS_PAGE - 1) } else { x }); + crate::xlog_info!("[trace] now also tracing {x:#x}"); + } +} + +/// Non-zero bytes of the 64 KiB page at `a`, if it is committed (and where the first is). +pub fn page_nonzero(a: usize) -> Option<(usize, Option)> { + let a = a & !(PHYS_PAGE - 1); + if !committed_page(a) { + return None; + } + let b = unsafe { std::slice::from_raw_parts(a as *const u8, PHYS_PAGE) }; + Some((b.iter().filter(|&&x| x != 0).count(), b.iter().position(|&x| x != 0))) +} + /// The physical page (its number) the title mapped at the 64 KiB page of `view`: the one that /// is there now, or the last one that was there before the title mapped it somewhere else /// (on the console it would still show there). @@ -916,6 +1108,130 @@ pub fn physical_page_at(va: usize) -> bool { AWAY.lock().unwrap().as_ref().is_some_and(|a| a.at.contains_key(&(va & !(PHYS_PAGE - 1)))) } +/// What has its data at a 64 KiB page of the address space: a physical page the title mapped +/// there, a page at its home there – or the home of a page mapped elsewhere now (what is there is +/// not that page's data). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PageHere { + Mapped(usize), + Home(usize), + HomeOf(usize, usize), +} + +/// `PageHere` of the 64 KiB page at `a` (aligned), from the page map and the blocks (their locks +/// held). The blocks are not kept by home: the one whose homes hold `a` is looked for in all of +/// them (GTA VI's pool is one; the allocations before it are others). +fn page_here(away: Option<&Away>, blocks: &std::collections::BTreeMap, a: usize) -> Option { + if let Some(&p) = away.and_then(|w| w.at.get(&a)) { + return Some(PageHere::Mapped(p)); + } + let page = blocks.iter().find_map(|(&first, &(count, live, home))| { + let bytes = count.checked_mul(PHYS_PAGE)?; + (live > 0 && a >= home && a - home < bytes).then(|| page_number(first + (a - home) / PHYS_PAGE)) + })?; + Some(match away.and_then(|w| w.page.get(&page)) { + Some(&at) => PageHere::HomeOf(page, at), + None => PageHere::Home(page), + }) +} + +/// What has its data at each 64 KiB page from `first` (aligned), `count` of them. The kernel's +/// locks are waited for, the page map's first and then the blocks' (`map_pages`' order: it calls +/// `page_home` with `AWAY` held); the blocks only for pages with no page mapped there. Not in a +/// crash's report. +pub fn pages_here(first: usize, count: usize) -> Vec> { + let g = AWAY.lock().unwrap_or_else(|e| e.into_inner()); + let mut out: Vec> = (0..count).map(|i| g.as_ref().and_then(|w| w.at.get(&(first + i * PHYS_PAGE))).map(|&p| PageHere::Mapped(p))).collect(); + if out.iter().any(Option::is_none) { + let blocks = PHYS_BLOCKS.lock().unwrap_or_else(|e| e.into_inner()); + for (i, o) in out.iter_mut().enumerate() { + if o.is_none() { + *o = page_here(g.as_ref(), &blocks, first + i * PHYS_PAGE); + } + } + } + out +} + +/// What has its data at `addr`'s 64 KiB page (`pages_here`). +pub fn page_of_address(addr: usize) -> Option { + pages_here(addr & !(PHYS_PAGE - 1), 1).pop().flatten() +} + +/// `page_of_address` for a crash's report: the kernel's locks only tried while `left_ms` lasts +/// (`eh::try_lock_within`). Err: one stayed busy. +pub(crate) fn page_of_address_within(addr: usize, left_ms: &AtomicU32) -> Result, ()> { + let a = addr & !(PHYS_PAGE - 1); + let g = crate::eh::try_lock_within(&AWAY, left_ms).ok_or(())?; + if let Some(&p) = g.as_ref().and_then(|w| w.at.get(&a)) { + return Ok(Some(PageHere::Mapped(p))); + } + let blocks = crate::eh::try_lock_within(&PHYS_BLOCKS, left_ms).ok_or(())?; + Ok(page_here(g.as_ref(), &blocks, a)) +} + +/// Where physical page `page`'s data is (the page a DirectStorage entry named before it changed). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PagePlace { + /// the title mapped it at this address (away from its home) + Mapped(usize), + /// at its home, which holds memory: it was used there + Home(usize), + /// at its home, which holds none (never used, or given back): zeros + Unused, + /// not a page of a live allocation + NotAPage, +} + +/// `PagePlace` of each of `pages`: the page map's lock waited for (`describe_physical_page` only +/// tries it) – one look for all of them, let go – then their homes (the blocks' lock, a +/// working-set or VirtualQuery look each). +pub fn page_places(pages: &[usize]) -> Vec { + let away: Vec> = { + let g = AWAY.lock().unwrap_or_else(|e| e.into_inner()); + pages.iter().map(|p| g.as_ref().and_then(|a| a.page.get(p).copied())).collect() + }; + pages + .iter() + .zip(away) + .map(|(&p, at)| match (page_home(p), at) { + (None, _) => PagePlace::NotAPage, + (Some(_), Some(at)) => PagePlace::Mapped(at), + (Some(h), None) if committed_page(h) => PagePlace::Home(h), + (Some(_), None) => PagePlace::Unused, + }) + .collect() +} + +/// (tests) The page map held by another thread until this is dropped, or 2 s at most: what a +/// worker or a crash's report meets while the title maps pages. The helper never panics while it +/// holds the lock (a poisoned page map would fail every later test). +#[cfg(test)] +pub(crate) struct PageMapHold(Option>, Option>); + +#[cfg(test)] +pub(crate) fn hold_page_map() -> PageMapHold { + let (held, is_held) = std::sync::mpsc::channel(); + let (go, gone) = std::sync::mpsc::channel::<()>(); + let t = std::thread::spawn(move || { + let _g = AWAY.lock().unwrap_or_else(|e| e.into_inner()); + let _ = held.send(()); + let _ = gone.recv_timeout(std::time::Duration::from_secs(2)); + }); + let _ = is_held.recv(); + PageMapHold(Some(go), Some(t)) +} + +#[cfg(test)] +impl Drop for PageMapHold { + fn drop(&mut self) { + drop(self.0.take()); // (its sender gone: the helper lets go at once) + if let Some(t) = self.1.take() { + let _ = t.join(); + } + } +} + /// Counts the calls that map or unmap physical pages in a GPU view (`mirrors`): what /// `physical_page_at` says there may have changed. static GPU_VIEW_MAP_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -1027,25 +1343,36 @@ pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) - }) } -/// Visit the writable chunks of a physical-page range. All page numbers are resolved before -/// the first write, and the addresses stay mapped until the callback has returned. -pub(super) unsafe fn write_physical_pages_with( +/// `write_physical_pages_with`, giving the address each page's bytes landed at (its home, or where +/// the title mapped it) – None: nothing written. +pub(super) unsafe fn write_physical_pages_landing( pages: &[usize], offset: usize, len: usize, mut write: impl FnMut(*mut u8, usize, usize), -) -> bool { +) -> Option> { if len == 0 { - return offset < PHYS_PAGE; + return (offset < PHYS_PAGE).then(Vec::new); } let g = AWAY.lock().unwrap(); - let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, len) else { return false }; + let addrs = resolve_physical_pages(g.as_ref(), pages, offset, len)?; let mut done = 0; let mut page_off = offset; - for addr in addrs { + for &addr in &addrs { let chunk = (PHYS_PAGE - page_off).min(len - done); write((addr + page_off) as *mut u8, done, chunk); done += chunk; page_off = 0; } - true + Some(addrs) +} + +/// Visit the writable chunks of a physical-page range. All page numbers are resolved before +/// the first write, and the addresses stay mapped until the callback has returned. +pub(super) unsafe fn write_physical_pages_with(pages: &[usize], offset: usize, len: usize, write: impl FnMut(*mut u8, usize, usize)) -> bool { + write_physical_pages_landing(pages, offset, len, write).is_some() +} + +/// `write_physical_pages`, giving where each page's bytes landed (DirectStorage's record). +pub unsafe fn write_physical_pages_at(pages: &[usize], offset: usize, src: &[u8]) -> Option> { + write_physical_pages_landing(pages, offset, src.len(), |dst, done, len| std::ptr::copy_nonoverlapping(src.as_ptr().add(done), dst, len)) } /// A page's data went from `home` to another address: a home in a sparse window is @@ -1207,6 +1534,9 @@ thread_local! { /// never used, or none mapped at `at`, leaves it as it was). unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range) -> bool { if let Some(page) = away.at.remove(&at) { + if traced(at) || traced(page) { + crate::xlog_info!("[trace] unmap page {page:#x} at {at:#x}: {:?} non-zero bytes there; its home {:x?} (lazy here: {})", page_nonzero(at), page_home(page), lazy::is_marked(at)); + } away.page.remove(&page); // never used where it was mapped: its home still holds the page (zeros) if lazy::unmark(at) { @@ -1265,6 +1595,9 @@ unsafe fn move_away(away: &mut Away, old: usize, at: usize, page: usize, in_uma: } away.at.remove(&old); away.page.remove(&page); + if traced(old) || traced(at) || traced(page) { + crate::xlog_info!("[trace] move page {page:#x} from {old:#x} to {at:#x}: {:?} non-zero bytes moved", page_nonzero(old)); + } std::ptr::copy_nonoverlapping(old as *const u8, at as *mut u8, PHYS_PAGE); if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); @@ -1312,10 +1645,20 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu // (a sparse or plain home is committed when it is used: `home_again`); without room in // unified memory plain memory (pages mapped into the title's own reservations never use // their home: a retail game's 6.1 GB of them did not fit next to its GPU heaps) - let block = u.sparse_alloc(bytes, PHYS_PAGE).map(|(p, _)| p).or_else(|| u.alloc(bytes, PHYS_PAGE).map(|p| p as usize)).or_else(|| { + // (a block over `sparse_64k_max`: plain memory whatever the room) + let over = bytes > sparse_64k_max(); + let in_uma = if over { + crate::xlog_info!("AllocateTitlePhysicalPages({n}): over XCL_SPARSE_64K_MAX_MB – their home is plain memory"); + None + } else { + u.sparse_alloc(bytes, PHYS_PAGE).map(|(p, _)| p).or_else(|| u.alloc(bytes, PHYS_PAGE).map(|p| p as usize)) + }; + let block = in_uma.or_else(|| { let p = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| crate::xlog_info!("AllocateTitlePhysicalPages({n}): no room in unified memory – their home is plain memory")); + if !over { + ONCE.call_once(|| crate::xlog_info!("AllocateTitlePhysicalPages({n}): no room in unified memory – their home is plain memory")); + } (p != 0).then_some(p) }); let Some(block) = block else { @@ -1326,6 +1669,9 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu let first = NEXT_PAGE_INDEX.fetch_add(n, Ordering::Relaxed); for i in 0..n { *arr.add(i) = page_number(first + i); + if traced(page_number(first + i)) { + crate::xlog_info!("[trace] page {:#x} allocated (page {i} of {n}, home {:#x})", page_number(first + i), block + i * PHYS_PAGE); + } } PHYS_BLOCKS.lock().unwrap().insert(first, (n, n, block)); 1 @@ -1337,11 +1683,21 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } + for i in 0..n { + let p = *arr.add(i); + if traced(p) { + crate::xlog_info!("[trace] page {p:#x} freed (mapped at {:x?})", AWAY.lock().unwrap().as_ref().and_then(|a| a.page.get(&p).copied())); + } + } // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes if let Some(away) = AWAY.lock().unwrap().as_mut() { for i in 0..n { if let Some(at) = away.page.remove(&*arr.add(i)) { away.at.remove(&at); + // (a page never used there leaves the address only reserved, unmarked: a page the + // title maps there later with its bytes would be taken for one never used there + // when it moves on or goes home, and arrive without them) + lazy::unmark(at); note_mapping_at(at); } } @@ -1437,6 +1793,20 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let (mut at_run, mut home_run) = (StateRun::default(), StateRun::default()); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; + if traced(at) || traced(p) { + let prev = away.at.get(&at).copied(); + let old = if p != 0 { away.page.get(&p).copied() } else { None }; + crate::xlog_info!( + "[trace] map page {p:#x} at {at:#x}: there was page {prev:x?} ({:?} non-zero bytes, first at); the page was at {old:x?} ({:?}), its home {:x?}", + page_nonzero(at), + old.and_then(page_nonzero), + (p != 0).then(|| page_home(p)).flatten() + ); + if p != 0 { + trace_add(p); + trace_add(at); + } + } if unmap_away(away, at, &(0..0)) { (at_run, home_run) = Default::default(); } @@ -1679,6 +2049,126 @@ pub unsafe extern "system" fn SetThreadGroupAffinity(h: HANDLE, a: *const GROUP_ thr::SetThreadGroupAffinity(h, &fit, prev) } +/// The title's SetThreadPriority, passed through as it is – the same arguments, answer and last +/// error – and noted (`note_priority`). CrossOver's wineserver maps a thread's priority onto Mach +/// QoS tiers, IDLE and LOWEST onto the background class's; cool_fox's notes found six of GTA VI's +/// threads at IDLE, its streaming pager among them, running about once in 4 s while every core +/// was busy. The log says which of the title's threads it puts where. +pub unsafe extern "system" fn SetThreadPriority(h: HANDLE, priority: i32) -> BOOL { + let ok = thr::SetThreadPriority(h, priority); + keep_last_error(|| note_priority(h, priority, ok)); + ok +} + +/// lines the title's priorities got so far (the cheap look once `PRIORITY_LINES_MAX` are out) +static PRIORITY_LINES: AtomicU32 = AtomicU32::new(0); +const PRIORITY_LINES_MAX: u32 = 64; +/// calls on a thread's handle other than GetCurrentThread()'s noted so far: each asks Wine the +/// thread's id (GetThreadId, a wineserver call) – after `PRIORITY_CALLS_MAX` such calls they are +/// not noted any more (a title that keeps setting priorities through handles, with fewer than 64 +/// lines to give, would ask on every call) +static PRIORITY_CALLS: AtomicU32 = AtomicU32::new(0); +const PRIORITY_CALLS_MAX: u32 = 4096; +/// the lines given, by thread id (`PriorityLog`) +static PRIORITIES: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// Which of the title's priority changes are logged: once per (thread, THREAD_PRIORITY_IDLE / +/// THREAD_PRIORITY_LOWEST), once per thread for any other value, `max` lines in all. +#[derive(Default)] +struct PriorityLog { + seen: std::collections::HashSet<(u32, Option)>, + lines: u32, +} + +impl PriorityLog { + fn admit(&mut self, tid: u32, priority: i32, max: u32) -> bool { + if self.lines >= max || !self.seen.insert((tid, priority_key(priority))) { + return false; + } + self.lines += 1; + true + } +} + +/// IDLE and LOWEST each count on their own (the background tiers); the other values as one. +fn priority_key(priority: i32) -> Option { + matches!(priority, thr::THREAD_PRIORITY_IDLE | thr::THREAD_PRIORITY_LOWEST).then_some(priority) +} + +fn priority_name(priority: i32) -> &'static str { + match priority { + thr::THREAD_PRIORITY_IDLE => "THREAD_PRIORITY_IDLE", + thr::THREAD_PRIORITY_LOWEST => "THREAD_PRIORITY_LOWEST", + thr::THREAD_PRIORITY_BELOW_NORMAL => "THREAD_PRIORITY_BELOW_NORMAL", + thr::THREAD_PRIORITY_NORMAL => "THREAD_PRIORITY_NORMAL", + thr::THREAD_PRIORITY_ABOVE_NORMAL => "THREAD_PRIORITY_ABOVE_NORMAL", + thr::THREAD_PRIORITY_HIGHEST => "THREAD_PRIORITY_HIGHEST", + thr::THREAD_PRIORITY_TIME_CRITICAL => "THREAD_PRIORITY_TIME_CRITICAL", + 0x1_0000 => "THREAD_MODE_BACKGROUND_BEGIN", + 0x2_0000 => "THREAD_MODE_BACKGROUND_END", + _ => "a value Windows does not name", + } +} + +/// "SetThreadPriority: thread 476 \"StreamingPager\" to THREAD_PRIORITY_IDLE (-15)" – the thread's +/// id (0: not known: its handle instead), its name if it has one, the value; a failed call says so. +fn priority_line(tid: u32, handle: usize, name: Option<&str>, priority: i32, failed: Option) -> String { + let thread = if tid != 0 { format!("thread {tid}") } else { format!("thread ? (handle {handle:#x})") }; + let name = name.map_or_else(|| "(no name)".to_string(), |n| format!("{n:?}")); + let failed = failed.map_or_else(String::new, |e| format!(" – the call failed (error {e})")); + format!("SetThreadPriority: {thread} {name} to {} ({priority}){failed}", priority_name(priority)) +} + +/// The title set thread `h` to `priority` (`ok`: its answer): logged per `PriorityLog`, by the +/// thread's id – asked first, never the handle's value: Wine hands a closed handle's value to the +/// next handle made (the lowest free one), so a later thread set through the same value would +/// look like the earlier one. The id of a thread other than the caller is a wineserver call +/// (`PRIORITY_CALLS`). No lock is held across a Wine call. +unsafe fn note_priority(h: HANDLE, priority: i32, ok: BOOL) { + if PRIORITY_LINES.load(Ordering::Relaxed) >= PRIORITY_LINES_MAX { + return; + } + let failed = (ok == 0).then(|| fnd::GetLastError()); + // (GetCurrentThread()'s pseudo handle is every thread's: the caller's own id is its) + let current = h as isize == -2; + if !current && PRIORITY_CALLS.fetch_add(1, Ordering::Relaxed) >= PRIORITY_CALLS_MAX { + return; + } + let tid = if current { thr::GetCurrentThreadId() } else { thr::GetThreadId(h) }; + { + let mut g = PRIORITIES.lock().unwrap_or_else(|e| e.into_inner()); + if !g.get_or_insert_with(Default::default).admit(tid, priority, PRIORITY_LINES_MAX) { + return; + } + PRIORITY_LINES.fetch_add(1, Ordering::Relaxed); + } + let name = thread_description(h); + let line = priority_line(tid, h as usize, name.as_deref(), priority, failed); + crate::xlog_info!("{line}"); + #[cfg(test)] + PRIORITY_LINES_SEEN.with(|l| l.borrow_mut().push(line)); +} + +/// Thread `h`'s description (SetThreadDescription, the title's SetThreadName), its first 64 +/// characters; None: none, or the handle may not ask. +unsafe fn thread_description(h: HANDLE) -> Option { + let mut p: *mut u16 = std::ptr::null_mut(); + if thr::GetThreadDescription(h, &mut p) < 0 || p.is_null() { + return None; + } + let n = (0..256).take_while(|&i| *p.add(i) != 0).count(); + let s = String::from_utf16_lossy(std::slice::from_raw_parts(p, n)); + fnd::LocalFree(p as *mut c_void); + let s: String = s.chars().take(64).collect(); + (!s.is_empty()).then_some(s) +} + +#[cfg(test)] +thread_local! { + /// (tests) the priority lines this thread logged + static PRIORITY_LINES_SEEN: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + pub unsafe extern "system" fn QueryProcessorSchedulingStatistics(out: *mut [u64; 3]) { if out.is_null() { return; @@ -1947,7 +2437,7 @@ fn module_handle_in(reg: &crate::hle::Registry, name: &str) -> usize { // minappmodelx) fall back to the HLE pseudo handle, matching LoadLibrary. // SAFETY: `wide(name)` produces a valid NUL-terminated UTF-16 string. let real = unsafe { ll::GetModuleHandleW(crate::util::wide(name).as_ptr()) as usize }; - if real != 0 { + if real != 0 || m.real_dll { return real; } } @@ -2152,6 +2642,121 @@ mod tests { .unwrap(); } + /// The title's priorities are logged once per (thread, IDLE / LOWEST) and once per thread for + /// any other value, 64 lines at most; a line names the thread, its name and the value. + #[test] + fn thread_priorities_are_logged_once_per_thread_and_kind() { + use thr::{THREAD_PRIORITY_ABOVE_NORMAL as ABOVE, THREAD_PRIORITY_HIGHEST as HIGHEST, THREAD_PRIORITY_IDLE as IDLE, THREAD_PRIORITY_LOWEST as LOWEST, THREAD_PRIORITY_NORMAL as NORMAL}; + let mut log = PriorityLog::default(); + assert!(log.admit(7, IDLE, 64)); + assert!(!log.admit(7, IDLE, 64), "the same thread at IDLE again"); + assert!(log.admit(7, LOWEST, 64), "LOWEST: a line of its own"); + assert!(log.admit(7, NORMAL, 64), "the thread's first other value"); + assert!(!log.admit(7, HIGHEST, 64), "any other value: once per thread"); + assert!(!log.admit(7, LOWEST, 64)); + assert!(log.admit(8, HIGHEST, 64), "another thread"); + assert!(!log.admit(8, ABOVE, 64)); + assert!(log.admit(8, IDLE, 64)); + let mut log = PriorityLog::default(); + assert_eq!((0..100u32).filter(|&t| log.admit(t, IDLE, PRIORITY_LINES_MAX)).count(), 64, "64 lines at most"); + assert!(!log.admit(1000, LOWEST, PRIORITY_LINES_MAX)); + assert_eq!(priority_line(476, 0x1234, Some("StreamingPager"), IDLE, None), "SetThreadPriority: thread 476 \"StreamingPager\" to THREAD_PRIORITY_IDLE (-15)"); + assert_eq!( + priority_line(0, 0x1234, None, 0x1_0000, Some(6)), + "SetThreadPriority: thread ? (handle 0x1234) (no name) to THREAD_MODE_BACKGROUND_BEGIN (65536) – the call failed (error 6)" + ); + assert_eq!(priority_line(9, 0, None, 3, None), "SetThreadPriority: thread 9 (no name) to a value Windows does not name (3)"); + } + + /// The title's SetThreadPriority reaches Wine as it is – the same answer and last error, the + /// priority set, a refused call refused alike – and each thread's IDLE, LOWEST and first other + /// value are logged once. + #[test] + fn set_thread_priority_passes_through_unchanged() { + use thr::{THREAD_PRIORITY_BELOW_NORMAL as BELOW, THREAD_PRIORITY_HIGHEST as HIGHEST, THREAD_PRIORITY_IDLE as IDLE, THREAD_PRIORITY_LOWEST as LOWEST, THREAD_PRIORITY_NORMAL as NORMAL}; + // (a thread of its own: the test runner's keeps its priority) + let (lines, tid, name, refused) = std::thread::Builder::new() + .name("xcl-priority-test".into()) + .spawn(|| unsafe { + let me = thr::GetCurrentThread(); + for p in [IDLE, IDLE, LOWEST, NORMAL, HIGHEST, BELOW] { + fnd::SetLastError(0x7F0F); + let real = thr::SetThreadPriority(me, p); + let real_error = fnd::GetLastError(); + fnd::SetLastError(0x7F0F); + assert_eq!(SetThreadPriority(me, p), real, "{p}: Wine's answer"); + assert_eq!(fnd::GetLastError(), real_error, "{p}: the last error as Wine left it"); + assert_eq!(thr::GetThreadPriority(me), p, "{p}: set"); + } + fnd::SetLastError(0); + let real = thr::SetThreadPriority(std::ptr::null_mut(), NORMAL); + let real_error = fnd::GetLastError(); + fnd::SetLastError(0); + assert_eq!((SetThreadPriority(std::ptr::null_mut(), NORMAL), fnd::GetLastError()), (real, real_error), "a call Wine refuses"); + assert_eq!(real, 0); + (PRIORITY_LINES_SEEN.with(|l| std::mem::take(&mut *l.borrow_mut())), thr::GetCurrentThreadId(), thread_description(me), real_error) + }) + .unwrap() + .join() + .unwrap(); + assert_eq!(name.as_deref(), Some("xcl-priority-test"), "the thread's name, as Rust's std gave it to Windows"); + let line = |p: i32| priority_line(tid, 0, name.as_deref(), p, None); + let mut want = vec![line(IDLE), line(LOWEST), line(NORMAL)]; + // (the refused call's line: unless an earlier one of an unknown thread was logged) + if lines.len() == 4 { + want.push(priority_line(0, 0, None, NORMAL, Some(refused))); + } + assert_eq!(lines, want); + // a handle's value used again for another thread – Wine gives a closed handle's value to the + // next handle made –: that thread's priority is logged too, by its id (F-3). Threads that + // never run anything of XCL's, with small stacks (threads made by the hundred move where + // later tests' memory lands). + unsafe extern "system" fn returns(_: *mut c_void) -> u32 { + 0 + } + let (reused, lines) = std::thread::spawn(|| unsafe { + let make = || thr::CreateThread(std::ptr::null(), 0x1_0000, Some(returns), std::ptr::null(), thr::CREATE_SUSPENDED | thr::STACK_SIZE_PARAM_IS_A_RESERVATION, std::ptr::null_mut()); + let end = |h: HANDLE| { + thr::ResumeThread(h); + thr::WaitForSingleObject(h, 5000); + fnd::CloseHandle(h); + }; + let a = make(); + assert!(!a.is_null(), "a thread"); + let tid_a = thr::GetThreadId(a); + assert_ne!(SetThreadPriority(a, IDLE), 0); + end(a); + // (the suite's other threads make handles meanwhile: up to 64 tries, the others closed after) + let (mut b, mut others) = (None, Vec::new()); + for _ in 0..64 { + let h = make(); + if h.is_null() { + break; + } + if h == a { + b = Some(h); + break; + } + others.push(h); + } + for h in others { + end(h); + } + let Some(b) = b else { return (None, Vec::new()) }; + let tid_b = thr::GetThreadId(b); + assert_ne!(SetThreadPriority(b, IDLE), 0); + end(b); + (Some((tid_a, tid_b)), PRIORITY_LINES_SEEN.with(|l| std::mem::take(&mut *l.borrow_mut()))) + }) + .join() + .unwrap(); + let Some((tid_a, tid_b)) = reused else { + return crate::gpu::recomp::runner::skip_config("no thread got a closed thread handle's value back in 64 tries"); + }; + assert_ne!(tid_a, tid_b, "two threads"); + assert_eq!(lines, vec![priority_line(tid_a, 0, None, IDLE, None), priority_line(tid_b, 0, None, IDLE, None)], "the second thread, set through the same handle value"); + } + /// Tracing keeps the last error of the call it traces: a lookup of an unset environment /// variable (what trace_mem's first call does) sets 203, which reached the title instead of /// the call's own error (xmem_and_physical_page_overflows_fail_cleanly, when it ran first). @@ -2322,6 +2927,65 @@ mod tests { } } + /// `XCL_SPARSE_64K_MAX_MB`: a reservation of 64 KiB pages with no commit and a block of + /// physical pages over it are plain memory (no tile of video memory); its pages mapped into + /// the reservation, moved, sent home and mapped again keep their bytes. + #[test] + fn a_page_pool_over_the_limit_is_plain_memory_and_keeps_its_pages() { + unsafe { + let Some(u) = crate::gpu::uma::get() else { return }; + if !u.has_sparse() { + return; + } + TEST_SPARSE_64K_MAX.with(|c| c.set(Some(4 * PHYS_PAGE))); + let t = MEM_64K_PAGES | mem::MEM_RESERVE; + let pool = VirtualAlloc(std::ptr::null(), 8 * PHYS_PAGE, t, mem::PAGE_READWRITE) as usize; + let small = VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, t, mem::PAGE_READWRITE) as usize; + assert!(pool != 0 && !u.is_sparse(pool) && !u.contains(pool), "a reservation over the limit is plain memory"); + assert!(small != 0 && u.is_sparse(small), "one under it is in a sparse window"); + let mut n = 8usize; + let mut pages = [0usize; 8]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let home = page_home(pages[0]).unwrap(); + assert!(!u.is_sparse(home) && !u.contains(home), "so are the homes of a block over it"); + let mut two = 2usize; + let mut few = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut two, few.as_mut_ptr()), 1); + assert!(u.contains(page_home(few[0]).unwrap()), "a block under it has its homes in unified memory"); + // the pages in the pool, one moved to a second place, sent home and mapped again: + // their bytes stay + assert_eq!(MapTitlePhysicalPages(pool as *mut c_void, 8, 0, 4, pages.as_mut_ptr()) as usize, pool); + for (i, _) in pages.iter().enumerate() { + *((pool + i * PHYS_PAGE + 0x40) as *mut u32) = 0xA000 + i as u32; + } + let cpu = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let mut one = [pages[3]]; + assert_eq!(MapTitlePhysicalPages(cpu as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, cpu); + assert_eq!(*((cpu + 0x40) as *const u32), 0xA003, "moved with its bytes"); + let mut none = [0usize]; + assert_eq!(MapTitlePhysicalPages(cpu as *mut c_void, 1, 0, 4, none.as_mut_ptr()) as usize, cpu); + let at_home = page_address(pages[3]).unwrap(); + assert!(!u.is_sparse(at_home), "home is plain memory"); + assert_eq!(*((at_home + 0x40) as *const u32), 0xA003, "kept at home"); + assert_eq!(MapTitlePhysicalPages((pool + 3 * PHYS_PAGE) as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, pool + 3 * PHYS_PAGE); + for i in 0..8 { + assert_eq!(*((pool + i * PHYS_PAGE + 0x40) as *const u32), 0xA000 + i as u32, "page {i}"); + } + assert!( + crate::hle::d3d12x::sparse::mapped_ranges().iter().all(|&(a, b)| b <= pool || a >= pool + 8 * PHYS_PAGE), + "no tile of video memory under the pool" + ); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 8, pages.as_mut_ptr()), 1); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, few.as_mut_ptr()), 1); + TEST_SPARSE_64K_MAX.with(|c| c.set(None)); + mem::VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE); + mem::VirtualFree(cpu as *mut c_void, 0, mem::MEM_RELEASE); + if let Some(u) = crate::gpu::uma::get() { + u.sparse_release(small); + } + } + } + /// A page the title maps at a second address is found by the first one too (a page pool /// maps its pages at the pool's address, then one at a time where they are used: the GPU's /// page mappings name them by their place in the pool). @@ -2366,6 +3030,48 @@ mod tests { } } + /// What has its data at an address (a crash's DirectStorage lookup): the page at its home, no + /// page, the page where the title mapped it and the home it left; with the page map held by + /// another thread the crash's look gives up within its wait – no hang, no false answer – and + /// with a wait of its own it finds the page. + #[test] + fn a_crash_lookup_finds_the_page_at_an_address_or_gives_up_on_a_busy_map() { + unsafe { + if crate::gpu::uma::get().is_none() { + crate::gpu::recomp::runner::skip_config("no unified memory"); + return; + } + let mut n = 1usize; + let mut one = [0usize; 1]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, one.as_mut_ptr()), 1); + let q = one[0]; + let h = page_home(q).unwrap(); + assert_eq!(page_of_address(h + 0x10), Some(PageHere::Home(q))); + let heap = Box::new(0u64); + assert_eq!(page_of_address(&*heap as *const u64 as usize), None, "no page there"); + let r = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(r, 0); + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 1, 0, 4, one.as_mut_ptr()) as usize, r); + assert_eq!(page_of_address(r + 0x10), Some(PageHere::Mapped(q))); + assert_eq!(page_of_address(h), Some(PageHere::HomeOf(q, r)), "its home holds something else now"); + assert_eq!(pages_here(r, 1), [Some(PageHere::Mapped(q))]); + // the page map busy (a title mapping pages): the look gives up once its wait is spent + let hold = hold_page_map(); + let left = AtomicU32::new(20); + let busy = page_of_address_within(r + 0x10, &left); + let spent = left.load(Ordering::Relaxed); + drop(hold); + assert_eq!(busy, Err(())); + assert_eq!(spent, 0, "all of the wait"); + // (a wait of its own: other tests take the map now and then) + assert_eq!(page_of_address_within(r + 0x10, &AtomicU32::new(2000)), Ok(Some(PageHere::Mapped(q)))); + // back home (the address left lazy is unmarked), freed + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, one.as_mut_ptr()) as usize, h); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, one.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + /// A page mapped away from a home in a sparse window is committed once: the home gives its /// memory back while the page is away and has the page's contents again when it returns. #[test] @@ -2434,8 +3140,8 @@ mod tests { assert!(!committed_page(r + 2 * PHYS_PAGE) && !committed_page(r + 4 * PHYS_PAGE), "the others are left lazy"); assert!(!committed_page(page_home(pages[N - 1]).unwrap()), "and their homes stay reserved"); assert_eq!(*((r + 4 * PHYS_PAGE) as *const u32), 0); - // back home: the pages left lazy are unmarked (a freed one stays marked, and the address - // is another test's later) + // back home: the pages left lazy are unmarked (as a freed one is: the address is another + // test's later) assert!(!MapTitlePhysicalPages(std::ptr::null_mut(), N, 0, 4, pages.as_mut_ptr()).is_null()); assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), N, pages.as_mut_ptr()), 1); mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); @@ -2473,8 +3179,8 @@ mod tests { let want = if i >= N / 2 { 0x100 + i as u32 } else { 0 }; assert_eq!(*((r2 + i * PHYS_PAGE) as *const u32), want, "page {i} (same address: {same_address})"); } - // back home: the pages left lazy are unmarked (a freed one stays marked, and the address - // is another test's later) + // back home: the pages left lazy are unmarked (as a freed one is: the address is another + // test's later) assert!(!MapTitlePhysicalPages(std::ptr::null_mut(), N, 0, 4, pages.as_mut_ptr()).is_null()); assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), N, pages.as_mut_ptr()), 1); mem::VirtualFree(r1 as *mut c_void, 0, mem::MEM_RELEASE); @@ -2509,8 +3215,8 @@ mod tests { let queries = VIRTUAL_QUERIES.with(|q| q.get()) - before; assert!(queries <= 8, "{queries} VirtualQuery calls for {N} pages mapped again"); } - // back home: the pages left lazy are unmarked (a freed one stays marked, and the address - // is another test's later) + // back home: the pages left lazy are unmarked (as a freed one is: the address is another + // test's later) assert!(!MapTitlePhysicalPages(std::ptr::null_mut(), N, 0, 4, pages.as_mut_ptr()).is_null()); assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), N, pages.as_mut_ptr()), 1); mem::VirtualFree(r1 as *mut c_void, 0, mem::MEM_RELEASE); @@ -2677,6 +3383,20 @@ mod tests { } } + /// GetModuleHandle of a name routed to a module of XCL's that stands for a real DLL + /// (`HleModule::real_dll`, dbghelp) answers as the system does: NULL while that DLL is not + /// loaded, never XCL's pseudo handle (which knows only the functions XCL overrides). + #[test] + fn get_module_handle_of_a_real_dll_not_loaded_is_null() { + if !crate::hle::dbghelp::enabled() { + return; + } + let mut cfg = crate::config::Config::default(); + cfg.aliases.insert("xcl_unloaded_real_dll_probe.dll".into(), crate::hle::dbghelp::DBGHELP.into()); + let reg = crate::hle::build(&cfg); + assert_eq!(module_handle_in(®, "xcl_unloaded_real_dll_probe.dll"), 0); + } + /// A move whose destination cannot be committed fails with the page still mapped away where /// it was: its bytes and both lookups are kept. #[test] @@ -2684,9 +3404,10 @@ mod tests { unsafe { let old = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize; *(old as *mut u32) = 7; - // an address with nothing reserved: committing there fails - let at = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; - mem::VirtualFree(at as *mut c_void, 0, mem::MEM_RELEASE); + // an address where nothing is ever reserved (the low 64 KiB): committing there fails. + // (An address freed here first could be reserved by another thread before the move – + // a test thread suspended in between while another dumped the process.) + let at = 0x1000usize; let page = 0x7E57_0000usize; let mut away = Away::default(); away.at.insert(old, page); @@ -2752,6 +3473,51 @@ mod tests { } } + /// A page freed while it is mapped where it was never used – left lazy there – takes that + /// address's mark with it: a page the title maps there later with its bytes is not taken for + /// one never used there, and moves on and goes home with them (with the mark left behind, it + /// arrived without them: zeros). Pages, a reservation and values (0x5A0C_000n) of its own. + #[test] + fn a_page_freed_where_it_was_left_lazy_takes_its_mark_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 (p, q) = (pages[0], pages[1]); + let r = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(r, 0); + let (a, b) = (r as *mut c_void, (r + PHYS_PAGE) as *mut c_void); + // (a fresh reservation: a mark there is another test's) + lazy::unmark(r); + lazy::unmark(r + PHYS_PAGE); + // (a home committed as a whole – the coherent window's – holds the page: not left lazy) + let lazy_here = lazy::enabled() && !committed_page(page_home(p).unwrap()); + let mut one = [p as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(&a, 1, one.as_mut_ptr()), 1); + assert_eq!(lazy::is_marked(r), lazy_here, "never used there: left lazy where pages are committed on first use"); + let mut freed = [p]; + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, freed.as_mut_ptr()), 1); + assert!(!lazy::is_marked(r), "the mark goes with the freed page"); + // the other page, used at home, mapped where the freed one was, written there, moved on + assert!(write_physical_pages(&[q], 0x40, &0x5A0C_0001u32.to_le_bytes())); + let mut other = [q as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(&a, 1, other.as_mut_ptr()), 1); + assert_eq!(*((r + 0x40) as *const u32), 0x5A0C_0001); + *((r + 0x80) as *mut u32) = 0x5A0C_0002; + assert_eq!(XMemMapPhysicalPagesScatter(&b, 1, other.as_mut_ptr()), 1); + let at = b as usize; + assert_eq!((*((at + 0x40) as *const u32), *((at + 0x80) as *const u32)), (0x5A0C_0001, 0x5A0C_0002), "moved with its bytes"); + assert!(!committed_page(r), "the address it left is given up"); + let mut home = [q]; + let h = MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, home.as_mut_ptr()) as usize; + assert_eq!(h, page_home(q).unwrap()); + assert_eq!(*((h + 0x80) as *const u32), 0x5A0C_0002, "and home with them"); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, home.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. @@ -3001,6 +3767,33 @@ mod tests { } } + /// GPU-visible title memory that reaches the plain-memory fallback is known – while the census + /// of placed buffers is on (`d3d12x::outside`) – until its release, end excluded. A graphics + /// protection without MEM_GRAPHICS, 64 KiB pages or a commit: no window takes it, whether or + /// not a test made them. + #[test] + fn gpu_visible_plain_memory_is_known_until_released() { + let _g = crate::hle::d3d12x::outside::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + { + let _on = crate::hle::d3d12x::outside::test_on(true); + let q = VirtualAlloc(std::ptr::null(), 0x10_0000, mem::MEM_RESERVE, 0x2004); + assert!(!q.is_null(), "a GPU-visible reservation"); + let a = q as usize; + assert_eq!(plain_gpu_at(a + 0x1234), Some((a, 0x10_0000))); + assert_eq!(plain_gpu_at(a + 0x10_0000), None, "its end is not in it"); + assert_eq!(VirtualFree(q, 0, mem::MEM_RELEASE), 1); + assert_eq!(plain_gpu_at(a + 0x1234), None, "known until its release"); + } + let _off = crate::hle::d3d12x::outside::test_on(false); + let q = VirtualAlloc(std::ptr::null(), 0x10_0000, mem::MEM_RESERVE, 0x2004); + assert!(!q.is_null()); + let known = plain_gpu_at(q as usize + 0x1234); + assert_eq!(VirtualFree(q, 0, mem::MEM_RELEASE), 1); + assert_eq!(known, None, "not kept with the census off"); + } + } + #[test] fn virtual_free_ex_and_sparse_validation() { unsafe { diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index a3f5270..260bf6f 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -178,3 +178,8 @@ mod tests { } } } + +/// (diagnostic) Whether the page of `at` is mapped but not committed yet. +pub fn is_marked(at: usize) -> bool { + LAZY.read().unwrap_or_else(|e| e.into_inner()).contains(&(at & !(PAGE - 1))) +} diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index 87d6475..50b984a 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -14,6 +14,7 @@ pub mod acphal; pub mod bcpack; pub mod d3d12_layout; pub mod d3d12x; +pub mod dbghelp; pub mod dstorage; pub mod dxcompiler; pub mod gameinput; @@ -44,6 +45,10 @@ pub struct HleModule { /// For names we do not implement: real Windows DLLs to try, in order. `"@self"` is /// the DLL name the title imported (when it is not our canonical name). pub fallback: &'static [&'static str], + /// The names routed here are real Windows DLLs, which need not be loaded (`dbghelp`): + /// GetModuleHandle answers as the system does – NULL while one is not loaded – and + /// LoadLibrary gives the system's module or fails, never XCL's pseudo handle. + pub real_dll: bool, } /// The real DLL a name we route here stands for. @@ -51,7 +56,7 @@ pub const SELF: &str = "@self"; impl HleModule { fn new(name: &'static str, list: Vec<(&'static str, usize)>, fallback: &'static [&'static str]) -> Self { - HleModule { name, exports: list.into_iter().collect(), ordinals: HashMap::new(), fallback } + HleModule { name, exports: list.into_iter().collect(), ordinals: HashMap::new(), fallback, real_dll: false } } /// Kernel family: the names routed here (kernel32.dll, api-ms-win-core-*) are real @@ -118,6 +123,12 @@ fn build(config: &Config) -> Registry { m.ordinals = netoff::ordinals().into_iter().collect(); modules.push(m); } + if dbghelp::enabled() { + // the title's crash handler: Wine's MiniDumpWriteDump, kept off XCL's DWARF (`dbghelp`) + let mut m = HleModule::new(dbghelp::DBGHELP, dbghelp::exports(), &[SELF]); + m.real_dll = true; + modules.push(m); + } let idx = |n: &str| modules.iter().position(|m| m.name == n).unwrap(); let mut routes: Vec<(String, Route)> = Vec::new(); // user aliases first – they take precedence @@ -187,6 +198,9 @@ fn build(config: &Config) -> Registry { for p in ["dxcompiler_xs.dll", "dxcompiler_x.dll"] { routes.push((p.into(), Route::Hle(c))); } + if dbghelp::enabled() { + routes.push(("dbghelp.dll".into(), Route::Hle(idx(dbghelp::DBGHELP)))); + } if offline { let n = idx(netoff::NETOFF); for p in ["winhttp.dll", "ws2_32.dll"] { diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index ba5dcb4..9ed794d 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -29,8 +29,39 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + // (read before the title runs: kernelx asks it inside the title's VirtualAlloc – `outside`) + let _ = crate::hle::d3d12x::outside::on(); + // (and so are XCL_SKIP_CS and XCL_SKIP_CS_ROOTS: XCL's views are recorded from the first one + // without the environment read inside the title's calls – `skip_roots`) + let _ = crate::hle::d3d12x::skip_roots::on(); + // (and so is XCL_VIEW_CENSUS: the view census's map is made with the shared heap, inside the + // title's device calls – `view_census`) + let _ = crate::hle::d3d12x::view_census::on(); + // (and so is XCL_PSO_TIERS: a pipeline's tier in the workers' queue is set at its first bind, + // inside the title's calls – `pso_async::tier_of` –, and so are the translation cache's folder + // and debug switches that tier looks up – `pso::translation_lookup`) + let _ = crate::hle::d3d12x::pso_async::tiers_on(); + let _ = crate::gpu::recomp::pso::translation_lookup(); + // (and so are XCL_FRAME_DUMP_WORLD – the world's first frame is marked inside the title's + // dispatches, `present::note_world_mark` –, XCL_UPLOAD_STAGING_MB – the title textures' uploads + // run inside its submits – and XCL_COHERENT_OWN_MB – the coherent window is made inside its first + // call that asks for unified memory) + let _ = crate::hle::d3d12x::present::world_dumps(); + let _ = crate::gpu::texture::staging_cap(); + let _ = crate::gpu::uma::own_part(); // `XCL_ACTIVITY=1`: every 2 s what the title did since (a timeline of where it stops) if std::env::var_os("XCL_ACTIVITY").is_some() { + // what the PC view descriptors name – the textures made for views by address that none + // names any more – and where the textures' memory is, every 10 s on a thread of its own: its + // pass (V1 says its ms) takes HEAPS, GLOBAL, MADE and ARENA_OF, which the title's threads + // hold, so the activity lines' 2-s spacing (tools/cadence.py's "late") and the no-Present + // line never wait for it + let _ = std::thread::Builder::new().name("xcl-view-census".into()).spawn(|| loop { + std::thread::sleep(std::time::Duration::from_secs(10)); + for l in crate::hle::d3d12x::view_census_lines() { + crate::xlog_info!("{l}"); + } + }); let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| { let snap = || { let (p, e) = crate::hle::d3d12x::present::activity(); @@ -40,39 +71,99 @@ pub fn host_main(boot_path: &Path) -> i32 { [p, e, d, x, f[0], f[1], f[2], f[3], r, b >> 20, fail] }; let mut last = snap(); + // D3DMetal's count of its video memory is its Metal device's allocated size modulo + // 4 GiB: unwrapped by its jumps between looks a quarter of a second apart (it moves + // in blocks of 256 MiB; a world load moved it by 1.8 GiB in one 2 s look) + let mut unwrap = VideoMemory::default(); + let mut quiet = NoPresent::default(); + // what the coherent window's line said last (it is said when its numbers moved) + let mut coherent = crate::gpu::uma::CoherentWatch::default(); + // what the host's figures are, once (under Wine the process's commit is not reported) + if let Some(n) = host_note(crate::util::mac_host(), crate::util::under_wine()) { + crate::xlog_info!("{n}"); + } + // activity lines so far: the outside census every 15th (30 s) + let mut tick = 0u64; loop { - std::thread::sleep(std::time::Duration::from_secs(2)); + for _ in 0..8 { + std::thread::sleep(std::time::Duration::from_millis(250)); + unwrap.look(); + } let now = snap(); let d: Vec = now.iter().zip(last).map(|(a, b)| a - b).collect(); crate::xlog_info!( "activity (2 s): {} presents, {} submits, {} draws, {} dispatches, {} frame-event waits ({} timed out), {} frame statistics ({} not flipped); DirectStorage {} requests, {} MB, {} failed", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10] ); - // where the memory is: the process's commit, video memory, and XCL's parts of it - let private = unsafe { - use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; - let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); - c.cb = std::mem::size_of_val(&c) as u32; - K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); - c.PrivateUsage - }; + if let Some(l) = crate::hle::d3d12x::pso_async::activity_line() { + crate::xlog_info!("{l}"); + // the workers' queue by tier and kind, DXC, commit waits, first uses, the + // programs skipped most – with the pipelines line only + crate::xlog_info!("{}", crate::hle::d3d12x::pso_async::queue_line()); + } + // each pipeline built in this run, the first time a bind got it (1024 a process) + for l in crate::hle::d3d12x::pso_async::first_use_lines() { + crate::xlog_info!("{l}"); + } + let ms = (crate::log::uptime() * 1000.0) as u64; + if let Some((secs, since, frozen)) = quiet.look(ms, now[0], crate::hle::d3d12x::pso_async::frozen_ms()) { + let held = if crate::waitwatch::on() { crate::waitwatch::in_xcl() } else { crate::hle::d3d12x::pso_async::building() }; + let line = no_present_line( + (secs, since, now[0], frozen), + &held, + &crate::hle::d3d12x::pso_async::most_skipped(4), + &crate::hle::d3d12x::pso_async::waits_since_present(), + ); + crate::xlog_warn!("{line}"); + } + // where the memory is: the process's commit (under Wine: none), video memory, + // XCL's parts of it, what the host says + let counters = process_counters(); let (local, non_local) = crate::hle::d3d12x::real::video_memory().unwrap_or((0, 0)); let (arenas, arenas_made) = crate::hle::d3d12x::vram::arena_bytes(); let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); - let mb = |b: u64| b >> 20; - crate::xlog_info!( - "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped)", - mb(private as u64), - mb(local), - mb(non_local), - mb(pages as u64), - mb(page_pools as u64), - mb(arenas as u64), - mb(arenas_made as u64), - mb(pools as u64), - mb(pools_mapped as u64) - ); + let (held, let_go, waiting) = crate::hle::d3d12x::deferred_releases(); + let f = MemoryFigures { + committed: counters.map_or(0, |c| c.PrivateUsage as u64), + local, + non_local, + pages: pages as u64, + page_pools: page_pools as u64, + arenas: arenas as u64, + arenas_made: arenas_made as u64, + pools: pools as u64, + pools_mapped: pools_mapped as u64, + held, + let_go, + waiting, + }; + crate::xlog_info!("{}", memory_line(&f, HostMemory::now(counters.as_ref()).as_ref())); + // the title's textures in its memory: how they were made, what is kept now, the + // lazy ones' tiles + crate::xlog_info!("{}; {}", crate::hle::d3d12x::device_x::creation_stats(), crate::hle::d3d12x::title_textures::census()); + if let Some(l) = crate::hle::d3d12x::lazy_stats() { + crate::xlog_info!("{l}"); + } + crate::xlog_info!("{}", crate::hle::d3d12x::gpu_work_line()); + if let Some(l) = crate::hle::d3d12x::bind::indirect_line() { + crate::xlog_info!("{l}"); + } + if let Some(v) = unwrap.now() { + crate::xlog_info!("video memory: {} MB local{} (upload staging {} MB)", v >> 20, if unwrap.wraps { " – unwrapped" } else { "" }, crate::gpu::texture::staging_bytes() >> 20); + } + // the coherent window's use, high-water and refused per-draw blocks, when they moved + // (never makes the window: `uma::made`) + if let Some(l) = crate::gpu::uma::made().and_then(|u| coherent.look(u, crate::gpu::uma::own_part())) { + crate::xlog_info!("{l}"); + } + tick += 1; + // the buffers the title placed outside unified memory, every 30 s (when that changed) + if tick % 15 == 0 { + if let Some(l) = crate::hle::d3d12x::outside_census() { + crate::xlog_info!("{l}"); + } + } last = now; } }); @@ -142,7 +233,297 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::report::write_final(None); let code = crate::loader::run_main(&main); crate::xlog_info!("game entry point returned code {code}"); + crate::xlog_info!("{}", crate::hle::d3d12x::pso_async::end_line()); crate::report::write_final(None); crate::log::flush(); code as i32 } + +/// A stretch without a Present is said once, after `NO_PRESENT_MS` (`look`). +const NO_PRESENT_MS: u64 = 30_000; + +/// The "no Present" line: (its length in s, when it began in s, presents so far, s the process +/// stood still in it), the threads in XCL (`held`), the programs skipped most, and – last, so that +/// what parses the fields before it still finds them – the threads whose binds waited for +/// pipelines since the last Present (`pso_async::waits_since_present`: run 65's thread 472 waited +/// 27.5 s for ~45 in a row, which the merged waits watch showed as one wait of 19.3 s). +fn no_present_line((secs, since, presents, frozen): (u64, f64, u64, u64), held: &[String], most_skipped: &str, waits: &str) -> String { + format!( + "activity: no Present for {secs} s (the last by {since:.1} s, {presents} so far; the process stood still {frozen} s of it); threads in XCL: {}; most skipped: {most_skipped}; pipeline waits since the last Present: {waits}", + if held.is_empty() { "none".to_string() } else { held.join("; ") }, + ) +} + +#[derive(Default)] +struct NoPresent { + presents: u64, + /// when the count last moved (ms), and the process's frozen ms then + at: u64, + frozen_at: u64, + said: bool, +} + +impl NoPresent { + /// At `now` (ms) with `presents` so far and the process frozen `frozen` ms so far: once a + /// stretch, after `NO_PRESENT_MS`, its length (s), when it began (s) and the s it stood + /// still in it. Nothing before the title's first Present. + fn look(&mut self, now: u64, presents: u64, frozen: u64) -> Option<(u64, f64, u64)> { + if presents != self.presents { + *self = NoPresent { presents, at: now, frozen_at: frozen, said: false }; + return None; + } + if presents == 0 || self.said || now.saturating_sub(self.at) < NO_PRESENT_MS { + return None; + } + self.said = true; + Some((now.saturating_sub(self.at) / 1000, self.at as f64 / 1000.0, frozen.saturating_sub(self.frozen_at) / 1000)) + } +} + +/// The local video memory D3DMetal reports, unwrapped: it gives its Metal device's allocated size +/// truncated to 32 bits (`DXGIAdapter::QueryVideoMemoryInfo`, a MOV EAX, EAX), so a fall of more +/// than 2 GiB between two looks is a wrap upward, a rise of more than 2 GiB after a wrap one +/// downward. Elsewhere the figure is as given. +#[derive(Default)] +struct VideoMemory { + last: Option, + wrapped: u64, + /// unwrapping (a Mac host) + wraps: bool, +} + +impl VideoMemory { + fn look(&mut self) { + let Some((local, _)) = crate::hle::d3d12x::real::video_memory() else { return }; + self.wraps = crate::util::mac_host(); + if self.wraps { + if let Some(last) = self.last { + if local + (2 << 30) < last { + self.wrapped += 1; + } else if local > last + (2 << 30) && self.wrapped > 0 { + self.wrapped -= 1; + } + } + } + self.last = Some(local); + } + + fn now(&self) -> Option { + self.last.map(|l| if self.wraps { l + (self.wrapped << 32) } else { l }) + } +} + +/// What the host says of its memory (the memory line's end): GlobalMemoryStatusEx's load, +/// physical memory and commit (available, total), GetProcessMemoryInfo's working set and its +/// peak (bytes). Under Wine on a Mac (CrossOver 26.3's kernelbase and ntdll): physical available +/// is free + inactive pages, commit is physical memory + swap (available: physical available + +/// free swap), the load is 100 − physical available in %, the working set is the task's resident +/// memory (not macOS's footprint: compressed memory is not in it); figures at most a second old +/// (Wine keeps them that long). ullAvailVirtual is left out: Wine gives the address space less the +/// working set. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct HostMemory { + load: u32, + /// (available, total) + phys: (u64, u64), + commit: (u64, u64), + /// (working set, its peak); None: GetProcessMemoryInfo failed + working_set: Option<(u64, u64)>, +} + +impl HostMemory { + /// Now (None: GlobalMemoryStatusEx failed); `c`: the process's counters. + fn now(c: Option<&windows_sys::Win32::System::ProcessStatus::PROCESS_MEMORY_COUNTERS_EX>) -> 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; + if unsafe { GlobalMemoryStatusEx(&mut m) } == 0 { + return None; + } + Some(HostMemory { + load: m.dwMemoryLoad, + phys: (m.ullAvailPhys, m.ullTotalPhys), + commit: (m.ullAvailPageFile, m.ullTotalPageFile), + working_set: c.map(|c| (c.WorkingSetSize as u64, c.PeakWorkingSetSize as u64)), + }) + } + + /// "host: load 72%, physical 6787 of 24576 MB available, commit 7490 of 27648 MB available, + /// working set 3612 MB (peak 9876 MB)" + fn clause(&self) -> String { + let mb = |b: u64| b >> 20; + let mut s = format!( + "host: load {}%, physical {} of {} MB available, commit {} of {} MB available", + self.load, mb(self.phys.0), mb(self.phys.1), mb(self.commit.0), mb(self.commit.1) + ); + if let Some((ws, peak)) = self.working_set { + s.push_str(&format!(", working set {} MB (peak {} MB)", mb(ws), mb(peak))); + } + s + } +} + +/// The process's memory counters (None: the call failed). Wine fills the fields before +/// PrivateUsage only (its GetProcessMemoryInfo asks ntdll for VM_COUNTERS): 0 there. +fn process_counters() -> Option { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; + unsafe { + let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + c.cb = std::mem::size_of_val(&c) as u32; + (K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb) != 0).then_some(c) + } +} + +/// The one-time line saying what the host's figures are (None: not under Wine). +fn host_note(mac: bool, wine: bool) -> Option<&'static str> { + if mac { + Some("host memory (Wine on a Mac): physical available = free + inactive pages, commit = physical memory + swap (available: physical available + free swap), load = 100 − physical available in %, working set = resident memory (not the footprint: compressed memory is not in it); the process's commit is not reported (the 0 MB committed by the process of the memory lines), nor available virtual memory (Wine gives the address space less the working set)") + } else if wine { + Some("host memory (Wine): the host's figures as Wine gives them; the process's commit is not reported (the 0 MB committed by the process of the memory lines)") + } else { + None + } +} + +/// The memory line's figures (bytes). +#[derive(Default)] +struct MemoryFigures { + committed: u64, + local: u64, + non_local: u64, + pages: u64, + page_pools: u64, + arenas: u64, + arenas_made: u64, + pools: u64, + pools_mapped: u64, + held: u64, + let_go: u64, + waiting: usize, +} + +/// "memory: …": the fields the analyses read, as before (`memlines.py`: up to "waiting"), the +/// host's at the end. +fn memory_line(f: &MemoryFigures, host: Option<&HostMemory>) -> String { + let mb = |b: u64| b >> 20; + let mut s = format!( + "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped); deferred releases: {} held so far, {} let go, {} waiting", + mb(f.committed), mb(f.local), mb(f.non_local), mb(f.pages), mb(f.page_pools), mb(f.arenas), mb(f.arenas_made), mb(f.pools), mb(f.pools_mapped), f.held, f.let_go, f.waiting + ); + if let Some(h) = host { + s.push_str("; "); + s.push_str(&h.clause()); + } + s +} + +#[cfg(test)] +mod no_present_tests { + use super::*; + + /// A stretch without a Present is said once, 30 s after the last one, with the time the + /// process stood still in it – never before the first Present. + #[test] + fn a_stretch_without_a_present_is_said_once_after_30_s() { + let mut q = NoPresent::default(); + for t in (0..=60_000u64).step_by(2000) { + assert_eq!(q.look(t, 0, 0), None, "no Present yet at {t} ms"); + } + let mut presents = 0; + for t in (62_000..=100_000u64).step_by(2000) { + presents += 60; + assert_eq!(q.look(t, presents, 0), None, "presents at {t} ms"); + } + // none from 100 s on; the process frozen 7 s of it + let mut said = Vec::new(); + for t in (102_000..=200_000u64).step_by(2000) { + let frozen = if t >= 120_000 { 7_000 } else { 0 }; + if let Some(l) = q.look(t, presents, frozen) { + said.push((t, l)); + } + } + assert_eq!(said, vec![(130_000, (30, 100.0, 7))], "once, 30 s after the last Present"); + // presents again, then none from 202 s on + presents += 1; + let mut said = Vec::new(); + for t in (202_000..=300_000u64).step_by(2000) { + if let Some(l) = q.look(t, presents, 7_000) { + said.push((t, l)); + } + } + assert_eq!(said, vec![(232_000, (30, 202.0, 0))], "once more for the next stretch"); + } + + /// The "no Present" line keeps its text up to "most skipped: …" as before 0023.1 (the run + /// scripts' events find it by "activity: no Present for") and names the pipeline waits since + /// the last Present after it. + #[test] + fn the_no_present_line_names_the_pipeline_waits_last() { + let held = ["thread 472 in XCL: waiting for a pipeline still being built for 9.4 s".to_string()]; + let waits = "thread 472 waited 27.5 s for 45 pipelines"; + assert_eq!( + no_present_line((30, 160.8, 2430, 0), &held, "56c0cd3b82a00c6e ×2", waits), + "activity: no Present for 30 s (the last by 160.8 s, 2430 so far; the process stood still 0 s of it); threads in XCL: thread 472 in XCL: waiting for a pipeline still being built for 9.4 s; most skipped: 56c0cd3b82a00c6e ×2; pipeline waits since the last Present: thread 472 waited 27.5 s for 45 pipelines" + ); + assert!(no_present_line((31, 1.0, 5, 2), &[], "none", "none").ends_with("threads in XCL: none; most skipped: none; pipeline waits since the last Present: none")); + } +} + +#[cfg(test)] +mod memory_tests { + use super::*; + + /// The memory line keeps the fields the analyses read up to "waiting" (`memlines.py`), as + /// 0022 wrote them, and ends with what the host says; the one-time note says what Wine's + /// figures are on a Mac, a sentence of its own on another Wine host, nothing natively. + #[test] + fn the_memory_line_keeps_its_fields_and_ends_with_the_hosts() { + let m = |n: u64| n << 20; + let f = MemoryFigures { + committed: 0, + local: m(3651), + non_local: 0, + pages: 0, + page_pools: 0, + arenas: m(1823), + arenas_made: m(1890), + pools: m(1088), + pools_mapped: m(1058), + held: 125, + let_go: 125, + waiting: 0, + }; + let h = HostMemory { load: 72, phys: (m(6787), m(24576)), commit: (m(7490), m(27648)), working_set: Some((m(3612), m(9876))) }; + assert_eq!( + memory_line(&f, Some(&h)), + "memory: 0 MB committed by the process; video memory 3651 MB local, 0 MB non-local; target pages 0 MB (pools 0 MB); arenas 1823 MB in use, 1890 MB made; sparse pools 1088 MB (1058 MB mapped); deferred releases: 125 held so far, 125 let go, 0 waiting; host: load 72%, physical 6787 of 24576 MB available, commit 7490 of 27648 MB available, working set 3612 MB (peak 9876 MB)" + ); + // 0022's line, word for word + let old = format!( + "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped); deferred releases: {} held so far, {} let go, {} waiting", + 0, 3651, 0, 0, 0, 1823, 1890, 1088, 1058, 125, 125, 0 + ); + assert_eq!(memory_line(&f, None), old, "no host figures: 0022's line"); + let c = HostMemory { working_set: None, ..h }.clause(); + assert_eq!(c, "host: load 72%, physical 6787 of 24576 MB available, commit 7490 of 27648 MB available"); + assert!(host_note(true, true).is_some_and(|n| n.starts_with("host memory (Wine on a Mac): ") && n.contains("free + inactive pages"))); + assert_eq!( + host_note(false, true), + Some("host memory (Wine): the host's figures as Wine gives them; the process's commit is not reported (the 0 MB committed by the process of the memory lines)") + ); + assert_eq!(host_note(false, false), None, "natively: nothing to say"); + } + + /// What the host gives here lies within its totals: physical memory of a GiB or more, the + /// figures available no more than their totals, a load in %, a working set no more than its + /// peak (under Wine on a Mac: the task's resident memory and its peak). + #[test] + fn the_host_reports_its_memory_within_its_totals() { + let h = HostMemory::now(process_counters().as_ref()).expect("GlobalMemoryStatusEx"); + assert!(h.phys.1 >= 1 << 30, "{h:?}"); + assert!(h.phys.0 <= h.phys.1 && h.commit.0 <= h.commit.1, "{h:?}"); + assert!(h.load <= 100, "{h:?}"); + let (ws, peak) = h.working_set.expect("GetProcessMemoryInfo"); + assert!(0 < ws && ws <= peak, "{h:?}"); + } +} diff --git a/crates/xcl/src/isa.rs b/crates/xcl/src/isa.rs index adae46d..ae9d577 100644 --- a/crates/xcl/src/isa.rs +++ b/crates/xcl/src/isa.rs @@ -58,6 +58,9 @@ pub enum Op { /// 0F 01 FC: zero the 64-byte line at RAX. Only `thunk` knows it (with the instruction /// that follows); `decode` leaves the lone instruction to the caller. Clzero, + /// A whole zeroing loop `clzero; add rax, 0x40; cmp rax, r64; jb -12` (12 bytes): only + /// `thunk` knows it – one helper runs the loop and returns past it. + ClzeroLoop, } impl Op { @@ -70,6 +73,7 @@ impl Op { Op::Movntsd => "MOVNTSD", Op::InsertqImm => "INSERTQ", Op::Clzero => "CLZERO", + Op::ClzeroLoop => "CLZERO loop", } } } @@ -297,7 +301,7 @@ pub unsafe fn exec( } } // emulated by `eh::emulate_console_only` (`insn`); here they are only redirected (`thunk`) - Op::InsertqImm | Op::Clzero => return false, + Op::InsertqImm | Op::Clzero | Op::ClzeroLoop => return false, } c.set_rip(next); true @@ -352,6 +356,32 @@ impl Emit<'_> { /// whose flags are the ones the loop branch reads. pub fn thunk(c: &[u8], out: &mut [u8; THUNK_MAX]) -> Option { let mut e = Emit { out, n: 0 }; + // the whole loop `clzero; add rax, 0x40; cmp rax, r64; jb -12` (as `insn` decodes it): the + // call replaces the CLZERO and the helper returns 12 bytes past it, having run the loop – + // the same stores, the same RAX and the flags of the last compare. Nothing returns into + // the loop's body, so the bytes after the call are never run (see `eh::redirect`). + if let [0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, rex @ (0x48 | 0x4C), 0x39, m, 0x72, 0xF4, ..] = c { + let end = ((m >> 3) & 7) | if *rex == 0x4C { 8 } else { 0 }; + if m & 0xC7 == 0xC0 && end != 0 && end != 4 { + // two scratch registers (low ones, no REX.R/B) that are not the loop's end + let mut scratch = [1u8, 7, 6, 3, 2].into_iter().filter(|&r| r != end); + let (a, b) = (scratch.next()?, scratch.next()?); + e.put(&[0x48, 0x83, 0x04, 0x24, 0x07]); // add qword [rsp], 7: return past the loop + e.put(&[0x50 + a, 0x50 + b]); // push a; push b + e.put(&[0x31, 0xC0 | a << 3 | a]); // xor a32, a32 + let top = e.n; + e.put(&[0x48, 0x89, 0xC0 | b]); // mov b, rax + e.put(&[0x48, 0x83, 0xE0 | b, 0xC0]); // and b, -64 + for d in 0..8u8 { + e.put(&[0x48, 0x89, 0x40 | a << 3 | b, d * 8]); // mov [b + d*8], a + } + e.put(&c[3..10]); // add rax, 0x40; cmp rax, end + let rel = top as i64 - (e.n as i64 + 2); + e.put(&[0x72, rel as i8 as u8]); // jb top + e.put(&[0x58 + b, 0x58 + a, 0xC3]); // pop b; pop a; ret + return Some(Thunk { site_len: 5, len: e.n as u8, slot: None, op: Op::ClzeroLoop }); + } + } if let [0x0F, 0x01, 0xFC, tail @ ..] = c { let t = match tail { [0x48, 0x83, 0xC0, 0x40, ..] => 4, @@ -502,4 +532,77 @@ mod tests { let t = thunk(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40], &mut out).unwrap(); assert_eq!((t.op, t.site_len), (Op::Clzero, 7)); } + + /// The whole CLZERO loop's helper, run: called from a site as the patch has it, it zeroes + /// the lines from RAX's on until RAX reaches the end register (at least one: a do-while + /// loop), leaves RAX there and the flags of the last compare, keeps every other register, + /// and returns 12 bytes past the call – with the end in RDX and in R10 (GTA VI's loops). + #[test] + fn clzero_loop_helper_runs_the_loop() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; + // not a loop: the jump goes elsewhere, the compare is with RSP, the CLZERO has a prefix + let mut out = [0u8; THUNK_MAX]; + for c in [ + [0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF0], + [0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xE0, 0x72, 0xF4], + [0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72], + ] { + assert_ne!(thunk(&c, &mut out).map(|t| t.op), Some(Op::ClzeroLoop), "{c:02x?}"); + } + unsafe { + let code = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as *mut u8; + let buf = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert!(!code.is_null() && buf != 0); + // (cmp rax, rdx / cmp rax, r10; the load of the end register) + let cases: [([u8; 3], [u8; 4]); 2] = [([0x48, 0x39, 0xD0], [0x48, 0x8B, 0x51, 0x08]), ([0x4C, 0x39, 0xD0], [0x4C, 0x8B, 0x51, 0x08])]; + for (k, (cmp, load_end)) in cases.into_iter().enumerate() { + let site = [0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, cmp[0], cmp[1], cmp[2], 0x72, 0xF4]; + let mut out = [0u8; THUNK_MAX]; + let t = thunk(&site, &mut out).unwrap(); + assert_eq!((t.op, t.site_len, t.slot), (Op::ClzeroLoop, 5, None)); + let (stub, helper) = (0x200 * k, 0x200 * k + 0x100); + std::ptr::copy_nonoverlapping(out.as_ptr(), code.add(helper), t.len as usize); + // the stub: RAX and the end from [rcx], [rcx+8]; RBX, RSI, RDI, RCX's copy kept + // in [rcx+24..]; call the helper as the patched site does (7 bytes it skips); + // RAX, the flags and those registers back into the state + let mut s: Vec = vec![0x48, 0x8B, 0x01]; // mov rax, [rcx] + s.extend(load_end); // mov rdx|r10, [rcx+8] + s.extend([0x53, 0x56, 0x57]); // push rbx; push rsi; push rdi + s.extend([0x48, 0x8B, 0x59, 0x18, 0x48, 0x8B, 0x71, 0x20, 0x48, 0x8B, 0x79, 0x28]); // mov rbx/rsi/rdi, [rcx+24/32/40] + s.push(0x51); // push rcx + let call_at = s.len(); + s.push(0xE8); + s.extend((helper as i32 - (stub + call_at + 5) as i32).to_le_bytes()); + s.extend([0xCC; 7]); + s.push(0x59); // pop rcx + s.extend([0x48, 0x89, 0x01]); // mov [rcx], rax + s.extend([0x9C, 0x58, 0x48, 0x89, 0x41, 0x10]); // pushfq; pop rax; mov [rcx+16], rax + s.extend([0x48, 0x89, 0x59, 0x18, 0x48, 0x89, 0x71, 0x20, 0x48, 0x89, 0x79, 0x28]); // mov [rcx+24/32/40], rbx/rsi/rdi + s.extend([0x5F, 0x5E, 0x5B, 0xC3]); // pop rdi; pop rsi; pop rbx; ret + std::ptr::copy_nonoverlapping(s.as_ptr(), code.add(stub), s.len()); + let run: extern "system" fn(*mut [u64; 6]) = std::mem::transmute(code.add(stub)); + for (start, end) in [(0x40usize, 0x100usize), (0x50, 0xC0), (0x40, 0x41), (0x53, 0x40), (0x53, 0)] { + std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x200); + let (s0, e0) = ((buf + start) as u64, (buf + end) as u64); + let mut st = [s0, e0, 0, 0x1111, 0x2222, 0x3333]; + run(&mut st); + let lines = if end > start { (end - start).div_ceil(64) } else { 1 } as u64; + let fin = s0 + 64 * lines; + assert_eq!(st[0], fin, "rax, case {k} {start:#x}..{end:#x}"); + let (diff, borrow) = fin.overflowing_sub(e0); + assert_eq!((st[2] & 1 != 0, st[2] & 0x40 != 0), (borrow, diff == 0), "CF/ZF of the last compare"); + assert_eq!(st[3..], [0x1111, 0x2222, 0x3333], "the other registers kept"); + let first = (buf + start) & !63; + let mem = std::slice::from_raw_parts(buf as *const u8, 0x200); + for (i, &b) in mem.iter().enumerate() { + let a = buf + i; + let zeroed = a >= first && (a as u64) < (first as u64 + 64 * lines); + assert_eq!(b, if zeroed { 0 } else { 0xA5 }, "byte {i:#x}, case {k} {start:#x}..{end:#x}"); + } + } + } + VirtualFree(code as *mut _, 0, MEM_RELEASE); + VirtualFree(buf as *mut _, 0, MEM_RELEASE); + } + } } diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index 786a074..928a955 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -35,3 +35,5 @@ pub mod tls; pub mod util; pub mod vfs; pub mod vfs_hooks; +pub mod waitwatch; +pub mod widestore; diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index f4885ae..c3bf48f 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -137,9 +137,17 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> let code: Vec<(u32, u32)> = pe.sections.iter().filter(|s| s.characteristics & 0x2000_0000 != 0).map(|s| (s.va, s.mapped_size())).collect(); let ex = pe.dir(pe::DIR_EXCEPTION); unsafe { replace_masked_stores(base, size, &code, (ex.rva, ex.size), &name) }; + // after the masked stores (their calls are in the bytes this walks), before the + // runtime copies' entry points (`replace_runtime_copies` writes an address there) + if wide_store_helpers() { + unsafe { replace_wide_stores(base, size, &code, (ex.rva, ex.size), &name) }; + } } let exports = OwnedExports::from_pe(&pe).unwrap_or_default(); + if runtime_copies() && RUNTIME_COPY_DLLS.contains(&name.as_str()) { + unsafe { replace_runtime_copies(base, size, &exports, &name) }; + } let module = Arc::new(MappedModule { name: name.clone(), path: path.to_path_buf(), @@ -246,6 +254,298 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> /// Whether a title's AVX masked stores are replaced by calls to helpers (`maskmov`): /// Enabled where the title's code runs through Rosetta 2, unless disabled by /// `XCL_MASKED_STORES=0`. +/// The title runtimes whose memcpy / memmove / memset are replaced on a Rosetta host. +const RUNTIME_COPY_DLLS: [&str; 2] = ["vcruntime140.dll", "vcruntime140d.dll"]; + +fn runtime_copies() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| crate::util::rosetta() && std::env::var("XCL_RUNTIME_COPIES").map_or(true, |v| v.trim() != "0")) +} + +/// Rosetta cannot resume a 256-bit store that faults past its first half: it stores the two +/// halves apart, and when the second one faults after the first has landed it prints "rosetta +/// error: unexpectedly need to EmulateForward on a synchronous exception" and the faulting +/// thread never gets its exception. Rosetta's exception server stays with it, so every later +/// exception of the process – XCL's own emulation, Wine's write-watch faults, the title's – +/// waits for ever too. The title runtime's memmove (= memcpy) and memset copy with unaligned +/// 32-byte VMOVDQU, and one of them crossing into a write-watched page of unified memory +/// (`gpu::uma`, `title_textures`) is enough: GTA VI 1.0.2.1 froze 5-10 s into its first +/// loading screen at vcruntime140.dll+0x1597 in every run. On a Rosetta host their entry points +/// jump to `title_memmove` / `title_memset` instead: `rep movsb` / `rep stosb`, which stop at +/// the exact byte that faults and go on from it. Done while the image is mapped and none of its +/// code has run. `XCL_RUNTIME_COPIES=0` leaves them. +unsafe fn replace_runtime_copies(base: usize, size: usize, exports: &OwnedExports, name: &str) { + let targets: [(&str, usize); 3] = [("memmove", title_memmove as usize), ("memcpy", title_memmove as usize), ("memset", title_memset as usize)]; + let mut done: Vec = Vec::new(); + let mut patched: Vec = Vec::new(); + for (export, to) in targets { + let Some(pe::ExportTarget::Rva(rva)) = exports.by_name.get(export) else { continue }; + if patched.contains(rva) { + done.push(export.to_string()); + continue; + } + let at = base + *rva as usize; + if *rva as usize + 14 > size { + continue; + } + // jmp qword [rip + 0]; dq to + let mut jump = [0u8; 14]; + jump[..6].copy_from_slice(&[0xFF, 0x25, 0, 0, 0, 0]); + jump[6..].copy_from_slice(&(to as u64).to_le_bytes()); + std::ptr::copy_nonoverlapping(jump.as_ptr(), at as *mut u8, jump.len()); + patched.push(*rva); + done.push(export.to_string()); + } + if !done.is_empty() { + crate::xlog_info!( + "{name}: {} go to XCL's rep movsb / rep stosb – Rosetta cannot resume the runtime's 32-byte stores when one faults past its first half (XCL_RUNTIME_COPIES=0 leaves them)", + done.join(", ") + ); + } +} + +/// memmove / memcpy for a title runtime on Rosetta (`replace_runtime_copies`): forward, or +/// backward when the destination overlaps the source from above. +pub(crate) unsafe extern "C" fn title_memmove(dst: *mut u8, src: *const u8, n: usize) -> *mut u8 { + if (dst as usize).wrapping_sub(src as usize) >= n { + core::arch::asm!("rep movsb", inout("rdi") dst => _, inout("rsi") src => _, inout("rcx") n => _, options(nostack, preserves_flags)); + } else { + core::arch::asm!( + "std", + "rep movsb", + "cld", + inout("rdi") dst.add(n - 1) => _, + inout("rsi") src.add(n - 1) => _, + inout("rcx") n => _, + options(nostack), + ); + } + dst +} + +/// memset for a title runtime on Rosetta (`replace_runtime_copies`). +pub(crate) unsafe extern "C" fn title_memset(dst: *mut u8, c: i32, n: usize) -> *mut u8 { + core::arch::asm!("rep stosb", inout("rdi") dst => _, inout("rcx") n => _, in("al") c as u8, options(nostack, preserves_flags)); + dst +} + +/// `XCL_WIDE_STORES=0` leaves the title's 256-bit stores and VCVTPS2PH as they are (`widestore`). +fn wide_store_helpers() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| crate::util::rosetta() && std::env::var("XCL_WIDE_STORES").map_or(true, |v| v.trim() != "0")) +} + +/// The unwind data's entries of a mapped image: (start, end, flags) – flags bit 0: the +/// function (or the one its entry is chained to) has an exception or termination handler, +/// bit 1: its unwind data could not be read. +pub(crate) unsafe fn unwind_entries(base: usize, size: usize, unwind: (u32, u32)) -> Vec<(u32, u32, u8)> { + let image = std::slice::from_raw_parts(base as *const u8, size); + let word = |at: usize| image.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + image + .get(unwind.0 as usize..(unwind.0 as usize).saturating_add(unwind.1 as usize)) + .unwrap_or_default() + .chunks_exact(12) + .map(|e| { + let (begin, end) = (u32::from_le_bytes([e[0], e[1], e[2], e[3]]), u32::from_le_bytes([e[4], e[5], e[6], e[7]])); + let mut info = u32::from_le_bytes([e[8], e[9], e[10], e[11]]) as usize; + let mut flags = 2u8; + // UNWIND_INFO: version | flags << 3, prologue, code count, frame; codes (even count); + // then the handler, or the chained RUNTIME_FUNCTION + for _ in 0..8 { + let Some(&[vf, _, n, _]) = image.get(info..info + 4).map(|b| <&[u8; 4]>::try_from(b).unwrap()) else { break }; + let f = vf >> 3; + if f & 3 != 0 { + flags = 1; + break; + } + if f & 4 == 0 { + flags = 0; + break; + } + let chained = info + 4 + 2 * ((n as usize + 1) & !1); + let Some(next) = word(chained + 8) else { break }; + info = next as usize; + } + (begin, end, flags) + }) + .collect() +} + +/// Replaces the 256-bit stores and VCVTPS2PH of the image mapped at `base` (relocated, its +/// sections still writable, none of its code run yet) as `widestore` says, and says how many. +/// The helpers get memory of their own within a call's reach of the image, with unwind data, +/// read-only once written; four-byte stores left to a trap are known to `wide_store_trap`. +unsafe fn replace_wide_stores(base: usize, size: usize, code: &[(u32, u32)], unwind: (u32, u32), name: &str) -> usize { + use crate::widestore::{self, Frame, Kind, Patch}; + use windows_sys::Win32::System::Diagnostics::Debug::{FlushInstructionCache, RtlAddFunctionTable, IMAGE_RUNTIME_FUNCTION_ENTRY}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let started = std::time::Instant::now(); + let image = std::slice::from_raw_parts(base as *const u8, size); + let functions = unwind_entries(base, size, unwind); + let plan = widestore::plan(image, base as u64, code, &functions); + for (rva, why) in plan.skipped.iter().take(16) { + crate::xlog_warn!("{name}: a 256-bit store at +{rva:#x} is left as it is ({why:?}) – one that faults on a write-watched page freezes the process on this host"); + } + if plan.sites.is_empty() { + return 0; + } + // helpers, the two kinds of unwind data, one function entry each + let leaf_at = (plan.code.len() + 15) & !15; + let f16c_at = leaf_at + 16; + let table_at = f16c_at + 16; + let entry = std::mem::size_of::(); + let pool_size = (table_at + plan.helpers.len() * entry + 0xFFFF) & !0xFFFF; + let pool = crate::eh::alloc_near(base + size, pool_size); + if pool == 0 { + crate::xlog_error!("{name}: no memory near the image for the helpers of {} 256-bit stores – they stay, and one that faults on a write-watched page freezes the process on this host", plan.sites.len()); + return 0; + } + std::ptr::copy_nonoverlapping(plan.code.as_ptr(), pool as *mut u8, plan.code.len()); + // RIP-relative displacements of moved instructions, now that the helpers have an address + for &(d, end, target) in &plan.fixups { + let rel = target as i64 - (pool as i64 + end as i64); + let Ok(rel) = i32::try_from(rel) else { + VirtualFree(pool as *mut c_void, 0, MEM_RELEASE); + crate::xlog_error!("{name}: a moved RIP-relative operand is out of reach of its helper – the 256-bit stores stay"); + return 0; + }; + ((pool + d as usize) as *mut [u8; 4]).write_unaligned(rel.to_le_bytes()); + } + std::ptr::copy_nonoverlapping(widestore::UNWIND_INFO_LEAF.as_ptr(), (pool + leaf_at) as *mut u8, widestore::UNWIND_INFO_LEAF.len()); + std::ptr::copy_nonoverlapping(widestore::UNWIND_INFO_F16C.as_ptr(), (pool + f16c_at) as *mut u8, widestore::UNWIND_INFO_F16C.len()); + let table = (pool + table_at) as *mut IMAGE_RUNTIME_FUNCTION_ENTRY; + for (k, &(start, end, frame)) in plan.helpers.iter().enumerate() { + let e = &mut *table.add(k); + (e.BeginAddress, e.EndAddress) = (start, end); + e.Anonymous.UnwindInfoAddress = if frame == Frame::F16c { f16c_at } else { leaf_at } as u32; + } + // every patch's bytes, before any is written: a site whose call or jump cannot reach stays + let mut patches: Vec<(usize, Vec)> = Vec::new(); + let mut traps: Vec<(usize, usize)> = Vec::new(); + let mut far = 0usize; + let mut done = [0usize; 4]; + for s in &plan.sites { + let helper = (pool + s.helper as usize) as u64; + let site = base + s.rva as usize; + match s.patch { + Patch::Call { start, len } => { + let Some(b) = widestore::call_site((base + start as usize) as u64, len as usize, helper) else { + far += 1; + continue; + }; + patches.push((base + start as usize, b)); + } + Patch::Slot { slot } => { + let slot = base + slot as usize; + let (Some(call), Some(jump)) = (widestore::call_site(slot as u64, 5, helper), widestore::short_jump(site as u64, slot as u64)) else { + far += 1; + continue; + }; + patches.push((slot, call)); + patches.push((site, jump.to_vec())); + } + // an anchored store: the anchor's call does it (below); a branch into the run that + // lands on the store traps + Patch::Trap | Patch::Anchored { .. } => { + patches.push((site, vec![0xCC; 4])); + traps.push((site, helper as usize)); + } + } + done[Kind::ALL.iter().position(|&k| k == s.store.kind).unwrap_or(0)] += 1; + } + for &(start, len, h) in &plan.anchors { + let Some(b) = widestore::call_site((base + start as usize) as u64, len as usize, (pool + h as usize) as u64) else { + far += 1; + continue; + }; + patches.push((base + start as usize, b)); + } + let mut old = 0u32; + if VirtualProtect(pool as *const c_void, pool_size, PAGE_EXECUTE_READ, &mut old) == 0 + || FlushInstructionCache(GetCurrentProcess(), pool as *const c_void, pool_size) == 0 + || !RtlAddFunctionTable(table, plan.helpers.len() as u32, pool as u64) + { + VirtualFree(pool as *mut c_void, 0, MEM_RELEASE); + crate::xlog_warn!("{name}: failed to prepare executable 256-bit store helpers and their unwind data"); + return 0; + } + // The helpers, their unwind entries and the traps' table must be in place before any title + // byte points at them. + WIDE_STORE_HELPERS.lock().unwrap().push((pool, pool + plan.code.len())); + if !traps.is_empty() { + add_wide_store_traps(&traps); + } + for (at, b) in &patches { + std::ptr::copy_nonoverlapping(b.as_ptr(), *at as *mut u8, b.len()); + } + let kinds: Vec = Kind::ALL.iter().zip(done).filter(|(_, n)| *n != 0).map(|(k, n)| format!("{n} {}", k.name())).collect(); + let [slot, anchored, merged, trap] = plan.short; + crate::xlog_info!( + "{name}: {} stores ({}) call {} helpers at {pool:#x}..{:#x} that store in parts Rosetta resumes – it cannot resume a 256-bit store that faults past its first half, nor a VCVTPS2PH store (XCL_WIDE_STORES=0 leaves them); four-byte ones: {slot} through padding, {anchored} by the helper of an instruction before them, {merged} with a moved neighbour, {trap} by trap; {} on the stack or in the image left{}{}; {} ms", + done.iter().sum::(), + kinds.join(", "), + plan.helpers.len(), + pool + plan.code.len(), + plan.safe_place, + if plan.skipped.is_empty() { String::new() } else { format!("; {} left as they are", plan.skipped.len()) }, + if far != 0 { format!("; {far} out of reach and left") } else { String::new() }, + started.elapsed().as_millis() + ); + done.iter().sum() +} + +/// The 256-bit store helpers' memory, per image: (start, end). +static WIDE_STORE_HELPERS: Mutex> = Mutex::new(Vec::new()); + +/// Whether `addr` is in a 256-bit store helper. +pub fn in_wide_store_helper(addr: usize) -> bool { + WIDE_STORE_HELPERS.try_lock().is_ok_and(|g| g.iter().any(|r| (r.0..r.1).contains(&addr))) +} + +/// Four-byte stores left to a trap: (site, stub, times reached), by site. +static WIDE_STORE_TRAPS: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); + +fn add_wide_store_traps(traps: &[(usize, usize)]) { + static HANDLER: std::sync::Once = std::sync::Once::new(); + { + let mut t = WIDE_STORE_TRAPS.write().unwrap(); + t.extend(traps.iter().map(|&(s, h)| (s, h, std::sync::atomic::AtomicU64::new(0)))); + t.sort_unstable_by_key(|e| e.0); + } + HANDLER.call_once(|| unsafe { + windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(wide_store_trap)); + }); +} + +#[cfg(test)] +pub(crate) fn add_wide_store_traps_for_test(traps: &[(usize, usize)]) { + add_wide_store_traps(traps) +} + +/// A thread at a trapped four-byte store (`int3` there): on to its stub, which does the store +/// in two halves and jumps back past it. Sites reached often are logged: each one costs an +/// exception round trip. +unsafe extern "system" fn wide_store_trap(info: *mut windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_POINTERS) -> i32 { + if info.is_null() || (*info).ExceptionRecord.is_null() || (*info).ContextRecord.is_null() || (*(*info).ExceptionRecord).ExceptionCode as u32 != 0x8000_0003 { + return 0; + } + let ctx = &mut *(*info).ContextRecord; + let Ok(t) = WIDE_STORE_TRAPS.try_read() else { return 0 }; + let rip = ctx.Rip as usize; + let find = |a: usize| t.binary_search_by_key(&a, |e| e.0).ok(); + let Some(k) = find(rip).or_else(|| find(rip.wrapping_sub(1))) else { return 0 }; + let (site, stub, hits) = (&t[k].0, t[k].1, &t[k].2); + ctx.Rip = stub as u64; + let n = hits.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n == 1 || n == 1000 || n == 100_000 { + crate::log::try_write( + crate::log::Level::Warn, + format_args!("256-bit store at {} reached by trap {n} time(s) – each costs an exception", crate::modules::describe_address(*site)), + ); + } + -1 // EXCEPTION_CONTINUE_EXECUTION +} + fn masked_store_helpers() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| { @@ -544,6 +844,58 @@ pub fn on_tls_event(reason: u32) { mod tests { use super::*; + /// The runtime's copies on Rosetta: memmove forward and backward over every overlap and + /// length up to 300 bytes (as `copy` would do it), memset, and the value both return. + #[test] + fn title_memmove_and_memset_match_the_runtime_semantics() { + for n in [0usize, 1, 7, 31, 32, 33, 255, 300] { + for (from, to) in [(0usize, 400usize), (400, 0), (10, 20), (20, 10), (50, 50), (0, 1), (1, 0)] { + let mut want: Vec = (0..800u32).map(|i| (i * 7 + 3) as u8).collect(); + let mut got = want.clone(); + want.copy_within(from..from + n, to); + let p = got.as_mut_ptr(); + let r = unsafe { title_memmove(p.add(to), p.add(from), n) }; + assert_eq!(r, unsafe { p.add(to) }); + assert_eq!(got, want, "n {n}, {from} -> {to}"); + } + let mut buf = vec![0xA5u8; 400]; + let r = unsafe { title_memset(buf.as_mut_ptr().add(9), 0x1C3, n) }; + assert_eq!(r, unsafe { buf.as_mut_ptr().add(9) }); + assert!(buf[..9].iter().all(|&b| b == 0xA5) && buf[9..9 + n].iter().all(|&b| b == 0xC3) && buf[9 + n..].iter().all(|&b| b == 0xA5)); + } + } + + /// The exports' entry points become `jmp [rip + 0]` to XCL's copies (memcpy shares + /// memmove's code: patched once); the bytes around them are left as they were. + #[test] + fn runtime_copy_entry_points_jump_to_xcls() { + let mut image = vec![0xCCu8; 0x100]; + let base = image.as_mut_ptr() as usize; + let mut exports = OwnedExports::default(); + exports.by_name.insert("memmove".into(), pe::ExportTarget::Rva(0x10)); + exports.by_name.insert("memcpy".into(), pe::ExportTarget::Rva(0x10)); + exports.by_name.insert("memset".into(), pe::ExportTarget::Rva(0x40)); + exports.by_name.insert("memchr".into(), pe::ExportTarget::Rva(0x80)); + unsafe { replace_runtime_copies(base, image.len(), &exports, "vcruntime140.dll") }; + // (a function's address is not unique in Rust: what the jumps reach is run instead) + let target = |at: usize| { + assert_eq!(image[at..at + 6], [0xFF, 0x25, 0, 0, 0, 0]); + u64::from_le_bytes(image[at + 6..at + 14].try_into().unwrap()) as usize + }; + let (mv, set) = (target(0x10), target(0x40)); + assert!(image[..0x10].iter().chain(&image[0x1E..0x40]).chain(&image[0x4E..]).all(|&b| b == 0xCC)); + unsafe { + let mv: unsafe extern "C" fn(*mut u8, *const u8, usize) -> *mut u8 = std::mem::transmute(mv); + let set: unsafe extern "C" fn(*mut u8, i32, usize) -> *mut u8 = std::mem::transmute(set); + let mut b: Vec = (0..64).collect(); + let p = b.as_mut_ptr(); + assert_eq!(mv(p.add(4), p, 40), p.add(4)); + assert_eq!(b[4..44], (0..40).collect::>()[..]); + assert_eq!(set(p, 0xEE, 3), p); + assert_eq!(b[..5], [0xEE, 0xEE, 0xEE, 3, 0]); + } + } + #[test] fn masked_store_override_cannot_enable_rewriting_without_rosetta() { assert!(!masked_store_helpers_for(false, Some("1"))); diff --git a/crates/xcl/src/log.rs b/crates/xcl/src/log.rs index 2e72e12..9ddf51e 100644 --- a/crates/xcl/src/log.rs +++ b/crates/xcl/src/log.rs @@ -6,7 +6,7 @@ use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use std::sync::{Mutex, OnceLock}; -use std::time::Instant; +use std::time::{Duration, Instant}; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] #[repr(u8)] @@ -73,6 +73,8 @@ pub fn write(level: Level, args: std::fmt::Arguments<'_>) { if !enabled(level) { return; } + #[cfg(test)] + kept::note(args); let t = START.get_or_init(Instant::now).elapsed().as_secs_f64(); let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; let line = format!("[{t:9.3}][{tid:5}][{}] {args}\n", level.tag()); @@ -103,12 +105,208 @@ pub(crate) fn try_write(level: Level, args: std::fmt::Arguments<'_>) { return; } let Ok(mut file) = FILE.try_lock() else { return }; + put(&mut file, level, args); +} + +/// `try_write_soon` tries the log file again this many times while another thread writes, each +/// try `SOON_GAP` after the one before at the earliest, and none begun once `SOON` has passed: +/// about 5 ms – many times what one write holds the file (a line, or a thread dump's one write) –, +/// plus at most the one yield of the processor before the last try. +const SOON_TRIES: u32 = 200; +const SOON_GAP: Duration = Duration::from_micros(25); +const SOON: Duration = Duration::from_millis(5); + +/// `try_write` for a line that must not be lost to another thread's write (the exception handler's +/// "the title's stall watchdog … resuming" lines: one fire may be the only record of it): while +/// the log file is busy it is tried again (`SOON_TRIES`, `SOON`), then the line is given up as +/// `try_write` gives it up at once. Never a blocking wait – a thread that holds the file may be +/// suspended, or be the very thread an exception interrupted inside a write – and nothing +/// allocated. False: the file stayed busy (or a panic while it was held poisoned it), the line is +/// lost; true: written, or nothing to write it to (no log file, its level off). +pub(crate) fn try_write_soon(level: Level, args: std::fmt::Arguments<'_>) -> bool { + if !enabled(level) { + return true; + } + let started = Instant::now(); + let mut tries = 0u32; + #[cfg(test)] + let mut waiting = soon_test::Waiting(None); + let mut file = loop { + match FILE.try_lock() { + Ok(file) => break file, + Err(std::sync::TryLockError::WouldBlock) if tries < SOON_TRIES && started.elapsed() < SOON => { + tries += 1; + #[cfg(test)] + waiting.note(); + std::thread::yield_now(); + // (the next try SOON_GAP after this one at the earliest: the tries span SOON) + while started.elapsed() < SOON_GAP * tries { + std::hint::spin_loop(); + } + } + Err(_) => return false, + } + }; + #[cfg(test)] + soon_test::tried(tries); + put(&mut file, level, args); + true +} + +/// `args` as a line of the log file, if there is one (`file`: the file's lock, held). +fn put(file: &mut Option, level: Level, args: std::fmt::Arguments<'_>) { + // (tests: the test process has no log file – `init` runs only in host_main –, so the line is + // recorded here, before the file is looked at: a line that is never put shows as missing) + #[cfg(test)] + soon_test::seen(args); let Some(file) = file.as_mut() else { return }; let time = START.get().map_or(0.0, |start| start.elapsed().as_secs_f64()); let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; let _ = writeln!(file, "[{time:9.3}][{tid:5}][{}] {args}", level.tag()); } +/// (tests) What `try_write_soon` did: the threads in its tries now, and on each thread the last +/// line given to `put` (what it and `try_write` write) – the test process has no log file to read +/// it back from. +#[cfg(test)] +pub(crate) mod soon_test { + use std::cell::{Cell, RefCell}; + use std::sync::atomic::{AtomicU32, Ordering}; + + /// the ids of the threads that found the log file busy and try again now + static WAITING: [AtomicU32; 8] = [const { AtomicU32::new(0) }; 8]; + + thread_local! { + /// this thread's last line given to `put` (its first 320 bytes, the length) and how many + /// times the `try_write_soon` that put it tried again first (0: `try_write`'s) + static SEEN: RefCell<([u8; 320], usize, u32)> = const { RefCell::new(([0; 320], 0, 0)) }; + /// the tries of the `try_write_soon` whose line `put` is given next + static TRIED: Cell = const { Cell::new(0) }; + } + + /// this thread's place in `WAITING` while it tries again (taken at its first try again) + pub(super) struct Waiting(pub(super) Option); + + impl Waiting { + pub(super) fn note(&mut self) { + if self.0.is_some() { + return; + } + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + self.0 = WAITING.iter().position(|w| w.compare_exchange(0, tid, Ordering::AcqRel, Ordering::Relaxed).is_ok()); + } + } + + impl Drop for Waiting { + fn drop(&mut self) { + if let Some(i) = self.0 { + WAITING[i].store(0, Ordering::Release); + } + } + } + + /// `try_write_soon` took the file after `tries` tries again: for the line it gives `put` next + pub(super) fn tried(tries: u32) { + TRIED.with(|t| t.set(tries)); + } + + /// `put` was given `args` on this thread + pub(super) fn seen(args: std::fmt::Arguments<'_>) { + /// the line's first bytes into a fixed buffer (nothing allocated: an exception handler + /// writes these lines) + struct Cut<'a>(&'a mut [u8], usize); + impl std::fmt::Write for Cut<'_> { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + let n = s.len().min(self.0.len() - self.1); + self.0[self.1..self.1 + n].copy_from_slice(&s.as_bytes()[..n]); + self.1 += n; + Ok(()) + } + } + let tries = TRIED.with(|t| t.replace(0)); + SEEN.with(|s| { + let mut s = s.borrow_mut(); + let (buf, len, t) = &mut *s; + let mut cut = Cut(buf, 0); + let _ = std::fmt::write(&mut cut, args); + (*len, *t) = (cut.1, tries); + }); + } + + /// Whether thread `tid` is in `try_write_soon`'s tries now. + pub(crate) fn waiting(tid: u32) -> bool { + WAITING.iter().any(|w| w.load(Ordering::Acquire) == tid) + } + + /// This thread's last line given to `put` – written, had there been a log file –, and how many + /// times the `try_write_soon` that put it tried again first – taken (None: no line since the + /// last look). + pub(crate) fn take_seen() -> Option<(String, u32)> { + SEEN.with(|s| { + let mut s = s.borrow_mut(); + let (buf, len, tries) = &mut *s; + let line = (*len > 0).then(|| String::from_utf8_lossy(&buf[..*len]).into_owned()); + *len = 0; + line.map(|l| (l, *tries)) + }) + } + + /// The log file's lock, held by the caller until the guard drops (other threads' log lines + /// wait or are given up meanwhile; the test process has no log file). + pub(crate) fn hold_file() -> std::sync::MutexGuard<'static, Option> { + super::FILE.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +/// (tests) The lines `write` is given on a thread that keeps them (`keep`) – what follows the +/// time, the thread and the level: the test process has no log file to read them back from, and a +/// line's text is the only way a test sees what a log call wrote. +#[cfg(test)] +pub(crate) mod kept { + use std::cell::RefCell; + + thread_local! { + /// this thread's lines since the last look (None: not kept) + static LINES: RefCell>> = const { RefCell::new(None) }; + } + + /// This thread's lines are kept while the value lives. + pub(crate) struct Kept(()); + + pub(crate) fn keep() -> Kept { + LINES.with(|l| *l.borrow_mut() = Some(Vec::new())); + Kept(()) + } + + impl Kept { + /// the lines since `keep` or the last `take`, the first first + pub(crate) fn take(&self) -> Vec { + LINES.with(|l| l.borrow_mut().as_mut().map(std::mem::take).unwrap_or_default()) + } + } + + impl Drop for Kept { + fn drop(&mut self) { + LINES.with(|l| *l.borrow_mut() = None); + } + } + + /// `write` was given `args` on this thread + pub(super) fn note(args: std::fmt::Arguments<'_>) { + if LINES.with(|l| l.borrow().is_none()) { + return; + } + // (formatted before the record is taken: an argument that logs as it is formatted is kept + // first, not a second borrow) + let line = args.to_string(); + LINES.with(|l| { + if let Some(v) = l.borrow_mut().as_mut() { + v.push(line); + } + }); + } +} + #[macro_export] macro_rules! xlog_error { ($($a:tt)*) => { $crate::log::write($crate::log::Level::Error, format_args!($($a)*)) } } #[macro_export] diff --git a/crates/xcl/src/modules.rs b/crates/xcl/src/modules.rs index 31434de..0c0780e 100644 --- a/crates/xcl/src/modules.rs +++ b/crates/xcl/src/modules.rs @@ -180,6 +180,9 @@ pub fn describe_address(addr: usize) -> String { if crate::loader::in_masked_store_helper(addr) { return format!("{addr:#x} (a masked-store helper)"); } + if crate::loader::in_wide_store_helper(addr) { + return format!("{addr:#x} (a 256-bit store helper)"); + } format!("{addr:#x}") } diff --git a/crates/xcl/src/resolver.rs b/crates/xcl/src/resolver.rs index ee82916..89e1f6f 100644 --- a/crates/xcl/src/resolver.rs +++ b/crates/xcl/src/resolver.rs @@ -316,6 +316,12 @@ pub fn resolve_import(dll: &str, what: &ImportName, importer: &str, delay: bool) let key = dll_key(dll); let (mut addr, source) = resolve_inner(&key, what, 0); crate::xlog_debug!("import {importer}: {key}!{what} → {source:?}"); + // (local diagnostic `XCL_WATCH_WAITS`) the title's waits are wrapped + if let ImportName::Name { name, .. } = what { + if let Some(w) = crate::waitwatch::wrap(name, addr) { + addr = w; + } + } if let Some(f) = trace_filter() { if f.wants(&key, &fname(what), &source) { addr = crate::hle::d3d12x::guard::make_call_tracer(addr, format!("{key}!{what}")); @@ -379,6 +385,9 @@ pub fn load_library(name: &str) -> Option { if let Some(h) = system_module(name) { return Some(h); } + if m.real_dll { + return None; + } } return Some(modules::hle_handle(m.name)); } @@ -412,6 +421,15 @@ pub fn load_library(name: &str) -> Option { /// GetProcAddress as seen by the game. Missing functions return None (no stub) so /// that optional-API probing works. pub fn get_proc_address(h: usize, what: &ImportName) -> Option { + let a = get_proc_address_raw(h, what)?; + // (local diagnostic `XCL_WATCH_WAITS`: the STL looks WaitOnAddress up at run time) + match what { + ImportName::Name { name, .. } => Some(crate::waitwatch::wrap(name, a).unwrap_or(a)), + ImportName::Ordinal(_) => Some(a), + } +} + +fn get_proc_address_raw(h: usize, what: &ImportName) -> Option { let reg = registry(); if let Some(name) = modules::hle_name_by_handle(h) { let r = match reg.module_by_name(&name).or_else(|| reg.hle_for(&name)) { diff --git a/crates/xcl/src/waitwatch.rs b/crates/xcl/src/waitwatch.rs new file mode 100644 index 0000000..723f206 --- /dev/null +++ b/crates/xcl/src/waitwatch.rs @@ -0,0 +1,1728 @@ +//! Local diagnostic `XCL_WATCH_WAITS=1`: where the title's threads wait. +//! +//! The title's waits – on handles, condition variables, addresses, completion ports, sleeps, +//! and locks it could not take at once – are wrapped when its imports are resolved +//! (`resolver::resolve_import`, `resolver::get_proc_address`). Each thread notes in a slot of +//! its own, without a lock, what it waits in, since when and the title's call stack there. A +//! watcher thread looks every 5 s: a thread in one wait for 10 s or more, or one that keeps +//! coming back to the same wait from the same place (a polling loop), is logged with that +//! stack. Nothing is suspended – a stuck title is read as it is. MWAITX loops the exception +//! handler emulates (`eh`) are counted by address, with the address they watch, and the busy +//! ones are logged too. + +use std::cell::Cell; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering}; + +#[link(name = "kernel32")] +extern "system" { + fn GetCurrentThreadId() -> u32; + fn RtlCaptureStackBackTrace(skip: u32, n: u32, frames: *mut *mut c_void, hash: *mut u32) -> u16; + fn TryAcquireSRWLockExclusive(lock: usize) -> u8; + fn TryAcquireSRWLockShared(lock: usize) -> u8; + fn TryEnterCriticalSection(cs: usize) -> i32; + fn GetModuleHandleW(name: *const u16) -> usize; + fn OpenThread(access: u32, inherit: i32, tid: u32) -> usize; + fn GetExitCodeThread(h: usize, code: *mut u32) -> i32; + fn CloseHandle(h: usize) -> i32; + fn GetThreadTimes(h: usize, created: *mut u64, exited: *mut u64, kernel: *mut u64, user: *mut u64) -> i32; +} + +/// A thread's CPU time so far (ms; kernel + user) and whether it still runs. +unsafe fn thread_cpu(tid: u32) -> Option<(u64, bool)> { + let h = OpenThread(0x0800, 0, tid); // THREAD_QUERY_LIMITED_INFORMATION + if h == 0 { + return None; + } + let (mut c, mut e, mut k, mut u) = (0u64, 0u64, 0u64, 0u64); + let mut code = 0u32; + let times = GetThreadTimes(h, &mut c, &mut e, &mut k, &mut u) != 0; + let alive = GetExitCodeThread(h, &mut code) != 0 && code == 259; + CloseHandle(h); + times.then_some(((k + u) / 10_000, alive)) +} + +/// The functions wrapped, by index (`REAL` holds what each import resolved to). +const KINDS: [&str; 15] = [ + "WaitForSingleObject", + "WaitForSingleObjectEx", + "WaitForMultipleObjects", + "WaitForMultipleObjectsEx", + "SleepConditionVariableSRW", + "SleepConditionVariableCS", + "WaitOnAddress", + "Sleep", + "SleepEx", + "SignalObjectAndWait", + "GetQueuedCompletionStatus", + "GetQueuedCompletionStatusEx", + "AcquireSRWLockExclusive", + "AcquireSRWLockShared", + "EnterCriticalSection", +]; + +static REAL: [AtomicUsize; KINDS.len()] = [const { AtomicUsize::new(0) }; KINDS.len()]; + +/// XCL's own blocking points (kinds `KINDS.len()` + index): a title thread held inside XCL. +const XCL_KINDS: [&str; 8] = [ + "XCL: waiting for the GPU (fence)", + "XCL: WaitFrameEventX", + "XCL: waiting for a pipeline still being built", + "XCL: building a pipeline on this thread", + "XCL: building a pipeline (worker)", + "XCL: waiting for a sparse window's queue", + "XCL: waiting for the DXIL cache mutex", + "XCL: building a pipeline (big lane)", +]; +pub const X_GPU_FENCE: usize = 0; +pub const X_FRAME_EVENT: usize = 1; +pub const X_PIPELINE_WAIT: usize = 2; +pub const X_BUILD_HERE: usize = 3; +pub const X_BUILD_WORKER: usize = 4; +pub const X_SPARSE: usize = 5; +pub const X_DXC_MUTEX: usize = 6; +pub const X_BUILD_BIG: usize = 7; + +fn kind_name(k: u32) -> &'static str { + let i = k as usize - 1; + if i < KINDS.len() { + KINDS[i] + } else if i < KINDS.len() + XCL_KINDS.len() { + XCL_KINDS[i - KINDS.len()] + } else { + ANY.get(i - KINDS.len() - XCL_KINDS.len()).map_or("?", |a| a.0) + } +} + +/// The calling thread is held in XCL's own `what` (`X_*`) until the guard drops. +pub struct Marker(Option<(&'static Slot, bool)>); + +impl Drop for Marker { + fn drop(&mut self) { + leave(self.0); + } +} + +/// The XCL entry point a thread is in, until the guard drops (the one it was in before then). +pub struct Api(Option<(&'static Slot, usize, usize, u64)>); + +impl Drop for Api { + fn drop(&mut self) { + if let Some((s, p, l, t)) = self.0 { + s.api_since.store(t, Ordering::Relaxed); + s.api_len.store(l, Ordering::Relaxed); + s.api_ptr.store(p, Ordering::Release); + } + } +} + +/// The calling thread is in XCL's entry point `name` (no stack is taken: cheap). +#[inline] +pub fn api(name: &'static str) -> Api { + if !on() { + return Api(None); + } + let Some(s) = slot() else { return Api(None) }; + let prev = (s.api_ptr.load(Ordering::Relaxed), s.api_len.load(Ordering::Relaxed), s.api_since.load(Ordering::Relaxed)); + s.api_since.store(now_ms(), Ordering::Relaxed); + s.api_len.store(name.len(), Ordering::Relaxed); + s.api_ptr.store(name.as_ptr() as usize, Ordering::Release); + Api(Some((s, prev.0, prev.1, prev.2))) +} + +fn api_of(s: &Slot, now: u64) -> String { + let p = s.api_ptr.load(Ordering::Acquire); + if p == 0 { + return String::new(); + } + let l = s.api_len.load(Ordering::Relaxed).min(64); + let name = String::from_utf8_lossy(unsafe { std::slice::from_raw_parts(p as *const u8, l) }).into_owned(); + format!(" | inside XCL's {name} for {:.1} s", now.saturating_sub(s.api_since.load(Ordering::Relaxed)) as f64 / 1000.0) +} + +/// Mark the calling thread as held in XCL's own `what` (`X_*`), `arg` naming what for. +pub fn xcl(what: usize, arg: u64) -> Marker { + if !on() { + return Marker(None); + } + start_watcher(); + Marker(unsafe { enter(KINDS.len() + what, arg, true) }) +} + +/// `xcl` for XCL's pipeline states (`X_PIPELINE_WAIT`, `X_BUILD_*`): `hash` the console program, +/// `info` its stage and DXIL size (`program_info`) – named in the waits lines. +#[inline(never)] +pub fn xcl_program(what: usize, hash: u64, info: u64) -> Marker { + if !on() { + return Marker(None); + } + start_watcher(); + Marker(unsafe { enter_with(KINDS.len() + what, hash, info, true) }) +} + +/// (pso_async) This thread's pipeline state now has `info` (its translation said its size). +pub fn set_program_info(info: u64) { + if !on() { + return; + } + if let Some(s) = slot() { + if pipeline_kind(s.kind.load(Ordering::Relaxed)) && s.in_call.load(Ordering::Relaxed) != 0 { + s.arg2.store(info, Ordering::Relaxed); + } + } +} + +/// A program's stage letter (b'C', b'G', b'M'), KB of DXIL and whether estimated, for `xcl_program`. +pub fn program_info(kind: u8, kb: u32, estimated: bool) -> u64 { + (1 << 63) | ((estimated as u64) << 40) | ((kind as u64) << 32) | kb as u64 +} + +fn xcl_index(kind: u32) -> Option { + (kind as usize).checked_sub(1 + KINDS.len()).filter(|&i| i < XCL_KINDS.len()) +} + +/// XCL's pipeline states – waits and builds – name a program (`describe_arg`). +fn pipeline_kind(kind: u32) -> bool { + matches!(xcl_index(kind), Some(X_PIPELINE_WAIT | X_BUILD_HERE | X_BUILD_WORKER | X_BUILD_BIG)) +} + +fn build_kind(kind: u32) -> bool { + matches!(xcl_index(kind), Some(X_BUILD_HERE | X_BUILD_WORKER | X_BUILD_BIG)) +} + +/// What a state's argument says: a pipeline state's program "56c0cd3b82a00c6e, CS, 29059 KB DXIL", +/// else the handle / address / value as before. +fn describe_arg(kind: u32, arg: u64, arg2: u64) -> String { + if pipeline_kind(kind) && arg2 >> 63 == 1 { + let kb = arg2 as u32; + let what = match (arg2 >> 32) as u8 { + b'C' => "CS", + b'G' => "VS", + b'M' => "MS", + _ => "pipeline", + }; + let size = match (kb, (arg2 >> 40) & 1) { + (0, _) => "DXIL size not known".to_string(), + (k, 1) => format!("~{k} KB DXIL"), + (k, _) => format!("{k} KB DXIL"), + }; + return format!("{arg:016x}, {what}, {size}"); + } + format!("{arg:#x}") +} + +/// The threads held in XCL's own states now (alive): "thread 460: XCL: building a pipeline on +/// this thread for 25.3 s (56c0cd3b82a00c6e, CS, 29059 KB DXIL)" (16 at most). Empty when off. +pub fn in_xcl() -> Vec { + if !on() { + return Vec::new(); + } + let now = now_ms(); + let used = USED.load(Ordering::Relaxed).min(SLOTS); + TABLE[..used].iter().filter_map(|s| in_xcl_entry(s, now)).take(16).collect() +} + +/// One thread of `in_xcl`: "thread 460: XCL: building …" (`held_text`) – None unless the slot's +/// thread is in one of XCL's own states now, in a call, and alive. +fn in_xcl_entry(s: &Slot, now: u64) -> Option { + let kind = s.kind.load(Ordering::Acquire); + xcl_index(kind)?; + if s.in_call.load(Ordering::Acquire) == 0 { + return None; + } + let tid = s.tid.load(Ordering::Relaxed); + unsafe { thread_cpu(tid) }.filter(|t| t.1)?; + Some(format!("thread {tid}: {}", held_text(s, kind, now))) +} + +/// A thread held in XCL's own state `kind`, as `in_xcl` says it: "XCL: waiting for a pipeline +/// still being built for 19.3 s (3b9aa67a004b9371, CS, 222 KB DXIL) (14 calls, this one 1.2 s)" +/// – the calls at its end when the state merged several (`calls_tail`). +fn held_text(s: &Slot, kind: u32, now: u64) -> String { + format!( + "{} for {:.1} s ({}){}", + kind_name(kind), + now.saturating_sub(s.since.load(Ordering::Relaxed)) as f64 / 1000.0, + describe_arg(kind, s.arg.load(Ordering::Relaxed), s.arg2.load(Ordering::Relaxed)), + calls_tail(s, now) + ) +} + +/// What an in-call state's text ends with when the state merged several calls (`same_state`: the +/// same wait from the same place again within 500 ms, binds waiting for one pipeline after another): +/// how many, and how long the one it is in now has gone on – a merged "19.3 s" of pipeline waits +/// may be many waits of 1.5 s at most (run 65's thread 472). Nothing for a state of one call: its +/// length is its call's. +fn calls_tail(s: &Slot, now: u64) -> String { + let calls = s.calls.load(Ordering::Relaxed); + if calls < 2 { + return String::new(); + } + format!(" ({calls} calls, this one {:.1} s)", now.saturating_sub(s.call_since.load(Ordering::Relaxed)) as f64 / 1000.0) +} + +/// A thread in a call, as the snapshot says it: "in SleepConditionVariableSRW for 12.0 s" (`owner`: +/// ", held by thread 8" for a critical section) – the calls at its end when the state merged +/// several (`calls_tail`). +fn in_text(s: &Slot, kind: u32, now: u64, owner: &str) -> String { + format!("in {} for {:.1} s{owner}{}", kind_name(kind), now.saturating_sub(s.since.load(Ordering::Relaxed)) as f64 / 1000.0, calls_tail(s, now)) +} + +/// Whether `XCL_WATCH_WAITS=1`. +pub fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WATCH_WAITS").is_ok_and(|v| v.trim() == "1")) +} + +/// The wrapper standing for `name` resolved to `real` (None: not watched, or watching is off). +pub fn wrap(name: &str, real: usize) -> Option { + if !on() || real == 0 { + return None; + } + let k = KINDS.iter().position(|&n| n == name)?; + // (the first address resolved is the one called: they are all the same function) + let _ = REAL[k].compare_exchange(0, real, Ordering::AcqRel, Ordering::Acquire); + start_watcher(); + let w: usize = match k { + 0 => wait_single as usize, + 1 => wait_single_ex as usize, + 2 => wait_multiple as usize, + 3 => wait_multiple_ex as usize, + 4 => sleep_cv_srw as usize, + 5 => sleep_cv_cs as usize, + 6 => wait_on_address as usize, + 7 => sleep as usize, + 8 => sleep_ex as usize, + 9 => signal_and_wait as usize, + 10 => queued_status as usize, + 11 => queued_status_ex as usize, + 12 => srw_exclusive as usize, + 13 => srw_shared as usize, + _ => enter_cs as usize, + }; + Some(w) +} + +const SLOTS: usize = 1024; +const FRAMES: usize = 16; + +/// One thread's wait state (written only by that thread; read by the watcher). +struct Slot { + tid: AtomicU32, + /// `KINDS` index + 1 (0: never waited) + kind: AtomicU32, + /// the handle / address / milliseconds waited on + arg: AtomicU64, + /// a pipeline state's program: its stage and size (`program_info`; 0: none) + arg2: AtomicU64, + /// when this state began (ms, `log::uptime`) + since: AtomicU64, + /// when the last call in it returned + last_exit: AtomicU64, + in_call: AtomicU32, + /// the calls in this state (more than one: `same_state` merged them), and when the latest began + calls: AtomicU64, + call_since: AtomicU64, + /// the title's call stack at the wait (the first frame outside XCL first) + frames: [AtomicUsize; FRAMES], + /// (watcher) CPU time (ms) at the last snapshot + cpu_seen: AtomicU64, + /// the XCL entry point the thread is in (a `&'static str`: pointer, length) and since when + api_ptr: AtomicUsize, + api_len: AtomicUsize, + api_since: AtomicU64, + /// (watcher) the state last logged – its start, what and where, and when + reported: AtomicU64, + reported_sig: AtomicU64, + reported_at: AtomicU64, +} + +impl Slot { + const fn new() -> Slot { + Slot { + tid: AtomicU32::new(0), + kind: AtomicU32::new(0), + arg: AtomicU64::new(0), + arg2: AtomicU64::new(0), + since: AtomicU64::new(0), + last_exit: AtomicU64::new(0), + in_call: AtomicU32::new(0), + calls: AtomicU64::new(0), + call_since: AtomicU64::new(0), + frames: [const { AtomicUsize::new(0) }; FRAMES], + cpu_seen: AtomicU64::new(0), + api_ptr: AtomicUsize::new(0), + api_len: AtomicUsize::new(0), + api_since: AtomicU64::new(0), + reported: AtomicU64::new(u64::MAX), + reported_sig: AtomicU64::new(0), + reported_at: AtomicU64::new(0), + } + } +} + +static TABLE: [Slot; SLOTS] = [const { Slot::new() }; SLOTS]; +static USED: AtomicUsize = AtomicUsize::new(0); + +thread_local! { + static MINE: Cell = const { Cell::new(usize::MAX) }; + static MONITORED: Cell = const { Cell::new(0) }; +} + +fn now_ms() -> u64 { + (crate::log::uptime() * 1000.0) as u64 +} + +fn slot() -> Option<&'static Slot> { + let i = MINE.with(|m| { + if m.get() == usize::MAX { + let i = USED.fetch_add(1, Ordering::Relaxed); + m.set(i); + if let Some(s) = TABLE.get(i) { + s.tid.store(unsafe { GetCurrentThreadId() }, Ordering::Relaxed); + } + } + m.get() + }); + TABLE.get(i) +} + +/// xcl.exe's image: [base, end) +fn own_image() -> (usize, usize) { + static R: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new(); + *R.get_or_init(|| unsafe { + let base = GetModuleHandleW(std::ptr::null()); + if base == 0 { + return (0, 0); + } + let pe = base + (*((base + 0x3C) as *const u32)) as usize; + let size = *((pe + 0x18 + 0x38) as *const u32) as usize; + (base, base + size) + }) +} + +/// `keep_own`: XCL's own frames too (a wait inside XCL), else from the title's first frame. +/// A wait inside a wait already noted (a title's WaitForSingleObject reaching kernelbase's +/// NtWaitForSingleObject) only counts: the outer one stays what the thread is in. +#[inline(always)] +unsafe fn enter(kind: usize, arg: u64, keep_own: bool) -> Option<(&'static Slot, bool)> { + enter_with(kind, arg, 0, keep_own) +} + +/// `enter` with `arg2` (a pipeline state's program: `program_info`). Its own frame is the one the +/// stack is taken from, so the frames start where they did before 0023. +#[inline(never)] +unsafe fn enter_with(kind: usize, arg: u64, arg2: u64, keep_own: bool) -> Option<(&'static Slot, bool)> { + let s = slot()?; + if s.in_call.fetch_add(1, Ordering::AcqRel) > 0 { + return Some((s, false)); + } + let mut f = [std::ptr::null_mut::(); FRAMES + 4]; + let n = RtlCaptureStackBackTrace(1, f.len() as u32, f.as_mut_ptr(), std::ptr::null_mut()) as usize; + let (lo, hi) = own_image(); + let first = if keep_own { 1.min(n) } else { f[..n].iter().position(|&p| !(lo..hi).contains(&(p as usize))).unwrap_or(n) }; + let title = &f[first..n]; + let at = |i: usize| title.get(i).map_or(0, |&p| p as usize); + note_state(s, kind as u32 + 1, arg, arg2, at, now_ms()); + Some((s, true)) +} + +/// The same wait from the same place again soon after the last one returned is one state – but a +/// build of another program is a state of its own (a worker's builds one after another are not +/// one long build); binds waiting for one pipeline after another stay one polling state. A state +/// in a call says how many calls it merged and how long the current one has gone on (`calls_tail`). +fn same_state(prev: (u32, [usize; 2], u64, u64), kind: u32, frames: [usize; 2], arg: u64, now: u64) -> bool { + let (k, f, parg, last_exit) = prev; + k == kind && f == frames && now.saturating_sub(last_exit) < 500 && !(build_kind(kind) && parg != arg) +} + +/// A wait begins in `s` (`enter_with`'s state update): a new state unless `same_state`; its +/// argument and the program info `arg2` are the latest call's. +fn note_state(s: &Slot, k: u32, arg: u64, arg2: u64, at: impl Fn(usize) -> usize, now: u64) { + let prev = (s.kind.load(Ordering::Relaxed), [s.frames[0].load(Ordering::Relaxed), s.frames[1].load(Ordering::Relaxed)], s.arg.load(Ordering::Relaxed), s.last_exit.load(Ordering::Relaxed)); + if !same_state(prev, k, [at(0), at(1)], arg, now) { + s.since.store(now, Ordering::Relaxed); + s.calls.store(0, Ordering::Relaxed); + for (i, fr) in s.frames.iter().enumerate() { + fr.store(at(i), Ordering::Relaxed); + } + s.kind.store(k, Ordering::Release); + } + s.arg.store(arg, Ordering::Relaxed); + s.arg2.store(arg2, Ordering::Relaxed); + s.call_since.store(now, Ordering::Relaxed); + s.calls.fetch_add(1, Ordering::Relaxed); +} + +fn leave(s: Option<(&Slot, bool)>) { + if let Some((s, outer)) = s { + if outer { + s.last_exit.store(now_ms(), Ordering::Relaxed); + } + s.in_call.fetch_sub(1, Ordering::AcqRel); + } +} + +unsafe fn real(k: usize) -> T { + std::mem::transmute_copy(&REAL[k].load(Ordering::Relaxed)) +} + +unsafe extern "system" fn wait_single(h: usize, ms: u32) -> u32 { + let s = enter(0, h as u64, false); + let r = real:: u32>(0)(h, ms); + leave(s); + r +} + +unsafe extern "system" fn wait_single_ex(h: usize, ms: u32, alertable: i32) -> u32 { + let s = enter(1, h as u64, false); + let r = real:: u32>(1)(h, ms, alertable); + leave(s); + r +} + +unsafe fn first_handle(n: u32, hs: *const usize) -> u64 { + let first = if n > 0 && !hs.is_null() { *hs as u64 } else { 0 }; + (n as u64) << 48 | (first & 0xFFFF_FFFF_FFFF) +} + +unsafe extern "system" fn wait_multiple(n: u32, hs: *const usize, all: i32, ms: u32) -> u32 { + let s = enter(2, first_handle(n, hs), false); + let r = real:: u32>(2)(n, hs, all, ms); + leave(s); + r +} + +unsafe extern "system" fn wait_multiple_ex(n: u32, hs: *const usize, all: i32, ms: u32, alertable: i32) -> u32 { + let s = enter(3, first_handle(n, hs), false); + let r = real:: u32>(3)(n, hs, all, ms, alertable); + leave(s); + r +} + +unsafe extern "system" fn sleep_cv_srw(cv: usize, lock: usize, ms: u32, flags: u32) -> i32 { + let s = enter(4, cv as u64, false); + let r = real:: i32>(4)(cv, lock, ms, flags); + leave(s); + r +} + +unsafe extern "system" fn sleep_cv_cs(cv: usize, cs: usize, ms: u32) -> i32 { + let s = enter(5, cv as u64, false); + let r = real:: i32>(5)(cv, cs, ms); + leave(s); + r +} + +unsafe extern "system" fn wait_on_address(addr: usize, cmp: usize, size: usize, ms: u32) -> i32 { + let s = enter(6, addr as u64, false); + let r = real:: i32>(6)(addr, cmp, size, ms); + leave(s); + r +} + +unsafe extern "system" fn sleep(ms: u32) { + let s = enter(7, ms as u64, false); + real::(7)(ms); + leave(s); +} + +unsafe extern "system" fn sleep_ex(ms: u32, alertable: i32) -> u32 { + let s = enter(8, ms as u64, false); + let r = real:: u32>(8)(ms, alertable); + leave(s); + r +} + +unsafe extern "system" fn signal_and_wait(sig: usize, wait: usize, ms: u32, alertable: i32) -> u32 { + let s = enter(9, wait as u64, false); + let r = real:: u32>(9)(sig, wait, ms, alertable); + leave(s); + r +} + +unsafe extern "system" fn queued_status(port: usize, bytes: *mut u32, key: *mut usize, ov: *mut usize, ms: u32) -> i32 { + let s = enter(10, port as u64, false); + let r = real:: i32>(10)(port, bytes, key, ov, ms); + leave(s); + r +} + +unsafe extern "system" fn queued_status_ex(port: usize, entries: usize, count: u32, removed: *mut u32, ms: u32, alertable: i32) -> i32 { + let s = enter(11, port as u64, false); + let r = real:: i32>(11)(port, entries, count, removed, ms, alertable); + leave(s); + r +} + +unsafe extern "system" fn srw_exclusive(lock: usize) { + if TryAcquireSRWLockExclusive(lock) != 0 { + return; + } + let s = enter(12, lock as u64, false); + real::(12)(lock); + leave(s); +} + +unsafe extern "system" fn srw_shared(lock: usize) { + if TryAcquireSRWLockShared(lock) != 0 { + return; + } + let s = enter(13, lock as u64, false); + real::(13)(lock); + leave(s); +} + +unsafe extern "system" fn enter_cs(cs: usize) { + if TryEnterCriticalSection(cs) != 0 { + return; + } + let s = enter(14, cs as u64, false); + real::(14)(cs); + leave(s); +} + +// --- MWAITX loops (`eh::emulate_console_only`) + +const MW: usize = 64; +static MW_RIP: [AtomicUsize; MW] = [const { AtomicUsize::new(0) }; MW]; +static MW_N: [AtomicU64; MW] = [const { AtomicU64::new(0) }; MW]; +static MW_LAST: [AtomicU64; MW] = [const { AtomicU64::new(0) }; MW]; +static MW_ADDR: [AtomicU64; MW] = [const { AtomicU64::new(0) }; MW]; + +/// A MONITORX on this thread: the address its next MWAITX waits for a write to. +pub fn note_monitorx(addr: u64) { + if on() { + MONITORED.with(|m| m.set(addr)); + } +} + +/// An MWAITX at `rip`. +pub fn note_mwaitx(rip: usize) { + if !on() { + return; + } + start_watcher(); + let addr = MONITORED.with(|m| m.get()); + let h = (rip >> 2) % MW; + for i in 0..MW { + let k = (h + i) % MW; + let cur = MW_RIP[k].load(Ordering::Relaxed); + let mine = cur == rip + || (cur == 0 + && match MW_RIP[k].compare_exchange(0, rip, Ordering::AcqRel, Ordering::Relaxed) { + Ok(_) => true, + Err(v) => v == rip, + }); + if mine { + MW_N[k].fetch_add(1, Ordering::Relaxed); + MW_ADDR[k].store(addr, Ordering::Relaxed); + return; + } + } +} + +// --- XCL's own waits: xcl.exe's imports of WaitOnAddress (Rust's locks, condition variables, +// channels, thread parking), WaitForSingleObject, WaitForMultipleObjects and Sleep go through +// wrappers of their own (what the title resolved may be an HLE function of XCL's, which itself +// waits through these imports) + +static REAL_OWN: [AtomicUsize; KINDS.len()] = [const { AtomicUsize::new(0) }; KINDS.len()]; + +unsafe fn real_own(k: usize) -> T { + std::mem::transmute_copy(&REAL_OWN[k].load(Ordering::Relaxed)) +} + +unsafe extern "system" fn own_wait_single(h: usize, ms: u32) -> u32 { + let s = if ms != 0 { enter(0, h as u64, true) } else { None }; + let r = real_own:: u32>(0)(h, ms); + leave(s); + r +} + +unsafe extern "system" fn own_wait_multiple(n: u32, hs: *const usize, all: i32, ms: u32) -> u32 { + let s = if ms != 0 { enter(2, first_handle(n, hs), true) } else { None }; + let r = real_own:: u32>(2)(n, hs, all, ms); + leave(s); + r +} + +unsafe extern "system" fn own_wait_on_address(addr: usize, cmp: usize, size: usize, ms: u32) -> i32 { + let s = if ms != 0 { enter(6, addr as u64, true) } else { None }; + let r = real_own:: i32>(6)(addr, cmp, size, ms); + leave(s); + r +} + +unsafe extern "system" fn own_sleep(ms: u32) { + let s = if ms != 0 { enter(7, ms as u64, true) } else { None }; + real_own::(7)(ms); + leave(s); +} + +/// xcl.exe's import address table entries of those four functions, pointed at the wrappers. +unsafe fn patch_own_imports() { + #[link(name = "kernel32")] + extern "system" { + fn VirtualProtect(at: usize, size: usize, protect: u32, old: *mut u32) -> i32; + } + let base = GetModuleHandleW(std::ptr::null()); + if base == 0 { + return; + } + let pe = base + *((base + 0x3C) as *const u32) as usize; + // PE32+: the data directories at optional header + 0x70, the import table is entry 1 + let imports = *((pe + 0x18 + 0x70 + 8) as *const u32) as usize; + if imports == 0 { + return; + } + let mut patched = Vec::new(); + let mut desc = base + imports; + loop { + let (lookup, name, iat) = (*(desc as *const u32) as usize, *((desc + 12) as *const u32) as usize, *((desc + 16) as *const u32) as usize); + if name == 0 && iat == 0 { + break; + } + let lookup = if lookup != 0 { lookup } else { iat }; + for i in 0.. { + let entry = *((base + lookup + 8 * i) as *const u64); + if entry == 0 { + break; + } + if entry >> 63 != 0 { + continue; + } + let fname = std::ffi::CStr::from_ptr((base + (entry as usize & 0x7FFF_FFFF) + 2) as *const std::ffi::c_char).to_str().unwrap_or(""); + let wrapper: usize = match fname { + "WaitForSingleObject" => own_wait_single as usize, + "WaitForMultipleObjects" => own_wait_multiple as usize, + "WaitOnAddress" => own_wait_on_address as usize, + "Sleep" => own_sleep as usize, + _ => continue, + }; + let k = KINDS.iter().position(|&n| n == fname).unwrap(); + let slot = base + iat + 8 * i; + let real = *(slot as *const usize); + if real == wrapper { + continue; + } + REAL_OWN[k].store(real, Ordering::Release); + let mut old = 0u32; + if VirtualProtect(slot, 8, 0x04, &mut old) != 0 { + (*(slot as *const AtomicUsize)).store(wrapper, Ordering::Release); + VirtualProtect(slot, 8, old, &mut old); + patched.push(fname); + } + } + desc += 20; + } + crate::xlog_info!("[waits] XCL's own waits watched too: {patched:?} in xcl.exe's imports"); +} + +fn start_watcher() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + unsafe { patch_own_imports() }; + unsafe { patch_all_modules() }; + crate::xlog_info!("[waits] XCL_WATCH_WAITS: the title's waits are watched – a thread in one wait, or polling one, for 10 s or more is logged with its stack"); + let _ = std::thread::Builder::new().name("xcl-waitwatch".into()).spawn(|| { + // (syscall names now, while nothing is stuck: GetModuleHandle takes the loader lock) + let _ = syscall_name(0); + install_exception_ring(); + start_probe(); + for tick in 1u64.. { + std::thread::sleep(std::time::Duration::from_secs(5)); + // (modules loaded since: their imports too) + unsafe { patch_all_modules() }; + unsafe { scan() }; + // every 30 s: every thread's state as it is now + if tick % 6 == 0 { + unsafe { snapshot() }; + } + } + }); + }); +} + +unsafe fn scan() { + let now = now_ms(); + probe_check(now); + exception_test_check(now); + let used = USED.load(Ordering::Relaxed).min(SLOTS); + let mut lines = 0; + for s in &TABLE[..used] { + let kind = s.kind.load(Ordering::Acquire); + if kind == 0 { + continue; + } + let since = s.since.load(Ordering::Relaxed); + let in_call = s.in_call.load(Ordering::Acquire) != 0; + let polling = !in_call && now.saturating_sub(s.last_exit.load(Ordering::Relaxed)) < 1500; + if !in_call && !polling { + continue; + } + let d = now.saturating_sub(since); + // (a state once; the same wait from the same place again: at most once a minute) + let sig = (kind as u64) << 56 ^ s.frames[0].load(Ordering::Relaxed) as u64; + let again = s.reported_sig.load(Ordering::Relaxed) == sig && now.saturating_sub(s.reported_at.load(Ordering::Relaxed)) < 60_000; + if d < 10_000 || s.reported.load(Ordering::Relaxed) == since || again { + continue; + } + s.reported.store(since, Ordering::Relaxed); + s.reported_sig.store(sig, Ordering::Relaxed); + s.reported_at.store(now, Ordering::Relaxed); + let frames: Vec = s.frames.iter().map(|f| f.load(Ordering::Relaxed)).take_while(|&f| f != 0).map(crate::modules::describe_address).collect(); + crate::xlog_info!( + "[waits] thread {} {} {}({}) for {:.0} s{}; from {}", + s.tid.load(Ordering::Relaxed), + if in_call { "blocked in" } else { "polling" }, + kind_name(kind), + describe_arg(kind, s.arg.load(Ordering::Relaxed), s.arg2.load(Ordering::Relaxed)), + d as f64 / 1000.0, + scan_tail(s, polling, now), + frames.join(" < ") + ); + lines += 1; + if lines >= 48 { + break; + } + } + for k in 0..MW { + let rip = MW_RIP[k].load(Ordering::Relaxed); + if rip == 0 { + continue; + } + let n = MW_N[k].load(Ordering::Relaxed); + let d = n - MW_LAST[k].swap(n, Ordering::Relaxed); + if d >= 100 { + let addr = MW_ADDR[k].load(Ordering::Relaxed); + let value = (addr != 0 && crate::gpu::shader::readable(addr as usize, 8)).then(|| (addr as *const u64).read_volatile()); + crate::xlog_info!("[waits] MWAITX at {}: {d} in the last 5 s, watching {addr:#x} (now {value:x?})", crate::modules::describe_address(rip)); + } + } +} + +/// A thread's state as the snapshot says it (`in_call`, `last_exit`: as the snapshot read them): in +/// a call (`in_text`, after a critical section's owner), polling one, or running since its last +/// wait returned. +unsafe fn snapshot_state(s: &Slot, kind: u32, in_call: bool, last_exit: u64, now: u64) -> String { + let since = s.since.load(Ordering::Relaxed); + if in_call { + let owner = { + let k = kind as usize - 1; + if k >= ANY_BASE && matches!(ANY.get(k - ANY_BASE).map(|a| a.1), Some(Wait::Cs)) { + format!(", held by thread {}", cs_owner(s.arg.load(Ordering::Relaxed) as usize)) + } else { + String::new() + } + }; + in_text(s, kind, now, &owner) + } else if now.saturating_sub(last_exit) < 1500 { + format!("polling {} for {:.1} s ({} calls)", kind_name(kind), now.saturating_sub(since) as f64 / 1000.0, s.calls.load(Ordering::Relaxed)) + } else { + let running = now.saturating_sub(last_exit); + format!("RUNNING for {:.1} s since its last wait, {} returned", running as f64 / 1000.0, kind_name(kind)) + } +} + +/// What the 10-s line's state ends with: a polling state's calls, or – a state in a call that +/// merged several – `calls_tail`. +fn scan_tail(s: &Slot, polling: bool, now: u64) -> String { + if polling { + format!(" ({} calls)", s.calls.load(Ordering::Relaxed)) + } else { + calls_tail(s, now) + } +} + +/// Every thread that ever waited, as it is now: in a wait (how long), polling one, or running +/// since its last wait returned (where that was) – or gone. +unsafe fn snapshot() { + let now = now_ms(); + let used = USED.load(Ordering::Relaxed).min(SLOTS); + crate::xlog_info!("[waits] snapshot at {:.1} s: {used} threads, {} exceptions so far", now as f64 / 1000.0, RING_AT.load(Ordering::Relaxed)); + crate::xlog_info!("[waits] title fences behind what their queues were told: {}", crate::hle::d3d12x::fences_pending()); + crate::xlog_info!("[waits] {}", crate::hle::d3d12x::cpu_writes_probe()); + crate::xlog_info!("[waits] {}", crate::hle::d3d12x::pso_probe()); + crate::xlog_info!("[waits] {}", crate::hle::dstorage::probe_line()); + let pend = gpu_waits_pending(now); + crate::xlog_info!("[waits] GPU waits not satisfied: {}", if pend.is_empty() { "none".to_string() } else { pend.len().to_string() }); + for p in pend { + crate::xlog_info!("[waits] {p}"); + } + for k in 0..MW { + let rip = MW_RIP[k].load(Ordering::Relaxed); + if rip != 0 { + crate::xlog_info!("[waits] MWAITX at {}: {} so far, watching {:#x}", crate::modules::describe_address(rip), MW_N[k].load(Ordering::Relaxed), MW_ADDR[k].load(Ordering::Relaxed)); + } + } + // where the threads are on the Unix side (the frame each had at the last snapshot) + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); + let mut running = Vec::new(); + for s in &TABLE[..used] { + let kind = s.kind.load(Ordering::Acquire); + if kind == 0 { + continue; + } + let tid = s.tid.load(Ordering::Relaxed); + let (cpu, alive) = thread_cpu(tid).unwrap_or((0, false)); + if !alive { + continue; + } + let grew = cpu.saturating_sub(s.cpu_seen.swap(cpu, Ordering::Relaxed)); + let in_call = s.in_call.load(Ordering::Acquire) != 0; + let last_exit = s.last_exit.load(Ordering::Relaxed); + let state = snapshot_state(s, kind, in_call, last_exit, now); + let frames: Vec = s.frames.iter().map(|f| f.load(Ordering::Relaxed)).take_while(|&f| f != 0).map(crate::modules::describe_address).collect(); + if !in_call && now.saturating_sub(last_exit) >= 1500 { + running.push(tid); + } + crate::xlog_info!("[waits] thread {tid}: {state} ({}){}; at {}", describe_arg(kind, s.arg.load(Ordering::Relaxed), s.arg2.load(Ordering::Relaxed)), api_of(s, now), frames.join(" < ")); + let _ = (cpu, grew); + } + if running.is_empty() { + return; + } + let code = code_ranges(); + let mut seen = SEEN.lock().unwrap(); + let seen = seen.get_or_insert_with(Default::default); + for tid in running { + if let Some(u) = unix_side(tid, &code) { + let same = seen.insert(tid, u.key) == Some(u.key); + crate::xlog_info!("[waits] thread {tid} on the Unix side{}: {}", if same { " (the same frame as 30 s ago)" } else { "" }, u.detail); + } + } +} + +// --- waits the GPU queues were given (XCL's own and the title's): those whose fence has not +// reached the value yet are listed with each snapshot – a queue held by one of them for long +// stands still, and everything after it on that queue with it + +struct GpuWait { + site: &'static str, + queue: usize, + fence: windows::Win32::Graphics::Direct3D12::ID3D12Fence, + value: u64, + at: u64, +} + +// SAFETY: a fence is free-threaded; only its completed value is asked +unsafe impl Send for GpuWait {} + +static GPU_WAITS: std::sync::Mutex>> = std::sync::Mutex::new(None); + +/// `queue` was told to wait (on the GPU) until `fence` reaches `value`; `site` says where. +pub fn note_gpu_wait(site: &'static str, queue: usize, fence: &windows::Win32::Graphics::Direct3D12::ID3D12Fence, value: u64) { + if !on() { + return; + } + let mut g = GPU_WAITS.lock().unwrap(); + let q = g.get_or_insert_with(Default::default); + if q.len() >= 1024 { + q.pop_front(); + } + q.push_back(GpuWait { site, queue, fence: fence.clone(), value, at: now_ms() }); +} + +/// `note_gpu_wait` for a fence the title passed (a raw pointer). +pub unsafe fn note_gpu_wait_raw(site: &'static str, queue: usize, fence: usize, value: u64) { + if !on() || fence == 0 { + return; + } + let p = fence as *mut c_void; + if let Some(f) = ::from_raw_borrowed(&p) { + note_gpu_wait(site, queue, f, value); + } +} + +/// The GPU waits not satisfied yet (oldest first, one line per site and queue). +fn gpu_waits_pending(now: u64) -> Vec { + let g = GPU_WAITS.lock().unwrap(); + let Some(q) = g.as_ref() else { return Vec::new() }; + let mut out: Vec<(String, u64)> = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for w in q.iter() { + let done = unsafe { w.fence.GetCompletedValue() }; + if done >= w.value { + continue; + } + let fence = ::as_raw(&w.fence) as usize; + if !seen.insert((w.site, w.queue, fence)) { + continue; + } + out.push((format!("{} on queue {:#x}: fence {fence:#x} wanted {:#x}, at {:#x}, for {:.1} s", w.site, w.queue, w.value, done, now.saturating_sub(w.at) as f64 / 1000.0), w.at)); + } + out.sort_by_key(|e| e.1); + out.into_iter().map(|e| e.0).take(24).collect() +} + +// --- every other module's imports (Wine's DLLs, the CRT, the shader compiler …): their waits +// and contended locks go through wrappers too, so a thread held in a lock some DLL took – not +// the title, not XCL – shows where. Each name may resolve to a few functions (kernel32's, +// kernelbase's, ntdll's): up to `VARIANTS` targets get a wrapper each. + +#[derive(Clone, Copy, PartialEq)] +enum Wait { + /// no timeout argument to tell a poll by + Always, + /// milliseconds in argument `n` (0: a poll) + Ms(usize), + /// an NT timeout pointer in argument `n` (null: forever; *p == 0: a poll) + Nt(usize), + /// a critical section (TryEnterCriticalSection first: only a contended one is noted) + Cs, + SrwExclusive, + SrwShared, +} + +/// (name, how to tell a wait from a poll) +const ANY: [(&str, Wait); 32] = [ + ("WaitForSingleObject", Wait::Ms(2)), + ("WaitForSingleObjectEx", Wait::Ms(2)), + ("WaitForMultipleObjects", Wait::Ms(4)), + ("WaitForMultipleObjectsEx", Wait::Ms(4)), + ("SignalObjectAndWait", Wait::Ms(3)), + ("EnterCriticalSection", Wait::Cs), + ("RtlEnterCriticalSection", Wait::Cs), + ("AcquireSRWLockExclusive", Wait::SrwExclusive), + ("RtlAcquireSRWLockExclusive", Wait::SrwExclusive), + ("AcquireSRWLockShared", Wait::SrwShared), + ("RtlAcquireSRWLockShared", Wait::SrwShared), + ("SleepConditionVariableSRW", Wait::Ms(3)), + ("RtlSleepConditionVariableSRW", Wait::Nt(3)), + ("SleepConditionVariableCS", Wait::Ms(3)), + ("RtlSleepConditionVariableCS", Wait::Nt(3)), + ("WaitOnAddress", Wait::Ms(4)), + ("RtlWaitOnAddress", Wait::Nt(4)), + ("NtWaitForSingleObject", Wait::Nt(3)), + ("NtWaitForMultipleObjects", Wait::Nt(5)), + ("NtWaitForAlertByThreadId", Wait::Nt(2)), + ("NtDelayExecution", Wait::Nt(2)), + ("Sleep", Wait::Ms(1)), + ("SleepEx", Wait::Ms(1)), + ("GetQueuedCompletionStatus", Wait::Ms(5)), + ("GetQueuedCompletionStatusEx", Wait::Ms(5)), + ("NtRemoveIoCompletion", Wait::Nt(5)), + ("MsgWaitForMultipleObjects", Wait::Ms(4)), + ("MsgWaitForMultipleObjectsEx", Wait::Ms(3)), + ("GetMessageW", Wait::Always), + ("GetMessageA", Wait::Always), + ("SendMessageW", Wait::Always), + ("SendMessageA", Wait::Always), +]; +const VARIANTS: usize = 4; +static REAL_ANY: [[AtomicUsize; VARIANTS]; ANY.len()] = [const { [const { AtomicUsize::new(0) }; VARIANTS] }; ANY.len()]; +const ANY_BASE: usize = KINDS.len() + XCL_KINDS.len(); + +unsafe fn is_poll(how: Wait, a: &[usize; 6]) -> bool { + match how { + Wait::Ms(n) => a[n - 1] as u32 == 0, + Wait::Nt(n) => { + let p = a[n - 1]; + p != 0 && *(p as *const i64) == 0 + } + _ => false, + } +} + +unsafe extern "system" fn any_wrap(a1: usize, a2: usize, a3: usize, a4: usize, a5: usize, a6: usize) -> usize { + let real: unsafe extern "system" fn(usize, usize, usize, usize, usize, usize) -> usize = std::mem::transmute(REAL_ANY[K][V].load(Ordering::Relaxed)); + let how = ANY[K].1; + match how { + Wait::Cs if TryEnterCriticalSection(a1) != 0 => return 0, + Wait::SrwExclusive if TryAcquireSRWLockExclusive(a1) != 0 => return 0, + Wait::SrwShared if TryAcquireSRWLockShared(a1) != 0 => return 0, + _ => {} + } + if is_poll(how, &[a1, a2, a3, a4, a5, a6]) { + return real(a1, a2, a3, a4, a5, a6); + } + let s = enter(ANY_BASE + K, a1 as u64, true); + let r = real(a1, a2, a3, a4, a5, a6); + leave(s); + r +} + +/// The wrapper for name `k`, variant `v`. +fn any_wrapper(k: usize, v: usize) -> usize { + macro_rules! table { + ($($k:literal),*) => { + match (k, v) { + $( + ($k, 0) => any_wrap::<$k, 0> as usize, + ($k, 1) => any_wrap::<$k, 1> as usize, + ($k, 2) => any_wrap::<$k, 2> as usize, + ($k, 3) => any_wrap::<$k, 3> as usize, + )* + _ => 0, + } + }; + } + table!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31) +} + +/// Every module of the process (but xcl.exe, whose imports `patch_own_imports` saw to, and the +/// ones done before): its imports of `ANY` pointed at the wrappers. Returns how many entries. +unsafe fn patch_all_modules() -> usize { + #[link(name = "kernel32")] + extern "system" { + fn K32EnumProcessModules(process: usize, modules: *mut usize, cb: u32, needed: *mut u32) -> i32; + fn K32GetModuleBaseNameW(process: usize, module: usize, name: *mut u16, size: u32) -> u32; + fn GetCurrentProcess() -> usize; + fn VirtualProtect(at: usize, size: usize, protect: u32, old: *mut u32) -> i32; + } + static DONE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let mut mods = vec![0usize; 1024]; + let mut needed = 0u32; + if K32EnumProcessModules(GetCurrentProcess(), mods.as_mut_ptr(), (mods.len() * 8) as u32, &mut needed) == 0 { + return 0; + } + mods.truncate((needed as usize / 8).min(mods.len())); + let own = own_image().0; + let mut total = 0; + let mut names = Vec::new(); + for &base in &mods { + if base == 0 || base == own || DONE.lock().unwrap().contains(&base) { + continue; + } + DONE.lock().unwrap().push(base); + let mut buf = [0u16; 128]; + let n = K32GetModuleBaseNameW(GetCurrentProcess(), base, buf.as_mut_ptr(), buf.len() as u32) as usize; + let name = String::from_utf16_lossy(&buf[..n]).to_ascii_lowercase(); + if name == "ntdll.dll" { + continue; + } + let pe = base + *((base + 0x3C) as *const u32) as usize; + if *(pe as *const u32) != 0x4550 || *((pe + 0x18) as *const u16) != 0x20B { + continue; + } + let (imports, size) = (*((pe + 0x18 + 0x70 + 8) as *const u32) as usize, *((pe + 0x18 + 0x70 + 12) as *const u32) as usize); + if imports == 0 || size == 0 { + continue; + } + let mut count = 0; + let mut desc = base + imports; + loop { + let (lookup, dll, iat) = (*(desc as *const u32) as usize, *((desc + 12) as *const u32) as usize, *((desc + 16) as *const u32) as usize); + if dll == 0 && iat == 0 { + break; + } + let lookup = if lookup != 0 { lookup } else { iat }; + for i in 0..4096usize { + let entry = *((base + lookup + 8 * i) as *const u64); + if entry == 0 { + break; + } + if entry >> 63 != 0 { + continue; + } + let fname = std::ffi::CStr::from_ptr((base + (entry as usize & 0x7FFF_FFFF) + 2) as *const std::ffi::c_char).to_str().unwrap_or(""); + let Some(k) = ANY.iter().position(|a| a.0 == fname) else { continue }; + let slot = base + iat + 8 * i; + let target = (*(slot as *const AtomicUsize)).load(Ordering::Acquire); + if target == 0 || (0..VARIANTS).any(|v| any_wrapper(k, v) == target) { + continue; + } + // the variant whose real function this is, or a free one + let v = (0..VARIANTS).find(|&v| REAL_ANY[k][v].load(Ordering::Acquire) == target).or_else(|| (0..VARIANTS).find(|&v| REAL_ANY[k][v].compare_exchange(0, target, Ordering::AcqRel, Ordering::Acquire).is_ok())); + let Some(v) = v else { continue }; + let w = any_wrapper(k, v); + let mut old = 0u32; + if w != 0 && VirtualProtect(slot, 8, 0x04, &mut old) != 0 { + (*(slot as *const AtomicUsize)).store(w, Ordering::Release); + VirtualProtect(slot, 8, old, &mut old); + count += 1; + } + } + desc += 20; + } + if count > 0 { + total += count; + names.push(format!("{name} {count}")); + } + } + if !names.is_empty() { + crate::xlog_info!("[waits] waits in other modules watched: {}", names.join(", ")); + } + total +} + +/// The thread that owns critical section `cs` now (RTL_CRITICAL_SECTION.OwningThread at +0x10). +unsafe fn cs_owner(cs: usize) -> usize { + if cs == 0 || !crate::gpu::shader::readable(cs, 0x28) { + return 0; + } + *((cs + 0x10) as *const usize) +} + +// --- the Unix side of a thread ---------------------------------------------------------------- +// +// Wine keeps a thread's user-mode registers in its syscall frame from the moment it enters a +// syscall or a Unix library call (D3DMetal, the Mac driver, …) until it is back; CrossOver 26's +// ntdll.so finds that frame at TEB + 0x378 (`gs:[0x30] + 0x378` in both dispatchers). A thread +// that left its last wait long ago and keeps the same frame is blocked on the Unix side – or +// runs without making a syscall. Which syscall, the registers it keeps (a lock it waits for is +// often in one of them) and the return addresses on its stack from there are read without +// suspending it (SuspendThread does not come back for such a thread under Rosetta), and nothing +// here takes the loader lock (no unwinder, no GetModuleHandleEx): module ranges come from the +// PEB list and XCL's own table. + +const TEB_SYSCALL_FRAME: usize = 0x378; +/// syscall frame: rip, rsp, syscall number, flags (0x20000: a Unix library call) +const FRAME_RIP: usize = 0x70; +const FRAME_RSP: usize = 0x88; +const FRAME_NUMBER: usize = 0xb0; +const FRAME_FLAGS: usize = 0xb4; + +/// Executable sections of the loaded modules: (start, end, module base, module name). +unsafe fn code_ranges() -> Vec<(usize, usize, usize, String)> { + let mut mods: Vec<(usize, String)> = Vec::new(); + let peb: usize; + core::arch::asm!("mov {}, gs:[0x60]", out(reg) peb, options(nostack, readonly, preserves_flags)); + let ldr = *((peb + 0x18) as *const usize); + if ldr != 0 { + let head = ldr + 0x10; + let mut e = *(head as *const usize); + let mut guard = 0; + while e != 0 && e != head && guard < 1024 { + guard += 1; + let base = *((e + 0x30) as *const usize); + let len = (*((e + 0x58) as *const u16) / 2) as usize; + let buf = *((e + 0x60) as *const usize) as *const u16; + if base != 0 && !buf.is_null() && len > 0 && len < 260 { + mods.push((base, String::from_utf16_lossy(std::slice::from_raw_parts(buf, len)).to_ascii_lowercase())); + } + e = *(e as *const usize); + } + } + for m in crate::modules::mapped_modules() { + mods.push((m.base, m.name.clone())); + } + let mut out = Vec::new(); + for (base, name) in mods { + if !committed(base, 0x40) || *(base as *const u16) != 0x5A4D { + continue; + } + let pe = base + *((base + 0x3C) as *const u32) as usize; + if !committed(pe, 0x18) || *(pe as *const u32) != 0x4550 { + continue; + } + let sections = (*((pe + 6) as *const u16) as usize).min(96); + let first = pe + 24 + *((pe + 20) as *const u16) as usize; + if !committed(first, sections * 40) { + continue; + } + for i in 0..sections { + let s = first + 40 * i; + let (size, rva, chars) = (*((s + 8) as *const u32) as usize, *((s + 12) as *const u32) as usize, *((s + 36) as *const u32)); + if chars & 0x2000_0000 != 0 && size != 0 { + out.push((base + rva, base + rva + size, base, name.clone())); + } + } + } + out +} + +/// A syscall's name by its number, from the `mov r10, rcx; mov eax, n` stubs of ntdll.dll and +/// win32u.dll (read once, when the watcher starts). +fn syscall_name(n: u32) -> String { + static NAMES: std::sync::OnceLock> = std::sync::OnceLock::new(); + let names = NAMES.get_or_init(|| unsafe { + let mut m = std::collections::HashMap::new(); + for dll in ["ntdll.dll", "win32u.dll"] { + let w: Vec = dll.encode_utf16().chain(Some(0)).collect(); + let base = GetModuleHandleW(w.as_ptr()); + if base == 0 { + continue; + } + let pe = base + *((base + 0x3C) as *const u32) as usize; + let dir = *((pe + 0x18 + 0x70) as *const u32) as usize; + if dir == 0 { + continue; + } + let d = base + dir; + let count = *((d + 0x18) as *const u32) as usize; + let funcs = base + *((d + 0x1C) as *const u32) as usize; + let names = base + *((d + 0x20) as *const u32) as usize; + let ords = base + *((d + 0x24) as *const u32) as usize; + for i in 0..count { + let name = std::ffi::CStr::from_ptr((base + *((names + 4 * i) as *const u32) as usize) as *const std::ffi::c_char).to_string_lossy(); + if !name.starts_with("Nt") { + continue; + } + let f = base + *((funcs + 4 * *((ords + 2 * i) as *const u16) as usize) as *const u32) as usize; + let b = std::slice::from_raw_parts(f as *const u8, 8); + if b[..4] == [0x4C, 0x8B, 0xD1, 0xB8] { + m.entry(u32::from_le_bytes([b[4], b[5], b[6], b[7]])).or_insert_with(|| name.into_owned()); + } + } + } + m + }); + names.get(&n).cloned().unwrap_or_else(|| format!("syscall {n:#x}")) +} + +/// Whether the bytes before `v` end in a call instruction (`v` a return address); `v - 7` and on +/// must be readable. +unsafe fn call_before(v: usize) -> bool { + let b = |k: usize| *((v - k) as *const u8); + if b(5) == 0xE8 { + return true; + } + // FF /2 (call r/m64): FF D0+r; FF 50+r d8 | FF 14 24; FF 54 24 d8; FF 15 d32 | FF 90+r d32; + // FF 94 24 d32 | FF 14 25 abs32 + [2usize, 3, 4, 6, 7].iter().any(|&k| b(k) == 0xFF && (b(k - 1) >> 3) & 7 == 2) +} + +/// `p` as a critical section someone holds. +unsafe fn held_cs(p: usize) -> Option { + if p < 0x10000 || p % 8 != 0 || !committed(p, 0x28) { + return None; + } + let (lock_count, recursion, owner) = (*((p + 8) as *const i32), *((p + 12) as *const i32), *((p + 0x10) as *const usize)); + if owner == 0 || owner > 0x10_0000 || owner % 4 != 0 || !(1..=64).contains(&recursion) || lock_count < 0 { + return None; + } + Some(format!("critical section {p:#x} held by thread {owner} (recursion {recursion}, lock count {lock_count})")) +} + +/// Thread `tid` as its syscall frame has it. +struct UnixSide { + /// the syscall (name) or "a Unix library call", registers, critical sections they point to, the return addresses on the stack + detail: String, + /// changes whenever the thread enters the Unix side again + key: u64, +} + +unsafe fn unix_side(tid: u32, code: &[(usize, usize, usize, String)]) -> Option { + #[link(name = "ntdll")] + extern "system" { + fn NtQueryInformationThread(h: *mut c_void, class: u32, info: *mut c_void, len: u32, ret: *mut u32) -> i32; + } + let h = OpenThread(0x0040, 0, tid); // THREAD_QUERY_INFORMATION + if h == 0 { + return None; + } + let mut tbi = [0usize; 6]; + let ok = NtQueryInformationThread(h as *mut c_void, 0, tbi.as_mut_ptr() as *mut c_void, 48, std::ptr::null_mut()) >= 0; + CloseHandle(h); + let teb = if ok { tbi[1] } else { 0 }; + if teb == 0 || !committed(teb, 0x1480) { + return None; + } + let frame = *((teb + TEB_SYSCALL_FRAME) as *const usize); + if frame == 0 || frame % 16 != 0 || !committed(frame, 0xc0) { + return None; + } + let q = |o: usize| *((frame + o) as *const u64); + let (rip, rsp) = (q(FRAME_RIP) as usize, q(FRAME_RSP) as usize); + let (number, flags) = (*((frame + FRAME_NUMBER) as *const u32), *((frame + FRAME_FLAGS) as *const u32)); + let what = if flags & 0x20000 != 0 { "a Unix library call".to_string() } else { syscall_name(number) }; + let place = |a: usize| code.iter().find(|r| a >= r.0 && a < r.1).map(|r| format!("{}+{:#x}", r.3, a - r.2)); + // return addresses on the stack from rsp (up to 64 KiB, within the thread's stack) + let (top, low) = (*((teb + 8) as *const usize), *((teb + 0x1478) as *const usize)); + let mut stack: Vec<(usize, String)> = Vec::new(); + if rsp > low && rsp < top { + let end = top.min(rsp + 0x10000); + let mut at = rsp & !7; + while at + 8 <= end && stack.len() < 24 { + let v = *(at as *const usize); + if let Some(r) = code.iter().find(|r| v >= r.0 + 8 && v < r.1) { + if stack.last().map(|s| s.0) != Some(v) && call_before(v) { + stack.push((v, format!("{}+{:#x}", r.3, v - r.2))); + } + } + at += 8; + } + } + let regs = [("rbx", 0x8), ("rsi", 0x20), ("rdi", 0x28), ("rbp", 0x98), ("r12", 0x50), ("r13", 0x58), ("r14", 0x60), ("r15", 0x68)]; + let held: Vec = regs.iter().filter_map(|&(n, o)| held_cs(q(o) as usize).map(|h| format!("{n} → {h}"))).collect(); + let detail = format!( + "{what} at {} (rsp {rsp:#x}; rdx {:#x}; {}){}; stack: {}", + place(rip).unwrap_or_else(|| format!("{rip:#x}")), + q(0x18), + regs.iter().map(|&(n, o)| format!("{n} {:#x}", q(o))).collect::>().join(" "), + if held.is_empty() { String::new() } else { format!("; {}", held.join("; ")) }, + stack.iter().map(|s| s.1.as_str()).collect::>().join(" < ") + ); + let key = rsp as u64 ^ (rip as u64).rotate_left(17) ^ (number as u64) << 40 ^ (flags as u64) << 20; + Some(UnixSide { detail, key }) +} + +/// Whether `[p, p + len)` is committed and readable (VirtualQuery only: nothing is touched). +fn committed(p: usize, len: usize) -> bool { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_GUARD, PAGE_NOACCESS}; + let mut at = p; + let end = p.saturating_add(len); + while at < end { + let mut mbi: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(at as *const c_void, &mut mbi, std::mem::size_of::()) } == 0 { + return false; + } + if mbi.State != MEM_COMMIT || mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD) != 0 || mbi.Protect == 0 { + return false; + } + at = mbi.BaseAddress as usize + mbi.RegionSize; + } + true +} + +// --- the fault probe: does the process still take page faults and exceptions? ----------------- +// +// A thread of its own, every 100 ms: the first touch of a fresh page of private memory (a +// zero-fill fault the kernel resolves alone), of a page of a section (shared memory, as the +// title's), an access violation that is handled (the signal, Wine, the PE handlers, NtContinue), +// a VirtualQuery and a VirtualAlloc + VirtualFree. Each stage notes when it began: the watcher +// logs a stage that has not come back for 2 s, and when the last full round ended – the moment +// the process stopped taking that kind of fault. A stage slower than 250 ms is logged by the +// probe itself. + +const PROBE_STAGES: [&str; 6] = [ + "idle", + "first touch of private memory (zero-fill fault)", + "first touch of a section's page (shared memory)", + "an access violation, handled (exception and NtContinue)", + "VirtualQuery", + "VirtualAlloc + VirtualFree", +]; +static PROBE_STAGE: AtomicU32 = AtomicU32::new(0); +static PROBE_SINCE: AtomicU64 = AtomicU64::new(0); +static PROBE_LAST_OK: AtomicU64 = AtomicU64::new(0); +static PROBE_ROUNDS: AtomicU64 = AtomicU64::new(0); +static PROBE_REPORTED: AtomicU64 = AtomicU64::new(0); + +fn start_probe() { + use windows_sys::Win32::System::Memory::{CreateFileMappingW, IsBadReadPtr, MapViewOfFile, VirtualAlloc, VirtualFree, VirtualQuery, FILE_MAP_READ, FILE_MAP_WRITE, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + let _ = std::thread::Builder::new().name("xcl-faultprobe".into()).spawn(|| unsafe { + const SPAN: usize = 256 << 20; + let private = VirtualAlloc(std::ptr::null(), SPAN, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as usize; + let map = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, SPAN as u32, std::ptr::null()); + let shared = if map.is_null() { 0 } else { MapViewOfFile(map, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, SPAN).Value as usize }; + let hole = VirtualAlloc(std::ptr::null(), 0x10000, MEM_RESERVE, PAGE_NOACCESS) as usize; + crate::xlog_info!("[waits] fault probe: every 100 ms (private {private:#x}, section view {shared:#x}, hole {hole:#x})"); + let mut slow = 0; + let mut next = 0usize; + loop { + std::thread::sleep(std::time::Duration::from_millis(100)); + let at = next % SPAN; + next += 0x4000; + for k in 1..=5u32 { + let t0 = now_ms(); + PROBE_SINCE.store(t0, Ordering::Relaxed); + PROBE_STAGE.store(k, Ordering::Release); + match k { + 1 if private != 0 => std::ptr::write_volatile((private + at) as *mut u8, 1), + 2 if shared != 0 => std::ptr::write_volatile((shared + at) as *mut u8, 1), + 3 if hole != 0 => { + IsBadReadPtr(hole as *const c_void, 1); + } + 4 => { + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(&next as *const usize as *const c_void, &mut mbi, std::mem::size_of::()); + } + 5 => { + let p = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if !p.is_null() { + std::ptr::write_volatile(p as *mut u8, 1); + VirtualFree(p, 0, MEM_RELEASE); + } + } + _ => {} + } + let took = now_ms().saturating_sub(t0); + if took >= 250 && slow < 40 { + slow += 1; + crate::xlog_warn!("[waits] fault probe: \"{}\" took {took} ms (from {:.3} s)", PROBE_STAGES[k as usize], t0 as f64 / 1000.0); + } + } + PROBE_STAGE.store(0, Ordering::Release); + PROBE_LAST_OK.store(now_ms(), Ordering::Relaxed); + PROBE_ROUNDS.fetch_add(1, Ordering::Relaxed); + } + }); +} + +/// (watcher) A probe stage that has not come back for 2 s: logged, then at most every 30 s. +fn probe_check(now: u64) { + let k = PROBE_STAGE.load(Ordering::Acquire) as usize; + if k == 0 { + return; + } + let since = PROBE_SINCE.load(Ordering::Relaxed); + let stuck = now.saturating_sub(since); + if stuck < 2000 || now.saturating_sub(PROBE_REPORTED.load(Ordering::Relaxed)) < 30_000 { + return; + } + PROBE_REPORTED.store(now, Ordering::Relaxed); + dump_exception_ring(); + crate::xlog_warn!( + "[waits] fault probe: \"{}\" has not come back for {:.1} s (began at {:.3} s; the last full round ended at {:.3} s, round {})", + PROBE_STAGES[k.min(5)], + stuck as f64 / 1000.0, + since as f64 / 1000.0, + PROBE_LAST_OK.load(Ordering::Relaxed) as f64 / 1000.0, + PROBE_ROUNDS.load(Ordering::Relaxed) + ); +} + +// --- exceptions: the last ones raised (a ring), and a test of each kind ------------------------- +// +// Rosetta delivers every exception of the process through one thread of its own (its "exception +// server"); when that thread stops, every exception after – an access violation XCL handles, an +// instruction it emulates, the title's own – waits for ever, and the threads that raised them +// with it. The ring keeps the last exceptions the vectored handlers saw (time, thread, code, +// address, fault address, stack, the title's instruction bytes there); the watcher logs it when +// the fault probe stops coming back. `XCL_EXCEPTION_TEST_AT=`: a thread of XCL's raises +// one exception of each kind then, one after another, each handled here – which kind never +// comes back. + +const RING: usize = 256; +static RING_AT: AtomicUsize = AtomicUsize::new(0); +static RING_E: [[AtomicU64; 6]; RING] = [const { [const { AtomicU64::new(0) }; 6] }; RING]; +static RING_DUMPED: AtomicU32 = AtomicU32::new(0); + +const TESTS: [&str; 6] = [ + "ud2 (illegal instruction)", + "int3 (breakpoint)", + "hlt (privileged instruction)", + "a load from a non-canonical address", + "divss by zero, the exception unmasked in MXCSR (SIMD floating point)", + "div by zero (integer)", +]; +static TEST_TID: AtomicU32 = AtomicU32::new(0); +static TEST_ON: AtomicU32 = AtomicU32::new(0); +static TEST_SKIP: AtomicU32 = AtomicU32::new(0); +static TEST_SEEN: AtomicU32 = AtomicU32::new(0); +static TEST_STAGE: AtomicU32 = AtomicU32::new(0); +static TEST_SINCE: AtomicU64 = AtomicU64::new(0); + +unsafe extern "system" fn exception_ring(info: *mut windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_POINTERS) -> i32 { + let rec = &*(*info).ExceptionRecord; + let ctx = &mut *(*info).ContextRecord; + let code = rec.ExceptionCode as u32; + // the exception test's own: past the instruction, MXCSR masked again + if TEST_ON.load(Ordering::Acquire) != 0 && TEST_TID.load(Ordering::Relaxed) == GetCurrentThreadId() { + if code == 0x8000_0003 { + if *(ctx.Rip as *const u8) == 0xCC { + ctx.Rip += 1; + } + } else { + ctx.Rip += TEST_SKIP.load(Ordering::Relaxed) as u64; + } + ctx.MxCsr = 0x1F80; + ctx.Anonymous.FltSave.MxCsr = 0x1F80; + TEST_SEEN.store(code, Ordering::Release); + return -1; // EXCEPTION_CONTINUE_EXECUTION + } + let i = RING_AT.fetch_add(1, Ordering::Relaxed) % RING; + let e = &RING_E[i]; + let a = rec.ExceptionAddress as usize; + e[0].store(now_ms(), Ordering::Relaxed); + e[1].store((GetCurrentThreadId() as u64) << 32 | code as u64, Ordering::Relaxed); + e[2].store(a as u64, Ordering::Relaxed); + e[3].store(if rec.NumberParameters >= 2 { rec.ExceptionInformation[1] as u64 } else { 0 }, Ordering::Relaxed); + e[4].store(ctx.Rsp, Ordering::Relaxed); + let bytes = if crate::modules::image_base_for_addr(a).is_some() && crate::modules::image_base_for_addr(a + 7).is_some() { (a as *const u64).read_unaligned() } else { 0 }; + e[5].store(bytes, Ordering::Relaxed); + 0 // EXCEPTION_CONTINUE_SEARCH +} + +fn install_exception_ring() { + unsafe { + windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(exception_ring)); + } + let Some(at) = std::env::var("XCL_EXCEPTION_TEST_AT").ok().and_then(|v| v.trim().parse::().ok()) else { return }; + let _ = std::thread::Builder::new().name("xcl-exception-test".into()).spawn(move || unsafe { + let wait = at - now_ms() as f64 / 1000.0; + if wait > 0.0 { + std::thread::sleep(std::time::Duration::from_secs_f64(wait)); + } + TEST_TID.store(GetCurrentThreadId(), Ordering::Relaxed); + let one = 1.0f32; + for (k, name) in TESTS.iter().enumerate() { + let t0 = now_ms(); + TEST_SINCE.store(t0, Ordering::Relaxed); + TEST_SEEN.store(0, Ordering::Relaxed); + TEST_STAGE.store(k as u32 + 1, Ordering::Release); + crate::xlog_info!("[waits] exception test: {name} now"); + crate::log::flush(); + TEST_ON.store(1, Ordering::Release); + match k { + 0 => { + TEST_SKIP.store(2, Ordering::Relaxed); + core::arch::asm!("ud2"); + } + 1 => { + TEST_SKIP.store(1, Ordering::Relaxed); + core::arch::asm!("int3"); + } + 2 => { + TEST_SKIP.store(1, Ordering::Relaxed); + core::arch::asm!("hlt"); + } + 3 => { + // mov rax, [rax] (48 8B 00) + TEST_SKIP.store(3, Ordering::Relaxed); + core::arch::asm!("mov rax, 0x00f0000000001000", ".byte 0x48, 0x8b, 0x00", out("rax") _); + } + 4 => { + // divss xmm0, xmm1 (F3 0F 5E C1) with ZM clear + TEST_SKIP.store(4, Ordering::Relaxed); + core::arch::asm!( + "sub rsp, 8", "mov dword ptr [rsp], 0x1d80", "ldmxcsr [rsp]", + "movss xmm0, [{one}]", "xorps xmm1, xmm1", + ".byte 0xf3, 0x0f, 0x5e, 0xc1", + "mov dword ptr [rsp], 0x1f80", "ldmxcsr [rsp]", "add rsp, 8", + one = in(reg) &one, out("xmm0") _, out("xmm1") _, + ); + } + _ => { + // div ecx (F7 F1) + TEST_SKIP.store(2, Ordering::Relaxed); + core::arch::asm!("xor edx, edx", "xor eax, eax", "xor ecx, ecx", ".byte 0xf7, 0xf1", out("eax") _, out("edx") _, out("ecx") _); + } + } + TEST_ON.store(0, Ordering::Release); + crate::xlog_info!("[waits] exception test: {name}: came back in {} ms (exception {:#x})", now_ms().saturating_sub(t0), TEST_SEEN.load(Ordering::Acquire)); + TEST_STAGE.store(0, Ordering::Release); + std::thread::sleep(std::time::Duration::from_millis(500)); + } + }); +} + +/// (watcher) An exception test that has not come back for 2 s. +fn exception_test_check(now: u64) { + let k = TEST_STAGE.load(Ordering::Acquire) as usize; + if k == 0 { + return; + } + let since = TEST_SINCE.load(Ordering::Relaxed); + if now.saturating_sub(since) >= 2000 && now.saturating_sub(PROBE_REPORTED.load(Ordering::Relaxed)) >= 30_000 { + crate::xlog_warn!("[waits] exception test: {} has not come back for {:.1} s", TESTS[(k - 1).min(TESTS.len() - 1)], now.saturating_sub(since) as f64 / 1000.0); + } +} + +/// (watcher) The exceptions in the ring, oldest first (the last 64). +fn dump_exception_ring() { + if RING_DUMPED.swap(1, Ordering::AcqRel) != 0 { + return; + } + let at = RING_AT.load(Ordering::Relaxed); + let n = at.min(64); + crate::xlog_warn!("[waits] the last {n} exceptions before (of {at}):"); + for i in at - n..at { + let e = &RING_E[i % RING]; + let (t, tc, a, f, rsp, bytes) = (e[0].load(Ordering::Relaxed), e[1].load(Ordering::Relaxed), e[2].load(Ordering::Relaxed) as usize, e[3].load(Ordering::Relaxed), e[4].load(Ordering::Relaxed), e[5].load(Ordering::Relaxed)); + let place = if crate::modules::image_base_for_addr(a).is_some() { crate::modules::describe_address(a) } else { format!("{a:#x}") }; + crate::xlog_warn!("[waits] {:.3} s: thread {}, exception {:#010x} at {place} (fault address {f:#x}, rsp {rsp:#x}, code there {:02x?})", t as f64 / 1000.0, tc >> 32, tc as u32, bytes.to_le_bytes()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// the state number of XCL's own `x` (`X_*`) + fn kind(x: usize) -> u32 { + (KINDS.len() + x + 1) as u32 + } + + /// A pipeline state names its program by hash, stage and DXIL size; any other state, and a + /// pipeline state without a program (a stand-in's pointer), prints its argument as before. + #[test] + fn a_pipeline_state_names_its_program() { + let build = kind(X_BUILD_HERE); + assert_eq!(describe_arg(build, 0x56c0cd3b82a00c6e, program_info(b'C', 29059, false)), "56c0cd3b82a00c6e, CS, 29059 KB DXIL"); + assert_eq!(describe_arg(kind(X_PIPELINE_WAIT), 0x56c0cd3b82a00c6e, program_info(b'C', 272, true)), "56c0cd3b82a00c6e, CS, ~272 KB DXIL"); + assert_eq!(describe_arg(kind(X_BUILD_BIG), 0x1a2b, program_info(b'G', 0, false)), "0000000000001a2b, VS, DXIL size not known"); + assert_eq!(describe_arg(kind(X_GPU_FENCE), 0x1234, 0), "0x1234"); + assert_eq!(describe_arg(kind(X_GPU_FENCE), 0x1234, program_info(b'C', 7, false)), "0x1234", "not a pipeline state"); + assert_eq!(describe_arg(build, 0x7fa7_17d4_b010, 0), "0x7fa717d4b010", "a stand-in without a program"); + assert_eq!(kind_name(kind(X_BUILD_BIG)), "XCL: building a pipeline (big lane)"); + assert_eq!(kind_name(kind(X_DXC_MUTEX)), "XCL: waiting for the DXIL cache mutex"); + } + + /// A build of another program from the same place is a new state; binds waiting for one + /// pipeline after another stay one state, as other waits do within 500 ms. + #[test] + fn a_build_of_another_program_is_a_new_state_and_waits_stay_one() { + let s = Slot::new(); + let at = |i: usize| [0x10usize, 0x20].get(i).copied().unwrap_or(0); + let since = |s: &Slot| s.since.load(Ordering::Relaxed); + let (build, wait, fence) = (kind(X_BUILD_WORKER), kind(X_PIPELINE_WAIT), kind(X_GPU_FENCE)); + note_state(&s, build, 0xA, 0, at, 1000); + s.last_exit.store(1100, Ordering::Relaxed); + note_state(&s, build, 0xB, 0, at, 1200); + assert_eq!((since(&s), s.arg.load(Ordering::Relaxed)), (1200, 0xB), "another program's build: a state of its own"); + s.last_exit.store(1300, Ordering::Relaxed); + note_state(&s, wait, 0xC, program_info(b'C', 1, false), at, 1400); + assert_eq!(since(&s), 1400); + s.last_exit.store(1500, Ordering::Relaxed); + let d = program_info(b'C', 2, true); + note_state(&s, wait, 0xD, d, at, 1600); + assert_eq!(since(&s), 1400, "binds waiting for one pipeline after another: one state"); + assert_eq!((s.calls.load(Ordering::Relaxed), s.arg.load(Ordering::Relaxed), s.arg2.load(Ordering::Relaxed)), (2, 0xD, d), "the latest call's program"); + s.last_exit.store(1700, Ordering::Relaxed); + note_state(&s, fence, 0x1, 0, at, 1800); + assert_eq!(since(&s), 1800, "another kind"); + s.last_exit.store(1900, Ordering::Relaxed); + note_state(&s, fence, 0x2, 0, at, 2000); + assert_eq!(since(&s), 1800, "the same wait 100 ms after: one state"); + s.last_exit.store(2100, Ordering::Relaxed); + note_state(&s, fence, 0x3, 0, at, 2700); + assert_eq!(since(&s), 2700, "600 ms after: a new state"); + } + + /// A state in a call that merged several calls – binds waiting for one pipeline after another + /// – ends its text with how many and how long the current one has gone on (in the "no Present" + /// line's threads in XCL, the snapshot and the 10-s lines, each through the function that makes + /// its text: `in_xcl_entry`, `snapshot_state`, `scan_tail` – their one-line uses in in_xcl, + /// snapshot and scan are checked by reading, as the watcher runs only with XCL_WATCH_WAITS=1): + /// a merged 19.4 s of waits of at most 1.3 s no longer reads as one; a state of one call reads + /// as before. + #[test] + fn a_merged_waits_state_says_its_calls_and_how_long_the_current_one_is() { + let s = Slot::new(); + let at = |i: usize| [0x10usize, 0x20].get(i).copied().unwrap_or(0); + let wait = kind(X_PIPELINE_WAIT); + let info = program_info(b'C', 222, false); + note_state(&s, wait, 0x3b9a_a67a_004b_9371, info, at, 1_000); + assert_eq!(calls_tail(&s, 2_500), "", "one call: nothing more"); + assert_eq!(held_text(&s, wait, 2_500), "XCL: waiting for a pipeline still being built for 1.5 s (3b9aa67a004b9371, CS, 222 KB DXIL)"); + assert_eq!(in_text(&s, wait, 2_500, ""), "in XCL: waiting for a pipeline still being built for 1.5 s"); + // thirteen more waits, each begun 100 ms after the one before returned: one state + for k in 1..14u64 { + s.last_exit.store(900 + 1_400 * k, Ordering::Relaxed); + note_state(&s, wait, 0x3b9a_a67a_004b_9371, info, at, 1_000 + 1_400 * k); + } + assert_eq!((s.since.load(Ordering::Relaxed), s.calls.load(Ordering::Relaxed)), (1_000, 14), "merged"); + // 1.2 s into the latest (begun at 19.2 s) + let now = 20_400; + assert_eq!(calls_tail(&s, now), " (14 calls, this one 1.2 s)"); + assert_eq!(held_text(&s, wait, now), "XCL: waiting for a pipeline still being built for 19.4 s (3b9aa67a004b9371, CS, 222 KB DXIL) (14 calls, this one 1.2 s)"); + assert_eq!(in_text(&s, wait, now, ", held by thread 8"), "in XCL: waiting for a pipeline still being built for 19.4 s, held by thread 8 (14 calls, this one 1.2 s)"); + // … as each line says it, in a call on this (alive) thread: the "no Present" line's threads + // in XCL, the snapshot, the 10-s line (its polling state says its calls as before) + let tid = unsafe { GetCurrentThreadId() }; + s.tid.store(tid, Ordering::Relaxed); + s.in_call.store(1, Ordering::Relaxed); + assert_eq!(in_xcl_entry(&s, now), Some(format!("thread {tid}: XCL: waiting for a pipeline still being built for 19.4 s (3b9aa67a004b9371, CS, 222 KB DXIL) (14 calls, this one 1.2 s)"))); + assert_eq!(unsafe { snapshot_state(&s, wait, true, now - 1_300, now) }, "in XCL: waiting for a pipeline still being built for 19.4 s (14 calls, this one 1.2 s)"); + assert_eq!(scan_tail(&s, false, now), " (14 calls, this one 1.2 s)"); + assert_eq!(scan_tail(&s, true, now), " (14 calls)"); + assert_eq!(unsafe { snapshot_state(&s, wait, false, now - 100, now) }, "polling XCL: waiting for a pipeline still being built for 19.4 s (14 calls)"); + assert_eq!(unsafe { snapshot_state(&s, wait, false, now - 2_000, now) }, "RUNNING for 2.0 s since its last wait, XCL: waiting for a pipeline still being built returned"); + // (in_xcl: only a thread in a call, in one of XCL's own states) + s.in_call.store(0, Ordering::Relaxed); + assert_eq!(in_xcl_entry(&s, now), None, "not in a call"); + s.in_call.store(1, Ordering::Relaxed); + s.kind.store(1, Ordering::Relaxed); + assert_eq!(in_xcl_entry(&s, now), None, "in a title's wait (WaitForSingleObject)"); + s.kind.store(wait, Ordering::Relaxed); + s.in_call.store(0, Ordering::Relaxed); + // a new state: one call again + s.last_exit.store(now, Ordering::Relaxed); + note_state(&s, kind(X_GPU_FENCE), 0x1, 0, at, now + 100); + assert_eq!(calls_tail(&s, now + 600), "", "a new state: one call"); + } +} diff --git a/crates/xcl/src/widestore.rs b/crates/xcl/src/widestore.rs new file mode 100644 index 0000000..45aaf17 --- /dev/null +++ b/crates/xcl/src/widestore.rs @@ -0,0 +1,2166 @@ +//! A title's 256-bit unaligned stores (VMOVUPS / VMOVUPD / VMOVDQU m256, ymm) and its F16C +//! VCVTPS2PH with a memory destination, replaced when its image is loaded on a host whose +//! translator cannot resume them after a fault. +//! +//! Rosetta 2 cannot deliver a fault in some stores: it prints "rosetta error: unexpectedly need +//! to EmulateForward on a synchronous exception", the faulting thread never runs again, and +//! Rosetta's one exception thread stays with it, so every later exception of the process waits +//! for ever – the title freezes. Measured under CrossOver 26.3 on macOS 26.4, with a page that +//! is write-watched and still clean (read-only until written) right after one already written: +//! +//! * a 256-bit unaligned store that starts 17 to 32 bytes before the clean page, its first +//! 16 bytes on the written page: Rosetta stores the two halves apart, the second faults after +//! the first has landed. One that starts later (both halves fault, or the first does) resumes, +//! and so do the aligned and non-temporal forms, which cannot cross a page; +//! * VCVTPS2PH m64 / m128 wherever it faults: Rosetta converts before it stores; +//! * masked stores (`maskmov`). +//! +//! Every other store tried resumes: 128-bit and narrower moves (also across the boundary), +//! VEXTRACTF128 m128, lane extracts, MOVNTI, the x87 and MXCSR stores, FXSAVE, CMPXCHG16B and +//! the other atomics, REP STOSB / MOVSB. +//! +//! XCL's unified memory is write-watched by page protection (`gpu::uma`), and every title +//! submit re-arms the pages it scans (`title_textures`): a page the title keeps writing is clean +//! again after each submit, next to pages it has written since. GTA VI froze at such stores +//! within seconds of its first loading screen. +//! +//! Each store is done in parts Rosetta resumes: the low 16 bytes with the same instruction at +//! VEX.L = 0, the high 16 with VEXTRACTF128 m128, ymm, 1; VCVTPS2PH converts into a scratch +//! XMM (saved and restored whole, in two 16-byte halves, on the helper's stack) and stores that +//! with VMOVDQU m128 / VMOVQ m64. A fault on a part is an ordinary one (Wine's write watch, or +//! XCL, repairs the page and the part runs again); the low half may have landed by then, which +//! x86 allows for a store of 32 bytes. Nothing else changes: no general register, no flag, no +//! other vector register. +//! +//! Stores whose address is RSP- or RIP-based are left: they write the thread's stack or the +//! image's own sections, which are never write-watched. +//! +//! How a store reaches its helper: +//! +//! * five bytes or more: `call helper` and NOPs in the store's own bytes (no other byte of the +//! title changes, so a branch to any instruction still lands on one); +//! * four bytes (`vmovups [rdi], ymm0`), in this order: +//! - `jmp rel8` to a five-byte slot in the int3 padding between functions, holding `call +//! helper`; the helper first sets its return address to the store's end. Only the store's +//! bytes and padding change. +//! - an anchor: a `call` before the store, in the same straight run, whose helper does the +//! whole run – the stores in it in halves, the other instructions moved (an RSP-based +//! operand 8 further, as the call pushed its return; a RIP-relative one re-aimed; `mov +//! r64, rsp` as `lea r64, [rsp + 8]`), its conditional jumps taken there too (to the run's +//! end, or out: each way out sets its own return) – and returns past the run. The call +//! goes over one instruction of five bytes or more, or over several that end before the +//! store when those whose start it covers are conditional jumps (no branch lands on one: +//! it would read the flags of the branch into it) or every branch into the function is +//! known. No known branch may land in the run after the anchor (a loop's head, a return: +//! it would skip the helper), and the store's own bytes become a trap's too, for a branch +//! into the run nothing could see (a jump table's, an exception's continuation). +//! - the store and the instruction before it (or after it) become `call helper` and NOPs, the +//! helper doing both – only where nothing can branch to the second of them: the function +//! has no indirect jump and no exception handler, no direct branch in the image lands +//! there, and no call returns there. The moved instruction must not branch or be one XCL +//! emulates, nor use RSP but as a base (`relocate`). +//! - otherwise `int3` and three more: `eh` sends a thread that reaches it to a stub that +//! does the store and jumps back (an exception each time – the few sites left: a store a +//! branch lands on, or right after a call's return, in a function with branches not known). +//! +//! `loader` applies a plan after relocation, before the sections are protected. + +use crate::maskmov::{insn_len, Mem, GAP_MAX}; + +/// Which store. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + /// VEX.256.0F.WIG 11 /r: VMOVUPS m256, ymm + Ups, + /// VEX.256.66.0F.WIG 11 /r: VMOVUPD m256, ymm + Upd, + /// VEX.256.F3.0F.WIG 7F /r: VMOVDQU m256, ymm + Dqu, + /// VEX.128 / 256.66.0F3A.W0 1D /r ib: VCVTPS2PH m64 / m128, xmm / ymm, imm8 + Cvtps2ph, +} + +impl Kind { + pub const ALL: [Kind; 4] = [Kind::Ups, Kind::Upd, Kind::Dqu, Kind::Cvtps2ph]; + + pub fn name(self) -> &'static str { + match self { + Kind::Ups => "VMOVUPS", + Kind::Upd => "VMOVUPD", + Kind::Dqu => "VMOVDQU", + Kind::Cvtps2ph => "VCVTPS2PH", + } + } +} + +/// A store `decode` takes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Store { + pub kind: Kind, + /// Length in bytes. + pub len: u8, + /// VEX.L: a YMM source (VCVTPS2PH: 16 bytes stored, else 8). + pub wide: bool, + /// The register stored from (ModRM reg, VEX.R). + pub src: u8, + /// VCVTPS2PH's rounding control. + pub imm: u8, + pub mem: Mem, + /// The VEX prefix's length (2 or 3): the byte holding VEX.L is `vex - 1`. + pub vex: u8, +} + +impl Store { + /// Writes memory Rosetta never sees write-watched: the stack, or the image's own sections. + pub fn safe_place(&self) -> bool { + self.mem.rip || self.mem.base == Some(4) + } +} + +/// VEX + opcode + a memory ModRM of the stores `decode` takes (cheap, before the walk). +pub fn is_candidate(c: &[u8]) -> bool { + match *c { + [0xC5, b1, op, m, ..] => m >> 6 != 3 && b1 & 0x7C == 0x7C && matches!((op, b1 & 3), (0x11, 0 | 1) | (0x7F, 2)), + [0xC4, b1, b2, op, m, ..] => { + m >> 6 != 3 + && match (b1 & 0x1F, op) { + (1, 0x11) => b2 & 0x7C == 0x7C && b2 & 3 <= 1, + (1, 0x7F) => b2 & 0x7C == 0x7C && b2 & 3 == 2, + (3, 0x1D) => b2 & 0xF8 == 0x78 && b2 & 3 == 1, + _ => false, + } + } + _ => false, + } +} + +/// The memory operand of a ModRM byte at `c[at]` (mod != 3) with the X and B extension bits, +/// and the offset after it (and its SIB and displacement). +pub fn mem_operand(c: &[u8], at: usize, x: u8, b: u8) -> Option<(Mem, usize)> { + let m = *c.get(at)?; + let (md, rm) = (m >> 6, m & 7); + if md == 3 { + return None; + } + let mut i = at + 1; + let (mut base, mut index, mut scale, mut rip) = (None, None, 0, false); + let mut disp_len = match md { + 1 => 1, + 2 => 4, + _ => 0, + }; + if rm == 4 { + let sib = *c.get(i)?; + i += 1; + scale = sib >> 6; + let ix = ((sib >> 3) & 7) | x << 3; + if ix != 4 { + index = Some(ix); + } + if sib & 7 == 5 && md == 0 { + disp_len = 4; + } else { + base = Some((sib & 7) | b << 3); + } + } else if rm == 5 && md == 0 { + rip = true; + disp_len = 4; + } else { + base = Some(rm | b << 3); + } + let disp = match disp_len { + 1 => *c.get(i)? as i8 as i32, + 4 => i32::from_le_bytes([*c.get(i)?, *c.get(i + 1)?, *c.get(i + 2)?, *c.get(i + 3)?]), + _ => 0, + }; + Some((Mem { base, index, scale, disp, rip }, i + disp_len)) +} + +/// Decodes the store at the start of `c` (`None`: not one, or cut short). +pub fn decode(c: &[u8]) -> Option { + if !is_candidate(c) { + return None; + } + let (vex, r, x, b, l, pp, op) = if c[0] == 0xC5 { + (2usize, (!c[1] >> 7) & 1, 0, 0, (c[1] >> 2) & 1, c[1] & 3, c[2]) + } else { + (3, (!c[1] >> 7) & 1, (!c[1] >> 6) & 1, (!c[1] >> 5) & 1, (c[2] >> 2) & 1, c[2] & 3, c[3]) + }; + let kind = match (op, pp) { + (0x1D, 1) => Kind::Cvtps2ph, + (0x11, 0) => Kind::Ups, + (0x11, 1) => Kind::Upd, + (0x7F, 2) => Kind::Dqu, + _ => return None, + }; + let m = c[vex + 1]; + let (mem, mut end) = mem_operand(c, vex + 1, x, b)?; + let mut imm = 0; + if kind == Kind::Cvtps2ph { + imm = *c.get(end)?; + end += 1; + } + (end <= 15).then_some(Store { kind, len: end as u8, wide: l == 1, src: ((m >> 3) & 7) | r << 3, imm, mem, vex: vex as u8 }) +} + +/// ModRM (`reg` in its reg field), SIB and displacement of `mem` with displacement `disp` (not +/// RIP-relative); and the operand's X and B extension bits. +fn put_mem(out: &mut Vec, reg: u8, mem: &Mem, disp: i32) -> (u8, u8) { + let Mem { base, index, scale, .. } = *mem; + let (x, b) = (index.map_or(0, |i| i >> 3), base.map_or(0, |b| b >> 3)); + let sib = scale << 6 | index.map_or(4, |i| i & 7) << 3; + let reg = (reg & 7) << 3; + match base { + None => { + out.extend_from_slice(&[reg | 4, sib | 5]); + out.extend_from_slice(&disp.to_le_bytes()); + } + Some(bs) => { + // RBP / R13 as a base have no form without a displacement + let md = if disp == 0 && bs & 7 != 5 { + 0 + } else if i8::try_from(disp).is_ok() { + 1 + } else { + 2 + }; + if index.is_some() || bs & 7 == 4 { + out.extend_from_slice(&[md << 6 | reg | 4, sib | (bs & 7)]); + } else { + out.push(md << 6 | reg | (bs & 7)); + } + match md { + 1 => out.push(disp as u8), + 2 => out.extend_from_slice(&disp.to_le_bytes()), + _ => {} + } + } + } + (x, b) +} + +/// The operand of `vex`. +enum Operand<'a> { + Reg(u8), + Mem(&'a Mem, i32), +} + +/// A three-byte-VEX instruction: map (1: 0F, 3: 0F3A), pp, VEX.L, W0, no vvvv; ModRM reg +/// `reg`; the operand; an immediate byte. +fn vex(out: &mut Vec, map: u8, pp: u8, l: u8, op: u8, reg: u8, operand: Operand, imm: Option) { + let mut rest = Vec::with_capacity(8); + let (x, b) = match operand { + Operand::Reg(rm) => { + rest.push(0xC0 | (reg & 7) << 3 | (rm & 7)); + (0, rm >> 3) + } + Operand::Mem(m, disp) => put_mem(&mut rest, reg, m, disp), + }; + let r = reg >> 3; + out.extend_from_slice(&[0xC4, (1 - r) << 7 | (1 - x) << 6 | (1 - b) << 5 | map, 0x78 | l << 2 | pp, op]); + out.extend_from_slice(&rest); + if let Some(i) = imm { + out.push(i); + } +} + +/// Largest helper `helper` writes (a VCVTPS2PH one with a return-address fixup and moved +/// neighbours of at most 15 bytes each). +pub const HELPER_MAX: usize = 112; + +/// The register stack's frame a VCVTPS2PH helper uses below its return address. +const F16C_FRAME: u8 = 32; +/// `lea rsp, [rsp - 32]` (no flag written) +const F16C_PROLOGUE: [u8; 5] = [0x48, 0x8D, 0x64, 0x24, 0xE0]; +/// `lea rsp, [rsp + 32]` +const F16C_EPILOGUE: [u8; 5] = [0x48, 0x8D, 0x64, 0x24, 0x20]; + +/// Unwind data of a helper without a frame: `ret` is all there is to undo. +pub const UNWIND_INFO_LEAF: [u8; 4] = [0x01, 0, 0, 0]; +/// Unwind data of a VCVTPS2PH helper: a five-byte prologue that allocates 32 bytes. +pub const UNWIND_INFO_F16C: [u8; 8] = [0x01, F16C_PROLOGUE.len() as u8, 1, 0, F16C_PROLOGUE.len() as u8, ((F16C_FRAME / 8 - 1) << 4) | 2, 0, 0]; + +/// The unwind data a helper needs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Frame { + Leaf, + F16c, +} + +/// What surrounds a store in its helper. +#[derive(Clone, Copy, Debug, Default)] +pub struct Around<'a> { + /// The helper was reached from somewhere else than the store (a padding slot): its first + /// instruction sets the return address's low half to this. + pub ret_to: Option, + /// Instructions moved from before / after the store, run before / after it. + pub before: &'a [u8], + pub after: &'a [u8], +} + +/// Appends to `out` the helper for store `s` (its original bytes `bytes`), with what `around` +/// asks for, ending in `ret`; returns its unwind data, or `None` (nothing appended) for a store +/// `plan` does not replace (RSP- or RIP-based). +pub fn helper(s: &Store, bytes: &[u8], around: Around, out: &mut Vec) -> Option { + if s.safe_place() || bytes.len() < s.len as usize { + return None; + } + let start = out.len(); + if let Some(r) = around.ret_to { + // mov dword [rsp], imm32 + out.extend_from_slice(&[0xC7, 0x04, 0x24]); + out.extend_from_slice(&r.to_le_bytes()); + } + out.extend_from_slice(around.before); + let frame = if s.kind == Kind::Cvtps2ph { + let t = if s.src == 15 { 14 } else { 15 }; + let stack = Mem { base: Some(4), index: None, scale: 0, disp: 0, rip: false }; + out.extend_from_slice(&F16C_PROLOGUE); + vex(out, 1, 2, 0, 0x7F, t, Operand::Mem(&stack, 0), None); // vmovdqu [rsp], xmmT + vex(out, 3, 1, 1, 0x19, t, Operand::Mem(&stack, 16), Some(1)); // vextractf128 [rsp + 16], ymmT, 1 + vex(out, 3, 1, s.wide as u8, 0x1D, s.src, Operand::Reg(t), Some(s.imm)); // vcvtps2ph xmmT, src, imm + if s.wide { + vex(out, 1, 2, 0, 0x7F, t, Operand::Mem(&s.mem, s.mem.disp), None); // vmovdqu m128, xmmT + } else { + vex(out, 1, 1, 0, 0xD6, t, Operand::Mem(&s.mem, s.mem.disp), None); // vmovq m64, xmmT + } + vex(out, 1, 2, 1, 0x6F, t, Operand::Mem(&stack, 0), None); // vmovdqu ymmT, [rsp] + out.extend_from_slice(&F16C_EPILOGUE); + Frame::F16c + } else { + let Some(high) = s.mem.disp.checked_add(16) else { + out.truncate(start); + return None; + }; + // the low half: the store itself at VEX.L = 0 + let mut low = bytes[..s.len as usize].to_vec(); + low[s.vex as usize - 1] &= !4; + out.extend_from_slice(&low); + vex(out, 3, 1, 1, 0x19, s.src, Operand::Mem(&s.mem, high), Some(1)); // vextractf128 [m + 16], src, 1 + Frame::Leaf + }; + out.extend_from_slice(around.after); + out.push(0xC3); + debug_assert!(out.len() - start <= HELPER_MAX); + Some(frame) +} + +/// The bytes that replace `len` bytes at `site` (5..=30): `call helper`, then NOPs. +pub fn call_site(site: u64, len: usize, helper: u64) -> Option> { + if !(5..=30).contains(&len) { + return None; + } + let rel = i32::try_from(helper.wrapping_sub(site.wrapping_add(5)) as i64).ok()?; + let mut b = vec![0xE8]; + b.extend_from_slice(&rel.to_le_bytes()); + b.resize(len, 0x90); + Some(b) +} + +/// `jmp rel8` from a four-byte site to a slot, then two int3: `None` out of reach. +pub fn short_jump(site: u64, slot: u64) -> Option<[u8; 4]> { + let rel = i8::try_from(slot.wrapping_sub(site.wrapping_add(2)) as i64).ok()?; + Some([0xEB, rel as u8, 0xCC, 0xCC]) +} + +/// Why a store was left as it is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Skip { + /// In no function of the unwind data, and further than `GAP_MAX` from the end of one. + NoFunction, + /// An instruction on the way there (at this RVA) is not one the walk knows. + Undecodable(u32), + /// The walk passes over it: the bytes are part of another instruction (or follow a prefix). + NotAtBoundary, + /// At a boundary but not a store this takes. + Form, +} + +/// How a site reaches its helper. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Patch { + /// `call helper` + NOPs over `[start, start + len)` – the store, and a moved neighbour. + Call { start: u32, len: u8 }, + /// `jmp rel8` at the store to a slot (an RVA in padding) holding `call helper`. + Slot { slot: u32 }, + /// `int3` ×4 at the store; `eh` sends a thread that reaches it to the helper's stub. + Trap, + /// Done by the helper of the instruction at `anchor` (five bytes or more, before the store + /// in the same straight run that no known branch lands in): its call runs everything from + /// there to the store's end and returns past it. The store's own bytes become a `Trap`'s + /// too (its stub is the site's `helper`), for a branch into the run the walk could not see + /// – a jump table's, an exception's continuation – which then costs an exception, not a + /// store Rosetta cannot resume. + Anchored { anchor: u32 }, +} + +/// A store to replace. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Site { + pub rva: u32, + pub store: Store, + /// Offset of its helper in `Plan::code` (for `Trap` and `Anchored`: of its stub, which + /// does the store and jumps back past it). + pub helper: u32, + /// Not in a function of the unwind data. + pub leaf: bool, + pub patch: Patch, +} + +/// What to do to an image. +#[derive(Default, Debug)] +pub struct Plan { + pub sites: Vec, + pub skipped: Vec<(u32, Skip)>, + /// Stores left because they write the stack or the image (RSP-, RIP-based). + pub safe_place: usize, + /// The helpers, each at a multiple of 16; stores with the same bytes share one where they + /// are reached by a call at the store. + pub code: Vec, + /// (start, end, unwind data) of each helper in `code`, ascending. + pub helpers: Vec<(u32, u32, Frame)>, + /// Four-byte sites by how they were done: slot, anchored, merged with a neighbour, trap. + pub short: [usize; 4], + /// Anchors that are not stores themselves: (RVA, length, helper) – `call helper` + NOPs. + pub anchors: Vec<(u32, u8, u32)>, + /// RIP-relative displacements in moved instructions, fixed once `code` has its address: + /// (offset of the displacement in `code`, offset of the instruction's end, absolute target). + pub fixups: Vec<(u32, u32, u64)>, +} + +#[cfg(test)] +thread_local! { + /// A store whose anchor walk `plan` prints (`XCL_PLAN_DEBUG`). + static DEBUG_RVA: std::cell::Cell = const { std::cell::Cell::new(u32::MAX) }; +} + +/// A straight run a helper does for an anchor: at most this many instructions after it. +const RUN_MAX: usize = 8; + +/// Writes a trap's stub for the four-byte store `s` (`bytes`) whose end is at `end`: the +/// store in halves, then `jmp qword [rip + 0]; dq end`. Its offset in `p.code`. +fn trap_stub(p: &mut Plan, s: &Store, bytes: &[u8], end: u64) -> Option { + let mut stub = Vec::new(); + if helper(s, bytes, Around::default(), &mut stub) != Some(Frame::Leaf) { + return None; + } + stub.pop(); // its ret + stub.extend_from_slice(&[0xFF, 0x25, 0, 0, 0, 0]); + stub.extend_from_slice(&end.to_le_bytes()); + while p.code.len() % 16 != 0 { + p.code.push(0xCC); + } + let h = p.code.len() as u32; + p.code.extend_from_slice(&stub); + p.helpers.push((h, p.code.len() as u32, Frame::Leaf)); + Some(h) +} + +/// What an instruction is to the planner. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Insn { + pub len: u8, + /// A branch, call, return, interrupt or trap. + pub flow: bool, + /// A direct branch's or call's target, relative to the instruction's start. + pub target: Option, + /// An indirect jump that is not RIP-relative (a jump table, a computed tail call). + pub indirect_jump: bool, + /// A call (the instruction after it is a return target). + pub call: bool, + /// Can run in a helper (`relocate`): not flow, RSP not a register operand nor used + /// implicitly (an RSP- or RIP-based memory operand is fine: `relocate` adjusts it, and so is + /// `mov r64, rsp`: `rsp_copy`), nothing a translator traps on or XCL emulates, no masked or + /// 256-bit store of the kinds replaced here. + pub movable: bool, + /// A conditional jump (`jcc rel8` / `jcc rel32`, not `loop` / `jrcxz`): its condition code. + pub cond: Option, + /// `mov r64, rsp` (either form): the register it sets – `lea r64, [rsp + frame]` in a helper. + pub rsp_copy: Option, + /// The memory operand, if any: (operand, offset of its displacement, displacement bytes). + pub mem: Option<(Mem, u8, u8)>, + /// Offset of the ModRM byte (when `mem`). + pub modrm: u8, +} + +/// `insn_len`, and what the planner needs to know about the instruction. +pub fn insn_info(c: &[u8]) -> Option { + let len = insn_len(c)?; + let mut i = 0usize; + let (mut p66, mut pf2, mut pf3) = (false, false, false); + loop { + match c[i] { + 0x66 => p66 = true, + 0xF2 => pf2 = true, + 0xF3 => pf3 = true, + 0x67 | 0xF0 | 0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 => {} + _ => break, + } + i += 1; + } + let (mut rex_r, mut rex_x, mut rex_b, mut rex) = (0u8, 0u8, 0u8, false); + if c[i] & 0xF0 == 0x40 { + (rex_r, rex_x, rex_b, rex) = ((c[i] >> 2) & 1, (c[i] >> 1) & 1, c[i] & 1, true); + i += 1; + } + let op = c[i]; + let mut ins = Insn { len: len as u8, ..Default::default() }; + // control flow, traps, privileged and system instructions + let rel = |at: usize, n: usize| -> i64 { + match n { + 1 => c[at] as i8 as i64, + _ => i32::from_le_bytes([c[at], c[at + 1], c[at + 2], c[at + 3]]) as i64, + } + }; + let modrm_at: Option; + let mut vvvv = 0u8; + let mut vex_map = 0u8; + let mut vex_op = 0u8; + match op { + 0x70..=0x7F | 0xEB | 0xE0..=0xE3 => { + ins.flow = true; + ins.target = Some(len as i64 + rel(len - 1, 1)); + if op & 0xF0 == 0x70 { + ins.cond = Some(op & 0xF); + } + return Some(ins); + } + 0xE8 | 0xE9 => { + ins.flow = true; + ins.call = op == 0xE8; + ins.target = Some(len as i64 + rel(len - 4, 4)); + return Some(ins); + } + 0xC2 | 0xC3 | 0xCA | 0xCB | 0xCC | 0xCD | 0xCF | 0xF1 | 0xF4 | 0xFA | 0xFB | 0xE4..=0xE7 | 0xEC..=0xEF | 0x6C..=0x6F => { + ins.flow = true; + return Some(ins); + } + 0xFF => { + let m = c[i + 1]; + let r = (m >> 3) & 7; + if (2..=5).contains(&r) { + ins.flow = true; + ins.call = r == 2 || r == 3; + // jmp r/m64: RIP-relative is an import or a tail call through a pointer + ins.indirect_jump = r == 5 || (r == 4 && !(m >> 6 == 0 && m & 7 == 5)); + return Some(ins); + } + if r == 6 { + return Some(ins); // push r/m + } + modrm_at = Some(i + 1); + } + 0xC4 | 0xC5 => { + let (r, x, b, map, w_vvvv) = if op == 0xC5 { + ((!c[i + 1] >> 7) & 1, 0, 0, 1, c[i + 1]) + } else { + ((!c[i + 1] >> 7) & 1, (!c[i + 1] >> 6) & 1, (!c[i + 1] >> 5) & 1, c[i + 1] & 0x1F, c[i + 2]) + }; + (rex_r, rex_x, rex_b) = (r, x, b); + vvvv = (!w_vvvv >> 3) & 15; + vex_map = map; + let at = i + if op == 0xC5 { 2 } else { 3 }; + vex_op = c[at]; + if map == 1 && vex_op == 0x77 { + ins.movable = true; // vzeroupper / vzeroall + return Some(ins); + } + modrm_at = Some(at + 1); + } + 0x0F => { + let o = c[i + 1]; + match o { + 0x80..=0x8F => { + ins.flow = true; + ins.target = Some(len as i64 + rel(len - 4, 4)); + ins.cond = Some(o & 0xF); + return Some(ins); + } + // system, traps, and what XCL emulates or a translator may trap on + 0x00..=0x09 | 0x0B | 0x0D | 0x30..=0x37 | 0xA0..=0xA2 | 0xA8..=0xAA | 0xAE | 0xC7 | 0xFF => return Some(ins), + 0x78 | 0x79 if p66 || pf2 => return Some(ins), + 0x2B if pf2 || pf3 => return Some(ins), + 0x38 => { + if c[i + 2] == 0xF6 || c[i + 2] == 0xF0 || c[i + 2] == 0xF1 { + return Some(ins); // ADCX / ADOX, MOVBE + } + modrm_at = Some(i + 3); + } + 0x3A => modrm_at = Some(i + 3), + 0x40..=0x4F | 0x10..=0x17 | 0x18..=0x1F | 0x28..=0x2F | 0x50..=0x7F | 0x90..=0x9F | 0xA3..=0xA5 | 0xAB..=0xAD | 0xAF | 0xB0..=0xBF | 0xC0..=0xC6 | 0xD0..=0xFE => { + modrm_at = Some(i + 2); + } + _ => return Some(ins), + } + } + // implicit stack use, string I/O, segment pushes / pops, BCD and other odd ones + 0x50..=0x5F | 0x68 | 0x6A | 0x8F | 0x9C | 0x9D | 0xC8 | 0xC9 | 0x9A | 0xEA => return Some(ins), + // the plain ALU and move groups with a ModRM byte + 0x00..=0x3F if op & 7 <= 3 => modrm_at = Some(i + 1), + 0x00..=0x3F => { + ins.movable = op & 7 <= 5; // AL / eAX, imm + return Some(ins); + } + 0x63 | 0x69 | 0x6B | 0x80..=0x8B | 0x8D | 0xC0 | 0xC1 | 0xC6 | 0xC7 | 0xD0..=0xD3 | 0xF6 | 0xF7 | 0xFE => { + modrm_at = Some(i + 1); + } + 0x90..=0x99 | 0xA8 | 0xA9 | 0xB0..=0xBF => { + // NOP, XCHG eAX, CBW / CWD; TEST eAX, imm; MOV r, imm – not into RSP or SPL (B4 + // with a REX prefix) + ins.movable = !((matches!(op, 0x94 | 0xBC) || op == 0xB4 && rex) && rex_b == 0); + return Some(ins); + } + _ => return Some(ins), + } + let Some(at) = modrm_at else { return Some(ins) }; + let m = *c.get(at)?; + let (md, reg, rm) = (m >> 6, ((m >> 3) & 7) | rex_r << 3, (m & 7) | rex_b << 3); + // DIV / IDIV can raise #DE, MUL / IMUL by memory are fine; F6/F7 /6 /7 left + if matches!(op, 0xF6 | 0xF7) && (m >> 3) & 7 >= 6 { + return Some(ins); + } + // masked stores (`maskmov`) and the stores replaced here stay where they are + if (op == 0xC4 || op == 0xC5) && ((vex_map == 2 && matches!(vex_op, 0x2C..=0x2F | 0x8C | 0x8E)) || is_candidate(&c[i..])) { + return Some(ins); + } + let mut rsp = reg == 4 || (op == 0xC4 || op == 0xC5) && vvvv == 4; + if md == 3 { + rsp |= rm == 4; + // mov r64, rsp (89 /r with RSP the source, 8B /r with RSP the r/m): a copy of RSP + let w = rex && c[i - 1] & 8 != 0; + let copy = match op { + 0x89 if w && reg == 4 && rm != 4 => Some(rm), + 0x8B if w && rm == 4 && reg != 4 => Some(reg), + _ => None, + }; + if copy.is_some() && !p66 && !pf2 && !pf3 { + ins.rsp_copy = copy; + ins.movable = true; + return Some(ins); + } + } else { + let Some((mem, end)) = mem_operand(c, at, rex_x, rex_b) else { return Some(ins) }; + let disp_len = if mem.rip || mem.base.is_none() { 4 } else { [0, 1, 4][md as usize] }; + ins.mem = Some((mem, (end - disp_len) as u8, disp_len as u8)); + ins.modrm = at as u8; + rsp |= mem.index == Some(4); + } + ins.movable = !rsp; + Some(ins) +} + +/// The instruction `c` (`ins` its `insn_info`, `at` its address) as it must be to run in a +/// helper entered by `call` (RSP lower by `frame`): an RSP-based displacement grows by `frame` +/// (its form may grow too), a RIP-relative one is to be fixed once the helper's address is +/// known – (offset of the displacement, offset of the instruction's end, the absolute target). +pub fn relocate(c: &[u8], ins: &Insn, at: u64, frame: i32) -> Option<(Vec, Option<(usize, usize, u64)>)> { + let len = ins.len as usize; + let c = c.get(..len)?; + if let Some(d) = ins.rsp_copy { + // lea d, [rsp + frame] + let frame = i8::try_from(frame).ok()?; + return Some((vec![0x48 | (d >> 3) << 2, 0x8D, 0x44 | (d & 7) << 3, 0x24, frame as u8], None)); + } + let Some((mem, disp_at, disp_len)) = ins.mem else { return Some((c.to_vec(), None)) }; + let (disp_at, disp_len) = (disp_at as usize, disp_len as usize); + if mem.rip { + let target = at.wrapping_add(len as u64).wrapping_add(mem.disp as i64 as u64); + return Some((c.to_vec(), Some((disp_at, len, target)))); + } + if mem.base != Some(4) { + return Some((c.to_vec(), None)); + } + // [rsp + index * s + disp]: always a SIB; rewrite mod and the displacement + let disp = mem.disp.checked_add(frame)?; + let md = if disp == 0 { 0 } else if i8::try_from(disp).is_ok() { 1 } else { 2 }; + let modrm = ins.modrm as usize; + let mut out = c[..disp_at].to_vec(); + out[modrm] = (out[modrm] & 0x3F) | md << 6; + match md { + 1 => out.push(disp as u8), + 2 => out.extend_from_slice(&disp.to_le_bytes()), + _ => {} + } + out.extend_from_slice(&c[disp_at + disp_len..]); + (out.len() <= 15).then_some((out, None)) +} + +/// Writes the plan for an image: the stores (`decode`) at instruction boundaries of the +/// executable sections, their helpers, and how each is reached. `image` is the image as mapped +/// (relocated), `base` its address, `sections` the (RVA, length) of each executable section, +/// `functions` the (start, end, flags) of the unwind data's entries – flags: bit 0 an exception +/// handler, bit 1 none known (its unwind data could not be read). +pub fn plan(image: &[u8], base: u64, sections: &[(u32, u32)], functions: &[(u32, u32, u8)]) -> Plan { + let mut p = Plan::default(); + let mut funcs: Vec<(u32, u32, u8)> = functions.iter().copied().filter(|f| f.0 < f.1).collect(); + funcs.sort_unstable(); + funcs.dedup_by_key(|f| f.0); + let mut shared: std::collections::HashMap, u32> = std::collections::HashMap::new(); + for &(s_rva, s_len) in sections { + let (s_start, s_end) = (s_rva as usize, (s_rva as usize).saturating_add(s_len as usize).min(image.len())); + let Some(code) = image.get(s_start..s_end) else { continue }; + // 1. every function (and leaf gap) walked once: instruction starts, direct targets + // (and returns), what is reached by falling through, the stores + let n = code.len(); + let words = n / 64 + 1; + // `multi`: more than one branch (or return) lands there + let (mut starts, mut targets, mut fall, mut multi) = (vec![0u64; words], vec![0u64; words], vec![0u64; words], vec![0u64; words]); + fn set(v: &mut [u64], k: usize) { + v[k / 64] |= 1 << (k % 64); + } + fn has(v: &[u64], k: usize) -> bool { + v[k / 64] & (1 << (k % 64)) != 0 + } + fn land(targets: &mut [u64], multi: &mut [u64], k: usize) { + if has(targets, k) { + set(multi, k); + } else { + set(targets, k); + } + } + // (start, end, flags, leaf) of each walked range, section offsets, not overlapping + let mut ranges: Vec<(usize, usize, u8, bool)> = Vec::new(); + let first = funcs.partition_point(|f| (f.1 as usize) <= s_start); + let mut prev_end = s_start; + for k in first..=funcs.len() { + let f = funcs.get(k).copied().filter(|f| (f.0 as usize) < s_end); + let next_start = f.map_or(s_end, |f| f.0 as usize); + // the gap before this function: leaf functions without unwind data and padding + if next_start > prev_end && next_start - prev_end <= GAP_MAX as usize { + ranges.push((prev_end - s_start, next_start - s_start, 0, true)); + } + let Some(f) = f else { break }; + let (fs, fe) = ((f.0 as usize).max(s_start), (f.1 as usize).min(s_end)); + if fs >= prev_end && fs < fe { + ranges.push((fs - s_start, fe - s_start, f.2, false)); + prev_end = fe; + } + } + // per range: (an indirect jump in it, where its walk stopped short) + let mut range_flags: Vec<(bool, Option)> = Vec::with_capacity(ranges.len()); + let mut found: Vec<(usize, usize, Store)> = Vec::new(); // (offset, range, store) + for (ri, &(rs, re, _, _)) in ranges.iter().enumerate() { + let (mut at, mut indirect, mut bad) = (rs, false, None); + while at < re { + let Some(ins) = insn_info(&code[at..re]) else { + bad = Some(at); + break; + }; + set(&mut starts, at); + let next = at + ins.len as usize; + if let Some(t) = ins.target { + let t = at as i64 + t; + if (0..n as i64).contains(&t) { + land(&mut targets, &mut multi, t as usize); + } + } + if next < n { + if ins.call { + land(&mut targets, &mut multi, next); // a return lands there + } + // falls through to the next one unless it always goes elsewhere + let ends = matches!(code[at], 0xC3 | 0xC2 | 0xCC | 0xEB | 0xE9 | 0xF4) || ins.indirect_jump || (ins.flow && !ins.call && ins.target.is_none() && code[at] == 0xFF); + if !ends { + set(&mut fall, next); + } + } + indirect |= ins.indirect_jump; + if is_candidate(&code[at..re]) { + if let Some(s) = decode(&code[at..re]).filter(|s| s.len == ins.len) { + found.push((at, ri, s)); + } + } + at = next; + } + range_flags.push((indirect, bad)); + } + // padding slots: five int3 in a gap, each one an instruction start of the gap's walk, + // none a branch target or reached by falling through + let mut free: Vec = Vec::new(); + for &(rs, re, _, leaf) in &ranges { + if !leaf { + continue; + } + let mut k = rs; + while k + 5 <= re { + if code[k..k + 5].iter().all(|&b| b == 0xCC) && (k..k + 5).all(|j| has(&starts, j) && !has(&targets, j)) && !has(&fall, k) { + free.push(k); + k += 5; + } else { + k += 1; + } + } + } + let mut free_at = 0usize; // first slot not used (slots are taken in order) + let mut free_used = vec![false; free.len()]; + // bytes some patch has: the stores', and those a merge or an anchor takes + let mut taken = vec![0u64; words]; + for &(at, _, s) in &found { + for j in at..at + s.len as usize { + set(&mut taken, j); + } + } + let store_at: std::collections::HashMap = found.iter().map(|&(at, _, s)| (at, s)).collect(); + // anchor offset → (end of the run it does, the anchor's site index if it is a store, + // bytes its call goes over) + let mut groups: std::collections::BTreeMap, usize)> = std::collections::BTreeMap::new(); + // each run's instructions → its anchor + let mut in_run: std::collections::HashMap = std::collections::HashMap::new(); + // (site index) of stores done by an anchor, to point at its helper once it is written + let mut anchored: Vec<(usize, usize)> = Vec::new(); // (site index, anchor offset) + let mut site_of: std::collections::HashMap = std::collections::HashMap::new(); // offset → site index + // 2. each store + for &(at, ri, s) in &found { + let rva = (s_start + at) as u32; + let (rs, re, flags, leaf) = ranges[ri]; + if s.safe_place() { + p.safe_place += 1; + continue; + } + let bytes = &code[at..at + s.len as usize]; + let mut add = |p: &mut Plan, key: Option>, around: Around| -> Option { + if let Some(h) = key.as_ref().and_then(|k| shared.get(k)) { + return Some(*h); + } + while p.code.len() % 16 != 0 { + p.code.push(0xCC); + } + let h = p.code.len() as u32; + let frame = helper(&s, bytes, around, &mut p.code)?; + p.helpers.push((h, p.code.len() as u32, frame)); + if let Some(k) = key { + shared.insert(k, h); + } + Some(h) + }; + if s.len >= 5 { + let Some(h) = add(&mut p, Some(bytes.to_vec()), Around::default()) else { + p.skipped.push((rva, Skip::Form)); + continue; + }; + site_of.insert(at, p.sites.len()); + p.sites.push(Site { rva, store: s, helper: h, leaf, patch: Patch::Call { start: rva, len: s.len } }); + continue; + } + // four bytes: a padding slot in reach (slot + 5 and the store's end in the same + // 4 GiB, as the helper only rewrites the low half of its return address) + let end = at + 4; + let ret = base + (s_start + end) as u64; + while free_at < free.len() && (free[free_at] as i64) < at as i64 + 2 - 128 { + free_at += 1; + } + let slot = (free_at..free.len()) + .take_while(|&k| free[k] as i64 <= at as i64 + 2 + 127) + .find(|&k| !free_used[k] && (base + (s_start + free[k] + 5) as u64) >> 32 == ret >> 32); + if let Some(k) = slot { + if let Some(h) = add(&mut p, None, Around { ret_to: Some(ret as u32), ..Default::default() }) { + free_used[k] = true; + site_of.insert(at, p.sites.len()); + p.sites.push(Site { rva, store: s, helper: h, leaf, patch: Patch::Slot { slot: (s_start + free[k]) as u32 } }); + p.short[0] += 1; + continue; + } + } + // An anchor: where a call can go before the store, in a straight run of + // instructions a helper can do – moved ones; stores (the anchor may be one; no + // VCVTPS2PH, whose helper has a frame, and none left on the stack or in the image); + // conditional jumps, which the helper takes too (to an instruction of the run, to its + // end, or out: it returns to their target) – none after the anchor a known branch + // from outside lands on (a loop's head, a return: that branch would skip the helper). + // The call goes over one instruction of five bytes or more, or over several that end + // before the store when those whose start it covers are conditional jumps no branch + // lands on (nothing branches to one unseen: it would read the flags of the branch + // into it) or every branch into the function is known. A store whose run reaches an + // instruction of an earlier run (a merge's, an anchor's) joins that run instead. + let complete = flags == 0 && !range_flags[ri].0 && range_flags[ri].1.is_none(); + let near = |t: i64| ((base as i64 + s_start as i64 + t) as u64) >> 32 == ret >> 32; + // A loop around the store: on from it, instructions a helper can do, up to a + // conditional jump back to the store or before it that is the only branch landing + // there – the run goes on to that jump, and the whole loop runs in the helper (its + // head may then be in the run: no branch from outside lands on it). + let mut run_end = end; + let mut back = None; // the loop's head + let mut ext: Vec = Vec::new(); // the run's instructions after the store + { + let mut k2 = end; + let mut seen = Vec::new(); + for _ in 0..RUN_MAX { + if k2 >= re || !has(&starts, k2) || has(&targets, k2) { + break; + } + let Some(ki) = insn_info(&code[k2..re]) else { break }; + seen.push(k2); + if let (Some(_), Some(t)) = (ki.cond, ki.target) { + let t = k2 as i64 + t; + if !near(t) { + break; + } + if (rs as i64..=at as i64).contains(&t) { + if !has(&multi, t as usize) { + run_end = k2 + ki.len as usize; + back = Some(t as usize); + ext = seen; + } + break; + } + } else { + let st = store_at.get(&k2).copied(); + if ki.flow || st.is_some_and(|w| w.kind == Kind::Cvtps2ph || w.safe_place()) || (!ki.movable && st.is_none()) || relocate(&code[k2..re], &ki, 0, 8).is_none() { + break; + } + } + k2 += ki.len as usize; + } + } + let mut k = at; + let mut anchor = None; // (offset, own, bytes the call goes over) + let mut after: Vec<(usize, usize, bool, bool)> = Vec::new(); // the run's instructions after k: (start, length, a conditional jump, a branch target) + #[cfg(test)] + let debug = DEBUG_RVA.with(|d| d.get()) == rva; + for _ in 0..RUN_MAX { + if has(&targets, k) && back != Some(k) { + #[cfg(test)] + if debug { + println!(" {:#x}: a branch target", s_start + k); + } + break; + } + let Some(pk) = (k.saturating_sub(15).max(rs)..k).rev().find(|&j| has(&starts, j)) else { break }; + let Some(pi) = insn_info(&code[pk..re]).filter(|pi| pk + pi.len as usize == k) else { break }; + let st = store_at.get(&pk).copied(); + #[cfg(test)] + if debug { + println!(" {:#x}: {:02x?} {pi:?} store {st:?} taken {} run {:?}", s_start + pk, &code[pk..k], (pk..k).any(|j| has(&taken, j)), in_run.get(&pk)); + } + let fits = match pi.cond { + Some(_) => pi.target.is_some_and(|t| near(pk as i64 + t)), + None => !(pi.flow || st.is_some_and(|w| w.kind == Kind::Cvtps2ph || w.safe_place()) || (!pi.movable && st.is_none()) || relocate(&code[pk..re], &pi, 0, 8).is_none()), + }; + if !fits { + break; + } + if let Some(&g) = in_run.get(&pk) { + let (_, own, len) = groups[&g]; + anchor = Some((g, own.is_some(), len)); + break; + } + if pi.len >= 5 { + // its bytes must be its own: a store site of its own, the anchor of runs + // before this one, or no other patch's + let own = st.is_some() && site_of.contains_key(&pk); + if own || groups.contains_key(&pk) || !(pk..k).any(|j| has(&taken, j)) { + anchor = Some((pk, own, pi.len as usize)); + } + break; + } + if pk + 5 <= at { + let covered: Vec<&(usize, usize, bool, bool)> = after.iter().filter(|r| r.0 < pk + 5).collect(); + let len = covered.iter().map(|r| r.0 + r.1).max().unwrap_or(0).max(pk + 5) - pk; + if covered.iter().all(|r| complete || r.2 && !r.3) && (groups.contains_key(&pk) || !(pk..pk + len).any(|j| has(&taken, j))) { + anchor = Some((pk, false, len)); + break; + } + } + after.push((pk, pi.len as usize, pi.cond.is_some(), has(&targets, pk))); + k = pk; + } + if let Some((a, own, len)) = anchor.filter(|&(a, _, _)| (base + (s_start + a + 5) as u64) >> 32 == ret >> 32) { + let Some(stub) = trap_stub(&mut p, &s, bytes, ret) else { + p.skipped.push((rva, Skip::Form)); + continue; + }; + let e = groups.entry(a).or_insert((run_end, if own { site_of.get(&a).copied() } else { None }, len)); + e.0 = e.0.max(run_end); + if !own { + for j in a..a + len { + set(&mut taken, j); + } + } + // the run's instructions, for stores after this one to join + in_run.insert(a, a); + for r in &after { + in_run.insert(r.0, a); + } + in_run.insert(at, a); + for &x in &ext { + in_run.insert(x, a); + } + anchored.push((p.sites.len(), a)); + site_of.insert(at, p.sites.len()); + p.sites.push(Site { rva, store: s, helper: stub, leaf, patch: Patch::Anchored { anchor: (s_start + a) as u32 } }); + p.short[1] += 1; + continue; + } + // a neighbour moved into the helper, where nothing can branch to the second of the + // two: the function has no indirect jump and no exception handler and was walked + // to its end, and no direct branch or return lands there – a run of two, which a + // store after them may join + if complete { + let mut merged = false; + let prev = (at.saturating_sub(15).max(rs)..at).rev().find(|&j| has(&starts, j)); + if let Some(pk) = prev.filter(|&pk| !has(&targets, at) && !(pk..at).any(|j| has(&taken, j))) { + if let Some(pi) = insn_info(&code[pk..at]).filter(|pi| pi.movable && pi.len as usize == at - pk) { + if relocate(&code[pk..at], &pi, 0, 8).is_some() { + for j in pk..at { + set(&mut taken, j); + } + let si = p.sites.len(); + groups.insert(pk, (end, Some(si), end - pk)); + in_run.insert(pk, pk); + in_run.insert(at, pk); + site_of.insert(at, si); + p.sites.push(Site { rva, store: s, helper: 0, leaf, patch: Patch::Call { start: (s_start + pk) as u32, len: (end - pk) as u8 } }); + merged = true; + } + } + } + if !merged && end < re && has(&starts, end) && !has(&targets, end) { + if let Some(ni) = insn_info(&code[end..re]).filter(|ni| ni.movable) { + let after_end = end + ni.len as usize; + if !(end..after_end).any(|j| has(&taken, j)) && relocate(&code[end..re], &ni, 0, 8).is_some() { + for j in end..after_end { + set(&mut taken, j); + } + let si = p.sites.len(); + groups.insert(at, (after_end, Some(si), after_end - at)); + in_run.insert(at, at); + in_run.insert(end, at); + site_of.insert(at, si); + p.sites.push(Site { rva, store: s, helper: 0, leaf, patch: Patch::Call { start: rva, len: (after_end - at) as u8 } }); + merged = true; + } + } + } + if merged { + p.short[2] += 1; + continue; + } + } + // a trap: a stub that does the store and jumps back to its end + let Some(h) = trap_stub(&mut p, &s, bytes, ret) else { + p.skipped.push((rva, Skip::Form)); + continue; + }; + site_of.insert(at, p.sites.len()); + p.sites.push(Site { rva, store: s, helper: h, leaf, patch: Patch::Trap }); + p.short[3] += 1; + } + // 3. the runs' helpers: from the anchor to the last store it covers, the stores in two + // halves, the rest moved, conditional jumps inside the run, to its end or out (each + // way out sets its own return); then a return past the run. A run that ends where + // the call's bytes do (a merge) returns where the call does: NOPs lead to its end. + let mut group_helper: std::collections::HashMap = std::collections::HashMap::new(); + for (&a, &(e, own, len)) in &groups { + while p.code.len() % 16 != 0 { + p.code.push(0xCC); + } + let h = p.code.len() as u32; + let lo32 = |off: i64| ((base as i64 + s_start as i64 + off) as u64 as u32).to_le_bytes(); + let mut out = Vec::new(); + if a + len != e { + out.extend_from_slice(&[0xC7, 0x04, 0x24]); + out.extend_from_slice(&lo32(e as i64)); + } + let mut fixups = Vec::new(); + let mut jumps: Vec<(usize, i64)> = Vec::new(); // (offset of a rel32 in `out`, its target) + let mut pos: std::collections::HashMap = std::collections::HashMap::new(); // the run's instructions in `out` + let mut k = a; + let mut ok = true; + while k < e { + let Some(ki) = insn_info(&code[k..e.min(n)]) else { + ok = false; + break; + }; + pos.insert(k, out.len()); + if let (Some(cc), Some(t)) = (ki.cond, ki.target) { + out.extend_from_slice(&[0x0F, 0x80 | cc, 0, 0, 0, 0]); + jumps.push((out.len() - 4, k as i64 + t)); + k += ki.len as usize; + continue; + } + if ki.flow { + ok = false; // (the walk stops at these: not in a run) + break; + } + match store_at.get(&k) { + // (the walk stops at these: not in a run) its operand would need moving + Some(w) if w.safe_place() || w.kind == Kind::Cvtps2ph => { + ok = false; + break; + } + Some(w) => { + let mut part = Vec::new(); + if helper(w, &code[k..k + w.len as usize], Around::default(), &mut part).is_none() { + ok = false; + break; + } + part.pop(); // its ret + out.extend_from_slice(&part); + } + None => { + let Some((b, fix)) = relocate(&code[k..e.min(n)], &ki, base + (s_start + k) as u64, 8) else { + ok = false; + break; + }; + if let Some((d, en, t)) = fix { + fixups.push((out.len() + d, out.len() + en, t)); + } + out.extend_from_slice(&b); + } + } + k += ki.len as usize; + } + if !ok || k != e { + continue; // (cannot happen: the run was walked before) – its stores trap below + } + let ret_at = out.len(); + out.push(0xC3); + // the jumps: to the run's end, the ret; to an instruction of the run (a loop's + // head), its place here; anywhere else, out – return there instead + for (at_rel, t) in jumps { + let inside = usize::try_from(t).ok().and_then(|t| pos.get(&t).copied()); + let dest = if t == e as i64 { + ret_at + } else if let Some(x) = inside { + x + } else { + let x = out.len(); + out.extend_from_slice(&[0xC7, 0x04, 0x24]); + out.extend_from_slice(&lo32(t)); + out.push(0xC3); + x + }; + out[at_rel..at_rel + 4].copy_from_slice(&((dest as i64 - (at_rel as i64 + 4)) as i32).to_le_bytes()); + } + p.code.extend_from_slice(&out); + p.helpers.push((h, p.code.len() as u32, Frame::Leaf)); + for (d, en, t) in fixups { + p.fixups.push((h + d as u32, h + en as u32, t)); + } + group_helper.insert(a, h); + match own { + Some(si) => p.sites[si].helper = h, + None => p.anchors.push(((s_start + a) as u32, len as u8, h)), + } + } + // (not expected: each run was walked before) a merge whose helper could not be written + // leaves its store to a trap + let failed: Vec = groups.iter().filter(|(a, g)| !group_helper.contains_key(a) && g.1.is_some()).map(|(_, g)| g.1.unwrap()).collect(); + for si in failed { + let site = p.sites[si]; + let at = site.rva as usize - s_start; + if site.store.len >= 5 { + continue; // its own helper stays + } + if let Some(h) = trap_stub(&mut p, &site.store, &code[at..at + 4], base + site.rva as u64 + 4) { + p.sites[si].helper = h; + p.sites[si].patch = Patch::Trap; + p.short[2] -= 1; + p.short[3] += 1; + } + } + // (not expected: each run was walked before) the stores of a run whose helper could not + // be written are left to their traps alone + for (si, a) in anchored { + if !group_helper.contains_key(&a) { + p.sites[si].patch = Patch::Trap; + p.short[1] -= 1; + p.short[3] += 1; + } + } + // stores after a byte a walk could not decode: left, and said + for (ri, &(_, bad)) in range_flags.iter().enumerate() { + let Some(b) = bad else { continue }; + let re = ranges[ri].1; + let mut k = b; + while let Some(j) = code[k..re].iter().position(|&x| x == 0xC4 || x == 0xC5) { + let at = k + j; + if decode(&code[at..re]).is_some_and(|s| !s.safe_place()) { + p.skipped.push(((s_start + at) as u32, Skip::Undecodable((s_start + b) as u32))); + } + k = at + 1; + } + } + } + p.sites.sort_unstable_by_key(|s| s.rva); + p +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(c: &[u8]) -> Store { + decode(c).unwrap_or_else(|| panic!("{c:02x?} not decoded")) + } + + /// The stores this takes, in every operand shape the retail game has; what it leaves. + #[test] + fn decodes_the_stores() { + // vmovups [rdi], ymm0 + let s = d(&[0xC5, 0xFC, 0x11, 0x07]); + assert_eq!((s.kind, s.len, s.wide, s.src, s.vex), (Kind::Ups, 4, true, 0, 2)); + assert_eq!(s.mem, Mem { base: Some(7), index: None, scale: 0, disp: 0, rip: false }); + // vmovdqu [rcx + r9 - 0xc0], ymm1 (vcruntime140+0x1597) + let s = d(&[0xC4, 0xA1, 0x7E, 0x7F, 0x8C, 0x09, 0x40, 0xFF, 0xFF, 0xFF]); + assert_eq!((s.kind, s.len, s.src, s.vex), (Kind::Dqu, 10, 1, 3)); + assert_eq!(s.mem, Mem { base: Some(1), index: Some(9), scale: 0, disp: -0xC0, rip: false }); + // vmovupd [r13 + 8], ymm9 + let s = d(&[0xC4, 0x41, 0x7D, 0x11, 0x4D, 0x08]); + assert_eq!((s.kind, s.len, s.src), (Kind::Upd, 6, 9)); + assert_eq!(s.mem.base, Some(13)); + // vmovups [rsp + 0x20], ymm2 and [rip + 0x100], ymm3: decoded, a place left alone + assert!(d(&[0xC5, 0xFC, 0x11, 0x54, 0x24, 0x20]).safe_place()); + assert!(d(&[0xC5, 0xFC, 0x11, 0x1D, 0, 1, 0, 0]).safe_place()); + // vcvtps2ph [r15 + 0x20], ymm9, 3 (GTA V's) and vcvtps2ph [rax], xmm1, 0 + let s = d(&[0xC4, 0x43, 0x7D, 0x1D, 0x4F, 0x20, 0x03]); + assert_eq!((s.kind, s.len, s.wide, s.src, s.imm), (Kind::Cvtps2ph, 7, true, 9, 3)); + assert_eq!(s.mem.base, Some(15)); + let s = d(&[0xC4, 0xE3, 0x79, 0x1D, 0x08, 0x00]); + assert_eq!((s.kind, s.len, s.wide, s.src), (Kind::Cvtps2ph, 6, false, 1)); + // left: loads, register destinations, 128-bit stores, aligned and non-temporal forms, + // vmovss / vmovsd, a register VCVTPS2PH, W1 VCVTPS2PH, a vvvv operand + for c in [ + &[0xC5, 0xFC, 0x10, 0x07][..], // vmovups ymm0, [rdi] + &[0xC5, 0xFC, 0x11, 0xC1], // vmovups ymm1, ymm0 (register) + &[0xC5, 0xF8, 0x11, 0x07], // vmovups [rdi], xmm0 + &[0xC5, 0xFC, 0x29, 0x07], // vmovaps [rdi], ymm0 + &[0xC5, 0xFD, 0x7F, 0x07], // vmovdqa [rdi], ymm0 + &[0xC5, 0xFD, 0xE7, 0x07], // vmovntdq [rdi], ymm0 + &[0xC5, 0xFA, 0x11, 0x07], // vmovss [rdi], xmm0 + &[0xC4, 0xE3, 0x7D, 0x1D, 0xC1, 0x00], // vcvtps2ph xmm1, ymm0, 0 + &[0xC4, 0xE3, 0xFD, 0x1D, 0x07, 0x00], // W1 + &[0xC5, 0xF4, 0x11, 0x07], // vvvv != 1111 + ] { + assert!(decode(c).is_none(), "{c:02x?}"); + } + // every store `decode` takes is as long as `insn_len` says + for c in [ + &[0xC5, 0xFC, 0x11, 0x07][..], + &[0xC4, 0xA1, 0x7E, 0x7F, 0x8C, 0x09, 0x40, 0xFF, 0xFF, 0xFF], + &[0xC4, 0x41, 0x7D, 0x11, 0x4D, 0x08], + &[0xC4, 0x43, 0x7D, 0x1D, 0x4F, 0x20, 0x03], + &[0xC4, 0xE3, 0x79, 0x1D, 0x08, 0x00], + &[0xC5, 0xFE, 0x7F, 0x04, 0x25, 0x00, 0x10, 0x00, 0x00], // no base: [disp32] + ] { + assert_eq!(insn_len(c), Some(d(c).len as usize), "{c:02x?}"); + } + } + + /// The helpers' exact bytes (checked with the llvm-mingw assembler). + #[test] + fn helper_bytes() { + let h = |c: &[u8], around: Around| { + let mut out = Vec::new(); + let f = helper(&d(c), c, around, &mut out); + (f, out) + }; + // vmovups [rdi], ymm0 → vmovups [rdi], xmm0; vextractf128 [rdi + 16], ymm0, 1; ret + assert_eq!(h(&[0xC5, 0xFC, 0x11, 0x07], Around::default()), (Some(Frame::Leaf), vec![0xC5, 0xF8, 0x11, 0x07, 0xC4, 0xE3, 0x7D, 0x19, 0x47, 0x10, 0x01, 0xC3])); + // vcruntime140+0x1597 + let (f, b) = h(&[0xC4, 0xA1, 0x7E, 0x7F, 0x8C, 0x09, 0x40, 0xFF, 0xFF, 0xFF], Around::default()); + assert_eq!(f, Some(Frame::Leaf)); + assert_eq!(b, [0xC4, 0xA1, 0x7A, 0x7F, 0x8C, 0x09, 0x40, 0xFF, 0xFF, 0xFF, 0xC4, 0xA3, 0x7D, 0x19, 0x8C, 0x09, 0x50, 0xFF, 0xFF, 0xFF, 0x01, 0xC3]); + // vmovups [rbp], ymm8 → disp8 0 for RBP, then +16 + let (_, b) = h(&[0xC5, 0x7C, 0x11, 0x45, 0x00], Around::default()); + assert_eq!(b, [0xC5, 0x78, 0x11, 0x45, 0x00, 0xC4, 0x63, 0x7D, 0x19, 0x45, 0x10, 0x01, 0xC3]); + // vmovdqu [rax + 0x78], ymm1: disp8 0x78 + 16 → disp32 + let (_, b) = h(&[0xC5, 0xFE, 0x7F, 0x48, 0x78], Around::default()); + assert_eq!(b, [0xC5, 0xFA, 0x7F, 0x48, 0x78, 0xC4, 0xE3, 0x7D, 0x19, 0x88, 0x88, 0x00, 0x00, 0x00, 0x01, 0xC3]); + // a padding slot's helper first sets its return address; a moved instruction before + let (_, b) = h(&[0xC5, 0xFC, 0x11, 0x07], Around { ret_to: Some(0x0D84_679C), before: &[0xC5, 0xF8, 0x57, 0xC0], after: &[] }); + assert_eq!(b, [0xC7, 0x04, 0x24, 0x9C, 0x67, 0x84, 0x0D, 0xC5, 0xF8, 0x57, 0xC0, 0xC5, 0xF8, 0x11, 0x07, 0xC4, 0xE3, 0x7D, 0x19, 0x47, 0x10, 0x01, 0xC3]); + // vcvtps2ph [r15 + 0x20], ymm9, 3 through xmm15 + let (f, b) = h(&[0xC4, 0x43, 0x7D, 0x1D, 0x4F, 0x20, 0x03], Around::default()); + assert_eq!(f, Some(Frame::F16c)); + assert_eq!( + b, + [ + 0x48, 0x8D, 0x64, 0x24, 0xE0, // lea rsp, [rsp - 32] + 0xC4, 0x61, 0x7A, 0x7F, 0x3C, 0x24, // vmovdqu [rsp], xmm15 + 0xC4, 0x63, 0x7D, 0x19, 0x7C, 0x24, 0x10, 0x01, // vextractf128 [rsp + 16], ymm15, 1 + 0xC4, 0x43, 0x7D, 0x1D, 0xCF, 0x03, // vcvtps2ph xmm15, ymm9, 3 + 0xC4, 0x41, 0x7A, 0x7F, 0x7F, 0x20, // vmovdqu [r15 + 0x20], xmm15 + 0xC4, 0x61, 0x7E, 0x6F, 0x3C, 0x24, // vmovdqu ymm15, [rsp] + 0x48, 0x8D, 0x64, 0x24, 0x20, // lea rsp, [rsp + 32] + 0xC3, + ] + ); + // vcvtps2ph [rax], xmm15, 0: scratch xmm14, an 8-byte vmovq + let (_, b) = h(&[0xC4, 0x63, 0x79, 0x1D, 0x38, 0x00], Around::default()); + assert_eq!(&b[25..30], &[0xC4, 0x61, 0x79, 0xD6, 0x30]); + // stack and image stores have no helper + assert_eq!(h(&[0xC5, 0xFC, 0x11, 0x54, 0x24, 0x20], Around::default()), (None, vec![])); + assert!(UNWIND_INFO_F16C == [0x01, 5, 1, 0, 5, 0x32, 0, 0]); + } + + #[test] + fn call_and_jump_bytes() { + assert_eq!(call_site(0x1000, 8, 0x2000).unwrap(), [0xE8, 0xFB, 0x0F, 0, 0, 0x90, 0x90, 0x90]); + assert_eq!(call_site(0x1000, 4, 0x2000), None); + assert_eq!(short_jump(0x1000, 0x1050), Some([0xEB, 0x4E, 0xCC, 0xCC])); + assert_eq!(short_jump(0x1000, 0x0F84), Some([0xEB, 0x82, 0xCC, 0xCC])); + assert_eq!(short_jump(0x1000, 0x1082), None); + } + + /// What `insn_info` says of instructions the planner meets. + #[test] + fn instruction_info() { + let i = |c: &[u8]| insn_info(c).unwrap_or_else(|| panic!("{c:02x?}")); + // movable: register and memory ALU, moves, AVX; RSP- and RIP-based memory operands + // (`relocate` moves their displacements) + for c in [ + &[0xC5, 0xF8, 0x57, 0xC0][..], + &[0x48, 0x8B, 0x47, 0x08], + &[0x45, 0x0F, 0xB6, 0x7E, 0x01], + &[0x48, 0x83, 0xC0, 0x40], + &[0xC5, 0xFC, 0x10, 0x4F, 0x20], + &[0x48, 0x8D, 0x0C, 0x49], + &[0x48, 0x8B, 0x44, 0x24, 0x08], // mov rax, [rsp + 8] + &[0x48, 0x8B, 0x05, 0, 0, 0, 0], // mov rax, [rip] + ] { + assert!(i(c).movable, "{c:02x?}"); + } + // relocated into a helper entered by call: RSP-based displacements + 8 (the form grows + // where it must, an immediate after it kept), RIP-relative ones to be fixed + let r = |c: &[u8]| relocate(c, &i(c), 0x1000, 8).unwrap(); + assert_eq!(r(&[0x48, 0x8B, 0x44, 0x24, 0x08]), (vec![0x48, 0x8B, 0x44, 0x24, 0x10], None)); + assert_eq!(r(&[0x48, 0x8B, 0x04, 0x24]), (vec![0x48, 0x8B, 0x44, 0x24, 0x08], None)); // [rsp] → [rsp + 8] + assert_eq!(r(&[0x48, 0x8B, 0x44, 0x24, 0x78]), (vec![0x48, 0x8B, 0x84, 0x24, 0x80, 0, 0, 0], None)); + assert_eq!(r(&[0x48, 0x8D, 0x4C, 0x44, 0x10]), (vec![0x48, 0x8D, 0x4C, 0x44, 0x18], None)); // lea rcx, [rsp + rax*2 + 0x10] + assert_eq!(r(&[0xC7, 0x44, 0x24, 0x78, 1, 0, 0, 0]), (vec![0xC7, 0x84, 0x24, 0x80, 0, 0, 0, 1, 0, 0, 0], None)); + assert_eq!(r(&[0x48, 0x8B, 0x44, 0x24, 0xF8]), (vec![0x48, 0x8B, 0x04, 0x24], None)); // [rsp - 8] → [rsp] + assert_eq!(r(&[0x48, 0x8B, 0x47, 0x08]), (vec![0x48, 0x8B, 0x47, 0x08], None)); + assert_eq!(r(&[0x48, 0x8B, 0x05, 0x00, 0x01, 0, 0]), (vec![0x48, 0x8B, 0x05, 0x00, 0x01, 0, 0], Some((3, 7, 0x1107)))); + assert_eq!(r(&[0x81, 0x3D, 0x10, 0, 0, 0, 1, 0, 0, 0]), (vec![0x81, 0x3D, 0x10, 0, 0, 0, 1, 0, 0, 0], Some((2, 10, 0x101A)))); // cmp dword [rip + 0x10], 1 + // a copy of RSP: lea, 8 on + assert_eq!(i(&[0x48, 0x89, 0xE2]).rsp_copy, Some(2)); // mov rdx, rsp + assert_eq!(r(&[0x48, 0x89, 0xE2]), (vec![0x48, 0x8D, 0x54, 0x24, 0x08], None)); + assert_eq!(r(&[0x48, 0x89, 0xE5]), (vec![0x48, 0x8D, 0x6C, 0x24, 0x08], None)); // mov rbp, rsp + assert_eq!(r(&[0x4C, 0x8B, 0xE4]), (vec![0x4C, 0x8D, 0x64, 0x24, 0x08], None)); // mov r12, rsp + assert_eq!(r(&[0x49, 0x89, 0xE1]), (vec![0x4C, 0x8D, 0x4C, 0x24, 0x08], None)); // mov r9, rsp + // conditional jumps: their condition + assert_eq!(i(&[0x74, 0x04]).cond, Some(4)); + assert_eq!(i(&[0x0F, 0x85, 0, 1, 0, 0]).cond, Some(5)); + assert_eq!(i(&[0xEB, 0x04]).cond, None); + assert_eq!(i(&[0xE3, 0x04]).cond, None); // jrcxz + // not movable: RSP as a register, stack ops, flow, emulated, the stores themselves + for c in [ + &[0x48, 0x83, 0xC4, 0x08][..], // add rsp, 8 + &[0x48, 0x89, 0xEC], // mov rsp, rbp + &[0x89, 0xE2], // mov edx, esp + &[0x48, 0x8D, 0x64, 0x24, 0x08], // lea rsp, [rsp + 8] + &[0x50], // push rax + &[0x0F, 0x01, 0xFC], // clzero + &[0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], // insertq + &[0x66, 0x0F, 0x38, 0xF6, 0xC1], // adcx + &[0xC5, 0xFC, 0x11, 0x07], // vmovups [rdi], ymm0 + &[0xC4, 0xE2, 0x7D, 0x8E, 0x07], // vpmaskmovd [rdi], ymm0, ymm0 + &[0xF7, 0xF1], // div ecx + ] { + assert!(!i(c).movable, "{c:02x?}"); + } + assert_eq!(i(&[0x75, 0x10]).target, Some(0x12)); + assert_eq!(i(&[0x0F, 0x85, 0x00, 0x01, 0, 0]).target, Some(0x106)); + assert!(i(&[0xE8, 0, 0, 0, 0]).call); + assert!(i(&[0xFF, 0xE0]).indirect_jump); // jmp rax + assert!(!i(&[0xFF, 0x25, 0, 0, 0, 0]).indirect_jump); // jmp [rip]: an import + } + + /// `XCL_PLAN_IMAGE=`: the plan of a real image, mapped from its file (no + /// relocation), with what it did and how long it took. + #[test] + #[ignore] + fn plan_of_an_image_file() { + let Ok(path) = std::env::var("XCL_PLAN_IMAGE") else { return }; + let file = std::fs::read(&path).unwrap(); + let pe = crate::pe::Pe::parse(&file, crate::pe::Layout::File).unwrap(); + let mut img = vec![0u8; pe.size_of_image as usize]; + let hdr = (pe.size_of_headers as usize).min(file.len()); + img[..hdr].copy_from_slice(&file[..hdr]); + for sec in &pe.sections { + let raw = (sec.raw_size as usize).min(sec.mapped_size() as usize); + img[sec.va as usize..sec.va as usize + raw].copy_from_slice(&file[sec.raw_ptr as usize..sec.raw_ptr as usize + raw]); + } + let code: Vec<(u32, u32)> = pe.sections.iter().filter(|s| s.characteristics & 0x2000_0000 != 0).map(|s| (s.va, s.mapped_size())).collect(); + let ex = pe.dir(crate::pe::DIR_EXCEPTION); + if let Ok(d) = std::env::var("XCL_PLAN_DEBUG") { + DEBUG_RVA.with(|c| c.set(u32::from_str_radix(d.trim_start_matches("0x"), 16).unwrap())); + } + let t = std::time::Instant::now(); + let funcs = unsafe { crate::loader::unwind_entries(img.as_ptr() as usize, img.len(), (ex.rva, ex.size)) }; + let p = plan(&img, pe.image_base, &code, &funcs); + let took = t.elapsed(); + let mut kinds = std::collections::HashMap::new(); + for s in &p.sites { + *kinds.entry((s.store.kind, s.store.len >= 5)).or_insert(0usize) += 1; + } + let handlers = funcs.iter().filter(|f| f.2 & 1 != 0).count(); + let unread = funcs.iter().filter(|f| f.2 & 2 != 0).count(); + println!("{path}: {} functions ({handlers} with a handler, {unread} unreadable); {} sites {kinds:?}; short {:?}; safe place {}; skipped {}; {} helpers, {} bytes; {} ms", funcs.len(), p.sites.len(), p.short, p.safe_place, p.skipped.len(), p.helpers.len(), p.code.len(), took.as_millis()); + let mut why = std::collections::HashMap::new(); + for (_, w) in &p.skipped { + *why.entry(format!("{:?}", std::mem::discriminant(w))).or_insert(0usize) += 1; + } + println!("skipped by reason: {why:?}; first: {:x?}", &p.skipped[..p.skipped.len().min(8)]); + if let Some(s) = p.sites.iter().find(|s| s.rva == 0x4f96798) { + println!("+0x4f96798: {:?}", s.patch); + } + let traps: Vec = p.sites.iter().filter(|s| s.patch == Patch::Trap).take(12).map(|s| format!("{:#x}", s.rva)).collect(); + println!("first traps: {}", traps.join(" ")); + // `XCL_PLAN_SITES=` (sites seen trapping in a run): how each is done now + if let Ok(list) = std::env::var("XCL_PLAN_SITES") { + let mut by = std::collections::BTreeMap::new(); + for l in std::fs::read_to_string(list).unwrap().lines() { + let Ok(rva) = u32::from_str_radix(l.trim().trim_start_matches("0x"), 16) else { continue }; + let what = p.sites.iter().find(|s| s.rva == rva).map_or("none".to_string(), |s| format!("{:?}", s.patch).split([' ', '{']).next().unwrap().to_string()); + if what == "Trap" || what == "none" { + println!("still {what}: {rva:#x}"); + } + *by.entry(what).or_insert(0usize) += 1; + } + println!("listed sites: {by:?}"); + } + if let Ok(out) = std::env::var("XCL_PLAN_TRAPS") { + let all: Vec = p.sites.iter().filter(|s| s.patch == Patch::Trap).map(|s| format!("{:#x}", s.rva)).collect(); + std::fs::write(out, all.join("\n")).unwrap(); + } + } + + /// Made-up images: every way a four-byte store is done, and the rules that pick it. + #[test] + fn plan_of_small_images() { + let put = |img: &mut Vec, at: usize, b: &[u8]| img[at..at + b.len()].copy_from_slice(b); + // no padding anywhere (NOP filler): merges and traps + let mut img = vec![0x90u8; 0x400]; + // A [0x100, 0x180) + put(&mut img, 0x100, &[0xC5, 0xF8, 0x57, 0xC0]); // vxorps xmm0, xmm0, xmm0 + put(&mut img, 0x104, &[0xC5, 0xFC, 0x11, 0x07]); // S1 vmovups [rdi], ymm0: merged with the vxorps + put(&mut img, 0x108, &[0xE8, 0x00, 0x00, 0x00, 0x00]); // call 0x10D: S2 is a return target + put(&mut img, 0x10D, &[0xC5, 0xFC, 0x11, 0x06]); // S2 vmovups [rsi], ymm0: merged with the mov after it + put(&mut img, 0x111, &[0x48, 0x8B, 0x47, 0x08]); // mov rax, [rdi + 8] + put(&mut img, 0x115, &[0xC5, 0xFE, 0x7F, 0x4F, 0x20]); // S3 vmovdqu [rdi + 0x20], ymm1: five bytes, in place + put(&mut img, 0x11A, &[0x75, 0x04]); // jne 0x120: S4 is a branch target + put(&mut img, 0x11C, &[0x48, 0x89, 0xC1]); // mov rcx, rax + put(&mut img, 0x11F, &[0x90]); // nop + put(&mut img, 0x120, &[0xC5, 0xFC, 0x11, 0x01]); // S4 vmovups [rcx], ymm0: merged forward + put(&mut img, 0x124, &[0x48, 0x89, 0xC2]); // mov rdx, rax + put(&mut img, 0x127, &[0x48, 0x89, 0xEC]); // mov rsp, rbp: not movable + put(&mut img, 0x12A, &[0xC5, 0xFC, 0x11, 0x03]); // S5 vmovups [rbx], ymm0: neither neighbour moves – trap + put(&mut img, 0x12E, &[0xC5, 0xFC, 0x11, 0x04, 0x24]); // vmovups [rsp], ymm0: the stack, left + put(&mut img, 0x133, &[0xC3]); + // B [0x200, 0x240): an indirect jump + put(&mut img, 0x200, &[0xC5, 0xF8, 0x57, 0xC0]); + put(&mut img, 0x204, &[0xC5, 0xFC, 0x11, 0x02]); // S6: trap + put(&mut img, 0x208, &[0xFF, 0xE0]); + // C [0x280, 0x2C0): an exception handler + put(&mut img, 0x280, &[0xC5, 0xF8, 0x57, 0xC0]); + put(&mut img, 0x284, &[0xC5, 0xFC, 0x11, 0x02]); // S7: trap + put(&mut img, 0x288, &[0xC3]); + let funcs = [(0x100, 0x180, 0), (0x200, 0x240, 0), (0x280, 0x2C0, 1)]; + let p = plan(&img, 0x1_4000_0000, &[(0x100, 0x300)], &funcs); + let site = |rva: u32| p.sites.iter().find(|s| s.rva == rva).map(|s| s.patch); + assert_eq!(site(0x104), Some(Patch::Call { start: 0x100, len: 8 }), "{:#x?}", p.sites); + assert_eq!(site(0x10D), Some(Patch::Call { start: 0x10D, len: 8 })); + assert_eq!(site(0x115), Some(Patch::Call { start: 0x115, len: 5 })); + assert_eq!(site(0x120), Some(Patch::Call { start: 0x120, len: 7 })); + assert_eq!(site(0x12A), Some(Patch::Trap)); + assert_eq!(site(0x204), Some(Patch::Trap)); + assert_eq!(site(0x284), Some(Patch::Trap)); + // (no anchor: the instructions before S1, S4, S5 are short, S2's is a call) + assert_eq!((p.sites.len(), p.safe_place, p.short, p.skipped.len()), (7, 1, [0, 0, 3, 3], 0)); + // helpers: S3's is the store alone; S1's starts with the moved vxorps; S2's ends with the mov + let h = |rva: u32| p.sites.iter().find(|s| s.rva == rva).unwrap().helper as usize; + assert_eq!(&p.code[h(0x115)..h(0x115) + 5], &[0xC5, 0xFA, 0x7F, 0x4F, 0x20]); + assert_eq!(&p.code[h(0x104)..h(0x104) + 8], &[0xC5, 0xF8, 0x57, 0xC0, 0xC5, 0xF8, 0x11, 0x07]); + assert_eq!(&p.code[h(0x10D) + 11..h(0x10D) + 16], &[0x48, 0x8B, 0x47, 0x08, 0xC3]); + // a trap stub ends in a jump back to the store's end + let t = h(0x12A); + assert_eq!(&p.code[t + 11..t + 17], &[0xFF, 0x25, 0, 0, 0, 0]); + assert_eq!(u64::from_le_bytes(p.code[t + 17..t + 25].try_into().unwrap()), 0x1_4000_012E); + + // anchors: a five-byte store before (its own helper does both), a non-store + // instruction before (an RSP-based load, moved with its displacement + 8), a RIP-based + // load before a run of two short stores + let mut img = vec![0x90u8; 0x400]; + put(&mut img, 0x100, &[0xC5, 0xFC, 0x11, 0x43, 0x60]); // W vmovups [rbx + 0x60], ymm0 + put(&mut img, 0x105, &[0xC5, 0xFC, 0x11, 0x03]); // S9 vmovups [rbx], ymm0 + put(&mut img, 0x109, &[0xC5, 0xFC, 0x10, 0x84, 0x24, 0xF0, 0x00, 0x00, 0x00]); // vmovups ymm0, [rsp + 0xf0] + put(&mut img, 0x112, &[0xC5, 0xFC, 0x11, 0x06]); // S10 vmovups [rsi], ymm0 + put(&mut img, 0x116, &[0x8B, 0x05, 0x00, 0x01, 0x00, 0x00]); // mov eax, [rip + 0x100] + put(&mut img, 0x11C, &[0x48, 0x89, 0xC1]); // mov rcx, rax + put(&mut img, 0x11F, &[0xC5, 0xFC, 0x11, 0x07]); // S11 vmovups [rdi], ymm0 + put(&mut img, 0x123, &[0xC5, 0xFC, 0x11, 0x01]); // S12 vmovups [rcx], ymm0 + put(&mut img, 0x127, &[0xFF, 0xE0]); // jmp rax: no merges here, anchors do not care + // a loop whose head is the store, its back branch the only one landing there: the whole + // loop in the run + put(&mut img, 0x130, &[0x48, 0x8B, 0x87, 0x00, 0x01, 0x00, 0x00]); // mov rax, [rdi + 0x100] + put(&mut img, 0x137, &[0xC5, 0xFC, 0x11, 0x06]); // S13 vmovups [rsi], ymm0 + put(&mut img, 0x13B, &[0x48, 0x83, 0xC6, 0x20]); // add rsi, 0x20 + put(&mut img, 0x13F, &[0xFF, 0xC9]); // dec ecx + put(&mut img, 0x141, &[0x75, 0xF4]); // jne 0x137 + put(&mut img, 0x143, &[0xC3]); + let p = plan(&img, 0x1_4000_0000, &[(0x100, 0x300)], &[(0x100, 0x180, 1)]); + let site = |rva: u32| p.sites.iter().find(|s| s.rva == rva).copied().unwrap_or_else(|| panic!("{rva:#x}: {:#x?}", p.sites)); + assert_eq!(site(0x105).patch, Patch::Anchored { anchor: 0x100 }); + assert_eq!(site(0x112).patch, Patch::Anchored { anchor: 0x109 }); + assert_eq!(site(0x11F).patch, Patch::Anchored { anchor: 0x116 }); + assert_eq!(site(0x123).patch, Patch::Anchored { anchor: 0x116 }); + assert_eq!(site(0x100).patch, Patch::Call { start: 0x100, len: 5 }); + assert_eq!(site(0x137).patch, Patch::Anchored { anchor: 0x130 }); + assert_eq!((p.short, p.skipped.len()), ([0, 5, 0, 0], 0)); + assert_eq!(p.anchors.iter().map(|a| (a.0, a.1)).collect::>(), [(0x109, 9), (0x116, 6), (0x130, 7)]); + // the loop's helper: back to S13 in it (jne rel32 to the store's halves), past the loop + let h = p.anchors[2].2 as usize; + assert_eq!(&p.code[h..h + 14], &[0xC7, 0x04, 0x24, 0x43, 0x01, 0x00, 0x40, 0x48, 0x8B, 0x87, 0x00, 0x01, 0x00, 0x00]); + assert_eq!(&p.code[h + 31..h + 38], &[0x0F, 0x85, 0xE9, 0xFF, 0xFF, 0xFF, 0xC3]); // to h + 14 (from h + 37) + // W's helper does both: return past S9; W in halves; S9 in halves; ret + let h = site(0x100).helper as usize; + let w = [0xC5, 0xF8, 0x11, 0x43, 0x60, 0xC4, 0xE3, 0x7D, 0x19, 0x43, 0x70, 0x01]; + let s9 = [0xC5, 0xF8, 0x11, 0x03, 0xC4, 0xE3, 0x7D, 0x19, 0x43, 0x10, 0x01]; + assert_eq!(&p.code[h..h + 7], &[0xC7, 0x04, 0x24, 0x09, 0x01, 0x00, 0x40]); + assert_eq!(&p.code[h + 7..h + 19], &w); + assert_eq!(&p.code[h + 19..h + 31], &[&s9[..], &[0xC3]].concat()[..]); + // S9's own bytes trap to a stub: S9 in halves, then back to its end + let t = site(0x105).helper as usize; + assert_eq!(&p.code[t..t + 11], &s9); + assert_eq!(&p.code[t + 11..t + 17], &[0xFF, 0x25, 0, 0, 0, 0]); + assert_eq!(u64::from_le_bytes(p.code[t + 17..t + 25].try_into().unwrap()), 0x1_4000_0109); + // the RSP load's helper: [rsp + 0xf8] (still a disp32) + let h = p.anchors[0].2 as usize; + assert_eq!(&p.code[h + 7..h + 16], &[0xC5, 0xFC, 0x10, 0x84, 0x24, 0xF8, 0x00, 0x00, 0x00]); + // the RIP load's helper: its displacement is a fixup to the same target + let h = p.anchors[1].2 as usize; + assert_eq!(p.fixups, [(h as u32 + 7 + 2, h as u32 + 7 + 6, 0x1_4000_0116 + 6 + 0x100)]); + // the run's end: S12's end + assert_eq!(&p.code[h..h + 7], &[0xC7, 0x04, 0x24, 0x27, 0x01, 0x00, 0x40]); + + // conditional jumps in runs, in a function whose branches are not all known: a call + // over `test` + `je` (the jump it covers cannot be a branch's target), a jump out, a + // copy of RSP moved + let mut img = vec![0x90u8; 0x400]; + put(&mut img, 0x100, &[0x48, 0x85, 0xC0]); // test rax, rax (a loop's head) + put(&mut img, 0x103, &[0x74, 0x04]); // je 0x109 + put(&mut img, 0x105, &[0xC5, 0xFC, 0x11, 0x00]); // S14 vmovups [rax], ymm0 + put(&mut img, 0x109, &[0x48, 0x83, 0xC0, 0x20]); // add rax, 0x20 + put(&mut img, 0x10D, &[0x48, 0x83, 0xC1, 0xE0]); // add rcx, -0x20 + put(&mut img, 0x111, &[0x75, 0xED]); // jne 0x100 + put(&mut img, 0x113, &[0x48, 0x39, 0x0A]); // cmp [rdx], rcx + put(&mut img, 0x116, &[0x75, 0x08]); // jne 0x120: out + put(&mut img, 0x118, &[0xC5, 0xFC, 0x11, 0x02]); // S15 vmovups [rdx], ymm0 + put(&mut img, 0x11C, &[0x48, 0x89, 0x42, 0x20]); // mov [rdx + 0x20], rax + put(&mut img, 0x120, &[0x85, 0xC9]); // test ecx, ecx (a branch lands here) + put(&mut img, 0x122, &[0x74, 0x04]); // je 0x128 + put(&mut img, 0x124, &[0xC5, 0xFC, 0x11, 0x01]); // S16 vmovups [rcx], ymm0: four bytes before it – trap + put(&mut img, 0x128, &[0xC3]); + put(&mut img, 0x130, &[0xC5, 0xFC, 0x28, 0x0D, 0x00, 0x01, 0x00, 0x00]); // vmovaps ymm1, [rip + 0x100] + put(&mut img, 0x138, &[0x48, 0x89, 0xE2]); // mov rdx, rsp + put(&mut img, 0x13B, &[0xC5, 0xFC, 0x11, 0x0A]); // S17 vmovups [rdx], ymm1 + put(&mut img, 0x13F, &[0xC3]); + let p = plan(&img, 0x1_4000_0000, &[(0x100, 0x300)], &[(0x100, 0x180, 1)]); + let site = |rva: u32| p.sites.iter().find(|s| s.rva == rva).copied().unwrap_or_else(|| panic!("{rva:#x}: {:#x?}", p.sites)); + assert_eq!(site(0x105).patch, Patch::Anchored { anchor: 0x100 }); + assert_eq!(site(0x118).patch, Patch::Anchored { anchor: 0x113 }); + assert_eq!(site(0x124).patch, Patch::Trap); + assert_eq!(site(0x13B).patch, Patch::Anchored { anchor: 0x130 }); + assert_eq!((p.short, p.skipped.len()), ([0, 3, 0, 1], 0)); + assert_eq!(p.anchors.iter().map(|a| (a.0, a.1)).collect::>(), [(0x100, 5), (0x113, 5), (0x130, 8)]); + // test; je → the ret; S14 in halves + let h = p.anchors[0].2 as usize; + assert_eq!(&p.code[h..h + 28], &[0xC7, 0x04, 0x24, 0x09, 0x01, 0x00, 0x40, 0x48, 0x85, 0xC0, 0x0F, 0x84, 0x0B, 0, 0, 0, 0xC5, 0xF8, 0x11, 0x00, 0xC4, 0xE3, 0x7D, 0x19, 0x40, 0x10, 0x01, 0xC3]); + // cmp; jne → out (return to 0x120); S15 in halves; ret + let h = p.anchors[1].2 as usize; + assert_eq!(&p.code[h..h + 36], &[0xC7, 0x04, 0x24, 0x1C, 0x01, 0x00, 0x40, 0x48, 0x39, 0x0A, 0x0F, 0x85, 0x0C, 0, 0, 0, 0xC5, 0xF8, 0x11, 0x02, 0xC4, 0xE3, 0x7D, 0x19, 0x42, 0x10, 0x01, 0xC3, 0xC7, 0x04, 0x24, 0x20, 0x01, 0x00, 0x40, 0xC3]); + // vmovaps (its displacement fixed later); lea rdx, [rsp + 8]; S17 in halves + let h = p.anchors[2].2 as usize; + assert_eq!(&p.code[h + 7..h + 11], &[0xC5, 0xFC, 0x28, 0x0D]); + assert_eq!(&p.code[h + 15..h + 20], &[0x48, 0x8D, 0x54, 0x24, 0x08]); + assert_eq!(p.fixups, [(h as u32 + 11, h as u32 + 15, 0x1_4000_0238)]); + + // a store that joins a merge's run (a swap through the stack, every branch known): + // S21 merged with the load after it, S22 – whose only anchor that load is – in the + // same helper, which then returns past S22 + let mut img = vec![0x90u8; 0x400]; + put(&mut img, 0x100, &[0xC5, 0xFC, 0x10, 0x02]); // vmovups ymm0, [rdx] + put(&mut img, 0x104, &[0xC5, 0xFC, 0x10, 0x17]); // vmovups ymm2, [rdi] + put(&mut img, 0x108, &[0xC5, 0xFC, 0x11, 0x04, 0x24]); // vmovups [rsp], ymm0: left + put(&mut img, 0x10D, &[0xC5, 0xFC, 0x11, 0x12]); // S21 vmovups [rdx], ymm2 + put(&mut img, 0x111, &[0xC5, 0xFC, 0x10, 0x0C, 0x24]); // vmovups ymm1, [rsp] + put(&mut img, 0x116, &[0xC5, 0xFC, 0x11, 0x0F]); // S22 vmovups [rdi], ymm1 + put(&mut img, 0x11A, &[0xC3]); + let p = plan(&img, 0x1_4000_0000, &[(0x100, 0x300)], &[(0x100, 0x180, 0)]); + let site = |rva: u32| p.sites.iter().find(|s| s.rva == rva).copied().unwrap_or_else(|| panic!("{rva:#x}: {:#x?}", p.sites)); + assert_eq!(site(0x10D).patch, Patch::Call { start: 0x10D, len: 9 }); + assert_eq!(site(0x116).patch, Patch::Anchored { anchor: 0x10D }); + assert_eq!((p.short, p.safe_place, p.anchors.len()), ([0, 1, 1, 0], 1, 0)); + let h = site(0x10D).helper as usize; + assert_eq!( + &p.code[h..h + 36], + &[ + 0xC7, 0x04, 0x24, 0x1A, 0x01, 0x00, 0x40, // return past S22 + 0xC5, 0xF8, 0x11, 0x12, 0xC4, 0xE3, 0x7D, 0x19, 0x52, 0x10, 0x01, // S21 + 0xC5, 0xFC, 0x10, 0x4C, 0x24, 0x08, // vmovups ymm1, [rsp + 8] + 0xC5, 0xF8, 0x11, 0x0F, 0xC4, 0xE3, 0x7D, 0x19, 0x4F, 0x10, 0x01, // S22 + 0xC3, + ] + ); + + // loops in the run, branches not all known: the loop's head (its back branch the only + // one landing there) inside the run, the whole loop in the helper; a head a second + // branch lands on cannot be + let mut img = vec![0x90u8; 0x400]; + put(&mut img, 0x100, &[0x4C, 0x8D, 0x0C, 0xCD, 0, 0, 0, 0]); // lea r9, [rcx*8] + put(&mut img, 0x108, &[0xC5, 0xEC, 0x59, 0x00]); // L: vmulps ymm0, ymm2, [rax] + put(&mut img, 0x10C, &[0xC5, 0xFC, 0x11, 0x00]); // S18 vmovups [rax], ymm0 + put(&mut img, 0x110, &[0x48, 0x8D, 0x40, 0x20]); // lea rax, [rax + 0x20] + put(&mut img, 0x114, &[0x48, 0x83, 0xE9, 0x01]); // sub rcx, 1 + put(&mut img, 0x118, &[0x75, 0xEE]); // jne L + put(&mut img, 0x11A, &[0xC3]); + put(&mut img, 0x120, &[0x4A, 0x8D, 0x0C, 0x85, 0x1F, 0, 0, 0]); // lea rcx, [r8*4 + 0x1f] + put(&mut img, 0x128, &[0x48, 0xC1, 0xE9, 0x05]); // shr rcx, 5 + put(&mut img, 0x12C, &[0xC5, 0xF8, 0x57, 0xC0]); // vxorps xmm0, xmm0, xmm0 + put(&mut img, 0x130, &[0xC5, 0xFC, 0x11, 0x00]); // S19 M: vmovups [rax], ymm0 + put(&mut img, 0x134, &[0x48, 0x8D, 0x40, 0x20]); // lea rax, [rax + 0x20] + put(&mut img, 0x138, &[0x48, 0x83, 0xE9, 0x01]); // sub rcx, 1 + put(&mut img, 0x13C, &[0x75, 0xF2]); // jne M + put(&mut img, 0x13E, &[0xC3]); + put(&mut img, 0x140, &[0x48, 0x85, 0xD2]); // test rdx, rdx + put(&mut img, 0x143, &[0x74, 0x0B]); // je N: a second branch to the head + put(&mut img, 0x145, &[0x48, 0x8B, 0x87, 0x00, 0x01, 0x00, 0x00]); // mov rax, [rdi + 0x100] + put(&mut img, 0x14C, &[0xC5, 0xF8, 0x57, 0xC0]); // vxorps xmm0, xmm0, xmm0 + put(&mut img, 0x150, &[0xC5, 0xFC, 0x11, 0x00]); // S20 N: vmovups [rax], ymm0: trap + put(&mut img, 0x154, &[0x48, 0x83, 0xC0, 0x20]); // add rax, 0x20 + put(&mut img, 0x158, &[0xFF, 0xC9]); // dec ecx + put(&mut img, 0x15A, &[0x75, 0xF4]); // jne N + put(&mut img, 0x15C, &[0xC3]); + let p = plan(&img, 0x1_4000_0000, &[(0x100, 0x300)], &[(0x100, 0x11B, 1), (0x120, 0x13F, 1), (0x140, 0x15D, 1)]); + let site = |rva: u32| p.sites.iter().find(|s| s.rva == rva).copied().unwrap_or_else(|| panic!("{rva:#x}: {:#x?}", p.sites)); + assert_eq!(site(0x10C).patch, Patch::Anchored { anchor: 0x100 }); + assert_eq!(site(0x130).patch, Patch::Anchored { anchor: 0x120 }); + assert_eq!(site(0x150).patch, Patch::Trap); + assert_eq!(p.short, [0, 2, 0, 1]); + // lea r9; L: vmulps; S18; lea; sub; jne L (back in the helper); ret – past the loop + let h = p.anchors[0].2 as usize; + assert_eq!(&p.code[h..h + 7], &[0xC7, 0x04, 0x24, 0x1A, 0x01, 0x00, 0x40]); + assert_eq!(&p.code[h + 15..h + 19], &[0xC5, 0xEC, 0x59, 0x00]); + assert_eq!(&p.code[h + 38..h + 45], &[0x0F, 0x85, 0xE3, 0xFF, 0xFF, 0xFF, 0xC3]); // to h + 15 + + // padding behind a function: a slot (after the ret, so nothing falls into it) + let mut img = vec![0x90u8; 0x300]; + put(&mut img, 0x100, &[0xC5, 0xF8, 0x57, 0xC0]); + put(&mut img, 0x104, &[0xC5, 0xFC, 0x11, 0x07]); // S8 + put(&mut img, 0x108, &[0xC3]); + img[0x109..0x200].fill(0xCC); + put(&mut img, 0x200, &[0xC3]); + let p = plan(&img, 0x1_4000_0000, &[(0x100, 0x200)], &[(0x100, 0x109, 0), (0x200, 0x201, 0)]); + assert_eq!(p.sites.iter().map(|s| (s.rva, s.patch)).collect::>(), [(0x104, Patch::Slot { slot: 0x109 })]); + let h = p.sites[0].helper as usize; + // mov dword [rsp], lo32(store's end) + assert_eq!(&p.code[h..h + 7], &[0xC7, 0x04, 0x24, 0x08, 0x01, 0x00, 0x40]); + assert_eq!(p.short, [1, 0, 0, 0]); + } +} + +/// The helpers run against the instructions they stand for (`maskmov::exec`'s harness): a +/// made-up register file and memory, the instruction or its replacement, everything compared. +#[cfg(all(test, windows, target_arch = "x86_64"))] +mod exec { + use super::*; + use crate::maskmov::exec::{has_avx2, run, Code, Rng, State}; + use std::ffi::c_void; + use windows_sys::Win32::System::Memory::{GetWriteWatch, VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + /// The instruction's bytes, the reverse of `decode` (two-byte VEX when `short` allows it). + fn encode(kind: Kind, wide: bool, src: u8, mem: &Mem, imm: u8, short: bool) -> Vec { + let (map, pp, op) = match kind { + Kind::Ups => (1, 0, 0x11), + Kind::Upd => (1, 1, 0x11), + Kind::Dqu => (1, 2, 0x7F), + Kind::Cvtps2ph => (3, 1, 0x1D), + }; + let mut operand = Vec::new(); + let (x, b) = put_mem(&mut operand, src, mem, mem.disp); + let r = src >> 3; + let l = wide as u8; + let mut c = if short && map == 1 && x == 0 && b == 0 { + vec![0xC5, (1 - r) << 7 | 0x78 | l << 2 | pp, op] + } else { + vec![0xC4, (1 - r) << 7 | (1 - x) << 6 | (1 - b) << 5 | map, 0x78 | l << 2 | pp, op] + }; + c.extend_from_slice(&operand); + if kind == Kind::Cvtps2ph { + c.push(imm); + } + c + } + + /// Operand shapes: (base, index, scale, disp) – no RSP base (stack stores are left alone), + /// no RIP; RBP / R13 bases need a displacement, R12 needs a SIB. + fn shapes() -> Vec<(Option, Option, u8, i32)> { + let mut v = Vec::new(); + for base in [0u8, 1, 2, 3, 5, 6, 7, 8, 9, 12, 13, 15] { + for disp in [0i32, 0x10, -0x40, 0x7F, 0x80, -0x1000, 0x123] { + v.push((Some(base), None, 0, disp)); + } + v.push((Some(base), Some(if base == 9 { 10 } else { 9 }), 3, 0x20)); + v.push((Some(base), Some(if base == 12 { 11 } else { 12 }), 1, -0x18)); + } + v.push((Some(1), Some(5), 2, 0x40)); // RBP as an index + v + } + + /// Memory for the stores: 64 KiB, the operand aimed at its middle. + struct Buf(usize); + impl Buf { + unsafe fn new(flags: u32) -> Buf { + let p = VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_RESERVE | MEM_COMMIT | flags, PAGE_READWRITE) as usize; + assert!(p != 0); + Buf(p) + } + } + impl Drop for Buf { + fn drop(&mut self) { + unsafe { VirtualFree(self.0 as *mut c_void, 0, MEM_RELEASE) }; + } + } + + /// Registers that make `mem` address `target` (the index register gets a small value). + fn aim(s: &mut State, mem: &Mem, target: usize, rng: &mut Rng) { + let mut at = target as i64 - mem.disp as i64; + if let Some(i) = mem.index { + let v = (rng.next() % 16) as i64; + s.gpr[i as usize] = v as u64; + at -= v << mem.scale; + } + if let Some(b) = mem.base { + assert_ne!(mem.index, Some(b), "the shapes use different base and index registers"); + s.gpr[b as usize] = at as u64; + } + } + + /// The instruction and a replacement (`code` bytes laid out by `lay`) run on the same state + /// and memory; both results must agree everywhere. + unsafe fn compare(code: &mut Code, insn: &[u8], replacement: usize, state: &State, buf: &Buf, what: &str) { + let mut original = insn.to_vec(); + original.push(0xC3); + let o = code.put(&original); + let mem = |seed: u64| { + let mut r = Rng(seed); + let m = std::slice::from_raw_parts_mut(buf.0 as *mut u8, 0x1_0000); + r.fill(m); + }; + mem(7); + let a = run(o, state); + let after_a = std::slice::from_raw_parts(buf.0 as *const u8, 0x1_0000).to_vec(); + mem(7); + let b = run(replacement, state); + let after_b = std::slice::from_raw_parts(buf.0 as *const u8, 0x1_0000).to_vec(); + assert_eq!(a, b, "registers / flags / stack differ: {what}, {insn:02x?}"); + assert!(after_a == after_b, "memory differs: {what}, {insn:02x?}"); + } + + /// Every store kind, every operand shape, sources 0–15: `call helper; nops; ret` does what + /// the instruction does. + #[test] + fn a_helper_does_what_the_store_does() { + if !has_avx2() { + return; + } + unsafe { + let mut code = Code::new(); + let buf = Buf::new(0); + let mut rng = Rng(0x5EED_1234_ABCD_0001); + let mut n = 0; + for kind in Kind::ALL { + for wide in [true, false] { + if !wide && kind != Kind::Cvtps2ph { + continue; + } + for (k, &(base, index, scale, disp)) in shapes().iter().enumerate() { + let src = (k % 16) as u8; + let mem = Mem { base, index, scale, disp, rip: false }; + let imm = (k % 4) as u8; + for short in [true, false] { + let insn = encode(kind, wide, src, &mem, imm, short); + let s = decode(&insn).unwrap_or_else(|| panic!("{insn:02x?}")); + assert_eq!((s.kind, s.wide, s.src, s.mem, s.len as usize), (kind, wide, src, mem, insn.len())); + let mut h = Vec::new(); + assert!(helper(&s, &insn, Around::default(), &mut h).is_some()); + let site = code.next(); + let mut r = call_site(site as u64, insn.len().max(5), (site + 32) as u64).unwrap(); + r.push(0xC3); + r.resize(32, 0xCC); + r.extend_from_slice(&h); + let replacement = code.put(&r); + assert_eq!(replacement, site); + let mut state = rng.state(k % 2 == 0); + aim(&mut state, &mem, buf.0 + 0x8000 + (k % 48), &mut rng); + compare(&mut code, &insn, replacement, &state, &buf, kind.name()); + n += 1; + } + } + } + } + assert!(n > 400); + } + } + + /// The four-byte forms: through a padding slot (`jmp rel8`, a `call` in the slot, the helper + /// sets its return to the store's end), merged with the instruction before or after, and by + /// trap (`int3`, `loader`'s handler, the stub). + #[test] + fn four_byte_stores_by_slot_merge_and_trap() { + if !has_avx2() { + return; + } + unsafe { + let mut code = Code::new(); + let buf = Buf::new(0); + let mut rng = Rng(0x5EED_0000_0004); + for (k, (rm, src)) in [(0u8, 0u8), (1, 3), (2, 7), (3, 9), (6, 12), (7, 15)].into_iter().enumerate() { + let mem = Mem { base: Some(rm), index: None, scale: 0, disp: 0, rip: false }; + let insn = encode(Kind::Ups, true, src, &mem, 0, true); + assert_eq!(insn.len(), 4, "{insn:02x?}"); + let s = decode(&insn).unwrap(); + let mut state = rng.state(k % 2 == 1); + aim(&mut state, &mem, buf.0 + 0x8000 + k * 8, &mut rng); + // slot: site: jmp rel8 → slot (16 bytes on): call helper; the helper returns to the site's end + let site = code.next(); + let mut h = Vec::new(); + helper(&s, &insn, Around { ret_to: Some((site + 4) as u32), ..Default::default() }, &mut h).unwrap(); + assert_eq!((site + 4) >> 32, (site + 16 + 5) >> 32, "the test's code is in one 4 GiB"); + let mut r = short_jump(site as u64, (site + 16) as u64).unwrap().to_vec(); + r.push(0xC3); // the store's end: ret + r.resize(16, 0xCC); + r.extend_from_slice(&call_site((site + 16) as u64, 5, (site + 32) as u64).unwrap()); + r.resize(32, 0xCC); + r.extend_from_slice(&h); + assert_eq!(code.put(&r), site); + compare(&mut code, &insn, site, &state, &buf, "slot"); + // merged with an instruction before (vxorps xmm0..) and one after (add rax, 0x40) + for (before, after) in [(&[0xC5, 0xF8, 0x57, 0xC0][..], &[][..]), (&[][..], &[0x48, 0x83, 0xC0, 0x40][..])] { + let mut h = Vec::new(); + helper(&s, &insn, Around { before, after, ..Default::default() }, &mut h).unwrap(); + let site = code.next(); + let len = before.len() + 4 + after.len(); + let mut r = call_site(site as u64, len, (site + 32) as u64).unwrap(); + r.push(0xC3); + r.resize(32, 0xCC); + r.extend_from_slice(&h); + assert_eq!(code.put(&r), site); + let mut whole = before.to_vec(); + whole.extend_from_slice(&insn); + whole.extend_from_slice(after); + compare(&mut code, &whole, site, &state, &buf, "merge"); + } + // trap: int3 ×4 at the site, the stub (the store, then a jump back to the end) + let site = code.next(); + let mut stub = Vec::new(); + helper(&s, &insn, Around::default(), &mut stub).unwrap(); + stub.pop(); + stub.extend_from_slice(&[0xFF, 0x25, 0, 0, 0, 0]); + stub.extend_from_slice(&((site + 4) as u64).to_le_bytes()); + let mut r = vec![0xCC; 4]; + r.push(0xC3); + r.resize(32, 0xCC); + r.extend_from_slice(&stub); + assert_eq!(code.put(&r), site); + crate::loader::add_wide_store_traps_for_test(&[(site, site + 32)]); + compare(&mut code, &insn, site, &state, &buf, "trap"); + } + } + } + + /// Anchored runs: `call` at the anchor, the helper doing the run with the return set past + /// it – an anchor that is a store, an RSP-based load (displacement + 8), a run of two short + /// stores with a moved instruction between them – each against the instructions themselves. + #[test] + fn anchored_runs_do_what_the_instructions_do() { + if !has_avx2() { + return; + } + unsafe { + let mut code = Code::new(); + let buf = Buf::new(0); + let mut rng = Rng(0x5EED_0000_0A0C); + // (the run's bytes, the stores' offsets in it) + let runs: [(&[u8], &[usize]); 3] = [ + (&[0xC5, 0xFC, 0x11, 0x43, 0x60, 0xC5, 0xFC, 0x11, 0x03], &[0, 5]), // vmovups [rbx+0x60], ymm0; vmovups [rbx], ymm0 + (&[0xC5, 0xFC, 0x10, 0x44, 0x24, 0x20, 0xC5, 0xFC, 0x11, 0x06], &[6]), // vmovups ymm0, [rsp+0x20]; vmovups [rsi], ymm0 + (&[0x48, 0x8B, 0x44, 0x24, 0x28, 0xC5, 0xFC, 0x11, 0x07, 0x48, 0x89, 0xC1, 0xC5, 0xF4, 0x11, 0x00][..], &[5, 12]), // mov rax, [rsp+0x28]; S; mov rcx, rax; vmovups [rax], ymm1? (vvvv) – see below + ]; + for (n, (run, stores)) in runs.iter().enumerate() { + // the third run's last store must be a real one: vmovups [rax], ymm1 is C5 FC 11 08 + let mut run = run.to_vec(); + if n == 2 { + run.truncate(12); + run.extend_from_slice(&[0xC5, 0xFC, 0x11, 0x08]); + } + let mut state = rng.state(n % 2 == 0); + for r in [0usize, 1, 3, 6, 7] { + state.gpr[r] = (buf.0 + 0x4000 + r * 0x200) as u64; + } + // what the RSP loads read: an address in the buffer at [rsp + 0x28] (stack[0x10]) + state.stack[0x10..0x18].copy_from_slice(&((buf.0 + 0x9000) as u64).to_le_bytes()); + // the helper: return past the run, then each instruction (stores in halves, the rest relocated) + let site = code.next(); + let end = site + run.len(); + let mut h = vec![0xC7, 0x04, 0x24]; + h.extend_from_slice(&(end as u32).to_le_bytes()); + let mut k = 0; + while k < run.len() { + let ki = insn_info(&run[k..]).unwrap(); + if stores.contains(&k) { + let s = decode(&run[k..]).unwrap(); + let mut part = Vec::new(); + helper(&s, &run[k..], Around::default(), &mut part).unwrap(); + part.pop(); + h.extend_from_slice(&part); + } else { + let (b, fix) = relocate(&run[k..], &ki, (site + k) as u64, 8).unwrap(); + assert!(fix.is_none()); + h.extend_from_slice(&b); + } + k += ki.len as usize; + } + h.push(0xC3); + assert_eq!(end >> 32, (site + 5) >> 32); + let first = insn_len(&run).unwrap(); + let mut r = call_site(site as u64, first, (site + 64) as u64).unwrap(); + r.extend_from_slice(&run[first..]); // the rest of the run's bytes stay as they were + r.push(0xC3); // past the run: ret + r.resize(64, 0xCC); + r.extend_from_slice(&h); + assert_eq!(code.put(&r), site); + compare(&mut code, &run, site, &state, &buf, "anchored run"); + } + } + } + + /// `plan` on an image of `bytes` at `img` (code at 0x100 on, `funcs` its functions), applied + /// as the loader does it: the helpers at `pool`, RIP-relative operands fixed, the patches, + /// the traps known to the handler. + unsafe fn apply(bytes: &[u8], img: usize, pool: usize, funcs: &[(u32, u32, u8)]) -> Plan { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), img as *mut u8, bytes.len()); + let p = plan(bytes, img as u64, &[(0x100, (bytes.len() - 0x100) as u32)], funcs); + std::ptr::copy_nonoverlapping(p.code.as_ptr(), pool as *mut u8, p.code.len()); + for &(d, end, target) in &p.fixups { + let rel = i32::try_from(target as i64 - (pool as i64 + end as i64)).unwrap(); + ((pool + d as usize) as *mut [u8; 4]).write_unaligned(rel.to_le_bytes()); + } + let write = |at: usize, b: &[u8]| std::ptr::copy_nonoverlapping(b.as_ptr(), at as *mut u8, b.len()); + let mut traps = Vec::new(); + for s in &p.sites { + let helper = (pool + s.helper as usize) as u64; + let site = img + s.rva as usize; + match s.patch { + Patch::Call { start, len } => write(img + start as usize, &call_site((img + start as usize) as u64, len as usize, helper).unwrap()), + Patch::Slot { slot } => { + write(img + slot as usize, &call_site((img + slot as usize) as u64, 5, helper).unwrap()); + write(site, &short_jump(site as u64, (img + slot as usize) as u64).unwrap()); + } + Patch::Trap | Patch::Anchored { .. } => { + write(site, &[0xCC; 4]); + traps.push((site, helper as usize)); + } + } + } + for &(start, len, h) in &p.anchors { + write(img + start as usize, &call_site((img + start as usize) as u64, len as usize, (pool + h as usize) as u64).unwrap()); + } + crate::loader::add_wide_store_traps_for_test(&traps); + p + } + + /// Runs with conditional jumps, planned and applied as for a title: a call over `test` + + /// `je` to the run's end, over `test` + `jne` out of the run (its own return), a copy of + /// RSP moved; each way through, against the title's instructions – and a branch into a run + /// that lands on its store, which traps to the stub. + #[test] + fn runs_with_conditional_jumps_do_what_the_instructions_do() { + if !has_avx2() { + return; + } + unsafe { + use windows_sys::Win32::System::Memory::PAGE_EXECUTE_READWRITE; + let region = VirtualAlloc(std::ptr::null(), 0x2_0000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize; + assert!(region != 0); + let (img, pool) = (region, region + 0x1_0000); + // (RVA, the title's bytes – a function each, with a handler: not every branch known) + let cases: [(u32, &[u8]); 3] = [ + (0x100, &[0x48, 0x85, 0xC9, 0x74, 0x04, 0xC5, 0xFC, 0x11, 0x00, 0xC3]), // test rcx, rcx; je end; vmovups [rax], ymm0; end: ret + (0x140, &[0x48, 0x85, 0xC9, 0x75, 0x05, 0xC5, 0xFC, 0x11, 0x06, 0xC3, 0x48, 0xFF, 0xC0, 0xC3]), // test rcx, rcx; jne out; vmovups [rsi], ymm0; ret; out: inc rax; ret + (0x180, &[0x48, 0x8B, 0x87, 0x00, 0x01, 0x00, 0x00, 0x48, 0x89, 0xE2, 0xC5, 0xFC, 0x11, 0x07, 0xC3]), // mov rax, [rdi + 0x100]; mov rdx, rsp; vmovups [rdi], ymm0; ret + ]; + let mut bytes = vec![0x90u8; 0x1C0]; // (no padding: no slots) + for (rva, c) in cases { + bytes[rva as usize..rva as usize + c.len()].copy_from_slice(c); + } + let funcs: Vec<(u32, u32, u8)> = cases.iter().map(|&(rva, c)| (rva, rva + c.len() as u32, 1)).collect(); + let p = apply(&bytes, img, pool, &funcs); + assert_eq!(p.sites.iter().map(|s| s.patch).collect::>(), [Patch::Anchored { anchor: 0x100 }, Patch::Anchored { anchor: 0x140 }, Patch::Anchored { anchor: 0x180 }]); + let mut code = Code::new(); + let buf = Buf::new(0); + let mut rng = Rng(0x5EED_0000_0CC0); + for (n, (rva, c)) in cases.iter().enumerate() { + for taken in [false, true] { + let mut state = rng.state(taken); + for r in [0usize, 6, 7] { + state.gpr[r] = (buf.0 + 0x4000 + r * 0x400) as u64; + } + state.gpr[1] = taken as u64; // rcx: the jumps' condition + compare(&mut code, &c[..c.len() - 1], img + *rva as usize, &state, &buf, &format!("run {n}, rcx {}", taken as u8)); + } + } + // a branch into the first run, to its store: the trap, the stub, back to the end + let mut state = rng.state(false); + state.gpr[0] = (buf.0 + 0x4100) as u64; + compare(&mut code, &[0xC5, 0xFC, 0x11, 0x00], img + 0x105, &state, &buf, "into the run"); + VirtualFree(region as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A store that joins a merge's run (a swap through the stack), and loops run whole in a + /// helper (the loop's head inside the run), planned and applied as for a title, against + /// the title's instructions. + #[test] + fn joined_runs_and_loops_do_what_the_instructions_do() { + if !has_avx2() { + return; + } + unsafe { + use windows_sys::Win32::System::Memory::PAGE_EXECUTE_READWRITE; + let region = VirtualAlloc(std::ptr::null(), 0x2_0000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize; + assert!(region != 0); + let (img, pool) = (region, region + 0x1_0000); + // (RVA, the title's bytes, flags: 0 every branch known, 1 a handler) + let cases: [(u32, &[u8], u8); 3] = [ + ( + 0x100, + &[ + 0xC5, 0xFC, 0x10, 0x02, // vmovups ymm0, [rdx] + 0xC5, 0xFC, 0x10, 0x17, // vmovups ymm2, [rdi] + 0xC5, 0xFC, 0x11, 0x44, 0x24, 0x20, // vmovups [rsp + 0x20], ymm0 + 0xC5, 0xFC, 0x11, 0x12, // vmovups [rdx], ymm2 + 0xC5, 0xFC, 0x10, 0x4C, 0x24, 0x20, // vmovups ymm1, [rsp + 0x20] + 0xC5, 0xFC, 0x11, 0x0F, // vmovups [rdi], ymm1 + 0xC3, + ], + 0, + ), + ( + 0x140, + &[ + 0x4C, 0x8D, 0x0C, 0xCD, 0, 0, 0, 0, // lea r9, [rcx*8] + 0xC5, 0xEC, 0x59, 0x00, // L: vmulps ymm0, ymm2, [rax] + 0xC5, 0xFC, 0x11, 0x00, // vmovups [rax], ymm0 + 0x48, 0x8D, 0x40, 0x20, // lea rax, [rax + 0x20] + 0x48, 0x83, 0xE9, 0x01, // sub rcx, 1 + 0x75, 0xEE, // jne L + 0xC3, + ], + 1, + ), + ( + 0x180, + &[ + 0x4A, 0x8D, 0x0C, 0x85, 0x1F, 0, 0, 0, // lea rcx, [r8*4 + 0x1f] + 0x48, 0xC1, 0xE9, 0x05, // shr rcx, 5 + 0xC5, 0xF8, 0x57, 0xC0, // vxorps xmm0, xmm0, xmm0 + 0xC5, 0xFC, 0x11, 0x00, // M: vmovups [rax], ymm0 + 0x48, 0x8D, 0x40, 0x20, // lea rax, [rax + 0x20] + 0x48, 0x83, 0xE9, 0x01, // sub rcx, 1 + 0x75, 0xF2, // jne M + 0xC3, + ], + 1, + ), + ]; + let mut bytes = vec![0x90u8; 0x1C0]; // (no padding: no slots) + for (rva, c, _) in cases { + bytes[rva as usize..rva as usize + c.len()].copy_from_slice(c); + } + let funcs: Vec<(u32, u32, u8)> = cases.iter().map(|&(rva, c, f)| (rva, rva + c.len() as u32, f)).collect(); + let p = apply(&bytes, img, pool, &funcs); + assert_eq!( + p.sites.iter().map(|s| (s.rva, s.patch)).collect::>(), + [ + (0x10E, Patch::Call { start: 0x10E, len: 10 }), + (0x118, Patch::Anchored { anchor: 0x10E }), + (0x14C, Patch::Anchored { anchor: 0x140 }), + (0x190, Patch::Anchored { anchor: 0x180 }), + ] + ); + let mut code = Code::new(); + let buf = Buf::new(0); + let mut rng = Rng(0x5EED_0000_100B); + for (n, (rva, c, _)) in cases.iter().enumerate() { + for round in 0..3u64 { + let mut state = rng.state(round == 1); + state.gpr[0] = (buf.0 + 0x4000) as u64; // rax + state.gpr[2] = (buf.0 + 0x7000) as u64; // rdx + state.gpr[7] = (buf.0 + 0x7400) as u64; // rdi + state.gpr[1] = 1 + round * 3; // rcx: the second loop's count + state.gpr[8] = 1 + round * 20; // r8: the third's (r8 * 4 + 31) / 32 + compare(&mut code, &c[..c.len() - 1], img + *rva as usize, &state, &buf, &format!("case {n}, round {round}")); + } + } + VirtualFree(region as *mut c_void, 0, MEM_RELEASE); + } + } + + /// The case Rosetta cannot resume: a 32-byte store whose first half lands on a written page + /// and whose second half reaches a write-watched page that is still clean. The helper's + /// two halves fault and resume (this would never return with the instruction itself); both + /// pages are reported written; the bytes are the instruction's. Also VCVTPS2PH, which + /// Rosetta cannot resume wherever it faults. + #[test] + fn a_helper_resumes_across_a_clean_write_watched_page() { + if !has_avx2() { + return; + } + unsafe { + let mut code = Code::new(); + let mut rng = Rng(0x5EED_0000_0777); + for (insn, offset) in [ + (encode(Kind::Ups, true, 1, &Mem { base: Some(7), index: None, scale: 0, disp: 0, rip: false }, 0, true), 0x1000 - 16), + (encode(Kind::Dqu, true, 9, &Mem { base: Some(1), index: Some(9), scale: 0, disp: -0xC0, rip: false }, 0, false), 0x1000 - 20), + (encode(Kind::Cvtps2ph, true, 3, &Mem { base: Some(15), index: None, scale: 0, disp: 0x20, rip: false }, 3, false), 0x1000 + 0x40), + (encode(Kind::Cvtps2ph, false, 14, &Mem { base: Some(2), index: None, scale: 0, disp: 0, rip: false }, 0, false), 0x1000 - 4), + ] { + let buf = Buf::new(MEM_WRITE_WATCH); + std::ptr::write_volatile(buf.0 as *mut u8, 1); // page 0 written; page 1 still clean + let s = decode(&insn).unwrap(); + let mut h = Vec::new(); + helper(&s, &insn, Around::default(), &mut h).unwrap(); + let site = code.next(); + let mut r = call_site(site as u64, insn.len().max(5), (site + 32) as u64).unwrap(); + r.push(0xC3); + r.resize(32, 0xCC); + r.extend_from_slice(&h); + code.put(&r); + let mut state = rng.state(false); + aim(&mut state, &s.mem, buf.0 + offset, &mut rng); + let after = run(site, &state); + assert_eq!(after.gpr, state.gpr); + // what was stored: the instruction run on an ordinary buffer + let plain = Buf::new(0); + let mut st2 = state.clone(); + aim(&mut st2, &s.mem, plain.0 + offset, &mut rng); + let mut o = insn.clone(); + o.push(0xC3); + let _ = run(code.put(&o), &st2); + let n = if s.kind == Kind::Cvtps2ph { if s.wide { 16 } else { 8 } } else { 32 }; + let got = std::slice::from_raw_parts((buf.0 + offset) as *const u8, n); + let want = std::slice::from_raw_parts((plain.0 + offset) as *const u8, n); + assert_eq!(got, want, "{insn:02x?}"); + let mut pages = [std::ptr::null_mut(); 16]; + let (mut count, mut grain) = (16usize, 0u32); + assert_eq!(GetWriteWatch(0, buf.0 as *const c_void, 0x1_0000, pages.as_mut_ptr(), &mut count, &mut grain), 0); + assert!(pages[..count].iter().any(|&p| p as usize == buf.0 + 0x1000), "{insn:02x?}: page 1 written"); + } + } + } +} diff --git a/docs/gdkx/XBTC.h b/docs/gdkx/XBTC.h new file mode 100644 index 0000000..8d8c29b --- /dev/null +++ b/docs/gdkx/XBTC.h @@ -0,0 +1,1034 @@ +//------------------------------------------------------------------------------------- +// XBTC.h +// +// Xbox Texture Compressor (XBTC) archive file manipulation +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +//------------------------------------------------------------------------------------- + +#pragma once + +#include + +#ifdef _GAMING_XBOX_SCARLETT +# include +#elif defined(_GAMING_XBOX) +# error XBTC is not supported on Xbox One +#else +# include +#endif + +#include +#include + +// Exported DLL functions follow this convention +#define XBTCDLLAPI(typename) extern "C" typename __cdecl + +//------------------------------------------------------------------------------------------------- +// A unique identifier to register the archive file format. +#define XBTC_ARCHIVE_IDENTIFIER \ + ((uint32_t('X') << 0) | (uint32_t('B') << 8) | (uint32_t('T') << 16) | (uint32_t('C') << 24)) + +//------------------------------------------------------------------------------------------------- +// The version number matching the runtime to the archive format. +#define XBTC_ARCHIVE_VERSION (3) + +//------------------------------------------------------------------------------------------------- +// Helper macros +#define XBTC_MIN(a, b) ((a) < (b) ? (a) : (b)) +#define XBTC_MAX(a, b) ((a) > (b) ? (a) : (b)) + +//------------------------------------------------------------------------------------------------- + +enum XBTC_TEX_DIMENSION +{ + XBTC_TEX_DIMENSION_1D, + XBTC_TEX_DIMENSION_2D, + XBTC_TEX_DIMENSION_3D, + XBTC_TEX_DIMENSION_CUBE +}; + +//------------------------------------------------------------------------------------------------- +// Swizzle patterns and tile granularity. + +enum XBTC_TILING_MODE +{ + XBTC_TILING_SCARLETT_LINEAR, // Texel elements are arranged in row major order, mips are 256B aligned + XBTC_TILING_SCARLETT_256B, // Tiles are 256B (NO mip tail) + XBTC_TILING_SCARLETT_4KB, // Tiles are 4KB (4KB mip tail) + XBTC_TILING_SCARLETT_64KB, // Tiles are 64KB (64KB mip tail) + XBTC_TILING_STANDARD_SWIZZLE // D3D Standard Swizzle (64KB tiles) +}; + +//------------------------------------------------------------------------------------------------- +// Texture compression options. + +enum XBTC_COMPRESSION_FLAGS +{ + XBTC_COMPRESSION_NONE = 0x0, // Try both codecs and keep the best result + XBTC_COMPRESSION_DISABLE_DEFLATE = 0x1, // Disable the data-generic Deflate codec + XBTC_COMPRESSION_DISABLE_BCPACK = 0x2, // Disable the texture-specific BCPack codec + XBTC_COMPRESSION_DISABLE_ALL = 0x3, // Disable both forms of compression + XBTC_COMPRESSION_USE_SLOW_DEFLATE = 0x4 // Better compression with slower search +}; +DEFINE_ENUM_FLAG_OPERATORS(XBTC_COMPRESSION_FLAGS); + +//------------------------------------------------------------------------------------------------- +// Texture streaming options. + +enum XBTC_STREAM_GRANULARITY +{ + XBTC_STREAM_GRANULARITY_WHOLE_MIPS = 0x0, // Compress whole mips for streaming + XBTC_STREAM_GRANULARITY_64KB = 0x1, // Compress individual pages for streaming (requires 64KB tiling) + XBTC_STREAM_GRANULARITY_128KB = 0x2, // Compress 2x1 (contiguous) pages for streaming (requires 64KB tiling) + XBTC_STREAM_GRANULARITY_256KB = 0x3 // Compress 2x2 page clusters for streaming (requires 64KB tiling) +}; + +//------------------------------------------------------------------------------------------------- +// Archive v.2 format description +// ------------------------------------------------------------------------------------------------ +// XBTC_ARCHIVE_HEADER 1 Header +// XBTC_TEXTURE_INFO n Texture information for each resource in archive +// XBTC_OFFSET_AND_INDEX n Base offset and stream index for each texture's streams +// XBTC_STREAM_INFO m Relative offset, stream length, and compression format +// Binary blob m Each compressed stream, aligned to 16 bytes + +//------------------------------------------------------------------------------------------------- +// First 16 bytes of an archive file. + +struct XBTC_ARCHIVE_HEADER +{ + uint32_t Identifier; // File identifier; "XBTC" as char[] + uint32_t Version : 8; // Archive format version + uint32_t TextureCount : 24; // Number of individual textures in archive + uint64_t DataOffset : 24; // Header + Index size in bytes + uint64_t DataSize : 40; // Size of all data streams in bytes +}; +static_assert(sizeof(XBTC_ARCHIVE_HEADER) == 16, "Unexpected change in size of XBTC_ARCHIVE_HEADER"); + + +//------------------------------------------------------------------------------------------------- +// Description of a texture in the archive. + +struct XBTC_TEXTURE_INFO +{ + uint64_t Format : 8; // Must not be DXGI_FORMAT_UNKNOWN + uint64_t Dimension : 2; // Texture dimension + uint64_t Width : 14; // Width in pixels of mip 0 (minus 1) + uint64_t Height : 14; // Height in pixels of mip 0 (minus 1) + uint64_t Depth : 11; // Depth or array count (minus 1) + uint64_t TileMode : 3; // Linear, 256B, 4KB, or 64KB + uint64_t MipCount : 4; // Total number of LODs + uint64_t MipStreams : 4; // Number of additional LODs that can be streamed after initial load + uint64_t Granularity : 2; // One of XBTC_STREAM_GRANULARITY + uint64_t Reserved : 2; +}; +static_assert(sizeof(XBTC_TEXTURE_INFO) == 8, "Unexpected change in size of XBTC_TEXTURE_INFO"); + +//------------------------------------------------------------------------------------------------- +// Description of a buffer in the archive. This structure aliases with XBTC_TEXTURE_INFO. When +// Format is DXGI_FORMAT_UNKNOWN, the information refers to a buffer rather than a texture. +// Buffers need not be tiled or detiled. + +struct XBTC_BUFFER_INFO +{ + uint64_t Format : 8; // Must be DXGI_FORMAT_UNKNOWN + uint64_t SizeBytes : 40; // Size of buffer in bytes + uint64_t Reserved : 16; +}; +static_assert(sizeof(XBTC_BUFFER_INFO) == sizeof(XBTC_TEXTURE_INFO), "XBTC_BUFFER_INFO must alias with XBTC_TEXTURE_INFO"); + + +//------------------------------------------------------------------------------------------------- +// Table of contents lookup for a compressed texture. + +struct XBTC_OFFSET_AND_INDEX +{ + uint64_t BaseOffset : 40; // Base offset into data chunk. Stream offsets are relative to this. + uint64_t NextIndex : 24; // Base stream index of *next* resource. Can be used to compute stream count and base stream index. +}; +static_assert(sizeof(XBTC_OFFSET_AND_INDEX) == 8, "Unexpected change in size of XBTC_OFFSET_AND_INDEX"); + +//------------------------------------------------------------------------------------------------- +// A description of a compressed stream. + +struct XBTC_STREAM_INFO +{ + uint32_t RelativeOffset; // Stream start offset (relative to BaseOffset) + uint32_t CompressedSize; // Length of compressed stream + uint32_t InflatedSize; // Size of stream before Deflate + uint32_t UncompressedSize; // Uncompressed stream size +}; +static_assert(sizeof(XBTC_STREAM_INFO) == 16, "Unexpected change in size of XBTC_STREAM_INFO"); + +//------------------------------------------------------------------------------------------------- +// Free the memory associated with an XBTC resource + +XBTCDLLAPI(void) XBTCFreeResource(class XBTCRefCountedResource* pResource); + +//------------------------------------------------------------------------------------------------- +class XBTCRefCountedResource +{ +public: + + //------------------------------------------------------------------------------------------------- + XBTCRefCountedResource() : m_RefCount(1) {} + + //------------------------------------------------------------------------------------------------- + virtual ~XBTCRefCountedResource() {} + + //------------------------------------------------------------------------------------------------- + // Increments the refcount and returns the new value. + ULONG AddRef() + { + return ++m_RefCount; + } + + //------------------------------------------------------------------------------------------------- + // Decrements the refcount and returns the new value. If the new value is 0, the object is deleted. + ULONG Release() + { + ULONG NewRefCount = --m_RefCount; + if (NewRefCount == 0) + { + XBTCFreeResource(this); + } + return NewRefCount; + } + +private: + + ULONG m_RefCount; +}; + +//------------------------------------------------------------------------------------------------- +// A container to hold texture data throughout the compression pipeline. + +class XBTCTextureContainer : public XBTCRefCountedResource +{ +public: + + //------------------------------------------------------------------------------------------------- + // Get base pointer of texture data + virtual void* GetTextureMemory() const = 0; + + //------------------------------------------------------------------------------------------------- + // Get total size of texture data + virtual size_t GetTextureSize() const = 0; + + //------------------------------------------------------------------------------------------------- + // Get a pointer to the start of a subresource's memory + virtual void* GetSubresourceMemory(size_t MipLevel, size_t ArraySlice=0) const = 0; + + //------------------------------------------------------------------------------------------------- + // Get the memory size of the subresource. This is the same for each array slice. + virtual size_t GetSubresourceSize(size_t MipLevel) const = 0; + + //------------------------------------------------------------------------------------------------- + // Get the row pitch of the subresource. This is the same for each array slice. + virtual size_t GetSubresourcePitch(size_t MipLevel) const = 0; +}; + +//------------------------------------------------------------------------------------------------- +// A generic texture arrangement similar to a DDS file. In memory, subresources are arranged +// compactly with largest resolution mip levels preceding smallest (ascending order w.r.t. +// LOD indices). Texture arrays have contiguous mip chains for reach array element. + +XBTCDLLAPI(HRESULT) XBTCCreateLinearTexture( + _Out_ XBTCTextureContainer** ppLinearTexture, + _In_ XBTC_TEX_DIMENSION Dimension, + _In_ DXGI_FORMAT Format, + _In_ size_t Width, + _In_ size_t Height, + _In_ size_t DepthOrArraySize, + _In_ int8_t MipCount); + +//------------------------------------------------------------------------------------------------- +// Create a generic data container. This is equivalent to creating a 1D texture without mipmaps +// but skips the tiling requirement prior to compression. + +XBTCDLLAPI(HRESULT) XBTCCreateBuffer( + _Out_ XBTCTextureContainer** ppBuffer, + _In_ SIZE_T SizeInBytes +); + +//------------------------------------------------------------------------------------------------- +// Options to control the BC encoder + +struct XBTC_ENCODING_OPTIONS +{ + XBTC_ENCODING_OPTIONS( + uint32_t PowerIter = 4, + uint32_t RefineIter = 2, + uint32_t ChannelCount = 4, + uint32_t Quality = 15, + uint8_t BC7Mask = 0xFF) + { + PCAPowerIterations = XBTC_MIN(PowerIter, 15); + RefinementIterations = XBTC_MIN(RefineIter, 15); + ChannelCountMinusOne = XBTC_MIN(uint32_t(ChannelCount - 1), 3); + QualityLevel = XBTC_MIN(Quality, 15); + BC7ModeMask = (BC7Mask & 0xFF); + } + + uint32_t PCAPowerIterations : 4; // Diminishing returns after 4 iterations + uint32_t RefinementIterations : 4; // Try adjusting endpoints for quality gains + uint32_t ChannelCountMinusOne : 2; // Number of channels to consider (mainly for BC7) + uint32_t BC7ModeMask : 8; // Restrict BC7 encoding to these modes + uint32_t QualityLevel : 4; // Higher quality means less compression + + // Proposed options but not yet in effect + uint32_t ContainsColorMap : 1; // Reduce error for color data (sRGB / Rec.709) + uint32_t ContainsNormalMap : 1; // Reduce error for normal data +}; + +#define XBTC_DEFAULT_ENCODING_OPTIONS XBTC_ENCODING_OPTIONS() + +//------------------------------------------------------------------------------------------------- +// Statistics reported by the BC encoder + +struct XBTC_ENCODING_STATS +{ + uint64_t NumSamples; // Number of accumulated samples (pixels) + uint32_t CRC32; // 32-bit cyclic redundancy check (hash of encoding) + float ErrorRange; // Maximum theoretical error per channel (e.g. '255') + float RMSE[4]; // Root mean square error per channel + float PSNR[4]; // Peak signal to noise ratio per channel + float MaxError[4]; // Maximum observed error per channel + float MaxNormError[4]; // Maximum error norm (length) over all pixels (1-4 dimensions) + float EncodingTimeMS; // GPU encoding time in milliseconds +}; + +//------------------------------------------------------------------------------------------------- +// Block compress (encode to a BCn format) the source texture. Source texture should be linear. +// Allocates a linear texture for output. + +XBTCDLLAPI(HRESULT) XBTCBlockCompressTexture( + _Out_ XBTCTextureContainer** ppBCTexture, + _In_ const XBTCTextureContainer* pSourceTexture, + _In_ DXGI_FORMAT BlockCompressFormat, + _In_ XBTC_ENCODING_OPTIONS Options = XBTC_DEFAULT_ENCODING_OPTIONS, + _Out_opt_ XBTC_ENCODING_STATS* pStats = nullptr); + +//------------------------------------------------------------------------------------------------- +// Creates a tiled texture container and "swizzles" linear memory into it according to TilingMode. + +XBTCDLLAPI(HRESULT) XBTCTileTexture( + _Out_ XBTCTextureContainer** ppTiledTexture, + _In_ const XBTCTextureContainer* pLinearTexture, + _In_ XBTC_TILING_MODE TilingMode); + +//------------------------------------------------------------------------------------------------- +// Creates a linear texture container and "unswizzles" tiled memory into it. + +XBTCDLLAPI(HRESULT) XBTCDetileTexture( + _Out_ XBTCTextureContainer** ppLinearTexture, + _In_ const XBTCTextureContainer* pTiledTexture); + +//------------------------------------------------------------------------------------------------- +// Compress a single texture stream. This function allocates a buffer to hold the compressed stream. +// When done with the compressed stream, call XBTCFreeCompressedStream(*ppCompressedStream). +// NOTE: If the stream is incompressible, sets *ppCompressStream to NULL. + +XBTCDLLAPI(HRESULT) XBTCCompressStreamAlloc( + _Out_ size_t* pCompressedSize, // Resultant size after compression + _Out_ size_t* pInflatedSize, // Size of stream prior to Deflate + _Out_ void** ppCompressedStream, + _In_reads_bytes_(UncompressedSize) + const void* pUncompressedStream, + _In_ size_t UncompressedSize, // Size of uncompressed stream + _In_ DXGI_FORMAT Format, // Texture format (for BCPack) + _In_ XBTC_COMPRESSION_FLAGS Flags); // Compression options + + +//------------------------------------------------------------------------------------------------- +// Frees the memory allocated to hold a compressed stream. + +XBTCDLLAPI(void) XBTCFreeCompressedStream( + _In_ void* pCompressedStream); + +//------------------------------------------------------------------------------------------------- +// Compress a single texture stream. If the stream is incompressible, copies the source buffer +// to the destination buffer. (It will never expand data.) +// This is the non-allocating variant. Provide a destination buffer at least as large as the source. + +XBTCDLLAPI(HRESULT) XBTCCompressStream( + _Out_ size_t* pCompressedSize, // Resultant size after compression + _Out_ size_t* pInflatedSize, // Size of stream prior to Deflate + _Out_writes_bytes_(UncompressedSize) + void* pCompressedStream, + _In_reads_bytes_(UncompressedSize) + const void* pUncompressedStream, + _In_ size_t UncompressedSize, // Size of uncompressed stream + _In_ DXGI_FORMAT Format, // Texture format (for BCPack) + _In_ XBTC_COMPRESSION_FLAGS Flags); // Compression options + +//------------------------------------------------------------------------------------------------- +// Decompress a single texture stream. Returns E_FAIL if the stream is corrupt. +// Writes to pre-allocated memory. + +XBTCDLLAPI(HRESULT) XBTCDecompressStream( + _Out_writes_bytes_(UncompressedSize) + void* pUncompressedStream, + _In_reads_bytes_(CompressedSize) + const void* pCompressedStream, + _In_ size_t CompressedSize, // Size of compressed stream + _In_ size_t InflatedSize, // Size before Deflate (after BCPack) + _In_ size_t UncompressedSize, // Size of uncompressed stream + _In_ DXGI_FORMAT Format); // Texture format (for BCPack) + +//------------------------------------------------------------------------------------------------- + +class XBTCArchive : public XBTCRefCountedResource +{ +public: + + //------------------------------------------------------------------------------------------------- + // Get the number of archived resources. + virtual uint32_t GetResourceCount() const = 0; + + //------------------------------------------------------------------------------------------------- + // Get the number of compressed streams. + virtual uint32_t GetStreamCount() const = 0; + + //------------------------------------------------------------------------------------------------- + // Access texture information. Consider null pointers an error (index out of range). + virtual const XBTC_TEXTURE_INFO* GetTextureInfo(uint32_t ResourceIdx) const = 0; + + //------------------------------------------------------------------------------------------------- + // Access texture offset and index information. Consider null pointers an error (index out of range). + virtual const XBTC_OFFSET_AND_INDEX* GetTextureOffset(uint32_t ResourceIdx) const = 0; + + //------------------------------------------------------------------------------------------------- + // Access stream information. Consider null pointers an error (index out of range). + virtual const XBTC_STREAM_INFO* GetStreamInfo(uint32_t StreamIdx) const = 0; + + //------------------------------------------------------------------------------------------------- + // Returns the the start address of the resource's compressed streams. + virtual const uint8_t* GetResourceStreamDataStart(uint32_t ResourceIdx) const = 0; + + //------------------------------------------------------------------------------------------------- + // Returns the total size of the resource's compressed streams. + virtual int32_t GetResourceCompressedSize(uint32_t ResourceIdx) const = 0; + + //------------------------------------------------------------------------------------------------- + // Returns the number of compressed streams associated with the resource. + virtual int32_t GetResourceStreamCount(uint32_t ResourceIdx) const = 0; + + //------------------------------------------------------------------------------------------------- + // Returns the first stream index associated with the resource. + virtual int32_t GetResourceBaseStreamIndex(uint32_t ResourceIdx) const = 0; + + //------------------------------------------------------------------------------------------------- + // Returns the uncompressed size of the first stream associated with a texture. This is to be used + // with streamable textures. + virtual int32_t GetBaseTextureSize(uint32_t ResourceIdx) const = 0; +}; + +class XBTCArchiveWriter : public XBTCArchive +{ +public: + //------------------------------------------------------------------------------------------------- + // Save archive contents to a file. Optionally return the size written. + virtual HRESULT WriteArchiveToFile(const wchar_t* filePath, size_t* fileSize = nullptr) const = 0; +}; + +//------------------------------------------------------------------------------------------------- +// Create an empty writeable archive. You may append compressed textures to the archive with the +// following functions. + +XBTCDLLAPI(HRESULT) XBTCCreateArchive( + _Out_ XBTCArchiveWriter** ppArchive); + +//------------------------------------------------------------------------------------------------- +// Statistics related to compressing textures + +struct XBTC_COMPRESSION_STATS +{ + size_t UncompressedSizeBytes; // Size of texture before compression (may be inflated due to tiling alignment) + size_t CompressedSizeBytes; // Size of texture data after compression + float CompressionTime; // Cumulative CPU time spent compressing on multiple threads + float WallTime; // Actual end-to-end time spent compressing + + float CompressionRatio() const + { + return (float)UncompressedSizeBytes / (float)CompressedSizeBytes; + } + + float CompressedSizeAsPercent() const + { + return (float)CompressedSizeBytes / (float)UncompressedSizeBytes * 100.0f; + } +}; + +//------------------------------------------------------------------------------------------------- +// Compress a buffer with arbitrary data and append it to the archive. + +XBTCDLLAPI(HRESULT) XBTCCompressBuffer( + _Inout_ XBTCArchiveWriter* pArchive, + _Out_opt_ XBTC_COMPRESSION_STATS* pStats, + _In_ const XBTCTextureContainer* pBufferContainer, + _In_ XBTC_COMPRESSION_FLAGS Flags); + + +//------------------------------------------------------------------------------------------------- +// Compress the source (pre-tiled) texture and append it to the archive. +// +// Loss of 0 (lossless) will not re-encode a BC texture with rate distortion optimization. +// If the texture is re-encoded, the contents of the pTextureContainer will be overwritten. +// Loss will never be introduced for non-BC textures. + +XBTCDLLAPI(HRESULT) XBTCCompressTexture( + _Inout_ XBTCArchiveWriter* pArchive, + _Out_opt_ XBTC_COMPRESSION_STATS* pStats, + _In_ const XBTCTextureContainer* pTextureContainer, + _In_ size_t MipStreams, // Number of streamable LODs after the base texture + _In_ XBTC_STREAM_GRANULARITY Granularity, // Streaming granularity + _In_ XBTC_COMPRESSION_FLAGS Flags, + _In_ size_t Loss = 0); // More loss will improve compression ratios. [0-15] + +//------------------------------------------------------------------------------------------------- +// Tile the texture, compress it, and append it to the archive. +// +// Loss of 0 (lossless) will not re-encode a BC texture with rate distortion optimization. +// If the texture is re-encoded, the contents of the pTextureContainer will be overwritten. +// Loss will never be introduced for non-BC textures. + +XBTCDLLAPI(HRESULT) XBTCTileAndCompressTexture( + _Inout_ XBTCArchiveWriter* pArchive, + _Out_opt_ XBTC_COMPRESSION_STATS* pStats, + _In_ const XBTCTextureContainer* pTextureContainer, + _In_ XBTC_TILING_MODE TilingMode, + _In_ size_t MipStreams, // Number of streamable LODs after the base texture + _In_ XBTC_STREAM_GRANULARITY Granularity, // Streaming granularity + _In_ XBTC_COMPRESSION_FLAGS Flags, + _In_ size_t Loss = 0); // More loss will improve compression ratios. [0-15] + +//------------------------------------------------------------------------------------------------- +// Extract a texture from the archive. Writes to pre-allocated tiled texture memory. + +XBTCDLLAPI(HRESULT) XBTCDecompressTexture( + _Out_writes_(UncompressedSize) + void* pTiledMemory, + _In_ size_t UncompressedSize, + _In_ const XBTCArchive* pArchive, + _In_ uint32_t TextureIdx); + +//------------------------------------------------------------------------------------------------- +// Extract a texture from the archive. Allocates a texture container. + +XBTCDLLAPI(HRESULT) XBTCDecompressTextureAlloc( + _Out_ XBTCTextureContainer** ppTextureContainer, + _In_ const XBTCArchive* pArchive, + _In_ uint32_t TextureIdx); + +//------------------------------------------------------------------------------------------------- +// Extract a texture from the archive and linearizes it. Allocates a texture container. + +XBTCDLLAPI(HRESULT) XBTCDecompressAndDetileTextureAlloc( + _Out_ XBTCTextureContainer** ppTextureContainer, + _In_ const XBTCArchive* pArchive, + _In_ uint32_t TextureIdx); + + +//------------------------------------------------------------------------------------------------- +// Stream indices can be identified either from relative virtual memory addressing in the +// case of paged textures (SFS) or by the mip level in all other cases. The stream index +// offset should be added to the resource's base stream index to determine the absolute +// stream index. +// +// Note: Interpret negative values as errors. + +//------------------------------------------------------------------------------------------------- +// For SFS, each 64KB/128KB page after the base texture is compressed in order. The base texture is always stream 0. + +inline int32_t XBTCGetRelativeStreamIndex(ptrdiff_t OffsetFromBaseAddr, size_t BaseTextureSize, size_t PageSize = 0x10000) +{ + // You shouldn't really be calling this function for the base texture stream + if (OffsetFromBaseAddr == 0) + return 0; + + // Subtract the size of the base texture which is not chunked into pages + OffsetFromBaseAddr -= BaseTextureSize; + + // If the address is not aligned to a page boundry, return an error + if (OffsetFromBaseAddr & (PageSize - 1)) + return -1; + + return (int32_t)(OffsetFromBaseAddr / PageSize) + 1; +} + +//------------------------------------------------------------------------------------------------- +// For mip-streaming textures, the base texture is compressed first and each more resolute +// mip level after that. Assumes the texture has dimension kTexture2D. + +inline int32_t XBTCGetRelativeStreamIndex(uint32_t MipStreams, uint32_t MipLevel) +{ + return (int32_t)(MipStreams - MipLevel); +} + +//------------------------------------------------------------------------------------------------- +// This is a helper class for looking up stream indices associated with PRT texture regions (motived +// by Sampler Feedback Streaming.) Use this in conjunction with XBTCArchiveReader to stream compressed +// regions of granularity 64KB, 128KB, or 256KB. + +class XBTCStreamingTextureReader +{ +public: + XBTCStreamingTextureReader() + { + ZeroMemory(this, sizeof(*this)); + } + + HRESULT PrepareTexture(const XBTCArchive* pArchive, uint32_t ResourceIdx) + { + const XBTC_TEXTURE_INFO* TexInfo = pArchive->GetTextureInfo(ResourceIdx); + + // Only valid textures with stream granularity other than whole mips are supported + if (TexInfo == nullptr || + TexInfo->Format == DXGI_FORMAT_UNKNOWN || + TexInfo->Granularity == XBTC_STREAM_GRANULARITY_WHOLE_MIPS) + { + return E_INVALIDARG; + } + + const DXGI_FORMAT Format = (DXGI_FORMAT)TexInfo->Format; + const bool IsBlockCompressed = + (Format >= DXGI_FORMAT_BC1_TYPELESS && Format <= DXGI_FORMAT_BC5_SNORM) || + (Format >= DXGI_FORMAT_BC6H_TYPELESS && Format <= DXGI_FORMAT_BC7_UNORM_SRGB); + + // 3D, 2DArray, and non-BC formats are not yet supported + if (TexInfo->Depth != 0 || !IsBlockCompressed) + { + return E_NOTIMPL; + } + + const uint32_t ElementSize = + (Format >= DXGI_FORMAT_BC1_TYPELESS && Format <= DXGI_FORMAT_BC1_UNORM_SRGB) || + (Format >= DXGI_FORMAT_BC4_TYPELESS && Format <= DXGI_FORMAT_BC4_SNORM) ? 8 : 16; + + m_BaseStreamIndex = pArchive->GetResourceBaseStreamIndex(ResourceIdx); + m_MipStreamCount = (uint32_t)TexInfo->MipStreams; + + static const uint32_t s_TileHeights[] = { 4, 16, 64, 256, 256 }; + uint32_t TileWidthInPixels = s_TileHeights[TexInfo->TileMode]; + uint32_t TileHeightInPixels = s_TileHeights[TexInfo->TileMode]; + if (ElementSize < 16) + TileWidthInPixels *= 2; + + m_ClusterWidthLog2 = TexInfo->Granularity == XBTC_STREAM_GRANULARITY_64KB ? 0 : 1; + m_ClusterHeightLog2 = TexInfo->Granularity == XBTC_STREAM_GRANULARITY_128KB ? 0 : 1; + + uint32_t StreamIndex = pArchive->GetResourceStreamCount(ResourceIdx); + uint32_t LevelWidth = (uint32_t)TexInfo->Width + 1; + uint32_t LevelHeight = (uint32_t)TexInfo->Height + 1; + + // For every mip that is streamable, count how many streams it requires and subtract that memory from the base + for (size_t mip = 0; mip < m_MipStreamCount; ++mip) + { + const uint32_t WidthInPages = (LevelWidth + TileWidthInPixels - 1) / TileWidthInPixels; + const uint32_t HeightInPages = (LevelHeight + TileHeightInPixels - 1) / TileHeightInPixels; + const uint32_t StreamsThisMip = (WidthInPages >> m_ClusterWidthLog2) * (HeightInPages >> m_ClusterHeightLog2); + + StreamIndex -= StreamsThisMip; + LevelWidth = (LevelWidth + 1) / 2; + LevelHeight = (LevelHeight + 1) / 2; + + m_MipStreams[mip].FirstStreamIndex = StreamIndex; + m_MipStreams[mip].WidthInPages = WidthInPages; + m_MipStreams[mip].HeightInPages = HeightInPages; + } + + return S_OK; + } + + int32_t GetAbsoluteStreamIndex(size_t MipLevel, uint32_t TileX, uint32_t TileY) const + { + // Check for invalid mip level + if (MipLevel >= m_MipStreamCount) + { + return -1; + } + + const MipDigest& Digest = m_MipStreams[MipLevel]; + const uint32_t NumCols = Digest.WidthInPages >> m_ClusterWidthLog2; + const uint32_t NumRows = Digest.HeightInPages >> m_ClusterHeightLog2; + + // Check for tile coordinates out of bounds + if (TileX >= NumCols || TileY >= NumRows) + { + return -1; + } + + const uint32_t AbsoluteStreamIndex = m_BaseStreamIndex + Digest.FirstStreamIndex + + TileY * NumCols + TileX; + + return (int32_t)AbsoluteStreamIndex; + } + + // Referring to a specific mip level, access the stream index associated with the memory region starting at the + // offset relative to the start of the level's base address. + int32_t GetAbsoluteStreamIndex(size_t MipLevel, ptrdiff_t OffsetFromLevelStart) const + { + // Check for invalid mip level or offset + if (MipLevel >= m_MipStreamCount || (OffsetFromLevelStart & 0xFFFFFFFF0000FFFFull)) + { + return -1; + } + + const MipDigest& Digest = m_MipStreams[MipLevel]; + const uint32_t OffsetInPages = (uint32_t)OffsetFromLevelStart >> 16; + + // Check for offset out of bounds for the mip level + if (OffsetInPages >= Digest.WidthInPages * Digest.HeightInPages) + { + return -1; + } + + const uint32_t TileX = (OffsetInPages % Digest.WidthInPages) >> m_ClusterWidthLog2; + const uint32_t TileY = (OffsetInPages / Digest.WidthInPages) >> m_ClusterHeightLog2; + + const uint32_t AbsoluteStreamIndex = m_BaseStreamIndex + Digest.FirstStreamIndex + + TileY * (Digest.WidthInPages >> m_ClusterWidthLog2) + TileX; + + return (int32_t)AbsoluteStreamIndex; + } + +private: + struct MipDigest + { + uint32_t FirstStreamIndex : 16; + uint32_t WidthInPages : 8; // Width of texture level in 64KB tiles + uint32_t HeightInPages : 8; // Height of texture level in 64KB tiles + }; + + uint32_t m_MipStreamCount : 4; + uint32_t m_ClusterWidthLog2 : 2; + uint32_t m_ClusterHeightLog2 : 2; + uint32_t m_BaseStreamIndex; + MipDigest m_MipStreams[6]; +}; + +//------------------------------------------------------------------------------------------------- + +class XBTCArchiveReader : public XBTCArchive +{ +public: + + //------------------------------------------------------------------------------------------------- + XBTCArchiveReader() : m_InternalMemory(nullptr), m_FilePointer(nullptr) { Close(); } + + //------------------------------------------------------------------------------------------------- + ~XBTCArchiveReader() { Close(); } + + //------------------------------------------------------------------------------------------------- + // Tests if the file path is a valid archive and returns the amount of the file to read and + // open the archive. Use with OpenFromMemory() to handle your own memory management or file I/O. + static size_t IsValidArchive(const wchar_t* ArchiveFilePath); + + //------------------------------------------------------------------------------------------------- + // Parse an archive header in memory + bool OpenFromMemory(const XBTC_ARCHIVE_HEADER* ArchiveMemory); + + //------------------------------------------------------------------------------------------------- + // Parse an archive header from a file pointer. This allocates memory for the header. + bool OpenFromFile(const wchar_t* ArchiveFilePath); + + //------------------------------------------------------------------------------------------------- + // Close the archive reader to allow for reuse or to free memory + void Close(); + + //------------------------------------------------------------------------------------------------- + // Check if the archive is open and valid + bool IsValid() const + { + return m_ResourceCount != 0; + } + + //------------------------------------------------------------------------------------------------- + // Check if the archive is open and valid + operator bool () const + { + return IsValid(); + } + + //------------------------------------------------------------------------------------------------- + virtual uint32_t GetResourceCount() const override { return m_ResourceCount; } + + //------------------------------------------------------------------------------------------------- + virtual uint32_t GetStreamCount() const override { return m_StreamCount; } + + //------------------------------------------------------------------------------------------------- + virtual const XBTC_TEXTURE_INFO* GetTextureInfo(uint32_t ResourceIdx) const override { + return ResourceIdx < m_ResourceCount ? &m_TextureInfos[ResourceIdx] : nullptr; + } + + //------------------------------------------------------------------------------------------------- + virtual const XBTC_OFFSET_AND_INDEX* GetTextureOffset(uint32_t ResourceIdx) const override { + return ResourceIdx < m_ResourceCount ? &m_BaseLocations[ResourceIdx] : nullptr; + } + + //------------------------------------------------------------------------------------------------- + virtual const XBTC_STREAM_INFO* GetStreamInfo(uint32_t StreamIdx) const override { + return StreamIdx < m_StreamCount ? &m_StreamInfos[StreamIdx] : nullptr; + } + + //------------------------------------------------------------------------------------------------- + virtual const uint8_t* GetResourceStreamDataStart(uint32_t ResourceIdx) const override; + + //------------------------------------------------------------------------------------------------- + virtual int32_t GetResourceCompressedSize(uint32_t ResourceIdx) const override; + + //------------------------------------------------------------------------------------------------- + virtual int32_t GetResourceStreamCount(uint32_t ResourceIdx) const override; + + //------------------------------------------------------------------------------------------------- + virtual int32_t GetResourceBaseStreamIndex(uint32_t ResourceIdx) const override; + + //------------------------------------------------------------------------------------------------- + virtual int32_t GetBaseTextureSize(uint32_t ResourceIdx) const override; + + //------------------------------------------------------------------------------------------------- + // Returns the offset from the start of the file for the this resource's compressed streams. + int64_t GetResourceSeekOffset(uint32_t ResourceIdx) const; + + //------------------------------------------------------------------------------------------------- + // If the archive was opened from a file, returns the file pointer for seeking and reading. + FILE* GetOpenFile() const { return m_FilePointer; } + +private: + uint32_t m_ResourceCount; + uint32_t m_StreamCount; + uint32_t m_DataOffset; // File seek offset to stream data + const XBTC_TEXTURE_INFO* m_TextureInfos; + const XBTC_OFFSET_AND_INDEX* m_BaseLocations; + const XBTC_STREAM_INFO* m_StreamInfos; + const uint8_t* m_StreamData; + char* m_InternalMemory; // Memory to hold the archive contents with OpenFromFile() + FILE* m_FilePointer; +}; + +//------------------------------------------------------------------------------------------------- + +inline void XBTCArchiveReader::Close() +{ + m_ResourceCount = 0; + m_StreamCount = 0; + m_DataOffset = 0; + m_TextureInfos = nullptr; + m_BaseLocations = nullptr; + m_StreamInfos = nullptr; + m_StreamData = nullptr; + if (m_InternalMemory != nullptr) + { + free(m_InternalMemory); + m_InternalMemory = nullptr; + } + if (m_FilePointer != nullptr) + { + fclose(m_FilePointer); + m_FilePointer = nullptr; + } +} + +//------------------------------------------------------------------------------------------------- + +inline size_t XBTCArchiveReader::IsValidArchive(const wchar_t* archiveFilePath) +{ + XBTC_ARCHIVE_HEADER archive; + + FILE* file; + if (0 != _wfopen_s(&file, archiveFilePath, L"rb" )) // file found? + { + return 0; + } + + if (1 != fread_s(&archive, sizeof(archive), sizeof(archive), 1, file) || // read success? + XBTC_ARCHIVE_IDENTIFIER != archive.Identifier || // proper ID? + XBTC_ARCHIVE_VERSION != archive.Version) // correct version? + { + fclose(file); + return 0; + } + + fclose(file); + + return archive.DataOffset; +} + +//------------------------------------------------------------------------------------------------- + +inline bool XBTCArchiveReader::OpenFromMemory(const XBTC_ARCHIVE_HEADER* archive) +{ + if (IsValid() || // already open? + XBTC_ARCHIVE_IDENTIFIER != archive->Identifier || // proper ID? + XBTC_ARCHIVE_VERSION != archive->Version) // correct version? + { + return false; + } + + m_ResourceCount = archive->TextureCount; + m_TextureInfos = (const XBTC_TEXTURE_INFO*)(archive + 1); + m_BaseLocations = (const XBTC_OFFSET_AND_INDEX*)(m_TextureInfos + m_ResourceCount); + m_StreamInfos = (const XBTC_STREAM_INFO*)(m_BaseLocations + m_ResourceCount); + m_StreamCount = m_BaseLocations[m_ResourceCount - 1].NextIndex; + m_DataOffset = (uint32_t)archive->DataOffset; + m_StreamData = (const uint8_t*)archive + m_DataOffset; + m_FilePointer = nullptr; + + return true; +} + +//------------------------------------------------------------------------------------------------- + +inline bool XBTCArchiveReader::OpenFromFile(const wchar_t* archiveFilePath) +{ + if (IsValid()) // already open? + return false; + + XBTC_ARCHIVE_HEADER archive; + + FILE* file; + if (0 != _wfopen_s(&file, archiveFilePath, L"rb" )) // file found? + { + return false; + } + + if (1 != fread_s(&archive, sizeof(archive), sizeof(archive), 1, file) || // read success? + XBTC_ARCHIVE_IDENTIFIER != archive.Identifier || // proper ID? + XBTC_ARCHIVE_VERSION != archive.Version) // correct version? + { + fclose(file); + return false; + } + + const size_t sizeOfTOC = archive.DataOffset - sizeof(XBTC_ARCHIVE_HEADER); + m_InternalMemory = (char*)malloc(sizeOfTOC); + if (!fread_s(m_InternalMemory, sizeOfTOC, sizeOfTOC, 1, file)) + { + fclose(file); + free(m_InternalMemory); + m_InternalMemory = nullptr; + return false; + } + + m_ResourceCount = archive.TextureCount; + m_TextureInfos = (const XBTC_TEXTURE_INFO*)m_InternalMemory; + m_BaseLocations = (const XBTC_OFFSET_AND_INDEX*)(m_TextureInfos + m_ResourceCount); + m_StreamInfos = (const XBTC_STREAM_INFO*)(m_BaseLocations + m_ResourceCount); + m_StreamCount = m_BaseLocations[m_ResourceCount - 1].NextIndex; + m_DataOffset = (uint32_t)archive.DataOffset; + m_StreamData = nullptr; + m_FilePointer = file; + + return true; +} + +//------------------------------------------------------------------------------------------------- + +inline int32_t XBTCArchiveReader::GetResourceStreamCount(uint32_t ResourceIdx) const +{ + if (ResourceIdx >= m_ResourceCount) + { + return -1; + } + else if (ResourceIdx == 0) + { + return (int32_t)m_BaseLocations[ResourceIdx].NextIndex; + } + else + { + return (int32_t)m_BaseLocations[ResourceIdx].NextIndex - + (int32_t)m_BaseLocations[ResourceIdx-1].NextIndex; + } +} + +//------------------------------------------------------------------------------------------------- + +inline int32_t XBTCArchiveReader::GetResourceBaseStreamIndex(uint32_t ResourceIdx) const +{ + if (ResourceIdx == 0) + { + return 0; + } + else if (ResourceIdx >= m_ResourceCount) + { + return -1; + } + else + { + return (int32_t)m_BaseLocations[ResourceIdx-1].NextIndex; + } +} + +//------------------------------------------------------------------------------------------------- + +inline int32_t XBTCArchiveReader::GetBaseTextureSize(uint32_t ResourceIdx) const +{ + const XBTC_TEXTURE_INFO* TexInfo = GetTextureInfo(ResourceIdx); + + // Invalid resources and buffers do not have a base texture size + if (TexInfo == nullptr || TexInfo->Format == DXGI_FORMAT_UNKNOWN) + { + return -1; + } + + // Textures without separate mip streams have a base size of zero. + if (TexInfo->MipStreams == 0) + { + return 0; + } + + const int32_t BaseStreamIndex = m_BaseLocations[ResourceIdx-1].NextIndex; + + return (int32_t)GetStreamInfo(BaseStreamIndex)->UncompressedSize; +} + +//------------------------------------------------------------------------------------------------- + +inline const uint8_t* XBTCArchiveReader::GetResourceStreamDataStart(uint32_t ResourceIdx) const +{ + if (m_StreamData == nullptr || ResourceIdx >= m_ResourceCount) + { + return nullptr; + } + else + { + return m_StreamData + m_BaseLocations[ResourceIdx].BaseOffset; + } +} + +//------------------------------------------------------------------------------------------------- + +inline int64_t XBTCArchiveReader::GetResourceSeekOffset(uint32_t ResourceIdx) const +{ + if (ResourceIdx >= m_ResourceCount) + { + return -1; + } + else + { + return m_DataOffset + m_BaseLocations[ResourceIdx].BaseOffset; + } +} + +//------------------------------------------------------------------------------------------------- + +inline int32_t XBTCArchiveReader::GetResourceCompressedSize(uint32_t ResourceIdx) const +{ + if (ResourceIdx >= m_ResourceCount) + { + return -1; + } + + const int32_t lastStreamIdx = (ResourceIdx == m_ResourceCount - 1) ? + m_StreamCount - 1 : + (int32_t)m_BaseLocations[ResourceIdx].NextIndex - 1; + + const XBTC_STREAM_INFO* lastStream = GetStreamInfo(lastStreamIdx); + + return lastStream->RelativeOffset + lastStream->CompressedSize; +} + diff --git a/docs/gdkx/XBTC_NOTICE.txt b/docs/gdkx/XBTC_NOTICE.txt new file mode 100644 index 0000000..a27dab9 --- /dev/null +++ b/docs/gdkx/XBTC_NOTICE.txt @@ -0,0 +1,304 @@ +NOTICES AND INFORMATION +Do Not Translate or Localize + +This software incorporates material from third parties. Microsoft makes certain +open source code available at https://3rdpartysource.microsoft.com, or you may +send a check or money order for US $5.00, including the product name, the open +source component name, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the +extent required to debug changes to any libraries licensed under the GNU Lesser +General Public License. + + +------------------------------------------------------------------------------- +Zlib -- https://github.com/madler/zlib + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate and + zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; they + are too numerous to cite here. + +Copyright notice: + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + +------------------------------------------------------------------------------- +JSON for Modern C++ -- https://github.com/nlohmann/json + +MIT License + +Copyright (c) 2013-2019 Niels Lohmann + +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. + +Acknowledgments: + +The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed +under the MIT License (see above). Copyright © 2008-2009 Björn Hoehrmann +bjoern@hoehrmann.de + +The class contains a slightly modified version of the Grisu2 algorithm from +Florian Loitsch which is licensed under the MIT License (see above). +Copyright © 2009 Florian Loitsch + +The class contains a copy of Hedley from Evan Nemerson which is licensed as +CC0-1.0. + + +------------------------------------------------------------------------------- +Zopfli -- https://github.com/google/zopfli + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2011 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Acknowledgements: + +Zopfli Compression Algorithm was created by Lode Vandevenne and Jyrki +Alakuijala, based on an algorithm by Jyrki Alakuijala. + +------------------------------------------------------------------------------- +END \ No newline at end of file diff --git a/docs/gdkx/XDXRStandaloneTraverseReadMe.md b/docs/gdkx/XDXRStandaloneTraverseReadMe.md new file mode 100644 index 0000000..190f40d --- /dev/null +++ b/docs/gdkx/XDXRStandaloneTraverseReadMe.md @@ -0,0 +1,2 @@ +See "XDXR Standalone Traverse" in the GDK.chm or online GDK documentation. +// ver:xb_flt_2610ge:20160101-0000 \ No newline at end of file diff --git a/docs/gdkx/XSystem.h b/docs/gdkx/XSystem.h new file mode 100644 index 0000000..3e1605c --- /dev/null +++ b/docs/gdkx/XSystem.h @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved + +#if !defined(__cplusplus) + #error C++11 required +#endif + +#pragma once + +#include + +extern "C" +{ + +struct XSystemAnalyticsInfo +{ + XVersion osVersion; + XVersion hostingOsVersion; + _Field_z_ char family[64]; + _Field_z_ char form[64]; +}; + +STDAPI_(XSystemAnalyticsInfo) XSystemGetAnalyticsInfo() noexcept; + +const size_t XSystemConsoleIdBytes = 39; + +STDAPI XSystemGetConsoleId( + _In_ size_t consoleIdSize, + _Out_writes_bytes_to_(consoleIdSize, *consoleIdUsed) char* consoleId, + _Out_opt_ size_t* consoleIdUsed + ) noexcept; + + +const size_t XSystemXboxLiveSandboxIdMaxBytes = 16; + +STDAPI XSystemGetXboxLiveSandboxId( + _In_ size_t sandboxIdSize, + _Out_writes_bytes_to_(sandboxIdSize, *sandboxIdUsed) char* sandboxId, + _Out_opt_ size_t* sandboxIdUsed + ) noexcept; + +enum class XSystemDeviceType : uint32_t { + Unknown = 0x00, + Pc = 0x01, + XboxOne = 0x02, + XboxOneS = 0x03, + XboxOneX = 0x04, + XboxOneXDevkit = 0x05, + XboxScarlettLockhart = 0x06, + XboxScarlettAnaconda = 0x07, + XboxScarlettDevkit = 0x08 +}; + +STDAPI_(XSystemDeviceType) XSystemGetDeviceType() noexcept; + +const size_t XSystemAppSpecificDeviceIdBytes = 45; + +STDAPI XSystemGetAppSpecificDeviceId( + _In_ size_t appSpecificDeviceIdSize, + _Out_writes_bytes_to_(appSpecificDeviceIdSize, *appSpecificDeviceIdUsed) char* appSpecificDeviceId, + _Out_opt_ size_t* appSpecificDeviceIdUsed + ) noexcept; + + +// Handle tracking. + +enum class XSystemHandleType : uint32_t +{ + AppCaptureScreenshotStream = 0x00, + DisplayTimeoutDeferral = 0x01, + GameSaveContainer = 0x02, + GameSaveProvider = 0x03, + GameSaveUpdate = 0x04, + PackageInstallationMonitor = 0x05, + PackageMount = 0x06, + SpeechSynthesizer = 0x07, + SpeechSynthesizerStream = 0x08, + StoreContext = 0x09, + StoreLicense = 0x0a, + StoreProductQuery = 0x0b, + TaskQueue = 0x0c, + User = 0x0d, + UserSignOutDeferral = 0x0e, + GameUiTextEntry = 0x0f, + PFXGameSaveConfig = 0x10, +}; + +enum class XSystemHandleCallbackReason : uint32_t +{ + Created = 0x00, + Destroyed = 0x01, +}; + +typedef void* XSystemHandle; + +typedef void (CALLBACK *XSystemHandleCallback)( + _In_ XSystemHandle handle, + _In_ XSystemHandleType type, + _In_ XSystemHandleCallbackReason reason, + _In_ void* context + ); + +STDAPI XSystemHandleTrack( + _In_ XSystemHandleCallback callback, + _In_opt_ void* context + ) noexcept; + +STDAPI_(bool) XSystemIsHandleValid( + _In_ XSystemHandle handle + ) noexcept; + + +struct XSystemRuntimeInfo +{ + XVersion runtimeVersion; + XVersion availableVersion; +}; + +STDAPI_(XSystemRuntimeInfo) XSystemGetRuntimeInfo() noexcept; + + +STDAPI_(void) XSystemAllowFullDownloadBandwidth( + _In_ bool enable + ) noexcept; +} diff --git a/docs/gdkx/XTaskQueue.h b/docs/gdkx/XTaskQueue.h new file mode 100644 index 0000000..0aae209 --- /dev/null +++ b/docs/gdkx/XTaskQueue.h @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Corporation +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#if !defined(__cplusplus) + #error C++11 required +#endif + +#pragma once +#include + +extern "C" +{ + +///

+/// A task queue contains and dispatches callbacks. A task queue has two ports: a worker port and +/// a completion port. Each port can have different rules for how queued calls +/// are dispatched. +/// +typedef struct XTaskQueueObject* XTaskQueueHandle; + +/// +/// A task queue port represents one port of a task queue. A port's lifetime is controlled +/// by its owning task queue. +/// +typedef struct XTaskQueuePortObject* XTaskQueuePortHandle; + +/// +/// Describes how task queue callbacks are processed. +/// +enum class XTaskQueueDispatchMode : uint32_t +{ + /// + /// Callbacks are invoked manually by XTaskQueueDispatch + /// + Manual, + + /// + /// Callbacks are queued to the system thread pool and will + /// be processed in order by the thread pool across multiple thread + /// pool threads. + /// + ThreadPool, + + /// + /// Callbacks are queued to the system thread pool and + /// will be processed one at a time. + /// + SerializedThreadPool, + + /// + /// Callbacks are not queued at all but are dispatched + /// immediately by the thread that submits them. + /// + Immediate +}; + +/// +/// Declares which port of a task queue to dispatch or submit +/// callbacks to. +/// +enum class XTaskQueuePort : uint32_t +{ + /// + /// Work callbacks + /// + Work, + + /// + /// Completion callbacks after work is done + /// + Completion +}; + +/// +/// A token returned when registering a callback to identify the registration. This token +/// is later used to unregister the callback. +/// +struct XTaskQueueRegistrationToken +{ + uint64_t token; +}; + +/// +/// A callback that is invoked by the task queue. +/// +/// A context pointer that was passed during XTaskQueueSubmitCallback. +/// If true, callbacks are being canceled because the queue is terminating. +/// +typedef void CALLBACK XTaskQueueCallback(_In_opt_ void* context, _In_ bool canceled); + +/// +/// A callback that is invoked by the task queue whenever an item is submitted for execution. +/// +/// A context pointer that was passed during XTaskQueueRegisterMonitor. +/// The task queue where the callback was submitted. +/// The port the callback was submitted to. +/// +typedef void CALLBACK XTaskQueueMonitorCallback(_In_opt_ void* context, _In_ XTaskQueueHandle queue, _In_ XTaskQueuePort port); + +/// +/// A callback that is invoked when a task queue is terminated. +/// +/// A context pointer that was passed during XTaskQueueTerminate. +typedef void CALLBACK XTaskQueueTerminatedCallback(_In_opt_ void* context); + +/// +/// Creates a Task Queue, which can be used to queue +/// and dispatch calls. Task Queues are +/// reference counted objects. Release the reference +/// by calling XTaskQueueCloseHandle. +/// +/// The dispatch mode for the "work" port of the queue. +/// The dispatch mode for the "completion" port of the queue. +/// The newly created queue. +STDAPI XTaskQueueCreate( + _In_ XTaskQueueDispatchMode workDispatchMode, + _In_ XTaskQueueDispatchMode completionDispatchMode, + _Out_ XTaskQueueHandle* queue + ) noexcept; + +/// +/// Creates a task queue composed of ports of other +/// task queues. A composite task queue will duplicate +/// the handles of queues that own the provided ports. +/// +/// The port to use for queuing work callbacks. +/// The port to use for queuing completion callbacks. +STDAPI XTaskQueueCreateComposite( + _In_ XTaskQueuePortHandle workPort, + _In_ XTaskQueuePortHandle completionPort, + _Out_ XTaskQueueHandle* queue + ) noexcept; + +/// +/// Returns the task queue port handle for the given +/// port. Task queue port handles are owned by the +/// task queue and do not have to be closed. They are +/// used when creating composite task queues. +/// +/// The task queue to get the port from. +/// The port to get. +STDAPI XTaskQueueGetPort( + _In_ XTaskQueueHandle queue, + _In_ XTaskQueuePort port, + _Out_ XTaskQueuePortHandle* portHandle + ) noexcept; + +/// +/// Duplicates the XTaskQueueHandle object. Use XTaskQueueCloseHandle to close it. +/// +/// The queue to reference. +/// The duplicated queue handle. +STDAPI XTaskQueueDuplicateHandle( + _In_ XTaskQueueHandle queueHandle, + _Out_ XTaskQueueHandle* duplicatedHandle + ) noexcept; + +/// +/// Processes an item in the task queue for the given port. If an item +/// is processed this will return true. If there are no items to process +/// this returns false. You can pass a timeout, which will cause +/// XTaskQueueDispatch to wait for something to arrive in the queue. +/// +/// The queue to dispatch work on. +/// The port to dispatch. +/// The number of ms to wait for work to arrive before returning false. +STDAPI_(bool) XTaskQueueDispatch( + _In_ XTaskQueueHandle queue, + _In_ XTaskQueuePort port, + _In_ uint32_t timeoutInMs + ) noexcept; + +/// +/// Closes the task queue. The queue is not actually destroyed until +/// all handles are closed and there are no outstanding callbacks +/// enqueued. +/// +/// The queue to close. +STDAPI_(void) XTaskQueueCloseHandle( + _In_ XTaskQueueHandle queue + ) noexcept; + +/// +/// Terminates a task queue by canceling all pending items and +/// preventing new items from being queued. Once a queue is terminated +/// its handle can be closed. New items cannot be enqueued to a task +/// queue that has been terminated. +/// +/// Each task queue terminates independently. For composite queues created +/// with XTaskQueueCreateComposite, terminating a composite queue does NOT +/// automatically terminate other queues sharing the same ports. +/// +/// When wait=true: +/// - Blocks until this queue's termination callback completes +/// - Does NOT wait for other independent queues (including composite delegates) +/// - Ensures this queue's termination callback has finished executing +/// - Safe to unload code/modules after this returns +/// +/// When wait=false: +/// - Returns immediately after initiating termination +/// - The termination callback will be invoked asynchronously when termination completes +/// +/// The termination callback is invoked after all work and completion callbacks +/// have been canceled or completed. After the termination callback returns, the +/// implementation will no longer access the queue's internal state. +/// +/// For coordinated shutdown of multiple queues sharing ports, use termination +/// callbacks to track completion of each queue before performing final cleanup. +/// +/// The queue to terminate. +/// True to wait for the termination to complete. +/// An optional context pointer to pass to the callback. +/// An optional callback that will be called when the queue has terminated. +STDAPI XTaskQueueTerminate( + _In_ XTaskQueueHandle queue, + _In_ bool wait, + _In_opt_ void* callbackContext, + _In_opt_ XTaskQueueTerminatedCallback* callback + ) noexcept; + +/// +/// Submits a callback to the queue for the given port. +/// +/// The queue to submit the callback to. +/// The port to submit the callback to. +/// An optional context pointer that will be passed to the callback. +/// A pointer to the callback function. +STDAPI XTaskQueueSubmitCallback( + _In_ XTaskQueueHandle queue, + _In_ XTaskQueuePort port, + _In_opt_ void* callbackContext, + _In_ XTaskQueueCallback* callback + ) noexcept; + +/// +/// Submits a callback to the queue for the given port. The callback will be added +/// to the queue after delayMs milliseconds. +/// +/// The queue to submit the callback to. +/// The port to submit the callback to. +/// The number of milliseconds to delay before submitting the callback to the queue. +/// An optional context pointer that will be passed to the callback. +/// A pointer to the callback function. +STDAPI XTaskQueueSubmitDelayedCallback( + _In_ XTaskQueueHandle queue, + _In_ XTaskQueuePort port, + _In_ uint32_t delayMs, + _In_opt_ void* callbackContext, + _In_ XTaskQueueCallback* callback + ) noexcept; + +/// +/// Registers a wait handle with the task queue. When the wait handle +/// is satisfied the task queue will invoke the given callback. This +/// provides an efficient way to add items to a task queue in +/// response to handles becoming signaled. +/// +/// The queue to submit the callback to. +/// The port to invoke the callback on. +/// The handle to monitor. +/// An optional context pointer that will be passed to the callback. +/// A pointer to the callback function. +/// A registration token. +STDAPI XTaskQueueRegisterWaiter( + _In_ XTaskQueueHandle queue, + _In_ XTaskQueuePort port, + _In_ HANDLE waitHandle, + _In_opt_ void* callbackContext, + _In_ XTaskQueueCallback* callback, + _Out_ XTaskQueueRegistrationToken* token + ) noexcept; + +/// +/// Unregisters a previously registered task queue waiter. +/// +/// The queue to remove the waiter from. +/// The token returned from XTaskQueueRegisterWaiter. +STDAPI_(void) XTaskQueueUnregisterWaiter( + _In_ XTaskQueueHandle queue, + _In_ XTaskQueueRegistrationToken token + ) noexcept; + +/// +/// Registers a callback that will be invoked whenever a callback +/// is submitted to this queue. +/// +/// The queue to register the submit callback to. +/// An optional context pointer to be passed to the callback. +/// A callback that will be invoked when a new callback is submitted to the queue. +/// A token used in a later call to XTaskQueueUnregisterMonitor to remove the callback. +STDAPI XTaskQueueRegisterMonitor( + _In_ XTaskQueueHandle queue, + _In_opt_ void* callbackContext, + _In_ XTaskQueueMonitorCallback* callback, + _Out_ XTaskQueueRegistrationToken* token + ) noexcept; + +/// +/// Unregisters a previously registered callback. This blocks if there are outstanding montior +/// callbacks. +/// +/// The queue to remove the submit callback from. +/// The token returned from XTaskQueueRegisterMonitor. +STDAPI_(void) XTaskQueueUnregisterMonitor( + _In_ XTaskQueueHandle queue, + _In_ XTaskQueueRegistrationToken token + ) noexcept; + +/// +/// Obtains a handle to the process task queue, or nullptr if there is no +/// process task queue. By default, there is a process task queue +/// that uses the thread pool for both work and completion ports. You +/// can replace the default process task queue by calling +/// XTaskQueueSetCurrentProcessTaskQueue, and you can prevent callers using +/// the process task queue by calling XTaskQueueSetCurrentProcessTaskQueue +/// with a null queue parameter. +/// +/// This API returns true if there is a process task queue available. +/// You are responsible for calling XTaskQueueCloseHandle on the handle +/// returned from this API. +/// +STDAPI_(bool) XTaskQueueGetCurrentProcessTaskQueue(_Out_ XTaskQueueHandle* queue) noexcept; + +/// +/// Sets the given task queue as the process wide task queue. The +/// queue can be set to nullptr, in which case XTaskQueueGetCurrentProcessTaskQueue will +/// also return nullptr. The provided queue will have its handle duplicated +/// and any existing process task queue will have its handle closed. +/// +/// The queue to set up as the default task queue for the procces. +STDAPI_(void) XTaskQueueSetCurrentProcessTaskQueue( + _In_ XTaskQueueHandle queue + ) noexcept; + +} // extern "C" diff --git a/docs/gdkx/XUser.h b/docs/gdkx/XUser.h new file mode 100644 index 0000000..ce20f46 --- /dev/null +++ b/docs/gdkx/XUser.h @@ -0,0 +1,579 @@ +// Copyright (c) Microsoft Corporation. All rights reserved + +#if !defined(__cplusplus) + #error C++11 required +#endif + +#pragma once + +#include +#include +#include + +extern "C" +{ + +typedef struct XUser* XUserHandle; + +struct XUserLocalId +{ + uint64_t value; +}; + +const XUserLocalId XUserNullUserLocalId = {}; +const APP_LOCAL_DEVICE_ID XUserNullDeviceId = {}; + +STDAPI XUserDuplicateHandle( + _In_ XUserHandle handle, + _Out_ XUserHandle* duplicatedHandle + ) noexcept; + +STDAPI_(void) XUserCloseHandle( + _In_ XUserHandle user + ) noexcept; + +STDAPI_(int32_t) XUserCompare( + _In_opt_ XUserHandle user1, + _In_opt_ XUserHandle user2 + ) noexcept; + +// MaxUsers + +STDAPI XUserGetMaxUsers( + _Out_ uint32_t* maxUsers + ) noexcept; + +// AddUser + +enum class XUserAddOptions: uint32_t +{ + None = 0x00, + AddDefaultUserSilently = 0x01, + AllowGuests = 0x02, + AddDefaultUserAllowingUI = 0x04, +}; + +DEFINE_ENUM_FLAG_OPERATORS(XUserAddOptions); + +STDAPI XUserAddAsync( + _In_ XUserAddOptions options, + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserAddResult( + _Inout_ XAsyncBlock* async, + _Out_ XUserHandle* newUser + ) noexcept; + +STDAPI XUserAddByIdWithUiAsync ( + _In_ uint64_t userId, + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserAddByIdWithUiResult( + _Inout_ XAsyncBlock* async, + _Out_ XUserHandle* newUser +) noexcept; + +STDAPI_(bool) XUserIsSignOutPresent() noexcept; + +STDAPI XUserSignOutAsync( + _In_ XUserHandle user, + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserSignOutResult( + _Inout_ XAsyncBlock* async + ) noexcept; + +// UserId + +STDAPI XUserGetId( + _In_ XUserHandle user, + _Out_ uint64_t* userId + ) noexcept; + +STDAPI XUserFindUserById( + _In_ uint64_t userId, + _Out_ XUserHandle* handle + ) noexcept; + +// UserLocalId + +STDAPI XUserGetLocalId( + _In_ XUserHandle user, + _Out_ XUserLocalId* userLocalId + ) noexcept; + +STDAPI XUserFindUserByLocalId( + _In_ XUserLocalId userLocalId, + _Out_ XUserHandle* handle + ) noexcept; + +// APP_LOCAL_DEVICE_ID + +STDAPI XUserFindForDevice( + _In_ const APP_LOCAL_DEVICE_ID* deviceId, + _Out_ XUserHandle* handle + ) noexcept; + +// UserIsGuest + +STDAPI XUserGetIsGuest( + _In_ XUserHandle user, + _Out_ bool* isGuest + ) noexcept; + +// UserState + +enum class XUserState: uint32_t +{ + SignedIn = 0, + SigningOut = 1, + SignedOut = 2, +}; + +STDAPI XUserGetState( + _In_ XUserHandle user, + _Out_ XUserState* state + ) noexcept; + +// UserGamertag + +const size_t XUserGamertagComponentClassicMaxBytes = 16; +const size_t XUserGamertagComponentModernMaxBytes = 97; +const size_t XUserGamertagComponentModernSuffixMaxBytes = 15; +const size_t XUserGamertagComponentUniqueModernMaxBytes = 101; + +enum class XUserGamertagComponent: uint32_t +{ + Classic = 0, // Clasic Gamertag + Modern = 1, // Modern Gamertag without Suffix + ModernSuffix = 2, // Modern Gamertag Suffix if present (otherwise empty) + UniqueModern = 3, // Combined Modern Gamertag with Suffix +}; + +STDAPI XUserGetGamertag( + _In_ XUserHandle user, + _In_ XUserGamertagComponent gamertagComponent, + _In_ size_t gamertagSize, + _Out_writes_bytes_to_(gamertagSize, *gamertagUsed) char* gamertag, + _Out_opt_ size_t* gamertagUsed + ) noexcept; + +// UserGamerPicture + +enum class XUserGamerPictureSize: uint32_t +{ + Small = 0, // 64x64 + Medium = 1, // 208x208 + Large = 2, // 424x424 + ExtraLarge = 3, // 1080x1080 +}; + +STDAPI XUserGetGamerPictureAsync( + _In_ XUserHandle user, + _In_ XUserGamerPictureSize pictureSize, + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserGetGamerPictureResultSize( + _Inout_ XAsyncBlock* async, + _Out_ size_t* bufferSize + ) noexcept; + +STDAPI XUserGetGamerPictureResult( + _Inout_ XAsyncBlock* async, + _In_ size_t bufferSize, + _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, + _Out_opt_ size_t* bufferUsed + ) noexcept; + +// UserAgeGroup + +enum class XUserAgeGroup: uint32_t +{ + Unknown = 0, + Child = 1, + Teen = 2, + Adult = 3, +}; + +STDAPI XUserGetAgeGroup( + _In_ XUserHandle user, + _Out_ XUserAgeGroup* ageGroup + ) noexcept; + +// UserPrivilege + +enum class XUserPrivilege: uint32_t +{ + CrossPlay = 185, // The user can play with people outside of Xbox Live + Clubs = 188, // Create/join/participate in Clubs + Sessions = 189, // Create/join non interactive multiplayer sessions + Broadcast = 190, // Broadcast live gameplay + ManageProfilePrivacy = 196, // Change settings to show real name + GameDvr = 198, // Upload GameDVR + MultiplayerParties = 203, // Join parties + CloudManageSession = 207, // Allocate cloud compute resources for their session + CloudJoinSession = 208, // Join cloud compute sessions + CloudSavedGames = 209, // Save games on the cloud + SocialNetworkSharing = 220, // Share progress to social networks + UserGeneratedContent = 247, // Access user generated content in game + Communications = 252, // Use real time voice and text communication + Multiplayer = 254, // Join multiplayer sessions + AddFriends = 255, // Add friends / people to follow +}; + +enum class XUserPrivilegeDenyReason: uint32_t +{ + None = 0, + PurchaseRequired = 1, + Restricted = 2, + Banned = 3, + + Unknown = 0xFFFFFFFF +}; + +enum class XUserPrivilegeOptions: uint32_t +{ + None = 0x00, + AllUsers = 0x01, +}; + +DEFINE_ENUM_FLAG_OPERATORS(XUserPrivilegeOptions); + +STDAPI XUserCheckPrivilege( + _In_ XUserHandle user, + _In_ XUserPrivilegeOptions options, + _In_ XUserPrivilege privilege, + _Out_ bool* hasPrivilege, + _Out_opt_ XUserPrivilegeDenyReason* reason + ) noexcept; + +STDAPI XUserResolvePrivilegeWithUiAsync( + _In_ XUserHandle user, + _In_ XUserPrivilegeOptions options, + _In_ XUserPrivilege privilege, + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserResolvePrivilegeWithUiResult( + _Inout_ XAsyncBlock* async + ) noexcept; + +// UserTokenAndSignature + +enum class XUserGetTokenAndSignatureOptions: uint32_t +{ + None = 0x00, + ForceRefresh = 0x01, + AllUsers = 0x02, +}; + +DEFINE_ENUM_FLAG_OPERATORS(XUserGetTokenAndSignatureOptions); + +struct XUserGetTokenAndSignatureData +{ + size_t tokenSize; + size_t signatureSize; + _Field_size_bytes_opt_(tokenSize) _Null_terminated_ const char* token; + _Field_size_bytes_opt_(signatureSize) _Null_terminated_ const char* signature; +}; + +struct XUserGetTokenAndSignatureHttpHeader +{ + _Field_z_ const char* name; + _Field_z_ const char* value; +}; + +STDAPI XUserGetTokenAndSignatureAsync( + _In_ XUserHandle user, + _In_ XUserGetTokenAndSignatureOptions options, + _In_z_ const char* method, + _In_z_ const char* url, + _In_ size_t headerCount, + _In_reads_opt_(headerCount) const XUserGetTokenAndSignatureHttpHeader* headers, + _In_ size_t bodySize, + _In_reads_bytes_opt_(bodySize) const void* bodyBuffer, + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserGetTokenAndSignatureResultSize( + _Inout_ XAsyncBlock* async, + _Out_ size_t* bufferSize + ) noexcept; + +STDAPI XUserGetTokenAndSignatureResult( + _Inout_ XAsyncBlock* async, + _In_ size_t bufferSize, + _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, + _Outptr_ XUserGetTokenAndSignatureData** ptrToBuffer, + _Out_opt_ size_t* bufferUsed + ) noexcept; + +struct XUserGetTokenAndSignatureUtf16HttpHeader +{ + _Field_z_ const wchar_t* name; + _Field_z_ const wchar_t* value; +}; + +struct XUserGetTokenAndSignatureUtf16Data +{ + size_t tokenCount; + size_t signatureCount; + _Field_size_opt_(tokenCount) _Null_terminated_ const wchar_t* token; + _Field_size_opt_(signatureCount) _Null_terminated_ const wchar_t* signature; +}; + +STDAPI XUserGetTokenAndSignatureUtf16Async( + _In_ XUserHandle user, + _In_ XUserGetTokenAndSignatureOptions options, + _In_z_ const wchar_t* method, + _In_z_ const wchar_t* url, + _In_ size_t headerCount, + _In_reads_opt_(headerCount) const XUserGetTokenAndSignatureUtf16HttpHeader* headers, + _In_ size_t bodySize, + _In_reads_bytes_opt_(bodySize) const void* bodyBuffer, + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserGetTokenAndSignatureUtf16ResultSize( + _Inout_ XAsyncBlock* async, + _Out_ size_t* bufferSize + ) noexcept; + +STDAPI XUserGetTokenAndSignatureUtf16Result( + _Inout_ XAsyncBlock* async, + _In_ size_t bufferSize, + _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, + _Outptr_ XUserGetTokenAndSignatureUtf16Data** ptrToBuffer, + _Out_opt_ size_t* bufferUsed + ) noexcept; + +// ResolveUserIssue + +STDAPI XUserResolveIssueWithUiAsync( + _In_ XUserHandle user, + _In_opt_z_ const char* url, + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserResolveIssueWithUiResult( + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserResolveIssueWithUiUtf16Async( + _In_ XUserHandle user, + _In_opt_z_ const wchar_t* url, + _Inout_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserResolveIssueWithUiUtf16Result( + _Inout_ XAsyncBlock* async + ) noexcept; + +// UserEvent + +enum class XUserChangeEvent: uint32_t +{ + SignedInAgain = 0, + SigningOut = 1, + SignedOut = 2, + Gamertag = 3, + GamerPicture = 4, + Privileges = 5, +}; + +typedef void CALLBACK XUserChangeEventCallback( + _In_opt_ void* context, + _In_ XUserLocalId userLocalId, + _In_ XUserChangeEvent event + ); + +STDAPI XUserRegisterForChangeEvent( + _In_opt_ XTaskQueueHandle queue, + _In_opt_ void* context, + _In_ XUserChangeEventCallback* callback, + _Out_ XTaskQueueRegistrationToken* token + ) noexcept; + +STDAPI_(bool) XUserUnregisterForChangeEvent( + _In_ XTaskQueueRegistrationToken token, + _In_ bool wait + ) noexcept; + +// UserSignOutDeferral + +typedef struct XUserSignOutDeferral* XUserSignOutDeferralHandle; + +STDAPI XUserGetSignOutDeferral( + _Out_ XUserSignOutDeferralHandle* deferral + ) noexcept; + +STDAPI_(void) XUserCloseSignOutDeferralHandle( + _In_ XUserSignOutDeferralHandle deferral + ) noexcept; + +// UserDeviceAssociation + +struct XUserDeviceAssociationChange +{ + APP_LOCAL_DEVICE_ID deviceId; + XUserLocalId oldUser; + XUserLocalId newUser; +}; + +typedef void CALLBACK XUserDeviceAssociationChangedCallback( + _In_opt_ void* context, + _In_ const XUserDeviceAssociationChange* change + ); + +// Will replay all the current associations upon addition +STDAPI XUserRegisterForDeviceAssociationChanged( + _In_opt_ XTaskQueueHandle queue, + _In_opt_ void* context, + _In_ XUserDeviceAssociationChangedCallback* callback, + _Out_ XTaskQueueRegistrationToken* token + ) noexcept; + +STDAPI_(bool) XUserUnregisterForDeviceAssociationChanged( + XTaskQueueRegistrationToken token, + bool wait + ) noexcept; + +STDAPI XUserFindControllerForUserWithUiAsync( + _In_ XUserHandle user, + _In_ XAsyncBlock* async + ) noexcept; + +STDAPI XUserFindControllerForUserWithUiResult( + _Inout_ XAsyncBlock* async, + _Out_ APP_LOCAL_DEVICE_ID* deviceId + ) noexcept; + +// UserAudioAssociation + +enum class XUserDefaultAudioEndpointKind : uint32_t +{ + CommunicationRender = 0, + CommunicationCapture = 1 +}; + +const size_t XUserAudioEndpointMaxUtf16Count = 56; + +STDAPI XUserGetDefaultAudioEndpointUtf16( + XUserLocalId user, + XUserDefaultAudioEndpointKind defaultAudioEndpointKind, + size_t endpointIdUtf16Count, + _Out_writes_to_(endpointIdUtf16Count, *endpointIdUtf16Used) wchar_t* endpointIdUtf16, + _Out_opt_ size_t* endpointIdUtf16Used + ) noexcept; + +typedef void CALLBACK XUserDefaultAudioEndpointUtf16ChangedCallback( + _In_opt_ void* context, + XUserLocalId user, + XUserDefaultAudioEndpointKind defaultAudioEndpointKind, + _In_opt_z_ const wchar_t* endpointIdUtf16 + ); + +STDAPI XUserRegisterForDefaultAudioEndpointUtf16Changed( + _In_opt_ XTaskQueueHandle queue, + _In_opt_ void* context, + _In_ XUserDefaultAudioEndpointUtf16ChangedCallback* callback, + _Out_ XTaskQueueRegistrationToken* token + ) noexcept; + +STDAPI_(bool) XUserUnregisterForDefaultAudioEndpointUtf16Changed( + XTaskQueueRegistrationToken token, + bool wait + ) noexcept; + +// MsaToken + +enum class XUserGetMsaTokenSilentlyOptions : uint32_t +{ + None = 0x00, +}; + +STDAPI_(bool) XUserIsStoreUser( + _In_ XUserHandle user + ) noexcept; + +// Platform implementation api and callbacks + +typedef struct XUserPlatformOperationToken* XUserPlatformOperation; + +enum class XUserPlatformOperationResult +{ + Success = 0, + Failure = 1, + Canceled = 2, +}; + +enum class XUserPlatformSpopOperationResult +{ + SignInHere = 0, + SwitchAccount = 1, + Failure = 2, + Canceled = 3, +}; + +typedef void (XUserPlatformRemoteConnectShowPromptEventHandler)( + _In_opt_ void* context, + _In_ uint32_t userIdentifier, + _In_ XUserPlatformOperation operation, + _In_z_ char const* url, + _In_z_ char const* code, + _In_ size_t qrCodeSize, + _In_reads_bytes_(dataSize) void const* qrCode + ); + +typedef void (XUserPlatformRemoteConnectClosePromptEventHandler)( + _In_opt_ void* context, + _In_ uint32_t userIdentifier, + _In_ XUserPlatformOperation operation + ); + +typedef struct XUserPlatformRemoteConnectEventHandlers +{ + XUserPlatformRemoteConnectShowPromptEventHandler* show; + XUserPlatformRemoteConnectClosePromptEventHandler* close; + void* context; +} XUserPlatformRemoteConnectEventHandlers; + +STDAPI XUserPlatformRemoteConnectSetEventHandlers( + _In_opt_ XTaskQueueHandle queue, + _In_ XUserPlatformRemoteConnectEventHandlers* handlers + ) noexcept; + +STDAPI XUserPlatformRemoteConnectCancelPrompt( + _In_ XUserPlatformOperation operation + ) noexcept; + +typedef void (XUserPlatformSpopPromptEventHandler)( + _In_opt_ void* context, + _In_ uint32_t userIdentifier, + _In_ XUserPlatformOperation operation, + _In_z_ char const* modernGamertag, + _In_opt_z_ char const* modernGamertagSuffix +); + +STDAPI XUserPlatformSpopPromptSetEventHandlers( + _In_opt_ XTaskQueueHandle queue, + _In_ XUserPlatformSpopPromptEventHandler* handler, + _In_opt_ void* context +) noexcept; + +STDAPI XUserPlatformSpopPromptComplete( + _In_ XUserPlatformOperation operation, + _In_ XUserPlatformSpopOperationResult result +) noexcept; + +// TODO +typedef void CALLBACK XUserFindControllerForUserUiCallback( + _In_opt_ void* context, + _In_ XUserHandle user + ); + +} // extern "C" diff --git a/docs/gdkx/aco_compute_pso.h b/docs/gdkx/aco_compute_pso.h new file mode 100644 index 0000000..938275b --- /dev/null +++ b/docs/gdkx/aco_compute_pso.h @@ -0,0 +1,265 @@ +/* + * Copyright © 2025 Microsoft Corporation + * + * SPDX-License-Identifier: MIT + */ + +#ifndef ACO_COMPUTE_PSO_H +#define ACO_COMPUTE_PSO_H + +#include +#include + +#ifndef ACO_DXBC_VOCAB_DEFINED +#define ACO_DXBC_VOCAB_DEFINED + +#define ACO_DXBC_FOURCC_DXBC 0x43425844u +#define ACO_DXBC_FOURCC_DXIL 0x4C495844u +#define ACO_DXBC_FOURCC_HASH 0x48534148u +#define ACO_DXBC_FOURCC_ILDB 0x42444C49u +#define ACO_DXBC_FOURCC_ILDN 0x4E444C49u +#define ACO_DXBC_FOURCC_RTS0 0x30535452u +#define ACO_DXBC_FOURCC_PSV0 0x30565350u +#define ACO_DXBC_FOURCC_STAT 0x54415453u + +#define ACO_DXBC_FOURCC_ACGS 0x53474341u +#define ACO_DXBC_FOURCC_ACCC 0x43434341u + +typedef struct aco_dxbc_part_info { + uint32_t fourcc; + uint32_t offset; + uint32_t size; +} aco_dxbc_part_info; + +#endif + +#ifndef ACO_DXBC_HEADER_SIZE +#define ACO_DXBC_HEADER_SIZE 32u +#endif + +#define ACO_XPSF_MAGIC 0x58505346u +#define ACO_XPSF_HEADER_SIZE 16u +#define ACO_XPSF_ENTRY_SIZE 16u + +#define ACO_XPSF_PACKET 0u +#define ACO_XPSF_METADATA 1u +#define ACO_XPSF_CS_ISA 6u +#define ACO_XPSF_CS_META 7u + +#define ACO_CSO_CS_ISA_ALIGN 256u + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct aco_blob_span { + const void *data; + uint32_t size; +} aco_blob_span; + +typedef struct aco_compute_pso_view { + aco_blob_span packet; + aco_blob_span pso_metadata; + aco_blob_span cs_isa; + aco_blob_span cs_meta; +} aco_compute_pso_view; + +typedef enum aco_cso_result { + ACO_CSO_OK = 0, + ACO_CSO_E_NULL, + ACO_CSO_E_NOT_CONTAINER, + ACO_CSO_E_NO_ACCC, + ACO_CSO_E_BAD_XPSF, + ACO_CSO_E_MISSING_ENTRY +} aco_cso_result; + +static inline uint32_t +aco__cso_rd_u32(const uint8_t *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | + ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} + +static inline void +aco__cso_clear_view(aco_compute_pso_view *v) +{ + if (!v) + return; + v->packet.data = NULL; v->packet.size = 0; + v->pso_metadata.data = NULL; v->pso_metadata.size = 0; + v->cs_isa.data = NULL; v->cs_isa.size = 0; + v->cs_meta.data = NULL; v->cs_meta.size = 0; +} + +static inline aco_cso_result +aco_cso_find_dxbc_part(const void *blob, uint32_t size, uint32_t fourcc, + const void **out_body, uint32_t *out_body_size) +{ + const uint8_t *p; + uint32_t total, part_count, i; + + if (out_body) + *out_body = NULL; + if (out_body_size) + *out_body_size = 0; + + if (!blob || size < ACO_DXBC_HEADER_SIZE) + return ACO_CSO_E_NOT_CONTAINER; + + p = (const uint8_t *)blob; + if (aco__cso_rd_u32(p) != ACO_DXBC_FOURCC_DXBC) + return ACO_CSO_E_NOT_CONTAINER; + + total = aco__cso_rd_u32(p + 24); + part_count = aco__cso_rd_u32(p + 28); + + if (total > size) + total = size; + + if ((uint64_t)ACO_DXBC_HEADER_SIZE + (uint64_t)part_count * 4u > (uint64_t)total) + return ACO_CSO_E_NOT_CONTAINER; + + for (i = 0; i < part_count; i++) { + uint32_t off = aco__cso_rd_u32(p + ACO_DXBC_HEADER_SIZE + i * 4u); + uint32_t pf, ps; + if ((uint64_t)off + 8u > (uint64_t)total) + continue; + pf = aco__cso_rd_u32(p + off); + ps = aco__cso_rd_u32(p + off + 4u); + if ((uint64_t)off + 8u + (uint64_t)ps > (uint64_t)total) + continue; + if (pf != fourcc) + continue; + if (out_body) + *out_body = p + off + 8u; + if (out_body_size) + *out_body_size = ps; + return ACO_CSO_OK; + } + return ACO_CSO_E_NO_ACCC; +} + +static inline aco_cso_result +aco_compute_pso_view_from_xpsf(const void *xpsf, uint32_t size, + aco_compute_pso_view *out) +{ + const uint8_t *p; + uint32_t num_entries, total, i; + + aco__cso_clear_view(out); + if (!out) + return ACO_CSO_E_NULL; + if (!xpsf || size < ACO_XPSF_HEADER_SIZE) + return ACO_CSO_E_NULL; + + p = (const uint8_t *)xpsf; + if (aco__cso_rd_u32(p) != ACO_XPSF_MAGIC) + return ACO_CSO_E_NOT_CONTAINER; + + num_entries = aco__cso_rd_u32(p + 8); + total = aco__cso_rd_u32(p + 12); + if (total > size) + total = size; + + { + uint64_t payload_base = (uint64_t)ACO_XPSF_HEADER_SIZE + + (uint64_t)num_entries * ACO_XPSF_ENTRY_SIZE; + if (payload_base > (uint64_t)total) + return ACO_CSO_E_BAD_XPSF; + + for (i = 0; i < num_entries; i++) { + const uint8_t *e = p + ACO_XPSF_HEADER_SIZE + (uint64_t)i * ACO_XPSF_ENTRY_SIZE; + uint32_t type = aco__cso_rd_u32(e); + uint32_t off = aco__cso_rd_u32(e + 4); + uint32_t esz = aco__cso_rd_u32(e + 8); + aco_blob_span span; + + if ((uint64_t)off < payload_base || + (uint64_t)off + (uint64_t)esz > (uint64_t)total) + continue; + + span.data = p + off; + span.size = esz; + + switch (type) { + case ACO_XPSF_PACKET: out->packet = span; break; + case ACO_XPSF_METADATA: out->pso_metadata = span; break; + case ACO_XPSF_CS_ISA: out->cs_isa = span; break; + case ACO_XPSF_CS_META: out->cs_meta = span; break; + default: break; + } + } + } + + if (!out->packet.data || out->packet.size == 0 || + !out->cs_isa.data || out->cs_isa.size == 0) + return ACO_CSO_E_MISSING_ENTRY; + return ACO_CSO_OK; +} + +static inline aco_cso_result +aco_compute_pso_view_from_cso(const void *blob, uint32_t size, + aco_compute_pso_view *out) +{ + uint32_t magic; + + aco__cso_clear_view(out); + if (!out) + return ACO_CSO_E_NULL; + if (!blob || size < ACO_XPSF_HEADER_SIZE) + return ACO_CSO_E_NULL; + + magic = aco__cso_rd_u32((const uint8_t *)blob); + + if (magic == ACO_XPSF_MAGIC) + return aco_compute_pso_view_from_xpsf(blob, size, out); + + if (magic == ACO_DXBC_FOURCC_DXBC) { + const void *xpsf = NULL; + uint32_t xpsf_size = 0; + aco_cso_result r = + aco_cso_find_dxbc_part(blob, size, ACO_DXBC_FOURCC_ACCC, + &xpsf, &xpsf_size); + if (r != ACO_CSO_OK) + return r; + return aco_compute_pso_view_from_xpsf(xpsf, xpsf_size, out); + } + + return ACO_CSO_E_NOT_CONTAINER; +} + +static inline const char * +aco_cso_result_str(aco_cso_result r) +{ + switch (r) { + case ACO_CSO_OK: return "ok"; + case ACO_CSO_E_NULL: return "null or undersized input"; + case ACO_CSO_E_NOT_CONTAINER: return "not a DXBC container or XPSF blob"; + case ACO_CSO_E_NO_ACCC: return "no 'ACCC' compute cook part in container"; + case ACO_CSO_E_BAD_XPSF: return "malformed XPSF (out-of-bounds directory)"; + case ACO_CSO_E_MISSING_ENTRY: return "XPSF missing a required compute entry"; + default: return "unknown"; + } +} + +#ifdef ACO_CSO_WITH_D3D12 + +static inline void +aco_cso_fill_deserialize_compute(const aco_compute_pso_view *v, + D3D12XBOX_DESERIALIZE_COMPUTE_PIPELINE_STATE *ds) +{ + ds->pPacket = (void *)v->packet.data; + ds->PacketSize = v->packet.size; + ds->pMetaData = (void *)v->pso_metadata.data; + ds->MetaDataSize = v->pso_metadata.size; + ds->CS.pMetaData = (void *)v->cs_meta.data; + ds->CS.MetaDataSize = v->cs_meta.size; + ds->CS.GpuInstructionsSize = v->cs_isa.size; +} +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/docs/gdkx/aco_xbox.h b/docs/gdkx/aco_xbox.h new file mode 100644 index 0000000..9c50f0f --- /dev/null +++ b/docs/gdkx/aco_xbox.h @@ -0,0 +1,171 @@ +/* + * Copyright © 2025 Microsoft Corporation + * + * SPDX-License-Identifier: MIT + */ + +#ifndef ACO_XBOX_H +#define ACO_XBOX_H + +#ifdef _WIN32 +# ifdef ACO_XBOX_DLL_BUILDING +# define ACO_DLL_API __declspec(dllexport) +# else +# define ACO_DLL_API __declspec(dllimport) +# endif +#else +# define ACO_DLL_API __attribute__((visibility("default"))) +#endif + +#ifndef _D3D12_XS_H_INCLUDED_ +struct D3D12_ROOT_SIGNATURE_DESC1; +struct D3D12XBOX_SERIALIZE_GRAPHICS_PIPELINE_STATE; +struct D3D12XBOX_SERIALIZE_COMPUTE_PIPELINE_STATE; +#endif + +#ifndef __cplusplus +typedef struct D3D12_ROOT_SIGNATURE_DESC1 D3D12_ROOT_SIGNATURE_DESC1; +typedef struct D3D12XBOX_SERIALIZE_GRAPHICS_PIPELINE_STATE D3D12XBOX_SERIALIZE_GRAPHICS_PIPELINE_STATE; +typedef struct D3D12XBOX_SERIALIZE_COMPUTE_PIPELINE_STATE D3D12XBOX_SERIALIZE_COMPUTE_PIPELINE_STATE; +#endif + +#include +#include + +#ifndef ACO_DXBC_VOCAB_DEFINED +#define ACO_DXBC_VOCAB_DEFINED + +#define ACO_DXBC_FOURCC_DXBC 0x43425844u +#define ACO_DXBC_FOURCC_DXIL 0x4C495844u +#define ACO_DXBC_FOURCC_HASH 0x48534148u +#define ACO_DXBC_FOURCC_ILDB 0x42444C49u +#define ACO_DXBC_FOURCC_ILDN 0x4E444C49u +#define ACO_DXBC_FOURCC_RTS0 0x30535452u +#define ACO_DXBC_FOURCC_PSV0 0x30565350u +#define ACO_DXBC_FOURCC_STAT 0x54415453u +#define ACO_DXBC_FOURCC_ACGS 0x53474341u +#define ACO_DXBC_FOURCC_ACCC 0x43434341u + +typedef struct aco_dxbc_part_info { + uint32_t fourcc; + uint32_t offset; + uint32_t size; +} aco_dxbc_part_info; + +#endif /* ACO_DXBC_VOCAB_DEFINED */ + +#ifdef __cplusplus +extern "C" { +#endif + +ACO_DLL_API long AcoOfflineInit(void); +ACO_DLL_API void AcoOfflineShutdown(void); +ACO_DLL_API void AcoOfflineFree(void *ptr); + +#define ACO_ALLOC_ATTR_ALIGN_MASK 0xFFFFull +#define ACO_ALLOC_ATTR_ALIGNMENT(attr) ((size_t)((attr) & ACO_ALLOC_ATTR_ALIGN_MASK)) +#define ACO_ALLOC_ATTR_MAKE_ALIGN(a) ((uint64_t)(a) & ACO_ALLOC_ATTR_ALIGN_MASK) + +typedef void *(*PFN_AcoOfflineAlloc)(size_t size, uint64_t attributes); +typedef void (*PFN_AcoOfflineFree )(void *ptr, uint64_t attributes); + +ACO_DLL_API void AcoOfflineSetAllocationHooks(PFN_AcoOfflineAlloc pfnAlloc, + PFN_AcoOfflineFree pfnFree); + +typedef struct aco_compile_options { + uint32_t size; + uint32_t target_min_waves; + uint32_t use_re_z; + uint32_t force_zorder; + uint32_t enable_wgp_mode; + uint32_t break_on_shader_start; + uint32_t skip_dxbc_hash_check; + uint32_t num_static_sampler_flags; + const uint32_t *static_sampler_flags; + uint32_t line_rasterization_mode; + uint32_t reserved[19]; +} aco_compile_options; + +#define ACO_XBOX_SAMPLER_FLAG_UINT_BORDER_COLOR 0x1u +#define ACO_XBOX_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES 0x2u + +#define ACO_XBOX_LINE_RASTER_LEGACY 0u +#define ACO_XBOX_LINE_RASTER_ALIASED 1u +#define ACO_XBOX_LINE_RASTER_ALPHA_ANTIALIASED 2u +#define ACO_XBOX_LINE_RASTER_QUADRILATERAL_WIDE 3u +#define ACO_XBOX_LINE_RASTER_QUADRILATERAL_NARROW 4u + +#define ACO_COMPILE_OPTIONS_DEFAULT { sizeof(aco_compile_options), 0, 0, 0, 0, 0, 0, 0, NULL, 0, {0} } + +ACO_DLL_API long AcoOfflineSerializePipelineStateX( + const void *pStreamDesc, + const D3D12_ROOT_SIGNATURE_DESC1 *pRootSigDesc, + D3D12XBOX_SERIALIZE_GRAPHICS_PIPELINE_STATE *pGraphicsOut, + D3D12XBOX_SERIALIZE_COMPUTE_PIPELINE_STATE *pComputeOut); + +ACO_DLL_API long AcoOfflineSerializePipelineStateXEx( + const void *pStreamDesc, + const D3D12_ROOT_SIGNATURE_DESC1 *pRootSigDesc, + D3D12XBOX_SERIALIZE_GRAPHICS_PIPELINE_STATE *pGraphicsOut, + D3D12XBOX_SERIALIZE_COMPUTE_PIPELINE_STATE *pComputeOut, + const char *pszName, + const aco_compile_options *pCompileOpts); + +typedef enum aco_cook_stage { + ACO_COOK_STAGE_VS = 0, + ACO_COOK_STAGE_PS = 1, + ACO_COOK_STAGE_GS = 2, + ACO_COOK_STAGE_HS = 3, + ACO_COOK_STAGE_DS = 4, + ACO_COOK_STAGE_MS = 5, +} aco_cook_stage; + +#define ACO_COOK_FLAG_COMPRESS_NIR 0x00000001u + +ACO_DLL_API long AcoOfflineCookGraphicsStage( + uint32_t stage, + const void *pDxilBytes, uint32_t cbDxil, + const D3D12_ROOT_SIGNATURE_DESC1 *pRootSigDesc, + const aco_compile_options *pCompileOpts, + void **ppCookedBlob, uint32_t *pCookedSize); + +ACO_DLL_API long AcoOfflineCookGraphicsStageEx( + uint32_t stage, + const void *pDxilBytes, uint32_t cbDxil, + const D3D12_ROOT_SIGNATURE_DESC1 *pRootSigDesc, + const aco_compile_options *pCompileOpts, + uint32_t cookFlags, + void **ppCookedBlob, uint32_t *pCookedSize); + +#define ACO_FOURCC_ACGS 0x53474341u +#define ACO_FOURCC_ACCC 0x43434341u + +ACO_DLL_API long AcoOfflineInjectCookPartIntoDxil( + const void *pDxilContainer, uint32_t cbDxilContainer, + uint32_t fourcc, + const void *pPayload, uint32_t cbPayload, + void **ppOutContainer, uint32_t *pOutContainerSize); + +ACO_DLL_API long AcoOfflineFindCookPartInDxil( + const void *pDxilContainer, uint32_t cbDxilContainer, + uint32_t fourcc, + const void **ppPayload, uint32_t *pPayloadSize); + +ACO_DLL_API long AcoOfflineEnumPartsInDxil( + const void *pDxilContainer, uint32_t cbDxilContainer, + aco_dxbc_part_info *pParts, uint32_t maxParts, uint32_t *pCount); + +ACO_DLL_API long AcoOfflineStripPartsFromDxil( + const void *pDxilContainer, uint32_t cbDxilContainer, + const uint32_t *pFourccs, uint32_t numFourccs, int keepOnly, + void **ppOutContainer, uint32_t *pOutContainerSize); + +ACO_DLL_API long AcoOfflineStripDxilBitcodeFromDxil( + const void *pDxilContainer, uint32_t cbDxilContainer, + void **ppOutContainer, uint32_t *pOutContainerSize); + +#ifdef __cplusplus +} +#endif + +#endif /* ACO_XBOX_H */ diff --git a/docs/gdkx/d3d12_xs.h b/docs/gdkx/d3d12_xs.h new file mode 100644 index 0000000..d5b89a9 --- /dev/null +++ b/docs/gdkx/d3d12_xs.h @@ -0,0 +1,31214 @@ +//------------------------------------------------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// Xbox Series X|S Direct3D 12.XS constants, structures, and interfaces. +// +// Offline PC Tool Build +// +// Compile Time Flags +// ------------------ +// +// The following is an optional #define that affects codegen for calls to D3D. #define it +// before including d3d12_xs.h. +// +// #define D3DCOMPILE_NO_DEBUG 1 +// +// Setting D3DCOMPILE_NO_DEBUG improves the performance of CreateConstantBufferView, +// CopyDescriptorsSimple, and related APIs by removing a run-time 'if'. When this +// is enabled, parameter validation will no longer be applied to the affected APIs, +// even when used with D3D12_PROCESS_DEBUG_FLAG_DEBUG_LAYER_ENABLED. +// +// This mode is recommended only for your retail builds. + +#ifndef __d3d12_xs_h__ +#define __d3d12_xs_h__ + +#pragma once + +#define __XBOX_D3D12_X__ + +#pragma warning( push ) + +// Disable unreferenced parameter, nameless struct/union, zero-sized array, structure padded +// due to __declspec(align()), conditional expression is constant, unreachable code +// enum not handled in case, implicit structure padding, 'symbol' is not defined as a +// preprocessor macro, replacing with '0' for 'directives', sign mismatch + +#pragma warning( disable : 4100 4201 4200 4324 4127 4702 4061 4820 4668 4365 ) + +#ifndef COM_NO_WINDOWS_H +#include "windows.h" +#include "ole2.h" +#endif /*COM_NO_WINDOWS_H*/ + +#include "rpc.h" +#include "rpcndr.h" +#include "oaidl.h" +#include "emmintrin.h" + +#ifdef __dxgit_h__ +#error D3D12_X cannot be mixed with stock DXGI +#endif +#ifdef __dxgit1_2_h__ +#error D3D12_X cannot be mixed with stock DXGI1_2 +#endif +#ifdef __dxgicommon_h__ +#error D3D12_X cannot be mixed with stock DXGICommon +#endif +#ifdef __dxgiformat_h__ +#error D3D12_X cannot be mixed with stock DXGIFormat +#endif +#ifdef _D3D9_H_ +#error D3D12_X cannot be mixed with stock D3D9 +#endif +#ifdef __d3d10_h__ +#error D3D12_X cannot be mixed with stock D3D10 +#endif +#ifdef __d3d11_h__ +#error D3D12_X cannot be mixed with stock D3D11 +#endif +#ifdef __d3d11_1_h__ +#error D3D12_X cannot be mixed with stock D3D11_1 +#endif +#ifdef __d3d11_x_h__ +#error D3D12_X cannot be mixed with legacy D3D11_X +#endif + +// The DXGI headers cause problems when being included via other headers such as wincodec.h. +// Prevent their inclusion which will cause the xbox definitions to be used. +#define __dxgicommon_h__ +#define __dxgitype_h__ +#define __dxgiformat_h__ +#define DCOMMON_H_INCLUDED + +#if !defined(__NO_XBOX_GRAPHICS_MISMATCH__) +// D3D12_SDK_VERSION_MINOR corresponds to this version check +#pragma detect_mismatch("Xbox Graphics 12 Version", "D3D12_XS Monolithic 2_4") +#endif + +#ifndef __cplusplus +#error Usage of D3D12_X requires C++ +#endif + +#define D3DINLINE __forceinline + +#define D3DAPI STDMETHODCALLTYPE +#define D3DCONST extern __declspec(selectany) +#define D3DDECL_UUID(Uuid) __declspec(uuid(#Uuid)) +#define D3DOFFSETOF(s,_) (UINT)( (ptrdiff_t)&(((s *)0)->_) ) + +#ifdef INITGUID +#define DEFINE_D3DGUID DEFINE_GUID +#else +#define DEFINE_D3DGUID(Name, Guid0, Guid1, Guid2, Guid3, Guid4, \ + Guid5, Guid6, Guid7, Guid8, Guid9, Guid10) \ + EXTERN_C const GUID __declspec(dllimport) FAR Name +#endif + +#define D3DINTERFACE(Name, Guid0, Guid1, Guid2, Guid3, Guid4, \ + Guid5, Guid6, Guid7, Guid8, Guid9, Guid10) \ + \ + DEFINE_D3DGUID(IID_##Name, 0x##Guid0, 0x##Guid1, 0x##Guid2, 0x##Guid3, 0x##Guid4, \ + 0x##Guid5, 0x##Guid6, 0x##Guid7, 0x##Guid8, 0x##Guid9, 0x##Guid10); \ + \ + struct D3DDECL_UUID(Guid0-Guid1-Guid2-Guid3##Guid4-Guid5##Guid6##Guid7##Guid8##Guid9##Guid10) Name + +extern "C" +{ + +// +// IGraphicsUnknown +// + +struct IGraphicsUnknown; + +struct GraphicsUnknown_Function_Table +{ + HRESULT (D3DAPI* QueryInterface)( + _Inout_ IGraphicsUnknown* pUnknown, + _In_ REFIID riid, + _Out_ void** ppObject); + + ULONG (D3DAPI* AddRef)( + _Inout_ IGraphicsUnknown* pUnknown); + + ULONG (D3DAPI* Release)( + _Inout_ IGraphicsUnknown* pUnknown); +}; + +#define IID_GRAPHICS_PPV_ARGS(ppType) __uuidof(**(ppType)), (static_cast(*(ppType)),reinterpret_cast(ppType)) + + +} + +D3DINTERFACE(IGraphicsUnknown, aceeea63,e0a9,4a1c,bb,ec,71,b2,f4,85,f7,58) +{ +public: + + GraphicsUnknown_Function_Table* m_pFunction; + +public: + + ULONG m_PrivateDataPresent : 1; + ULONG m_DisableCollectiveRefCount : 1; + ULONG m_Internal : 30; + + ULONG m_RefCount; + +public: + + D3DINLINE GraphicsUnknown_Function_Table* UnknownFunction() + { + return m_pFunction; + } + + D3DINLINE HRESULT D3DAPI QueryInterface( + _In_ REFIID riid, + _Out_ void** ppObject) + { + return UnknownFunction()->QueryInterface(this, riid, ppObject); + } + + D3DINLINE ULONG D3DAPI AddRef() + { + return UnknownFunction()->AddRef(this); + } + + D3DINLINE ULONG D3DAPI Release() + { + return UnknownFunction()->Release(this); + } +}; + + +extern "C" +{ + +// +// DXGI +// + +struct IDXGIObject; +struct IDXGIDeviceSubObject; +struct IDXGIFactory; +struct IDXGIFactory1; +struct IDXGIFactory2; +struct IDXGIAdapter; +struct IDXGIAdapter1; +struct IDXGIAdapter2; +struct IDXGIDevice; +struct IDXGIDevice1; +struct IDXGIDevice2; +struct IDXGIInfoQueue; +struct IDXGIInfoQueue1; +struct IDXGIOutput; +struct IDXGIFenceInternal; + +#if !defined(DXGI_FORMAT_DEFINED) +#define DXGI_FORMAT_DEFINED 1 + +typedef enum DXGI_FORMAT +{ + DXGI_FORMAT_UNKNOWN = 0, + DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, + DXGI_FORMAT_R32G32B32A32_FLOAT = 2, + DXGI_FORMAT_R32G32B32A32_UINT = 3, + DXGI_FORMAT_R32G32B32A32_SINT = 4, + DXGI_FORMAT_R32G32B32_TYPELESS = 5, + DXGI_FORMAT_R32G32B32_FLOAT = 6, + DXGI_FORMAT_R32G32B32_UINT = 7, + DXGI_FORMAT_R32G32B32_SINT = 8, + DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, + DXGI_FORMAT_R16G16B16A16_FLOAT = 10, + DXGI_FORMAT_R16G16B16A16_UNORM = 11, + DXGI_FORMAT_R16G16B16A16_UINT = 12, + DXGI_FORMAT_R16G16B16A16_SNORM = 13, + DXGI_FORMAT_R16G16B16A16_SINT = 14, + DXGI_FORMAT_R32G32_TYPELESS = 15, + DXGI_FORMAT_R32G32_FLOAT = 16, + DXGI_FORMAT_R32G32_UINT = 17, + DXGI_FORMAT_R32G32_SINT = 18, + DXGI_FORMAT_R32G8X24_TYPELESS = 19, + DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, + DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, + DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, + DXGI_FORMAT_R10G10B10A2_UNORM = 24, + DXGI_FORMAT_R10G10B10A2_UINT = 25, + DXGI_FORMAT_R11G11B10_FLOAT = 26, + DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, + DXGI_FORMAT_R8G8B8A8_UNORM = 28, + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, + DXGI_FORMAT_R8G8B8A8_UINT = 30, + DXGI_FORMAT_R8G8B8A8_SNORM = 31, + DXGI_FORMAT_R8G8B8A8_SINT = 32, + DXGI_FORMAT_R16G16_TYPELESS = 33, + DXGI_FORMAT_R16G16_FLOAT = 34, + DXGI_FORMAT_R16G16_UNORM = 35, + DXGI_FORMAT_R16G16_UINT = 36, + DXGI_FORMAT_R16G16_SNORM = 37, + DXGI_FORMAT_R16G16_SINT = 38, + DXGI_FORMAT_R32_TYPELESS = 39, + DXGI_FORMAT_D32_FLOAT = 40, + DXGI_FORMAT_R32_FLOAT = 41, + DXGI_FORMAT_R32_UINT = 42, + DXGI_FORMAT_R32_SINT = 43, + DXGI_FORMAT_R24G8_TYPELESS = 44, + DXGI_FORMAT_D24_UNORM_S8_UINT = 45, + DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, + DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, + DXGI_FORMAT_R8G8_TYPELESS = 48, + DXGI_FORMAT_R8G8_UNORM = 49, + DXGI_FORMAT_R8G8_UINT = 50, + DXGI_FORMAT_R8G8_SNORM = 51, + DXGI_FORMAT_R8G8_SINT = 52, + DXGI_FORMAT_R16_TYPELESS = 53, + DXGI_FORMAT_R16_FLOAT = 54, + DXGI_FORMAT_D16_UNORM = 55, + DXGI_FORMAT_R16_UNORM = 56, + DXGI_FORMAT_R16_UINT = 57, + DXGI_FORMAT_R16_SNORM = 58, + DXGI_FORMAT_R16_SINT = 59, + DXGI_FORMAT_R8_TYPELESS = 60, + DXGI_FORMAT_R8_UNORM = 61, + DXGI_FORMAT_R8_UINT = 62, + DXGI_FORMAT_R8_SNORM = 63, + DXGI_FORMAT_R8_SINT = 64, + DXGI_FORMAT_A8_UNORM = 65, + DXGI_FORMAT_R1_UNORM = 66, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, + DXGI_FORMAT_R8G8_B8G8_UNORM = 68, + DXGI_FORMAT_G8R8_G8B8_UNORM = 69, + DXGI_FORMAT_BC1_TYPELESS = 70, + DXGI_FORMAT_BC1_UNORM = 71, + DXGI_FORMAT_BC1_UNORM_SRGB = 72, + DXGI_FORMAT_BC2_TYPELESS = 73, + DXGI_FORMAT_BC2_UNORM = 74, + DXGI_FORMAT_BC2_UNORM_SRGB = 75, + DXGI_FORMAT_BC3_TYPELESS = 76, + DXGI_FORMAT_BC3_UNORM = 77, + DXGI_FORMAT_BC3_UNORM_SRGB = 78, + DXGI_FORMAT_BC4_TYPELESS = 79, + DXGI_FORMAT_BC4_UNORM = 80, + DXGI_FORMAT_BC4_SNORM = 81, + DXGI_FORMAT_BC5_TYPELESS = 82, + DXGI_FORMAT_BC5_UNORM = 83, + DXGI_FORMAT_BC5_SNORM = 84, + DXGI_FORMAT_B5G6R5_UNORM = 85, + DXGI_FORMAT_B5G5R5A1_UNORM = 86, + DXGI_FORMAT_B8G8R8A8_UNORM = 87, + DXGI_FORMAT_B8G8R8X8_UNORM = 88, + DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, + DXGI_FORMAT_B8G8R8A8_TYPELESS = 90, + DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91, + DXGI_FORMAT_B8G8R8X8_TYPELESS = 92, + DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93, + DXGI_FORMAT_BC6H_TYPELESS = 94, + DXGI_FORMAT_BC6H_UF16 = 95, + DXGI_FORMAT_BC6H_SF16 = 96, + DXGI_FORMAT_BC7_TYPELESS = 97, + DXGI_FORMAT_BC7_UNORM = 98, + DXGI_FORMAT_BC7_UNORM_SRGB = 99, + DXGI_FORMAT_AYUV = 100, + DXGI_FORMAT_Y410 = 101, + DXGI_FORMAT_Y416 = 102, + DXGI_FORMAT_NV12 = 103, + DXGI_FORMAT_P010 = 104, + DXGI_FORMAT_P016 = 105, + DXGI_FORMAT_420_OPAQUE = 106, + DXGI_FORMAT_YUY2 = 107, + DXGI_FORMAT_Y210 = 108, + DXGI_FORMAT_Y216 = 109, + DXGI_FORMAT_NV11 = 110, + DXGI_FORMAT_AI44 = 111, + DXGI_FORMAT_IA44 = 112, + DXGI_FORMAT_P8 = 113, + DXGI_FORMAT_A8P8 = 114, + DXGI_FORMAT_B4G4R4A4_UNORM = 115, + DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT = 116, + DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT = 117, + DXGI_FORMAT_D16_UNORM_S8_UINT = 118, + DXGI_FORMAT_R16_UNORM_X8_TYPELESS = 119, + DXGI_FORMAT_X16_TYPELESS_G8_UINT = 120, + DXGI_FORMAT_P208 = 130, + DXGI_FORMAT_V208 = 131, + DXGI_FORMAT_V408 = 132, + + DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 187, + DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 188, + + DXGI_FORMAT_R10G10B10_SNORM_A2_UNORM = 189, + DXGI_FORMAT_R4G4_UNORM = 190, + DXGI_FORMAT_R24G8_UNORM = 191, + + DXGI_FORMAT_FORCE_UINT = 0xffffffff +} DXGI_FORMAT; + +#endif // DXGI_FORMAT_DEFINED + +#define _FACDXGI 0x87a +#define MAKE_DXGI_HRESULT(code) MAKE_HRESULT(1, _FACDXGI, code) +#define MAKE_DXGI_STATUS(code) MAKE_HRESULT(0, _FACDXGI, code) + +#define DXGI_CPU_ACCESS_NONE ( 0 ) +#define DXGI_CPU_ACCESS_DYNAMIC ( 1 ) +#define DXGI_CPU_ACCESS_READ_WRITE ( 2 ) +#define DXGI_CPU_ACCESS_SCRATCH ( 3 ) +#define DXGI_CPU_ACCESS_FIELD 15 +#define DXGI_USAGE_SHADER_INPUT ( 1L << (0 + 4) ) +#define DXGI_USAGE_RENDER_TARGET_OUTPUT ( 1L << (1 + 4) ) +#define DXGI_USAGE_BACK_BUFFER ( 1L << (2 + 4) ) +#define DXGI_USAGE_SHARED ( 1L << (3 + 4) ) +#define DXGI_USAGE_READ_ONLY ( 1L << (4 + 4) ) +#define DXGI_USAGE_DISCARD_ON_PRESENT ( 1L << (5 + 4) ) +#define DXGI_USAGE_UNORDERED_ACCESS ( 1L << (6 + 4) ) +typedef UINT DXGI_USAGE; + +typedef struct DXGI_RGB +{ + float Red; + float Green; + float Blue; +} DXGI_RGB; + +#ifndef D3DCOLORVALUE_DEFINED +typedef struct _D3DCOLORVALUE { + float r; + float g; + float b; + float a; +} D3DCOLORVALUE; + +#define D3DCOLORVALUE_DEFINED +#endif + +typedef D3DCOLORVALUE DXGI_RGBA; + +typedef struct DXGI_GAMMA_CONTROL +{ + DXGI_RGB Scale; + DXGI_RGB Offset; + DXGI_RGB GammaCurve[1025]; +} DXGI_GAMMA_CONTROL; + +typedef struct DXGI_GAMMA_CONTROL_CAPABILITIES +{ + BOOL ScaleAndOffsetSupported; + float MaxConvertedValue; + float MinConvertedValue; + UINT NumGammaControlPoints; + float ControlPointPositions[1025]; +} DXGI_GAMMA_CONTROL_CAPABILITIES; + +typedef struct DXGI_RATIONAL +{ + UINT Numerator; + UINT Denominator; +} DXGI_RATIONAL; + +typedef enum DXGI_MODE_SCANLINE_ORDER +{ + DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED = 0, + DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE = 1, + DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST = 2, + DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST = 3 +} DXGI_MODE_SCANLINE_ORDER; + +typedef enum DXGI_MODE_SCALING +{ + DXGI_MODE_SCALING_UNSPECIFIED = 0, + DXGI_MODE_SCALING_CENTERED = 1, + DXGI_MODE_SCALING_STRETCHED = 2 +} DXGI_MODE_SCALING; + +typedef enum DXGI_MODE_ROTATION +{ + DXGI_MODE_ROTATION_UNSPECIFIED = 0, + DXGI_MODE_ROTATION_IDENTITY = 1, + DXGI_MODE_ROTATION_ROTATE90 = 2, + DXGI_MODE_ROTATION_ROTATE180 = 3, + DXGI_MODE_ROTATION_ROTATE270 = 4 +} DXGI_MODE_ROTATION; + +typedef struct DXGI_MODE_DESC +{ + UINT Width; + UINT Height; + DXGI_RATIONAL RefreshRate; + DXGI_FORMAT Format; + DXGI_MODE_SCANLINE_ORDER ScanlineOrdering; + DXGI_MODE_SCALING Scaling; +} DXGI_MODE_DESC; + +typedef enum DXGIXBOX_MODE_FLAGS +{ + DXGIXBOX_MODE_FLAG_NONE = 0x0, + DXGIXBOX_MODE_FLAG_VARIABLE_REFRESH_RATE = 0x1, +} DXGIXBOX_MODE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( DXGIXBOX_MODE_FLAGS ); + +typedef struct DXGIXBOX_MODE_DESC +{ + UINT Width; + UINT Height; + DXGI_RATIONAL RefreshRate; + DXGI_FORMAT Format; + DXGI_MODE_SCANLINE_ORDER ScanlineOrdering; + DXGI_MODE_SCALING Scaling; + DXGIXBOX_MODE_FLAGS Flags; +} DXGIXBOX_MODE_DESC; + +#ifndef __DXGI_SAMPLE_DESC__DEFINED__ +#define __DXGI_SAMPLE_DESC__DEFINED__ + +typedef struct DXGI_SAMPLE_DESC +{ + UINT Count; + UINT Quality; +} DXGI_SAMPLE_DESC; + +#endif // __DXGI_SAMPLE_DESC__DEFINED__ + +typedef struct DXGI_JPEG_DC_HUFFMAN_TABLE +{ + BYTE CodeCounts[12]; + BYTE CodeValues[12]; +} DXGI_JPEG_DC_HUFFMAN_TABLE; + +typedef struct DXGI_JPEG_AC_HUFFMAN_TABLE +{ + BYTE CodeCounts[16]; + BYTE CodeValues[162]; +} DXGI_JPEG_AC_HUFFMAN_TABLE; + +typedef struct DXGI_JPEG_QUANTIZATION_TABLE +{ + BYTE Elements[64]; +} DXGI_JPEG_QUANTIZATION_TABLE; + +#define DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN 0xffffffff +#define DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN 0xfffffffe + +typedef enum DXGI_COLOR_SPACE_TYPE +{ + DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709 = 0, + DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709 = 1, + DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P709 = 2, + DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P2020 = 3, + DXGI_COLOR_SPACE_RESERVED = 4, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_NONE_P709_X601 = 5, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P601 = 6, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P601 = 7, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709 = 8, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P709 = 9, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P2020 = 10, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P2020 = 11, + DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 = 12, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G2084_LEFT_P2020 = 13, + DXGI_COLOR_SPACE_RGB_STUDIO_G2084_NONE_P2020 = 14, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_TOPLEFT_P2020 = 15, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G2084_TOPLEFT_P2020 = 16, + DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P2020 = 0x10000000, // XBox extension + DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_D65P3 = 0x10000001, // XBox extension + DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_D65P3 = 0x10000002, // XBox extension + DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P709 = 0x10000003, // XBox extension + DXGI_COLOR_SPACE_CUSTOM = 0xFFFFFFFF +} DXGI_COLOR_SPACE_TYPE; + +typedef enum DXGI_RESIDENCY +{ + DXGI_RESIDENCY_FULLY_RESIDENT = 1, + DXGI_RESIDENCY_RESIDENT_IN_SHARED_MEMORY = 2, + DXGI_RESIDENCY_EVICTED_TO_DISK = 3 +} DXGI_RESIDENCY; + +typedef struct DXGI_SURFACE_DESC +{ + UINT Width; + UINT Height; + DXGI_FORMAT Format; + DXGI_SAMPLE_DESC SampleDesc; +} DXGI_SURFACE_DESC; + +typedef enum DXGI_ADAPTER_FLAG +{ + DXGI_ADAPTER_FLAG_NONE = 0, + DXGI_ADAPTER_FLAG_REMOTE = 1, + DXGI_ADAPTER_FLAG_SOFTWARE = 2, + DXGI_ADAPTER_FLAG_FORCE_DWORD = 0xffffffff +} DXGI_ADAPTER_FLAG; + +typedef enum DXGI_GRAPHICS_PREEMPTION_GRANULARITY +{ + DXGI_GRAPHICS_PREEMPTION_DMA_BUFFER_BOUNDARY = 0, + DXGI_GRAPHICS_PREEMPTION_PRIMITIVE_BOUNDARY = 1, + DXGI_GRAPHICS_PREEMPTION_TRIANGLE_BOUNDARY = 2, + DXGI_GRAPHICS_PREEMPTION_PIXEL_BOUNDARY = 3, + DXGI_GRAPHICS_PREEMPTION_INSTRUCTION_BOUNDARY = 4 +} DXGI_GRAPHICS_PREEMPTION_GRANULARITY; + +typedef enum DXGI_COMPUTE_PREEMPTION_GRANULARITY +{ + DXGI_COMPUTE_PREEMPTION_DMA_BUFFER_BOUNDARY = 0, + DXGI_COMPUTE_PREEMPTION_DISPATCH_BOUNDARY = 1, + DXGI_COMPUTE_PREEMPTION_THREAD_GROUP_BOUNDARY = 2, + DXGI_COMPUTE_PREEMPTION_THREAD_BOUNDARY = 3, + DXGI_COMPUTE_PREEMPTION_INSTRUCTION_BOUNDARY = 4 +} DXGI_COMPUTE_PREEMPTION_GRANULARITY; + +typedef struct DXGI_ADAPTER_DESC +{ + WCHAR Description[128]; + UINT VendorId; + UINT DeviceId; + UINT SubSysId; + UINT Revision; + SIZE_T DedicatedVideoMemory; + SIZE_T DedicatedSystemMemory; + SIZE_T SharedSystemMemory; + LUID AdapterLuid; +} DXGI_ADAPTER_DESC; + +typedef struct DXGI_ADAPTER_DESC1 +{ + WCHAR Description[128]; + UINT VendorId; + UINT DeviceId; + UINT SubSysId; + UINT Revision; + SIZE_T DedicatedVideoMemory; + SIZE_T DedicatedSystemMemory; + SIZE_T SharedSystemMemory; + LUID AdapterLuid; + UINT Flags; +} DXGI_ADAPTER_DESC1; + +typedef struct DXGI_ADAPTER_DESC2 +{ + WCHAR Description[128]; + UINT VendorId; + UINT DeviceId; + UINT SubSysId; + UINT Revision; + SIZE_T DedicatedVideoMemory; + SIZE_T DedicatedSystemMemory; + SIZE_T SharedSystemMemory; + LUID AdapterLuid; + UINT Flags; + DXGI_GRAPHICS_PREEMPTION_GRANULARITY GraphicsPreemptionGranularity; + DXGI_COMPUTE_PREEMPTION_GRANULARITY ComputePreemptionGranularity; +} DXGI_ADAPTER_DESC2; + +typedef struct DXGI_SHARED_RESOURCE +{ + HANDLE Handle; +} DXGI_SHARED_RESOURCE; + +#ifdef HMONITOR +#undef HMONITOR +#endif +#define HMONITOR void* + +typedef struct DXGI_OUTPUT_DESC +{ + WCHAR DeviceName[32]; + RECT DesktopCoordinates; + BOOL AttachedToDesktop; + DXGI_MODE_ROTATION Rotation; + HMONITOR Monitor; +} DXGI_OUTPUT_DESC; + +typedef enum DXGI_SCALING +{ + DXGI_SCALING_STRETCH = 0, + DXGI_SCALING_NONE = 1, +} DXGI_SCALING; + +typedef enum DXGI_ALPHA_MODE +{ + DXGI_ALPHA_MODE_UNSPECIFIED = 0, + DXGI_ALPHA_MODE_PREMULTIPLIED = 1, + DXGI_ALPHA_MODE_STRAIGHT = 2, + DXGI_ALPHA_MODE_IGNORE = 3, + DXGI_ALPHA_MODE_FORCE_DWORD = 0xffffffff +} DXGI_ALPHA_MODE; + +typedef enum _DXGI_OFFER_RESOURCE_PRIORITY +{ + DXGI_OFFER_RESOURCE_PRIORITY_LOW = 1, + DXGI_OFFER_RESOURCE_PRIORITY_NORMAL = ( DXGI_OFFER_RESOURCE_PRIORITY_LOW + 1 ) , + DXGI_OFFER_RESOURCE_PRIORITY_HIGH = ( DXGI_OFFER_RESOURCE_PRIORITY_NORMAL + 1 ) +} DXGI_OFFER_RESOURCE_PRIORITY; + +extern "C" +{ + +typedef enum D2D1_ALPHA_MODE +{ + D2D1_ALPHA_MODE_UNKNOWN = 0, + D2D1_ALPHA_MODE_PREMULTIPLIED = 1, + D2D1_ALPHA_MODE_STRAIGHT = 2, + D2D1_ALPHA_MODE_IGNORE = 3, + D2D1_ALPHA_MODE_FORCE_DWORD = 0xffffffff +} D2D1_ALPHA_MODE; + +typedef struct D2D1_PIXEL_FORMAT +{ + DXGI_FORMAT format; + D2D1_ALPHA_MODE alphaMode; +} D2D1_PIXEL_FORMAT; + +} + +extern "C" +{ +struct IDXGISwapChain; +struct IDXGISwapChain1; +} + +// Deprecated swap chain and presentation declarations: + +#define DXGI_MAX_SWAP_CHAIN_BUFFERS ( 16 ) +#define DXGI_PRESENT_TEST 0x00000001UL +#define DXGI_PRESENT_DO_NOT_SEQUENCE 0x00000002UL +#define DXGI_PRESENT_RESTART 0x00000004UL +#define DXGI_PRESENT_DO_NOT_WAIT 0x00000008UL +#define DXGI_PRESENT_STEREO_PREFER_RIGHT 0x00000010UL +#define DXGI_PRESENT_STEREO_TEMPORARY_MONO 0x00000020UL +#define DXGI_PRESENT_RESTRICT_TO_OUTPUT 0x00000040UL +#define DXGIX_PRESENT_UPSCALE_FILTER_DEFAULT 0x00000000UL +#define DXGIX_PRESENT_UPSCALE_FILTER_BILINEAR 0x00100000UL +#define DXGIX_PRESENT_UPSCALE_FILTER_SINC4 0x00200000UL +#define DXGIX_PRESENT_UPSCALE_FILTER_LANCZOS4 0x00300000UL +#define DXGIX_PRESENT_UPSCALE_FILTER_LANCZOS6 0x00400000UL +#define DXGIX_PRESENT_UPSCALE_FILTER_LANCZOS6_SOFT 0x00500000UL +#define DXGIX_PRESENT_UPSCALE_FILTER_LANCZOS8 0x00600000UL +#define DXGIX_PRESENT_UPSCALE_FILTER_LANCZOS10 0x00700000UL +#define DXGIX_PRESENT_UPSCALE_FILTER_MASK 0x00F00000UL +#define DXGIX_PRESENT_DISABLE_VARIABLE_REFRESH_RATE 0x01000000UL +#define DXGIX_PRESENT_PRESERVE_FRAMEBUFFER 0x10000000UL + +extern "C" +{ + +typedef enum DXGI_SWAP_EFFECT +{ + DXGI_SWAP_EFFECT_DISCARD = 0, + DXGI_SWAP_EFFECT_SEQUENTIAL = 1, + DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL = 3 +} DXGI_SWAP_EFFECT; + +typedef enum DXGI_SWAP_CHAIN_FLAG +{ + DXGI_SWAP_CHAIN_FLAG_NONPREROTATED = 1, + DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH = 2, + DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE = 4, + DXGI_SWAP_CHAIN_FLAG_RESTRICTED_CONTENT = 8, + DXGI_SWAP_CHAIN_FLAG_RESTRICT_SHARED_RESOURCE_DRIVER = 16, + DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY = 32, + DXGIX_SWAP_CHAIN_FLAG_QUANTIZATION_RGB_FULL = 0, + DXGIX_SWAP_CHAIN_FLAG_QUANTIZATION_RGB_LIMITED = 0x00100000, + DXGIX_SWAP_CHAIN_FLAG_COLORIMETRY_sRGB_TO_REC709 = 0x00200000, + DXGIX_SWAP_CHAIN_MATCH_OTHER_CONSOLES = (DXGIX_SWAP_CHAIN_FLAG_QUANTIZATION_RGB_FULL), + DXGIX_SWAP_CHAIN_MATCH_XBOX360_AND_PC = (DXGIX_SWAP_CHAIN_FLAG_QUANTIZATION_RGB_FULL | DXGIX_SWAP_CHAIN_FLAG_COLORIMETRY_sRGB_TO_REC709), + DXGIX_SWAP_CHAIN_FLAG_COLORIMETRY_RGB_BT2020_ST2084 = 0x00800000, + DXGIX_SWAP_CHAIN_FLAG_AUTOMATIC_GAMEDVR_TONEMAP = 0x02000000, +} DXGI_SWAP_CHAIN_FLAG; + +typedef struct DXGI_SWAP_CHAIN_DESC +{ + DXGI_MODE_DESC BufferDesc; + DXGI_SAMPLE_DESC SampleDesc; + DXGI_USAGE BufferUsage; + UINT BufferCount; + HWND OutputWindow; + BOOL Windowed; + DXGI_SWAP_EFFECT SwapEffect; + UINT Flags; +} DXGI_SWAP_CHAIN_DESC; + +typedef struct DXGI_SWAP_CHAIN_DESC1 +{ + UINT Width; + UINT Height; + DXGI_FORMAT Format; + BOOL Stereo; + DXGI_SAMPLE_DESC SampleDesc; + DXGI_USAGE BufferUsage; + UINT BufferCount; + DXGI_SCALING Scaling; + DXGI_SWAP_EFFECT SwapEffect; + DXGI_ALPHA_MODE AlphaMode; + UINT Flags; // DXGI_SWAP_CHAIN_FLAG +} DXGI_SWAP_CHAIN_DESC1; + +typedef struct DXGI_SWAP_CHAIN_FULLSCREEN_DESC +{ + DXGI_RATIONAL RefreshRate; + DXGI_MODE_SCANLINE_ORDER ScanlineOrdering; + DXGI_MODE_SCALING Scaling; + BOOL Windowed; +} DXGI_SWAP_CHAIN_FULLSCREEN_DESC; + +typedef struct DXGI_PRESENT_PARAMETERS +{ + UINT DirtyRectsCount; + RECT* pDirtyRects; + RECT* pScrollRect; + POINT* pScrollOffset; +} DXGI_PRESENT_PARAMETERS; + +} + +extern "C" +{ + +// +// DXGIX: +// + +#ifndef __D3D11_RECT__DEFINED__ +#define __D3D11_RECT__DEFINED__ +typedef RECT D3D11_RECT; +#endif // __D3D11_RECT__DEFINED__ + +// +// Multiplane Present (deprecated): +// + +typedef struct _DXGIX_PRESENTARRAY_PARAMETERS +{ + BOOL Disable; + BOOL UsePreviousBuffer; + D3D11_RECT SourceRect; + POINT DestRectUpperLeft; + FLOAT ScaleFactorVert; + FLOAT ScaleFactorHorz; + VOID* Cookie; + UINT Flags; +} DXGIX_PRESENTARRAY_PARAMETERS; + + +// +// Presentation statistics (deprecated): +// + +typedef struct _DXGIX_FRAME_STATISTICS +{ + // CPU time line + UINT64 CPUTimePresentCalled; + UINT64 CPUTimeAddedToQueue; + UINT32 QueueLengthAddedToQueue; + + // GPU time line + UINT64 CPUTimeFrameComplete; + UINT64 GPUTimeFrameComplete; + UINT64 GPUCountTitleUsed; + UINT64 GPUCountSystemUsed; + + // Display time line + UINT64 CPUTimeVSync; + UINT64 GPUTimeVSync; + UINT64 CPUTimeFlip; + UINT64 GPUTimeFlip; + UINT64 VSyncCount; + FLOAT PercentScanned; + + VOID* Cookie[2]; +} DXGIX_FRAME_STATISTICS; + + +// +// VLine notification (deprecated): +// + +typedef enum DXGIX_VLINECOUNTER +{ + VLINECOUNTER0 = 0, + VLINECOUNTER1 = 1 +} DXGIX_VLINECOUNTER; + + +// +// Frame notifications (deprecated): +// + +typedef enum DXGIX_FRAME_NOTIFICATION +{ + FRAME_NOTIFICATION_QUEUED = 0, + FRAME_NOTIFICATION_COMPLETED = 1, + FRAME_NOTIFICATION_FLIPPED = 2 +} DXGIX_FRAME_NOTIFICATION; + + +} + + +// +// IDXGIObject +// + +struct DXGIObject_Function_Table +{ + GraphicsUnknown_Function_Table UnknownFunction; + + HRESULT (D3DAPI* SetPrivateData)( + _Inout_ IDXGIObject* pObject, + _In_ REFGUID Name, + _In_ UINT DataSize, + _In_reads_bytes_(DataSize) const void* pData); + + HRESULT (D3DAPI* SetPrivateDataInterface)( + _Inout_ IDXGIObject* pObject, + _In_ REFGUID Name, + _In_ const IUnknown* pUnknown); + + HRESULT (D3DAPI* GetPrivateData)( + _Inout_ IDXGIObject* pObject, + _In_ REFGUID Name, + _Inout_ UINT* pDataSize, + _Out_writes_bytes_(*pDataSize) void* pData); + + HRESULT (D3DAPI* GetParent)( + _Inout_ IDXGIObject* pObject, + _In_ REFIID riid, + _Out_ void** ppParent); +}; + + +} + +D3DINTERFACE(IDXGIObject, aec22fb8,76f3,4639,9b,e0,28,eb,43,a6,7a,2e) : public IGraphicsUnknown +{ +public: + + void* m_pPrivateData; + +public: + + D3DINLINE DXGIObject_Function_Table* ObjectFunction() + { + return (DXGIObject_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI SetPrivateData( + _In_ REFGUID Name, + _In_ UINT DataSize, + _In_reads_bytes_(DataSize) const void* pData) + { + return ObjectFunction()->SetPrivateData(this, Name, DataSize, pData); + } + + D3DINLINE HRESULT D3DAPI SetPrivateDataInterface( + _In_ REFGUID Name, + _In_ const IUnknown* pUnknown) + { + return ObjectFunction()->SetPrivateDataInterface(this, Name, pUnknown); + } + + D3DINLINE HRESULT D3DAPI GetPrivateData( + _In_ REFGUID Name, + _Inout_ UINT* pDataSize, + _Out_writes_bytes_(*pDataSize) void* pData) + { + return ObjectFunction()->GetPrivateData(this, Name, pDataSize, pData); + } + + D3DINLINE HRESULT D3DAPI GetParent( + _In_ REFIID riid, + _Out_ void** ppParent) + { + return ObjectFunction()->GetParent(this, riid, ppParent); + } +}; + +extern "C" +{ + +// +// IDXGIDeviceSubObject +// + +struct DXGIDeviceSubObject_Function_Table +{ + DXGIObject_Function_Table ObjectFunction; + + HRESULT (D3DAPI* GetDevice)( + _Inout_ IDXGIDeviceSubObject* pDeviceSubObject, + _In_ REFIID riid, + _Out_ void** ppDevice); +}; + + +} + +D3DINTERFACE(IDXGIDeviceSubObject, 3d3e0379,f9de,4d58,bb,6c,18,d6,29,92,f1,a6) : public IDXGIObject +{ +public: + + D3DINLINE DXGIDeviceSubObject_Function_Table* DeviceSubObjectFunction() + { + return (DXGIDeviceSubObject_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetDevice( + _In_ REFIID riid, + _Out_ void** ppDevice) + { + return DeviceSubObjectFunction()->GetDevice(this, riid, ppDevice); + } +}; + +extern "C" +{ + +// +// IDXGIFactory +// + +typedef VOID IDXGIResource; +typedef VOID IDXGISurface; + +struct DXGIFactory_Function_Table +{ + DXGIObject_Function_Table ObjectFunction; + + HRESULT (D3DAPI* EnumAdapters)( + _Inout_ IDXGIFactory* pFactory, + _In_ UINT Adapter, + _Out_ IDXGIAdapter** ppAdapter); + + HRESULT (D3DAPI* MakeWindowAssociation)( + _Inout_ IDXGIFactory* pFactory, + HWND WindowHandle, + UINT Flags); + + HRESULT (D3DAPI* GetWindowAssociation)( + _Inout_ IDXGIFactory* pFactory, + _Out_ HWND* pWindowHandle); + + HRESULT (D3DAPI* CreateSwapChain)( + _Inout_ IDXGIFactory* pFactory, + _In_ IGraphicsUnknown* pDevice, + _In_ DXGI_SWAP_CHAIN_DESC* pDesc, + _Out_ IDXGISwapChain** ppSwapChain); + + HRESULT (D3DAPI* CreateSoftwareAdapter)( + _Inout_ IDXGIFactory* pFactory, + _In_ HMODULE Module, + _Out_ IDXGIAdapter** ppAdapter); +}; + + +} + +D3DINTERFACE(IDXGIFactory, 7b7166ec,21c7,44ae,b2,1a,c9,ae,32,1a,e3,69) : public IDXGIObject +{ +public: + + struct IDXGIAdapter2* m_pAdapter; + +public: + + D3DINLINE DXGIFactory_Function_Table* FactoryFunction() + { + return (DXGIFactory_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI EnumAdapters( + _In_ UINT Adapter, + _Out_ IDXGIAdapter** ppAdapter) + { + return FactoryFunction()->EnumAdapters(this, Adapter, ppAdapter); + } + + D3DINLINE HRESULT D3DAPI MakeWindowAssociation( + HWND WindowHandle, + UINT Flags) + { + return FactoryFunction()->MakeWindowAssociation(this, WindowHandle, Flags); + } + + D3DINLINE HRESULT D3DAPI GetWindowAssociation( + _Out_ HWND* pWindowHandle) + { + return FactoryFunction()->GetWindowAssociation(this, pWindowHandle); + } + + + D3DINLINE HRESULT D3DAPI CreateSoftwareAdapter( + _In_ HMODULE Module, + _Out_ IDXGIAdapter** ppAdapter) + { + return FactoryFunction()->CreateSoftwareAdapter(this, Module, ppAdapter); + } +}; + +extern "C" +{ + +// +// IDXGIFactory1 +// + +struct DXGIFactory1_Function_Table +{ + DXGIFactory_Function_Table FactoryFunction; + + HRESULT (D3DAPI* EnumAdapters1)( + _Inout_ IDXGIFactory1* pFactory1, + _In_ UINT Adapter, + _Out_ IDXGIAdapter1** ppAdapter); + + BOOL (D3DAPI* IsCurrent)( + _Inout_ IDXGIFactory1* pFactory1); + +}; + + +} + +D3DINTERFACE(IDXGIFactory1, 770aae78,f26f,4dba,a8,29,25,3c,83,d1,b3,87) : public IDXGIFactory +{ +public: + + D3DINLINE DXGIFactory1_Function_Table* Factory1Function() + { + return (DXGIFactory1_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI EnumAdapters1( + _In_ UINT Adapter, + _Out_ IDXGIAdapter1** ppAdapter) + { + return Factory1Function()->EnumAdapters1(this, Adapter, ppAdapter); + } + + D3DINLINE BOOL D3DAPI IsCurrent() + { + return Factory1Function()->IsCurrent(this); + } +}; + +extern "C" +{ + +// +// IDXGIFactory2 +// + +struct DXGIFactory2_Function_Table +{ + DXGIFactory1_Function_Table Factory1Function; + + BOOL (D3DAPI* IsWindowedStereoEnabled)( + _Inout_ IDXGIFactory2* pFactory2); + + HRESULT (D3DAPI* CreateSwapChainForHwnd)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ IGraphicsUnknown* pDevice, + _In_ HWND hWnd, + _In_ const DXGI_SWAP_CHAIN_DESC1* pDesc, + _In_opt_ const DXGI_SWAP_CHAIN_FULLSCREEN_DESC* pFullscreenDesc, + _In_opt_ IDXGIOutput* pRestrictToOutput, + _Out_ IDXGISwapChain1** ppSwapChain); + + HRESULT (D3DAPI* CreateSwapChainForCoreWindow)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ IGraphicsUnknown* pDevice, + _In_ IUnknown* pWindow, + _In_ const DXGI_SWAP_CHAIN_DESC1* pDesc, + _In_opt_ IDXGIOutput* pRestrictToOutput, + _Out_ IDXGISwapChain1** ppSwapChain); + + HRESULT (D3DAPI* GetSharedResourceAdapterLuid)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ HANDLE hResource, + _Out_ LUID* pLuid); + + HRESULT (D3DAPI* RegisterStereoStatusWindow)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ HWND WindowHandle, + _In_ UINT wMsg, + _Out_ DWORD* pdwCookie); + + HRESULT (D3DAPI* RegisterStereoStatusEvent)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ HANDLE hEvent, + _Out_ DWORD* pdwCookie); + + void (D3DAPI* UnregisterStereoStatus)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ DWORD dwCookie); + + HRESULT (D3DAPI* RegisterOcclusionStatusWindow)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ HWND WindowHandle, + _In_ UINT wMsg, + _Out_ DWORD* pdwCookie); + + HRESULT (D3DAPI* RegisterOcclusionStatusEvent)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ HANDLE hEvent, + _Out_ DWORD* pdwCookie); + + void (D3DAPI* UnregisterOcclusionStatus)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ DWORD dwCookie); + + HRESULT (D3DAPI* CreateSwapChainForComposition)( + _Inout_ IDXGIFactory2* pFactory2, + _In_ IGraphicsUnknown* pDevice, + _In_ const DXGI_SWAP_CHAIN_DESC1* pDesc, + _In_opt_ IDXGIOutput* pRestrictToOutput, + _Outptr_ IDXGISwapChain1** ppSwapChain); +}; + + +} + +D3DINTERFACE(IDXGIFactory2, 50c83a1c,e072,4c48,87,b0,36,30,fa,36,a6,d0) : public IDXGIFactory1 +{ +public: + + D3DINLINE DXGIFactory2_Function_Table* Factory2Function() + { + return (DXGIFactory2_Function_Table*)m_pFunction; + } + + D3DINLINE BOOL D3DAPI IsWindowedStereoEnabled() + { + return Factory2Function()->IsWindowedStereoEnabled(this); + } + + + D3DINLINE HRESULT D3DAPI GetSharedResourceAdapterLuid( + _In_ HANDLE hResource, + _Out_ LUID* pLuid) + { + return Factory2Function()->GetSharedResourceAdapterLuid(this, hResource, pLuid); + } + + D3DINLINE HRESULT D3DAPI RegisterStereoStatusWindow( + _In_ HWND WindowHandle, + _In_ UINT wMsg, + _Out_ DWORD* pdwCookie) + { + return Factory2Function()->RegisterStereoStatusWindow(this, WindowHandle, wMsg, pdwCookie); + } + + D3DINLINE HRESULT D3DAPI RegisterStereoStatusEvent( + _In_ HANDLE hEvent, + _Out_ DWORD* pdwCookie) + { + return Factory2Function()->RegisterStereoStatusEvent(this, hEvent, pdwCookie); + } + + D3DINLINE void D3DAPI UnregisterStereoStatus( + _In_ DWORD dwCookie) + { + return Factory2Function()->UnregisterStereoStatus(this, dwCookie); + } + + D3DINLINE HRESULT D3DAPI RegisterOcclusionStatusWindow( + _In_ HWND WindowHandle, + _In_ UINT wMsg, + _Out_ DWORD* pdwCookie) + { + return Factory2Function()->RegisterOcclusionStatusWindow(this, + WindowHandle, + wMsg, + pdwCookie); + } + + D3DINLINE HRESULT D3DAPI RegisterOcclusionStatusEvent( + _In_ HANDLE hEvent, + _Out_ DWORD* pdwCookie) + { + return Factory2Function()->RegisterOcclusionStatusEvent(this, hEvent, pdwCookie); + } + + D3DINLINE void D3DAPI UnregisterOcclusionStatus( + _In_ DWORD dwCookie) + { + return Factory2Function()->UnregisterOcclusionStatus(this, dwCookie); + } + +}; + +extern "C" +{ + +// +// IDXGIAdapter +// + +struct DXGIAdapter_Function_Table +{ + DXGIObject_Function_Table ObjectFunction; + + HRESULT (D3DAPI* EnumOutputs)( + _Inout_ IDXGIAdapter* pAdapter, + _In_ UINT Output, + _Out_ IDXGIOutput** ppOutput); + + HRESULT (D3DAPI* GetDesc)( + _Inout_ IDXGIAdapter* pAdapter, + _Out_ DXGI_ADAPTER_DESC* pDesc); + + HRESULT (D3DAPI* CheckInterfaceSupport)( + _Inout_ IDXGIAdapter* pAdapter, + _In_ REFGUID InterfaceName, + _Out_ LARGE_INTEGER* pUMDVersion); +}; + + +} + +D3DINTERFACE(IDXGIAdapter, 2411e7e1,12ac,4ccf,bd,14,97,98,e8,53,4d,c0) : public IDXGIObject +{ +public: + + D3DINLINE DXGIAdapter_Function_Table* AdapterFunction() + { + return (DXGIAdapter_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI EnumOutputs( + _In_ UINT Output, + _Out_ IDXGIOutput** ppOutput) + { + return AdapterFunction()->EnumOutputs(this, Output, ppOutput); + } + + D3DINLINE HRESULT D3DAPI GetDesc( + _Out_ DXGI_ADAPTER_DESC* pDesc) + { + return AdapterFunction()->GetDesc(this, pDesc); + } + + D3DINLINE HRESULT D3DAPI CheckInterfaceSupport( + _In_ REFGUID InterfaceName, + _Out_ LARGE_INTEGER* pUMDVersion) + { + return AdapterFunction()->CheckInterfaceSupport(this, InterfaceName, pUMDVersion); + } +}; + +extern "C" +{ + +// +// IDXGIAdapter1 +// + +struct DXGIAdapter1_Function_Table +{ + DXGIAdapter_Function_Table AdapterFunction; + + HRESULT (D3DAPI* GetDesc1)( + _Inout_ IDXGIAdapter1* pAdapter1, + _Out_ DXGI_ADAPTER_DESC1* pDesc); + +}; + + +} + +D3DINTERFACE(IDXGIAdapter1, 29038f61,3839,4626,91,fd,08,68,79,01,1a,05) : public IDXGIAdapter +{ +public: + + D3DINLINE DXGIAdapter1_Function_Table* Adapter1Function() + { + return (DXGIAdapter1_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetDesc1( + _Out_ DXGI_ADAPTER_DESC1* pDesc) + { + return Adapter1Function()->GetDesc1(this, pDesc); + } +}; + +extern "C" +{ + +// +// IDXGIAdapter2 +// + +struct DXGIAdapter2_Function_Table +{ + DXGIAdapter1_Function_Table Adapter1Function; + + HRESULT (D3DAPI* GetDesc2)( + _Inout_ IDXGIAdapter2* pAdapter2, + _Out_ DXGI_ADAPTER_DESC2* pDesc); + +}; + + +} + +D3DINTERFACE(IDXGIAdapter2, 0AA1AE0A,FA0E,4B84,86,44,E0,5F,F8,E5,AC,B5) : public IDXGIAdapter1 +{ +public: + + D3DINLINE DXGIAdapter2_Function_Table* Adapter2Function() + { + return (DXGIAdapter2_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetDesc2( + _Out_ DXGI_ADAPTER_DESC2* pDesc) + { + return Adapter2Function()->GetDesc2(this, pDesc); + } +}; + +extern "C" +{ + +// +// IDXGIDevice +// + +struct DXGIDevice_Function_Table +{ + DXGIObject_Function_Table ObjectFunction; + + HRESULT (D3DAPI* GetAdapter)( + _Inout_ IDXGIDevice* pDevice, + _Out_ IDXGIAdapter** pAdapter); + + HRESULT (D3DAPI* CreateSurface)( + _Inout_ IDXGIDevice* pDevice, + _In_ const DXGI_SURFACE_DESC *pDesc, + _In_ UINT NumSurfaces, + _In_ DXGI_USAGE Usage, + _In_opt_ const DXGI_SHARED_RESOURCE* pSharedResource, + _Out_ IDXGISurface** ppSurface); + + HRESULT (D3DAPI* QueryResourceResidency)( + _Inout_ IDXGIDevice* pDevice, + _In_reads_ (NumResources) IGraphicsUnknown* const* ppResources, + _Out_writes_ (NumResources) DXGI_RESIDENCY* pResidencyStatus, + _In_ UINT NumResources); + + HRESULT (D3DAPI* SetGPUThreadPriority)( + _Inout_ IDXGIDevice* pDevice, + _In_ INT Priority); + + HRESULT (D3DAPI* GetGPUThreadPriority)( + _Inout_ IDXGIDevice* pDevice, + _Out_ INT* pPriority); +}; + + +} + +D3DINTERFACE(IDXGIDevice, 54ec77fa,1377,44e6,8c,32,88,fd,5f,44,c8,4c) : public IDXGIObject +{ +public: + + struct ID3D12Device* m_pDevice; + +public: + + D3DINLINE DXGIDevice_Function_Table* DeviceFunction() + { + return (DXGIDevice_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetAdapter( + _Out_ IDXGIAdapter** pAdapter) + { + return DeviceFunction()->GetAdapter(this, pAdapter); + } + + D3DINLINE HRESULT D3DAPI CreateSurface( + _In_ const DXGI_SURFACE_DESC *pDesc, + _In_ UINT NumSurfaces, + _In_ DXGI_USAGE Usage, + _In_opt_ const DXGI_SHARED_RESOURCE* pSharedResource, + _Out_ IDXGISurface** ppSurface) + { + return DeviceFunction()->CreateSurface(this, + pDesc, + NumSurfaces, + Usage, + pSharedResource, + ppSurface); + } + + D3DINLINE HRESULT D3DAPI QueryResourceResidency( + _In_reads_ (NumResources) IGraphicsUnknown* const* ppResources, + _Out_writes_ (NumResources) DXGI_RESIDENCY* pResidencyStatus, + _In_ UINT NumResources) + { + return DeviceFunction()->QueryResourceResidency(this, + ppResources, + pResidencyStatus, + NumResources); + } + + D3DINLINE HRESULT D3DAPI SetGPUThreadPriority( + _In_ INT Priority) + { + return DeviceFunction()->SetGPUThreadPriority(this, Priority); + } + + D3DINLINE HRESULT D3DAPI GetGPUThreadPriority( + _Out_ INT* pPriority) + { + return DeviceFunction()->GetGPUThreadPriority(this, pPriority); + } +}; + +extern "C" +{ + +// +// IDXGIDevice1 +// + +struct DXGIDevice1_Function_Table +{ + DXGIDevice_Function_Table DeviceFunction; + + HRESULT (D3DAPI* SetMaximumFrameLatency)( + _Inout_ IDXGIDevice1* pDevice1, + _In_ UINT MaxLatency); + + HRESULT (D3DAPI* GetMaximumFrameLatency)( + _Inout_ IDXGIDevice1* pDevice1, + _Out_ UINT* pMaxLatency); +}; + + +} + +D3DINTERFACE(IDXGIDevice1, 77db970f,6276,48ba,ba,28,07,01,43,b4,39,2c) : public IDXGIDevice +{ +public: + + D3DINLINE DXGIDevice1_Function_Table* Device1Function() + { + return (DXGIDevice1_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI SetMaximumFrameLatency( + _In_ UINT MaxLatency) + { + return Device1Function()->SetMaximumFrameLatency(this, MaxLatency); + } + + D3DINLINE HRESULT D3DAPI GetMaximumFrameLatency( + _Out_ UINT* pMaxLatency) + { + return Device1Function()->GetMaximumFrameLatency(this, pMaxLatency); + } +}; + +extern "C" +{ + +// +// IDXGIDevice2 +// + +struct DXGIDevice2_Function_Table +{ + DXGIDevice1_Function_Table Device1Function; + + HRESULT (D3DAPI* OfferResources)( + _Inout_ IDXGIDevice2* pDevice2, + _In_ UINT NumResources, + _In_reads_ (NumResources) IDXGIResource* const* ppResources, + _In_ DXGI_OFFER_RESOURCE_PRIORITY Priority); + + HRESULT (D3DAPI* ReclaimResources)( + _Inout_ IDXGIDevice2* pDevice2, + _In_ UINT NumResources, + _In_reads_ (NumResources) IDXGIResource* const* ppResources, + _Out_writes_all_opt_ (NumResources) BOOL* pDiscarded); + + HRESULT (D3DAPI* EnqueueSetEvent)( + _Inout_ IDXGIDevice2* pDevice2, + _In_ HANDLE hEvent); +}; + + +} + +D3DINTERFACE(IDXGIDevice2, 05008617,fbfd,4051,a7,90,14,48,84,b4,f6,a9) : public IDXGIDevice1 +{ +public: + + D3DINLINE DXGIDevice2_Function_Table* Device2Function() + { + return (DXGIDevice2_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI OfferResources( + _In_ UINT NumResources, + _In_reads_ (NumResources) IDXGIResource* const* ppResources, + _In_ DXGI_OFFER_RESOURCE_PRIORITY Priority) + { + return Device2Function()->OfferResources(this, NumResources, ppResources, Priority); + } + + D3DINLINE HRESULT D3DAPI ReclaimResources( + _In_ UINT NumResources, + _In_reads_ (NumResources) IDXGIResource* const* ppResources, + _Out_writes_all_opt_ (NumResources) BOOL* pDiscarded) + { + return Device2Function()->ReclaimResources(this, NumResources, ppResources, pDiscarded); + } + + D3DINLINE HRESULT D3DAPI EnqueueSetEvent( + _In_ HANDLE hEvent) + { + return Device2Function()->EnqueueSetEvent(this, hEvent); + } +}; + + +extern "C" +{ +typedef VOID DXGI_FRAME_STATISTICS; +} + + +// Swap chains have been deprecated and replaced by swap resources (D3D12_HEAP_FLAG_ALLOW_DISPLAY) +// and presentation through ID3D12CommandQueue::PresentX. + +D3DINTERFACE(IDXGISwapChain, 310d36a0,d2e7,4c0a,aa,04,6a,9d,23,b8,88,6a) : public IDXGIDeviceSubObject +{ +}; + + +D3DINTERFACE(IDXGISwapChain1, 790a45f7,0d42,4876,98,3a,0a,55,cf,e6,f4,aa) : public IDXGISwapChain +{ +}; + +extern "C" +{ + +// +// DXGI Info Queue +// + +typedef enum DXGI_INFO_QUEUE_MESSAGE_CATEGORY +{ + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_UNKNOWN = 0, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_MISCELLANEOUS, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_INITIALIZATION, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_CLEANUP, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_COMPILATION, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_STATE_CREATION, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_STATE_SETTING, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_STATE_GETTING, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_RESOURCE_MANIPULATION, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_EXECUTION, + DXGI_INFO_QUEUE_MESSAGE_CATEGORY_SHADER +} DXGI_INFO_QUEUE_MESSAGE_CATEGORY; + +typedef enum DXGI_INFO_QUEUE_MESSAGE_SEVERITY +{ + DXGI_INFO_QUEUE_MESSAGE_SEVERITY_CORRUPTION = 0, + DXGI_INFO_QUEUE_MESSAGE_SEVERITY_ERROR, + DXGI_INFO_QUEUE_MESSAGE_SEVERITY_WARNING, + DXGI_INFO_QUEUE_MESSAGE_SEVERITY_INFO, + DXGI_INFO_QUEUE_MESSAGE_SEVERITY_MESSAGE +} DXGI_INFO_QUEUE_MESSAGE_SEVERITY; + +typedef int DXGI_INFO_QUEUE_MESSAGE_ID; +#define DXGI_INFO_QUEUE_MESSAGE_ID_STRING_FROM_APPLICATION 0 + +typedef GUID DXGI_DEBUG_ID; + +DEFINE_D3DGUID(DXGI_DEBUG_ALL, 0xe48ae283, 0xda80, 0x490b, 0x87, 0xe6, 0x43, 0xe9, 0xa9, 0xcf, 0xda, 0x8); +DEFINE_D3DGUID(DXGI_DEBUG_DX, 0x35cdd7fc, 0x13b2, 0x421d, 0xa5, 0xd7, 0x7e, 0x44, 0x51, 0x28, 0x7d, 0x64); +DEFINE_D3DGUID(DXGI_DEBUG_DXGI, 0x25cddaa4, 0xb1c6, 0x47e1, 0xac, 0x3e, 0x98, 0x87, 0x5b, 0x5a, 0x2e, 0x2a); +DEFINE_D3DGUID(DXGI_DEBUG_APP, 0x6cd6e01, 0x4219, 0x4ebd, 0x87, 0x9, 0x27, 0xed, 0x23, 0x36, 0xc, 0x62); +DEFINE_D3DGUID(DXGI_DEBUG_D3D11, 0x4b99317b, 0xac39, 0x4aa6, 0xbb, 0xb, 0xba, 0xa0, 0x47, 0x84, 0x79, 0x8f); + +typedef struct DXGI_INFO_QUEUE_MESSAGE +{ + DXGI_DEBUG_ID Producer; + DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category; + DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity; + DXGI_INFO_QUEUE_MESSAGE_ID ID; + const char* pDescription; + SIZE_T DescriptionByteLength; +} DXGI_INFO_QUEUE_MESSAGE; + +typedef struct DXGI_INFO_QUEUE_FILTER_DESC +{ + UINT NumCategories; + DXGI_INFO_QUEUE_MESSAGE_CATEGORY* pCategoryList; + + UINT NumSeverities; + DXGI_INFO_QUEUE_MESSAGE_SEVERITY* pSeverityList; + + UINT NumIDs; + DXGI_INFO_QUEUE_MESSAGE_ID* pIDList; +} DXGI_INFO_QUEUE_FILTER_DESC; + +// To use, memset to 0, then fill in what you need. +typedef struct DXGI_INFO_QUEUE_FILTER +{ + DXGI_INFO_QUEUE_FILTER_DESC AllowList; + DXGI_INFO_QUEUE_FILTER_DESC DenyList; +} DXGI_INFO_QUEUE_FILTER; + +typedef enum DXGI_INFO_QUEUE_MESSAGE_CALLBACK_FLAGS +{ + DXGI_INFO_QUEUE_MESSAGE_CALLBACK_FLAG_NONE = 0, + DXGI_INFO_QUEUE_MESSAGE_CALLBACK_IGNORE_FILTERS = 0x1 +} DXGI_INFO_QUEUE_MESSAGE_CALLBACK_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(DXGI_INFO_QUEUE_MESSAGE_CALLBACK_FLAGS) + +typedef void(__stdcall* DxgiMessageFunc)( + DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category, + DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, + DXGI_INFO_QUEUE_MESSAGE_ID ID, + LPCSTR pDescription, + void* pContext); + +#define DXGI_INFO_QUEUE_DEFAULT_MESSAGE_COUNT_LIMIT 1024 + +// +// IDXGIInfoQueue +// + +struct DXGIInfoQueue_Function_Table +{ + GraphicsUnknown_Function_Table UnknownFunction; + + HRESULT (D3DAPI* SetMessageCountLimit)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ UINT64 MessageCountLimit); + + void (D3DAPI* ClearStoredMessages)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* GetMessage)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ UINT64 MessageIndex, + _Out_writes_bytes_opt_(*pMessageByteLength) DXGI_INFO_QUEUE_MESSAGE* pMessage, + _Inout_ SIZE_T* pMessageByteLength); + + UINT64 (D3DAPI* GetNumStoredMessagesAllowedByRetrievalFilters)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + UINT64 (D3DAPI* GetNumStoredMessages)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + UINT64 (D3DAPI* GetNumMessagesDiscardedByMessageCountLimit)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + UINT64 (D3DAPI* GetMessageCountLimit)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + UINT64 (D3DAPI* GetNumMessagesAllowedByStorageFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + UINT64 (D3DAPI* GetNumMessagesDeniedByStorageFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* AddStorageFilterEntries)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_FILTER* pFilter); + + HRESULT (D3DAPI* GetStorageFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _Out_writes_bytes_opt_(*pFilterByteLength) DXGI_INFO_QUEUE_FILTER* pFilter, + _Inout_ SIZE_T* pFilterByteLength); + + void (D3DAPI* ClearStorageFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* PushEmptyStorageFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* PushDenyAllStorageFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* PushCopyOfStorageFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* PushStorageFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_FILTER* pFilter); + + void (D3DAPI* PopStorageFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + UINT (D3DAPI* GetStorageFilterStackSize)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* AddRetrievalFilterEntries)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_FILTER* pFilter ); + + HRESULT (D3DAPI* GetRetrievalFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _Out_writes_bytes_opt_(*pFilterByteLength) DXGI_INFO_QUEUE_FILTER* pFilter, + _Inout_ SIZE_T* pFilterByteLength ); + + void (D3DAPI* ClearRetrievalFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* PushEmptyRetrievalFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* PushDenyAllRetrievalFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* PushCopyOfRetrievalFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* PushRetrievalFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_FILTER* pFilter ); + + void (D3DAPI* PopRetrievalFilter)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + UINT (D3DAPI* GetRetrievalFilterStackSize)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); + + HRESULT (D3DAPI* AddMessage)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category, + _In_ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, + _In_ DXGI_INFO_QUEUE_MESSAGE_ID ID, + _In_ LPCSTR pDescription); + + HRESULT (D3DAPI* AddApplicationMessage)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, + _In_ LPCSTR pDescription); + + HRESULT (D3DAPI* SetBreakOnCategory)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category, + _In_ BOOL bEnable ); + + HRESULT (D3DAPI* SetBreakOnSeverity)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, + _In_ BOOL bEnable ); + + HRESULT (D3DAPI* SetBreakOnID)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_ID ID, + _In_ BOOL bEnable ); + + BOOL (D3DAPI* GetBreakOnCategory)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category); + + BOOL (D3DAPI* GetBreakOnSeverity)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity); + + BOOL (D3DAPI* GetBreakOnID)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_ID ID ); + + void (D3DAPI* SetMuteDebugOutput)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer, + _In_ BOOL bMute ); + + BOOL (D3DAPI* GetMuteDebugOutput)( + _Inout_ IDXGIInfoQueue* pInfoQueue, + _In_ DXGI_DEBUG_ID Producer); +}; + + +} + +D3DINTERFACE(IDXGIInfoQueue, d67441c7,672a,476f,9e,82,cd,55,b4,49,49,ce) : public IGraphicsUnknown +{ +public: + + D3DINLINE DXGIInfoQueue_Function_Table* InfoQueueFunction() + { + return (DXGIInfoQueue_Function_Table*)m_pFunction; + } + + //========================================================================= + // Methods for configuring how much data is stored in the queue. + + // SetMessageCountLimit() + // This sets how many messages are stored for a given producer. When the queue + // is full, new messages coming in push old messages out (for that producer). + // Passing -1 to SetMessageCountLimit means the queue has + // unlimited size (go until out of memory or ClearStoredMessages()). + // The default message count size is DXGI_INFO_QUEUE_DEFAULT_MESSAGE_COUNT_LIMIT + // Returns S_OK or E_INVALIDARG. + D3DINLINE HRESULT D3DAPI SetMessageCountLimit( + _In_ DXGI_DEBUG_ID Producer, + _In_ UINT64 MessageCountLimit) + { + return InfoQueueFunction()->SetMessageCountLimit(this, Producer, MessageCountLimit); + } + + // ClearStoredMessages + D3DINLINE void D3DAPI ClearStoredMessages( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->ClearStoredMessages(this, Producer); + } + + //========================================================================= + // Methods for retrieving data or statistics from the queue. + + // GetMessage() + // Retrieves messages, one at a time, from the queue which pass any + // retrieval filter currently defined. + // + // Call GetMessage with (DXGI_INFO_QUEUE_PRODUCER_ALL) to get messages + // from all producers. + // + // The MessageIndex parameter is a 0 based index into the results passing + // the filter. The number of results is returned by + // GetNumStoredMessagesAllowedByRetrievalFilter(). + // + // Note this does not remove the message from the queue. + // + // pMessageByteLength inputs the size of the buffer passed in via + // pMessage, and outputs the size of the message. pMessage can be NULL + // when the size of the required buffer is being queried (return S_FALSE). + // + // NOTE: The returned buffer pMessage is NOT just the size of DXGI_INFO_QUEUE_MESSAGE, + // it includes extra memory after the DXGI_INFO_QUEUE_MESSAGE for storing the string + // description, which is pointed to from within DXGI_INFO_QUEUE_MESSAGE. Therefore + // applications should check the size needed for pMessage as described above. + // + // Watch out for thread safety when making consecutive calls first to + // determine the buffer size required and then to pass in the buffer and + // retrieve the message, and also between calling + // GetNumStoredMessagesAllowedByRetrievalFilter() and enumerating through + // the results via GetMessagE(). + // + // Returns: S_OK, S_FALSE, E_INVALIDARG or E_OUTOFMEMORY. + D3DINLINE HRESULT D3DAPI GetMessage( + _In_ DXGI_DEBUG_ID Producer, + _In_ UINT64 MessageIndex, + _Out_writes_bytes_opt_(*pMessageByteLength) DXGI_INFO_QUEUE_MESSAGE* pMessage, + _Inout_ SIZE_T* pMessageByteLength) + { + return InfoQueueFunction()->GetMessage(this, + Producer, + MessageIndex, + pMessage, + pMessageByteLength); + } + + // GetNumStoredMessagesAllowedByRetrievalFilter() + // Returns how many messages that are currently in the queue which + // pass the retrieval filter. + // The MessageIndex parameter to GetMessage() indexes + // an array of this many results. + D3DINLINE UINT64 D3DAPI GetNumStoredMessagesAllowedByRetrievalFilters( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->GetNumStoredMessagesAllowedByRetrievalFilters(this, Producer); + } + + // GetNumStoredMessages() + // Returns how many messages are currently stored in the queue for the specified producer. + D3DINLINE UINT64 D3DAPI GetNumStoredMessages( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->GetNumStoredMessages(this, Producer); + } + + // GetNumMessagesDiscardedByMessageCountLimit() for the specified producer. + D3DINLINE UINT64 D3DAPI GetNumMessagesDiscardedByMessageCountLimit( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->GetNumMessagesDiscardedByMessageCountLimit(this, Producer); + } + + // GetMessageCountLimit + // This is how many messages can be stored in the queue for the specified producer. + // When the queue is full, new messages coming in push old messages out. + // -1 means there is no limit. + D3DINLINE UINT64 D3DAPI GetMessageCountLimit( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->GetMessageCountLimit(this, Producer); + } + + // GetNumMessagesAllowedByStorageFilter() + // Returns how many messages sent to the queue passed + // whatever storage filter was active upon receipt of + // the message. + // This can be a larger value than the message count limit, + // returned by GetMessageCountLimit(), since old messages are discarded + // when the queue is full to prevent overflow. + D3DINLINE UINT64 D3DAPI GetNumMessagesAllowedByStorageFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->GetNumMessagesAllowedByStorageFilter(this, Producer); + } + + // GetNumMessagesDeniedByStorageFilter() + D3DINLINE UINT64 D3DAPI GetNumMessagesDeniedByStorageFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->GetNumMessagesDeniedByStorageFilter(this, Producer); + } + + //========================================================================= + // Methods for filtering what gets stored in the queue + + // AddStorageFilterEntries() + // Adds to the existing entries at top of stack + // Returns: S_OK, E_INVALIDARG or E_OUTOFMEMORY. + D3DINLINE HRESULT D3DAPI AddStorageFilterEntries( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_FILTER* pFilter) + { + return InfoQueueFunction()->AddStorageFilterEntries(this, Producer, pFilter); + } + + // GetStorageFilter() + // Gets all entries at top of stack. + // The application must allocate the output buffer. The size required can be + // queried by passing null for pFilter and looking at the returned + // pFilterByteLength (HRESULT is S_FALSE). Note that DXGI_INFO_QUEUE_FILTER contains + // pointers - these will point to locations within the same + // contiguous buffer - *pFilterByteLength is the total storage needed for all + // data. So the application needs to only allocate/free the memory for pFilter. + // Returns S_OK, S_FALSE, E_INVALIDARG or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI GetStorageFilter( + _In_ DXGI_DEBUG_ID Producer, + _Out_writes_bytes_opt_(*pFilterByteLength) DXGI_INFO_QUEUE_FILTER* pFilter, + _Inout_ SIZE_T* pFilterByteLength) + { + return InfoQueueFunction()->GetStorageFilter(this, Producer, pFilter, pFilterByteLength); + } + + // ClearStorageFilter() + // Clears filter at the top of the stack (if there is one) + D3DINLINE void D3DAPI ClearStorageFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->ClearStorageFilter(this, Producer); + } + + // PushEmptyStorageFilter() + // Push an empty storage filter on the stack to allow local filtering changes. + // For convenience, this is automatically called by SetStorageFilter() + // if the stack is empty. Thus if the stack is not needed, filters can be + // defined without ever bothering to push or pop. + // Returns S_OK or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI PushEmptyStorageFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->PushEmptyStorageFilter(this, Producer); + } + + // PushDenyAllStorageFilter() + // Push a storage filter that denies all messages. This is for convience to + // silence all messages from a given producer. Messages that are not stored + // in the InfoQueue are not displayed to debug output. + // A deny all will be a filter with all of the severities in the deny list. + // Returns S_OK or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI PushDenyAllStorageFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->PushDenyAllStorageFilter(this, Producer); + } + + // PushCopyOfStorageFilter() + // Push a copy of the current filter so that local modifications can be made + // starting from what currently exists. + // Returns S_OK or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI PushCopyOfStorageFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->PushCopyOfStorageFilter(this, Producer); + } + + // PushStorageFilter() + // Push a filter passed as a parameter onto the stack. This is + // just a helper for calling PushEmptyStorageFilter() followed + // by AddStorageFilterEntries() + // Returns S_OK, E_INVALIDARG or E_OUTOFMEMORY. + D3DINLINE HRESULT D3DAPI PushStorageFilter( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_FILTER* pFilter) + { + return InfoQueueFunction()->PushStorageFilter(this, Producer, pFilter); + } + + // PopStorageFilter() + // Pop the current storage filter off the stack (if there is one) + D3DINLINE void D3DAPI PopStorageFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->PopStorageFilter(this, Producer); + } + + // GetStorageFilterStackSize() + D3DINLINE UINT D3DAPI GetStorageFilterStackSize( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->GetStorageFilterStackSize(this, Producer); + } + + //========================================================================= + // Methods for filtering what gets read out of the queue by GetMessage(). + + // AddRetrievalFilterEntries() + // Adds to the existing entries at top of stack + // Returns: S_OK, E_INVALIDARG or E_OUTOFMEMORY. + D3DINLINE HRESULT D3DAPI AddRetrievalFilterEntries( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_FILTER* pFilter) + { + return InfoQueueFunction()->AddRetrievalFilterEntries(this, Producer, pFilter); + } + + // GetRetrievalFilter() + // Gets all entries at top of stack. + // The application must allocate the output buffer. The size required can be + // queried by passing null for pFilter and looking at the returned + // pFilterByteLength (HRESULT is S_FALSE). Note that DXGI_INFO_QUEUE_FILTER contains + // pointers - these will point to locations within the same + // contiguous buffer - *pFilterByteLength is the total storage needed for all + // data. So the application needs to only allocate/free the memory for pFilter. + // Returns S_OK, S_FALSE, E_INVALIDARG or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI GetRetrievalFilter( + _In_ DXGI_DEBUG_ID Producer, + _Out_writes_bytes_opt_(*pFilterByteLength) DXGI_INFO_QUEUE_FILTER* pFilter, + _Inout_ SIZE_T* pFilterByteLength) + { + return InfoQueueFunction()->GetRetrievalFilter(this, Producer, pFilter, pFilterByteLength); + } + + // ClearRetrievalFilter() + // Clears filter at the top of the stack (if there is one) + D3DINLINE void D3DAPI ClearRetrievalFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->ClearRetrievalFilter(this, Producer); + } + + // PushEmptyRetrievalFilter() + // Push an empty retrieval filter on the stack to allow local filtering changes. + // For convenience, this is automatically called by SetRetrievalFilter() + // if the stack is empty. Thus if the stack is not needed, filters can be + // defined without ever bothering to push or pop. + // Returns S_OK or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI PushEmptyRetrievalFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->PushEmptyRetrievalFilter(this, Producer); + } + + // PushDenyAllRetrievalFilter() + // Push a retrieval filter that denies all messages. This is for convience to + // ignore all messages from a given producer. + // A deny all will be a filter with all of the severities in the deny list. + // Returns S_OK or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI PushDenyAllRetrievalFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->PushDenyAllRetrievalFilter(this, Producer); + } + + // PushCopyOfRetrievalFilter() + // Push a copy of the current filter so that local modifications can be made + // starting from what currently exists. + // Returns S_OK or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI PushCopyOfRetrievalFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->PushCopyOfRetrievalFilter(this, Producer); + } + + // PushRetrievalFilter() + // Push a filter passed as a parameter onto the stack. This is + // just a helper for calling PushEmptyRetrievalFilter() followed + // by AddRetrievalFilterEntries() + // Returns S_OK, E_INVALIDARG or E_OUTOFMEMORY. + D3DINLINE HRESULT D3DAPI PushRetrievalFilter( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_FILTER* pFilter) + { + return InfoQueueFunction()->PushRetrievalFilter(this, Producer, pFilter); + } + + // PopRetrievalFilter() + // Pop the current storage filter off the stack (if there is one) + D3DINLINE void D3DAPI PopRetrievalFilter( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->PopRetrievalFilter(this, Producer); + } + + // GetRetrievalFilterStackSize() + D3DINLINE UINT D3DAPI GetRetrievalFilterStackSize( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->GetRetrievalFilterStackSize(this, Producer); + } + + //========================================================================= + // Methods for adding entries to the queue. + + // AddMessage() + // This is used by DX components to log messages. Nothing stops + // applications from calling this, but it isn't particularly useful. + // If an application wishes to insert custom strings into the queue, + // AddApplicationMessage() below is suggested. See below. + // + // Returns S_OK, E_INVALIDARG or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI AddMessage( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category, + _In_ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, + _In_ DXGI_INFO_QUEUE_MESSAGE_ID ID, + _In_ LPCSTR pDescription) + { + return InfoQueueFunction()->AddMessage(this, + Producer, + Category, + Severity, + ID, + pDescription); + } + + // AddApplicationMessage() + // This is a convenience for applications that want + // to insert strings of their own into the queue, perhaps to log issues + // of its own, or to mark out points in time in the queue. This + // has the same effect as calling AddMessage() above with the + // following settings: + // Category = DXGI_INFO_QUEUE_MESSAGE_CATEGORY_APPLICATION_DEFINED + // Severity = + // ID = DXGI_INFO_QUEUE_MESSAGE_ID_STRING_FROM_APPLICATION + // pDescription = + // + // Returns S_OK, E_INVALIDARG or E_OUTOFMEMORY + D3DINLINE HRESULT D3DAPI AddApplicationMessage( + _In_ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, + _In_ LPCSTR pDescription) + { + return InfoQueueFunction()->AddApplicationMessage(this, Severity, pDescription); + } + + //========================================================================= + // Methods for breaking on errors that pass the storage filter. + D3DINLINE HRESULT D3DAPI SetBreakOnCategory( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category, + _In_ BOOL bEnable) + { + return InfoQueueFunction()->SetBreakOnCategory(this, Producer, Category, bEnable); + } + + D3DINLINE HRESULT D3DAPI SetBreakOnSeverity( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity, + _In_ BOOL bEnable) + { + return InfoQueueFunction()->SetBreakOnSeverity(this, Producer, Severity, bEnable); + } + + D3DINLINE HRESULT D3DAPI SetBreakOnID( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_ID ID, + _In_ BOOL bEnable) + { + return InfoQueueFunction()->SetBreakOnID(this, Producer, ID, bEnable); + } + + D3DINLINE BOOL D3DAPI GetBreakOnCategory( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_CATEGORY Category) + { + return InfoQueueFunction()->GetBreakOnCategory(this, Producer, Category); + } + + D3DINLINE BOOL D3DAPI GetBreakOnSeverity( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_SEVERITY Severity) + { + return InfoQueueFunction()->GetBreakOnSeverity(this, Producer, Severity); + } + + D3DINLINE BOOL D3DAPI GetBreakOnID( + _In_ DXGI_DEBUG_ID Producer, + _In_ DXGI_INFO_QUEUE_MESSAGE_ID ID) + { + return InfoQueueFunction()->GetBreakOnID(this, Producer, ID); + } + + //========================================================================= + // Methods for muting debug spew from the InfoQueue + D3DINLINE void D3DAPI SetMuteDebugOutput( + _In_ DXGI_DEBUG_ID Producer, + _In_ BOOL bMute) + { + return InfoQueueFunction()->SetMuteDebugOutput(this, Producer, bMute); + } + + D3DINLINE BOOL D3DAPI GetMuteDebugOutput( + _In_ DXGI_DEBUG_ID Producer) + { + return InfoQueueFunction()->GetMuteDebugOutput(this, Producer); + } +}; + +// +// IDXGIInfoQueue1 +// + +extern "C" +{ + struct DXGIInfoQueue1_Function_Table + { + DXGIInfoQueue_Function_Table ParentFunction; + + HRESULT(D3DAPI* RegisterMessageCallback)( + _Inout_ IDXGIInfoQueue1* pInfoQueue, + DxgiMessageFunc CallbackFunc, + DXGI_INFO_QUEUE_MESSAGE_CALLBACK_FLAGS CallbackFilterFlags, + void* pContext, + DWORD* pCallbackCookie + ); + + HRESULT(D3DAPI* UnregisterMessageCallback)( + _Inout_ IDXGIInfoQueue1* pInfoQueue, + DWORD CallbackCookie + ); + }; + +#if DECLARE_UMD_EXPORTS_DXGI + + HRESULT DxgiInfoQueue1_RegisterMessageCallback( + _Inout_ IDXGIInfoQueue1* pInfoQueue, + DxgiMessageFunc CallbackFunc, + DXGI_INFO_QUEUE_MESSAGE_CALLBACK_FLAGS CallbackFilterFlags, + void* pContext, + DWORD* pCallbackCookie + ); + + HRESULT DxgiInfoQueue1_UnregisterMessageCallback( + _Inout_ IDXGIInfoQueue1* pInfoQueue, + DWORD CallbackCookie + ); + + D3DCONST DXGIInfoQueue1_Function_Table D3D__DxgiInfoQueue1_Function_Table = + { + D3D__DxgiInfoQueue_Function_Table, + DxgiInfoQueue1_RegisterMessageCallback, + DxgiInfoQueue1_UnregisterMessageCallback, + }; + +#endif + +} // extern C + +D3DINTERFACE(IDXGIInfoQueue1, 2852dd88, b484, 4c0c, b6, b1, 67, 16, 85, 00, e6, 00) : public IDXGIInfoQueue +{ +public: + D3DINLINE DXGIInfoQueue1_Function_Table* InfoQueue1Function() + { + return (DXGIInfoQueue1_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT RegisterMessageCallback( + DxgiMessageFunc CallbackFunc, + DXGI_INFO_QUEUE_MESSAGE_CALLBACK_FLAGS CallbackFilterFlags, + void* pContext, + DWORD * pCallbackCookie + ) + { + return InfoQueue1Function()->RegisterMessageCallback(this, CallbackFunc, CallbackFilterFlags, pContext, pCallbackCookie); + } + + D3DINLINE HRESULT UnregisterMessageCallback( + DWORD CallbackCookie + ) + { + return InfoQueue1Function()->UnregisterMessageCallback(this, CallbackCookie); + } +}; + +extern "C" +{ + +// +// IDXGIOutput +// + +struct DXGIOutput_Function_Table +{ + DXGIObject_Function_Table ObjectFunction; + + HRESULT (D3DAPI* GetDesc)( + _Inout_ IDXGIOutput* pOutput, + _Out_ DXGI_OUTPUT_DESC *pDesc); + + HRESULT (D3DAPI* GetDisplayModeList)( + _Inout_ IDXGIOutput* pOutput, + _In_ DXGI_FORMAT EnumFormat, + _In_ UINT Flags, + _Inout_ UINT * pNumModes, + _Out_writes_to_opt_(*pNumModes,*pNumModes) DXGI_MODE_DESC *pDesc); + + HRESULT (D3DAPI* FindClosestMatchingMode)( + _Inout_ IDXGIOutput* pOutput, + _In_ const DXGI_MODE_DESC *pModeToMatch, + _Out_ DXGI_MODE_DESC *pClosestMatch, + _In_opt_ IUnknown * pConcernedDevice); + + HRESULT (D3DAPI* WaitForVBlank)( + _Inout_ IDXGIOutput* pOutput); + + HRESULT (D3DAPI* TakeOwnership)( + _Inout_ IDXGIOutput* pOutput, + _In_ IUnknown *pDevice, + BOOL Exclusive); + + void (D3DAPI* ReleaseOwnership)( + _Inout_ IDXGIOutput* pOutput); + + HRESULT (D3DAPI* GetGammaControlCapabilities)( + _Inout_ IDXGIOutput* pOutput, + _Out_ DXGI_GAMMA_CONTROL_CAPABILITIES *pGammaCaps); + + HRESULT (D3DAPI* SetGammaControl)( + _Inout_ IDXGIOutput* pOutput, + _In_ const DXGI_GAMMA_CONTROL *pArray); + + HRESULT (D3DAPI* GetGammaControl)( + _Inout_ IDXGIOutput* pOutput, + _Out_ DXGI_GAMMA_CONTROL *pArray); + + HRESULT (D3DAPI* SetDisplaySurface)( + _Inout_ IDXGIOutput* pOutput, + _In_ IDXGISurface *pScanoutSurface); + + HRESULT (D3DAPI* GetDisplaySurfaceData)( + _Inout_ IDXGIOutput* pOutput, + _In_ IDXGISurface *pDestination); + + HRESULT (D3DAPI* GetFrameStatistics)( + _Inout_ IDXGIOutput* pOutput, + _Out_ DXGI_FRAME_STATISTICS *pStats); + + HRESULT (D3DAPI* GetRefreshRate)( + _Inout_ IDXGIOutput* pOutput, + _Out_ DXGI_RATIONAL* pRefreshRate); + + HRESULT (D3DAPI* GetAspectRatio)( + _Inout_ IDXGIOutput* pOutput, + _Out_ DXGI_RATIONAL* pAspectRatio); + + HRESULT (D3DAPI* GetDisplayModeListX)( + _Inout_ IDXGIOutput* pOutput, + _In_ DXGI_FORMAT EnumFormat, + _In_ UINT Flags, + _Inout_ UINT * pNumModes, + _Out_writes_to_opt_(*pNumModes,*pNumModes) DXGIXBOX_MODE_DESC *pDesc); +}; + + +} + +D3DINTERFACE(IDXGIOutput, ae02eedb,c735,4690,8d,52,5a,8d,c2,02,13,aa) : public IDXGIObject +{ +public: + + D3DINLINE DXGIOutput_Function_Table* OutputFunction() + { + return (DXGIOutput_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetDesc( _Out_ DXGI_OUTPUT_DESC *pDesc ) + { + return OutputFunction()->GetDesc( this, pDesc ); + } + + D3DINLINE HRESULT D3DAPI GetDisplayModeList( + _In_ DXGI_FORMAT EnumFormat, + _In_ UINT Flags, + _Inout_ UINT * pNumModes, + _Out_writes_to_opt_(*pNumModes,*pNumModes) DXGI_MODE_DESC *pDesc) + { + return OutputFunction()->GetDisplayModeList( this, EnumFormat, Flags, pNumModes, pDesc ); + } + + D3DINLINE HRESULT D3DAPI FindClosestMatchingMode( + _In_ const DXGI_MODE_DESC *pModeToMatch, + _Out_ DXGI_MODE_DESC *pClosestMatch, + _In_opt_ IUnknown * pConcernedDevice ) + { + return OutputFunction()->FindClosestMatchingMode( this, pModeToMatch, pClosestMatch, pConcernedDevice ); + } + + D3DINLINE HRESULT D3DAPI WaitForVBlank() + { + return OutputFunction()->WaitForVBlank( this ); + } + + D3DINLINE HRESULT D3DAPI TakeOwnership( + _In_ IUnknown *pDevice, + BOOL Exclusive ) + { + return OutputFunction()->TakeOwnership( this, pDevice, Exclusive ); + } + + D3DINLINE void D3DAPI ReleaseOwnership() + { + return OutputFunction()->ReleaseOwnership( this ); + } + + //The following methods can only be called when this output is owned by a device. + D3DINLINE HRESULT D3DAPI GetGammaControlCapabilities( _Out_ DXGI_GAMMA_CONTROL_CAPABILITIES *pGammaCaps ) + { + return OutputFunction()->GetGammaControlCapabilities( this, pGammaCaps ); + } + + D3DINLINE HRESULT D3DAPI SetGammaControl( _In_ const DXGI_GAMMA_CONTROL *pArray ) + { + return OutputFunction()->SetGammaControl( this, pArray ); + } + + D3DINLINE HRESULT D3DAPI GetGammaControl( _Out_ DXGI_GAMMA_CONTROL *pArray ) + { + return OutputFunction()->GetGammaControl( this, pArray ); + } + + D3DINLINE HRESULT D3DAPI SetDisplaySurface( _In_ IDXGISurface *pScanoutSurface ) + { + return OutputFunction()->SetDisplaySurface( this, pScanoutSurface ); + } + + D3DINLINE HRESULT D3DAPI GetDisplaySurfaceData( _In_ IDXGISurface *pDestination ) + { + return OutputFunction()->GetDisplaySurfaceData( this, pDestination ); + } + + D3DINLINE HRESULT D3DAPI GetFrameStatistics( _Out_ DXGI_FRAME_STATISTICS *pStats ) + { + return OutputFunction()->GetFrameStatistics( this, pStats ); + } + + D3DINLINE HRESULT D3DAPI GetRefreshRate( + _Out_ DXGI_RATIONAL* pRefreshRate) + { + return OutputFunction()->GetRefreshRate( this, pRefreshRate ); + } + + D3DINLINE HRESULT D3DAPI GetAspectRatio( + _Out_ DXGI_RATIONAL* pAspectRatio) + { + return OutputFunction()->GetAspectRatio( this, pAspectRatio ); + } + + D3DINLINE HRESULT D3DAPI GetDisplayModeListX( + _In_ DXGI_FORMAT EnumFormat, + _In_ UINT Flags, + _Inout_ UINT * pNumModes, + _Out_writes_to_opt_(*pNumModes,*pNumModes) DXGIXBOX_MODE_DESC *pDesc) + { + return OutputFunction()->GetDisplayModeListX( this, EnumFormat, Flags, pNumModes, pDesc ); + } +}; + + +// 10.0 + +extern "C" +{ + +// +// Forward Declarations +// + +struct ID3D10Blob; +struct ID3DInclude; + +} + +#ifndef _D3D10_CONSTANTS +#define _D3D10_CONSTANTS + +const UINT D3D10_16BIT_INDEX_STRIP_CUT_VALUE = 0xffff; +const UINT D3D10_32BIT_INDEX_STRIP_CUT_VALUE = 0xffffffff; +const UINT D3D10_8BIT_INDEX_STRIP_CUT_VALUE = 0xff; +const UINT D3D10_ARRAY_AXIS_ADDRESS_RANGE_BIT_COUNT = 9; +const UINT D3D10_CLIP_OR_CULL_DISTANCE_COUNT = 8; +const UINT D3D10_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT = 2; +const UINT D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT = 14; +const UINT D3D10_COMMONSHADER_CONSTANT_BUFFER_COMPONENTS = 4; +const UINT D3D10_COMMONSHADER_CONSTANT_BUFFER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_COMMONSHADER_CONSTANT_BUFFER_HW_SLOT_COUNT = 15; +const UINT D3D10_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COMPONENTS = 4; +const UINT D3D10_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COUNT = 15; +const UINT D3D10_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READS_PER_INST = 1; +const UINT D3D10_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READ_PORTS = 1; +const UINT D3D10_COMMONSHADER_FLOWCONTROL_NESTING_LIMIT = 64; +const UINT D3D10_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COMPONENTS = 4; +const UINT D3D10_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COUNT = 1; +const UINT D3D10_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READS_PER_INST = 1; +const UINT D3D10_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READ_PORTS = 1; +const UINT D3D10_COMMONSHADER_IMMEDIATE_VALUE_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_COMMONSHADER_INPUT_RESOURCE_REGISTER_COMPONENTS = 1; +const UINT D3D10_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT = 128; +const UINT D3D10_COMMONSHADER_INPUT_RESOURCE_REGISTER_READS_PER_INST = 1; +const UINT D3D10_COMMONSHADER_INPUT_RESOURCE_REGISTER_READ_PORTS = 1; +const UINT D3D10_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT = 128; +const UINT D3D10_COMMONSHADER_SAMPLER_REGISTER_COMPONENTS = 1; +const UINT D3D10_COMMONSHADER_SAMPLER_REGISTER_COUNT = 16; +const UINT D3D10_COMMONSHADER_SAMPLER_REGISTER_READS_PER_INST = 1; +const UINT D3D10_COMMONSHADER_SAMPLER_REGISTER_READ_PORTS = 1; +const UINT D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT = 16; +const UINT D3D10_COMMONSHADER_SUBROUTINE_NESTING_LIMIT = 32; +const UINT D3D10_COMMONSHADER_TEMP_REGISTER_COMPONENTS = 4; +const UINT D3D10_COMMONSHADER_TEMP_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_COMMONSHADER_TEMP_REGISTER_COUNT = 4096; +const UINT D3D10_COMMONSHADER_TEMP_REGISTER_READS_PER_INST = 3; +const UINT D3D10_COMMONSHADER_TEMP_REGISTER_READ_PORTS = 3; +const UINT D3D10_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MAX = 10; +const INT D3D10_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MIN = -10; +const INT D3D10_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE = -8; +const UINT D3D10_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE = 7; +#define D3D10_DEFAULT_BLEND_FACTOR_ALPHA ( 1.0f ) +#define D3D10_DEFAULT_BLEND_FACTOR_BLUE ( 1.0f ) +#define D3D10_DEFAULT_BLEND_FACTOR_GREEN ( 1.0f ) +#define D3D10_DEFAULT_BLEND_FACTOR_RED ( 1.0f ) +#define D3D10_DEFAULT_BORDER_COLOR_COMPONENT ( 0.0f ) +const UINT D3D10_DEFAULT_DEPTH_BIAS = 0; +#define D3D10_DEFAULT_DEPTH_BIAS_CLAMP ( 0.0f ) +#define D3D10_DEFAULT_MAX_ANISOTROPY ( 16.0f ) +#define D3D10_DEFAULT_MIP_LOD_BIAS ( 0.0f ) +const UINT D3D10_DEFAULT_RENDER_TARGET_ARRAY_INDEX = 0; +const UINT D3D10_DEFAULT_SAMPLE_MASK = 0xffffffff; +const UINT D3D10_DEFAULT_SCISSOR_ENDX = 0; +const UINT D3D10_DEFAULT_SCISSOR_ENDY = 0; +const UINT D3D10_DEFAULT_SCISSOR_STARTX = 0; +const UINT D3D10_DEFAULT_SCISSOR_STARTY = 0; +#define D3D10_DEFAULT_SLOPE_SCALED_DEPTH_BIAS ( 0.0f ) +const UINT D3D10_DEFAULT_STENCIL_READ_MASK = 0xff; +const UINT D3D10_DEFAULT_STENCIL_REFERENCE = 0; +const UINT D3D10_DEFAULT_STENCIL_WRITE_MASK = 0xff; +const UINT D3D10_DEFAULT_VIEWPORT_AND_SCISSORRECT_INDEX = 0; +const UINT D3D10_DEFAULT_VIEWPORT_HEIGHT = 0; +#define D3D10_DEFAULT_VIEWPORT_MAX_DEPTH ( 0.0f ) +#define D3D10_DEFAULT_VIEWPORT_MIN_DEPTH ( 0.0f ) +const UINT D3D10_DEFAULT_VIEWPORT_TOPLEFTX = 0; +const UINT D3D10_DEFAULT_VIEWPORT_TOPLEFTY = 0; +const UINT D3D10_DEFAULT_VIEWPORT_WIDTH = 0; +#define D3D10_FLOAT16_FUSED_TOLERANCE_IN_ULP ( 0.6 ) +#define D3D10_FLOAT32_MAX ( 3.402823466e+38f ) +#define D3D10_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP ( 0.6f ) +#define D3D10_FLOAT_TO_SRGB_EXPONENT_DENOMINATOR ( 2.4f ) +#define D3D10_FLOAT_TO_SRGB_EXPONENT_NUMERATOR ( 1.0f ) +#define D3D10_FLOAT_TO_SRGB_OFFSET ( 0.055f ) +#define D3D10_FLOAT_TO_SRGB_SCALE_1 ( 12.92f ) +#define D3D10_FLOAT_TO_SRGB_SCALE_2 ( 1.055f ) +#define D3D10_FLOAT_TO_SRGB_THRESHOLD ( 0.0031308f ) +#define D3D10_FTOI_INSTRUCTION_MAX_INPUT ( 2147483647.999f ) +#define D3D10_FTOI_INSTRUCTION_MIN_INPUT ( -2147483648.999f ) +#define D3D10_FTOU_INSTRUCTION_MAX_INPUT ( 4294967295.999f ) +#define D3D10_FTOU_INSTRUCTION_MIN_INPUT ( 0.0f ) +const UINT D3D10_GS_INPUT_PRIM_CONST_REGISTER_COMPONENTS = 1; +const UINT D3D10_GS_INPUT_PRIM_CONST_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_GS_INPUT_PRIM_CONST_REGISTER_COUNT = 1; +const UINT D3D10_GS_INPUT_PRIM_CONST_REGISTER_READS_PER_INST = 2; +const UINT D3D10_GS_INPUT_PRIM_CONST_REGISTER_READ_PORTS = 1; +const UINT D3D10_GS_INPUT_REGISTER_COMPONENTS = 4; +const UINT D3D10_GS_INPUT_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_GS_INPUT_REGISTER_COUNT = 16; +const UINT D3D10_GS_INPUT_REGISTER_READS_PER_INST = 2; +const UINT D3D10_GS_INPUT_REGISTER_READ_PORTS = 1; +const UINT D3D10_GS_INPUT_REGISTER_VERTICES = 6; +const UINT D3D10_GS_OUTPUT_ELEMENTS = 32; +const UINT D3D10_GS_OUTPUT_REGISTER_COMPONENTS = 4; +const UINT D3D10_GS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_GS_OUTPUT_REGISTER_COUNT = 32; +const UINT D3D10_IA_DEFAULT_INDEX_BUFFER_OFFSET_IN_BYTES = 0; +const UINT D3D10_IA_DEFAULT_PRIMITIVE_TOPOLOGY = 0; +const UINT D3D10_IA_DEFAULT_VERTEX_BUFFER_OFFSET_IN_BYTES = 0; +const UINT D3D10_IA_INDEX_INPUT_RESOURCE_SLOT_COUNT = 1; +const UINT D3D10_IA_INSTANCE_ID_BIT_COUNT = 32; +const UINT D3D10_IA_INTEGER_ARITHMETIC_BIT_COUNT = 32; +const UINT D3D10_IA_PRIMITIVE_ID_BIT_COUNT = 32; +const UINT D3D10_IA_VERTEX_ID_BIT_COUNT = 32; +const UINT D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT = 16; +const UINT D3D10_IA_VERTEX_INPUT_STRUCTURE_ELEMENTS_COMPONENTS = 64; +const UINT D3D10_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT = 16; +const UINT D3D10_INTEGER_DIVIDE_BY_ZERO_QUOTIENT = 0xffffffff; +const UINT D3D10_INTEGER_DIVIDE_BY_ZERO_REMAINDER = 0xffffffff; +#define D3D10_LINEAR_GAMMA ( 1.0f ) +#define D3D10_MAX_BORDER_COLOR_COMPONENT ( 1.0f ) +#define D3D10_MAX_DEPTH ( 1.0f ) +const UINT D3D10_MAX_MAXANISOTROPY = 16; +const UINT D3D10_MAX_MULTISAMPLE_SAMPLE_COUNT = 32; +#define D3D10_MAX_POSITION_VALUE ( 3.402823466e+34f ) +const UINT D3D10_MAX_TEXTURE_DIMENSION_2_TO_EXP = 17; +#define D3D10_MIN_BORDER_COLOR_COMPONENT ( 0.0f ) +#define D3D10_MIN_DEPTH ( 0.0f ) +const UINT D3D10_MIN_MAXANISOTROPY = 0; +#define D3D10_MIP_LOD_BIAS_MAX ( 15.99f ) +#define D3D10_MIP_LOD_BIAS_MIN ( -16.0f ) +const UINT D3D10_MIP_LOD_FRACTIONAL_BIT_COUNT = 6; +const UINT D3D10_MIP_LOD_RANGE_BIT_COUNT = 8; +#define D3D10_MULTISAMPLE_ANTIALIAS_LINE_WIDTH ( 1.4f ) +const UINT D3D10_NONSAMPLE_FETCH_OUT_OF_RANGE_ACCESS_RESULT = 0; +const UINT D3D10_PIXEL_ADDRESS_RANGE_BIT_COUNT = 13; +const UINT D3D10_PRE_SCISSOR_PIXEL_ADDRESS_RANGE_BIT_COUNT = 15; +const UINT D3D10_PS_FRONTFACING_DEFAULT_VALUE = 0xFFFFFFFF; +const UINT D3D10_PS_FRONTFACING_FALSE_VALUE = 0x00000000; +const UINT D3D10_PS_FRONTFACING_TRUE_VALUE = 0xFFFFFFFF; +const UINT D3D10_PS_INPUT_REGISTER_COMPONENTS = 4; +const UINT D3D10_PS_INPUT_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_PS_INPUT_REGISTER_COUNT = 32; +const UINT D3D10_PS_INPUT_REGISTER_READS_PER_INST = 2; +const UINT D3D10_PS_INPUT_REGISTER_READ_PORTS = 1; +#define D3D10_PS_LEGACY_PIXEL_CENTER_FRACTIONAL_COMPONENT ( 0.0f ) +const UINT D3D10_PS_OUTPUT_DEPTH_REGISTER_COMPONENTS = 1; +const UINT D3D10_PS_OUTPUT_DEPTH_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_PS_OUTPUT_DEPTH_REGISTER_COUNT = 1; +const UINT D3D10_PS_OUTPUT_REGISTER_COMPONENTS = 4; +const UINT D3D10_PS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_PS_OUTPUT_REGISTER_COUNT = 8; +#define D3D10_PS_PIXEL_CENTER_FRACTIONAL_COMPONENT ( 0.5f ) +const UINT D3D10_REQ_BLEND_OBJECT_COUNT_PER_CONTEXT = 4096; +const UINT D3D10_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP = 27; +const UINT D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT = 4096; +const UINT D3D10_REQ_DEPTH_STENCIL_OBJECT_COUNT_PER_CONTEXT = 4096; +const UINT D3D10_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP = 32; +const UINT D3D10_REQ_DRAW_VERTEX_COUNT_2_TO_EXP = 32; +const UINT D3D10_REQ_FILTERING_HW_ADDRESSABLE_RESOURCE_DIMENSION = 8192; +const UINT D3D10_REQ_GS_INVOCATION_32BIT_OUTPUT_COMPONENT_LIMIT = 1024; +const UINT D3D10_REQ_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT = 4096; +const UINT D3D10_REQ_MAXANISOTROPY = 16; +const UINT D3D10_REQ_MIP_LEVELS = 14; +const UINT D3D10_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES = 2048; +const UINT D3D10_REQ_RASTERIZER_OBJECT_COUNT_PER_CONTEXT = 4096; +const UINT D3D10_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH = 8192; +const UINT D3D10_REQ_RESOURCE_SIZE_IN_MEGABYTES = 128; +const UINT D3D10_REQ_RESOURCE_VIEW_COUNT_PER_CONTEXT_2_TO_EXP = 20; +const UINT D3D10_REQ_SAMPLER_OBJECT_COUNT_PER_CONTEXT = 4096; +const UINT D3D10_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION = 512; +const UINT D3D10_REQ_TEXTURE1D_U_DIMENSION = 8192; +const UINT D3D10_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION = 512; +const UINT D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION = 8192; +const UINT D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION = 2048; +const UINT D3D10_REQ_TEXTURECUBE_DIMENSION = 8192; +const UINT D3D10_RESINFO_INSTRUCTION_MISSING_COMPONENT_RETVAL = 0; +const UINT D3D10_SHADER_MAJOR_VERSION = 4; +const UINT D3D10_SHADER_MINOR_VERSION = 0; +const UINT D3D10_SHIFT_INSTRUCTION_PAD_VALUE = 0; +const UINT D3D10_SHIFT_INSTRUCTION_SHIFT_VALUE_BIT_COUNT = 5; +const UINT D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT = 8; +const UINT D3D10_SO_BUFFER_MAX_STRIDE_IN_BYTES = 2048; +const UINT D3D10_SO_BUFFER_MAX_WRITE_WINDOW_IN_BYTES = 256; +const UINT D3D10_SO_BUFFER_SLOT_COUNT = 4; +const UINT D3D10_SO_DDI_REGISTER_INDEX_DENOTING_GAP = 0xffffffff; +const UINT D3D10_SO_MULTIPLE_BUFFER_ELEMENTS_PER_BUFFER = 1; +const UINT D3D10_SO_SINGLE_BUFFER_COMPONENT_LIMIT = 64; +#define D3D10_SRGB_GAMMA ( 2.2f ) +#define D3D10_SRGB_TO_FLOAT_DENOMINATOR_1 ( 12.92f ) +#define D3D10_SRGB_TO_FLOAT_DENOMINATOR_2 ( 1.055f ) +#define D3D10_SRGB_TO_FLOAT_EXPONENT ( 2.4f ) +#define D3D10_SRGB_TO_FLOAT_OFFSET ( 0.055f ) +#define D3D10_SRGB_TO_FLOAT_THRESHOLD ( 0.04045f ) +#define D3D10_SRGB_TO_FLOAT_TOLERANCE_IN_ULP ( 0.5f ) +const UINT D3D10_STANDARD_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_STANDARD_COMPONENT_BIT_COUNT_DOUBLED = 64; +const UINT D3D10_STANDARD_MAXIMUM_ELEMENT_ALIGNMENT_BYTE_MULTIPLE = 4; +const UINT D3D10_STANDARD_PIXEL_COMPONENT_COUNT = 128; +const UINT D3D10_STANDARD_PIXEL_ELEMENT_COUNT = 32; +const UINT D3D10_STANDARD_VECTOR_SIZE = 4; +const UINT D3D10_STANDARD_VERTEX_ELEMENT_COUNT = 16; +const UINT D3D10_STANDARD_VERTEX_TOTAL_COMPONENT_COUNT = 64; +const UINT D3D10_SUBPIXEL_FRACTIONAL_BIT_COUNT = 8; +const UINT D3D10_SUBTEXEL_FRACTIONAL_BIT_COUNT = 6; +const UINT D3D10_TEXEL_ADDRESS_RANGE_BIT_COUNT = 18; +const UINT D3D10_UNBOUND_MEMORY_ACCESS_RESULT = 0; +const UINT D3D10_VIEWPORT_AND_SCISSORRECT_MAX_INDEX = 15; +const UINT D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE = 16; +const UINT D3D10_VIEWPORT_BOUNDS_MAX = 16383; +const INT D3D10_VIEWPORT_BOUNDS_MIN = -16384; +const UINT D3D10_VS_INPUT_REGISTER_COMPONENTS = 4; +const UINT D3D10_VS_INPUT_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_VS_INPUT_REGISTER_COUNT = 16; +const UINT D3D10_VS_INPUT_REGISTER_READS_PER_INST = 2; +const UINT D3D10_VS_INPUT_REGISTER_READ_PORTS = 1; +const UINT D3D10_VS_OUTPUT_REGISTER_COMPONENTS = 4; +const UINT D3D10_VS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_VS_OUTPUT_REGISTER_COUNT = 16; +const UINT D3D10_WHQL_CONTEXT_COUNT_FOR_RESOURCE_LIMIT = 10; +const UINT D3D10_WHQL_DRAWINDEXED_INDEX_COUNT_2_TO_EXP = 25; +const UINT D3D10_WHQL_DRAW_VERTEX_COUNT_2_TO_EXP = 25; + +#endif + +#ifndef _D3D10_1_CONSTANTS +#define _D3D10_1_CONSTANTS + +const UINT D3D10_1_DEFAULT_SAMPLE_MASK = 0xffffffff; +#define D3D10_1_FLOAT16_FUSED_TOLERANCE_IN_ULP ( 0.6 ) +#define D3D10_1_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP ( 0.6f ) +const UINT D3D10_1_GS_INPUT_REGISTER_COUNT = 32; +const UINT D3D10_1_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT = 32; +const UINT D3D10_1_IA_VERTEX_INPUT_STRUCTURE_ELEMENTS_COMPONENTS = 128; +const UINT D3D10_1_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT = 32; +const UINT D3D10_1_PS_OUTPUT_MASK_REGISTER_COMPONENTS = 1; +const UINT D3D10_1_PS_OUTPUT_MASK_REGISTER_COMPONENT_BIT_COUNT = 32; +const UINT D3D10_1_PS_OUTPUT_MASK_REGISTER_COUNT = 1; +const UINT D3D10_1_SHADER_MAJOR_VERSION = 4; +const UINT D3D10_1_SHADER_MINOR_VERSION = 1; +const UINT D3D10_1_SO_BUFFER_MAX_STRIDE_IN_BYTES = 2048; +const UINT D3D10_1_SO_BUFFER_MAX_WRITE_WINDOW_IN_BYTES = 256; +const UINT D3D10_1_SO_BUFFER_SLOT_COUNT = 4; +const UINT D3D10_1_SO_MULTIPLE_BUFFER_ELEMENTS_PER_BUFFER = 1; +const UINT D3D10_1_SO_SINGLE_BUFFER_COMPONENT_LIMIT = 64; +const UINT D3D10_1_STANDARD_VERTEX_ELEMENT_COUNT = 32; +const UINT D3D10_1_SUBPIXEL_FRACTIONAL_BIT_COUNT = 8; +const UINT D3D10_1_VS_INPUT_REGISTER_COUNT = 32; +const UINT D3D10_1_VS_OUTPUT_REGISTER_COUNT = 32; + +#endif + +// 11.0 + +// +// Constants +// + +#ifndef _D3D11_CONSTANTS +#define _D3D11_CONSTANTS + +#define D3D11_16BIT_INDEX_STRIP_CUT_VALUE ( 0xffff ) + +#define D3D11_32BIT_INDEX_STRIP_CUT_VALUE ( 0xffffffff ) + +#define D3D11_8BIT_INDEX_STRIP_CUT_VALUE ( 0xff ) + +#define D3D11_ARRAY_AXIS_ADDRESS_RANGE_BIT_COUNT ( 9 ) + +#define D3D11_CLIP_OR_CULL_DISTANCE_COUNT ( 8 ) + +#define D3D11_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT ( 2 ) + +#define D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ( 14 ) + +#define D3D11_COMMONSHADER_CONSTANT_BUFFER_COMPONENTS ( 4 ) + +#define D3D11_COMMONSHADER_CONSTANT_BUFFER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_COMMONSHADER_CONSTANT_BUFFER_HW_SLOT_COUNT ( 15 ) + +#define D3D11_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT ( 16 ) + +#define D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COUNT ( 15 ) + +#define D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READS_PER_INST ( 1 ) + +#define D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_COMMONSHADER_FLOWCONTROL_NESTING_LIMIT ( 64 ) + +#define D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COUNT ( 1 ) + +#define D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READS_PER_INST ( 1 ) + +#define D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_COMMONSHADER_IMMEDIATE_VALUE_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT ( 128 ) + +#define D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_READS_PER_INST ( 1 ) + +#define D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ( 128 ) + +#define D3D11_COMMONSHADER_SAMPLER_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_COMMONSHADER_SAMPLER_REGISTER_COUNT ( 16 ) + +#define D3D11_COMMONSHADER_SAMPLER_REGISTER_READS_PER_INST ( 1 ) + +#define D3D11_COMMONSHADER_SAMPLER_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT ( 16 ) + +#define D3D11_COMMONSHADER_SUBROUTINE_NESTING_LIMIT ( 32 ) + +#define D3D11_COMMONSHADER_TEMP_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_COMMONSHADER_TEMP_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_COMMONSHADER_TEMP_REGISTER_COUNT ( 4096 ) + +#define D3D11_COMMONSHADER_TEMP_REGISTER_READS_PER_INST ( 3 ) + +#define D3D11_COMMONSHADER_TEMP_REGISTER_READ_PORTS ( 3 ) + +#define D3D11_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MAX ( 10 ) + +#define D3D11_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MIN ( -10 ) + +#define D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE ( -8 ) + +#define D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE ( 7 ) + +#define D3D11_CS_4_X_BUCKET00_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 256 ) + +#define D3D11_CS_4_X_BUCKET00_MAX_NUM_THREADS_PER_GROUP ( 64 ) + +#define D3D11_CS_4_X_BUCKET01_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 240 ) + +#define D3D11_CS_4_X_BUCKET01_MAX_NUM_THREADS_PER_GROUP ( 68 ) + +#define D3D11_CS_4_X_BUCKET02_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 224 ) + +#define D3D11_CS_4_X_BUCKET02_MAX_NUM_THREADS_PER_GROUP ( 72 ) + +#define D3D11_CS_4_X_BUCKET03_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 208 ) + +#define D3D11_CS_4_X_BUCKET03_MAX_NUM_THREADS_PER_GROUP ( 76 ) + +#define D3D11_CS_4_X_BUCKET04_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 192 ) + +#define D3D11_CS_4_X_BUCKET04_MAX_NUM_THREADS_PER_GROUP ( 84 ) + +#define D3D11_CS_4_X_BUCKET05_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 176 ) + +#define D3D11_CS_4_X_BUCKET05_MAX_NUM_THREADS_PER_GROUP ( 92 ) + +#define D3D11_CS_4_X_BUCKET06_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 160 ) + +#define D3D11_CS_4_X_BUCKET06_MAX_NUM_THREADS_PER_GROUP ( 100 ) + +#define D3D11_CS_4_X_BUCKET07_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 144 ) + +#define D3D11_CS_4_X_BUCKET07_MAX_NUM_THREADS_PER_GROUP ( 112 ) + +#define D3D11_CS_4_X_BUCKET08_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 128 ) + +#define D3D11_CS_4_X_BUCKET08_MAX_NUM_THREADS_PER_GROUP ( 128 ) + +#define D3D11_CS_4_X_BUCKET09_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 112 ) + +#define D3D11_CS_4_X_BUCKET09_MAX_NUM_THREADS_PER_GROUP ( 144 ) + +#define D3D11_CS_4_X_BUCKET10_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 96 ) + +#define D3D11_CS_4_X_BUCKET10_MAX_NUM_THREADS_PER_GROUP ( 168 ) + +#define D3D11_CS_4_X_BUCKET11_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 80 ) + +#define D3D11_CS_4_X_BUCKET11_MAX_NUM_THREADS_PER_GROUP ( 204 ) + +#define D3D11_CS_4_X_BUCKET12_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 64 ) + +#define D3D11_CS_4_X_BUCKET12_MAX_NUM_THREADS_PER_GROUP ( 256 ) + +#define D3D11_CS_4_X_BUCKET13_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 48 ) + +#define D3D11_CS_4_X_BUCKET13_MAX_NUM_THREADS_PER_GROUP ( 340 ) + +#define D3D11_CS_4_X_BUCKET14_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 32 ) + +#define D3D11_CS_4_X_BUCKET14_MAX_NUM_THREADS_PER_GROUP ( 512 ) + +#define D3D11_CS_4_X_BUCKET15_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 16 ) + +#define D3D11_CS_4_X_BUCKET15_MAX_NUM_THREADS_PER_GROUP ( 768 ) + +#define D3D11_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION ( 1 ) + +#define D3D11_CS_4_X_RAW_UAV_BYTE_ALIGNMENT ( 256 ) + +#define D3D11_CS_4_X_THREAD_GROUP_MAX_THREADS_PER_GROUP ( 768 ) + +#define D3D11_CS_4_X_THREAD_GROUP_MAX_X ( 768 ) + +#define D3D11_CS_4_X_THREAD_GROUP_MAX_Y ( 768 ) + +#define D3D11_CS_4_X_UAV_REGISTER_COUNT ( 1 ) + +#define D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION ( 65535 ) + +#define D3D11_CS_TGSM_REGISTER_COUNT ( 8192 ) + +#define D3D11_CS_TGSM_REGISTER_COUNT_CI (8192 * 2); + +#define D3D11_CS_TGSM_REGISTER_READS_PER_INST ( 1 ) + +#define D3D11_CS_TGSM_RESOURCE_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_CS_TGSM_RESOURCE_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_CS_THREADGROUPID_REGISTER_COMPONENTS ( 3 ) + +#define D3D11_CS_THREADGROUPID_REGISTER_COUNT ( 1 ) + +#define D3D11_CS_THREADIDINGROUPFLATTENED_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_CS_THREADIDINGROUPFLATTENED_REGISTER_COUNT ( 1 ) + +#define D3D11_CS_THREADIDINGROUP_REGISTER_COMPONENTS ( 3 ) + +#define D3D11_CS_THREADIDINGROUP_REGISTER_COUNT ( 1 ) + +#define D3D11_CS_THREADID_REGISTER_COMPONENTS ( 3 ) + +#define D3D11_CS_THREADID_REGISTER_COUNT ( 1 ) + +#define D3D11_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP ( 1024 ) + +#define D3D11_CS_THREAD_GROUP_MAX_X ( 1024 ) + +#define D3D11_CS_THREAD_GROUP_MAX_Y ( 1024 ) + +#define D3D11_CS_THREAD_GROUP_MAX_Z ( 64 ) + +#define D3D11_CS_THREAD_GROUP_MIN_X ( 1 ) + +#define D3D11_CS_THREAD_GROUP_MIN_Y ( 1 ) + +#define D3D11_CS_THREAD_GROUP_MIN_Z ( 1 ) + +#define D3D11_CS_THREAD_LOCAL_TEMP_REGISTER_POOL ( 16384 ) + +#define D3D11_DEFAULT_BLEND_FACTOR_ALPHA ( 1.0f ) +#define D3D11_DEFAULT_BLEND_FACTOR_BLUE ( 1.0f ) +#define D3D11_DEFAULT_BLEND_FACTOR_GREEN ( 1.0f ) +#define D3D11_DEFAULT_BLEND_FACTOR_RED ( 1.0f ) +#define D3D11_DEFAULT_BORDER_COLOR_COMPONENT ( 0.0f ) +#define D3D11_DEFAULT_DEPTH_BIAS ( 0 ) + +#define D3D11_DEFAULT_DEPTH_BIAS_CLAMP ( 0.0f ) +#define D3D11_DEFAULT_MAX_ANISOTROPY ( 16 ) + +#define D3D11_DEFAULT_MIP_LOD_BIAS ( 0.0f ) +#define D3D11_DEFAULT_RENDER_TARGET_ARRAY_INDEX ( 0 ) + +#define D3D11_DEFAULT_SAMPLE_MASK ( 0xffffffff ) + +#define D3D11_DEFAULT_SCISSOR_ENDX ( 0 ) + +#define D3D11_DEFAULT_SCISSOR_ENDY ( 0 ) + +#define D3D11_DEFAULT_SCISSOR_STARTX ( 0 ) + +#define D3D11_DEFAULT_SCISSOR_STARTY ( 0 ) + +#define D3D11_DEFAULT_SLOPE_SCALED_DEPTH_BIAS ( 0.0f ) +#define D3D11_DEFAULT_STENCIL_READ_MASK ( 0xff ) + +#define D3D11_DEFAULT_STENCIL_REFERENCE ( 0 ) + +#define D3D11_DEFAULT_STENCIL_WRITE_MASK ( 0xff ) + +#define D3D11_DEFAULT_VIEWPORT_AND_SCISSORRECT_INDEX ( 0 ) + +#define D3D11_DEFAULT_VIEWPORT_HEIGHT ( 0 ) + +#define D3D11_DEFAULT_VIEWPORT_MAX_DEPTH ( 0.0f ) +#define D3D11_DEFAULT_VIEWPORT_MIN_DEPTH ( 0.0f ) +#define D3D11_DEFAULT_VIEWPORT_TOPLEFTX ( 0 ) + +#define D3D11_DEFAULT_VIEWPORT_TOPLEFTY ( 0 ) + +#define D3D11_DEFAULT_VIEWPORT_WIDTH ( 0 ) + +#define D3D11_DS_INPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS ( 3968 ) + +#define D3D11_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_DS_INPUT_CONTROL_POINT_REGISTER_COUNT ( 32 ) + +#define D3D11_DS_INPUT_CONTROL_POINT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_DS_INPUT_CONTROL_POINT_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENTS ( 3 ) + +#define D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_COUNT ( 1 ) + +#define D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_COUNT ( 32 ) + +#define D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_COUNT ( 1 ) + +#define D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_DS_OUTPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_DS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_DS_OUTPUT_REGISTER_COUNT ( 32 ) + +#define D3D11_FLOAT16_FUSED_TOLERANCE_IN_ULP ( 0.6 ) +#define D3D11_FLOAT32_MAX ( 3.402823466e+38f ) +#define D3D11_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP ( 0.6f ) +#define D3D11_FLOAT_TO_SRGB_EXPONENT_DENOMINATOR ( 2.4f ) +#define D3D11_FLOAT_TO_SRGB_EXPONENT_NUMERATOR ( 1.0f ) +#define D3D11_FLOAT_TO_SRGB_OFFSET ( 0.055f ) +#define D3D11_FLOAT_TO_SRGB_SCALE_1 ( 12.92f ) +#define D3D11_FLOAT_TO_SRGB_SCALE_2 ( 1.055f ) +#define D3D11_FLOAT_TO_SRGB_THRESHOLD ( 0.0031308f ) +#define D3D11_FTOI_INSTRUCTION_MAX_INPUT ( 2147483647.999f ) +#define D3D11_FTOI_INSTRUCTION_MIN_INPUT ( -2147483648.999f ) +#define D3D11_FTOU_INSTRUCTION_MAX_INPUT ( 4294967295.999f ) +#define D3D11_FTOU_INSTRUCTION_MIN_INPUT ( 0.0f ) +#define D3D11_GS_INPUT_INSTANCE_ID_READS_PER_INST ( 2 ) + +#define D3D11_GS_INPUT_INSTANCE_ID_READ_PORTS ( 1 ) + +#define D3D11_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_GS_INPUT_INSTANCE_ID_REGISTER_COUNT ( 1 ) + +#define D3D11_GS_INPUT_PRIM_CONST_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_GS_INPUT_PRIM_CONST_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_GS_INPUT_PRIM_CONST_REGISTER_COUNT ( 1 ) + +#define D3D11_GS_INPUT_PRIM_CONST_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_GS_INPUT_PRIM_CONST_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_GS_INPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_GS_INPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_GS_INPUT_REGISTER_COUNT ( 32 ) + +#define D3D11_GS_INPUT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_GS_INPUT_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_GS_INPUT_REGISTER_VERTICES ( 32 ) + +#define D3D11_GS_MAX_INSTANCE_COUNT ( 32 ) + +#define D3D11_GS_MAX_OUTPUT_VERTEX_COUNT_ACROSS_INSTANCES ( 1024 ) + +#define D3D11_GS_OUTPUT_ELEMENTS ( 32 ) + +#define D3D11_GS_OUTPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_GS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_GS_OUTPUT_REGISTER_COUNT ( 32 ) + +#define D3D11_HS_CONTROL_POINT_PHASE_INPUT_REGISTER_COUNT ( 32 ) + +#define D3D11_HS_CONTROL_POINT_PHASE_OUTPUT_REGISTER_COUNT ( 32 ) + +#define D3D11_HS_CONTROL_POINT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_HS_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_HS_CONTROL_POINT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_HS_CONTROL_POINT_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_HS_FORK_PHASE_INSTANCE_COUNT_UPPER_BOUND ( 0xffffffff ) + +#define D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COUNT ( 1 ) + +#define D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COUNT ( 1 ) + +#define D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_COUNT ( 1 ) + +#define D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_HS_JOIN_PHASE_INSTANCE_COUNT_UPPER_BOUND ( 0xffffffff ) + +#define D3D11_HS_MAXTESSFACTOR_LOWER_BOUND ( 1.0f ) +#define D3D11_HS_MAXTESSFACTOR_UPPER_BOUND ( 64.0f ) +#define D3D11_HS_OUTPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS ( 3968 ) + +#define D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COUNT ( 1 ) + +#define D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COUNT ( 32 ) + +#define D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_SCALAR_COMPONENTS ( 128 ) + +#define D3D11_IA_DEFAULT_INDEX_BUFFER_OFFSET_IN_BYTES ( 0 ) + +#define D3D11_IA_DEFAULT_PRIMITIVE_TOPOLOGY ( 0 ) + +#define D3D11_IA_DEFAULT_VERTEX_BUFFER_OFFSET_IN_BYTES ( 0 ) + +#define D3D11_IA_INDEX_INPUT_RESOURCE_SLOT_COUNT ( 1 ) + +#define D3D11_IA_INSTANCE_ID_BIT_COUNT ( 32 ) + +#define D3D11_IA_INTEGER_ARITHMETIC_BIT_COUNT ( 32 ) + +#define D3D11_IA_PATCH_MAX_CONTROL_POINT_COUNT ( 32 ) + +#define D3D11_IA_PRIMITIVE_ID_BIT_COUNT ( 32 ) + +#define D3D11_IA_VERTEX_ID_BIT_COUNT ( 32 ) + +#define D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT ( 32 ) + +#define D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENTS_COMPONENTS ( 128 ) + +#define D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT ( 32 ) + +#define D3D11_INTEGER_DIVIDE_BY_ZERO_QUOTIENT ( 0xffffffff ) + +#define D3D11_INTEGER_DIVIDE_BY_ZERO_REMAINDER ( 0xffffffff ) + +#define D3D11_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL ( 0xffffffff ) + +#define D3D11_KEEP_UNORDERED_ACCESS_VIEWS ( 0xffffffff ) + +#define D3D11_LINEAR_GAMMA ( 1.0f ) +#define D3D11_MAJOR_VERSION ( 11 ) + +#define D3D11_MAX_BORDER_COLOR_COMPONENT ( 1.0f ) +#define D3D11_MAX_DEPTH ( 1.0f ) +#define D3D11_MAX_MAXANISOTROPY ( 16 ) + +#define D3D11X_MAX_SAMPLER_ANISOTROPY_THRESHOLD ( ( 1 << 3 ) - 1 ) +#define D3D11X_MAX_SAMPLER_BORDER_COLOR_INDEX ( ( 1 << 12 ) - 1 ) +#define D3D11X_MAX_SAMPLER_PERFORMANCE_MIP ( ( 1 << 4 ) - 1 ) +#define D3D11X_MAX_SAMPLER_PERFORMANCE_Z ( ( 1 << 4 ) - 1 ) + +#define D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT ( 32 ) + +#define D3D11_MAX_POSITION_VALUE ( 3.402823466e+34f ) +#define D3D11_MAX_TEXTURE_DIMENSION_2_TO_EXP ( 17 ) + +#define D3D11_MINOR_VERSION ( 0 ) + +#define D3D11_MIN_BORDER_COLOR_COMPONENT ( 0.0f ) +#define D3D11_MIN_DEPTH ( 0.0f ) +#define D3D11_MIN_MAXANISOTROPY ( 0 ) + +#define D3D11_MIP_LOD_BIAS_MAX ( 15.99f ) +#define D3D11_MIP_LOD_BIAS_MIN ( -16.0f ) +#define D3D11_MIP_LOD_FRACTIONAL_BIT_COUNT ( 8 ) + +#define D3D11_MIP_LOD_RANGE_BIT_COUNT ( 8 ) + +#define D3D11_MULTISAMPLE_ANTIALIAS_LINE_WIDTH ( 1.4f ) +#define D3D11_NONSAMPLE_FETCH_OUT_OF_RANGE_ACCESS_RESULT ( 0 ) + +#define D3D11_PIXEL_ADDRESS_RANGE_BIT_COUNT ( 15 ) + +#define D3D11_PRE_SCISSOR_PIXEL_ADDRESS_RANGE_BIT_COUNT ( 16 ) + +#define D3D11_PS_CS_UAV_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_PS_CS_UAV_REGISTER_COUNT ( 8 ) + +#define D3D11_PS_CS_UAV_REGISTER_READS_PER_INST ( 1 ) + +#define D3D11_PS_CS_UAV_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_PS_FRONTFACING_DEFAULT_VALUE ( 0xffffffff ) + +#define D3D11_PS_FRONTFACING_FALSE_VALUE ( 0 ) + +#define D3D11_PS_FRONTFACING_TRUE_VALUE ( 0xffffffff ) + +#define D3D11_PS_INPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_PS_INPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_PS_INPUT_REGISTER_COUNT ( 32 ) + +#define D3D11_PS_INPUT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_PS_INPUT_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_PS_LEGACY_PIXEL_CENTER_FRACTIONAL_COMPONENT ( 0.0f ) +#define D3D11_PS_OUTPUT_DEPTH_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_PS_OUTPUT_DEPTH_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_PS_OUTPUT_DEPTH_REGISTER_COUNT ( 1 ) + +#define D3D11_PS_OUTPUT_MASK_REGISTER_COMPONENTS ( 1 ) + +#define D3D11_PS_OUTPUT_MASK_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_PS_OUTPUT_MASK_REGISTER_COUNT ( 1 ) + +#define D3D11_PS_OUTPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_PS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_PS_OUTPUT_REGISTER_COUNT ( 8 ) + +#define D3D11_PS_PIXEL_CENTER_FRACTIONAL_COMPONENT ( 0.5f ) +#define D3D11_RAW_UAV_SRV_BYTE_ALIGNMENT ( 16 ) + +#define D3D11_REQ_BLEND_OBJECT_COUNT_PER_DEVICE ( 4096 ) + +#define D3D11_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP ( 27 ) + +#define D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT ( 4096 ) + +#define D3D11_REQ_DEPTH_STENCIL_OBJECT_COUNT_PER_DEVICE ( 4096 ) + +#define D3D11_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP ( 32 ) + +#define D3D11_REQ_DRAW_VERTEX_COUNT_2_TO_EXP ( 32 ) + +#define D3D11_REQ_FILTERING_HW_ADDRESSABLE_RESOURCE_DIMENSION ( 16384 ) + +#define D3D11_REQ_GS_INVOCATION_32BIT_OUTPUT_COMPONENT_LIMIT ( 1024 ) + +#define D3D11_REQ_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT ( 4096 ) + +#define D3D11_REQ_MAXANISOTROPY ( 16 ) + +#define D3D11_REQ_MIP_LEVELS ( 15 ) + +#define D3D11_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES ( 2048 ) + +#define D3D11_REQ_RASTERIZER_OBJECT_COUNT_PER_DEVICE ( 4096 ) + +#define D3D11_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH ( 16384 ) + +#define D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM ( 128 ) + +#define D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_B_TERM ( 0.25f ) +#define D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_C_TERM ( 2048 ) + +#define D3D11_REQ_RESOURCE_VIEW_COUNT_PER_DEVICE_2_TO_EXP ( 20 ) + +#define D3D11_REQ_SAMPLER_OBJECT_COUNT_PER_DEVICE ( 4096 ) + +#define D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION ( 2048 ) +#define D3D11XBOX_REQ_TEXTURE1D_NON_RT_ARRAY_AXIS_DIMENSION ( 8192 ) + +#define D3D11_REQ_TEXTURE1D_U_DIMENSION ( 16384 ) + +#define D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION ( 2048 ) +#define D3D11XBOX_REQ_TEXTURE2D_NON_RT_ARRAY_AXIS_DIMENSION ( 8192 ) + +#define D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION ( 16384 ) + +#define D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION ( 2048 ) + +#define D3D11_REQ_TEXTURECUBE_DIMENSION ( 16384 ) + +#define D3D11_RESINFO_INSTRUCTION_MISSING_COMPONENT_RETVAL ( 0 ) + +#define D3D11_SHADER_MAJOR_VERSION ( 5 ) + +#define D3D11_SHADER_MAX_INSTANCES ( 65535 ) + +#define D3D11_SHADER_MAX_INTERFACES ( 253 ) + +#define D3D11_SHADER_MAX_INTERFACE_CALL_SITES ( 4096 ) + +#define D3D11_SHADER_MAX_TYPES ( 65535 ) + +#define D3D11_SHADER_MINOR_VERSION ( 0 ) + +#define D3D11_SHIFT_INSTRUCTION_PAD_VALUE ( 0 ) + +#define D3D11_SHIFT_INSTRUCTION_SHIFT_VALUE_BIT_COUNT ( 5 ) + +#define D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT ( 8 ) + +#define D3D11_SO_BUFFER_MAX_STRIDE_IN_BYTES ( 2048 ) + +#define D3D11_SO_BUFFER_MAX_WRITE_WINDOW_IN_BYTES ( 512 ) + +#define D3D11_SO_BUFFER_SLOT_COUNT ( 4 ) + +#define D3D11_SO_DDI_REGISTER_INDEX_DENOTING_GAP ( 0xffffffff ) + +#define D3D11_SO_NO_RASTERIZED_STREAM ( 0xffffffff ) + +#define D3D11_SO_OUTPUT_COMPONENT_COUNT ( 128 ) + +#define D3D11_SO_STREAM_COUNT ( 4 ) + +#define D3D11_SPEC_DATE_DAY ( 16 ) + +#define D3D11_SPEC_DATE_MONTH ( 05 ) + +#define D3D11_SPEC_DATE_YEAR ( 2011 ) + +#define D3D11_SPEC_VERSION ( 1.07 ) +#define D3D11_SRGB_GAMMA ( 2.2f ) +#define D3D11_SRGB_TO_FLOAT_DENOMINATOR_1 ( 12.92f ) +#define D3D11_SRGB_TO_FLOAT_DENOMINATOR_2 ( 1.055f ) +#define D3D11_SRGB_TO_FLOAT_EXPONENT ( 2.4f ) +#define D3D11_SRGB_TO_FLOAT_OFFSET ( 0.055f ) +#define D3D11_SRGB_TO_FLOAT_THRESHOLD ( 0.04045f ) +#define D3D11_SRGB_TO_FLOAT_TOLERANCE_IN_ULP ( 0.5f ) +#define D3D11_STANDARD_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_STANDARD_COMPONENT_BIT_COUNT_DOUBLED ( 64 ) + +#define D3D11_STANDARD_MAXIMUM_ELEMENT_ALIGNMENT_BYTE_MULTIPLE ( 4 ) + +#define D3D11_STANDARD_PIXEL_COMPONENT_COUNT ( 128 ) + +#define D3D11_STANDARD_PIXEL_ELEMENT_COUNT ( 32 ) + +#define D3D11_STANDARD_VECTOR_SIZE ( 4 ) + +#define D3D11_STANDARD_VERTEX_ELEMENT_COUNT ( 32 ) + +#define D3D11_STANDARD_VERTEX_TOTAL_COMPONENT_COUNT ( 64 ) + +#define D3D11_SUBPIXEL_FRACTIONAL_BIT_COUNT ( 8 ) + +#define D3D11_SUBTEXEL_FRACTIONAL_BIT_COUNT ( 8 ) + +#define D3D11_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR ( 64 ) + +#define D3D11_TESSELLATOR_MAX_ISOLINE_DENSITY_TESSELLATION_FACTOR ( 64 ) + +#define D3D11_TESSELLATOR_MAX_ODD_TESSELLATION_FACTOR ( 63 ) + +#define D3D11_TESSELLATOR_MAX_TESSELLATION_FACTOR ( 64 ) + +#define D3D11_TESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR ( 2 ) + +#define D3D11_TESSELLATOR_MIN_ISOLINE_DENSITY_TESSELLATION_FACTOR ( 1 ) + +#define D3D11_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR ( 1 ) + +#define D3D11_TEXEL_ADDRESS_RANGE_BIT_COUNT ( 16 ) + +#define D3D11_UNBOUND_MEMORY_ACCESS_RESULT ( 0 ) + +#define D3D11_VIEWPORT_AND_SCISSORRECT_MAX_INDEX ( 15 ) + +#define D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE ( 16 ) + +#define D3D11_VIEWPORT_BOUNDS_MAX ( 32767 ) + +#define D3D11_VIEWPORT_BOUNDS_MIN ( -32768 ) + +#define D3D11_VS_INPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_VS_INPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_VS_INPUT_REGISTER_COUNT ( 32 ) + +#define D3D11_VS_INPUT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D11_VS_INPUT_REGISTER_READ_PORTS ( 1 ) + +#define D3D11_VS_OUTPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D11_VS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D11_VS_OUTPUT_REGISTER_COUNT ( 32 ) + +#define D3D11_WHQL_CONTEXT_COUNT_FOR_RESOURCE_LIMIT ( 10 ) + +#define D3D11_WHQL_DRAWINDEXED_INDEX_COUNT_2_TO_EXP ( 25 ) + +#define D3D11_WHQL_DRAW_VERTEX_COUNT_2_TO_EXP ( 25 ) + +#endif // _D3D11_CONSTANTS + +#ifndef _D3D11_1_CONSTANTS +#define _D3D11_1_CONSTANTS +#define D3D11_1_UAV_SLOT_COUNT ( 64 ) +#endif + +#ifndef _D3D11_2_CONSTANTS +#define _D3D11_2_CONSTANTS +#define D3D11_2_TILED_RESOURCE_TILE_SIZE_IN_BYTES ( 65536 ) +#endif + +#ifndef _D3D11_X_CONSTANTS +#define _D3D11_X_CONSTANTS + +#define D3D11X_OFFCHIP_TESSELLATION_BUFFER_SIZE ( 126 * 32 * 1024 ) +#define D3D11X_TESSELLATION_FACTORS_BUFFER_SIZE ( 32 * 1024 ) + +#define D3D11X_XBOX_GPU_TIMESTAMP_FREQUENCY ( 99750000 ) // 100 MHz * .9975 +#define D3D11X_XBOX_GPU_CLOCK_FREQUENCY ( 851200000 ) // 853.33 MHz * .9975 +#define D3D11X_XBOX_VIRTUAL_REFRESH ( 59.94f ) // 59.94 MHz + +#define D3D11X_DESCRIPTOR_RESOURCE_SIZE_IN_OWORDS 40 +#define D3D11X_DESCRIPTOR_RESOURCE_SIZE_IN_QWORDS 80 +#define D3D11X_DESCRIPTOR_RESOURCE_SIZE_IN_DWORDS 160 +#define D3D11X_DESCRIPTOR_RESOURCE_SIZE_IN_BYTES 640 +#define D3D11X_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_OWORDS 1 +#define D3D11X_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_QWORDS 2 +#define D3D11X_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_DWORDS 4 +#define D3D11X_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_BYTES 16 +#define D3D11X_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_OWORDS 2 +#define D3D11X_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_QWORDS 4 +#define D3D11X_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_DWORDS 8 +#define D3D11X_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_BYTES 32 +#define D3D11X_DESCRIPTOR_SHADER_RESOURCE_VIEW_SIZE_IN_OWORDS 2 +#define D3D11X_DESCRIPTOR_SHADER_RESOURCE_VIEW_SIZE_IN_QWORDS 4 +#define D3D11X_DESCRIPTOR_SHADER_RESOURCE_VIEW_SIZE_IN_DWORDS 8 +#define D3D11X_DESCRIPTOR_SHADER_RESOURCE_VIEW_SIZE_IN_BYTES 32 +#define D3D11X_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_OWORDS 2 +#define D3D11X_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_QWORDS 4 +#define D3D11X_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_DWORDS 8 +#define D3D11X_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_BYTES 32 +#define D3D11X_DESCRIPTOR_CONSTANT_BUFFER_VIEW_SIZE_IN_OWORDS 1 +#define D3D11X_DESCRIPTOR_CONSTANT_BUFFER_VIEW_SIZE_IN_QWORDS 2 +#define D3D11X_DESCRIPTOR_CONSTANT_BUFFER_VIEW_SIZE_IN_DWORDS 4 +#define D3D11X_DESCRIPTOR_CONSTANT_BUFFER_VIEW_SIZE_IN_BYTES 16 +#define D3D11X_DESCRIPTOR_VERTEX_BUFFER_VIEW_SIZE_IN_OWORDS 1 +#define D3D11X_DESCRIPTOR_VERTEX_BUFFER_VIEW_SIZE_IN_QWORDS 2 +#define D3D11X_DESCRIPTOR_VERTEX_BUFFER_VIEW_SIZE_IN_DWORDS 4 +#define D3D11X_DESCRIPTOR_VERTEX_BUFFER_VIEW_SIZE_IN_BYTES 16 +#define D3D11X_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_OWORDS 1 +#define D3D11X_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_QWORDS 2 +#define D3D11X_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_DWORDS 4 +#define D3D11X_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_BYTES 16 +#define D3D11X_FENCE_INVALID ( 0 ) + +#endif // _D3D11_X_CONSTANTS + +// +// Error definitions +// + +extern "C" +{ + +#define _FACD3D11 ( 0x87c ) + +#define _FACD3D11DEBUG ( ( _FACD3D11 + 1 ) ) + +// Standard Direct3D errors are defined in winerror.h + +#define MAKE_D3D11_HRESULT( code ) MAKE_HRESULT( 1, _FACD3D11, code ) +#define MAKE_D3D11_STATUS( code ) MAKE_HRESULT( 0, _FACD3D11, code ) + +// This makes the D3DERR match the legacy DD error (DDERR_WASSTILLDRAWING) +// used for Video. +#define _FACD3D 0x876 +#define MAKE_D3DHRESULT( code ) MAKE_HRESULT( 1, _FACD3D, code ) + +#define D3DERR_WASSTILLDRAWING MAKE_D3DHRESULT(540) + +} + +extern "C" +{ + +// Feature definitions + +typedef enum D3D_DRIVER_TYPE +{ + D3D_DRIVER_TYPE_UNKNOWN = 0, + D3D_DRIVER_TYPE_HARDWARE = ( D3D_DRIVER_TYPE_UNKNOWN + 1 ) , + D3D_DRIVER_TYPE_REFERENCE = ( D3D_DRIVER_TYPE_HARDWARE + 1 ) , + D3D_DRIVER_TYPE_NULL = ( D3D_DRIVER_TYPE_REFERENCE + 1 ) , + D3D_DRIVER_TYPE_SOFTWARE = ( D3D_DRIVER_TYPE_NULL + 1 ) , + D3D_DRIVER_TYPE_WARP = ( D3D_DRIVER_TYPE_SOFTWARE + 1 ) +} D3D_DRIVER_TYPE; + +typedef enum D3D_FEATURE_LEVEL +{ + D3D_FEATURE_LEVEL_9_1 = 0x9100, + D3D_FEATURE_LEVEL_9_2 = 0x9200, + D3D_FEATURE_LEVEL_9_3 = 0x9300, + D3D_FEATURE_LEVEL_10_0 = 0xa000, + D3D_FEATURE_LEVEL_10_1 = 0xa100, + D3D_FEATURE_LEVEL_11_0 = 0xb000, + D3D_FEATURE_LEVEL_11_1 = 0xb100, + D3D_FEATURE_LEVEL_12_0 = 0xc000, + D3D_FEATURE_LEVEL_12_1 = 0xc100, + D3D_FEATURE_LEVEL_12_2 = 0xc200 // A.K.A. DX12 'Ultimate' +} D3D_FEATURE_LEVEL; + +} + +extern "C" +{ + +// IA definitions + +#ifndef __D3D_PRIMITIVE_TOPOLOGY__DEFINED__ +#define __D3D_PRIMITIVE_TOPOLOGY__DEFINED__ + +typedef enum D3D_PRIMITIVE_TOPOLOGY +{ + D3D_PRIMITIVE_TOPOLOGY_UNDEFINED = 0, + D3D_PRIMITIVE_TOPOLOGY_POINTLIST = 1, + D3D_PRIMITIVE_TOPOLOGY_LINELIST = 2, + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP = 3, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN = 6, // Xbox extension + D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10, + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13, + D3D_PRIMITIVE_TOPOLOGY_RECTLIST = 17, // Xbox extension + D3D_PRIMITIVE_TOPOLOGY_LINELOOP = 18, // Xbox extension + D3D_PRIMITIVE_TOPOLOGY_QUADLIST = 19, // Xbox extension + D3D_PRIMITIVE_TOPOLOGY_QUADSTRIP = 20, // Xbox extension + D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = 33, + D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = 34, + D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = 35, + D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = 36, + D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = 37, + D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = 38, + D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = 39, + D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = 40, + D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = 41, + D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = 42, + D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = 43, + D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = 44, + D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = 45, + D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = 46, + D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = 47, + D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = 48, + D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = 49, + D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = 50, + D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = 51, + D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = 52, + D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = 53, + D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = 54, + D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = 55, + D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = 56, + D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = 57, + D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = 58, + D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = 59, + D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = 60, + D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = 61, + D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = 62, + D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = 63, + D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = 64, + D3D10_PRIMITIVE_TOPOLOGY_UNDEFINED = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED, + D3D10_PRIMITIVE_TOPOLOGY_POINTLIST = D3D_PRIMITIVE_TOPOLOGY_POINTLIST, + D3D10_PRIMITIVE_TOPOLOGY_LINELIST = D3D_PRIMITIVE_TOPOLOGY_LINELIST, + D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, + D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, + D3D10_PRIMITIVE_TOPOLOGY_TRIANGLEFAN = D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN, // Xbox extension + D3D10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ, + D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ, + D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ, + D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ, + D3D10_PRIMITIVE_TOPOLOGY_RECTLIST = D3D_PRIMITIVE_TOPOLOGY_RECTLIST, // Xbox extension + D3D10_PRIMITIVE_TOPOLOGY_LINELOOP = D3D_PRIMITIVE_TOPOLOGY_LINELOOP, // Xbox extension + D3D10_PRIMITIVE_TOPOLOGY_QUADLIST = D3D_PRIMITIVE_TOPOLOGY_QUADLIST, // Xbox extension + D3D10_PRIMITIVE_TOPOLOGY_QUADSTRIP = D3D_PRIMITIVE_TOPOLOGY_QUADSTRIP, // Xbox extension + D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED, + D3D11_PRIMITIVE_TOPOLOGY_POINTLIST = D3D_PRIMITIVE_TOPOLOGY_POINTLIST, + D3D11_PRIMITIVE_TOPOLOGY_LINELIST = D3D_PRIMITIVE_TOPOLOGY_LINELIST, + D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, + D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, + D3D11_PRIMITIVE_TOPOLOGY_TRIANGLEFAN = D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN, // Xbox extension + D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ, + D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ, + D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ, + D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ, + D3D11_PRIMITIVE_TOPOLOGY_RECTLIST = D3D_PRIMITIVE_TOPOLOGY_RECTLIST, // Xbox extension + D3D11_PRIMITIVE_TOPOLOGY_LINELOOP = D3D_PRIMITIVE_TOPOLOGY_LINELOOP, // Xbox extension + D3D11_PRIMITIVE_TOPOLOGY_QUADLIST = D3D_PRIMITIVE_TOPOLOGY_QUADLIST, // Xbox extension + D3D11_PRIMITIVE_TOPOLOGY_QUADSTRIP = D3D_PRIMITIVE_TOPOLOGY_QUADSTRIP, // Xbox extension + D3D11_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST, + D3D11_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST +} D3D_PRIMITIVE_TOPOLOGY; + +#endif // __D3D_PRIMITIVE_TOPOLOGY__DEFINED__ + +#ifndef __D3D_PRIMITIVE__DEFINED__ +#define __D3D_PRIMITIVE__DEFINED__ + +typedef enum D3D_PRIMITIVE +{ + D3D_PRIMITIVE_UNDEFINED = 0, + D3D_PRIMITIVE_POINT = 1, + D3D_PRIMITIVE_LINE = 2, + D3D_PRIMITIVE_TRIANGLE = 3, + D3D_PRIMITIVE_LINE_ADJ = 6, + D3D_PRIMITIVE_TRIANGLE_ADJ = 7, + D3D_PRIMITIVE_1_CONTROL_POINT_PATCH = 8, + D3D_PRIMITIVE_2_CONTROL_POINT_PATCH = 9, + D3D_PRIMITIVE_3_CONTROL_POINT_PATCH = 10, + D3D_PRIMITIVE_4_CONTROL_POINT_PATCH = 11, + D3D_PRIMITIVE_5_CONTROL_POINT_PATCH = 12, + D3D_PRIMITIVE_6_CONTROL_POINT_PATCH = 13, + D3D_PRIMITIVE_7_CONTROL_POINT_PATCH = 14, + D3D_PRIMITIVE_8_CONTROL_POINT_PATCH = 15, + D3D_PRIMITIVE_9_CONTROL_POINT_PATCH = 16, + D3D_PRIMITIVE_10_CONTROL_POINT_PATCH = 17, + D3D_PRIMITIVE_11_CONTROL_POINT_PATCH = 18, + D3D_PRIMITIVE_12_CONTROL_POINT_PATCH = 19, + D3D_PRIMITIVE_13_CONTROL_POINT_PATCH = 20, + D3D_PRIMITIVE_14_CONTROL_POINT_PATCH = 21, + D3D_PRIMITIVE_15_CONTROL_POINT_PATCH = 22, + D3D_PRIMITIVE_16_CONTROL_POINT_PATCH = 23, + D3D_PRIMITIVE_17_CONTROL_POINT_PATCH = 24, + D3D_PRIMITIVE_18_CONTROL_POINT_PATCH = 25, + D3D_PRIMITIVE_19_CONTROL_POINT_PATCH = 26, + D3D_PRIMITIVE_20_CONTROL_POINT_PATCH = 28, + D3D_PRIMITIVE_21_CONTROL_POINT_PATCH = 29, + D3D_PRIMITIVE_22_CONTROL_POINT_PATCH = 30, + D3D_PRIMITIVE_23_CONTROL_POINT_PATCH = 31, + D3D_PRIMITIVE_24_CONTROL_POINT_PATCH = 32, + D3D_PRIMITIVE_25_CONTROL_POINT_PATCH = 33, + D3D_PRIMITIVE_26_CONTROL_POINT_PATCH = 34, + D3D_PRIMITIVE_27_CONTROL_POINT_PATCH = 35, + D3D_PRIMITIVE_28_CONTROL_POINT_PATCH = 36, + D3D_PRIMITIVE_29_CONTROL_POINT_PATCH = 37, + D3D_PRIMITIVE_30_CONTROL_POINT_PATCH = 38, + D3D_PRIMITIVE_31_CONTROL_POINT_PATCH = 39, + D3D_PRIMITIVE_32_CONTROL_POINT_PATCH = 40, + D3D10_PRIMITIVE_UNDEFINED = D3D_PRIMITIVE_UNDEFINED, + D3D10_PRIMITIVE_POINT = D3D_PRIMITIVE_POINT, + D3D10_PRIMITIVE_LINE = D3D_PRIMITIVE_LINE, + D3D10_PRIMITIVE_TRIANGLE = D3D_PRIMITIVE_TRIANGLE, + D3D10_PRIMITIVE_LINE_ADJ = D3D_PRIMITIVE_LINE_ADJ, + D3D10_PRIMITIVE_TRIANGLE_ADJ = D3D_PRIMITIVE_TRIANGLE_ADJ, + D3D11_PRIMITIVE_UNDEFINED = D3D_PRIMITIVE_UNDEFINED, + D3D11_PRIMITIVE_POINT = D3D_PRIMITIVE_POINT, + D3D11_PRIMITIVE_LINE = D3D_PRIMITIVE_LINE, + D3D11_PRIMITIVE_TRIANGLE = D3D_PRIMITIVE_TRIANGLE, + D3D11_PRIMITIVE_LINE_ADJ = D3D_PRIMITIVE_LINE_ADJ, + D3D11_PRIMITIVE_TRIANGLE_ADJ = D3D_PRIMITIVE_TRIANGLE_ADJ, + D3D11_PRIMITIVE_1_CONTROL_POINT_PATCH = D3D_PRIMITIVE_1_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_2_CONTROL_POINT_PATCH = D3D_PRIMITIVE_2_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_3_CONTROL_POINT_PATCH = D3D_PRIMITIVE_3_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_4_CONTROL_POINT_PATCH = D3D_PRIMITIVE_4_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_5_CONTROL_POINT_PATCH = D3D_PRIMITIVE_5_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_6_CONTROL_POINT_PATCH = D3D_PRIMITIVE_6_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_7_CONTROL_POINT_PATCH = D3D_PRIMITIVE_7_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_8_CONTROL_POINT_PATCH = D3D_PRIMITIVE_8_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_9_CONTROL_POINT_PATCH = D3D_PRIMITIVE_9_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_10_CONTROL_POINT_PATCH = D3D_PRIMITIVE_10_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_11_CONTROL_POINT_PATCH = D3D_PRIMITIVE_11_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_12_CONTROL_POINT_PATCH = D3D_PRIMITIVE_12_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_13_CONTROL_POINT_PATCH = D3D_PRIMITIVE_13_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_14_CONTROL_POINT_PATCH = D3D_PRIMITIVE_14_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_15_CONTROL_POINT_PATCH = D3D_PRIMITIVE_15_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_16_CONTROL_POINT_PATCH = D3D_PRIMITIVE_16_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_17_CONTROL_POINT_PATCH = D3D_PRIMITIVE_17_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_18_CONTROL_POINT_PATCH = D3D_PRIMITIVE_18_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_19_CONTROL_POINT_PATCH = D3D_PRIMITIVE_19_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_20_CONTROL_POINT_PATCH = D3D_PRIMITIVE_20_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_21_CONTROL_POINT_PATCH = D3D_PRIMITIVE_21_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_22_CONTROL_POINT_PATCH = D3D_PRIMITIVE_22_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_23_CONTROL_POINT_PATCH = D3D_PRIMITIVE_23_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_24_CONTROL_POINT_PATCH = D3D_PRIMITIVE_24_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_25_CONTROL_POINT_PATCH = D3D_PRIMITIVE_25_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_26_CONTROL_POINT_PATCH = D3D_PRIMITIVE_26_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_27_CONTROL_POINT_PATCH = D3D_PRIMITIVE_27_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_28_CONTROL_POINT_PATCH = D3D_PRIMITIVE_28_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_29_CONTROL_POINT_PATCH = D3D_PRIMITIVE_29_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_30_CONTROL_POINT_PATCH = D3D_PRIMITIVE_30_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_31_CONTROL_POINT_PATCH = D3D_PRIMITIVE_31_CONTROL_POINT_PATCH, + D3D11_PRIMITIVE_32_CONTROL_POINT_PATCH = D3D_PRIMITIVE_32_CONTROL_POINT_PATCH +} D3D_PRIMITIVE; + +#endif //__D3D_PRIMITIVE__DEFINED__ + +typedef enum D3D_MIN_PRECISION +{ + D3D_MIN_PRECISION_DEFAULT = 0, + D3D_MIN_PRECISION_FLOAT_16 = 1, + D3D_MIN_PRECISION_FLOAT_2_8 = 2, + D3D_MIN_PRECISION_RESERVED = 3, + D3D_MIN_PRECISION_SINT_16 = 4, + D3D_MIN_PRECISION_UINT_16 = 5, + D3D_MIN_PRECISION_ANY_16 = 0xf0, + D3D_MIN_PRECISION_ANY_10 = 0xf1 +} D3D_MIN_PRECISION; + +} + +extern "C" +{ + +typedef struct _D3D_SHADER_MACRO +{ + LPCSTR Name; + LPCSTR Definition; +} D3D_SHADER_MACRO; + +typedef struct _D3D_SHADER_MACRO *LPD3D_SHADER_MACRO; + +typedef enum _D3D_INCLUDE_TYPE +{ + D3D_INCLUDE_LOCAL = 0, + D3D_INCLUDE_SYSTEM = ( D3D_INCLUDE_LOCAL + 1 ) , + D3D10_INCLUDE_LOCAL = D3D_INCLUDE_LOCAL, + D3D10_INCLUDE_SYSTEM = D3D_INCLUDE_SYSTEM, + D3D_INCLUDE_FORCE_DWORD = 0x7fffffff +} D3D_INCLUDE_TYPE; + +typedef enum _D3D_SHADER_VARIABLE_CLASS +{ + D3D_SVC_SCALAR = 0, + D3D_SVC_VECTOR = ( D3D_SVC_SCALAR + 1 ) , + D3D_SVC_MATRIX_ROWS = ( D3D_SVC_VECTOR + 1 ) , + D3D_SVC_MATRIX_COLUMNS = ( D3D_SVC_MATRIX_ROWS + 1 ) , + D3D_SVC_OBJECT = ( D3D_SVC_MATRIX_COLUMNS + 1 ) , + D3D_SVC_STRUCT = ( D3D_SVC_OBJECT + 1 ) , + D3D_SVC_INTERFACE_CLASS = ( D3D_SVC_STRUCT + 1 ) , + D3D_SVC_INTERFACE_POINTER = ( D3D_SVC_INTERFACE_CLASS + 1 ) , + D3D10_SVC_SCALAR = D3D_SVC_SCALAR, + D3D10_SVC_VECTOR = D3D_SVC_VECTOR, + D3D10_SVC_MATRIX_ROWS = D3D_SVC_MATRIX_ROWS, + D3D10_SVC_MATRIX_COLUMNS = D3D_SVC_MATRIX_COLUMNS, + D3D10_SVC_OBJECT = D3D_SVC_OBJECT, + D3D10_SVC_STRUCT = D3D_SVC_STRUCT, + D3D11_SVC_INTERFACE_CLASS = D3D_SVC_INTERFACE_CLASS, + D3D11_SVC_INTERFACE_POINTER = D3D_SVC_INTERFACE_POINTER, + D3D_SVC_FORCE_DWORD = 0x7fffffff +} D3D_SHADER_VARIABLE_CLASS; + +typedef enum _D3D_SHADER_VARIABLE_FLAGS +{ + D3D_SVF_USERPACKED = 1, + D3D_SVF_USED = 2, + D3D_SVF_INTERFACE_POINTER = 4, + D3D_SVF_INTERFACE_PARAMETER = 8, + D3D10_SVF_USERPACKED = D3D_SVF_USERPACKED, + D3D10_SVF_USED = D3D_SVF_USED, + D3D11_SVF_INTERFACE_POINTER = D3D_SVF_INTERFACE_POINTER, + D3D11_SVF_INTERFACE_PARAMETER = D3D_SVF_INTERFACE_PARAMETER, + D3D_SVF_FORCE_DWORD = 0x7fffffff +} D3D_SHADER_VARIABLE_FLAGS; + +typedef enum _D3D_SHADER_VARIABLE_TYPE +{ + D3D_SVT_VOID = 0, + D3D_SVT_BOOL = 1, + D3D_SVT_INT = 2, + D3D_SVT_FLOAT = 3, + D3D_SVT_STRING = 4, + D3D_SVT_TEXTURE = 5, + D3D_SVT_TEXTURE1D = 6, + D3D_SVT_TEXTURE2D = 7, + D3D_SVT_TEXTURE3D = 8, + D3D_SVT_TEXTURECUBE = 9, + D3D_SVT_SAMPLER = 10, + D3D_SVT_SAMPLER1D = 11, + D3D_SVT_SAMPLER2D = 12, + D3D_SVT_SAMPLER3D = 13, + D3D_SVT_SAMPLERCUBE = 14, + D3D_SVT_PIXELSHADER = 15, + D3D_SVT_VERTEXSHADER = 16, + D3D_SVT_PIXELFRAGMENT = 17, + D3D_SVT_VERTEXFRAGMENT = 18, + D3D_SVT_UINT = 19, + D3D_SVT_UINT8 = 20, + D3D_SVT_GEOMETRYSHADER = 21, + D3D_SVT_RASTERIZER = 22, + D3D_SVT_DEPTHSTENCIL = 23, + D3D_SVT_BLEND = 24, + D3D_SVT_BUFFER = 25, + D3D_SVT_CBUFFER = 26, + D3D_SVT_TBUFFER = 27, + D3D_SVT_TEXTURE1DARRAY = 28, + D3D_SVT_TEXTURE2DARRAY = 29, + D3D_SVT_RENDERTARGETVIEW = 30, + D3D_SVT_DEPTHSTENCILVIEW = 31, + D3D_SVT_TEXTURE2DMS = 32, + D3D_SVT_TEXTURE2DMSARRAY = 33, + D3D_SVT_TEXTURECUBEARRAY = 34, + D3D_SVT_HULLSHADER = 35, + D3D_SVT_DOMAINSHADER = 36, + D3D_SVT_INTERFACE_POINTER = 37, + D3D_SVT_COMPUTESHADER = 38, + D3D_SVT_DOUBLE = 39, + D3D_SVT_RWTEXTURE1D = 40, + D3D_SVT_RWTEXTURE1DARRAY = 41, + D3D_SVT_RWTEXTURE2D = 42, + D3D_SVT_RWTEXTURE2DARRAY = 43, + D3D_SVT_RWTEXTURE3D = 44, + D3D_SVT_RWBUFFER = 45, + D3D_SVT_BYTEADDRESS_BUFFER = 46, + D3D_SVT_RWBYTEADDRESS_BUFFER = 47, + D3D_SVT_STRUCTURED_BUFFER = 48, + D3D_SVT_RWSTRUCTURED_BUFFER = 49, + D3D_SVT_APPEND_STRUCTURED_BUFFER = 50, + D3D_SVT_CONSUME_STRUCTURED_BUFFER = 51, + D3D_SVT_MIN8FLOAT = 52, + D3D_SVT_MIN10FLOAT = 53, + D3D_SVT_MIN16FLOAT = 54, + D3D_SVT_MIN12INT = 55, + D3D_SVT_MIN16INT = 56, + D3D_SVT_MIN16UINT = 57, + D3D10_SVT_VOID = D3D_SVT_VOID, + D3D10_SVT_BOOL = D3D_SVT_BOOL, + D3D10_SVT_INT = D3D_SVT_INT, + D3D10_SVT_FLOAT = D3D_SVT_FLOAT, + D3D10_SVT_STRING = D3D_SVT_STRING, + D3D10_SVT_TEXTURE = D3D_SVT_TEXTURE, + D3D10_SVT_TEXTURE1D = D3D_SVT_TEXTURE1D, + D3D10_SVT_TEXTURE2D = D3D_SVT_TEXTURE2D, + D3D10_SVT_TEXTURE3D = D3D_SVT_TEXTURE3D, + D3D10_SVT_TEXTURECUBE = D3D_SVT_TEXTURECUBE, + D3D10_SVT_SAMPLER = D3D_SVT_SAMPLER, + D3D10_SVT_SAMPLER1D = D3D_SVT_SAMPLER1D, + D3D10_SVT_SAMPLER2D = D3D_SVT_SAMPLER2D, + D3D10_SVT_SAMPLER3D = D3D_SVT_SAMPLER3D, + D3D10_SVT_SAMPLERCUBE = D3D_SVT_SAMPLERCUBE, + D3D10_SVT_PIXELSHADER = D3D_SVT_PIXELSHADER, + D3D10_SVT_VERTEXSHADER = D3D_SVT_VERTEXSHADER, + D3D10_SVT_PIXELFRAGMENT = D3D_SVT_PIXELFRAGMENT, + D3D10_SVT_VERTEXFRAGMENT = D3D_SVT_VERTEXFRAGMENT, + D3D10_SVT_UINT = D3D_SVT_UINT, + D3D10_SVT_UINT8 = D3D_SVT_UINT8, + D3D10_SVT_GEOMETRYSHADER = D3D_SVT_GEOMETRYSHADER, + D3D10_SVT_RASTERIZER = D3D_SVT_RASTERIZER, + D3D10_SVT_DEPTHSTENCIL = D3D_SVT_DEPTHSTENCIL, + D3D10_SVT_BLEND = D3D_SVT_BLEND, + D3D10_SVT_BUFFER = D3D_SVT_BUFFER, + D3D10_SVT_CBUFFER = D3D_SVT_CBUFFER, + D3D10_SVT_TBUFFER = D3D_SVT_TBUFFER, + D3D10_SVT_TEXTURE1DARRAY = D3D_SVT_TEXTURE1DARRAY, + D3D10_SVT_TEXTURE2DARRAY = D3D_SVT_TEXTURE2DARRAY, + D3D10_SVT_RENDERTARGETVIEW = D3D_SVT_RENDERTARGETVIEW, + D3D10_SVT_DEPTHSTENCILVIEW = D3D_SVT_DEPTHSTENCILVIEW, + D3D10_SVT_TEXTURE2DMS = D3D_SVT_TEXTURE2DMS, + D3D10_SVT_TEXTURE2DMSARRAY = D3D_SVT_TEXTURE2DMSARRAY, + D3D10_SVT_TEXTURECUBEARRAY = D3D_SVT_TEXTURECUBEARRAY, + D3D11_SVT_HULLSHADER = D3D_SVT_HULLSHADER, + D3D11_SVT_DOMAINSHADER = D3D_SVT_DOMAINSHADER, + D3D11_SVT_INTERFACE_POINTER = D3D_SVT_INTERFACE_POINTER, + D3D11_SVT_COMPUTESHADER = D3D_SVT_COMPUTESHADER, + D3D11_SVT_DOUBLE = D3D_SVT_DOUBLE, + D3D11_SVT_RWTEXTURE1D = D3D_SVT_RWTEXTURE1D, + D3D11_SVT_RWTEXTURE1DARRAY = D3D_SVT_RWTEXTURE1DARRAY, + D3D11_SVT_RWTEXTURE2D = D3D_SVT_RWTEXTURE2D, + D3D11_SVT_RWTEXTURE2DARRAY = D3D_SVT_RWTEXTURE2DARRAY, + D3D11_SVT_RWTEXTURE3D = D3D_SVT_RWTEXTURE3D, + D3D11_SVT_RWBUFFER = D3D_SVT_RWBUFFER, + D3D11_SVT_BYTEADDRESS_BUFFER = D3D_SVT_BYTEADDRESS_BUFFER, + D3D11_SVT_RWBYTEADDRESS_BUFFER = D3D_SVT_RWBYTEADDRESS_BUFFER, + D3D11_SVT_STRUCTURED_BUFFER = D3D_SVT_STRUCTURED_BUFFER, + D3D11_SVT_RWSTRUCTURED_BUFFER = D3D_SVT_RWSTRUCTURED_BUFFER, + D3D11_SVT_APPEND_STRUCTURED_BUFFER = D3D_SVT_APPEND_STRUCTURED_BUFFER, + D3D11_SVT_CONSUME_STRUCTURED_BUFFER = D3D_SVT_CONSUME_STRUCTURED_BUFFER, + D3D_SVT_FORCE_DWORD = 0x7fffffff +} D3D_SHADER_VARIABLE_TYPE; + +typedef enum _D3D_SHADER_INPUT_FLAGS +{ + D3D_SIF_USERPACKED = 0x1, + D3D_SIF_COMPARISON_SAMPLER = 0x2, + D3D_SIF_TEXTURE_COMPONENT_0 = 0x4, + D3D_SIF_TEXTURE_COMPONENT_1 = 0x8, + D3D_SIF_TEXTURE_COMPONENTS = 0xc, + D3D_SIF_UNUSED = 0x10, + D3D10_SIF_USERPACKED = D3D_SIF_USERPACKED, + D3D10_SIF_COMPARISON_SAMPLER = D3D_SIF_COMPARISON_SAMPLER, + D3D10_SIF_TEXTURE_COMPONENT_0 = D3D_SIF_TEXTURE_COMPONENT_0, + D3D10_SIF_TEXTURE_COMPONENT_1 = D3D_SIF_TEXTURE_COMPONENT_1, + D3D10_SIF_TEXTURE_COMPONENTS = D3D_SIF_TEXTURE_COMPONENTS, + D3D_SIF_FORCE_DWORD = 0x7fffffff +} D3D_SHADER_INPUT_FLAGS; + +typedef enum _D3D_SHADER_INPUT_TYPE +{ + D3D_SIT_CBUFFER = 0, + D3D_SIT_TBUFFER = ( D3D_SIT_CBUFFER + 1 ) , + D3D_SIT_TEXTURE = ( D3D_SIT_TBUFFER + 1 ) , + D3D_SIT_SAMPLER = ( D3D_SIT_TEXTURE + 1 ) , + D3D_SIT_UAV_RWTYPED = ( D3D_SIT_SAMPLER + 1 ) , + D3D_SIT_STRUCTURED = ( D3D_SIT_UAV_RWTYPED + 1 ) , + D3D_SIT_UAV_RWSTRUCTURED = ( D3D_SIT_STRUCTURED + 1 ) , + D3D_SIT_BYTEADDRESS = ( D3D_SIT_UAV_RWSTRUCTURED + 1 ) , + D3D_SIT_UAV_RWBYTEADDRESS = ( D3D_SIT_BYTEADDRESS + 1 ) , + D3D_SIT_UAV_APPEND_STRUCTURED = ( D3D_SIT_UAV_RWBYTEADDRESS + 1 ) , + D3D_SIT_UAV_CONSUME_STRUCTURED = ( D3D_SIT_UAV_APPEND_STRUCTURED + 1 ) , + D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER = ( D3D_SIT_UAV_CONSUME_STRUCTURED + 1 ) , + D3D_SIT_RTACCELERATIONSTRUCTURE = ( D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER + 1 ) , + D3D_SIT_UAV_FEEDBACKTEXTURE = ( D3D_SIT_RTACCELERATIONSTRUCTURE + 1 ) , + D3D10_SIT_CBUFFER = D3D_SIT_CBUFFER, + D3D10_SIT_TBUFFER = D3D_SIT_TBUFFER, + D3D10_SIT_TEXTURE = D3D_SIT_TEXTURE, + D3D10_SIT_SAMPLER = D3D_SIT_SAMPLER, + D3D11_SIT_UAV_RWTYPED = D3D_SIT_UAV_RWTYPED, + D3D11_SIT_STRUCTURED = D3D_SIT_STRUCTURED, + D3D11_SIT_UAV_RWSTRUCTURED = D3D_SIT_UAV_RWSTRUCTURED, + D3D11_SIT_BYTEADDRESS = D3D_SIT_BYTEADDRESS, + D3D11_SIT_UAV_RWBYTEADDRESS = D3D_SIT_UAV_RWBYTEADDRESS, + D3D11_SIT_UAV_APPEND_STRUCTURED = D3D_SIT_UAV_APPEND_STRUCTURED, + D3D11_SIT_UAV_CONSUME_STRUCTURED = D3D_SIT_UAV_CONSUME_STRUCTURED, + D3D11_SIT_UAV_RWSTRUCTURED_WITH_COUNTER = D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER +} D3D_SHADER_INPUT_TYPE; + +typedef enum _D3D_SHADER_CBUFFER_FLAGS +{ + D3D_CBF_USERPACKED = 1, + D3D10_CBF_USERPACKED = D3D_CBF_USERPACKED, + D3D_CBF_FORCE_DWORD = 0x7fffffff +} D3D_SHADER_CBUFFER_FLAGS; + +typedef enum _D3D_CBUFFER_TYPE +{ + D3D_CT_CBUFFER = 0, + D3D_CT_TBUFFER = ( D3D_CT_CBUFFER + 1 ) , + D3D_CT_INTERFACE_POINTERS = ( D3D_CT_TBUFFER + 1 ) , + D3D_CT_RESOURCE_BIND_INFO = ( D3D_CT_INTERFACE_POINTERS + 1 ) , + D3D10_CT_CBUFFER = D3D_CT_CBUFFER, + D3D10_CT_TBUFFER = D3D_CT_TBUFFER, + D3D11_CT_CBUFFER = D3D_CT_CBUFFER, + D3D11_CT_TBUFFER = D3D_CT_TBUFFER, + D3D11_CT_INTERFACE_POINTERS = D3D_CT_INTERFACE_POINTERS, + D3D11_CT_RESOURCE_BIND_INFO = D3D_CT_RESOURCE_BIND_INFO +} D3D_CBUFFER_TYPE; + +#ifndef __D3D_SRV_DIMENSION__DEFINED__ +#define __D3D_SRV_DIMENSION__DEFINED__ + +typedef enum D3D_SRV_DIMENSION +{ + D3D_SRV_DIMENSION_UNKNOWN = 0, + D3D_SRV_DIMENSION_BUFFER = 1, + D3D_SRV_DIMENSION_TEXTURE1D = 2, + D3D_SRV_DIMENSION_TEXTURE1DARRAY = 3, + D3D_SRV_DIMENSION_TEXTURE2D = 4, + D3D_SRV_DIMENSION_TEXTURE2DARRAY = 5, + D3D_SRV_DIMENSION_TEXTURE2DMS = 6, + D3D_SRV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D_SRV_DIMENSION_TEXTURE3D = 8, + D3D_SRV_DIMENSION_TEXTURECUBE = 9, + D3D_SRV_DIMENSION_TEXTURECUBEARRAY = 10, + D3D_SRV_DIMENSION_BUFFEREX = 11, + D3D10_SRV_DIMENSION_UNKNOWN = D3D_SRV_DIMENSION_UNKNOWN, + D3D10_SRV_DIMENSION_BUFFER = D3D_SRV_DIMENSION_BUFFER, + D3D10_SRV_DIMENSION_TEXTURE1D = D3D_SRV_DIMENSION_TEXTURE1D, + D3D10_SRV_DIMENSION_TEXTURE1DARRAY = D3D_SRV_DIMENSION_TEXTURE1DARRAY, + D3D10_SRV_DIMENSION_TEXTURE2D = D3D_SRV_DIMENSION_TEXTURE2D, + D3D10_SRV_DIMENSION_TEXTURE2DARRAY = D3D_SRV_DIMENSION_TEXTURE2DARRAY, + D3D10_SRV_DIMENSION_TEXTURE2DMS = D3D_SRV_DIMENSION_TEXTURE2DMS, + D3D10_SRV_DIMENSION_TEXTURE2DMSARRAY = D3D_SRV_DIMENSION_TEXTURE2DMSARRAY, + D3D10_SRV_DIMENSION_TEXTURE3D = D3D_SRV_DIMENSION_TEXTURE3D, + D3D10_SRV_DIMENSION_TEXTURECUBE = D3D_SRV_DIMENSION_TEXTURECUBE, + D3D10_1_SRV_DIMENSION_UNKNOWN = D3D_SRV_DIMENSION_UNKNOWN, + D3D10_1_SRV_DIMENSION_BUFFER = D3D_SRV_DIMENSION_BUFFER, + D3D10_1_SRV_DIMENSION_TEXTURE1D = D3D_SRV_DIMENSION_TEXTURE1D, + D3D10_1_SRV_DIMENSION_TEXTURE1DARRAY = D3D_SRV_DIMENSION_TEXTURE1DARRAY, + D3D10_1_SRV_DIMENSION_TEXTURE2D = D3D_SRV_DIMENSION_TEXTURE2D, + D3D10_1_SRV_DIMENSION_TEXTURE2DARRAY = D3D_SRV_DIMENSION_TEXTURE2DARRAY, + D3D10_1_SRV_DIMENSION_TEXTURE2DMS = D3D_SRV_DIMENSION_TEXTURE2DMS, + D3D10_1_SRV_DIMENSION_TEXTURE2DMSARRAY = D3D_SRV_DIMENSION_TEXTURE2DMSARRAY, + D3D10_1_SRV_DIMENSION_TEXTURE3D = D3D_SRV_DIMENSION_TEXTURE3D, + D3D10_1_SRV_DIMENSION_TEXTURECUBE = D3D_SRV_DIMENSION_TEXTURECUBE, + D3D10_1_SRV_DIMENSION_TEXTURECUBEARRAY = D3D_SRV_DIMENSION_TEXTURECUBEARRAY, + D3D11_SRV_DIMENSION_UNKNOWN = D3D_SRV_DIMENSION_UNKNOWN, + D3D11_SRV_DIMENSION_BUFFER = D3D_SRV_DIMENSION_BUFFER, + D3D11_SRV_DIMENSION_TEXTURE1D = D3D_SRV_DIMENSION_TEXTURE1D, + D3D11_SRV_DIMENSION_TEXTURE1DARRAY = D3D_SRV_DIMENSION_TEXTURE1DARRAY, + D3D11_SRV_DIMENSION_TEXTURE2D = D3D_SRV_DIMENSION_TEXTURE2D, + D3D11_SRV_DIMENSION_TEXTURE2DARRAY = D3D_SRV_DIMENSION_TEXTURE2DARRAY, + D3D11_SRV_DIMENSION_TEXTURE2DMS = D3D_SRV_DIMENSION_TEXTURE2DMS, + D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY = D3D_SRV_DIMENSION_TEXTURE2DMSARRAY, + D3D11_SRV_DIMENSION_TEXTURE3D = D3D_SRV_DIMENSION_TEXTURE3D, + D3D11_SRV_DIMENSION_TEXTURECUBE = D3D_SRV_DIMENSION_TEXTURECUBE, + D3D11_SRV_DIMENSION_TEXTURECUBEARRAY = D3D_SRV_DIMENSION_TEXTURECUBEARRAY, + D3D11_SRV_DIMENSION_BUFFEREX = D3D_SRV_DIMENSION_BUFFEREX +} D3D_SRV_DIMENSION; + +#endif + +#ifndef __D3D_NAME__DEFINED__ +#define __D3D_NAME__DEFINED__ + +typedef enum D3D_NAME +{ + D3D_NAME_UNDEFINED = 0, + D3D_NAME_POSITION = 1, + D3D_NAME_CLIP_DISTANCE = 2, + D3D_NAME_CULL_DISTANCE = 3, + D3D_NAME_RENDER_TARGET_ARRAY_INDEX = 4, + D3D_NAME_VIEWPORT_ARRAY_INDEX = 5, + D3D_NAME_VERTEX_ID = 6, + D3D_NAME_PRIMITIVE_ID = 7, + D3D_NAME_INSTANCE_ID = 8, + D3D_NAME_IS_FRONT_FACE = 9, + D3D_NAME_SAMPLE_INDEX = 10, + D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR = 11, + D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR = 12, + D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR = 13, + D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR = 14, + D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR = 15, + D3D_NAME_FINAL_LINE_DENSITY_TESSFACTOR = 16, + D3D_NAME_BARYCENTRICS = 23, + D3D_NAME_SHADINGRATE = 24, + D3D_NAME_CULLPRIMITIVE = 25, + D3D_NAME_TARGET = 64, + D3D_NAME_DEPTH = 65, + D3D_NAME_COVERAGE = 66, + D3D_NAME_DEPTH_GREATER_EQUAL = 67, + D3D_NAME_DEPTH_LESS_EQUAL = 68, + D3D10_NAME_UNDEFINED = D3D_NAME_UNDEFINED, + D3D10_NAME_POSITION = D3D_NAME_POSITION, + D3D10_NAME_CLIP_DISTANCE = D3D_NAME_CLIP_DISTANCE, + D3D10_NAME_CULL_DISTANCE = D3D_NAME_CULL_DISTANCE, + D3D10_NAME_RENDER_TARGET_ARRAY_INDEX = D3D_NAME_RENDER_TARGET_ARRAY_INDEX, + D3D10_NAME_VIEWPORT_ARRAY_INDEX = D3D_NAME_VIEWPORT_ARRAY_INDEX, + D3D10_NAME_VERTEX_ID = D3D_NAME_VERTEX_ID, + D3D10_NAME_PRIMITIVE_ID = D3D_NAME_PRIMITIVE_ID, + D3D10_NAME_INSTANCE_ID = D3D_NAME_INSTANCE_ID, + D3D10_NAME_IS_FRONT_FACE = D3D_NAME_IS_FRONT_FACE, + D3D10_NAME_SAMPLE_INDEX = D3D_NAME_SAMPLE_INDEX, + D3D10_NAME_TARGET = D3D_NAME_TARGET, + D3D10_NAME_DEPTH = D3D_NAME_DEPTH, + D3D10_NAME_COVERAGE = D3D_NAME_COVERAGE, + D3D11_NAME_FINAL_QUAD_EDGE_TESSFACTOR = D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR, + D3D11_NAME_FINAL_QUAD_INSIDE_TESSFACTOR = D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR, + D3D11_NAME_FINAL_TRI_EDGE_TESSFACTOR = D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR, + D3D11_NAME_FINAL_TRI_INSIDE_TESSFACTOR = D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR, + D3D11_NAME_FINAL_LINE_DETAIL_TESSFACTOR = D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR, + D3D11_NAME_FINAL_LINE_DENSITY_TESSFACTOR = D3D_NAME_FINAL_LINE_DENSITY_TESSFACTOR, + D3D11_NAME_DEPTH_GREATER_EQUAL = D3D_NAME_DEPTH_GREATER_EQUAL, + D3D11_NAME_DEPTH_LESS_EQUAL = D3D_NAME_DEPTH_LESS_EQUAL +} D3D_NAME; + +#endif // __D3D_NAME__DEFINED__ + +typedef enum D3D_RESOURCE_RETURN_TYPE +{ + D3D_RETURN_TYPE_UNORM = 1, + D3D_RETURN_TYPE_SNORM = 2, + D3D_RETURN_TYPE_SINT = 3, + D3D_RETURN_TYPE_UINT = 4, + D3D_RETURN_TYPE_FLOAT = 5, + D3D_RETURN_TYPE_MIXED = 6, + D3D_RETURN_TYPE_DOUBLE = 7, + D3D_RETURN_TYPE_CONTINUED = 8, + D3D10_RETURN_TYPE_UNORM = D3D_RETURN_TYPE_UNORM, + D3D10_RETURN_TYPE_SNORM = D3D_RETURN_TYPE_SNORM, + D3D10_RETURN_TYPE_SINT = D3D_RETURN_TYPE_SINT, + D3D10_RETURN_TYPE_UINT = D3D_RETURN_TYPE_UINT, + D3D10_RETURN_TYPE_FLOAT = D3D_RETURN_TYPE_FLOAT, + D3D10_RETURN_TYPE_MIXED = D3D_RETURN_TYPE_MIXED, + D3D11_RETURN_TYPE_UNORM = D3D_RETURN_TYPE_UNORM, + D3D11_RETURN_TYPE_SNORM = D3D_RETURN_TYPE_SNORM, + D3D11_RETURN_TYPE_SINT = D3D_RETURN_TYPE_SINT, + D3D11_RETURN_TYPE_UINT = D3D_RETURN_TYPE_UINT, + D3D11_RETURN_TYPE_FLOAT = D3D_RETURN_TYPE_FLOAT, + D3D11_RETURN_TYPE_MIXED = D3D_RETURN_TYPE_MIXED, + D3D11_RETURN_TYPE_DOUBLE = D3D_RETURN_TYPE_DOUBLE, + D3D11_RETURN_TYPE_CONTINUED = D3D_RETURN_TYPE_CONTINUED +} D3D_RESOURCE_RETURN_TYPE; + +#ifndef __D3D_REGISTER_COMPONENT_TYPE__DEFINED__ +#define __D3D_REGISTER_COMPONENT_TYPE__DEFINED__ + +typedef enum D3D_REGISTER_COMPONENT_TYPE +{ + D3D_REGISTER_COMPONENT_UNKNOWN = 0, + D3D_REGISTER_COMPONENT_UINT32 = 1, + D3D_REGISTER_COMPONENT_SINT32 = 2, + D3D_REGISTER_COMPONENT_FLOAT32 = 3, + D3D10_REGISTER_COMPONENT_UNKNOWN = D3D_REGISTER_COMPONENT_UNKNOWN, + D3D10_REGISTER_COMPONENT_UINT32 = D3D_REGISTER_COMPONENT_UINT32, + D3D10_REGISTER_COMPONENT_SINT32 = D3D_REGISTER_COMPONENT_SINT32, + D3D10_REGISTER_COMPONENT_FLOAT32 = D3D_REGISTER_COMPONENT_FLOAT32 +} D3D_REGISTER_COMPONENT_TYPE; + +#endif // __D3D_REGISTER_COMPONENT_TYPE__DEFINED__ + +typedef enum D3D_TESSELLATOR_DOMAIN +{ + D3D_TESSELLATOR_DOMAIN_UNDEFINED = 0, + D3D_TESSELLATOR_DOMAIN_ISOLINE = 1, + D3D_TESSELLATOR_DOMAIN_TRI = 2, + D3D_TESSELLATOR_DOMAIN_QUAD = 3, + D3D11_TESSELLATOR_DOMAIN_UNDEFINED = D3D_TESSELLATOR_DOMAIN_UNDEFINED, + D3D11_TESSELLATOR_DOMAIN_ISOLINE = D3D_TESSELLATOR_DOMAIN_ISOLINE, + D3D11_TESSELLATOR_DOMAIN_TRI = D3D_TESSELLATOR_DOMAIN_TRI, + D3D11_TESSELLATOR_DOMAIN_QUAD = D3D_TESSELLATOR_DOMAIN_QUAD +} D3D_TESSELLATOR_DOMAIN; + +typedef enum D3D_TESSELLATOR_PARTITIONING +{ + D3D_TESSELLATOR_PARTITIONING_UNDEFINED = 0, + D3D_TESSELLATOR_PARTITIONING_INTEGER = 1, + D3D_TESSELLATOR_PARTITIONING_POW2 = 2, + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD = 3, + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN = 4, + D3D11_TESSELLATOR_PARTITIONING_UNDEFINED = D3D_TESSELLATOR_PARTITIONING_UNDEFINED, + D3D11_TESSELLATOR_PARTITIONING_INTEGER = D3D_TESSELLATOR_PARTITIONING_INTEGER, + D3D11_TESSELLATOR_PARTITIONING_POW2 = D3D_TESSELLATOR_PARTITIONING_POW2, + D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD = D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD, + D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN = D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN +} D3D_TESSELLATOR_PARTITIONING; + +typedef enum D3D_TESSELLATOR_OUTPUT_PRIMITIVE +{ + D3D_TESSELLATOR_OUTPUT_UNDEFINED = 0, + D3D_TESSELLATOR_OUTPUT_POINT = 1, + D3D_TESSELLATOR_OUTPUT_LINE = 2, + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CW = 3, + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CCW = 4, + D3D11_TESSELLATOR_OUTPUT_UNDEFINED = D3D_TESSELLATOR_OUTPUT_UNDEFINED, + D3D11_TESSELLATOR_OUTPUT_POINT = D3D_TESSELLATOR_OUTPUT_POINT, + D3D11_TESSELLATOR_OUTPUT_LINE = D3D_TESSELLATOR_OUTPUT_LINE, + D3D11_TESSELLATOR_OUTPUT_TRIANGLE_CW = D3D_TESSELLATOR_OUTPUT_TRIANGLE_CW, + D3D11_TESSELLATOR_OUTPUT_TRIANGLE_CCW = D3D_TESSELLATOR_OUTPUT_TRIANGLE_CCW +} D3D_TESSELLATOR_OUTPUT_PRIMITIVE; + + +// +// ID3D10Blob +// + +struct D3D10Blob_Function_Table +{ + GraphicsUnknown_Function_Table UnknownFunction; + + LPVOID (D3DAPI* GetBufferPointer)( + _Inout_ ID3D10Blob* pBlob); + + SIZE_T (D3DAPI* GetBufferSize)( + _Inout_ ID3D10Blob* pBlob); +}; + + +} + +D3DINTERFACE(ID3D10Blob, 8BA5FB08,5195,40e2,AC,58,0D,98,9C,3A,01,02) : public IGraphicsUnknown +{ +public: + + void* m_pBuffer; + SIZE_T m_SizeInBytes; + +public: + + D3DINLINE D3D10Blob_Function_Table* BlobFunction() + { + return (D3D10Blob_Function_Table*)m_pFunction; + } + + D3DINLINE LPVOID D3DAPI GetBufferPointer() + { + return BlobFunction()->GetBufferPointer(this); + } + + D3DINLINE SIZE_T D3DAPI GetBufferSize() + { + return BlobFunction()->GetBufferSize(this); + } +}; + +typedef struct ID3D10Blob* LPD3D10BLOB; +typedef ID3D10Blob ID3DBlob; +typedef ID3DBlob* LPD3DBLOB; +#define IID_ID3DBlob IID_ID3D10Blob + + +// +// ID3DInclude +// + +typedef interface ID3DInclude ID3DInclude; +#undef INTERFACE +#define INTERFACE ID3DInclude +DECLARE_INTERFACE(ID3DInclude) +{ + STDMETHOD(Open)(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) PURE; + STDMETHOD(Close)(THIS_ LPCVOID pData) PURE; +}; + +typedef ID3DInclude* LPD3DINCLUDE; + +extern "C" +{ + +/////////////////////////////////////////////////////////////////////////// +// D3DFlushCpuCache +// ------------------ +// +// pAddress +// A valid CPU virtual address, pointing to graphics memory or committed CPU memory. +// SizeBytes +// The size in bytes of the memory to flush from the CPU caches. +// +// Return Values +// No return value. +// +/////////////////////////////////////////////////////////////////////////// +D3DINLINE VOID D3DAPI D3DFlushCpuCache( + const VOID* pAddress, + SIZE_T SizeBytes ) +{ + _mm_mfence(); + BYTE* p = (BYTE*)( (SIZE_T)pAddress & ~(SIZE_T)0x3f ); + BYTE* pEndAddress = (BYTE*)( ( (SIZE_T)( p + SizeBytes ) + (SIZE_T)0x3f ) & ~(SIZE_T)0x3f ); + while ( p < pEndAddress ) + { + _mm_clflush( p ); + p += 64; + } + _mm_mfence(); +} + +/////////////////////////////////////////////////////////////////////////// +// D3DFlushEntireCpuCache +// ------------------ +// +// Flushes the entire CPU cache using the wbinvd instruction, executed from +// kernel mode. Flushing the entire cache may be faster than executing long +// sequences of mm_clflush instructions. +// +// Return Values +// No return value. +// +/////////////////////////////////////////////////////////////////////////// +VOID D3DAPI D3DFlushEntireCpuCache(); + +typedef enum D3D11_CREATE_DEFERRED_CONTEXT_FLAG +{ + D3D11_CREATE_DEFERRED_CONTEXT_LONG_LIFE_COMMAND_LISTS = 0x10000, + D3D11_CREATE_DEFERRED_CONTEXT_DRAW_BUNDLES = 0x20000, + D3D11_CREATE_DEFERRED_CONTEXT_TITLE_MANAGED_COMMAND_LIST_OBJECT_LIFETIMES = 0x40000, + D3D11_CREATE_DEFERRED_CONTEXT_FAST_SEMANTICS = 0x80000, +} D3D11_CREATE_DEFERRED_CONTEXT_FLAG; + +} + + +extern "C" +{ + +//------------------------------------------------------------------------------------------------- + +HRESULT D3DAPI D3D10CreateBlob( + _In_ SIZE_T NumBytes, + _Out_opt_ LPD3D10BLOB* ppBuffer); + + +} + + +// +// D3D12_X +// + +extern "C" +{ + +//-------------------------------------------------------------------------------------------------- +// Xbox One hardware definitions for Build-Your-Own-Bundle support. +//-------------------------------------------------------------------------------------------------- + +// These are the Command Processor dword packet headers for high-frequency D3D12 APIs. +static const UINT32 D3D12XBOX_PACKET_DRAW_INDEXED_INSTANCED = 0x4004c200; +static const UINT32 D3D12XBOX_PACKET_DRAW_INSTANCED = 0x4003c300; +static const UINT32 D3D12XBOX_PACKET_DISPATCH = 0x4002c400; +static const UINT32 D3D12XBOX_PACKET_SET_PRIMITIVE_TOPOLOGY = 0xc000b600; +static const UINT32 D3D12XBOX_PACKET_SET_INDEX_BUFFER = 0x4001b700; +static const UINT32 D3D12XBOX_PACKET_SET_STENCIL_REF = 0xc000b800; +static const UINT32 D3D12XBOX_PACKET_SET_VERTEX_BUFFERS = 0x3fffc600; // Encoded dword count of 0 +static const UINT32 D3D12XBOX_PACKET_CLEAR_VERTEX_BUFFERS = 0x4000c700; +static const UINT32 D3D12XBOX_PACKET_DISPATCH_X = 0x4003cc00; +static const UINT32 D3D12XBOX_PACKET_DRAW_INDEXED_X = 0x4004cd00; +static const UINT32 D3D12XBOX_PACKET_NOP = 0x80000000; +static const UINT32 D3D12XBOX_PACKET_NOP_WITH_COUNT = 0xbffe1000; // Encoded total packet size of 0 +static const UINT32 D3D12XBOX_PACKET_DISPATCH_MESH = 0x4003d500; + +// Fast path versions that don't handle shader memory a.k.a. 'shmem' +static const UINT32 D3D12XBOX_PACKET_DRAW_INSTANCED_NO_SHMEM = 0x4003e600; +static const UINT32 D3D12XBOX_PACKET_DRAW_INDEXED_INSTANCED_NO_SHMEM = 0x4004e700; +static const UINT32 D3D12XBOX_PACKET_DISPATCH_NO_SHMEM = 0x4002e800; + +// Command Processor packets encode the dword count minus one at bit 16. The above packet +// header constants already have pre-built sizes for all the fixed size packets, and default +// counts for the variable-sized packets as noted: +static const UINT32 D3D12XBOX_PACKET_COUNT_SHIFT = 16; + +// The SET_VERTEX_BUFFERS packet takes a qword for every vertex buffer where the GPU virtual +// address is in the low 48 bits and the stride, in bytes, in the high 16 bits: +static const UINT32 D3D12XBOX_SET_VERTEX_BUFFERS_STRIDE_SHIFT64 = 48; + +// This table converts from the D3D API topology enumerant value to the corresponding hardware +// version to be fed to the VGT_PRIMITIVE_TYPE register. Note that the non-patch transformation +// is almost identity except for D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5 where TRISTRIP = 6. +static const UINT8 D3D12XBOX_SET_PRIMITIVE_TOPOLOGY_LOOKUP[] = +{ + 0, // NONE, // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED = 0 + 1, // POINTLIST, // D3D_PRIMITIVE_TOPOLOGY_POINTLIST = 1 + 2, // LINELIST, // D3D_PRIMITIVE_TOPOLOGY_LINELIST = 2 + 3, // LINESTRIP, // D3D_PRIMITIVE_TOPOLOGY_LINESTRIP = 3 + 4, // TRILIST, // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4 + 6, // TRISTRIP, // D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5 + 5, // TRIFAN, // D3D_PRIMITIVE_TOPOLOGY_TRIANGLEFAN = 6 (Xbox extension) + 0, // 0, // 7 + 0, // 0, // 8 + 0, // 0, // 9 + 10, // LINELIST_ADJ, // D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10 + 11, // LINESTRIP_ADJ, // D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11 + 12, // TRILIST_ADJ, // D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12 + 13, // TRISTRIP_ADJ, // D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13 + 0, // 0, // 14 + 0, // 0, // 15 + 16, // TRI_WITH_WFLAGS, // 16 + 17, // RECTLIST, // D3D_PRIMITIVE_TOPOLOGY_RECTLIST = 17 (Xbox extension) + 18, // LINELOOP, // D3D_PRIMITIVE_TOPOLOGY_LINELOOP = 18 (Xbox extension) + 19, // QUADLIST, // D3D_PRIMITIVE_TOPOLOGY_QUADLIST = 19 (Xbox extension) + 20, // QUADSTRIP, // D3D_PRIMITIVE_TOPOLOGY_QUADSTRIP = 20 (Xbox extension) + 21, // POLYGON, // 21 + 22, // 2D_COPY_RECT_LIST_V0, // 22 + 23, // 2D_COPY_RECT_LIST_V1, // 23 + 24, // 2D_COPY_RECT_LIST_V2, // 24 + 25, // 2D_COPY_RECT_LIST_V3, // 25 + 26, // 2D_FILL_RECT_LIST, // 26 + 27, // 2D_LINE_STRIP, // 27 + 28, // 2D_TRI_STRIP, // 28 + 0, // 0, // 29 + 0, // 0, // 30 + 0, // 0, // 31 + 0, // 0, // 32 + + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = 33 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = 34 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = 35 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = 36 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = 37 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = 38 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = 39 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = 40 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = 41 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = 42 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = 43 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = 44 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = 45 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = 46 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = 47 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = 48 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = 49 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = 50 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = 51 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = 52 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = 53 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = 54 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = 55 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = 56 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = 57 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = 58 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = 59 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = 60 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = 61 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = 62 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = 63 + 9, // PATCH, // D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = 64 +}; + +namespace GPUPerfCounters +{ +typedef enum GC_ATC_L2_PERFCOUNTER_SELECT : unsigned int { + GC_ATC_L2_PERF_SEL_count_cycles = 0x00000000, // always counts + GC_ATC_L2_PERF_SEL_L1_requests = 0x00000001, // number of L1 requests + GC_ATC_L2_PERF_SEL_bank0_requests = 0x00000002, // number of bank0 requests + GC_ATC_L2_PERF_SEL_bank0_hits = 0x00000003, // number of bank0 hits + GC_ATC_L2_PERF_SEL_bank0_misses = 0x00000004, // number of bank0 misses + GC_ATC_L2_PERF_SEL_ATS_requests = 0x00000005, // number of ATS Requests + GC_ATC_L2_PERF_SEL_ATS_responses = 0x00000006, // number of ATS Responses + GC_ATC_L2_PERF_SEL_invalidate_requests = 0x00000007, // number of invalidate request + GC_ATC_L2_PERF_SEL_flushtype_invalidate_requests = 0x00000008, // number of flushtype invalidate request +} GC_ATC_L2_PERFCOUNTER_SELECT; + +typedef enum CB_PERFCOUNTER_SELECT : unsigned int { + CB_PERF_SEL_NONE = 0x00000000, // Count nothing + CB_PERF_SEL_BUSY = 0x00000001, // Number of busy cycles + CB_PERF_SEL_CORE_SCLK_VLD = 0x00000002, // Number of cycles that the core clock is enabled. + CB_PERF_SEL_REG_SCLK0_VLD = 0x00000003, // Number of cycles that the register clock is enabled. (Non-harvestable) + CB_PERF_SEL_REG_SCLK1_VLD = 0x00000004, // Number of cycles that the register clock is enabled. (harvestable) + CB_PERF_SEL_DRAWN_QUAD = 0x00000005, // This is the number of drawn quads. Use CB_PERF_SEL_DRAWN_BUSY as denominator to get per clock rates. Filtering using CB_PERFCOUNTER_FILTER fields has an effect in this mode. + CB_PERF_SEL_DRAWN_PIXEL = 0x00000006, // This is the number of drawn pixels. Use CB_PERF_SEL_DRAWN_BUSY as denominator to get per clock rates. Filtering using CB_PERFCOUNTER_FILTER fields has an effect in this mode. + CB_PERF_SEL_DRAWN_QUAD_FRAGMENT = 0x00000007, // This is the number of drawn quad fragments. Use CB_PERF_SEL_DRAWN_BUSY as denominator to get per clock rates. Filtering using CB_PERFCOUNTER_FILTER fields has an effect in this mode. + CB_PERF_SEL_DRAWN_TILE = 0x00000008, // This is the number of drawn tiles. Use CB_PERF_SEL_DRAWN_BUSY as denominator to get per clock rates. Filtering using CB_PERFCOUNTER_FILTER fields has an effect in this mode. This counter is slightly broken in that it actually counts the number of tiles reaching fragop. Some of these tiles may be empty when there is fast clear or compression. + CB_PERF_SEL_DB_CB_TILE_VALID_READY = 0x00000009, // Number of cycles the DB to CB tile interface is valid and ready. This is measured after the input fifo. It counts tiles + events. Subtract CB_PERF_SEL_EVENT to get the count of tiles + CB_PERF_SEL_DB_CB_TILE_VALID_READYB = 0x0000000a, // Number of cycles the DB to CB tile interface is valid and not ready. This is measured after the input fifo. + CB_PERF_SEL_DB_CB_TILE_VALIDB_READY = 0x0000000b, // Number of cycles the DB to CB tile interface is not valid and ready. This is measured after the input fifo. + CB_PERF_SEL_DB_CB_TILE_VALIDB_READYB = 0x0000000c, // Number of cycles the DB to CB tile interface is not valid and not ready. This is measured after the input fifo. + CB_PERF_SEL_CM_FC_TILE_VALID_READY = 0x0000000d, // Number of cycles the cmask to fmask tile interface is valid and ready. This interface counts tile times enabled render targets plus events. This will be different from CB_PERF_SEL_DB_CB_TILE_VALID_READY because each tile is replicated by the number of enabled render targets (events are not) + CB_PERF_SEL_CM_FC_TILE_VALID_READYB = 0x0000000e, // Number of cycles the cmask to fmask tile interface is valid and not ready + CB_PERF_SEL_CM_FC_TILE_VALIDB_READY = 0x0000000f, // Number of cycles the cmask to fmask tile interface is not valid and ready + CB_PERF_SEL_CM_FC_TILE_VALIDB_READYB = 0x00000010, // Number of cycles the cmask to fmask tile interface is not valid and not ready + CB_PERF_SEL_MERGE_TILE_ONLY_VALID_READY = 0x00000011, // Number of cycles the Merge tile interface has a valid tile-only tile and is ready. Measured at tile input to merge. + CB_PERF_SEL_MERGE_TILE_ONLY_VALID_READYB = 0x00000012, // Number of cycles the Merge tile interface has a valid tile-only tile and is not ready. Measured at tile input to merge. + CB_PERF_SEL_DB_CB_LQUAD_VALID_READY = 0x00000013, // Number of cycles the DB to CB lquad interface is valid and ready. This is measured after the input fifo. This is counting lquad which for fast modes are the same as quads but for slow mode are twice the number of quads. To get the number of quads on this interface use: CB_PERF_SEL_DB_CB_LQUAD_VALID_READY - CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_32_ABGR/2 + CB_PERF_SEL_DB_CB_LQUAD_VALID_READYB = 0x00000014, // Number of cycles the DB to CB lquad interface is valid and not ready. This is measured after the input fifo + CB_PERF_SEL_DB_CB_LQUAD_VALIDB_READY = 0x00000015, // Number of cycles the DB to CB lquad interface is not valid and ready. This is measured after the input fifo + CB_PERF_SEL_DB_CB_LQUAD_VALIDB_READYB = 0x00000016, // Number of cycles the DB to CB lquad interface is not valid and not ready. This is measured after the input fifo + CB_PERF_SEL_LQUAD_NO_TILE = 0x00000017, // Number of cycles that a quad has arrived over the lquad interface but the corresponding tile has not arrived yet. + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_32_R = 0x00000018, // Number of transactions/quads on the DB_CB_lquad interface that use the EXPORT_32_R (FAST MODE) format. Sum of all CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* should match CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_32_AR = 0x00000019, // Number of transactions/quads on the DB_CB_lquad interface that use the EXPORT_32_AR (FAST MODE) format. Sum of all CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* should match CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_32_GR = 0x0000001a, // Number of transactions/quads on the DB_CB_lquad interface that use the EXPORT_32_GR (FAST MODE) format. Sum of all CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* should match CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_32_ABGR = 0x0000001b, // Number of transactions on the DB_CB_lquad interface that use the EXPORT_32_ABGR (SLOW MODE) format. To get the number of quads divide this number by 2. Sum of all CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* should match CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_FP16_ABGR = 0x0000001c, // Number of transactions/quads on the DB_CB_lquad interface that use the EXPORT_FP16_ABGR (FAST MODE) format. Sum of all CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* should match CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_SIGNED16_ABGR = 0x0000001d, // Number of transactions/quads on the DB_CB_lquad interface that use the EXPORT_SIGNED16_ABGR (FAST MODE) format. Sum of all CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* should match CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_UNSIGNED16_ABGR = 0x0000001e, // Number of transactions/quads on the DB_CB_lquad interface that use the EXPORT_UNSIGNED16_ABGR (FAST MODE) format. Sum of all CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* should match CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_QUAD_KILLED_BY_EXTRA_PIXEL_EXPORT = 0x0000001f, // Number of quads that were killed because they were an extra pixel export from the shader based on CB_TARGET_MASK, CB_SHADER_MASK settings. + CB_PERF_SEL_QUAD_KILLED_BY_COLOR_INVALID = 0x00000020, // Number of quads that was killed because their render target had CB_COLOR_INFO.FORMAT set to invalid. + CB_PERF_SEL_QUAD_KILLED_BY_NULL_TARGET_SHADER_MASK = 0x00000021, // Number of quads that were killed because of null (target&shader) mask. + CB_PERF_SEL_QUAD_KILLED_BY_NULL_SAMPLE_MASK = 0x00000022, // Number of quads that were killed because of a null sample mask. + CB_PERF_SEL_QUAD_KILLED_BY_DISCARD_PIXEL = 0x00000023, // Number of quads that were killed because they were blending but enabled optimization to discard all the pixels of the quad. This optimization can be disabled by setting DISABLE_BLEND_OPT_DISCARD_PIXEL. + CB_PERF_SEL_FC_CLEAR_QUAD_VALID_READY = 0x00000024, // Number of cycles in the fmask logic that the read_latency fifo to the clear interface is valid and ready. This is counting quads + events. The number of quads should match the number of quads on the lquad interface (i.e. CB_PERF_SEL_DB_CB_LQUAD_VALID_READY - CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_32_ABGR/2) minus any quads that are dropped and show up in the perf counters CB_PERF_SEL_QUAD_KILLED_BY_* + CB_PERF_SEL_FC_CLEAR_QUAD_VALID_READYB = 0x00000025, // Number of cycles in the fmask logic that the read_latency fifo to the clear interface is valid and not ready. + CB_PERF_SEL_FC_CLEAR_QUAD_VALIDB_READY = 0x00000026, // Number of cycles in the fmask logic that the read_latency fifo to the clear interface is not valid and ready. + CB_PERF_SEL_FC_CLEAR_QUAD_VALIDB_READYB = 0x00000027, // Number of cycles in the fmask logic that the read_latency fifo to the clear interface is not valid and not ready. + CB_PERF_SEL_FOP_IN_VALID_READY = 0x00000028, // Number of cycles the fragop unit input interface is valid and ready. This is counting quads + events. The number of quads here should match CB_PERF_SEL_FC_CLEAR_QUAD_VALID_READY plus any quads inserted by the fast_clear_eliminate (fc_clear) block + CB_PERF_SEL_FOP_IN_VALID_READYB = 0x00000029, // Number of cycles the fragop unit input interface is valid and not ready + CB_PERF_SEL_FOP_IN_VALIDB_READY = 0x0000002a, // Number of cycles the fragop unit input interface is not valid and ready + CB_PERF_SEL_FOP_IN_VALIDB_READYB = 0x0000002b, // Number of cycles the fragop unit input interface is not valid and not ready + CB_PERF_SEL_FC_CC_QUADFRAG_VALID_READY = 0x0000002c, // Number of cycles the fmask to color cache interface is valid and ready. This is counting quad fragments + events. The number of quads here should match CB_PERF_SEL_FOP_IN_VALID_READY times the number of fragments created for each of these quads by the fragop block + CB_PERF_SEL_FC_CC_QUADFRAG_VALID_READYB = 0x0000002d, // Number of cycles the fmask to color cache interface is valid and not ready + CB_PERF_SEL_FC_CC_QUADFRAG_VALIDB_READY = 0x0000002e, // Number of cycles the fmask to color cache interface is not valid and ready + CB_PERF_SEL_FC_CC_QUADFRAG_VALIDB_READYB = 0x0000002f, // Number of cycles the fmask to color cache interface is not valid and not ready + CB_PERF_SEL_CC_IB_SR_FRAG_VALID_READY = 0x00000030, // Number of cycles the color cache input block's serializer interface is valid and ready. This is counting quad fragments + events. The number of quads here should match CB_PERF_SEL_FC_CC_QUADFRAG_VALID_READY times the number of cycles needed to handle these quads due to any HW limitations like 32bit floating point blending, linear or linear_aligned array mode etc + CB_PERF_SEL_CC_IB_SR_FRAG_VALID_READYB = 0x00000031, // Number of cycles the color cache input block's serializer two-lookup interface is valid and not ready + CB_PERF_SEL_CC_IB_SR_FRAG_VALIDB_READY = 0x00000032, // Number of cycles the color cache input block's serializer two-lookup interface is not valid and ready + CB_PERF_SEL_CC_IB_SR_FRAG_VALIDB_READYB = 0x00000033, // Number of cycles the color cache input block's serializer to two-lookup interface is not valid and not ready + CB_PERF_SEL_CC_IB_TB_FRAG_VALID_READY = 0x00000034, // Number of cycles the color cache input block to tag block interface is valid and ready. This is counting quad fragments + events. The number of quads here should match CB_PERF_SEL_CC_IB_SR_FRAG_VALID_READY + CB_PERF_SEL_TWO_PROBE_QUAD_FRAGMENT. + CB_PERF_SEL_CC_IB_TB_FRAG_VALID_READYB = 0x00000035, // Number of cycles the color cache input block to tag block interface is valid and not ready + CB_PERF_SEL_CC_IB_TB_FRAG_VALIDB_READY = 0x00000036, // Number of cycles the color cache input block to tag block interface is not valid and ready + CB_PERF_SEL_CC_IB_TB_FRAG_VALIDB_READYB = 0x00000037, // Number of cycles the color cache input block to tag block interface is not valid and not ready + CB_PERF_SEL_CC_RB_BC_EVENFRAG_VALID_READY = 0x00000038, // Number of cycles the reorder_buffer to blend_control interface (evenfrag) is valid and ready. This is counting quad fragments + events. The number of quads in (CB_PERF_SEL_CC_RB_BC_EVENFRAG_VALID_READY + CB_PERF_SEL_CC_RB_BC_ODDFRAG_VALID_READY) equals quads in CB_PERF_SEL_CC_IB_SR_FRAG_VALID_READY as the de-serializer collapses the two cache probe quads back into one. The quads are split into two fifos, evenfifo stores the quads with even 32B address. Events go down both paths + CB_PERF_SEL_CC_RB_BC_EVENFRAG_VALID_READYB = 0x00000039, // Number of cycles the reorder_buffer to blend_control interface (evenfrag) is valid and not ready + CB_PERF_SEL_CC_RB_BC_EVENFRAG_VALIDB_READY = 0x0000003a, // Number of cycles the reorder_buffer to blend_control interface (evenfrag) is not valid and ready + CB_PERF_SEL_CC_RB_BC_EVENFRAG_VALIDB_READYB = 0x0000003b, // Number of cycles the reorder_buffer to blend_control interface (evenfrag) is not valid and not ready + CB_PERF_SEL_CC_RB_BC_ODDFRAG_VALID_READY = 0x0000003c, // Number of cycles the reorder_buffer to blend_control interface (oddfrag) is valid and ready. This is counting quad fragments + events. The number of quads in (CB_PERF_SEL_CC_RB_BC_EVENFRAG_VALID_READY + CB_PERF_SEL_CC_RB_BC_ODDFRAG_VALID_READY) equals quads in CB_PERF_SEL_CC_IB_SR_FRAG_VALID_READY as the de-serializer collapses the two cache probe quads back into one. The quads are split into two fifos, oddfifo stores the quads with odd 32B address. Events go down both paths + CB_PERF_SEL_CC_RB_BC_ODDFRAG_VALID_READYB = 0x0000003d, // Number of cycles the reorder_buffer to blend_control interface (oddfrag) is valid and not ready + CB_PERF_SEL_CC_RB_BC_ODDFRAG_VALIDB_READY = 0x0000003e, // Number of cycles the reorder_buffer to blend_control interface (oddfrag) is not valid and ready + CB_PERF_SEL_CC_RB_BC_ODDFRAG_VALIDB_READYB = 0x0000003f, // Number of cycles the reorder_buffer to blend_control interface (oddfrag) is not valid and not ready + CB_PERF_SEL_CC_BC_CS_FRAG_VALID = 0x00000040, // Number of cycles the blend_control to cache_storage interface is valid. This is counting quad fragments + events. The number of quads here should match CB_PERF_SEL_CC_IB_SR_FRAG_VALID_READY + CB_PERF_SEL_CM_CACHE_HIT = 0x00000041, // Number of tile transactions that hit cmask cache (TAG HIT && SECTOR HIT). It is a hit if you hit the tag and a sector in that tag meaning that sector's data is valid. Total probe transactions = incoming tile transactions (in compressed AA mode or single sample with fast clear mode) times render targets = CB_PERF_SEL_CM_CACHE_HIT+CB_PERF_SEL_CM_CACHE_SECTOR_MISS. + CB_PERF_SEL_CM_CACHE_TAG_MISS = 0x00000042, // Number of tile transactions that have cmask cache tag misses (TAG MISS). A tag miss is when there isn't a tag that matches the input. Because of sectoring, a tag hit does not imply that the required data is in the cache (i.e TAG HIT && SECTOR MISS). + CB_PERF_SEL_CM_CACHE_SECTOR_MISS = 0x00000043, // Number of tile transactions that have cmask cache sector miss (TAG MISS || SECTOR MISS). A sector miss is when the required sector is not in the cache. Tag misses are included in this count because a sector cannot be in the cache if there is no tag for it. Total transactions that have TAG HIT && SECTOR MISS = CB_PERF_SEL_CM_CACHE_SECTOR_MISS - CB_PERF_SEL_CM_CACHE_TAG_MISS + CB_PERF_SEL_CM_CACHE_REEVICTION_STALL = 0x00000044, // Number of cycles the cmask cache is stalled because it is trying to evict a line that already has a pending evict. This can happen when a cacheline has been written out to memory and waiting for the write ack gets a hit again, eventually becoming dirty and needing to be re-evicted. Since only one eviction per cacheline can be outstanding, the cache is stalled + CB_PERF_SEL_CM_CACHE_EVICT_NONZERO_INFLIGHT_STALL = 0x00000045, // Number of cycles the cmask cache is stalled because it is trying to evict a line that has a nonzero inflight count. When a cachelines LRU count reaches the scaled eviction point set by CM_CACHE_EVICT_POINT and it is still inflight then this counter get incremented This is usually a sign that the cache is unable to withstand the memory read latency. CM_CACHE_EVICT_POINT can be set to a LOWER value to handle the increased read latency + CB_PERF_SEL_CM_CACHE_REPLACE_PENDING_EVICT_STALL = 0x00000046, // Number of cycles the cmask cache is stalled because the line being replaced has a pending evict. This happens when the cacheline chosen for allocation on a miss is still waiting for its write-ack to return from a previous eviction. This is usually a sign that the cache is unable to withstand the memory write latency. CM_CACHE_EVICT_POINT can be set to a HIGHER value to handle the increased write latency + CB_PERF_SEL_CM_CACHE_INFLIGHT_COUNTER_MAXIMUM_STALL = 0x00000047, // Number of cycles the cmask cache is stalled because one of the inflight counters has reached the maximum value. + CB_PERF_SEL_CM_CACHE_READ_OUTPUT_STALL = 0x00000048, // Number of cycles the cmask cache is stalled because the read request output path is stalled. This can happen due to increased memory read request ask-go latency + CB_PERF_SEL_CM_CACHE_WRITE_OUTPUT_STALL = 0x00000049, // Number of cycles the cmask cache is stalled because the write request output path is stalled. This can happen due to increased memory write request ask-go latency + CB_PERF_SEL_CM_CACHE_ACK_OUTPUT_STALL = 0x0000004a, // Number of cycles the cmask cache is stalled because the acknowledge output path is stalled. This can happen if the next stage in the pipeline (cmask cache read latency hiding fifo) is full and stalling the cmask cache so the cache cannot output any transactions. + CB_PERF_SEL_CM_CACHE_STALL = 0x0000004b, // Number of cycles the cmask cache is stalled. This is the combined cache stall signal. + CB_PERF_SEL_CM_CACHE_FLUSH = 0x0000004c, // This is the number of cmask cache flushes. + CB_PERF_SEL_CM_CACHE_TAGS_FLUSHED = 0x0000004d, // Number of dirty tags that are flushed (the cmask cache has 32 tags). + CB_PERF_SEL_CM_CACHE_SECTORS_FLUSHED = 0x0000004e, // Number of valid sectors (i.e they have valid data) per dirty tags that are flushed (the cmask cache has 1 sector per tag). The valid sectors may be dirty. The total valid non-dirty sectors in flushed out tags = CB_PERF_SEL_CM_CACHE_SECTORS_FLUSHED - CB_PERF_SEL_CM_CACHE_DIRTY_SECTORS_FLUSHED + CB_PERF_SEL_CM_CACHE_DIRTY_SECTORS_FLUSHED = 0x0000004f, // Number of dirty sectors per dirty tags that are flushed (the cmask cache has 1 sector per tag). + CB_PERF_SEL_FC_CACHE_HIT = 0x00000050, // Number of tile transactions that hit the fmask cache (TAG HIT && SECTOR HIT). It is a hit if you hit the tag and a sector in that tag meaning that sector's data is valid. Total probe transactions = incoming tile transactions times render targets = CB_PERF_SEL_FC_CACHE_HIT+CB_PERF_SEL_FC_CACHE_SECTOR_MISS. + CB_PERF_SEL_FC_CACHE_TAG_MISS = 0x00000051, // Number of tile transactions that have fmask cache tag misses (TAG MISS). A tag miss is when there isn't a tag that matches the input. Because of sectoring, a tag hit does not imply that the required data is in the cache (i.e TAG HIT && SECTOR MISS). + CB_PERF_SEL_FC_CACHE_SECTOR_MISS = 0x00000052, // Number of tile transactions that have fmask cache sector miss (TAG MISS || SECTOR MISS). A sector miss is when the required sector is not in the cache. Tag misses are included in this count because a sector cannot be in the cache if there is no tag for it. Total transactions that have TAG HIT && SECTOR MISS = CB_PERF_SEL_FC_CACHE_SECTOR_MISS - CB_PERF_SEL_FC_CACHE_TAG_MISS. + CB_PERF_SEL_FC_CACHE_REEVICTION_STALL = 0x00000053, // Number of cycles the fmask cache is stalled because it is trying to evict a line that already has a pending evict. This can happen when a cacheline has been written out to memory and waiting for the write ack gets a hit again, eventually becoming dirty and needing to be re-evicted. Since only one eviction per cacheline can be outstanding, the cache is stalled. + CB_PERF_SEL_FC_CACHE_EVICT_NONZERO_INFLIGHT_STALL = 0x00000054, // Number of cycles the fmask cache is stalled because it is trying to evict a line that has a nonzero inflight count. When a cachelines LRU count reaches the scaled eviction point set by FC_CACHE_EVICT_POINT and it is still inflight then this counter get incremented This is usually a sign that the cache is unable to withstand the memory read latency. FC_CACHE_EVICT_POINT can be set to a LOWER value to handle the increased read latency. + CB_PERF_SEL_FC_CACHE_REPLACE_PENDING_EVICT_STALL = 0x00000055, // Number of cycles the fmask cache is stalled because the line being replaced has a pending evict. This happens when the cacheline chosen for allocation on a miss is still waiting for its write-ack to return from a previous eviction. This is usually a sign that the cache is unable to withstand the memory write latency. FC_CACHE_EVICT_POINT can be set to a HIGHER value to handle the increased write latency. + CB_PERF_SEL_FC_CACHE_INFLIGHT_COUNTER_MAXIMUM_STALL = 0x00000056, // Number of cycles the fmask cache is stalled because one of the inflight counters has reached the maximum value. + CB_PERF_SEL_FC_CACHE_READ_OUTPUT_STALL = 0x00000057, // Number of cycles the fmask cache is stalled because the read request output path is stalled. This can happen due to increased memory read request ask-go latency + CB_PERF_SEL_FC_CACHE_WRITE_OUTPUT_STALL = 0x00000058, // Number of cycles the fmask cache is stalled because the write request output path is stalled. This can happen due to increased memory write request ask-go latency + CB_PERF_SEL_FC_CACHE_ACK_OUTPUT_STALL = 0x00000059, // Number of cycles the fmask cache is stalled because the acknowledge output path is stalled. This can happen if the next stage in the pipeline (fmask cache read latency hiding fifo) is full and stalling the fmask cache so the cache cannot output any transactions. + CB_PERF_SEL_FC_CACHE_STALL = 0x0000005a, // Number of cycles the fmask cache is stalled. This is the combined cache stall signal. + CB_PERF_SEL_FC_CACHE_FLUSH = 0x0000005b, // This is the number of fmask cache flushes. + CB_PERF_SEL_FC_CACHE_TAGS_FLUSHED = 0x0000005c, // Number of dirty tags that are flushed (the fmask cache has 64 tags). + CB_PERF_SEL_FC_CACHE_SECTORS_FLUSHED = 0x0000005d, // Number of valid sectors (i.e they have valid data) per dirty tags that are flushed (the fmask cache has 4 sectors per tag). The valid sectors may be dirty. The total valid non-dirty sectors in flushed out tags = CB_PERF_SEL_FC_CACHE_SECTORS_FLUSHED - CB_PERF_SEL_FC_CACHE_DIRTY_SECTORS_FLUSHED. + CB_PERF_SEL_FC_CACHE_DIRTY_SECTORS_FLUSHED = 0x0000005e, // Number of dirty sectors per dirty tags that are flushed (the fmask cache has 4 sectors per tag). + CB_PERF_SEL_CC_CACHE_HIT = 0x0000005f, // Number of quad fragment transactions that have color cache tag hits (TAG HIT). A tag hit is when there is a tag that matches the input. Because of sectoring, a tag hit does not imply that the required data is in the cache (i.e TAG HIT && SECTOR MISS). + CB_PERF_SEL_CC_CACHE_TAG_MISS = 0x00000060, // Number of quad fragment transactions that have color cache tag misses (TAG MISS). A tag miss is when there isn't a tag that matches the input. Because of sectoring, a tag hit does not imply that the required data is in the cache (i.e TAG HIT && SECTOR MISS). + CB_PERF_SEL_CC_CACHE_SECTOR_MISS = 0x00000061, // Number of quad fragment transactions that have color cache sector miss (TAG MISS || SECTOR MISS). A sector miss is when the required sector is not in the cache. Tag misses are included in this count because a sector cannot be in the cache if there is no tag for it. Total transactions that have TAG HIT && SECTOR MISS = CB_PERF_SEL_CC_CACHE_SECTOR_MISS - CB_PERF_SEL_CC_CACHE_TAG_MISS. + CB_PERF_SEL_CC_CACHE_REEVICTION_STALL = 0x00000062, // Number of cycles the color cache is stalled because it is trying to evict a line that already has a pending evict. This can happen when a cacheline has been written out to memory and waiting for the write ack gets a hit again, eventually becoming dirty and needing to be re-evicted. Since only one eviction per cacheline can be outstanding, the cache is stalled. + CB_PERF_SEL_CC_CACHE_EVICT_NONZERO_INFLIGHT_STALL = 0x00000063, // Number of cycles the color cache is stalled because it is trying to evict a line that has a nonzero inflight count. When a cachelines LRU count reaches the scaled eviction point set by CC_CACHE_EVICT_POINT and it is still inflight then this counter get incremented This is usually a sign that the cache is unable to withstand the memory read latency. CC_CACHE_EVICT_POINT can be set to a LOWER value to handle the increased read latency. + CB_PERF_SEL_CC_CACHE_REPLACE_PENDING_EVICT_STALL = 0x00000064, // Number of cycles the color cache is stalled because the line being replaced has a pending evict. This happens when the cacheline chosen for allocation on a miss is still waiting for its write-ack to return from a previous eviction. This is usually a sign that the cache is unable to withstand the memory write latency. CC_CACHE_EVICT_POINT can be set to a HIGHER value to handle the increased write latency. + CB_PERF_SEL_CC_CACHE_INFLIGHT_COUNTER_MAXIMUM_STALL = 0x00000065, // Number of cycles the color cache is stalled because one of the inflight counters has reached the maximum value. + CB_PERF_SEL_CC_CACHE_READ_OUTPUT_STALL = 0x00000066, // Number of cycles the color cache is stalled because the read request output path is stalled. This can happen due to increased memory read request ask-go latency + CB_PERF_SEL_CC_CACHE_WRITE_OUTPUT_STALL = 0x00000067, // Number of cycles the color cache is stalled because the write request output path is stalled. This can happen due to increased memory write request ask-go latency + CB_PERF_SEL_CC_CACHE_ACK_OUTPUT_STALL = 0x00000068, // Number of cycles the color cache is stalled because the acknowledge output path is stalled. This can happen if the next stage in the pipeline (color cache read latency hiding fifo) is full and stalling the color cache so the cache cannot output any transactions. + CB_PERF_SEL_CC_CACHE_STALL = 0x00000069, // Number of cycles the color cache is stalled. This is the combined cache stall signal. + CB_PERF_SEL_CC_CACHE_FLUSH = 0x0000006a, // This is the number of color cache flushes. This is includes surface sync flushes. + CB_PERF_SEL_CC_CACHE_TAGS_FLUSHED = 0x0000006b, // Number of dirty tags that are flushed (the color cache has 64 tags). + CB_PERF_SEL_CC_CACHE_SECTORS_FLUSHED = 0x0000006c, // Number of valid sectors (i.e they have valid data) per dirty tags that are flushed (the color cache has 4 sectors per tag). The valid sectors may be dirty. The total valid non-dirty sectors in flushed out tags = CB_PERF_SEL_CC_CACHE_SECTORS_FLUSHED - CB_PERF_SEL_CC_CACHE_DIRTY_SECTORS_FLUSHED. + CB_PERF_SEL_CC_CACHE_DIRTY_SECTORS_FLUSHED = 0x0000006d, // Number of dirty sectors per dirty tags that are flushed (the color cache has 4 sectors per tag). + CB_PERF_SEL_CC_CACHE_WA_TO_RMW_CONVERSION = 0x0000006e, // The number of color cache probe transactions that hit a write allocate cache line that convert it into a read-modify-write cache line because they need destination buffer data. + CB_PERF_SEL_CC_CACHE_READS_SAVED_DUE_TO_DCC = 0x0000006f, // Number of reads prevented by DCC. + CB_PERF_SEL_CB_TAP_WRREQ_VALID_READY = 0x00000070, // Number of cycles the CB to TAP write request interface is valid and ready. This is measured at the interface converter rather than directly on the interface. The should be equal to the sum of CB_PERF_SEL_*_MC_WRITE_REQUEST + CB_PERF_SEL_CB_TAP_WRREQ_VALID_READYB = 0x00000071, // Number of cycles the CB to TAP write request interface is valid and not ready. This is measured at the interface converter rather than directly on the interface. + CB_PERF_SEL_CB_TAP_WRREQ_VALIDB_READY = 0x00000072, // Number of cycles the CB to TAP write request interface is valid and ready. This is measured at the interface converter rather than directly on the interface. + CB_PERF_SEL_CB_TAP_WRREQ_VALIDB_READYB = 0x00000073, // Number of cycles the CB to TAP write request interface is not valid and not ready. This is measured at the interface converter rather than directly on the interface. + CB_PERF_SEL_CM_MC_WRITE_REQUEST = 0x00000074, // Number of 32-byte cmask mc write requests. + CB_PERF_SEL_FC_MC_WRITE_REQUEST = 0x00000075, // Number of 32-byte fmask mc write requests. + CB_PERF_SEL_CC_MC_WRITE_REQUEST = 0x00000076, // Number of 32-byte color mc write requests. + CB_PERF_SEL_CM_MC_WRITE_REQUESTS_IN_FLIGHT = 0x00000077, // Number of 32-byte cmask mc write requests in flight. CB_PERF_SEL_CM_MC_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_CM_MC_WRITE_REQUEST = average latency. + CB_PERF_SEL_FC_MC_WRITE_REQUESTS_IN_FLIGHT = 0x00000078, // Number of 32-byte fmask mc write requests in flight. CB_PERF_SEL_FC_MC_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_FC_MC_WRITE_REQUEST = average latency. + CB_PERF_SEL_CC_MC_WRITE_REQUESTS_IN_FLIGHT = 0x00000079, // Number of 32-byte color mc write requests in flight. CB_PERF_SEL_CC_MC_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_CC_MC_WRITE_REQUEST = average latency. + CB_PERF_SEL_CB_TAP_RDREQ_VALID_READY = 0x0000007a, // Number of cycles the CB to TAP read request interface is valid and ready. This is measured at the interface converter rather than directly on the interface. + CB_PERF_SEL_CB_TAP_RDREQ_VALID_READYB = 0x0000007b, // Number of cycles the CB to TAP read request interface is valid and not ready. This is measured at the interface converter rather than directly on the interface. + CB_PERF_SEL_CB_TAP_RDREQ_VALIDB_READY = 0x0000007c, // Number of cycles the CB to TAP read request interface is not valid and ready. This is measured at the interface converter rather than directly on the interface. + CB_PERF_SEL_CB_TAP_RDREQ_VALIDB_READYB = 0x0000007d, // Number of cycles the CB to TAP read request interface is not valid and not ready. This is measured at the interface converter rather than directly on the interface. + CB_PERF_SEL_CM_MC_READ_REQUEST = 0x0000007e, // Number of 32-byte cmask mc read requests. Cmask does not make 32-byte requests, so the counter will report the equivalent number of 32-byte requests. + CB_PERF_SEL_FC_MC_READ_REQUEST = 0x0000007f, // Number of 32-byte fmask mc read requests. + CB_PERF_SEL_CC_MC_READ_REQUEST = 0x00000080, // Number of 32-byte color mc read requests. Color does not make 32-byte requests, so the counter will report the equivalent number of 32-byte requests. + CB_PERF_SEL_CM_MC_READ_REQUESTS_IN_FLIGHT = 0x00000081, // Number of 32-byte cmask mc read requests in flight. Cmask does not make 32-byte requests, so the counter will report the equivalent number of 32-byte requests. CB_PERF_SEL_CM_MC_READ_REQUESTS_IN_FLIGHT/CB_PERF_SEL_CM_MC_READ_REQUEST = average latency. + CB_PERF_SEL_FC_MC_READ_REQUESTS_IN_FLIGHT = 0x00000082, // Number of 32-byte fmask mc read requests in flight. CB_PERF_SEL_FC_MC_READ_REQUESTS_IN_FLIGHT/CB_PERF_SEL_FC_MC_READ_REQUEST = average latency. + CB_PERF_SEL_CC_MC_READ_REQUESTS_IN_FLIGHT = 0x00000083, // Number of 32-byte color mc read requests in flight. Color does not make 32-byte requests, so the counter will report the equivalent number of 32-byte requests. CB_PERF_SEL_CC_MC_READ_REQUESTS_IN_FLIGHT/CB_PERF_SEL_CC_MC_READ_REQUEST = average latency. + CB_PERF_SEL_CM_TQ_FULL = 0x00000084, // Number of cycles the cmask tile queue is full. This fifo covers the cmask memory read latency and stalling indicates that this fifo does not have enough latency hiding capacity + CB_PERF_SEL_CM_TQ_FIFO_TILE_RESIDENCY_STALL = 0x00000085, // Number of cycles the cmask read latency hiding fifo's head entry is waiting for cmask read data to return from memory and become resident in cache so the transaction can be popped. This does not mean that cmask logic is stalled, look at CB_PERF_SEL_CM_TQ_FULL for that. + CB_PERF_SEL_FC_QUAD_RDLAT_FIFO_FULL = 0x00000086, // Number of cycles the fmask read latency quad fifo is full. This fifo covers the fmask memory read latency and stalling indicates that this fifo does not have enough latency hiding capacity + CB_PERF_SEL_FC_TILE_RDLAT_FIFO_FULL = 0x00000087, // Number of cycles the fmask read latency tile fifo is full. This fifo covers the fmask memory read latency and stalling indicates that this fifo does not have enough latency hiding capacity + CB_PERF_SEL_FC_RDLAT_FIFO_QUAD_RESIDENCY_STALL = 0x00000088, // Number of cycles the fmask read latency hiding fifo's head entry is waiting for fmask read data to return from memory and become resident in cache so the transaction can be popped. This does not mean that fmask logic is stalled, look at CB_PERF_SEL_FC_QUAD_RDLAT_FIFO_FULL || CB_PERF_SEL_FC_TILE_RDLAT_FIFO_FULL for that. + CB_PERF_SEL_FOP_FMASK_RAW_STALL = 0x00000089, // Number of cycles a quadA-quadA sequence (back-to-back) is stalled because of a read-after-write conflict in fragop block. + CB_PERF_SEL_FOP_FMASK_BYPASS_STALL = 0x0000008a, // Number of cycles a quadA-quadB-quadA sequence is stalled because of a read-after-write conflict in fragop block. + CB_PERF_SEL_CC_SF_FULL = 0x0000008b, // Number of cycles the color cache source fifo is full. This fifo covers the fmask memory read plus color cache memory read latency and stalling indicates that this fifo does not have enough latency hiding capacity + CB_PERF_SEL_CC_RB_FULL = 0x0000008c, // Number of cycles the color cache reorder buffer is full. This fifo covers the color cache memory read latency and stalling indicates that this fifo does not have enough latency hiding capacity + CB_PERF_SEL_CC_EVENFIFO_QUAD_RESIDENCY_STALL = 0x0000008d, // Number of cycles the color even side read latency hiding fifo's head entry is waiting for even 32B color read data to return from memory and become resident in cache so the transaction can be popped. This does not mean that color logic is stalled, look at CB_PERF_SEL_CC_RB_FULL for that. + CB_PERF_SEL_CC_ODDFIFO_QUAD_RESIDENCY_STALL = 0x0000008e, // Number of cycles the color odd side read latency hiding fifo's head entry is waiting for odd 32B color read data to return from memory and become resident in cache so the transaction can be popped. This does not mean that color logic is stalled, look at CB_PERF_SEL_CC_RB_FULL for that. + CB_PERF_SEL_BLENDER_RAW_HAZARD_STALL = 0x0000008f, // Number of cycles the blend pipeline is stalled to handle read after write hazards. + CB_PERF_SEL_EVENT = 0x00000090, // Total number of events reaching the CB. This includes events that the CB does not process. + CB_PERF_SEL_EVENT_CACHE_FLUSH_TS = 0x00000091, // Number of CACHE_FLUSH_TS events + CB_PERF_SEL_EVENT_CONTEXT_DONE = 0x00000092, // Number of CONTEXT_DONE events + CB_PERF_SEL_EVENT_CACHE_FLUSH = 0x00000093, // Number of CACHE_FLUSH events + CB_PERF_SEL_EVENT_CACHE_FLUSH_AND_INV_TS_EVENT = 0x00000094, // Number of CACHE_FLUSH_AND_INV_TS_EVENT events + CB_PERF_SEL_EVENT_CACHE_FLUSH_AND_INV_EVENT = 0x00000095, // Number of_CACHE_FLUSH_AND_INV_EVENTevents + CB_PERF_SEL_EVENT_FLUSH_AND_INV_CB_DATA_TS = 0x00000096, // Number of FLUSH_AND_INV_CB_DATA_TS events + CB_PERF_SEL_EVENT_FLUSH_AND_INV_CB_META = 0x00000097, // Number of FLUSH_AND_INV_CB_META events + CB_PERF_SEL_CC_SURFACE_SYNC = 0x00000098, // Number of surface syncs + CB_PERF_SEL_CMASK_READ_DATA_0xC = 0x00000099, // Number of fmask cache probe misses that read cmask with a value of 0xC. A value of 0xC means that a fmask tile requires 0 bit planes. Sum of CB_PERF_SEL_CMASK_READ_DATA_* should match CB_PERF_SEL_FC_CACHE_SECTOR_MISS. + CB_PERF_SEL_CMASK_READ_DATA_0xD = 0x0000009a, // Number of fmask cache probe misses that read cmask with a value of 0xD. A value of 0xD means that a fmask tile requires 1 bit planes. Sum of CB_PERF_SEL_CMASK_READ_DATA_* should match CB_PERF_SEL_FC_CACHE_SECTOR_MISS. + CB_PERF_SEL_CMASK_READ_DATA_0xE = 0x0000009b, // Number of fmask cache probe misses that read cmask with a value of 0xE. A value of 0xE means that a fmask tile requires 2 bit planes. Sum of CB_PERF_SEL_CMASK_READ_DATA_* should match CB_PERF_SEL_FC_CACHE_SECTOR_MISS. + CB_PERF_SEL_CMASK_READ_DATA_0xF = 0x0000009c, // Number of fmask cache probe misses that read cmask with a value of 0xF. A value of 0xF means that a fmask tile requires 3 bit planes. Sum of CB_PERF_SEL_CMASK_READ_DATA_* should match CB_PERF_SEL_FC_CACHE_SECTOR_MISS. + CB_PERF_SEL_CMASK_WRITE_DATA_0xC = 0x0000009d, // Number of tiles that wrote a value of 0xC to cmask. Cmask writes occur at the end of a tile. The hardware does not perform the write if fmask has not changed, but the counter will update as if regardless of whether the hardware wrote or not. A value of 0xC means that a fmask tile requires 0 bit planes. Sum of all CB_PERF_SEL_CMASK_WRITE_DATA_* equals cmask cache probes (CB_PERF_SEL_CM_CACHE_HIT + CB_PERF_SEL_CM_CACHE_SECTOR_MISS). + CB_PERF_SEL_CMASK_WRITE_DATA_0xD = 0x0000009e, // Number of tile that wrote a value of 0xD was written to cmask. Cmask writes occur at the end of a tile. The hardware does not perform the write if fmask has not changed, but the counter will update as if regardless of whether the hardware wrote or not. A value of 0xD means that a fmask tile requires 1 bit planes. Sum of all CB_PERF_SEL_CMASK_WRITE_DATA_* equals cmask cache probes (CB_PERF_SEL_CM_CACHE_HIT + CB_PERF_SEL_CM_CACHE_SECTOR_MISS). + CB_PERF_SEL_CMASK_WRITE_DATA_0xE = 0x0000009f, // Number of tiles that wrote a value of 0xE was written to cmask. Cmask writes occur at the end of a tile. The hardware does not perform the write if fmask has not changed, but the counter will update as if regardless of whether the hardware wrote or not. A value of 0xE means that a fmask tile requires 2 bit planes. Sum of all CB_PERF_SEL_CMASK_WRITE_DATA_* equals cmask cache probes (CB_PERF_SEL_CM_CACHE_HIT + CB_PERF_SEL_CM_CACHE_SECTOR_MISS). + CB_PERF_SEL_CMASK_WRITE_DATA_0xF = 0x000000a0, // Number of tiles that wrote a value of 0xF was written to cmask. Cmask writes occur at the end of a tile. The hardware does not perform the write if fmask has not changed, but the counter will update as if regardless of whether the hardware wrote or not. A value of 0xF means that a fmask tile requires 3 bit planes. Sum of all CB_PERF_SEL_CMASK_WRITE_DATA_* equals cmask cache probes (CB_PERF_SEL_CM_CACHE_HIT + CB_PERF_SEL_CM_CACHE_SECTOR_MISS). + CB_PERF_SEL_TWO_PROBE_QUAD_FRAGMENT = 0x000000a1, // Number of quad fragments that require two cache probes. AA blending can create these when the read fragment does not match the write fragment. + CB_PERF_SEL_EXPORT_32_ABGR_QUAD_FRAGMENT = 0x000000a2, // Number of EXPORT_32_ABGR quad fragments. It takes two clocks to send the src color data for these. + CB_PERF_SEL_DUAL_SOURCE_COLOR_QUAD_FRAGMENT = 0x000000a3, // Number of dual source blending color quad fragments + CB_PERF_SEL_QUAD_HAS_1_FRAGMENT_BEFORE_UPDATE = 0x000000a4, // Number of quads that started with 1 fragment in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_2_FRAGMENTS_BEFORE_UPDATE = 0x000000a5, // Number of quads that started with 2 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_3_FRAGMENTS_BEFORE_UPDATE = 0x000000a6, // Number of quads that started with 3 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_4_FRAGMENTS_BEFORE_UPDATE = 0x000000a7, // Number of quads that started with 4 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_5_FRAGMENTS_BEFORE_UPDATE = 0x000000a8, // Number of quads that started with 5 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_6_FRAGMENTS_BEFORE_UPDATE = 0x000000a9, // Number of quads that started with 6 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_7_FRAGMENTS_BEFORE_UPDATE = 0x000000aa, // Number of quads that started with 7 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_8_FRAGMENTS_BEFORE_UPDATE = 0x000000ab, // Number of quads that started with 8 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_1_FRAGMENT_AFTER_UPDATE = 0x000000ac, // Number of quads that ended up with 1 fragment in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_2_FRAGMENTS_AFTER_UPDATE = 0x000000ad, // Number of quads that ended up with 2 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_3_FRAGMENTS_AFTER_UPDATE = 0x000000ae, // Number of quads that ended up with 3 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_4_FRAGMENTS_AFTER_UPDATE = 0x000000af, // Number of quads that ended up with 4 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_5_FRAGMENTS_AFTER_UPDATE = 0x000000b0, // Number of quads that ended up with 5 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_6_FRAGMENTS_AFTER_UPDATE = 0x000000b1, // Number of quads that ended up with 6 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_7_FRAGMENTS_AFTER_UPDATE = 0x000000b2, // Number of quads that ended up with 7 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_HAS_8_FRAGMENTS_AFTER_UPDATE = 0x000000b3, // Number of quads that ended up with 8 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_ADDED_1_FRAGMENT = 0x000000b4, // Number of quads that added 1 fragment in AA mode in fragop block. + CB_PERF_SEL_QUAD_ADDED_2_FRAGMENTS = 0x000000b5, // Number of quads that added 2 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_ADDED_3_FRAGMENTS = 0x000000b6, // Number of quads that added 3 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_ADDED_4_FRAGMENTS = 0x000000b7, // Number of quads that added 4 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_ADDED_5_FRAGMENTS = 0x000000b8, // Number of quads that added 5 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_ADDED_6_FRAGMENTS = 0x000000b9, // Number of quads that added 6 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_ADDED_7_FRAGMENTS = 0x000000ba, // Number of quads that added 7 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_REMOVED_1_FRAGMENT = 0x000000bb, // Number of quads that removed 1 fragment in AA mode in fragop block. + CB_PERF_SEL_QUAD_REMOVED_2_FRAGMENTS = 0x000000bc, // Number of quads that removed 2 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_REMOVED_3_FRAGMENTS = 0x000000bd, // Number of quads that removed 3 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_REMOVED_4_FRAGMENTS = 0x000000be, // Number of quads that removed 4 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_REMOVED_5_FRAGMENTS = 0x000000bf, // Number of quads that removed 5 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_REMOVED_6_FRAGMENTS = 0x000000c0, // Number of quads that removed 6 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_REMOVED_7_FRAGMENTS = 0x000000c1, // Number of quads that removed 7 fragments in AA mode in fragop block. + CB_PERF_SEL_QUAD_READS_FRAGMENT_0 = 0x000000c2, // Number of quads that reads fragment 0 to the color cache. + CB_PERF_SEL_QUAD_READS_FRAGMENT_1 = 0x000000c3, // Number of quads that reads fragment 1 to the color cache. + CB_PERF_SEL_QUAD_READS_FRAGMENT_2 = 0x000000c4, // Number of quads that reads fragment 2 to the color cache. + CB_PERF_SEL_QUAD_READS_FRAGMENT_3 = 0x000000c5, // Number of quads that reads fragment 3 to the color cache. + CB_PERF_SEL_QUAD_READS_FRAGMENT_4 = 0x000000c6, // Number of quads that reads fragment 4 to the color cache. + CB_PERF_SEL_QUAD_READS_FRAGMENT_5 = 0x000000c7, // Number of quads that reads fragment 5 to the color cache. + CB_PERF_SEL_QUAD_READS_FRAGMENT_6 = 0x000000c8, // Number of quads that reads fragment 6 to the color cache. + CB_PERF_SEL_QUAD_READS_FRAGMENT_7 = 0x000000c9, // Number of quads that reads fragment 7 to the color cache. + CB_PERF_SEL_QUAD_WRITES_FRAGMENT_0 = 0x000000ca, // Number of quads that writes fragment 0 to the color cache. + CB_PERF_SEL_QUAD_WRITES_FRAGMENT_1 = 0x000000cb, // Number of quads that writes fragment 1 to the color cache. + CB_PERF_SEL_QUAD_WRITES_FRAGMENT_2 = 0x000000cc, // Number of quads that writes fragment 2 to the color cache. + CB_PERF_SEL_QUAD_WRITES_FRAGMENT_3 = 0x000000cd, // Number of quads that writes fragment 3 to the color cache. + CB_PERF_SEL_QUAD_WRITES_FRAGMENT_4 = 0x000000ce, // Number of quads that writes fragment 4 to the color cache. + CB_PERF_SEL_QUAD_WRITES_FRAGMENT_5 = 0x000000cf, // Number of quads that writes fragment 5 to the color cache. + CB_PERF_SEL_QUAD_WRITES_FRAGMENT_6 = 0x000000d0, // Number of quads that writes fragment 6 to the color cache. + CB_PERF_SEL_QUAD_WRITES_FRAGMENT_7 = 0x000000d1, // Number of quads that writes fragment 7 to the color cache. + CB_PERF_SEL_QUAD_BLEND_OPT_DONT_READ_DST = 0x000000d2, // Number of quads that were blending but enabled optimization to not need read destination data. This optimization can be disabled by setting DISABLE_BLEND_OPT_DONT_RD_DST. + CB_PERF_SEL_QUAD_BLEND_OPT_BLEND_BYPASS = 0x000000d3, // Number of quads that were blending but enabled optimization to bypassed blend operation. This optimization can be disabled by setting DISABLE_BLEND_OPT_BYPASS. + CB_PERF_SEL_QUAD_BLEND_OPT_DISCARD_PIXELS = 0x000000d4, // Number of quads that were blending but enabled optimization to discard at least 1 pixel. This optimization can be disabled by setting DISABLE_BLEND_OPT_DISCARD_PIXEL. + CB_PERF_SEL_QUAD_DST_READ_COULD_HAVE_BEEN_OPTIMIZED = 0x000000d5, // Number of quads that the blender detects that could have optimized away their destination reads (i.e destblend*dst == 0.0f). NOTE: this counter is not completely accurate and does not work for colors that have 32-bit components. + CB_PERF_SEL_QUAD_BLENDING_COULD_HAVE_BEEN_BYPASSED = 0x000000d6, // Number of quads that the blender detects that could have optimized away blending (destblend*dst == 0.0f && srcblend*src == 1.0f). NOTE: this counter is not completely accurate and does not work for colors that have 32-bit components. + CB_PERF_SEL_QUAD_COULD_HAVE_BEEN_DISCARDED = 0x000000d7, // Number of quads that the blender detects that could have discarded some pixels (destblend*dst == 1.0f && srcblend*src == 0.0f). NOTE: this counter is not completely accurate and does not work for colors that have 32-bit components. + CB_PERF_SEL_BLEND_OPT_PIXELS_RESULT_EQ_DEST = 0x000000d8, // Number of blended pixels that the blender detects can be dropped because the blended result is the same as the original destination value. + CB_PERF_SEL_DRAWN_BUSY = 0x000000d9, // Number of busy cycles around the stage calculating the CB_PERF_SEL_DRAWN_* counters. Used as denominator for all the CB_PERF_SEL_DRAWN_* counters. Filtering using CB_PERFCOUNTER_FILTER fields has an effect in this mode. + CB_PERF_SEL_TILE_TO_CMR_REGION_BUSY = 0x000000da, // Number of busy cycles b/w PERFCOUNTER_START and PERFCOUNTER_STOP for the pipeline region b/w DB_CB_TILE and CMASK CACHE READ. This can be used as denominator for rate calculation for counters in this region + CB_PERF_SEL_CMR_TO_FCR_REGION_BUSY = 0x000000db, // Number of busy cycles b/w PERFCOUNTER_START and PERFCOUNTER_STOP for the pipeline region b/w CMASK CACHE READ and FMASK CACHE READ. This can be used as denominator for rate calculation for counters in this region + CB_PERF_SEL_FCR_TO_CCR_REGION_BUSY = 0x000000dc, // Number of busy cycles b/w PERFCOUNTER_START and PERFCOUNTER_STOP for the pipeline region b/w FMASK CACHE READ and COLOR CACHE READ. This can be used as denominator for rate calculation for counters in this region + CB_PERF_SEL_CCR_TO_CCW_REGION_BUSY = 0x000000dd, // Number of busy cycles b/w PERFCOUNTER_START and PERFCOUNTER_STOP for the pipeline region b/w COLOR CACHE READ and COLOR CACHE WRITE. This can be used as denominator for rate calculation for counters in this region + CB_PERF_SEL_FC_PF_SLOW_MODE_QUAD_EMPTY_HALF_DROPPED = 0x000000de, // Number of lquad transactions (halves of slow mode 2-cycle quad) that were dropped in fc_merge logic due to optimization from going into the SRC fifo because the pixel pair in that half quad was unlit. This optimization can be disabled by setting: DISABLE_SLOW_MODE_EMPTY_HALF_QUAD_KILL + CB_PERF_SEL_FC_SEQUENCER_CLEAR = 0x000000df, // Number of quads that are generated to expand out the fast clear color as well as number of drawn quads that have partially lit pixels so that unlit samples need to expands their fast clear color. Use CB_PERF_SEL_DRAWN_BUSY as denominator to get per clock rates. + CB_PERF_SEL_FC_SEQUENCER_ELIMINATE_FAST_CLEAR = 0x000000e0, // Number of quads generated during ELIMINATE_FAST_CLEAR pass to expand their fast clear color Use CB_PERF_SEL_DRAWN_BUSY as denominator to get per clock rates. + CB_PERF_SEL_FC_SEQUENCER_FMASK_DECOMPRESS = 0x000000e1, // Number of quads generated during FMASK_DECOMPRESS pass to expand their fast clear color Use CB_PERF_SEL_DRAWN_BUSY as denominator to get per clock rates. + CB_PERF_SEL_FC_SEQUENCER_FMASK_COMPRESSION_DISABLE = 0x000000e2, // Number of quad fragments seen during normal rendering when the state was set to disable fmask compression. This will include drawn quads as well as generated quads to expand their fast clear Use CB_PERF_SEL_DRAWN_BUSY as denominator to get per clock rates. + CB_PERF_SEL_FC_KEYID_RDLAT_FIFO_FULL = 0x000000e3, // Number of cycles the fmask read latency keyid fifo is full. This fifo covers the fmask memory read latency and stalling indicates that this fifo does not have enough latency hiding capacity + CB_PERF_SEL_FC_DOC_IS_STALLED = 0x000000e4, // Number of cycles the overwrite combiner is stalled. + CB_PERF_SEL_FC_DOC_MRTS_NOT_COMBINED = 0x000000e5, // Number of times a quad's mrt was not able to be combined with another one (so as to share the same quarter-tile cam entry). + CB_PERF_SEL_FC_DOC_MRTS_COMBINED = 0x000000e6, // Number of times a quad's mrt was combined with another one (so as to share the same quarter-tile cam entry). + CB_PERF_SEL_FC_DOC_QTILE_CAM_MISS = 0x000000e7, // Number of misses in the overwrite combiner's quarter-tile cam. + CB_PERF_SEL_FC_DOC_QTILE_CAM_HIT = 0x000000e8, // Number of hits in the overwrite combiner's quarter-tile cam. + CB_PERF_SEL_FC_DOC_CLINE_CAM_MISS = 0x000000e9, // Number of misses in the overwrite combiner's cacheline cam. + CB_PERF_SEL_FC_DOC_CLINE_CAM_HIT = 0x000000ea, // Number of hits in the overwrite combiner's cacheline cam. + CB_PERF_SEL_FC_DOC_QUAD_PTR_FIFO_IS_FULL = 0x000000eb, // Number of cycles that the overwrite combiner's quad pointer fifo is full. + CB_PERF_SEL_FC_DOC_OVERWROTE_1_SECTOR = 0x000000ec, // Number of times that the overwrite combiner overwrote just 1 sector. + CB_PERF_SEL_FC_DOC_OVERWROTE_2_SECTORS = 0x000000ed, // Number of times that the overwrite combiner overwrote just 2 sector. + CB_PERF_SEL_FC_DOC_OVERWROTE_3_SECTORS = 0x000000ee, // Number of times that the overwrite combiner overwrote just 3 sector. + CB_PERF_SEL_FC_DOC_OVERWROTE_4_SECTORS = 0x000000ef, // Number of times that the overwrite combiner overwrote all 4 sectors. + CB_PERF_SEL_FC_DOC_TOTAL_OVERWRITTEN_SECTORS = 0x000000f0, // Number of total sectors overwritten by the Overwrite Combiner. + CB_PERF_SEL_FC_DCC_CACHE_HIT = 0x000000f1, // Number of hits in the DCC cache (TAG HIT && SECTOR HIT). + CB_PERF_SEL_FC_DCC_CACHE_TAG_MISS = 0x000000f2, // Number of tag misses in the DCC cache (TAG MISS). + CB_PERF_SEL_FC_DCC_CACHE_SECTOR_MISS = 0x000000f3, // Number of sector misses in the DCC cache (TAG MISS || SECTOR MISS). + CB_PERF_SEL_FC_DCC_CACHE_REEVICTION_STALL = 0x000000f4, // Number of cycles the DCC cache is stalled because it is trying to evict a line that already has a pending evict. This can happen when a cacheline has been written out to memory and waiting for the write ack gets a hit again, eventually becoming dirty and needing to be re-evicted. Since only one eviction per cacheline can be outstanding, the cache is stalled. + CB_PERF_SEL_FC_DCC_CACHE_EVICT_NONZERO_INFLIGHT_STALL = 0x000000f5, // Number of cycles the DCC cache is stalled because it is trying to evict a line that has a nonzero inflight count. When a cachelines LRU count reaches the scaled eviction point set by DCC_CACHE_EVICT_POINT and it is still inflight then this counter get incremented This is usually a sign that the cache is unable to withstand the memory read latency. DCC_CACHE_EVICT_POINT can be set to a LOWER value to handle the increased read latency. This count is the number of times the Key Cache sends a panic to the Color Cache. + CB_PERF_SEL_FC_DCC_CACHE_REPLACE_PENDING_EVICT_STALL = 0x000000f6, // Number of cycles the DCC cache is stalled because the line being replaced has a pending evict. This happens when the cacheline chosen for allocation on a miss is still waiting for its write-ack to return from a previous eviction. This is usually a sign that the cache is unable to withstand the memory write latency. DCC_CACHE_EVICT_POINT can be set to a HIGHER value to handle the increased write latency. + CB_PERF_SEL_FC_DCC_CACHE_INFLIGHT_COUNTER_MAXIMUM_STALL = 0x000000f7, // Number of cycles the DCC cache is stalled because one of the inflight counters has reached the maximum value. + CB_PERF_SEL_FC_DCC_CACHE_READ_OUTPUT_STALL = 0x000000f8, // Number of cycles the DCC cache is stalled because the read request output path is stalled. This can happen due to increased memory read request ask-go latency + CB_PERF_SEL_FC_DCC_CACHE_WRITE_OUTPUT_STALL = 0x000000f9, // Number of cycles the DCC cache is stalled because the write request output path is stalled. This can happen due to increased memory write request ask-go latency + CB_PERF_SEL_FC_DCC_CACHE_ACK_OUTPUT_STALL = 0x000000fa, // Number of cycles the DCC cache is stalled because the acknowledge output path is stalled. This can happen if the next stage in the pipeline (DCC cache read latency hiding fifo) is full and stalling the DCC cache so the cache cannot output any transactions. + CB_PERF_SEL_FC_DCC_CACHE_STALL = 0x000000fb, // Number of cycles the DCC cache is stalled. This is the combined cache stall signal. + CB_PERF_SEL_FC_DCC_CACHE_FLUSH = 0x000000fc, // This is the number of DCC cache flushes. + CB_PERF_SEL_FC_DCC_CACHE_SECTORS_FLUSHED = 0x000000fd, // Number of valid sectors (i.e they have valid data) per dirty tags that are flushed (the DCC cache has 1 sector per tag). The valid sectors may be dirty. The total valid non-dirty sectors in flushed out tags = CB_PERF_SEL_FC_DCC_CACHE_SECTORS_FLUSHED - CB_PERF_SEL_FC_DCC_CACHE_DIRTY_SECTORS_FLUSHED. + CB_PERF_SEL_FC_DCC_CACHE_DIRTY_SECTORS_FLUSHED = 0x000000fe, // Number of dirty sectors per dirty tags that are flushed (the DCC cache has 1 sector per tag). + CB_PERF_SEL_FC_DCC_CACHE_TAGS_FLUSHED = 0x000000ff, // Number of dirty tags that are flushed (the DCC cache has 32 tags). + CB_PERF_SEL_CC_DCC_BEYOND_TILE_SPLIT = 0x00000100, // Number of fragments that lie outside the tile split boundary. The color cache controller limits DCC compression support to only those fragments that are within the first tile split. + CB_PERF_SEL_FC_MC_DCC_WRITE_REQUEST = 0x00000101, // Number of 32-byte fmask mc DCC write requests. + CB_PERF_SEL_FC_MC_DCC_WRITE_REQUESTS_IN_FLIGHT = 0x00000102, // Number of 32-byte fmask mc DCC write requests in flight. CB_PERF_SEL_FC_MC_DCC_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_FC_MC_DCC_WRITE_REQUEST = average latency. + CB_PERF_SEL_FC_MC_DCC_READ_REQUEST = 0x00000103, // Number of 32-byte fmask mc DCC read requests. + CB_PERF_SEL_FC_MC_DCC_READ_REQUESTS_IN_FLIGHT = 0x00000104, // Number of 32-byte fmask mc DCC read requests in flight. CB_PERF_SEL_FC_MC_DCC_READ_REQUESTS_IN_FLIGHT/CB_PERF_SEL_FC_MC_DCC_READ_REQUEST = average latency. + CB_PERF_SEL_CC_DCC_RDREQ_STALL = 0x00000105, // Number of times DCC read requests are stalled because the internal scoreboard predicts that the skid fifo will be full. + CB_PERF_SEL_CC_DCC_DECOMPRESS_TIDS_IN = 0x00000106, // Number of tids that come into the DCC's decompress module. + CB_PERF_SEL_CC_DCC_DECOMPRESS_TIDS_OUT = 0x00000107, // Number of tids that come out of the DCC's decompress module. + CB_PERF_SEL_CC_DCC_COMPRESS_TIDS_IN = 0x00000108, // Number of tids that come into the DCC's compress module. + CB_PERF_SEL_CC_DCC_COMPRESS_TIDS_OUT = 0x00000109, // Number of tids that come out of the DCC's compress module. + CB_PERF_SEL_FC_DCC_KEY_VALUE__CLEAR = 0x0000010a, // From DCC cache: Number of times all sectors of a cacheline were initialized with a register-defined clear value. + CB_PERF_SEL_CC_DCC_KEY_VALUE__4_BLOCKS__2TO1 = 0x0000010b, // From DCC Compressor in Color Cache: Number of times all 4 sectors were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__3BLOCKS_2TO1__1BLOCK_2TO2 = 0x0000010c, // From DCC Compressor in Color Cache: Number of times sectors 1 through 3 were compressed as 2:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO1__1BLOCK_2TO2__1BLOCK_2TO1 = 0x0000010d, // From DCC Compressor in Color Cache: Number of times sectors 2 and 3 were compressed as 2:1 blocks, sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_2TO2__2BLOCKS_2TO1 = 0x0000010e, // From DCC Compressor in Color Cache: Number of times sector 3 was compressed as 2:1 blocks, sector 2 was compressed as 2:2 (uncompressed) and sectors 0 and 1 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__3BLOCKS_2TO1 = 0x0000010f, // From DCC Compressor in Color Cache: Number of times sector 3 was compressed as 2:2 (uncompressed) and sectors 0 through 2 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO1__2BLOCKS_2TO2 = 0x00000110, // From DCC Compressor in Color Cache: Number of times sectors 2 and 3 were compressed as 2:1 blocks and sectors 0 and 1 were compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__2BLOCKS_2TO2__1BLOCK_2TO1 = 0x00000111, // From DCC Compressor in Color Cache: Number of times sector 3 was compressed as 2:1 blocks, sectors 1 and 2 were compressed as 2:2 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_2TO2__1BLOCK_2TO1__1BLOCK_2TO2 = 0x00000112, // From DCC Compressor in Color Cache: Number of times sector 3 was compressed as 2:1 blocks, sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_2TO1__1BLOCK_2TO2__1BLOCK_2TO1 = 0x00000113, // From DCC Compressor in Color Cache: Number of times sector 3 was compressed as 2:2 (uncompressed), sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO2__2BLOCKS_2TO1 = 0x00000114, // From DCC Compressor in Color Cache: Number of times sectors 2 and 3 were compressed as 2:2 (uncompressed) and sectors 0 and 1 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__2BLOCKS_2TO1__1BLOCK_2TO2 = 0x00000115, // From DCC Compressor in Color Cache: Number of times sector 3 was compressed as 2:2 (uncompressed), sectors 1 and 2 were compressed as 2:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__3BLOCKS_2TO2 = 0x00000116, // From DCC Compressor in Color Cache: Number of times sector 3 was compressed as 2:1 blocks and sectors 0 through 2 were compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_2TO1__2BLOCKS_2TO2 = 0x00000117, // From DCC Compressor in Color Cache: Number of times sector 3 was compressed as 2:2 (uncompressed), sector 2 was compressed as 2:1 blocks and sectors 0 and 1 were compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO2__1BLOCK_2TO1__1BLOCK_2TO2 = 0x00000118, // From DCC Compressor in Color Cache: Number of times sectors 2 and 3 were compressed as 2:2 (uncompressed), sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__3BLOCKS_2TO2__1BLOCK_2TO1 = 0x00000119, // From DCC Compressor in Color Cache: Number of times sectors 1 through 3 were compressed as 2:2 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_4TO1 = 0x0000011a, // From DCC Compressor in Color Cache: Number of times sectors 0 and 1 were compressed as 4:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO1__1BLOCK_4TO2 = 0x0000011b, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:1 blocks and sector 0 was compressed as 4:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO1__1BLOCK_4TO3 = 0x0000011c, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:1 blocks and sector 0 was compressed as 4:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO1__1BLOCK_4TO4 = 0x0000011d, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:1 blocks and sector 0 was compressed as 4:4 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO2__1BLOCK_4TO1 = 0x0000011e, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:2 blocks and sector 0 was compressed as 4:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_4TO2 = 0x0000011f, // From DCC Compressor in Color Cache: Number of times sectors 0 and 1 were compressed as 4:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO2__1BLOCK_4TO3 = 0x00000120, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:2 blocks and sector 0 was compressed as 4:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO2__1BLOCK_4TO4 = 0x00000121, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:2 blocks and sector 0 was compressed as 4:4 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO3__1BLOCK_4TO1 = 0x00000122, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:3 blocks and sector 0 was compressed as 4:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO3__1BLOCK_4TO2 = 0x00000123, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:3 blocks and sector 0 was compressed as 4:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_4TO3 = 0x00000124, // From DCC Compressor in Color Cache: Number of times sectors 0 & 1 were compressed as 4:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO3__1BLOCK_4TO4 = 0x00000125, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:3 blocks and sector 0 was compressed as 4:4 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO4__1BLOCK_4TO1 = 0x00000126, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:4 (uncompressed) and sector 0 was compressed as 4:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO4__1BLOCK_4TO2 = 0x00000127, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:4 (uncompressed) and sector 0 was compressed as 4:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO4__1BLOCK_4TO3 = 0x00000128, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 4:4 (uncompressed) and sector 0 was compressed as 4:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO1__1BLOCK_4TO1 = 0x00000129, // From DCC Compressor in Color Cache: Number of times sectors 1 and 2 were compressed as 2:1 blocks and sector 0 was compressed as 4:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO1__1BLOCK_4TO2 = 0x0000012a, // From DCC Compressor in Color Cache: Number of times sectors 1 and 2 were compressed as 2:1 blocks and sector 0 was compressed as 4:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO1__1BLOCK_4TO3 = 0x0000012b, // From DCC Compressor in Color Cache: Number of times sectors 1 and 2 were compressed as 2:1 blocks and sector 0 was compressed as 4:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO1__1BLOCK_4TO4 = 0x0000012c, // From DCC Compressor in Color Cache: Number of times sectors 1 and 2 were compressed as 2:1 blocks and sector 0 was compressed as 4:4 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_2TO2__1BLOCK_4TO1 = 0x0000012d, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 4:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_2TO2__1BLOCK_4TO2 = 0x0000012e, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 4:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_2TO2__1BLOCK_4TO3 = 0x0000012f, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 4:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_2TO2__1BLOCK_4TO4 = 0x00000130, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 4:4 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_2TO1__1BLOCK_4TO1 = 0x00000131, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 4:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_2TO1__1BLOCK_4TO2 = 0x00000132, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 4:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_2TO1__1BLOCK_4TO3 = 0x00000133, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 4:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_2TO1__1BLOCK_4TO4 = 0x00000134, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 4:4 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO2__1BLOCK_4TO1 = 0x00000135, // From DCC Compressor in Color Cache: Number of times sectors 1 and 2 were compressed as 2:2 (uncompressed) and sector 0 was compressed as 4:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO2__1BLOCK_4TO2 = 0x00000136, // From DCC Compressor in Color Cache: Number of times sectors 1 and 2 were compressed as 2:2 (uncompressed) and sector 0 was compressed as 4:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__2BLOCKS_2TO2__1BLOCK_4TO3 = 0x00000137, // From DCC Compressor in Color Cache: Number of times sectors 1 and 2 were compressed as 2:2 (uncompressed) and sector 0 was compressed as 4:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_4TO1__1BLOCK_2TO1 = 0x00000138, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 4:1 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_4TO2__1BLOCK_2TO1 = 0x00000139, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 4:2 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_4TO3__1BLOCK_2TO1 = 0x0000013a, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 4:3 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_4TO4__1BLOCK_2TO1 = 0x0000013b, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 4:4 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_4TO1__1BLOCK_2TO1 = 0x0000013c, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 4:1 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_4TO2__1BLOCK_2TO1 = 0x0000013d, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 4:2 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_4TO3__1BLOCK_2TO1 = 0x0000013e, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 4:3 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_4TO4__1BLOCK_2TO1 = 0x0000013f, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 4:4 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_4TO1__1BLOCK_2TO2 = 0x00000140, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 4:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_4TO2__1BLOCK_2TO2 = 0x00000141, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 4:2 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_4TO3__1BLOCK_2TO2 = 0x00000142, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 4:3 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_4TO4__1BLOCK_2TO2 = 0x00000143, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:1 blocks, sector 1 was compressed as 4:4 (uncompressed) and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_4TO1__1BLOCK_2TO2 = 0x00000144, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 4:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_4TO2__1BLOCK_2TO2 = 0x00000145, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 4:2 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_4TO3__1BLOCK_2TO2 = 0x00000146, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 2:2 (uncompressed), sector 1 was compressed as 4:3 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO1__2BLOCKS_2TO1 = 0x00000147, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:1 blocks and sectors 0 and 1 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO2__2BLOCKS_2TO1 = 0x00000148, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:2 blocks and sectors 0 and 1 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO3__2BLOCKS_2TO1 = 0x00000149, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:3 blocks and sectors 0 and 1 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO4__2BLOCKS_2TO1 = 0x0000014a, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:4 (uncompressed) and sectors 0 and 1 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO1__2BLOCKS_2TO2 = 0x0000014b, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:1 blocks and sectors 0 and 1 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO2__2BLOCKS_2TO2 = 0x0000014c, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:1 blocks and sectors 0 and 1 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO3__2BLOCKS_2TO2 = 0x0000014d, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:1 blocks and sectors 0 and 1 were compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO1__1BLOCK_2TO1__1BLOCK_2TO2 = 0x0000014e, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:1 blocks, sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO2__1BLOCK_2TO1__1BLOCK_2TO2 = 0x0000014f, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:2 blocks, sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO3__1BLOCK_2TO1__1BLOCK_2TO2 = 0x00000150, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:3 blocks, sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO4__1BLOCK_2TO1__1BLOCK_2TO2 = 0x00000151, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:4 (uncompressed), sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO1__1BLOCK_2TO2__1BLOCK_2TO1 = 0x00000152, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:1 blocks, sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO2__1BLOCK_2TO2__1BLOCK_2TO1 = 0x00000153, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:2 blocks, sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO3__1BLOCK_2TO2__1BLOCK_2TO1 = 0x00000154, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:3 blocks, sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_4TO4__1BLOCK_2TO2__1BLOCK_2TO1 = 0x00000155, // From DCC Compressor in Color Cache: Number of times sector 2 was compressed as 4:4 (uncompressed), sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_6TO1 = 0x00000156, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 6:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_6TO2 = 0x00000157, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 6:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_6TO3 = 0x00000158, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 6:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_6TO4 = 0x00000159, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 6:4 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_6TO5 = 0x0000015a, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 6:5 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__1BLOCK_6TO6 = 0x0000015b, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:1 blocks and sector 0 was compressed as 6:6 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__INV0 = 0x0000015c, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:1 blocks and the key for the 6:x compression blocks is invalid (top 3 bits of the key are 3'b110). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO1__INV1 = 0x0000015d, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:1 blocks and the key for the 6:x compression blocks is invalid (top 3 bits of the key are 3'b111). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_6TO1 = 0x0000015e, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 6:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_6TO2 = 0x0000015f, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 6:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_6TO3 = 0x00000160, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 6:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_6TO4 = 0x00000161, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 6:4 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__1BLOCK_6TO5 = 0x00000162, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:2 (uncompressed) and sector 0 was compressed as 6:5 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__INV0 = 0x00000163, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:2 (uncompressed) and the key for the 6:x compression blocks is invalid (top 3 bits of the key are 3'b110). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_2TO2__INV1 = 0x00000164, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 2:2 (uncompressed) and the key for the 6:x compression blocks is invalid (top 3 bits of the key are 3'b111). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO1__1BLOCK_2TO1 = 0x00000165, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:1 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO2__1BLOCK_2TO1 = 0x00000166, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:2 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO3__1BLOCK_2TO1 = 0x00000167, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:3 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO4__1BLOCK_2TO1 = 0x00000168, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:4 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO5__1BLOCK_2TO1 = 0x00000169, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:5 blocks and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO6__1BLOCK_2TO1 = 0x0000016a, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:6 (uncompressed) and sector 0 was compressed as 2:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__INV0__1BLOCK_2TO1 = 0x0000016b, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 2:1 blocks and the key for the 6:x compression blocks is invalid (top 3 bits of the key are 3'b110). + CB_PERF_SEL_CC_DCC_KEY_VALUE__INV1__1BLOCK_2TO1 = 0x0000016c, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 2:1 blocks and the key for the 6:x compression blocks is invalid (top 3 bits of the key are 3'b111). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO1__1BLOCK_2TO2 = 0x0000016d, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:1 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO2__1BLOCK_2TO2 = 0x0000016e, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:2 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO3__1BLOCK_2TO2 = 0x0000016f, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:3 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO4__1BLOCK_2TO2 = 0x00000170, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:4 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_6TO5__1BLOCK_2TO2 = 0x00000171, // From DCC Compressor in Color Cache: Number of times sector 1 was compressed as 6:5 blocks and sector 0 was compressed as 2:2 (uncompressed). + CB_PERF_SEL_CC_DCC_KEY_VALUE__INV0__1BLOCK_2TO2 = 0x00000172, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 2:2 (uncompressed) and the key for the 6:x compression blocks is invalid (top 3 bits of the key are 3'b110). + CB_PERF_SEL_CC_DCC_KEY_VALUE__INV1__1BLOCK_2TO2 = 0x00000173, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 2:2 (uncompressed) and the key for the 6:x compression blocks is invalid (top 3 bits of the key are 3'b111). + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_8TO1 = 0x00000174, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 8:1 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_8TO2 = 0x00000175, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 8:2 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_8TO3 = 0x00000176, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 8:3 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_8TO4 = 0x00000177, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 8:4 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_8TO5 = 0x00000178, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 8:5 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_8TO6 = 0x00000179, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 8:6 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__1BLOCK_8TO7 = 0x0000017a, // From DCC Compressor in Color Cache: Number of times sector 0 was compressed as 8:7 blocks. + CB_PERF_SEL_CC_DCC_KEY_VALUE__UNCOMPRESSED = 0x0000017b, // From DCC Compressor in Color Cache: Number of times all sectors of a cacheline were uncompressed with a 2:2 ratio. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_2TO1 = 0x0000017c, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 2:1. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_4TO1 = 0x0000017d, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 4:1. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_4TO2 = 0x0000017e, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 4:2. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_4TO3 = 0x0000017f, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 4:3. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_6TO1 = 0x00000180, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 6:1. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_6TO2 = 0x00000181, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 6:2. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_6TO3 = 0x00000182, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 6:3. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_6TO4 = 0x00000183, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 6:4. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_6TO5 = 0x00000184, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 6:5. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_8TO1 = 0x00000185, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 8:1. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_8TO2 = 0x00000186, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 8:2. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_8TO3 = 0x00000187, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 8:3. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_8TO4 = 0x00000188, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 8:4. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_8TO5 = 0x00000189, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 8:5. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_8TO6 = 0x0000018a, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 8:6. + CB_PERF_SEL_CC_DCC_COMPRESS_RATIO_8TO7 = 0x0000018b, // From DCC Compressor in Color Cache: Number of times a sector was compressed as 8:7. + CB_PERF_SEL_RBP_EXPORT_8PIX_LIT_BOTH = 0x0000018c, // Number of 8PIX quad transfers that had both quads lit. + CB_PERF_SEL_RBP_EXPORT_8PIX_LIT_LEFT = 0x0000018d, // Number of 8PIX quad transfers that had only the left quad lit. + CB_PERF_SEL_RBP_EXPORT_8PIX_LIT_RIGHT = 0x0000018e, // Number of 8PIX quad transfers that had only the right quad lit. + CB_PERF_SEL_RBP_SPLIT_MICROTILE = 0x0000018f, // Number of 8PIX quad transfers that were split due to using DEPTH or ROTATED microtile mode. + CB_PERF_SEL_RBP_SPLIT_AA_SAMPLE_MASK = 0x00000190, // Number of 8PIX quad transfers that were split due to AA mode and not being either fully lit or fully unlit. + CB_PERF_SEL_RBP_SPLIT_PARTIAL_TARGET_MASK = 0x00000191, // Number of 8PIX quad transfers that were split due to partial target mask in AA or non-AA with non-byte-aligned target mask. + CB_PERF_SEL_RBP_SPLIT_LINEAR_ADDRESSING = 0x00000192, // Number of 8PIX quad transfers that were split due to the use of linear addressing. + CB_PERF_SEL_RBP_SPLIT_AA_NO_FMASK_COMPRESS = 0x00000193, // Number of 8PIX quad transfers that were split due to AA mode and no FMask Compression enabled. + CB_PERF_SEL_RBP_INSERT_MISSING_LAST_QUAD = 0x00000194, // Number of missing last quads of tile for MRTs needing CMask. + CB_PERF_SEL_NACK_CM_READ = 0x00000195, // A NACK was received for a CMask memory read request from RMI. + CB_PERF_SEL_NACK_CM_WRITE = 0x00000196, // A NACK was received for a CMask memory write request from RMI. + CB_PERF_SEL_NACK_FC_READ = 0x00000197, // A NACK was received for a FMask memory read request from RMI. + CB_PERF_SEL_NACK_FC_WRITE = 0x00000198, // A NACK was received for a FMask memory write request from RMI. + CB_PERF_SEL_NACK_DC_READ = 0x00000199, // A NACK was received for a DCC memory read request from RMI. + CB_PERF_SEL_NACK_DC_WRITE = 0x0000019a, // A NACK was received for a DCC memory write request from RMI. + CB_PERF_SEL_NACK_CC_READ = 0x0000019b, // A NACK was received for a Color memory read request from RMI. + CB_PERF_SEL_NACK_CC_WRITE = 0x0000019c, // A NACK was received for a Color memory write request from RMI. + CB_PERF_SEL_CM_MC_EARLY_WRITE_RETURN = 0x0000019d, // Number of early cmask mc write returns. CB_PERF_SEL_CM_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_CM_MC_EARLY_WRITE_RETURN = average early write latency. + CB_PERF_SEL_FC_MC_EARLY_WRITE_RETURN = 0x0000019e, // Number of early fmask mc write returns. CB_PERF_SEL_FC_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_FC_MC_EARLY_WRITE_RETURN = average early write latency. + CB_PERF_SEL_DC_MC_EARLY_WRITE_RETURN = 0x0000019f, // Number of early dcc mc write returns. CB_PERF_SEL_DC_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_DC_MC_EARLY_WRITE_RETURN = average early write latency. + CB_PERF_SEL_CC_MC_EARLY_WRITE_RETURN = 0x000001a0, // Number of early color mc write returns. CB_PERF_SEL_CC_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_CC_MC_EARLY_WRITE_RETURN = average early write latency. + CB_PERF_SEL_CM_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT = 0x000001a1, // Number of 32-byte cmask mc write requests in flight. CB_PERF_SEL_CM_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_CM_MC_EARLY_WRITE_RETURN = average early write latency IF all write requests had early write acks. + CB_PERF_SEL_FC_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT = 0x000001a2, // Number of 32-byte fmask mc write requests in flight. CB_PERF_SEL_FC_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_FC_MC_EARLY_WRITE_RETURN = average early write latency IF all write requests had early write acks. + CB_PERF_SEL_DC_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT = 0x000001a3, // Number of 32-byte dcc mc write requests in flight. CB_PERF_SEL_DC_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_DC_MC_EARLY_WRITE_RETURN = average early write latency IF all write requests had early write acks. + CB_PERF_SEL_CC_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT = 0x000001a4, // Number of 32-byte color mc write requests in flight. CB_PERF_SEL_CC_MC_EARLY_WRITE_REQUESTS_IN_FLIGHT/CB_PERF_SEL_CC_MC_EARLY_WRITE_RETURN = average early write latency IF all write requests had early write acks. + CB_PERF_SEL_CM_MC_WRITE_ACK64B = 0x000001a5, // Number of 64Byte write acks received by CB for write requests from CMask Cache. + CB_PERF_SEL_FC_MC_WRITE_ACK64B = 0x000001a6, // Number of 64Byte write acks received by CB for write requests from FMask Cache. + CB_PERF_SEL_DC_MC_WRITE_ACK64B = 0x000001a7, // Number of 64Byte write acks received by CB for write requests from DCC Cache. + CB_PERF_SEL_CC_MC_WRITE_ACK64B = 0x000001a8, // Number of 64Byte write acks received by CB for write requests from Color Cache. + CB_PERF_SEL_EVENT_BOTTOM_OF_PIPE_TS = 0x000001a9, // Number of BOTTOM_OF_PIPE_TS events. + CB_PERF_SEL_EVENT_FLUSH_AND_INV_DB_DATA_TS = 0x000001aa, // Number of FLUSH_AND_INV_DB_DATA_TS events. + CB_PERF_SEL_EVENT_FLUSH_AND_INV_CB_PIXEL_DATA = 0x000001ab, // Number of FLUSH_AND_INV_CB_PIXEL_DATA events. + CB_PERF_SEL_DB_CB_TILE_TILENOTEVENT = 0x000001ac, // Number of tiles (not events) received from DB. + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_32BPP_8PIX = 0x000001ad, // Number of transfers on DB_CB_lquad using EXPORT_32BPP_8PIX format. Sum of CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* == CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_16_16_UNSIGNED_8PIX = 0x000001ae, // Number of transfers on DB_CB_lquad using EXPORT_16_16_UNSIGNED_8PIX format. Sum of CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* == CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_16_16_SIGNED_8PIX = 0x000001af, // Number of transfers on DB_CB_lquad using EXPORT_16_16_SIGNED_8PIX format. Sum of CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* == CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_16_16_FLOAT_8PIX = 0x000001b0, // Number of transfers on DB_CB_lquad using EXPORT_16_16_FLOAT_8PIX format. Sum of CB_PERF_SEL_LQUAD_FORMAT_IS_EXPORT_* == CB_PERF_SEL_DB_CB_LQUAD_VALID_READY + CB_PERF_SEL_MERGE_PIXELS_WITH_BLEND_ENABLED = 0x000001b1, // Number of pixels, after tiles and quads are merged, that have blending enabled. + CB_PERF_SEL_DB_CB_CONTEXT_DONE = 0x000001b2, // Number of times the DB_CB_context_done signal, from DB, was asserted. + CB_PERF_SEL_DB_CB_EOP_DONE = 0x000001b3, // Number of times the DB_CB_eop_done signal, from DB, was asserted. + CB_PERF_SEL_CC_MC_WRITE_REQUEST_PARTIAL = 0x000001b4, // Number of color to MC write requests with partial write mask. (Note: CMask, Fmask and DCC are always full write mask writes). + CB_PERF_SEL_CC_BB_BLEND_PIXEL_VLD = 0x000001b5, // Number of transfers into CB's blender stage. + CB_PERF_SEL_CC_DCC_KEY_VALUE__CONST_CLEAR_REG = 0x000001b6, // From DCC Compressor in Color Cache: Number of times a sector was compressed as clear reg. + CB_PERF_SEL_CC_DCC_KEY_VALUE__CONST_CLEAR_SINGLE = 0x000001b7, // From DCC Compressor in Color Cache: Number of times a sector was compressed as clear single. + CB_PERF_SEL_CC_DCC_KEY_VALUE__CONST_CLEAR_AC00 = 0x000001b8, // From DCC Compressor in Color Cache: Number of times a sector was compressed as clear AC00. + CB_PERF_SEL_CC_DCC_KEY_VALUE__CONST_CLEAR_AC01 = 0x000001b9, // From DCC Compressor in Color Cache: Number of times a sector was compressed as clear AC01. + CB_PERF_SEL_CC_DCC_KEY_VALUE__CONST_CLEAR_AC10 = 0x000001ba, // From DCC Compressor in Color Cache: Number of times a sector was compressed as clear AC10. + CB_PERF_SEL_CC_DCC_KEY_VALUE__CONST_CLEAR_AC11 = 0x000001bb, // From DCC Compressor in Color Cache: Number of times a sector was compressed as clear AC11. + CB_PERF_SEL_TQ_STUTTER_STALL = 0x000001bc, // Number of times tq stutter stalled. + CB_PERF_SEL_FC_TILE_STUTTER_STALL = 0x000001bd, // Number of times fc tile stutter stalled. + CB_PERF_SEL_FC_QUAD_STUTTER_STALL = 0x000001be, // Number of times fc quad stutter stalled. + CB_PERF_SEL_FC_KEYID_STUTTER_STALL = 0x000001bf, // Number of times fc key stutter stalled. + CB_PERF_SEL_CC_EVENFIFO_STUTTER_STALL = 0x000001c0, // Number of times cc evenfifo stutter stalled. + CB_PERF_SEL_CC_ODDFIFO_STUTTER_STALL = 0x000001c1, // Number of times cc oddfifo stutter stalled. + CB_PERF_SEL_CC_CACHE_256BS_SAVED_DUE_TO_QSB = 0x000001c2, // Number of 256B fetches dropped due to intelligent scoreboard fetching with the QSB. + CB_PERF_SEL_FC_CACHE_FMASK_NO_FETCH = 0x000001c3, // Number of times FMask Cache Controller performed a skip of the FMask fetch (read) due to the FNF feature. + CB_PERF_SEL_CC_CACHE_SECTOR_HIT = 0x000001c4, // Number of quad fragment transactions that have color cache sector hit (TAG HIT && SECTOR HIT). A sector hit is when the required sector is in the cache. + CB_PERF_SEL_MIXMODE_CID_SWITCH_P0_GEN0_TO_P1 = 0x000001c5, // Number of context switches in mix mode in CB traffic from P0 in GEN0 to P1. + CB_PERF_SEL_MIXMODE_CID_SWITCH_P0_GEN1_TO_P1 = 0x000001c6, // Number of context switches in mix mode in CB traffic from P0 in GEN1 to P1. + CB_PERF_SEL_MIXMODE_CID_SWITCH_P0_GEN2_TO_P1 = 0x000001c7, // Number of context switches in mix mode in CB traffic from P0 in GEN2 to P1. + CB_PERF_SEL_MIXMODE_CID_SWITCH_P1_TO_P0_GEN0 = 0x000001c8, // Number of context switches in mix mode in CB traffic from P1 to P0 in GEN0. + CB_PERF_SEL_MIXMODE_CID_SWITCH_P1_TO_P0_GEN1 = 0x000001c9, // Number of context switches in mix mode in CB traffic from P1 to P0 in GEN1. + CB_PERF_SEL_MIXMODE_CID_SWITCH_P1_TO_P0_GEN2 = 0x000001ca, // Number of context switches in mix mode in CB traffic from P1 to P0 in GEN2. + CB_PERF_SEL_MIXMODE_CID_SWITCH_P1_TO_P1 = 0x000001cb, // Number of context switches in mix mode in CB traffic from P1 to P1 . + CB_PERF_SEL_MIXMODE_CID_SWITCH_P0_GENX_TO_P0_GENY = 0x000001cc, // Number of context switches in mix mode in CB traffic from P0 GENx to P0 GENy . +} CB_PERFCOUNTER_SELECT; + +typedef enum CHA_PERFCOUNTER_SELECT : unsigned int { + CHA_PERF_SEL_BUSY = 0x00000000, // Count busy cyles. Not windowable. + CHA_PERF_SEL_STALL_CHC0 = 0x00000001, // count stalled cycles. Not windowable. + CHA_PERF_SEL_STALL_CHC1 = 0x00000002, // count stalled cycles. Not windowable. + CHA_PERF_SEL_STALL_CHC2 = 0x00000003, // count stalled cycles. Not windowable. + CHA_PERF_SEL_STALL_CHC3 = 0x00000004, // count stalled cycles. Not windowable. + CHA_PERF_SEL_REQUEST_CHC0 = 0x00000005, // count request cycles. Not windowable. + CHA_PERF_SEL_REQUEST_CHC1 = 0x00000006, // count request cycles. Not windowable. + CHA_PERF_SEL_REQUEST_CHC2 = 0x00000007, // count request cycles. Not windowable. + CHA_PERF_SEL_REQUEST_CHC3 = 0x00000008, // count request cycles. Not windowable. + CHA_PERF_SEL_MEM_32B_WDS_CHC0 = 0x00000009, // count # of 32B words of memory xfers. Not windowable. + CHA_PERF_SEL_MEM_32B_WDS_CHC1 = 0x0000000a, // count # of 32B words of memory xfers. Not windowable. + CHA_PERF_SEL_MEM_32B_WDS_CHC2 = 0x0000000b, // count # of 32B words of memory xfers. Not windowable. + CHA_PERF_SEL_MEM_32B_WDS_CHC3 = 0x0000000c, // count # of 32B words of memory xfers. Not windowable. + CHA_PERF_SEL_IO_32B_WDS_CHC0 = 0x0000000d, // count # of 32B words of io xfers. Not windowable. + CHA_PERF_SEL_IO_32B_WDS_CHC1 = 0x0000000e, // count # of 32B words of io xfers. Not windowable. + CHA_PERF_SEL_IO_32B_WDS_CHC2 = 0x0000000f, // count # of 32B words of io xfers. Not windowable. + CHA_PERF_SEL_IO_32B_WDS_CHC3 = 0x00000010, // count # of 32B words of io xfers. Not windowable. + CHA_PERF_SEL_MEM_BURST_COUNT_CHC0 = 0x00000011, // count # of memory requests. Not windowable. + CHA_PERF_SEL_MEM_BURST_COUNT_CHC1 = 0x00000012, // count # of memory requests. Not windowable. + CHA_PERF_SEL_MEM_BURST_COUNT_CHC2 = 0x00000013, // count # of memory requests. Not windowable. + CHA_PERF_SEL_MEM_BURST_COUNT_CHC3 = 0x00000014, // count # of memory requests. Not windowable. + CHA_PERF_SEL_IO_BURST_COUNT_CHC0 = 0x00000015, // count # of io requests. Not windowable. + CHA_PERF_SEL_IO_BURST_COUNT_CHC1 = 0x00000016, // count # of io requests. Not windowable. + CHA_PERF_SEL_IO_BURST_COUNT_CHC2 = 0x00000017, // count # of io requests. Not windowable. + CHA_PERF_SEL_IO_BURST_COUNT_CHC3 = 0x00000018, // count # of io requests. Not windowable. + CHA_PERF_SEL_ARB_REQUESTS = 0x00000019, // count # of total arbiter requests. Not windowable. + CHA_PERF_SEL_REQ_INFLIGHT_LEVEL = 0x0000001a, // count # of total arbiter requests. Not windowable. + CHA_PERF_SEL_STALL_RET_CONFLICT_CHC0 = 0x0000001b, // count stalled return cycles. Not windowable. + CHA_PERF_SEL_STALL_RET_CONFLICT_CHC1 = 0x0000001c, // count stalled return cycles. Not windowable. + CHA_PERF_SEL_STALL_RET_CONFLICT_CHC2 = 0x0000001d, // count stalled return cycles. Not windowable. + CHA_PERF_SEL_STALL_RET_CONFLICT_CHC3 = 0x0000001e, // count stalled return cycles. Not windowable. + CHA_PERF_SEL_CYCLE = 0x0000001f, // Number of cycles. Not windowable. +} CHA_PERFCOUNTER_SELECT; + +typedef enum CHC_PERFCOUNTER_SELECT : unsigned int { + CHC_PERF_SEL_CYCLE = 0x00000000, // Number of cycles. Not windowable. + CHC_PERF_SEL_BUSY = 0x00000001, // Number of cycles with a request pending. Not Windowed. + CHC_PERF_SEL_STARVE = 0x00000002, // Number of cycles without a pending request from the CHA. Windowed. + CHC_PERF_SEL_ARB_RET_LEVEL = 0x00000003, // The sum of the number of requests sent to the GL1A for output arbitration in flight. Average GL1A return arbitration latency = GL1C_PERF_SEL_GL1A_RET_LEVEL/GL1C_PERF_SEL_REQ. + CHC_PERF_SEL_GL2_REQ_READ_LATENCY = 0x00000004, // Cycles in flight for reads, atomics w/ return, nop_rtn0. + CHC_PERF_SEL_GL2_REQ_WRITE_LATENCY = 0x00000005, // Cycles in flight for writes, atomics w/o return, nop_ack + CHC_PERF_SEL_REQ = 0x00000006, // Read, writes, atomics, nop. Invalids are not counted as requests. + CHC_PERF_SEL_REQ_ATOMIC_WITH_RET = 0x00000007, // Count of atomic requests with return + CHC_PERF_SEL_REQ_ATOMIC_WITHOUT_RET = 0x00000008, // Count of atomic requests without returns + CHC_PERF_SEL_REQ_NOP_ACK = 0x00000009, // Count of nops that require an ack + CHC_PERF_SEL_REQ_NOP_RTN0 = 0x0000000a, // Count of nops that require a return + CHC_PERF_SEL_REQ_READ = 0x0000000b, // Sum of REQ_READ_32B, REQ_READ_64B, REQ_READ_128B + CHC_PERF_SEL_REQ_READ_128B = 0x0000000c, // Count of read requests for 128B of data + CHC_PERF_SEL_REQ_READ_32B = 0x0000000d, // Count of read requests for 32B of data + CHC_PERF_SEL_REQ_READ_64B = 0x0000000e, // Count of read requests for 64B of data + CHC_PERF_SEL_REQ_WRITE = 0x0000000f, // Sum of REQ_WRITE_32B, REQ_WRITE_64B + CHC_PERF_SEL_REQ_WRITE_32B = 0x00000010, // Count of write requests containing 32B of data + CHC_PERF_SEL_REQ_WRITE_64B = 0x00000011, // Count of write requests containing 64B of data + CHC_PERF_SEL_STALL_GL2_GL1 = 0x00000012, // Number of cycles the cache was stalled due to backpressure from the GL2 + CHC_PERF_SEL_STALL_BUFFER_FULL = 0x00000013, // The buffer allocations have exhausted, and have stalled. We need to wait for a return before we can resume. + CHC_PERF_SEL_REQ_CLIENT0 = 0x00000014, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT1 = 0x00000015, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT2 = 0x00000016, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT3 = 0x00000017, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT4 = 0x00000018, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT5 = 0x00000019, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT6 = 0x0000001a, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT7 = 0x0000001b, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT8 = 0x0000001c, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT9 = 0x0000001d, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT10 = 0x0000001e, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT11 = 0x0000001f, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT12 = 0x00000020, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT13 = 0x00000021, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT14 = 0x00000022, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT15 = 0x00000023, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT16 = 0x00000024, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT17 = 0x00000025, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT18 = 0x00000026, // Count of per client requests + CHC_PERF_SEL_REQ_CLIENT19 = 0x00000027, // Count of per client requests +} CHC_PERFCOUNTER_SELECT; + +typedef enum CP_PERFCOUNTER_SELECT : unsigned int { + CPG_PERF_SEL_ALWAYS_COUNT = 0x00000000, // Always Count. + CPG_PERF_SEL_RBIU_FIFO_FULL = 0x00000001, // RBIU Transaction FIFO Full. + CPG_PERF_SEL_CSF_RTS_BUT_MIU_NOT_RTR = 0x00000002, // Reserved. + CPG_PERF_SEL_CSF_ST_BASE_SIZE_FIFO_FULL = 0x00000003, // Reserved. + CPG_PERF_SEL_CP_GRBM_DWORDS_SENT = 0x00000004, // Count of DWs actually sent to the GRBM. + CPG_PERF_SEL_ME_PARSER_BUSY = 0x00000005, // Count of MicroEngine Busy Clocks. + CPG_PERF_SEL_COUNT_TYPE0_PACKETS = 0x00000006, // Count of Type0 Packets processed in NRT. + CPG_PERF_SEL_COUNT_TYPE3_PACKETS = 0x00000007, // Count of Type3 Packets processed in NRT. + CPG_PERF_SEL_CSF_FETCHING_CMD_BUFFERS = 0x00000008, + CPG_PERF_SEL_CP_GRBM_OUT_OF_CREDITS = 0x00000009, // CP to GRBM path has data to send but is waiting for credits (free signals). + CPG_PERF_SEL_CP_PFP_GRBM_OUT_OF_CREDITS = 0x0000000a, // CP.PFP to GRBM path has data to send but is waiting for credits (free signals). + CPG_PERF_SEL_CP_GDS_GRBM_OUT_OF_CREDITS = 0x0000000b, // CP to GRBM path to GDS has data to send but is waiting for credits (free signals). + CPG_PERF_SEL_RCIU_STALLED_ON_ME_READ = 0x0000000c, // RCIU is stalled waiting for read data to be returned for the MicroEngine. + CPG_PERF_SEL_RCIU_STALLED_ON_DMA_READ = 0x0000000d, // RCIU is stalled waiting for read data to be returned for the DMA. + CPG_PERF_SEL_SSU_STALLED_ON_ACTIVE_CNTX = 0x0000000e, // Surface Sync Unit is waiting on a matching base in an Active Context. + CPG_PERF_SEL_SSU_STALLED_ON_CLEAN_SIGNALS = 0x0000000f, // Surface Sync Unit is waiting on all Clean signals to return. + CPG_PERF_SEL_QU_STALLED_ON_EOP_DONE_PULSE = 0x00000010, // Query Unit is stalled waiting for an EOP Done signal from the SC or SPI. + CPG_PERF_SEL_QU_STALLED_ON_EOP_DONE_WR_CONFIRM = 0x00000011, // Query Unit is stalled waiting for a write confirm on EOP Done data. + CPG_PERF_SEL_PFP_STALLED_ON_CSF_READY = 0x00000012, // PFP is stalled trying to write to the CSF. + CPG_PERF_SEL_PFP_STALLED_ON_MEQ_READY = 0x00000013, // PFP is stalled trying to write to the MEQ. + CPG_PERF_SEL_PFP_STALLED_ON_RCIU_READY = 0x00000014, // PFP is stalled trying to write to the RCIU + CPG_PERF_SEL_PFP_STALLED_FOR_DATA_FROM_ROQ = 0x00000015, // PFP is stalled waiting for data from the ROQ. + CPG_PERF_SEL_ME_STALLED_FOR_DATA_FROM_PFP = 0x00000016, // MicroEngine is stalled waiting for data from the PFP. + CPG_PERF_SEL_ME_STALLED_FOR_DATA_FROM_STQ = 0x00000017, // MicroEngine is stalled waiting for data from the State Queue. + CPG_PERF_SEL_ME_STALLED_ON_NO_AVAIL_GFX_CNTX = 0x00000018, // ME is stalled waiting for an available GFX context. + CPG_PERF_SEL_ME_STALLED_WRITING_TO_RCIU = 0x00000019, // ME is stalled trying to write to the RCIU (GRBM). + CPG_PERF_SEL_ME_STALLED_WRITING_CONSTANTS = 0x0000001a, // ME is stalled trying to write constants to the RCIU/MIU (GRBM/MC). + CPG_PERF_SEL_ME_STALLED_ON_PARTIAL_FLUSH = 0x0000001b, // The ME sent out a Partial Flush event and is waiting for a response from the SPI. + CPG_PERF_SEL_ME_WAIT_ON_CE_COUNTER = 0x0000001c, // The ME is waiting on the CE to write the constants to memory (and increment the up/down counter). + CPG_PERF_SEL_ME_WAIT_ON_AVAIL_BUFFER = 0x0000001d, // The ME is waiting on the next buffer to be available - it is still in use. + CPG_PERF_SEL_SEMAPHORE_BUSY_POLLING_FOR_PASS = 0x0000001e, // Reserved. + CPG_PERF_SEL_LOAD_STALLED_ON_SET_COHERENCY = 0x0000001f, // LOAD packet is stalled waiting on Coherency Counter=0 (SET packet writes completed). + CPG_PERF_SEL_DYNAMIC_CLK_VALID = 0x00000020, // Input from CGTT_LOCAL output: dyn_oclk_vld + CPG_PERF_SEL_REGISTER_CLK_VALID = 0x00000021, // Input from CGTT_LOCAL output: reg_oclk_vld + CPG_PERF_SEL_GUS_WRITE_REQUEST_SENT = 0x00000022, // Count of MC write requests. + CPG_PERF_SEL_GUS_READ_REQUEST_SENT = 0x00000023, // Count of MC read requests. + CPG_PERF_SEL_CE_STALL_RAM_DUMP = 0x00000024, // CE is stalled while trying to issue a RAM DUMP. + CPG_PERF_SEL_CE_STALL_RAM_WRITE = 0x00000025, // CE is stalled while trying to issue a RAM WRITE. + CPG_PERF_SEL_CE_STALL_ON_INC_FIFO = 0x00000026, // CE is stalled while trying to write to the increment FIFO. + CPG_PERF_SEL_CE_STALL_ON_WR_RAM_FIFO = 0x00000027, // CE is stalled while trying to write to the write ram FIFO. + CPG_PERF_SEL_CE_STALL_ON_DATA_FROM_MIU = 0x00000028, // Reserved. + CPG_PERF_SEL_CE_STALL_ON_DATA_FROM_ROQ = 0x00000029, // CE is stalled waiting on data from the ROQ. + CPG_PERF_SEL_CE_STALL_ON_CE_BUFFER_FLAG = 0x0000002a, // CE is stalled waiting for an available buffer. + CPG_PERF_SEL_CE_STALL_ON_DE_COUNTER = 0x0000002b, // CE is stalled waiting for the DE counter. + CPG_PERF_SEL_TCIU_STALL_WAIT_ON_FREE = 0x0000002c, // TCIU is stalled waiting on credits from the TC. + CPG_PERF_SEL_TCIU_STALL_WAIT_ON_TAGS = 0x0000002d, // TCIU has used all available tags and is waiting on the TC to return them. + CPG_PERF_SEL_UTCL2IU_STALL_WAIT_ON_FREE = 0x0000002e, // UTCL2IU is stalled waiting on credits from the UTCL2. + CPG_PERF_SEL_UTCL2IU_STALL_WAIT_ON_TAGS = 0x0000002f, // UTCL2IU has used all available tags and is waiting on the UTCL2 to return them. + CPG_PERF_SEL_UTCL1_STALL_ON_TRANSLATION = 0x00000030, // One of the UTCL1s is stalled waiting on translation, XNACK or PENDING response. + CPG_PERF_SEL_TCIU_WRITE_REQUEST_SENT = 0x00000031, // Count of TC write requests. + CPG_PERF_SEL_TCIU_READ_REQUEST_SENT = 0x00000032, // Count of TC read requests. + CPG_PERF_SEL_CPG_STAT_BUSY = 0x00000033, // CPG Busy. + CPG_PERF_SEL_CPG_STAT_IDLE = 0x00000034, // CPG Idle. + CPG_PERF_SEL_CPG_STAT_STALL = 0x00000035, // CPG Stalled. + CPG_PERF_SEL_CPG_TCIU_BUSY = 0x00000036, // CPG TCIU interface Busy. + CPG_PERF_SEL_CPG_TCIU_IDLE = 0x00000037, // CPG TCIU interface Idle. + CPG_PERF_SEL_CPG_TCIU_STALL = 0x00000038, // CPG TCIU interface Stalled waiting on Free, Tags. + CPG_PERF_SEL_CPG_UTCL2IU_BUSY = 0x00000039, // CPG UTCL2 interface Busy. + CPG_PERF_SEL_CPG_UTCL2IU_IDLE = 0x0000003a, // CPG UTCL2 interface Idle. + CPG_PERF_SEL_CPG_UTCL2IU_STALL = 0x0000003b, // CPG UTCL2 interface Stalled waiting on Free, Tags. + CPG_PERF_SEL_CPG_GCRIU_BUSY = 0x0000003c, // CPG GCR interface Busy. + CPG_PERF_SEL_CPG_GCRIU_IDLE = 0x0000003d, // CPG GCR interface Idle. + CPG_PERF_SEL_CPG_GCRIU_STALL = 0x0000003e, // CPG GCR interface Stalled waiting on Free. + CPG_PERF_SEL_GCRIU_STALL_WAIT_ON_FREE = 0x0000003f, // GCRIU is stalled waiting on credits from the GCR. + CPG_PERF_SEL_ALL_GFX_PIPES_BUSY = 0x00000040, // All Graphics Pipes Simultaneously Busy. + CPG_PERF_SEL_CPG_UTCL2IU_XACK = 0x00000041, // CPG UTCL2 response interface XACK. + CPG_PERF_SEL_CPG_UTCL2IU_XNACK = 0x00000042, // CPG UTCL2 response interface XNACK. + CPG_PERF_SEL_PFP_STALLED_ON_MEQ_DDID_READY = 0x00000043, // PFP is stalled trying to write to the MEQ due to DDID stall. + CPG_PERF_SEL_PFP_INSTR_CACHE_HIT = 0x00000044, // PFP Instruction Cache Hits + CPG_PERF_SEL_PFP_INSTR_CACHE_MISS = 0x00000045, // PFP Instruction Cache Misses + CPG_PERF_SEL_CE_INSTR_CACHE_HIT = 0x00000046, // CE Instruction Cache Hits + CPG_PERF_SEL_CE_INSTR_CACHE_MISS = 0x00000047, // CE Instruction Cache Misses + CPG_PERF_SEL_ME_INSTR_CACHE_HIT = 0x00000048, // ME Instruction Cache Hits + CPG_PERF_SEL_ME_INSTR_CACHE_MISS = 0x00000049, // ME Instruction Cache Misses + CPG_PERF_SEL_PFP_PACKET_FILTER_HIT_IB1 = 0x0000004a, // PFP Packet Filter Hits IB1 + CPG_PERF_SEL_PFP_PACKET_FILTER_MISS_IB1 = 0x0000004b, // PFP Packet Filter Misses IB1 + CPG_PERF_SEL_PFP_PACKET_FILTER_HIT_IB2 = 0x0000004c, // PFP Packet Filter Hits IB2 + CPG_PERF_SEL_PFP_PACKET_FILTER_MISS_IB2 = 0x0000004d, // PFP Packet Filter Misses IB2 + CPG_PERF_SEL_DMA_BUSY = 0x0000004e, // DMA Engine Busy + CPG_PERF_SEL_DMA_STARVED = 0x0000004f, // DMA Engine is waiting on source data + CPG_PERF_SEL_DMA_STALLED = 0x00000050, // DMA Engine is stalled writing destination data + CPG_PERF_SEL_DMA_FETCHER_STALLED_ON_ROQ_FULL = 0x00000051, // DMA Engine fetcher is stalled on ROQ full +} CP_PERFCOUNTER_SELECT; + +typedef enum CPC_PERFCOUNTER_SELECT : unsigned int { + CPC_PERF_SEL_ALWAYS_COUNT = 0x00000000, // Always Count. + CPC_PERF_SEL_RCIU_STALL_WAIT_ON_FREE = 0x00000001, // RCIU Stall Waiting on Free. + CPC_PERF_SEL_RCIU_STALL_PRIV_VIOLATION = 0x00000002, // RCIU Stall on Priv violation. + CPC_PERF_SEL_MIU_STALL_ON_RDREQ_FREE = 0x00000003, // Reserved. + CPC_PERF_SEL_MIU_STALL_ON_WRREQ_FREE = 0x00000004, // Reserved. + CPC_PERF_SEL_TCIU_STALL_WAIT_ON_FREE = 0x00000005, // TCIU Stall waiting for free. + CPC_PERF_SEL_ME1_STALL_WAIT_ON_RCIU_READY = 0x00000006, // Me1 stall waiting on RCIU Ready. + CPC_PERF_SEL_ME1_STALL_WAIT_ON_RCIU_READY_PERF = 0x00000007, // Me1 stall waiting on RCIU Ready Perf. + CPC_PERF_SEL_ME1_STALL_WAIT_ON_RCIU_READ = 0x00000008, // Me1 stall waiting on RCIU read. + CPC_PERF_SEL_ME1_STALL_WAIT_ON_GUS_READ = 0x00000009, // Me1 stall waiting on GUS read. + CPC_PERF_SEL_ME1_STALL_WAIT_ON_GUS_WRITE = 0x0000000a, // Me1 stall waiting on GUS write. + CPC_PERF_SEL_ME1_STALL_ON_DATA_FROM_ROQ = 0x0000000b, // Me1 stall on data from roq. + CPC_PERF_SEL_ME1_STALL_ON_DATA_FROM_ROQ_PERF = 0x0000000c, // Me1 stall on data from roq Perf. + CPC_PERF_SEL_ME1_BUSY_FOR_PACKET_DECODE = 0x0000000d, // Me1 busy for packet decode. + CPC_PERF_SEL_ME2_STALL_WAIT_ON_RCIU_READY = 0x0000000e, // Me2 stall waiting on RCIU Ready. (Valid Only if ME2 is available + CPC_PERF_SEL_ME2_STALL_WAIT_ON_RCIU_READY_PERF = 0x0000000f, // Me2 stall waiting on RCIU Ready Perf. (Valid Only if ME2 is available + CPC_PERF_SEL_ME2_STALL_WAIT_ON_RCIU_READ = 0x00000010, // Me2 stall waiting on RCIU read. (Valid Only if ME2 is available + CPC_PERF_SEL_ME2_STALL_WAIT_ON_GUS_READ = 0x00000011, // Me2 stall waiting on GUS read. + CPC_PERF_SEL_ME2_STALL_WAIT_ON_GUS_WRITE = 0x00000012, // Me2 stall waiting on GUS write. + CPC_PERF_SEL_ME2_STALL_ON_DATA_FROM_ROQ = 0x00000013, // Me2 stall on data from roq. (Valid Only if ME2 is available + CPC_PERF_SEL_ME2_STALL_ON_DATA_FROM_ROQ_PERF = 0x00000014, // Me2 stall on data from roq Perf. (Valid Only if ME2 is available + CPC_PERF_SEL_ME2_BUSY_FOR_PACKET_DECODE = 0x00000015, // Me2 busy for packet decode. (Valid Only if ME2 is available + CPC_PERF_SEL_UTCL2IU_STALL_WAIT_ON_FREE = 0x00000016, // UTCL2IU is stalled waiting on credits from the UTCL2. + CPC_PERF_SEL_UTCL2IU_STALL_WAIT_ON_TAGS = 0x00000017, // UTCL2IU has used all available tags and is waiting on the UTCL2 to return them. + CPC_PERF_SEL_UTCL1_STALL_ON_TRANSLATION = 0x00000018, // One of the UTCL1s is stalled waiting on translation, XNACK or PENDING response. + CPC_PERF_SEL_CPC_STAT_BUSY = 0x00000019, // CPC Busy. + CPC_PERF_SEL_CPC_STAT_IDLE = 0x0000001a, // CPC Idle. + CPC_PERF_SEL_CPC_STAT_STALL = 0x0000001b, // CPC Stalled. + CPC_PERF_SEL_CPC_TCIU_BUSY = 0x0000001c, // CPC TCIU interface Busy. + CPC_PERF_SEL_CPC_TCIU_IDLE = 0x0000001d, // CPC TCIU interface Idle. + CPC_PERF_SEL_CPC_UTCL2IU_BUSY = 0x0000001e, // CPC UTCL2 interface Busy. + CPC_PERF_SEL_CPC_UTCL2IU_IDLE = 0x0000001f, // CPC UTCL2 interface Idle. + CPC_PERF_SEL_CPC_UTCL2IU_STALL = 0x00000020, // CPC UTCL2 interface Stalled waiting on Free, Tags or Translation. + CPC_PERF_SEL_ME1_DC0_SPI_BUSY = 0x00000021, // CPC Me1 Processor Busy. + CPC_PERF_SEL_ME2_DC1_SPI_BUSY = 0x00000022, // CPC Me2 Processor Busy. (Valid Only if ME2 is available) + CPC_PERF_SEL_CPC_GCRIU_BUSY = 0x00000023, // CPC GCR interface Busy. + CPC_PERF_SEL_CPC_GCRIU_IDLE = 0x00000024, // CPC GCR interface Idle. + CPC_PERF_SEL_CPC_GCRIU_STALL = 0x00000025, // CPC GCR interface Stalled waiting on Free. + CPC_PERF_SEL_GCRIU_STALL_WAIT_ON_FREE = 0x00000026, // GCRIU is stalled waiting on credits from the GCR. + CPC_PERF_SEL_ME1_STALL_WAIT_ON_TCIU_READ = 0x00000027, // Me1 stall waiting on TCIU read. + CPC_PERF_SEL_ME2_STALL_WAIT_ON_TCIU_READ = 0x00000028, // Me2 stall waiting on TCIU read. + CPC_PERF_SEL_CPC_UTCL2IU_XACK = 0x00000029, // CPC UTCL2 response interface XACK. + CPC_PERF_SEL_CPC_UTCL2IU_XNACK = 0x0000002a, // CPC UTCL2 response interface XNACK. + CPC_PERF_SEL_MEC_INSTR_CACHE_HIT = 0x0000002b, // MEC Instruction Cache Hits + CPC_PERF_SEL_MEC_INSTR_CACHE_MISS = 0x0000002c, // MEC Instruction Cache Misses + CPC_PERF_SEL_MES_THREAD0 = 0x0000002d, // Thread0 Events - See CP_MES_PERFCOUNT_CNTL for more info + CPC_PERF_SEL_MES_THREAD1 = 0x0000002e, // Thread1 Events - See CP_MES_PERFCOUNT_CNTL for more info +} CPC_PERFCOUNTER_SELECT; + +typedef enum CPF_PERFCOUNTER_SELECT : unsigned int { + CPF_PERF_SEL_ALWAYS_COUNT = 0x00000000, // Always Count. + CPF_PERF_SEL_MIU_STALLED_WAITING_RDREQ_FREE = 0x00000001, // Reserved. + CPF_PERF_SEL_TCIU_STALLED_WAITING_ON_FREE = 0x00000002, // CPF TCIU stalled waiting on Free. + CPF_PERF_SEL_TCIU_STALLED_WAITING_ON_TAGS = 0x00000003, // CPF TCIU stalled waiting on tags. + CPF_PERF_SEL_CSF_BUSY_FOR_FETCHING_RING = 0x00000004, // CSF busy for fetching Ring data. + CPF_PERF_SEL_CSF_BUSY_FOR_FETCHING_IB1 = 0x00000005, // CSF busy for fetching Indirect buffer 1. + CPF_PERF_SEL_CSF_BUSY_FOR_FETCHING_IB2 = 0x00000006, // CSF busy for fetching Indirect buffer 2. + CPF_PERF_SEL_CSF_BUSY_FOR_FETCHING_STATE = 0x00000007, // CSF busy for fetching state data. + CPF_PERF_SEL_MIU_BUSY_FOR_OUTSTANDING_TAGS = 0x00000008, // Reserved. + CPF_PERF_SEL_CSF_RTS_MIU_NOT_RTR = 0x00000009, // Reserved. + CPF_PERF_SEL_CSF_STATE_FIFO_NOT_RTR = 0x0000000a, // CSF state fifo no RTR. + CPF_PERF_SEL_CSF_FETCHING_CMD_BUFFERS = 0x0000000b, // CSF is fetching command buffers. + CPF_PERF_SEL_GRBM_DWORDS_SENT = 0x0000000c, // CPF to GRBM 4 Dwords sent. + CPF_PERF_SEL_DYNAMIC_CLOCK_VALID = 0x0000000d, // CPF Dynamic clock is valid. + CPF_PERF_SEL_REGISTER_CLOCK_VALID = 0x0000000e, // CPF register clock is valid. + CPF_PERF_SEL_GUS_WRITE_REQUEST_SENT = 0x0000000f, // CPF Gus write request sent. + CPF_PERF_SEL_GUS_READ_REQUEST_SENT = 0x00000010, // CPF Gus read request sent. + CPF_PERF_SEL_UTCL2IU_STALL_WAIT_ON_FREE = 0x00000011, // UTCL2IU is stalled waiting on credits from the UTCL2. + CPF_PERF_SEL_UTCL2IU_STALL_WAIT_ON_TAGS = 0x00000012, // UTCL2IU has used all available tags and is waiting on the UTCL2 to return them. + CPF_PERF_SEL_GFX_UTCL1_STALL_ON_TRANSLATION = 0x00000013, // One of the Graphics UTCL1s is stalled waiting on translation, XNACK or PENDING response. + CPF_PERF_SEL_CMP_UTCL1_STALL_ON_TRANSLATION = 0x00000014, // One of the Compute UTCL1s is stalled waiting on translation, XNACK or PENDING response. + CPF_PERF_SEL_RCIU_STALL_WAIT_ON_FREE = 0x00000015, // CPF RCIU is stalled waiting on credits from GRBM. + CPF_PERF_SEL_TCIU_WRITE_REQUEST_SENT = 0x00000016, // Count of TC write requests + CPF_PERF_SEL_TCIU_READ_REQUEST_SENT = 0x00000017, // Count of TC read requests + CPF_PERF_SEL_CPF_STAT_BUSY = 0x00000018, // CPF Busy. + CPF_PERF_SEL_CPF_STAT_IDLE = 0x00000019, // CPF Idle. + CPF_PERF_SEL_CPF_STAT_STALL = 0x0000001a, // CPF Stalled. + CPF_PERF_SEL_CPF_TCIU_BUSY = 0x0000001b, // CPF TCIU interface Busy. + CPF_PERF_SEL_CPF_TCIU_IDLE = 0x0000001c, // CPF TCIU interface Idle. + CPF_PERF_SEL_CPF_TCIU_STALL = 0x0000001d, // CPF TCIU interface Stalled waiting on Free, Tags. + CPF_PERF_SEL_CPF_UTCL2IU_BUSY = 0x0000001e, // CPF UTCL2 interface Busy. + CPF_PERF_SEL_CPF_UTCL2IU_IDLE = 0x0000001f, // CPF UTCL2 interface Idle. + CPF_PERF_SEL_CPF_UTCL2IU_STALL = 0x00000020, // CPF UTCL2 interface Stalled waiting on Free, Tags. + CPF_PERF_SEL_CPF_GCRIU_BUSY = 0x00000021, // CPF GCR interface Busy. + CPF_PERF_SEL_CPF_GCRIU_IDLE = 0x00000022, // CPF GCR interface Idle. + CPF_PERF_SEL_CPF_GCRIU_STALL = 0x00000023, // CPF GCR interface Stalled waiting on Free. + CPF_PERF_SEL_GCRIU_STALL_WAIT_ON_FREE = 0x00000024, // GCRIU is stalled waiting on credits from the GCR. + CPF_PERF_SEL_CSF_BUSY_FOR_FETCHING_DB = 0x00000025, // CSF busy for fetching Data buffer. + CPF_PERF_SEL_CPF_UTCL2IU_XACK = 0x00000026, // CPF UTCL2 response interface XACK. + CPF_PERF_SEL_CPF_UTCL2IU_XNACK = 0x00000027, // CPF UTCL2 response interface XNACK. +} CPF_PERFCOUNTER_SELECT; + +typedef enum DB_PERFCOUNTER_SELECT : unsigned int { + DB_PERF_SEL_SC_DB_tile_sends = 0x00000000, // Cycles Interface is sending + DB_PERF_SEL_SC_DB_tile_busy = 0x00000001, // Cycles Interface is busy + DB_PERF_SEL_SC_DB_tile_stalls = 0x00000002, // Cycles Interface is stalled + DB_PERF_SEL_SC_DB_tile_events = 0x00000003, // Events sent over interface + DB_PERF_SEL_SC_DB_tile_tiles = 0x00000004, // Tiles sent over interface + DB_PERF_SEL_SC_DB_tile_covered = 0x00000005, // Fully covered tiles + DB_PERF_SEL_hiz_tc_read_starved = 0x00000006, // HiZ starved waiting for htile data from cache + DB_PERF_SEL_hiz_tc_write_stall = 0x00000007, // HiZ stalled writing to htile cache + DB_PERF_SEL_hiz_tile_culled = 0x00000008, // Tiles culled by hiZ + DB_PERF_SEL_his_tile_culled = 0x00000009, // Tiles culled by HiS + DB_PERF_SEL_DB_SC_tile_sends = 0x0000000a, // Cycles Interface is sending + DB_PERF_SEL_DB_SC_tile_busy = 0x0000000b, // Cycles Interface is busy + DB_PERF_SEL_DB_SC_tile_stalls = 0x0000000c, // Cycles Interface is stalled by SC + DB_PERF_SEL_DB_SC_tile_df_stalls = 0x0000000d, // Cycles Interface is stalled by detail walk tile fifo + DB_PERF_SEL_DB_SC_tile_tiles = 0x0000000e, // Tiles sent over interface + DB_PERF_SEL_DB_SC_tile_culled = 0x0000000f, // Tiles culled in total + DB_PERF_SEL_DB_SC_tile_hier_kill = 0x00000010, // Tiles culled due to a hierarchical fail test + DB_PERF_SEL_DB_SC_tile_fast_ops = 0x00000011, // Tiles culled because they were accerated fast tile ops. + DB_PERF_SEL_DB_SC_tile_no_ops = 0x00000012, // Tiles culled because they would not do anything + DB_PERF_SEL_DB_SC_tile_tile_rate = 0x00000013, // Tiles run at tile rate as opposed to sample rate tile + DB_PERF_SEL_DB_SC_tile_ssaa_kill = 0x00000014, // Tiles culled because they were supersample tiles that are merged into a fast tile op + DB_PERF_SEL_DB_SC_tile_fast_z_ops = 0x00000015, // Tiles that operate on Z in 1 clock. Can be inside a slow, pixel rate, or fast tile op + DB_PERF_SEL_DB_SC_tile_fast_stencil_ops = 0x00000016, // Tiles that operate on stencil in 1 clock. Can be inside a slow, pixel rate, or fast tile op + DB_PERF_SEL_SC_DB_quad_sends = 0x00000017, // Cycles Interface is sending + DB_PERF_SEL_SC_DB_quad_busy = 0x00000018, // Cycles Interface is busy + DB_PERF_SEL_SC_DB_quad_squads = 0x00000019, // Squads transferred over interface + DB_PERF_SEL_SC_DB_quad_tiles = 0x0000001a, // Tiles sent over interface + DB_PERF_SEL_SC_DB_quad_pixels = 0x0000001b, // Pixels transfered over interface + DB_PERF_SEL_SC_DB_quad_killed_tiles = 0x0000001c, // Number of detail killed tiles + DB_PERF_SEL_DB_SC_quad_sends = 0x0000001d, // Cycles Interface is sending + DB_PERF_SEL_DB_SC_quad_busy = 0x0000001e, // Cycles Interface is busy + DB_PERF_SEL_DB_SC_quad_stalls = 0x0000001f, // Cycles Interface is stalled + DB_PERF_SEL_DB_SC_quad_tiles = 0x00000020, // Tiles sent over interface + DB_PERF_SEL_DB_SC_quad_lit_quad = 0x00000021, // Quads transferred over the DB_SC_quad interface that are lit + DB_PERF_SEL_DB_CB_tile_sends = 0x00000022, // Cycles sending tiles/events to CB. Tiles not shaded or needed by the CB are not sent. + DB_PERF_SEL_DB_CB_tile_busy = 0x00000023, // + DB_PERF_SEL_DB_CB_tile_stalls = 0x00000024, // + DB_PERF_SEL_SX_DB_quad_sends = 0x00000025, // Cycles Interface is sending + DB_PERF_SEL_SX_DB_quad_busy = 0x00000026, // Cycles Interface is busy + DB_PERF_SEL_SX_DB_quad_stalls = 0x00000027, // Cycles Interface is stalled + DB_PERF_SEL_SX_DB_quad_quads = 0x00000028, // Quads sent over interface + DB_PERF_SEL_SX_DB_quad_pixels = 0x00000029, // Pixels sent over interface + DB_PERF_SEL_SX_DB_quad_exports = 0x0000002a, // Each MRT of a quad sent over interface + DB_PERF_SEL_SH_quads_outstanding_sum = 0x0000002b, // Multiply by 128 and divide by DB_SC_quad_quads to get PS latency. + DB_PERF_SEL_DB_CB_lquad_sends = 0x0000002c, // Cycles Interface is sending + DB_PERF_SEL_DB_CB_lquad_busy = 0x0000002d, // Cycles Interface is busy + DB_PERF_SEL_DB_CB_lquad_stalls = 0x0000002e, // Cycles Interface is stalled + DB_PERF_SEL_DB_CB_lquad_quads = 0x0000002f, // Coarse Quads sent over interface + DB_PERF_SEL_tile_rd_sends = 0x00000030, // HTile reads. Each is 256B + DB_PERF_SEL_mi_tile_rd_outstanding_sum = 0x00000031, // Multiply by 16 and divide by tile_rd_sends*8 to get htile memory latency + DB_PERF_SEL_quad_rd_sends = 0x00000032, // Quad read reqs. Each is 32B to 256B + DB_PERF_SEL_quad_rd_busy = 0x00000033, // Cycles quad read interface is trying to send requests + DB_PERF_SEL_quad_rd_mi_stall = 0x00000034, // Cycles quad read interface is stalled by the memory interface + DB_PERF_SEL_quad_rd_rw_collision = 0x00000035, // Cycles a quad read is stalled waiting for a write to finish + DB_PERF_SEL_quad_rd_tag_stall = 0x00000036, // Cycles a quad read is stalled because the read latency hiding fifo is full. + DB_PERF_SEL_quad_rd_32byte_reqs = 0x00000037, // Number of 32 Byte quad read requests + DB_PERF_SEL_quad_rd_panic = 0x00000038, // Cycles DB is panicing for quad read data + DB_PERF_SEL_mi_quad_rd_outstanding_sum = 0x00000039, // Multiply by 16 and divide by quad_rd_32byte_reqs to get depth buffer memory latency + DB_PERF_SEL_quad_rdret_sends = 0x0000003a, // Number of 32 byte quad read returns + DB_PERF_SEL_quad_rdret_busy = 0x0000003b, // Cycles the quad read data is returning + DB_PERF_SEL_tile_wr_sends = 0x0000003c, // 32 Byte HTile writes + DB_PERF_SEL_tile_wr_acks = 0x0000003d, // 32 Byte Htile write acks + DB_PERF_SEL_mi_tile_wr_outstanding_sum = 0x0000003e, // Multiply by 16 and divide by tile_wr_sends to get tile write memory latency + DB_PERF_SEL_quad_wr_sends = 0x0000003f, // Cycles quad is sending write requests to the memory interface block of the DB + DB_PERF_SEL_quad_wr_busy = 0x00000040, // Cycles quad is trying to write to the memory interface + DB_PERF_SEL_quad_wr_mi_stall = 0x00000041, // Cycles quad is stalled while writing to the memory interface + DB_PERF_SEL_quad_wr_coherency_stall = 0x00000042, // Cycles quad write is stalled waiting for a previous write to finish on the same address + DB_PERF_SEL_quad_wr_acks = 0x00000043, // Number of 32 Byte quad write acks + DB_PERF_SEL_mi_quad_wr_outstanding_sum = 0x00000044, // Multiply by 16 and divide by the quad_wr_sends to get quad memory write latency + DB_PERF_SEL_Tile_Cache_misses = 0x00000045, // Htile Cache misses + DB_PERF_SEL_Tile_Cache_hits = 0x00000046, // Htile Cache hits + DB_PERF_SEL_Tile_Cache_flushes = 0x00000047, // Htile Cache flushes + DB_PERF_SEL_Tile_Cache_surface_stall = 0x00000048, // Tile stalls waiting for an htile surface to flush and free + DB_PERF_SEL_Tile_Cache_starves = 0x00000049, // Tile stalls waiting for an htile cacheline to free + DB_PERF_SEL_Tile_Cache_mem_return_starve = 0x0000004a, // Tile stalls waiting for an htile memory read to return + DB_PERF_SEL_tcp_dispatcher_reads = 0x0000004b, // Number of htile cachelines fetched by the normal tile stream + DB_PERF_SEL_tcp_prefetcher_reads = 0x0000004c, // Number of htile cachelines fetched by the prefetcher + DB_PERF_SEL_tcp_preloader_reads = 0x0000004d, // Number of htile cachelines fetched by the preloader + DB_PERF_SEL_tcp_dispatcher_flushes = 0x0000004e, // Number of htile flushes caused byt the normal tile stream + DB_PERF_SEL_tcp_prefetcher_flushes = 0x0000004f, // Number of htile flushes caused byt the normal prefetcher + DB_PERF_SEL_tcp_preloader_flushes = 0x00000050, // Number of htile flushes caused byt the normal preloader + DB_PERF_SEL_Depth_Tile_Cache_sends = 0x00000051, // Tiles/Events through the Depth Tile Cache + DB_PERF_SEL_Depth_Tile_Cache_busy = 0x00000052, // Cycles the Depth Tile Cache is busy testing hit/miss on tiles/events + DB_PERF_SEL_Depth_Tile_Cache_starves = 0x00000053, // Cycles starved waiting for a depth surface tile tag to free up + DB_PERF_SEL_Depth_Tile_Cache_dtile_locked = 0x00000054, // Cycles stalled waiting for a forced flush or invalidate to finish + DB_PERF_SEL_Depth_Tile_Cache_alloc_stall = 0x00000055, // Cycles depth tile stalled while allocating data + DB_PERF_SEL_Depth_Tile_Cache_misses = 0x00000056, // Depth/Stencil Cache tile misses + DB_PERF_SEL_Depth_Tile_Cache_hits = 0x00000057, // Depth/Stencil Cache tile hits + DB_PERF_SEL_Depth_Tile_Cache_flushes = 0x00000058, // Depth/Stencil Cache tile flushes + DB_PERF_SEL_Depth_Tile_Cache_noop_tile = 0x00000059, // Noop tiles through the depth tile cache + DB_PERF_SEL_Depth_Tile_Cache_detailed_noop = 0x0000005a, // Detail walked noops though the depth tile cache + DB_PERF_SEL_Depth_Tile_Cache_event = 0x0000005b, // Events + DB_PERF_SEL_Depth_Tile_Cache_tile_frees = 0x0000005c, // Depth tile frees + DB_PERF_SEL_Depth_Tile_Cache_data_frees = 0x0000005d, // Depth tile data frees (may free data without freeing the dtile) + DB_PERF_SEL_Depth_Tile_Cache_mem_return_starve = 0x0000005e, // Cycles depth/stencil cache is waiting for memory to return + DB_PERF_SEL_Stencil_Cache_misses = 0x0000005f, // 512 bit allocation + DB_PERF_SEL_Stencil_Cache_hits = 0x00000060, // + DB_PERF_SEL_Stencil_Cache_flushes = 0x00000061, // 256 bit flushes. Two per cacheline unless it is compressed, in which case it is 1. + DB_PERF_SEL_Stencil_Cache_starves = 0x00000062, // Cache starves when the cache wants to miss but is out of cachelines to allocate + DB_PERF_SEL_Stencil_Cache_frees = 0x00000063, // + DB_PERF_SEL_Z_Cache_separate_Z_misses = 0x00000064, // + DB_PERF_SEL_Z_Cache_separate_Z_hits = 0x00000065, // + DB_PERF_SEL_Z_Cache_separate_Z_flushes = 0x00000066, // + DB_PERF_SEL_Z_Cache_separate_Z_starves = 0x00000067, // Cache starves when the cache wants to miss but is out of cachelines to allocate + DB_PERF_SEL_Z_Cache_pmask_misses = 0x00000068, // + DB_PERF_SEL_Z_Cache_pmask_hits = 0x00000069, // + DB_PERF_SEL_Z_Cache_pmask_flushes = 0x0000006a, // + DB_PERF_SEL_Z_Cache_pmask_starves = 0x0000006b, // Cache starves when the cache wants to miss but is out of cachelines to allocate + DB_PERF_SEL_Z_Cache_frees = 0x0000006c, // + DB_PERF_SEL_Plane_Cache_misses = 0x0000006d, // + DB_PERF_SEL_Plane_Cache_hits = 0x0000006e, // + DB_PERF_SEL_Plane_Cache_flushes = 0x0000006f, // + DB_PERF_SEL_Plane_Cache_starves = 0x00000070, // Cache starves when the cache wants to miss but is out of cachelines to allocate + DB_PERF_SEL_Plane_Cache_frees = 0x00000071, // + DB_PERF_SEL_flush_expanded_stencil = 0x00000072, // Tiles flushed with with expanded stencil + DB_PERF_SEL_flush_compressed_stencil = 0x00000073, // Tiles flushed with with compressed stencil + DB_PERF_SEL_flush_single_stencil = 0x00000074, // Tiles flushed with with single stencil + DB_PERF_SEL_planes_flushed = 0x00000075, // Total planes flushed among all tiles + DB_PERF_SEL_flush_1plane = 0x00000076, // Tiles flushed with 1 ZPlane + DB_PERF_SEL_flush_2plane = 0x00000077, // Tiles flushed with 2 ZPlanes + DB_PERF_SEL_flush_3plane = 0x00000078, // Tiles flushed with 3 ZPlanes + DB_PERF_SEL_flush_4plane = 0x00000079, // Tiles flushed with 4 ZPlanes + DB_PERF_SEL_flush_5plane = 0x0000007a, // Tiles flushed with 5 ZPlanes + DB_PERF_SEL_flush_6plane = 0x0000007b, // Tiles flushed with 6 ZPlanes + DB_PERF_SEL_flush_7plane = 0x0000007c, // Tiles flushed with 7 ZPlanes + DB_PERF_SEL_flush_8plane = 0x0000007d, // Tiles flushed with 8 ZPlanes + DB_PERF_SEL_flush_9plane = 0x0000007e, // Tiles flushed with 9 ZPlanes + DB_PERF_SEL_flush_10plane = 0x0000007f, // Tiles flushed with 10 ZPlanes + DB_PERF_SEL_flush_11plane = 0x00000080, // Tiles flushed with 11 ZPlanes + DB_PERF_SEL_flush_12plane = 0x00000081, // Tiles flushed with 12 ZPlanes + DB_PERF_SEL_flush_13plane = 0x00000082, // Tiles flushed with 13 ZPlanes + DB_PERF_SEL_flush_14plane = 0x00000083, // Tiles flushed with 14 ZPlanes + DB_PERF_SEL_flush_15plane = 0x00000084, // Tiles flushed with 15 ZPlanes + DB_PERF_SEL_flush_16plane = 0x00000085, // Tiles flushed with 16 ZPlanes + DB_PERF_SEL_flush_expanded_z = 0x00000086, // Tiles flushed with expanded Z + DB_PERF_SEL_earlyZ_waiting_for_postZ_done = 0x00000087, // Cycles stalled while transitioning from Late/ReZ to EarlyZ + DB_PERF_SEL_reZ_waiting_for_postZ_done = 0x00000088, // Cycles stalled while transitioning to ReZ from an incompatible Z mode/func/etc. + DB_PERF_SEL_dk_tile_sends = 0x00000089, // Detail kill block tiles/squads/events sent + DB_PERF_SEL_dk_tile_busy = 0x0000008a, // Cycles Detail Kill block busy + DB_PERF_SEL_dk_tile_quad_starves = 0x0000008b, // Cycles Detail Kill has tile, but no quads from the SC_DB_quad + DB_PERF_SEL_dk_tile_stalls = 0x0000008c, // Cycles Detail Kill is stalled from below + DB_PERF_SEL_dk_squad_sends = 0x0000008d, // Detail Kill squads + DB_PERF_SEL_dk_squad_busy = 0x0000008e, // Cycles the squad Detail Kill input is busy + DB_PERF_SEL_dk_squad_stalls = 0x0000008f, // Cycles squads are stalled from below. + DB_PERF_SEL_Op_Pipe_Busy = 0x00000090, // Cycles the quad OP pipe of the DB is busy (including memory fetches, but not initial startup) + DB_PERF_SEL_Op_Pipe_MC_Read_stall = 0x00000091, // Cycles the Op Pipe is waiting for memory to return (ignoring initial startup) + DB_PERF_SEL_qc_busy = 0x00000092, // Cycles the quad coherency is busy + DB_PERF_SEL_qc_xfc = 0x00000093, // Squads going through the quad coherency block + DB_PERF_SEL_qc_conflicts = 0x00000094, // Stalls ona a squad input because of a coherency check conflict (squads ahead of it could affect the dest data) + DB_PERF_SEL_qc_full_stall = 0x00000095, // Quad Coherency is stalled because it is out of slots. + DB_PERF_SEL_qc_in_preZ_tile_stalls_postZ = 0x00000096, // Cycles postZ squad inputs are stalled because the OP pipe is operating on a preZ tile, and there is no PreZ squad input available + DB_PERF_SEL_qc_in_postZ_tile_stalls_preZ = 0x00000097, // Cycles preZ squad inputs are stalled because the OP pipe is operating on a postZ tile, and there is no PostZ squad input available + DB_PERF_SEL_tsc_insert_summarize_stall = 0x00000098, // Cycles the op pipe is stalled by the tile summarizer inserting summarize squads + DB_PERF_SEL_tl_busy = 0x00000099, // Cycles Tile Lookup block busy + DB_PERF_SEL_tl_dtc_read_starved = 0x0000009a, // Cycles Tile Lookup block + DB_PERF_SEL_tl_z_fetch_stall = 0x0000009b, // Cycles Tile Lookup block stalled by zfetch block + DB_PERF_SEL_tl_stencil_stall = 0x0000009c, // Cycles Tile Lookup block stalled by stencil test block + DB_PERF_SEL_tl_z_decompress_stall = 0x0000009d, // Cycles Tile Lookup block stalled by z decompress block + DB_PERF_SEL_tl_stencil_locked_stall = 0x0000009e, // Cycles Tile Lookup block stalled by stencil being locked + DB_PERF_SEL_tl_events = 0x0000009f, // Cycles Tile Lookup block sends out events + DB_PERF_SEL_tl_summarize_squads = 0x000000a0, // Cycles Tile Lookup block sends out summarize squads + DB_PERF_SEL_tl_flush_expand_squads = 0x000000a1, // Cycles Tile Lookup block sends out flush expand squads + DB_PERF_SEL_tl_expand_squads = 0x000000a2, // Cycles Tile Lookup block sends out expand squads + DB_PERF_SEL_tl_preZ_squads = 0x000000a3, // Cycles Tile Lookup block sends out preZ squads + DB_PERF_SEL_tl_postZ_squads = 0x000000a4, // Cycles Tile Lookup block sends out postZ squads + DB_PERF_SEL_tl_preZ_noop_squads = 0x000000a5, // Cycles Tile Lookup block sends out noops on the preZ path + DB_PERF_SEL_tl_postZ_noop_squads = 0x000000a6, // Cycles Tile Lookup block sends out noops on the postZ path + DB_PERF_SEL_tl_tile_ops = 0x000000a7, // Cycles Tile Lookup block sends out tile op squads + DB_PERF_SEL_tl_in_xfc = 0x000000a8, // Cycles Tile Lookup block receives any input + DB_PERF_SEL_tl_in_single_stencil_expand_stall = 0x000000a9, // Cycles Tile Lookup block is stalling due to expanding single stencil + DB_PERF_SEL_tl_in_fast_z_stall = 0x000000aa, // Cycles Tile Lookup block is stalling due to fastZ + DB_PERF_SEL_tl_out_xfc = 0x000000ab, // Cycles Tile Lookup block is sending anything out + DB_PERF_SEL_tl_out_squads = 0x000000ac, // Cycles Tile Lookup block is sending squads out + DB_PERF_SEL_zf_plane_multicycle = 0x000000ad, // Cycles the z fetch is multicycling a squad because it needs to fetch more than 2 planes from the cache for compressed Z + DB_PERF_SEL_PostZ_Samples_passing_Z = 0x000000ae, // Samples passing Z test during a PostZ pass + DB_PERF_SEL_PostZ_Samples_failing_Z = 0x000000af, // Samples failing Z test during a PostZ pass + DB_PERF_SEL_PostZ_Samples_failing_S = 0x000000b0, // Samples failing Stencil test during a PostZ pass + DB_PERF_SEL_PreZ_Samples_passing_Z = 0x000000b1, // Samples passing Z test during a PreZ pass + DB_PERF_SEL_PreZ_Samples_failing_Z = 0x000000b2, // Samples failing Z test during a PreZ pass + DB_PERF_SEL_PreZ_Samples_failing_S = 0x000000b3, // Samples failing Stencil test during a PreZ pass + DB_PERF_SEL_ts_tc_update_stall = 0x000000b4, // Cycles Tile Summarizer to Tile Cache write interface is stalled + DB_PERF_SEL_sc_kick_start = 0x000000b5, // Times the DB sent a hang panic to the SC + DB_PERF_SEL_sc_kick_end = 0x000000b6, // Times the DB completed a hang panic + DB_PERF_SEL_clock_reg_active = 0x000000b7, // Cycles register part of DB is awake + DB_PERF_SEL_clock_main_active = 0x000000b8, // Cycles core part of DB is awake + DB_PERF_SEL_clock_mem_export_active = 0x000000b9, // Cycles mem export part of DB is awake + DB_PERF_SEL_esr_ps_out_busy = 0x000000ba, // Early Squad Router PS Iter Out cycles busy + DB_PERF_SEL_esr_ps_lqf_busy = 0x000000bb, // Early Squad Router to LQuad fifo cycles busy + DB_PERF_SEL_esr_ps_lqf_stall = 0x000000bc, // Early Squad Router to LQuad fifo cycles stalled + DB_PERF_SEL_etr_out_send = 0x000000bd, // Squads being sent through the Early Tile Router + DB_PERF_SEL_etr_out_busy = 0x000000be, // Cycles Early Tile router busy + DB_PERF_SEL_etr_out_ltile_probe_fifo_full_stall = 0x000000bf, // Cycles Early Tile router is stalled due to ltile probe fifo being full + DB_PERF_SEL_etr_out_cb_tile_stall = 0x000000c0, // Cycles Early Tile router is stalled due to running out of credits on cb tile interface + DB_PERF_SEL_etr_out_esr_stall = 0x000000c1, // Cycles Early Tile router is stalled due to Early Squad router back pressure + DB_PERF_SEL_esr_ps_sqq_busy = 0x000000c2, // Cycles Early Squad Router squad-to-quad block busy + DB_PERF_SEL_esr_ps_sqq_stall = 0x000000c3, // Cycles Early Squad Router squad-to-quad block stalled + DB_PERF_SEL_esr_eot_fwd_busy = 0x000000c4, // Cycles Early Squad Router end of tile forwarder busy + DB_PERF_SEL_esr_eot_fwd_holding_squad = 0x000000c5, // Cycles Early Squad Router end of tile forwarder is holding an squad waiting for end of tile + DB_PERF_SEL_esr_eot_fwd_forward = 0x000000c6, // Tiles where an end of tile is being forwarded + DB_PERF_SEL_esr_sqq_zi_busy = 0x000000c7, // Cycles Early Squad Router Z Interp busy + DB_PERF_SEL_esr_sqq_zi_stall = 0x000000c8, // Cycles Early Squad Router Z Interp stalled + DB_PERF_SEL_postzl_sq_pt_busy = 0x000000c9, // Cycles PostZ Squad Launcher squad to tile sync interface busy + DB_PERF_SEL_postzl_sq_pt_stall = 0x000000ca, // Cycles PostZ Squad Launcher squad to tile sync interface stalled + DB_PERF_SEL_postzl_se_busy = 0x000000cb, // Cycles PostZ Squad Launcher shader export busy + DB_PERF_SEL_postzl_se_stall = 0x000000cc, // Cycles PostZ Squad Launcher shader export stalled + DB_PERF_SEL_postzl_partial_launch = 0x000000cd, // Squads that are paritally launched by PostZ Squad Launcher + DB_PERF_SEL_postzl_full_launch = 0x000000ce, // Squads that are fully launched by PostZ Squad Launcher + DB_PERF_SEL_postzl_partial_waiting = 0x000000cf, // Cycles a partial squad is waiting for more quads to fill in the squad + DB_PERF_SEL_postzl_tile_mem_stall = 0x000000d0, // Cycles PostZ Squad Launcher stalled waiting for data from memory + DB_PERF_SEL_postzl_tile_init_stall = 0x000000d1, // Cycles PostZ Squad Launcher stalled waiting for cache to be initialized + DB_PERF_SEL_prezl_tile_mem_stall = 0x000000d2, // Cycles PreZ Squad Launcher stalled waiting for data from memory + DB_PERF_SEL_prezl_tile_init_stall = 0x000000d3, // Cycles PreZ Squad Launcher stalled waiting for cache to be initialized + DB_PERF_SEL_dtt_sm_clash_stall = 0x000000d4, // Cycles Depth Tile Tag Surface Manager stalled due to address clash with existing surface + DB_PERF_SEL_dtt_sm_slot_stall = 0x000000d5, // Cycles Depth Tile Tag Surface Manager stalled due to no slots being available + DB_PERF_SEL_dtt_sm_miss_stall = 0x000000d6, // Cycles Depth Tile Tag Surface Manager stalled due to surface miss + DB_PERF_SEL_mi_rdreq_busy = 0x000000d7, // Cycles Memory Interface read request busy + DB_PERF_SEL_mi_rdreq_stall = 0x000000d8, // Cycles Memory Interface read request stalled + DB_PERF_SEL_mi_wrreq_busy = 0x000000d9, // Cycles Memory Interface write request busy + DB_PERF_SEL_mi_wrreq_stall = 0x000000da, // Cycles Memory Interface write request stalled + DB_PERF_SEL_recomp_tile_to_1zplane_no_fastop = 0x000000db, // Tiles that went to 1 zplane without a fast z op + DB_PERF_SEL_dkg_tile_rate_tile = 0x000000dc, // Tiles running at tile rate through detail kill block + DB_PERF_SEL_prezl_src_in_sends = 0x000000dd, // Transactions going into Prez Squad Launcher Sample Rate converter + DB_PERF_SEL_prezl_src_in_stall = 0x000000de, // Cycles squad is stalled in the Prez Squad Launcher Sample Rate converter + DB_PERF_SEL_prezl_src_in_squads = 0x000000df, // Squads going into Prez Squad Launcher Sample Rate converter + DB_PERF_SEL_prezl_src_in_squads_unrolled = 0x000000e0, // Squads being unrolled in Prez Squad Launcher Sample Rate converter + DB_PERF_SEL_prezl_src_in_tile_rate = 0x000000e1, // Tile rate tiles going into the Prez Squad Launcher Sample Rate converter + DB_PERF_SEL_prezl_src_in_tile_rate_unrolled = 0x000000e2, // Tile rate tiles being unrolled in Prez Squad Launcher Sample Rate converter + DB_PERF_SEL_prezl_src_out_stall = 0x000000e3, // Cycles transaction is stalled on the output of Prez Squad Launcher Sample Rate converter + DB_PERF_SEL_postzl_src_in_sends = 0x000000e4, // Transactions going into Postz Squad Launcher Sample Rate converter + DB_PERF_SEL_postzl_src_in_stall = 0x000000e5, // Cycles squad is stalled in the Postz Squad Launcher Sample Rate converter + DB_PERF_SEL_postzl_src_in_squads = 0x000000e6, // Squads going into Postz Squad Launcher Sample Rate converter + DB_PERF_SEL_postzl_src_in_squads_unrolled = 0x000000e7, // Squads being unrolled in Postz Squad Launcher Sample Rate converter + DB_PERF_SEL_postzl_src_in_tile_rate = 0x000000e8, // Tile rate tiles going into the Postz Squad Launcher Sample Rate converter + DB_PERF_SEL_postzl_src_in_tile_rate_unrolled = 0x000000e9, // Tile rate tiles being unrolled in Postz Squad Launcher Sample Rate converter + DB_PERF_SEL_postzl_src_out_stall = 0x000000ea, // Cycles transaction is stalled on the output of Postz Squad Launcher Sample Rate converter + DB_PERF_SEL_esr_ps_src_in_sends = 0x000000eb, // Transactions going into Early Squad Router PS Iter Sample Rate converter + DB_PERF_SEL_esr_ps_src_in_stall = 0x000000ec, // Cycles squad is stalled in the Early Squad Router PS Iter Sample Rate converter + DB_PERF_SEL_esr_ps_src_in_squads = 0x000000ed, // Squads going into Early Squad Router PS Iter Sample Rate converter + DB_PERF_SEL_esr_ps_src_in_squads_unrolled = 0x000000ee, // Squads being unrolled in Early Squad Router PS Iter Sample Rate converter + DB_PERF_SEL_esr_ps_src_in_tile_rate = 0x000000ef, // Tile rate tiles going into the Early Squad Router PS Iter Sample Rate converter + DB_PERF_SEL_esr_ps_src_in_tile_rate_unrolled = 0x000000f0, // Tile rate tiles being unrolled in Early Squad Router PS Iter Sample Rate converter + DB_PERF_SEL_esr_ps_src_in_tile_rate_unrolled_to_pixel_rate = 0x000000f1, // Tile rate tiles being unrolled to pixel rate in Early Squad Router PS Iter Sample Rate converter + DB_PERF_SEL_esr_ps_src_out_stall = 0x000000f2, // Cycles transaction is stalled on the output of Early Squad Router PS Iter Sample Rate converter + DB_PERF_SEL_depth_bounds_tile_culled = 0x000000f3, // Tiles culled at hiz time due to depth bounds + DB_PERF_SEL_PreZ_Samples_failing_DB = 0x000000f4, // PreZ Samples failing depth bounds test + DB_PERF_SEL_PostZ_Samples_failing_DB = 0x000000f5, // PostZ Samples failing depth bounds test + DB_PERF_SEL_flush_compressed = 0x000000f6, // Tiles that flushed compressed + DB_PERF_SEL_flush_plane_le4 = 0x000000f7, // Tiles that flushed compressed with less than or equal to 4 planes + DB_PERF_SEL_tiles_z_fully_summarized = 0x000000f8, // Tiles that fully summarized z + DB_PERF_SEL_tiles_stencil_fully_summarized = 0x000000f9, // Tiles that fully summarized stencil + DB_PERF_SEL_tiles_z_clear_on_expclear = 0x000000fa, // Tiles that do a z clear on expanded and clear + DB_PERF_SEL_tiles_s_clear_on_expclear = 0x000000fb, // Tiles that do a stencil clear on expanded and clear + DB_PERF_SEL_tiles_decomp_on_expclear = 0x000000fc, // Tiles that do a z decompress on expanded and clear + DB_PERF_SEL_tiles_compressed_to_decompressed = 0x000000fd, // Tiles that transition from compressed to expanded + DB_PERF_SEL_Op_Pipe_Prez_Busy = 0x000000fe, // Cycles the op pipe is busy with prez squads + DB_PERF_SEL_Op_Pipe_Postz_Busy = 0x000000ff, // Cycles tha op pipe is busy with postz squads + DB_PERF_SEL_di_dt_stall = 0x00000100, // Cycles the op pipe stalls due to di/dt controller + DB_PERF_SEL_DB_SC_quad_lit_quad_pre_kill = 0x00000101, // Double quads transferred over the DB_SC_quad interface + DB_PERF_SEL_DB_SC_s_tile_rate = 0x00000102, // + DB_PERF_SEL_DB_SC_c_tile_rate = 0x00000103, // + DB_PERF_SEL_DB_SC_z_tile_rate = 0x00000104, // + Spare_261 = 0x00000105, // Spare + DB_PERF_SEL_DB_CB_lquad_export_quads = 0x00000106, // Number of lit quads for an export based on DB_CB_lquad_sample_mask + DB_PERF_SEL_DB_CB_lquad_double_format = 0x00000107, // Number of sends with format > 7 + DB_PERF_SEL_DB_CB_lquad_fast_format = 0x00000108, // Number of sends with format < 7 + DB_PERF_SEL_DB_CB_lquad_slow_format = 0x00000109, // Number of sends with format == 7 + DB_PERF_SEL_CB_DB_rdreq_sends = 0x0000010a, // Number of CB_DB memory read sends + DB_PERF_SEL_CB_DB_rdreq_prt_sends = 0x0000010b, // Number of CB_DB PRT memory read sends + DB_PERF_SEL_CB_DB_wrreq_sends = 0x0000010c, // Number of CB_DB memory write sends + DB_PERF_SEL_CB_DB_wrreq_prt_sends = 0x0000010d, // Number of CB_DB PRT memory write sends + DB_PERF_SEL_DB_CB_rdret_ack = 0x0000010e, // Number of DB_CB memory read return acks + DB_PERF_SEL_DB_CB_rdret_nack = 0x0000010f, // Number of DB_CB memory read return nacks + DB_PERF_SEL_DB_CB_wrret_ack = 0x00000110, // Number of DB_CB memory write return acks + DB_PERF_SEL_DB_CB_wrret_nack = 0x00000111, // Number of DB_CB memory write return nacks + Spare_274 = 0x00000112, // Spare + DB_PERF_SEL_DFSM_Stall_opmode_change = 0x00000113, // + DB_PERF_SEL_DFSM_Stall_cam_fifo = 0x00000114, // + DB_PERF_SEL_DFSM_Stall_bypass_fifo = 0x00000115, // + DB_PERF_SEL_DFSM_Stall_retained_tile_fifo = 0x00000116, // + DB_PERF_SEL_DFSM_Stall_control_fifo = 0x00000117, // + DB_PERF_SEL_DFSM_Stall_overflow_counter = 0x00000118, // + DB_PERF_SEL_DFSM_Stall_pops_stall_overflow = 0x00000119, // + DB_PERF_SEL_DFSM_Stall_pops_stall_self_flush = 0x0000011a, // + DB_PERF_SEL_DFSM_Stall_middle_output = 0x0000011b, // + DB_PERF_SEL_DFSM_Stall_stalling_general = 0x0000011c, // + Spare_285 = 0x0000011d, // Spare + Spare_286 = 0x0000011e, // Spare + DB_PERF_SEL_DFSM_prez_killed_squad = 0x0000011f, // Number of null squads killed prior to DFSM + DB_PERF_SEL_DFSM_squads_in = 0x00000120, // Number if squads in + DB_PERF_SEL_DFSM_full_cleared_squads_out = 0x00000121, // Number of squads out + DB_PERF_SEL_DFSM_quads_in = 0x00000122, // Number of quads in + DB_PERF_SEL_DFSM_fully_cleared_quads_out = 0x00000123, // Number of quads out + DB_PERF_SEL_DFSM_lit_pixels_in = 0x00000124, // Number of lit pixels in + DB_PERF_SEL_DFSM_fully_cleared_pixels_out = 0x00000125, // Number of lit pixels out + DB_PERF_SEL_DFSM_lit_samples_in = 0x00000126, // Number of lit samples in + DB_PERF_SEL_DFSM_lit_samples_out = 0x00000127, // Number of lit samples out + DB_PERF_SEL_DFSM_evicted_tiles_above_watermark = 0x00000128, // + DB_PERF_SEL_DFSM_cant_accept_squads_but_not_stalled_by_downstream = 0x00000129, // Number of cycles DFSM can't accept squads and not stalled by downstream + DB_PERF_SEL_DFSM_stalled_by_downstream = 0x0000012a, // Number of cycles DFSM stalled by downstream + DB_PERF_SEL_DFSM_evicted_squads_above_watermark = 0x0000012b, // Number of evicted squads due to above watermark + DB_PERF_SEL_DFSM_collisions_due_to_POPS_overflow = 0x0000012c, // Number of collisions detected due to overflow (POPS only) + DB_PERF_SEL_DFSM_collisions_detected_within_POPS_FIFO = 0x0000012d, // Number of collisions detected within the fifo (POPS only) + DB_PERF_SEL_DFSM_evicted_squads_due_to_prim_watermark = 0x0000012e, // Number of evicted squads due to primitive watermark + DB_PERF_SEL_MI_tile_req_wrack_counter_stall = 0x0000012f, // Number of cycles MI is stalled by tile wrack counter + DB_PERF_SEL_MI_quad_req_wrack_counter_stall = 0x00000130, // Number of cycles MI is stalled by quad wrack counter + DB_PERF_SEL_MI_zpc_req_wrack_counter_stall = 0x00000131, // Number of cycles MI is stalled by zpc wrack counter + DB_PERF_SEL_MI_psd_req_wrack_counter_stall = 0x00000132, // Number of cycles MI is stalled by psd wrack counter + DB_PERF_SEL_unmapped_z_tile_culled = 0x00000133, // Number of unmapped z tiles culled + DB_PERF_SEL_DB_CB_tile_is_event_FLUSH_AND_INV_DB_DATA_TS = 0x00000134, // Cycles sending FLUSH_AND_INV_DB_DATA_TS events to CB. + DB_PERF_SEL_DB_CB_tile_is_event_FLUSH_AND_INV_CB_PIXEL_DATA = 0x00000135, // Cycles sending FLUSH_AND_INV_CB_PIXEL_DATA events to CB. + DB_PERF_SEL_DB_CB_tile_is_event_BOTTOM_OF_PIPE_TS = 0x00000136, // Cycles sending BOTTOM_OF_PIPE_TS events to CB. + DB_PERF_SEL_DB_CB_tile_waiting_for_perfcounter_stop_event = 0x00000137, // Number of cycles between receiving a PERFCOUNTER_START event and a PERFCOUNTER_STOP event. + DB_PERF_SEL_DB_CB_lquad_fmt_32bpp_8pix = 0x00000138, // Number of sends with format == EXPORT_32BPP_8PIX. + DB_PERF_SEL_DB_CB_lquad_fmt_16_16_unsigned_8pix = 0x00000139, // Number of sends with format == EXPORT_16_16_UNSIGNED_8PIX. + DB_PERF_SEL_DB_CB_lquad_fmt_16_16_signed_8pix = 0x0000013a, // Number of sends with format == EXPORT_16_16_SIGNED_8PIX. + DB_PERF_SEL_DB_CB_lquad_fmt_16_16_float_8pix = 0x0000013b, // Number of sends with format == EXPORT_16_16_FLOAT_8PIX. + DB_PERF_SEL_DB_CB_lquad_num_pixels_need_blending = 0x0000013c, // Number of pixels sent to the CB that need blending. + DB_PERF_SEL_DB_CB_context_dones = 0x0000013d, // Number of context_done events sent to the CB. + DB_PERF_SEL_DB_CB_eop_dones = 0x0000013e, // Number of end-of-pipe (EOP) done events sent to the CB. + DB_PERF_SEL_SX_DB_quad_all_pixels_killed = 0x0000013f, // Number of times the pixel mask from the SX was all zeroes (empty mask). + DB_PERF_SEL_SX_DB_quad_all_pixels_enabled = 0x00000140, // Number of times the pixel mask from the SX was all ones (full mask). + DB_PERF_SEL_SX_DB_quad_need_blending_and_dst_read = 0x00000141, // Number of times the SX sends a quad that requires blending and a destination read. + DB_PERF_SEL_SC_DB_tile_backface = 0x00000142, // Backface tiles + DB_PERF_SEL_SC_DB_quad_quads = 0x00000143, // Number of quads sent to the DB. Depends on the sample rate. + DB_PERF_SEL_DB_SC_quad_quads_with_1_pixel = 0x00000144, // Number of times the DB sends the SC a quad with 1 pixel. Dual-quad mode is accounted for in this counter. + DB_PERF_SEL_DB_SC_quad_quads_with_2_pixels = 0x00000145, // Number of times the DB sends the SC a quad with 2 pixels. Dual-quad mode is accounted for in this counter. + DB_PERF_SEL_DB_SC_quad_quads_with_3_pixels = 0x00000146, // Number of times the DB sends the SC a quad with 3 pixels. Dual-quad mode is accounted for in this counter. + DB_PERF_SEL_DB_SC_quad_quads_with_4_pixels = 0x00000147, // Number of times the DB sends the SC a quad with 4 pixels. Dual-quad mode is accounted for in this counter. + DB_PERF_SEL_DFSM_Flush_flushabit = 0x00000148, // + DB_PERF_SEL_DFSM_Flush_flushabit_camcoord_fifo = 0x00000149, // + DB_PERF_SEL_DFSM_Flush_flushabit_passthrough = 0x0000014a, // + DB_PERF_SEL_DFSM_Flush_flushabit_forceflush = 0x0000014b, // + DB_PERF_SEL_DFSM_Flush_flushabit_nearlyfull = 0x0000014c, // + DB_PERF_SEL_DFSM_Flush_flushabit_primitivesinflightwatermark = 0x0000014d, // + DB_PERF_SEL_DFSM_Flush_flushabit_punch_stalling = 0x0000014e, // + DB_PERF_SEL_DFSM_Flush_flushabit_retainedtilefifo_watermark = 0x0000014f, // + DB_PERF_SEL_DFSM_Flush_flushabit_tilesinflightwatermark = 0x00000150, // + DB_PERF_SEL_DFSM_Flush_flushall = 0x00000151, // + DB_PERF_SEL_DFSM_Flush_flushall_dfsmflush = 0x00000152, // + DB_PERF_SEL_DFSM_Flush_flushall_opmodechange = 0x00000153, // + DB_PERF_SEL_DFSM_Flush_flushall_sampleratechange = 0x00000154, // + DB_PERF_SEL_DFSM_Flush_flushall_watchdog = 0x00000155, // + DB_PERF_SEL_DB_SC_quad_double_quad = 0x00000156, // + DB_PERF_SEL_SX_DB_quad_export_quads = 0x00000157, // + DB_PERF_SEL_SX_DB_quad_double_format = 0x00000158, // + DB_PERF_SEL_SX_DB_quad_fast_format = 0x00000159, // + DB_PERF_SEL_SX_DB_quad_slow_format = 0x0000015a, // + DB_PERF_SEL_quad_rd_sends_unc = 0x0000015b, // + DB_PERF_SEL_quad_rd_mi_stall_unc = 0x0000015c, // + DB_PERF_SEL_DFSM_OutputPunch = 0x0000015d, // + DB_PERF_SEL_DFSM_OutputPops = 0x0000015e, // + DB_PERF_SEL_DFSM_OutputFifo = 0x0000015f, // + DB_PERF_SEL_DFSM_StallOpmodeChange = 0x00000160, // + DB_PERF_SEL_DFSM_StallCAMFifoFull = 0x00000161, // + DB_PERF_SEL_DFSM_StallBypassFifoFull = 0x00000162, // + DB_PERF_SEL_DFSM_StallRetainedTileFifoFull = 0x00000163, // + DB_PERF_SEL_DFSM_StallControlFifoFull = 0x00000164, // + DB_PERF_SEL_DFSM_StallControlCountFull = 0x00000165, // + DB_PERF_SEL_DFSM_StallOverflowMaximum = 0x00000166, // + DB_PERF_SEL_DFSM_StallPopsStallOverflow = 0x00000167, // + DB_PERF_SEL_DFSM_StallPopsStallSelfStall = 0x00000168, // + DB_PERF_SEL_DFSM_StallCamSlotFlush = 0x00000169, // + DB_PERF_SEL_DFSM_StallOutput = 0x0000016a, // + DB_PERF_SEL_DFSM_WatchdogTrigger = 0x0000016b, // + DB_PERF_SEL_DFSM_StallOnPOPSStall = 0x0000016c, // + DB_PERF_SEL_SC_DB_tile_tiles_pipe0 = 0x0000016d, // + DB_PERF_SEL_SC_DB_tile_tiles_pipe1 = 0x0000016e, // + DB_PERF_SEL_SC_DB_quad_quads_pipe0 = 0x0000016f, // + DB_PERF_SEL_SC_DB_quad_quads_pipe1 = 0x00000170, // + DB_PERF_SEL_FG_LOB_FWDR_TIMEOUT_hits = 0x00000171, // + DB_PERF_SEL_noz_waiting_for_postz_done = 0x00000172, // + DB_PERF_SEL_DB_CB_lquad_quads_vrs_rate_1x1 = 0x00000173, // Number of coarse quads with 1x1 VRS rate or finer + DB_PERF_SEL_DB_CB_lquad_quads_vrs_rate_2x1 = 0x00000174, // Number of coarse quads with 2x2 VRS rate + DB_PERF_SEL_DB_CB_lquad_quads_vrs_rate_1x2 = 0x00000175, // Number of coarse quads with 1x2 VRS rate +} DB_PERFCOUNTER_SELECT; + +typedef enum EA_PERFCOUNTER_SELECT : unsigned int { + EA_PERF_Cycles = 0x00000000, // Count cycles. + EA_PERF_DRAM_Number_of_pending_banks = 0x00000001, // 1 | rdram | numbanksvld | Number of pending banks, saturates at 16 + EA_PERF_DRAM_Requests_0_per_client_group = 0x00000002, // 2 | rdram | (cligrp, 1'b1) & (4(req )) | Requests per client-group + EA_PERF_DRAM_Request_chains_per_client_group = 0x00000003, // 3 | rdram | (cligrp, 1'b1) & (4(reqeob )) | Request chains per client-group + EA_PERF_DRAM_Transaction_start_from_latency_sampler_0 = 0x00000004, // 4 | rdram | (3'b0, start0) | Transaction 'start' from latency sampler 0 + EA_PERF_DRAM_Transaction_end_from_latency_sampler_0 = 0x00000005, // 5 | rdram | (3'b0, end0 ) | Transaction 'end' from latency sampler 0 + EA_PERF_DRAM_Transaction_start_from_latency_sampler_1 = 0x00000006, // 6 | rdram | (3'b0, start1) | Transaction 'start' from latency sampler 1 + EA_PERF_DRAM_Transaction_end_from_latency_sampler_1 = 0x00000007, // 7 | rdram | (3'b0, end1 ) | Transaction 'end' from latency sampler 1 + EA_PERF_DRAM_Number_of_pending_banks_saturates_at_16 = 0x00000008, // 8 | wdram | numbanksvld | Number of pending banks, saturates at 16 + EA_PERF_DRAM_Requests_1_per_client_group = 0x00000009, // 9 | wdram | (cligrp, 1'b1) & (4(req )) | Requests per client-group + EA_PERF_WDRAM_Request_chains_per_client_group = 0x0000000a, // 10 | wdram | (cligrp, 1'b1) & (4(reqeob )) | Request chains per client-group + EA_PERF_WDRAM_Transaction_start_from_latency_sampler_0 = 0x0000000b, // 11 | wdram | (3'b0, start0) | Transaction 'start' from latency sampler 0 + EA_PERF_WDRAM_Transaction_end_from_latency_sampler_0 = 0x0000000c, // 12 | wdram | (3'b0, end0 ) | Transaction 'end' from latency sampler 0 + EA_PERF_WDRAM_Transaction_start_from_latency_sampler_1 = 0x0000000d, // 13 | wdram | (3'b0, start1) | Transaction 'start' from latency sampler 1 + EA_PERF_WDRAM_Transaction_end_from_latency_sampler_1 = 0x0000000e, // 14 | wdram | (3'b0, end1 ) | Transaction 'end' from latency sampler 1 + EA_PERF_RGMI_Number_of_pending_banks_saturates_at_16 = 0x0000000f, // 15 | rgmi | numbanksvld | Number of pending banks, saturates at 16 + EA_PERF_RGMI_Requests_per_client_group = 0x00000010, // 16 | rgmi | (cligrp, 1'b1) & (4(req )) | Requests per client-group + EA_PERF_RGMI_Request_chains_per_client_group = 0x00000011, // 17 | rgmi | (cligrp, 1'b1) & (4(reqeob )) | Request chains per client-group + EA_PERF_RGMI_Transaction_start_from_latency_sampler_0 = 0x00000012, // 18 | rgmi | (3'b0, start0) | Transaction 'start' from latency sampler 0 + EA_PERF_RGMI_Transaction_end_from_latency_sampler_0 = 0x00000013, // 19 | rgmi | (3'b0, end0 ) | Transaction 'end' from latency sampler 0 + EA_PERF_RGMI_Transaction_start_from_latency_sampler_1 = 0x00000014, // 20 | rgmi | (3'b0, start1) | Transaction 'start' from latency sampler 1 + EA_PERF_RGMI_Transaction_end_from_latency_sampler_1 = 0x00000015, // 21 | rgmi | (3'b0, end1 ) | Transaction 'end' from latency sampler 1 + EA_PERF_WGMI_Number_of_pending_banks_saturates_at_16 = 0x00000016, // 22 | wgmi | numbanksvld | Number of pending banks, saturates at 16 + EA_PERF_WGMI_Requests_per_client_group = 0x00000017, // 23 | wgmi | (cligrp, 1'b1) & (4(req )) | Requests per client-group + EA_PERF_WGMI_Request_chains_per_client_group = 0x00000018, // 24 | wgmi | (cligrp, 1'b1) & (4(reqeob )) | Request chains per client-group + EA_PERF_WGMI_Transaction_start_from_latency_sampler_0 = 0x00000019, // 25 | wgmi | (3'b0, start0) | Transaction 'start' from latency sampler 0 + EA_PERF_WGMI_Transaction_end_from_latency_sampler_0 = 0x0000001a, // 26 | wgmi | (3'b0, end0 ) | Transaction 'end' from latency sampler 0 + EA_PERF_WGMI_Transaction_start_from_latency_sampler_1 = 0x0000001b, // 27 | wgmi | (3'b0, start1) | Transaction 'start' from latency sampler 1 + EA_PERF_WGMI_Transaction_end_from_latency_sampler_1 = 0x0000001c, // 28 | wgmi | (3'b0, end1 ) | Transaction 'end' from latency sampler 1 + EA_PERF_RIO_Requests_per_client_group = 0x0000001d, // 29 | rio | (cligrp, 1'b1 ) & (4(req )) | Requests per client-group + EA_PERF_RIO_Sized_requests = 0x0000001e, // 30 | rio | (size_p1 ) & (4(req )) | Sized (in 32 byte increments) requests + EA_PERF_RIO_Client_group0_sized_requests = 0x0000001f, // 31 | rio | (size_p1 ) & (4(reqcligrp0)) | Client-group0 sized requests + EA_PERF_RIO_Client_group1_sized_requests = 0x00000020, // 32 | rio | (size_p1 ) & (4(reqcligrp1)) | Client-group1 sized requests + EA_PERF_RIO_Client_group2_sized_requests = 0x00000021, // 33 | rio | (size_p1 ) & (4(reqcligrp2)) | Client-group2 sized requests + EA_PERF_RIO_Client_group3_sized_requests = 0x00000022, // 34 | rio | (size_p1 ) & (4(reqcligrp3)) | Client-group3 sized requests + EA_PERF_RIO_Transaction_start_from_latency_sampler_0 = 0x00000023, // 35 | rio | (3'b0, start0) | Transaction 'start' from latency sampler 0 + EA_PERF_RIO_Transaction_end_from_latency_sampler_0 = 0x00000024, // 36 | rio | (3'b0, end0 ) | Transaction 'end' from latency sampler 0 + EA_PERF_RIO_Transaction_start_from_latency_sampler_1 = 0x00000025, // 37 | rio | (3'b0, start1) | Transaction 'start' from latency sampler 1 + EA_PERF_RIO_Transaction_end_from_latency_sampler_1 = 0x00000026, // 38 | rio | (3'b0, end1 ) | Transaction 'end' from latency sampler 1 + EA_PERF_WIO_Requests_per_client_group = 0x00000027, // 39 | wio | (cligrp, 1'b1 ) & (4(req )) | Requests per client-group + EA_PERF_WIO_Request_chains_per_client_group = 0x00000028, // 40 | wio | (cligrp, 1'b1 ) & (4(reqeob )) | Request chains per client-group + EA_PERF_WIO_Sized_requests = 0x00000029, // 41 | wio | (2'b0, size_p1) & (4(req )) | Sized (in 32 byte increments) requests + EA_PERF_WIO_Client_group0_sized_requests = 0x0000002a, // 42 | wio | (2'b0, size_p1) & (4(reqcligrp0)) | Client-group0 sized requests + EA_PERF_WIO_Client_group1_sized_requests = 0x0000002b, // 43 | wio | (2'b0, size_p1) & (4(reqcligrp1)) | Client-group1 sized requests + EA_PERF_WIO_Client_group2_sized_requests = 0x0000002c, // 44 | wio | (2'b0, size_p1) & (4(reqcligrp2)) | Client-group2 sized requests + EA_PERF_WIO_Client_group3_sized_requests = 0x0000002d, // 45 | wio | (2'b0, size_p1) & (4(reqcligrp3)) | Client-group3 sized requests + EA_PERF_WIO_Transaction_start_from_latency_sampler_0 = 0x0000002e, // 46 | wio | (3'b0, start0) | Transaction 'start' from latency sampler 0 + EA_PERF_WIO_Transaction_end_from_latency_sampler_0 = 0x0000002f, // 47 | wio | (3'b0, end0 ) | Transaction 'end' from latency sampler 0 + EA_PERF_WIO_Transaction_start_from_latency_sampler_1 = 0x00000030, // 48 | wio | (3'b0, start1) | Transaction 'start' from latency sampler 1 + EA_PERF_WIO_Transaction_end_from_latency_sampler_1 = 0x00000031, // 49 | wio | (3'b0, end1 ) | Transaction 'end' from latency sampler 1 + EA_PERF_SARB_Requests_per_virtual_channel = 0x00000032, // 50 | sarb | (vc, 1'b1) & (4(req )) | Requests per virtual channel + EA_PERF_SARB_DRAM_request_per_virtual_channel = 0x00000033, // 51 | sarb | (vc, 1'b1) & (4(reqdram)) | DRAM request per virtual channel + EA_PERF_SARB_GMI_request_per_virtual_channel = 0x00000034, // 52 | sarb | (vc, 1'b1) & (4(reqgmi )) | GMI request per virtual channel + EA_PERF_SARB_IO_request_per_virtual_channel = 0x00000035, // 53 | sarb | (vc, 1'b1) & (4(reqio )) | I/O request per virtual channel + EA_PERF_SARB_Sized_requests = 0x00000036, // 54 | sarb | (size_p1 ) & (4(req )) | Sized (in 32 byte increments) requests + EA_PERF_SARB_DRAM_sized_requests = 0x00000037, // 55 | sarb | (size_p1 ) & (4(reqdram)) | DRAM sized (in 32 byte increments) requests + EA_PERF_SARB_GMI_sized_requests = 0x00000038, // 56 | sarb | (size_p1 ) & (4(reqgmi )) | GMI sized (in 32 byte increments) requests + EA_PERF_SARB_IO_sized_requests = 0x00000039, // 57 | sarb | (size_p1 ) & (4(reqio )) | I/O sized (in 32 byte increments) requests + EA_PERF_SARB_Transaction_start_from_latency_sampler_0 = 0x0000003a, // 58 | sarb | (3'b0, start0) | Transaction 'start' from latency sampler 0 + EA_PERF_SARB_Transaction_end_from_latency_sampler_0 = 0x0000003b, // 59 | sarb | (3'b0, end0 ) | Transaction 'end' from latency sampler 0 + EA_PERF_SARB_Transaction_start_from_latency_sampler_1 = 0x0000003c, // 60 | sarb | (3'b0, start1) | Transaction 'start' from latency sampler 1 + EA_PERF_SARB_Transaction_end_from_latency_sampler_1 = 0x0000003d, // 61 | sarb | (3'b0, end1 ) | Transaction 'end' from latency sampler 1 + EA_PERF_SARB_Busy = 0x0000003e, // 62 | sarb | (3'b0, valid_ready ) | Busy + EA_PERF_SARB_Stalled = 0x0000003f, // 63 | sarb | (3'b0, valid_readyb ) | Stalled + EA_PERF_SARB_Starving = 0x00000040, // 64 | sarb | (3'b0, validb_ready ) | Starving + EA_PERF_SARB_Idling = 0x00000041, // 65 | sarb | (3'b0, validb_readyb) | Idling + EA_PERF_RRET_Read_returns = 0x00000042, // 66 | rret | (3'b0, ret_vld) | Read returns + EA_PERF_WRET_Write_returns = 0x00000043, // 67 | wret | (3'b0, ret_vld) | Write returns + EA_PERF_PR_Probe_invalidates = 0x00000044, // 68 | prb | (3'b0, invld_req) | Probe-invalidates + EA_PERF_MAM_Eviction_from_the_Access_memory_coalescing_array = 0x00000045, // 69 | mam | (3'b0, aram_fa_evict) | Eviction from the Access memory coalescing array + EA_PERF_MAM_Request_considered_valid_by_Access_RAM_sub_module = 0x00000046, // 70 | mam | (3'b0, aram_req_vld) | Request considered valid by Access RAM sub-module + EA_PERF_MAM_Dirty_bit_query_start = 0x00000047, // 71 | mam | (3'b0, dqry_start) | Dirty-bit query 'start' + EA_PERF_MAM_Dirty_bit_query_end = 0x00000048, // 72 | mam | (3'b0, dqry_end) | Dirty-bit query 'end' + EA_PERF_MAM_Interrupts_issued_by_MAM = 0x00000049, // 73 | mam | (3'b0, interrupt) | Interrupts issued by MAM + EA_PERF_MAM_Requests_that_are_considered_valid_by_ALOG = 0x0000004a, // 74 | mam | (3'b0, alog_req_vld) | Requests that are considered valid by ALOG + EA_PERF_MAM_Requests_making_to_ALOG_cache = 0x0000004b, // 75 | mam | (3'b0, alog_cache_req) | Requests making to ALOG cache + EA_PERF_MAM_Requests_hitting_an_entry_in_ALOG_cache = 0x0000004c, // 76 | mam | (3'b0, alog_cache_hit) | Requests hitting an entry in ALOG cache + EA_PERF_RDRAM_Sized_requests = 0x0000004d, // 77 | rdram | (size_p1) & (4(req )) | Sized (in 32 byte increments) requests + EA_PERF_WDRAM_Sized_requests = 0x0000004e, // 78 | wdram | (size_p1) & (4(req )) | Sized (in 32 byte increments) requests + EA_PERF_RGMI_Sized_requests = 0x0000004f, // 79 | rgmi | (size_p1) & (4(req )) | Sized (in 32 byte increments) requests + EA_PERF_WGMI_Sized_requests = 0x00000050, // 80 | wgmi | (size_p1) & (4(req )) | Sized (in 32 byte increments) requests + EA_PERF_SARB_DRAM_read_write_switch = 0x00000051, // 81 | sarb | (3'b0, rwswitch_dram) | DRAM read/write switch + EA_PERF_SARB_GMI_read_write_switch = 0x00000052, // 82 | sarb | (3'b0, rwswitch_gmi ) | GMI read/write switch + EA_PERF_RDRAM_Request_chains_per_burst_length = 0x00000053, // 83 | rdram | (burst_length) & (4(reqeob )) | Request chains per burst length + EA_PERF_WDRAM_Request_chains_per_burst_length = 0x00000054, // 84 | wdram | (burst_length) & (4(reqeob )) | Request chains per burst length + EA_PERF_RGMI_Request_chains_per_burst_length = 0x00000055, // 85 | rgmi | (burst_length) & (4(reqeob )) | Request chains per burst length + EA_PERF_WGMI_Request_chains_per_burst_length = 0x00000056, // 86 | wgmi | (burst_length) & (4(reqeob )) | Request chains per burst length + EA_PERF_MAM_Eviction_from_the_DBIT_memory_coalescing_array = 0x00000057, // 87 | mam | (3'b0, dbit_fa_evict) | Eviction from the DBIT memory coalescing array + EA_PERF_MAM_Request_considered_valid_by_DBIT_Memory_sub_module = 0x00000058, // 88 | mam | (3'b0, dbit_req_vld) | Request considered valid by DBIT Memory sub-module + EA_PERF_SARB_Coherent_sized_requests = 0x00000059, // 89 | sarb | (size_p1 ) & (4(reqcoherent )) | Coherent sized (in 32 byte increments) requests +} EA_PERFCOUNTER_SELECT; + +typedef enum GCR_PERFCOUNTER_SELECT : unsigned int { + GCR_PERF_SEL_NONE = 0x00000000, // Count nothing + GCR_PERF_SEL_SDMA0_ALL_REQ = 0x00000001, // SDMA0 to all cache requests + GCR_PERF_SEL_SDMA0_GL2_RANGE_REQ = 0x00000002, // SDMA0 to GL2 range requests + GCR_PERF_SEL_SDMA0_GL2_RANGE_LT16K_REQ = 0x00000003, // SDMA0 to GL2 range (<16K) requests + GCR_PERF_SEL_SDMA0_GL2_RANGE_16K_REQ = 0x00000004, // SDMA0 to GL2 range (16K) requests + GCR_PERF_SEL_SDMA0_GL2_RANGE_GT16K_REQ = 0x00000005, // SDMA0 to GL2 range (>16K) requests + GCR_PERF_SEL_SDMA0_GL2_ALL_REQ = 0x00000006, // SDMA0 to GL2 all requests + GCR_PERF_SEL_SDMA0_GL1_RANGE_REQ = 0x00000007, // SDMA0 to GL1 range requests + GCR_PERF_SEL_SDMA0_GL1_RANGE_LT16K_REQ = 0x00000008, // SDMA0 to GL1 range (<16K) requests + GCR_PERF_SEL_SDMA0_GL1_RANGE_16K_REQ = 0x00000009, // SDMA0 to GL1 range (16K) requests + GCR_PERF_SEL_SDMA0_GL1_RANGE_GT16K_REQ = 0x0000000a, // SDMA0 to GL1 range (>16K) requests + GCR_PERF_SEL_SDMA0_GL1_ALL_REQ = 0x0000000b, // SDMA0 to GL1 all requests + GCR_PERF_SEL_SDMA0_METADATA_REQ = 0x0000000c, // SDMA0 to GL2 Metadata cache requests + GCR_PERF_SEL_SDMA0_SQC_DATA_REQ = 0x0000000d, // SDMA0 to SQC data requests + GCR_PERF_SEL_SDMA0_SQC_INST_REQ = 0x0000000e, // SDMA0 to SQC inst requests + GCR_PERF_SEL_SDMA0_TCP_REQ = 0x0000000f, // SDMA0 to TCP requests + GCR_PERF_SEL_SDMA0_TCP_TLB_SHOOTDOWN_REQ = 0x00000010, // SDMA0 to TCP tlb shootdown requests + GCR_PERF_SEL_SDMA1_ALL_REQ = 0x00000011, // SDMA1 to all cache requests + GCR_PERF_SEL_SDMA1_GL2_RANGE_REQ = 0x00000012, // SDMA1 to GL2 range requests + GCR_PERF_SEL_SDMA1_GL2_RANGE_LT16K_REQ = 0x00000013, // SDMA1 to GL2 range (<16K) requests + GCR_PERF_SEL_SDMA1_GL2_RANGE_16K_REQ = 0x00000014, // SDMA1 to GL2 range (16K) requests + GCR_PERF_SEL_SDMA1_GL2_RANGE_GT16K_REQ = 0x00000015, // SDMA1 to GL2 range (>16K) requests + GCR_PERF_SEL_SDMA1_GL2_ALL_REQ = 0x00000016, // SDMA1 to GL2 all requests + GCR_PERF_SEL_SDMA1_GL1_RANGE_REQ = 0x00000017, // SDMA1 to GL1 range requests + GCR_PERF_SEL_SDMA1_GL1_RANGE_LT16K_REQ = 0x00000018, // SDMA1 to GL1 range (<16K) requests + GCR_PERF_SEL_SDMA1_GL1_RANGE_16K_REQ = 0x00000019, // SDMA1 to GL1 range (16K) requests + GCR_PERF_SEL_SDMA1_GL1_RANGE_GT16K_REQ = 0x0000001a, // SDMA1 to GL1 range (>16K) requests + GCR_PERF_SEL_SDMA1_GL1_ALL_REQ = 0x0000001b, // SDMA1 to GL1 all requests + GCR_PERF_SEL_SDMA1_METADATA_REQ = 0x0000001c, // SDMA1 to GL2 Metadata cache requests + GCR_PERF_SEL_SDMA1_SQC_DATA_REQ = 0x0000001d, // SDMA1 to SQC data requests + GCR_PERF_SEL_SDMA1_SQC_INST_REQ = 0x0000001e, // SDMA1 to SQC inst requests + GCR_PERF_SEL_SDMA1_TCP_REQ = 0x0000001f, // SDMA1 to TCP requests + GCR_PERF_SEL_SDMA1_TCP_TLB_SHOOTDOWN_REQ = 0x00000020, // SDMA1 to TCP tlb shootdown requests + GCR_PERF_SEL_CPC_ALL_REQ = 0x00000021, // CPC to all cache requests + GCR_PERF_SEL_CPC_GL2_RANGE_REQ = 0x00000022, // CPC to GL2 range requests + GCR_PERF_SEL_CPC_GL2_RANGE_LT16K_REQ = 0x00000023, // CPC to GL2 range (<16K) requests + GCR_PERF_SEL_CPC_GL2_RANGE_16K_REQ = 0x00000024, // CPC to GL2 range (16K) requests + GCR_PERF_SEL_CPC_GL2_RANGE_GT16K_REQ = 0x00000025, // CPC to GL2 range (>16K) requests + GCR_PERF_SEL_CPC_GL2_ALL_REQ = 0x00000026, // CPC to GL2 all requests + GCR_PERF_SEL_CPC_GL1_RANGE_REQ = 0x00000027, // CPC to GL1 range requests + GCR_PERF_SEL_CPC_GL1_RANGE_LT16K_REQ = 0x00000028, // CPC to GL1 range (<16K) requests + GCR_PERF_SEL_CPC_GL1_RANGE_16K_REQ = 0x00000029, // CPC to GL1 range (16K) requests + GCR_PERF_SEL_CPC_GL1_RANGE_GT16K_REQ = 0x0000002a, // CPC to GL1 range (>16K) requests + GCR_PERF_SEL_CPC_GL1_ALL_REQ = 0x0000002b, // CPC to GL1 all requests + GCR_PERF_SEL_CPC_METADATA_REQ = 0x0000002c, // CPG to GL2 Metadata cache requests + GCR_PERF_SEL_CPC_SQC_DATA_REQ = 0x0000002d, // CPC to SQC data requests + GCR_PERF_SEL_CPC_SQC_INST_REQ = 0x0000002e, // CPC to SQC inst requests + GCR_PERF_SEL_CPC_TCP_REQ = 0x0000002f, // CPC to TCP requests + GCR_PERF_SEL_CPC_TCP_TLB_SHOOTDOWN_REQ = 0x00000030, // CPC to TCP tlb shootdown requests + GCR_PERF_SEL_CPG_ALL_REQ = 0x00000031, // CPG to all cache requests + GCR_PERF_SEL_CPG_GL2_RANGE_REQ = 0x00000032, // CPG to GL2 range requests + GCR_PERF_SEL_CPG_GL2_RANGE_LT16K_REQ = 0x00000033, // CPG to GL2 range (<16K) requests + GCR_PERF_SEL_CPG_GL2_RANGE_16K_REQ = 0x00000034, // CPG to GL2 range (16K) requests + GCR_PERF_SEL_CPG_GL2_RANGE_GT16K_REQ = 0x00000035, // CPG to GL2 range (>16K) requests + GCR_PERF_SEL_CPG_GL2_ALL_REQ = 0x00000036, // CPG to GL2 all requests + GCR_PERF_SEL_CPG_GL1_RANGE_REQ = 0x00000037, // CPG to GL1 range requests + GCR_PERF_SEL_CPG_GL1_RANGE_LT16K_REQ = 0x00000038, // CPG to GL1 range (<16K) requests + GCR_PERF_SEL_CPG_GL1_RANGE_16K_REQ = 0x00000039, // CPG to GL1 range (16K) requests + GCR_PERF_SEL_CPG_GL1_RANGE_GT16K_REQ = 0x0000003a, // CPG to GL1 range (>16K) requests + GCR_PERF_SEL_CPG_GL1_ALL_REQ = 0x0000003b, // CPG to GL1 all requests + GCR_PERF_SEL_CPG_METADATA_REQ = 0x0000003c, // CPG to GL2 Metadata cache requests + GCR_PERF_SEL_CPG_SQC_DATA_REQ = 0x0000003d, // CPG to SQC data requests + GCR_PERF_SEL_CPG_SQC_INST_REQ = 0x0000003e, // CPG to SQC inst requests + GCR_PERF_SEL_CPG_TCP_REQ = 0x0000003f, // CPG to TCP requests + GCR_PERF_SEL_CPG_TCP_TLB_SHOOTDOWN_REQ = 0x00000040, // CPG to TCP tlb shootdown requests + GCR_PERF_SEL_CPF_ALL_REQ = 0x00000041, // CPF to all cache requests + GCR_PERF_SEL_CPF_GL2_RANGE_REQ = 0x00000042, // CPF to GL2 range requests + GCR_PERF_SEL_CPF_GL2_RANGE_LT16K_REQ = 0x00000043, // CPF to GL2 range (<16K) requests + GCR_PERF_SEL_CPF_GL2_RANGE_16K_REQ = 0x00000044, // CPF to GL2 range (16K) requests + GCR_PERF_SEL_CPF_GL2_RANGE_GT16K_REQ = 0x00000045, // CPF to GL2 range (>16K) requests + GCR_PERF_SEL_CPF_GL2_ALL_REQ = 0x00000046, // CPF to GL2 all requests + GCR_PERF_SEL_CPF_GL1_RANGE_REQ = 0x00000047, // CPF to GL1 range requests + GCR_PERF_SEL_CPF_GL1_RANGE_LT16K_REQ = 0x00000048, // CPF to GL1 range (<16K) requests + GCR_PERF_SEL_CPF_GL1_RANGE_16K_REQ = 0x00000049, // CPF to GL1 range (16K) requests + GCR_PERF_SEL_CPF_GL1_RANGE_GT16K_REQ = 0x0000004a, // CPF to GL1 range (>16K) requests + GCR_PERF_SEL_CPF_GL1_ALL_REQ = 0x0000004b, // CPF to GL1 all requests + GCR_PERF_SEL_CPF_METADATA_REQ = 0x0000004c, // CPF to GL2 Metadata cache requests + GCR_PERF_SEL_CPF_SQC_DATA_REQ = 0x0000004d, // CPF to SQC data requests + GCR_PERF_SEL_CPF_SQC_INST_REQ = 0x0000004e, // CPF to SQC inst requests + GCR_PERF_SEL_CPF_TCP_REQ = 0x0000004f, // CPF to TCP requests + GCR_PERF_SEL_CPF_TCP_TLB_SHOOTDOWN_REQ = 0x00000050, // CPF to TCP tlb shootdown requests + GCR_PERF_SEL_VIRT_REQ = 0x00000051, // GCR to clients virtual/all requests + GCR_PERF_SEL_PHY_REQ = 0x00000052, // GCR to clients physical/all requests + GCR_PERF_SEL_TLB_SHOOTDOWN_HEAVY_REQ = 0x00000053, // GCR to TCP tlb shootdown (heavy) requests + GCR_PERF_SEL_TLB_SHOOTDOWN_LIGHT_REQ = 0x00000054, // GCR to TCP tlb shootdown (light) requests + GCR_PERF_SEL_ALL_REQ = 0x00000055, // GCR to clients physical/virtual/all requests + GCR_PERF_SEL_CLK_FOR_PHY_OUTSTANDING_REQ = 0x00000056, // Count of outstanding clocks for all current physical outstanding requests + GCR_PERF_SEL_CLK_FOR_VIRT_OUTSTANDING_REQ = 0x00000057, // Count of outstanding clocks for all current virtual outstanding requests + GCR_PERF_SEL_CLK_FOR_ALL_OUTSTANDING_REQ = 0x00000058, // Count of outstanding clocks for all current outstanding requests + GCR_PERF_SEL_UTCL2_REQ = 0x00000059, // GCR to UTCL2 requests + GCR_PERF_SEL_UTCL2_RET = 0x0000005a, // UTCL2 to GCR returns + GCR_PERF_SEL_UTCL2_OUT_OF_CREDIT_EVENT = 0x0000005b, // GCR to UTCL2 out of credit events + GCR_PERF_SEL_UTCL2_INFLIGHT_REQ = 0x0000005c, // Count of GCR/UTCL2 inflight requests outstanding cycles + GCR_PERF_SEL_UTCL2_FILTERED_RET = 0x0000005d, // UTCL2 to GCR filtered by big page returns + GCR_PERF_SEL_SDMA2_ALL_REQ = 0x0000005e, // SDMA2 to all cache requests + GCR_PERF_SEL_SDMA2_GL2_RANGE_REQ = 0x0000005f, // SDMA2 to GL2 range requests + GCR_PERF_SEL_SDMA2_GL2_RANGE_LT16K_REQ = 0x00000060, // SDMA2 to GL2 range (<16K) requests + GCR_PERF_SEL_SDMA2_GL2_RANGE_16K_REQ = 0x00000061, // SDMA2 to GL2 range (16K) requests + GCR_PERF_SEL_SDMA2_GL2_RANGE_GT16K_REQ = 0x00000062, // SDMA2 to GL2 range (>16K) requests + GCR_PERF_SEL_SDMA2_GL2_ALL_REQ = 0x00000063, // SDMA2 to GL2 all requests + GCR_PERF_SEL_SDMA2_GL1_RANGE_REQ = 0x00000064, // SDMA2 to GL1 range requests + GCR_PERF_SEL_SDMA2_GL1_RANGE_LT16K_REQ = 0x00000065, // SDMA2 to GL1 range (<16K) requests + GCR_PERF_SEL_SDMA2_GL1_RANGE_16K_REQ = 0x00000066, // SDMA2 to GL1 range (16K) requests + GCR_PERF_SEL_SDMA2_GL1_RANGE_GT16K_REQ = 0x00000067, // SDMA2 to GL1 range (>16K) requests + GCR_PERF_SEL_SDMA2_GL1_ALL_REQ = 0x00000068, // SDMA2 to GL1 all requests + GCR_PERF_SEL_SDMA2_METADATA_REQ = 0x00000069, // SDMA2 to GL2 Metadata cache requests + GCR_PERF_SEL_SDMA2_SQC_DATA_REQ = 0x0000006a, // SDMA2 to SQC data requests + GCR_PERF_SEL_SDMA2_SQC_INST_REQ = 0x0000006b, // SDMA2 to SQC inst requests + GCR_PERF_SEL_SDMA2_TCP_REQ = 0x0000006c, // SDMA2 to TCP requests + GCR_PERF_SEL_SDMA2_TCP_TLB_SHOOTDOWN_REQ = 0x0000006d, // SDMA2 to TCP tlb shootdown requests + GCR_PERF_SEL_SDMA3_ALL_REQ = 0x0000006e, // SDMA3 to all cache requests + GCR_PERF_SEL_SDMA3_GL2_RANGE_REQ = 0x0000006f, // SDMA3 to GL2 range requests + GCR_PERF_SEL_SDMA3_GL2_RANGE_LT16K_REQ = 0x00000070, // SDMA3 to GL2 range (<16K) requests + GCR_PERF_SEL_SDMA3_GL2_RANGE_16K_REQ = 0x00000071, // SDMA3 to GL2 range (16K) requests + GCR_PERF_SEL_SDMA3_GL2_RANGE_GT16K_REQ = 0x00000072, // SDMA3 to GL2 range (>16K) requests + GCR_PERF_SEL_SDMA3_GL2_ALL_REQ = 0x00000073, // SDMA3 to GL2 all requests + GCR_PERF_SEL_SDMA3_GL1_RANGE_REQ = 0x00000074, // SDMA3 to GL1 range requests + GCR_PERF_SEL_SDMA3_GL1_RANGE_LT16K_REQ = 0x00000075, // SDMA3 to GL1 range (<16K) requests + GCR_PERF_SEL_SDMA3_GL1_RANGE_16K_REQ = 0x00000076, // SDMA3 to GL1 range (16K) requests + GCR_PERF_SEL_SDMA3_GL1_RANGE_GT16K_REQ = 0x00000077, // SDMA3 to GL1 range (>16K) requests + GCR_PERF_SEL_SDMA3_GL1_ALL_REQ = 0x00000078, // SDMA3 to GL1 all requests + GCR_PERF_SEL_SDMA3_METADATA_REQ = 0x00000079, // SDMA3 to GL2 Metadata cache requests + GCR_PERF_SEL_SDMA3_SQC_DATA_REQ = 0x0000007a, // SDMA3 to SQC data requests + GCR_PERF_SEL_SDMA3_SQC_INST_REQ = 0x0000007b, // SDMA3 to SQC inst requests + GCR_PERF_SEL_SDMA3_TCP_REQ = 0x0000007c, // SDMA3 to TCP requests + GCR_PERF_SEL_SDMA3_TCP_TLB_SHOOTDOWN_REQ = 0x0000007d, // SDMA3 to TCP tlb shootdown requests + GCR_PERF_SEL_PIO_ALL_REQ = 0x0000007e, // PIO to all cache requests + GCR_PERF_SEL_PIO_GL2_RANGE_REQ = 0x0000007f, // PIO to GL2 range requests + GCR_PERF_SEL_PIO_GL2_RANGE_LT16K_REQ = 0x00000080, // PIO to GL2 range (<16K) requests + GCR_PERF_SEL_PIO_GL2_RANGE_16K_REQ = 0x00000081, // PIO to GL2 range (16K) requests + GCR_PERF_SEL_PIO_GL2_RANGE_GT16K_REQ = 0x00000082, // PIO to GL2 range (>16K) requests + GCR_PERF_SEL_PIO_GL2_ALL_REQ = 0x00000083, // PIO to GL2 all requests + GCR_PERF_SEL_PIO_GL1_RANGE_REQ = 0x00000084, // PIO to GL1 range requests + GCR_PERF_SEL_PIO_GL1_RANGE_LT16K_REQ = 0x00000085, // PIO to GL1 range (<16K) requests + GCR_PERF_SEL_PIO_GL1_RANGE_16K_REQ = 0x00000086, // PIO to GL1 range (16K) requests + GCR_PERF_SEL_PIO_GL1_RANGE_GT16K_REQ = 0x00000087, // PIO to GL1 range (>16K) requests + GCR_PERF_SEL_PIO_GL1_ALL_REQ = 0x00000088, // PIO to GL1 all requests + GCR_PERF_SEL_PIO_METADATA_REQ = 0x00000089, // PIO to GL2 Metadata cache requests + GCR_PERF_SEL_PIO_SQC_DATA_REQ = 0x0000008a, // PIO to SQC data requests + GCR_PERF_SEL_PIO_SQC_INST_REQ = 0x0000008b, // PIO to SQC inst requests + GCR_PERF_SEL_PIO_TCP_REQ = 0x0000008c, // PIO to TCP requests + GCR_PERF_SEL_PIO_TCP_TLB_SHOOTDOWN_REQ = 0x0000008d, // PIO to TCP tlb shootdown requests +} GCR_PERFCOUNTER_SELECT; + +typedef enum GDS_PERFCOUNTER_SELECT : unsigned int { + GDS_PERF_SEL_DS_ADDR_CONFL = 0x00000000, // : Number of conflicting addresses in DS memory + GDS_PERF_SEL_DS_BANK_CONFL = 0x00000001, // : Number of conflicting banks in DS memory + GDS_PERF_SEL_WBUF_FLUSH = 0x00000002, // : Number of times the RBIU write buffer is flushed + GDS_PERF_SEL_WR_COMP = 0x00000003, // : Number of times a WRITE_COMPLETE is put in write buffer + GDS_PERF_SEL_WBUF_WR = 0x00000004, // : Number of times the RBIU writes to buffer + GDS_PERF_SEL_RBUF_HIT = 0x00000005, // : Number of times an RBIU read hits in the buffer + GDS_PERF_SEL_RBUF_MISS = 0x00000006, // : Number of times an RBIU read misses the buffer + GDS_PERF_SEL_SE0_SH0_NORET = 0x00000007, // : Number of commands that do not return data + GDS_PERF_SEL_SE0_SH0_RET = 0x00000008, // : Number of commands that do return data + GDS_PERF_SEL_SE0_SH0_ORD_CNT = 0x00000009, // : Number of ordered count operations + GDS_PERF_SEL_SE0_SH0_2COMP_REQ = 0x0000000a, // : Number of commands that return two components + GDS_PERF_SEL_SE0_SH0_ORD_WAVE_VALID = 0x0000000b, // : Number of valid wave ID's processed by ordered append + GDS_PERF_SEL_SE0_SH0_GDS_DATA_VALID = 0x0000000c, // : Number of valid write enables from the data bus + GDS_PERF_SEL_SE0_SH0_GDS_STALL_BY_ORD = 0x0000000d, // : Number of cycles GDS data is stalled due to Ordered count data + GDS_PERF_SEL_SE0_SH0_GDS_WR_OP = 0x0000000e, // : Number of GDS Write operations + GDS_PERF_SEL_SE0_SH0_GDS_RD_OP = 0x0000000f, // : Number of GDS Read operations + GDS_PERF_SEL_SE0_SH0_GDS_ATOM_OP = 0x00000010, // : Number of GDS Atomic operations + GDS_PERF_SEL_SE0_SH0_GDS_REL_OP = 0x00000011, // : Number of GDS Relative operations + GDS_PERF_SEL_SE0_SH0_GDS_CMPXCH_OP = 0x00000012, // : Number of GDS Compare or Exchange operations + GDS_PERF_SEL_SE0_SH0_GDS_BYTE_OP = 0x00000013, // : Number of GDS byte operations + GDS_PERF_SEL_SE0_SH0_GDS_SHORT_OP = 0x00000014, // : Number of GDS short operations + GDS_PERF_SEL_SE0_SH1_NORET = 0x00000015, // : Number of commands that do not return data + GDS_PERF_SEL_SE0_SH1_RET = 0x00000016, // : Number of commands that do return data + GDS_PERF_SEL_SE0_SH1_ORD_CNT = 0x00000017, // : Number of ordered count operations + GDS_PERF_SEL_SE0_SH1_2COMP_REQ = 0x00000018, // : Number of commands that return two components + GDS_PERF_SEL_SE0_SH1_ORD_WAVE_VALID = 0x00000019, // : Number of valid wave ID's processed by ordered append + GDS_PERF_SEL_SE0_SH1_GDS_DATA_VALID = 0x0000001a, // : Number of valid write enables from the data bus + GDS_PERF_SEL_SE0_SH1_GDS_STALL_BY_ORD = 0x0000001b, // : Number of cycles GDS data is stalled due to Ordered count data + GDS_PERF_SEL_SE0_SH1_GDS_WR_OP = 0x0000001c, // : Number of GDS Write operations + GDS_PERF_SEL_SE0_SH1_GDS_RD_OP = 0x0000001d, // : Number of GDS Read operations + GDS_PERF_SEL_SE0_SH1_GDS_ATOM_OP = 0x0000001e, // : Number of GDS Atomic operations + GDS_PERF_SEL_SE0_SH1_GDS_REL_OP = 0x0000001f, // : Number of GDS Relative operations + GDS_PERF_SEL_SE0_SH1_GDS_CMPXCH_OP = 0x00000020, // : Number of GDS Compare or Exchange operations + GDS_PERF_SEL_SE0_SH1_GDS_BYTE_OP = 0x00000021, // : Number of GDS byte operations + GDS_PERF_SEL_SE0_SH1_GDS_SHORT_OP = 0x00000022, // : Number of GDS short operations + GDS_PERF_SEL_SE1_SH0_NORET = 0x00000023, // : Number of commands that do not return data + GDS_PERF_SEL_SE1_SH0_RET = 0x00000024, // : Number of commands that do return data + GDS_PERF_SEL_SE1_SH0_ORD_CNT = 0x00000025, // : Number of ordered count operations + GDS_PERF_SEL_SE1_SH0_2COMP_REQ = 0x00000026, // : Number of commands that return two components + GDS_PERF_SEL_SE1_SH0_ORD_WAVE_VALID = 0x00000027, // : Number of valid wave ID's processed by ordered append + GDS_PERF_SEL_SE1_SH0_GDS_DATA_VALID = 0x00000028, // : Number of valid write enables from the data bus + GDS_PERF_SEL_SE1_SH0_GDS_STALL_BY_ORD = 0x00000029, // : Number of cycles GDS data is stalled due to Ordered count data + GDS_PERF_SEL_SE1_SH0_GDS_WR_OP = 0x0000002a, // : Number of GDS Write operations + GDS_PERF_SEL_SE1_SH0_GDS_RD_OP = 0x0000002b, // : Number of GDS Read operations + GDS_PERF_SEL_SE1_SH0_GDS_ATOM_OP = 0x0000002c, // : Number of GDS Atomic operations + GDS_PERF_SEL_SE1_SH0_GDS_REL_OP = 0x0000002d, // : Number of GDS Relative operations + GDS_PERF_SEL_SE1_SH0_GDS_CMPXCH_OP = 0x0000002e, // : Number of GDS Compare or Exchange operations + GDS_PERF_SEL_SE1_SH0_GDS_BYTE_OP = 0x0000002f, // : Number of GDS byte operations + GDS_PERF_SEL_SE1_SH0_GDS_SHORT_OP = 0x00000030, // : Number of GDS short operations + GDS_PERF_SEL_SE1_SH1_NORET = 0x00000031, // : Number of commands that do not return data + GDS_PERF_SEL_SE1_SH1_RET = 0x00000032, // : Number of commands that do return data + GDS_PERF_SEL_SE1_SH1_ORD_CNT = 0x00000033, // : Number of ordered count operations + GDS_PERF_SEL_SE1_SH1_2COMP_REQ = 0x00000034, // : Number of commands that return two components + GDS_PERF_SEL_SE1_SH1_ORD_WAVE_VALID = 0x00000035, // : Number of valid wave ID's processed by ordered append + GDS_PERF_SEL_SE1_SH1_GDS_DATA_VALID = 0x00000036, // : Number of valid write enables from the data bus + GDS_PERF_SEL_SE1_SH1_GDS_STALL_BY_ORD = 0x00000037, // : Number of cycles GDS data is stalled due to Ordered count data + GDS_PERF_SEL_SE1_SH1_GDS_WR_OP = 0x00000038, // : Number of GDS Write operations + GDS_PERF_SEL_SE1_SH1_GDS_RD_OP = 0x00000039, // : Number of GDS Read operations + GDS_PERF_SEL_SE1_SH1_GDS_ATOM_OP = 0x0000003a, // : Number of GDS Atomic operations + GDS_PERF_SEL_SE1_SH1_GDS_REL_OP = 0x0000003b, // : Number of GDS Relative operations + GDS_PERF_SEL_SE1_SH1_GDS_CMPXCH_OP = 0x0000003c, // : Number of GDS Compare or Exchange operations + GDS_PERF_SEL_SE1_SH1_GDS_BYTE_OP = 0x0000003d, // : Number of GDS byte operations + GDS_PERF_SEL_SE1_SH1_GDS_SHORT_OP = 0x0000003e, // : Number of GDS short operations + GDS_PERF_SEL_SE2_SH0_NORET = 0x0000003f, // : Number of commands that do not return data + GDS_PERF_SEL_SE2_SH0_RET = 0x00000040, // : Number of commands that do return data + GDS_PERF_SEL_SE2_SH0_ORD_CNT = 0x00000041, // : Number of ordered count operations + GDS_PERF_SEL_SE2_SH0_2COMP_REQ = 0x00000042, // : Number of commands that return two components + GDS_PERF_SEL_SE2_SH0_ORD_WAVE_VALID = 0x00000043, // : Number of valid wave ID's processed by ordered append + GDS_PERF_SEL_SE2_SH0_GDS_DATA_VALID = 0x00000044, // : Number of valid write enables from the data bus + GDS_PERF_SEL_SE2_SH0_GDS_STALL_BY_ORD = 0x00000045, // : Number of cycles GDS data is stalled due to Ordered count data + GDS_PERF_SEL_SE2_SH0_GDS_WR_OP = 0x00000046, // : Number of GDS Write operations + GDS_PERF_SEL_SE2_SH0_GDS_RD_OP = 0x00000047, // : Number of GDS Read operations + GDS_PERF_SEL_SE2_SH0_GDS_ATOM_OP = 0x00000048, // : Number of GDS Atomic operations + GDS_PERF_SEL_SE2_SH0_GDS_REL_OP = 0x00000049, // : Number of GDS Relative operations + GDS_PERF_SEL_SE2_SH0_GDS_CMPXCH_OP = 0x0000004a, // : Number of GDS Compare or Exchange operations + GDS_PERF_SEL_SE2_SH0_GDS_BYTE_OP = 0x0000004b, // : Number of GDS byte operations + GDS_PERF_SEL_SE2_SH0_GDS_SHORT_OP = 0x0000004c, // : Number of GDS short operations + GDS_PERF_SEL_SE2_SH1_NORET = 0x0000004d, // : Number of commands that do not return data + GDS_PERF_SEL_SE2_SH1_RET = 0x0000004e, // : Number of commands that do return data + GDS_PERF_SEL_SE2_SH1_ORD_CNT = 0x0000004f, // : Number of ordered count operations + GDS_PERF_SEL_SE2_SH1_2COMP_REQ = 0x00000050, // : Number of commands that return two components + GDS_PERF_SEL_SE2_SH1_ORD_WAVE_VALID = 0x00000051, // : Number of valid wave ID's processed by ordered append + GDS_PERF_SEL_SE2_SH1_GDS_DATA_VALID = 0x00000052, // : Number of valid write enables from the data bus + GDS_PERF_SEL_SE2_SH1_GDS_STALL_BY_ORD = 0x00000053, // : Number of cycles GDS data is stalled due to Ordered count data + GDS_PERF_SEL_SE2_SH1_GDS_WR_OP = 0x00000054, // : Number of GDS Write operations + GDS_PERF_SEL_SE2_SH1_GDS_RD_OP = 0x00000055, // : Number of GDS Read operations + GDS_PERF_SEL_SE2_SH1_GDS_ATOM_OP = 0x00000056, // : Number of GDS Atomic operations + GDS_PERF_SEL_SE2_SH1_GDS_REL_OP = 0x00000057, // : Number of GDS Relative operations + GDS_PERF_SEL_SE2_SH1_GDS_CMPXCH_OP = 0x00000058, // : Number of GDS Compare or Exchange operations + GDS_PERF_SEL_SE2_SH1_GDS_BYTE_OP = 0x00000059, // : Number of GDS byte operations + GDS_PERF_SEL_SE2_SH1_GDS_SHORT_OP = 0x0000005a, // : Number of GDS short operations + GDS_PERF_SEL_SE3_SH0_NORET = 0x0000005b, // : Number of commands that do not return data + GDS_PERF_SEL_SE3_SH0_RET = 0x0000005c, // : Number of commands that do return data + GDS_PERF_SEL_SE3_SH0_ORD_CNT = 0x0000005d, // : Number of ordered count operations + GDS_PERF_SEL_SE3_SH0_2COMP_REQ = 0x0000005e, // : Number of commands that return two components + GDS_PERF_SEL_SE3_SH0_ORD_WAVE_VALID = 0x0000005f, // : Number of valid wave ID's processed by ordered append + GDS_PERF_SEL_SE3_SH0_GDS_DATA_VALID = 0x00000060, // : Number of valid write enables from the data bus + GDS_PERF_SEL_SE3_SH0_GDS_STALL_BY_ORD = 0x00000061, // : Number of cycles GDS data is stalled due to Ordered count data + GDS_PERF_SEL_SE3_SH0_GDS_WR_OP = 0x00000062, // : Number of GDS Write operations + GDS_PERF_SEL_SE3_SH0_GDS_RD_OP = 0x00000063, // : Number of GDS Read operations + GDS_PERF_SEL_SE3_SH0_GDS_ATOM_OP = 0x00000064, // : Number of GDS Atomic operations + GDS_PERF_SEL_SE3_SH0_GDS_REL_OP = 0x00000065, // : Number of GDS Relative operations + GDS_PERF_SEL_SE3_SH0_GDS_CMPXCH_OP = 0x00000066, // : Number of GDS Compare or Exchange operations + GDS_PERF_SEL_SE3_SH0_GDS_BYTE_OP = 0x00000067, // : Number of GDS byte operations + GDS_PERF_SEL_SE3_SH0_GDS_SHORT_OP = 0x00000068, // : Number of GDS short operations + GDS_PERF_SEL_SE3_SH1_NORET = 0x00000069, // : Number of commands that do not return data + GDS_PERF_SEL_SE3_SH1_RET = 0x0000006a, // : Number of commands that do return data + GDS_PERF_SEL_SE3_SH1_ORD_CNT = 0x0000006b, // : Number of ordered count operations + GDS_PERF_SEL_SE3_SH1_2COMP_REQ = 0x0000006c, // : Number of commands that return two components + GDS_PERF_SEL_SE3_SH1_ORD_WAVE_VALID = 0x0000006d, // : Number of valid wave ID's processed by ordered append + GDS_PERF_SEL_SE3_SH1_GDS_DATA_VALID = 0x0000006e, // : Number of valid write enables from the data bus + GDS_PERF_SEL_SE3_SH1_GDS_STALL_BY_ORD = 0x0000006f, // : Number of cycles GDS data is stalled due to Ordered count data + GDS_PERF_SEL_SE3_SH1_GDS_WR_OP = 0x00000070, // : Number of GDS Write operations + GDS_PERF_SEL_SE3_SH1_GDS_RD_OP = 0x00000071, // : Number of GDS Read operations + GDS_PERF_SEL_SE3_SH1_GDS_ATOM_OP = 0x00000072, // : Number of GDS Atomic operations + GDS_PERF_SEL_SE3_SH1_GDS_REL_OP = 0x00000073, // : Number of GDS Relative operations + GDS_PERF_SEL_SE3_SH1_GDS_CMPXCH_OP = 0x00000074, // : Number of GDS Compare or Exchange operations + GDS_PERF_SEL_SE3_SH1_GDS_BYTE_OP = 0x00000075, // : Number of GDS byte operations + GDS_PERF_SEL_SE3_SH1_GDS_SHORT_OP = 0x00000076, // : Number of GDS short operations + GDS_PERF_SEL_GWS_RELEASED = 0x00000077, // : Number of waves released by GWS + GDS_PERF_SEL_GWS_BYPASS = 0x00000078, // : Number of waves bypassed by GWS + GDS_PERF_SEL_SE0_BACK_COMPAT_MODE_SWITCH = 0x00000079, // : se0 gfx back compat mode switch + GDS_PERF_SEL_SE1_BACK_COMPAT_MODE_SWITCH = 0x0000007a, // : se1 gfx back compat mode switch +} GDS_PERFCOUNTER_SELECT; + +typedef enum GE_PERFCOUNTER_SELECT : unsigned int { + GE_PERFCOUNT_SEL_ASSEMBLER_BUSY = 0x00000000, // GE Assembler busy + GE_PERFCOUNT_SEL_ASSEMBLER_STALLED = 0x00000001, // GE Assembler stalled + GE_PERFCOUNT_SEL_CM_READING_STALLED = 0x00000002, // the GOG can accept data and the CM should be sending data, but is not + GE_PERFCOUNT_SEL_CM_STALLED_BY_GOG = 0x00000003, // the output fifo to the GOG is full and the CM wants to send data + GE_PERFCOUNT_SEL_CM_STALLED_BY_GSFETCH_DONE = 0x00000004, // all CM state machines are waiting for gsfetch_done + GE_PERFCOUNT_SEL_DMA_BUSY = 0x00000005, // GE DMA engine busy + GE_PERFCOUNT_SEL_DMA_LAT_BIN_0 = 0x00000006, // number of requests in bin 0. The range is determined by VGT_MC_LAT_CNTL. A setting of 0 means each bin is 128 clocks so bin 0 is 0-128 clocks. Includes UTC latency. + GE_PERFCOUNT_SEL_DMA_LAT_BIN_1 = 0x00000007, // number of requests in bin 1. The range is determined by VGT_MC_LAT_CNTL. A setting of 0 means each bin is 128 clocks so bin 1 is 129-256 clocks. Includes UTC latency. + GE_PERFCOUNT_SEL_DMA_LAT_BIN_2 = 0x00000008, // number of requests in bin 2. The range is determined by VGT_MC_LAT_CNTL. A setting of 0 means each bin is 128 clocks so bin 2 is 257-384 clocks. Includes UTC latency. + GE_PERFCOUNT_SEL_DMA_LAT_BIN_3 = 0x00000009, // number of requests in bin 3. The range is determined by VGT_MC_LAT_CNTL. A setting of 0 means each bin is 128 clocks so bin 3 is 385-512 clocks. Includes UTC latency. + GE_PERFCOUNT_SEL_DMA_LAT_BIN_4 = 0x0000000a, // number of requests in bin 4. The range is determined by VGT_MC_LAT_CNTL. A setting of 0 means each bin is 128 clocks so bin 4 is 513-640 clocks. Includes UTC latency + GE_PERFCOUNT_SEL_DMA_LAT_BIN_5 = 0x0000000b, // number of requests in bin 5. The range is determined by VGT_MC_LAT_CNTL. A setting of 0 means each bin is 128 clocks so bin 5 is 641-768 clocks. Includes UTC latency. + GE_PERFCOUNT_SEL_DMA_LAT_BIN_6 = 0x0000000c, // number of requests in bin 6. The range is determined by VGT_MC_LAT_CNTL. A setting of 0 means each bin is 128 clocks so bin 6 is 769-896 clocks. Includes UTC latency. + GE_PERFCOUNT_SEL_DMA_LAT_BIN_7 = 0x0000000d, // number of requests in bin 7. The range is determined by VGT_MC_LAT_CNTL. A setting of 0 means each bin is 128 clocks so bin 7 is 897-1024 clocks. Includes UTC latency. + GE_PERFCOUNT_SEL_DMA_RETURN_CL0 = 0x0000000e, // GE DMA returned data CH0 + GE_PERFCOUNT_SEL_DMA_RETURN_CL1 = 0x0000000f, // GE DMA returned data CH1 + GE_PERFCOUNT_SEL_DMA_UTCL1_CONSECUTIVE_RETRY_EVENT = 0x00000010, // UTCL2 consecutive (2 or more) retries + GE_PERFCOUNT_SEL_DMA_UTCL1_REQUEST_EVENT = 0x00000011, // The number of clocks cycles the DMA engine has a memory request + GE_PERFCOUNT_SEL_DMA_UTCL1_RETRY_EVENT = 0x00000012, // UTCL2 translation retry + GE_PERFCOUNT_SEL_DMA_UTCL1_STALL_EVENT = 0x00000013, // UTCL1 translation stall + GE_PERFCOUNT_SEL_DMA_UTCL1_STALL_UTCL2_EVENT = 0x00000014, // UTCL2 stall + GE_PERFCOUNT_SEL_DMA_UTCL1_TRANSLATION_HIT_EVENT = 0x00000015, // UTCL1 translation hit + GE_PERFCOUNT_SEL_DMA_UTCL1_TRANSLATION_MISS_EVENT = 0x00000016, // UTCL1 translation miss + GE_PERFCOUNT_SEL_DS_CACHE_HITS = 0x00000017, // number of parameter cache hits due to a DS (hardware VS is a GS, so tessellation is enabled with GS disabled) + GE_PERFCOUNT_SEL_DS_PRIMS = 0x00000018, // Number of prims output from the tessellator + GE_PERFCOUNT_SEL_ES_DONE = 0x00000019, // Counts number of SX ES DONES received by the VGT. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_ES_DONE_LATENCY = 0x0000001a, // Total latency ES FLUSHES issued to the SX DONES received. Divide by ES FLUSHES issued for average latency. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_ES_FLUSH = 0x0000001b, // Counts number of ES FLUSH events issues by the VGT. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_ES_RING_HIGH_WATER_MARK = 0x0000001c, // Records maximum number of ES waves outstanding in the ES ring. Counter select must be set to MAX mode + GE_PERFCOUNT_SEL_ES_THREAD_GROUPS = 0x0000001d, // Count of thread groups issued to the ES (these are Domain Shader Threadgroups). Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_ESTHREAD_STALLED_ES_RB_FULL = 0x0000001e, // ES thread sends are stalled because the ES ring buffer is full + GE_PERFCOUNT_SEL_ESTHREAD_STALLED_SPI_BP = 0x0000001f, // ES thread is stalled due to back pressure from the SPI + GE_PERFCOUNT_SEL_ESVERT_STALLED_GS_EVENT = 0x00000020, // esvert transfers are stalled because of events + GE_PERFCOUNT_SEL_ESVERT_STALLED_GS_TBL = 0x00000021, // esvert transfers are stalled because of GS table being full + GE_PERFCOUNT_SEL_ESVERT_STALLED_GSPRIM = 0x00000022, // esvert transfers are stalled because of GS prim interface is full + GE_PERFCOUNT_SEL_ASSEMBLER_DMA_STARVED = 0x00000023, // Assembler has a draw pending but is waiting for data from the DMA + GE_PERFCOUNT_SEL_GOG_BUSY = 0x00000024, // Counts number of cycles that the GOG block is busy + GE_PERFCOUNT_SEL_GOG_OUT_INDX_STALLED = 0x00000025, // GOG is stalled by back pressure from the output block + GE_PERFCOUNT_SEL_GOG_OUT_PRIM_STALLED = 0x00000026, // GOG is stalled by back pressure from the output block + GE_PERFCOUNT_SEL_GOG_VS_TBL_STALLED = 0x00000027, // GOG is stalled because the VS table is full + GE_PERFCOUNT_SEL_GS_CACHE_HITS = 0x00000028, // number of parameter cache hits due to a copy shader (hardware VS when GS is enabled) + GE_PERFCOUNT_SEL_GS_COUNTERS_AVAIL_STALLED = 0x00000029, // GS thread send is stalled because no counters are available + GE_PERFCOUNT_SEL_GS_DONE = 0x0000002a, // Counts number of GS DONES processed by the VGT. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_GS_DONE_LATENCY = 0x0000002b, // Total latency GS FLUSHES issued to the SX DONES received. Divide by GS FLUSHES issued for average latency. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_GS_ISSUE_RTR_STALLED = 0x0000002c, // GS thread send is stalled due to something other than the counters or ring buffer being full + GE_PERFCOUNT_SEL_GS_RB_SPACE_AVAIL_STALLED = 0x0000002d, // GS thread send is stalled because the GS/VS ring buffer is full + GE_PERFCOUNT_SEL_GS_RING_HIGH_WATER_MARK = 0x0000002e, // Records maximum number of GS waves outstanding in the GS ring. Counter select must be set to MAX mode + GE_PERFCOUNT_SEL_GSPRIM_STALLED_ES_TBL = 0x0000002f, // gsprim transfers are stalled because ES table is full + GE_PERFCOUNT_SEL_GSPRIM_STALLED_ESVERT = 0x00000030, // gsprim transfers are stalled because of ES vert interface is full + GE_PERFCOUNT_SEL_GSPRIM_STALLED_GS_EVENT = 0x00000031, // gsprim transfers are stalled because of events + GE_PERFCOUNT_SEL_GSPRIM_STALLED_GS_TBL = 0x00000032, // gsprim transfers are stalled because of GS table being full + GE_PERFCOUNT_SEL_GSTHREAD_STALLED = 0x00000033, // GS thread send is stalled. Inclusive of the 3 counters above. + GE_PERFCOUNT_SEL_HS_DONE = 0x00000034, // Counts number of HS DONES received by the GE (total for all SEs).Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_HS_DONE_LATENCY = 0x00000035, // Total latency HS FLUSHES issued to the DONES received. Divide by HS FLUSHES issued for average latency. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_HS_DONE_SE0 = 0x00000036, // Counts number of SX HS DONES received by the VGT0. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_HS_DONE_SE1 = 0x00000037, // Counts number of SX HS DONES received by the VGT1. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_HS_DONE_SE2_RESERVED = 0x00000038, // RESERVED + GE_PERFCOUNT_SEL_HS_DONE_SE3_RESERVED = 0x00000039, // RESERVED + GE_PERFCOUNT_SEL_HS_TFM_STALL = 0x0000003a, // HS TF Memory stall + GE_PERFCOUNT_SEL_HS_TGS_ACTIVE_HIGH_WATER_MARK = 0x0000003b, // Records maximum number of active threadgroups. Counter select must be set to MAX mode + GE_PERFCOUNT_SEL_HS_THREAD_GROUPS = 0x0000003c, // Count of thread groups issued to the HS. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_INSIDE_TF_BIN_0 = 0x0000003d, // counts number of cycles, the average of inside tess factors is 0 + GE_PERFCOUNT_SEL_INSIDE_TF_BIN_1 = 0x0000003e, // counts number of cycles, the average of inside tess factors is 1 + GE_PERFCOUNT_SEL_INSIDE_TF_BIN_2 = 0x0000003f, // counts number of cycles, the average of inside tess factors is 2 + GE_PERFCOUNT_SEL_INSIDE_TF_BIN_3 = 0x00000040, // counts number of cycles, the average of inside tess factors is 3 + GE_PERFCOUNT_SEL_INSIDE_TF_BIN_4 = 0x00000041, // counts number of cycles, the average of inside tess factors is 4 + GE_PERFCOUNT_SEL_INSIDE_TF_BIN_5 = 0x00000042, // counts number of cycles, the average of inside tess factors is 5 + GE_PERFCOUNT_SEL_INSIDE_TF_BIN_6 = 0x00000043, // counts number of cycles, the average of inside tess factors is between 6-24 inclusive + GE_PERFCOUNT_SEL_INSIDE_TF_BIN_7 = 0x00000044, // counts number of cycles, the average of inside tess factors is between 25-44 inclusive + GE_PERFCOUNT_SEL_INSIDE_TF_BIN_8 = 0x00000045, // counts number of cycles, the average of inside tess factors is between 45-64 inclusive + GE_PERFCOUNT_SEL_LS_DONE = 0x00000046, // Counts number of SX LS DONES received by the GE + GE_PERFCOUNT_SEL_LS_DONE_LATENCY = 0x00000047, // Total latency LS FLUSHES issued to the SX DONES received. Divide by LS FLUSHES issued for average latency. + GE_PERFCOUNT_SEL_NULL_PATCH = 0x00000048, // patch discarded by tf + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_EOP = 0x00000049, // number of end of packet transfers (can accompany a valid or null primitive, but not an event) + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_EOPG = 0x0000004a, // Counts number of CLIPP EOPG issued by the GE + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_IS_EVENT = 0x0000004b, // number of events sent to the PA + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_NEW_VTX_VECT = 0x0000004c, // number of primitives that start a new VS wavefront/vector (used by Parameter Cache logic) + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_NULL_PRIM = 0x0000004d, // number of null primitives sent to the PA (these transfers carry information like eop or PC dealloc information) + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_SEND = 0x0000004e, // number of transfers across the CLIPP interface (primitives, tokens, and events) + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_SEND_NOT_EVENT = 0x0000004f, // Counts send on the VGT_PA_clipp interface that are not events + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_STALLED = 0x00000050, // ready to send a CLIPP transfer, but stalled by the PA (means the max number of primitives are in flight). If there are stalls on this interface we don't have a deep enough FIFO to hide VS latency from the start to position export or there is back pressure from downstream. Usually the SC in this case, but sometimes due to clipping. + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_STARVED_BUSY = 0x00000051, // CLIPP interface is starved while the VGT is busy (most accurate with VS only tests since these have the least time between the VGT going busy and the CLIPP receiving work. If looking at counts from a single draw use vgt_perf_vgt_pa_clipp_starved_after_work) + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_STARVED_AFTER_WORK = 0x00000052, // Counts number of cycles between non-event clipp_send and stop when clipp_send with eop. + GE_PERFCOUNT_SEL_SE0PA0_CLIPP_VALID_PRIM = 0x00000053, // Counts send on the VGT_PA_clipp interface that are valid prims + GE_PERFCOUNT_SEL_SE0PA0_CLIPS_SEND = 0x00000054, // number of transfers sent across the CLIPS interface (S stands for state data and there is a transfer per draw packet) + GE_PERFCOUNT_SEL_SE0PA0_CLIPS_STALLED = 0x00000055, // ready to send a CLIPS transfer, but stalled by the PA. If there are stalls here it means the draw calls are really small. + GE_PERFCOUNT_SEL_SE0PA0_CLIPV_SEND = 0x00000056, // number of transfers sent across the clipv interface. V stands for vector as in vertex vector or vertex wave. When the VGT sends a VS wave to the SPI it also sends a clipv transfer to the PA. The PA uses data on this interface to know how many positions to fetch after they are exported from the corresponding VS. + GE_PERFCOUNT_SEL_SE0PA0_CLIPV_STALLED = 0x00000057, // ready to send a CLIPV transfer, but stalled by the PA. + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_EOP = 0x00000058, // number of end of packet transfers (can accompany a valid or null primitive, but not an event) + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_EOPG = 0x00000059, // Counts number of CLIPP EOPG issued by the GE + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_IS_EVENT = 0x0000005a, // number of events sent to the PA + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_NEW_VTX_VECT = 0x0000005b, // number of primitives that start a new VS wavefront/vector (used by Parameter Cache logic) + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_NULL_PRIM = 0x0000005c, // number of null primitives sent to the PA (these transfers carry information like eop or PC dealloc information) + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_SEND = 0x0000005d, // number of transfers across the CLIPP interface (primitives, tokens, and events) + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_SEND_NOT_EVENT = 0x0000005e, // Counts send on the VGT_PA_clipp interface that are not events + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_STALLED = 0x0000005f, // ready to send a CLIPP transfer, but stalled by the PA (means the max number of primitives are in flight). If there are stalls on this interface we don't have a deep enough FIFO to hide VS latency from the start to position export or there is back pressure from downstream. Usually the SC in this case, but sometimes due to clipping. + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_STARVED_BUSY = 0x00000060, // CLIPP interface is starved while the VGT is busy (most accurate with VS only tests since these have the least time between the VGT going busy and the CLIPP receiving work. If looking at counts from a single draw use vgt_perf_vgt_pa_clipp_starved_after_work) + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_STARVED_AFTER_WORK = 0x00000061, // Counts number of cycles between non-event clipp_send and stop when clipp_send with eop. + GE_PERFCOUNT_SEL_SE0PA1_CLIPP_VALID_PRIM = 0x00000062, // Counts send on the VGT_PA_clipp interface that are valid prims + GE_PERFCOUNT_SEL_SE0PA1_CLIPS_SEND = 0x00000063, // number of transfers sent across the CLIPS interface (S stands for state data and there is a transfer per draw packet) + GE_PERFCOUNT_SEL_SE0PA1_CLIPS_STALLED = 0x00000064, // ready to send a CLIPS transfer, but stalled by the PA. If there are stalls here it means the draw calls are really small. + GE_PERFCOUNT_SEL_SE0PA1_CLIPV_SEND = 0x00000065, // number of transfers sent across the clipv interface. V stands for vector as in vertex vector or vertex wave. When the VGT sends a VS wave to the SPI it also sends a clipv transfer to the PA. The PA uses data on this interface to know how many positions to fetch after they are exported from the corresponding VS. + GE_PERFCOUNT_SEL_SE0PA1_CLIPV_STALLED = 0x00000066, // ready to send a CLIPV transfer, but stalled by the PA. + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_EOP = 0x00000067, // number of end of packet transfers (can accompany a valid or null primitive, but not an event) + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_EOPG = 0x00000068, // Counts number of CLIPP EOPG issued by the GE + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_IS_EVENT = 0x00000069, // number of events sent to the PA + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_NEW_VTX_VECT = 0x0000006a, // number of primitives that start a new VS wavefront/vector (used by Parameter Cache logic) + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_NULL_PRIM = 0x0000006b, // number of null primitives sent to the PA (these transfers carry information like eop or PC dealloc information) + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_SEND = 0x0000006c, // number of transfers across the CLIPP interface (primitives, tokens, and events) + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_SEND_NOT_EVENT = 0x0000006d, // Counts send on the VGT_PA_clipp interface that are not events + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_STALLED = 0x0000006e, // ready to send a CLIPP transfer, but stalled by the PA (means the max number of primitives are in flight). If there are stalls on this interface we don't have a deep enough FIFO to hide VS latency from the start to position export or there is back pressure from downstream. Usually the SC in this case, but sometimes due to clipping. + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_STARVED_BUSY = 0x0000006f, // CLIPP interface is starved while the VGT is busy (most accurate with VS only tests since these have the least time between the VGT going busy and the CLIPP receiving work. If looking at counts from a single draw use vgt_perf_vgt_pa_clipp_starved_after_work) + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_STARVED_AFTER_WORK = 0x00000070, // Counts number of cycles between non-event clipp_send and stop when clipp_send with eop. + GE_PERFCOUNT_SEL_SE1PA0_CLIPP_VALID_PRIM = 0x00000071, // Counts send on the VGT_PA_clipp interface that are valid prims + GE_PERFCOUNT_SEL_SE1PA0_CLIPS_SEND = 0x00000072, // number of transfers sent across the CLIPS interface (S stands for state data and there is a transfer per draw packet) + GE_PERFCOUNT_SEL_SE1PA0_CLIPS_STALLED = 0x00000073, // ready to send a CLIPS transfer, but stalled by the PA. If there are stalls here it means the draw calls are really small. + GE_PERFCOUNT_SEL_SE1PA0_CLIPV_SEND = 0x00000074, // number of transfers sent across the clipv interface. V stands for vector as in vertex vector or vertex wave. When the VGT sends a VS wave to the SPI it also sends a clipv transfer to the PA. The PA uses data on this interface to know how many positions to fetch after they are exported from the corresponding VS. + GE_PERFCOUNT_SEL_SE1PA0_CLIPV_STALLED = 0x00000075, // ready to send a CLIPV transfer, but stalled by the PA. + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_EOP = 0x00000076, // number of end of packet transfers (can accompany a valid or null primitive, but not an event) + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_EOPG = 0x00000077, // Counts number of CLIPP EOPG issued by the GE + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_IS_EVENT = 0x00000078, // number of events sent to the PA + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_NEW_VTX_VECT = 0x00000079, // number of primitives that start a new VS wavefront/vector (used by Parameter Cache logic) + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_NULL_PRIM = 0x0000007a, // number of null primitives sent to the PA (these transfers carry information like eop or PC dealloc information) + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_SEND = 0x0000007b, // number of transfers across the CLIPP interface (primitives, tokens, and events) + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_SEND_NOT_EVENT = 0x0000007c, // Counts send on the VGT_PA_clipp interface that are not events + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_STALLED = 0x0000007d, // ready to send a CLIPP transfer, but stalled by the PA (means the max number of primitives are in flight). If there are stalls on this interface we don't have a deep enough FIFO to hide VS latency from the start to position export or there is back pressure from downstream. Usually the SC in this case, but sometimes due to clipping. + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_STARVED_BUSY = 0x0000007e, // CLIPP interface is starved while the VGT is busy (most accurate with VS only tests since these have the least time between the VGT going busy and the CLIPP receiving work. If looking at counts from a single draw use vgt_perf_vgt_pa_clipp_starved_after_work) + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_STARVED_AFTER_WORK = 0x0000007f, // Counts number of cycles between non-event clipp_send and stop when clipp_send with eop. + GE_PERFCOUNT_SEL_SE1PA1_CLIPP_VALID_PRIM = 0x00000080, // Counts send on the VGT_PA_clipp interface that are valid prims + GE_PERFCOUNT_SEL_SE1PA1_CLIPS_SEND = 0x00000081, // number of transfers sent across the CLIPS interface (S stands for state data and there is a transfer per draw packet) + GE_PERFCOUNT_SEL_SE1PA1_CLIPS_STALLED = 0x00000082, // ready to send a CLIPS transfer, but stalled by the PA. If there are stalls here it means the draw calls are really small. + GE_PERFCOUNT_SEL_SE1PA1_CLIPV_SEND = 0x00000083, // number of transfers sent across the clipv interface. V stands for vector as in vertex vector or vertex wave. When the VGT sends a VS wave to the SPI it also sends a clipv transfer to the PA. The PA uses data on this interface to know how many positions to fetch after they are exported from the corresponding VS. + GE_PERFCOUNT_SEL_SE1PA1_CLIPV_STALLED = 0x00000084, // ready to send a CLIPV transfer, but stalled by the PA. + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_EOP = 0x00000085, // number of end of packet transfers (can accompany a valid or null primitive, but not an event) + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_EOPG = 0x00000086, // Counts number of CLIPP EOPG issued by the GE + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_IS_EVENT = 0x00000087, // number of events sent to the PA + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_NEW_VTX_VECT = 0x00000088, // number of primitives that start a new VS wavefront/vector (used by Parameter Cache logic) + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_NULL_PRIM = 0x00000089, // number of null primitives sent to the PA (these transfers carry information like eop or PC dealloc information) + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_SEND = 0x0000008a, // number of transfers across the CLIPP interface (primitives, tokens, and events) + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_SEND_NOT_EVENT = 0x0000008b, // Counts send on the VGT_PA_clipp interface that are not events + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_STALLED = 0x0000008c, // ready to send a CLIPP transfer, but stalled by the PA (means the max number of primitives are in flight). If there are stalls on this interface we don't have a deep enough FIFO to hide VS latency from the start to position export or there is back pressure from downstream. Usually the SC in this case, but sometimes due to clipping. + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_STARVED_BUSY = 0x0000008d, // CLIPP interface is starved while the VGT is busy (most accurate with VS only tests since these have the least time between the VGT going busy and the CLIPP receiving work. If looking at counts from a single draw use vgt_perf_vgt_pa_clipp_starved_after_work) + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_STARVED_AFTER_WORK = 0x0000008e, // Counts number of cycles between non-event clipp_send and stop when clipp_send with eop. + GE_PERFCOUNT_SEL_SE2PA0_CLIPP_VALID_PRIM = 0x0000008f, // Counts send on the VGT_PA_clipp interface that are valid prims + GE_PERFCOUNT_SEL_SE2PA0_CLIPS_SEND = 0x00000090, // number of transfers sent across the CLIPS interface (S stands for state data and there is a transfer per draw packet) + GE_PERFCOUNT_SEL_SE2PA0_CLIPS_STALLED = 0x00000091, // ready to send a CLIPS transfer, but stalled by the PA. If there are stalls here it means the draw calls are really small. + GE_PERFCOUNT_SEL_SE2PA0_CLIPV_SEND = 0x00000092, // number of transfers sent across the clipv interface. V stands for vector as in vertex vector or vertex wave. When the VGT sends a VS wave to the SPI it also sends a clipv transfer to the PA. The PA uses data on this interface to know how many positions to fetch after they are exported from the corresponding VS. + GE_PERFCOUNT_SEL_SE2PA0_CLIPV_STALLED = 0x00000093, // ready to send a CLIPV transfer, but stalled by the PA. + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_EOP = 0x00000094, // number of end of packet transfers (can accompany a valid or null primitive, but not an event) + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_EOPG = 0x00000095, // Counts number of CLIPP EOPG issued by the GE + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_IS_EVENT = 0x00000096, // number of events sent to the PA + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_NEW_VTX_VECT = 0x00000097, // number of primitives that start a new VS wavefront/vector (used by Parameter Cache logic) + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_NULL_PRIM = 0x00000098, // number of null primitives sent to the PA (these transfers carry information like eop or PC dealloc information) + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_SEND = 0x00000099, // number of transfers across the CLIPP interface (primitives, tokens, and events) + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_SEND_NOT_EVENT = 0x0000009a, // Counts send on the VGT_PA_clipp interface that are not events + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_STALLED = 0x0000009b, // ready to send a CLIPP transfer, but stalled by the PA (means the max number of primitives are in flight). If there are stalls on this interface we don't have a deep enough FIFO to hide VS latency from the start to position export or there is back pressure from downstream. Usually the SC in this case, but sometimes due to clipping. + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_STARVED_BUSY = 0x0000009c, // CLIPP interface is starved while the VGT is busy (most accurate with VS only tests since these have the least time between the VGT going busy and the CLIPP receiving work. If looking at counts from a single draw use vgt_perf_vgt_pa_clipp_starved_after_work) + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_STARVED_AFTER_WORK = 0x0000009d, // Counts number of cycles between non-event clipp_send and stop when clipp_send with eop. + GE_PERFCOUNT_SEL_SE2PA1_CLIPP_VALID_PRIM = 0x0000009e, // Counts send on the VGT_PA_clipp interface that are valid prims + GE_PERFCOUNT_SEL_SE2PA1_CLIPS_SEND = 0x0000009f, // number of transfers sent across the CLIPS interface (S stands for state data and there is a transfer per draw packet) + GE_PERFCOUNT_SEL_SE2PA1_CLIPS_STALLED = 0x000000a0, // ready to send a CLIPS transfer, but stalled by the PA. If there are stalls here it means the draw calls are really small. + GE_PERFCOUNT_SEL_SE2PA1_CLIPV_SEND = 0x000000a1, // number of transfers sent across the clipv interface. V stands for vector as in vertex vector or vertex wave. When the VGT sends a VS wave to the SPI it also sends a clipv transfer to the PA. The PA uses data on this interface to know how many positions to fetch after they are exported from the corresponding VS. + GE_PERFCOUNT_SEL_SE2PA1_CLIPV_STALLED = 0x000000a2, // ready to send a CLIPV transfer, but stalled by the PA. + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_EOP = 0x000000a3, // number of end of packet transfers (can accompany a valid or null primitive, but not an event) + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_EOPG = 0x000000a4, // Counts number of CLIPP EOPG issued by the GE + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_IS_EVENT = 0x000000a5, // number of events sent to the PA + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_NEW_VTX_VECT = 0x000000a6, // number of primitives that start a new VS wavefront/vector (used by Parameter Cache logic) + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_NULL_PRIM = 0x000000a7, // number of null primitives sent to the PA (these transfers carry information like eop or PC dealloc information) + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_SEND = 0x000000a8, // number of transfers across the CLIPP interface (primitives, tokens, and events) + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_SEND_NOT_EVENT = 0x000000a9, // Counts send on the VGT_PA_clipp interface that are not events + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_STALLED = 0x000000aa, // ready to send a CLIPP transfer, but stalled by the PA (means the max number of primitives are in flight). If there are stalls on this interface we don't have a deep enough FIFO to hide VS latency from the start to position export or there is back pressure from downstream. Usually the SC in this case, but sometimes due to clipping. + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_STARVED_BUSY = 0x000000ab, // CLIPP interface is starved while the VGT is busy (most accurate with VS only tests since these have the least time between the VGT going busy and the CLIPP receiving work. If looking at counts from a single draw use vgt_perf_vgt_pa_clipp_starved_after_work) + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_STARVED_AFTER_WORK = 0x000000ac, // Counts number of cycles between non-event clipp_send and stop when clipp_send with eop. + GE_PERFCOUNT_SEL_SE3PA0_CLIPP_VALID_PRIM = 0x000000ad, // Counts send on the VGT_PA_clipp interface that are valid prims + GE_PERFCOUNT_SEL_SE3PA0_CLIPS_SEND = 0x000000ae, // number of transfers sent across the CLIPS interface (S stands for state data and there is a transfer per draw packet) + GE_PERFCOUNT_SEL_SE3PA0_CLIPS_STALLED = 0x000000af, // ready to send a CLIPS transfer, but stalled by the PA. If there are stalls here it means the draw calls are really small. + GE_PERFCOUNT_SEL_SE3PA0_CLIPV_SEND = 0x000000b0, // number of transfers sent across the clipv interface. V stands for vector as in vertex vector or vertex wave. When the VGT sends a VS wave to the SPI it also sends a clipv transfer to the PA. The PA uses data on this interface to know how many positions to fetch after they are exported from the corresponding VS. + GE_PERFCOUNT_SEL_SE3PA0_CLIPV_STALLED = 0x000000b1, // ready to send a CLIPV transfer, but stalled by the PA. + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_EOP = 0x000000b2, // number of end of packet transfers (can accompany a valid or null primitive, but not an event) + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_EOPG = 0x000000b3, // Counts number of CLIPP EOPG issued by the GE + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_IS_EVENT = 0x000000b4, // number of events sent to the PA + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_NEW_VTX_VECT = 0x000000b5, // number of primitives that start a new VS wavefront/vector (used by Parameter Cache logic) + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_NULL_PRIM = 0x000000b6, // number of null primitives sent to the PA (these transfers carry information like eop or PC dealloc information) + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_SEND = 0x000000b7, // number of transfers across the CLIPP interface (primitives, tokens, and events) + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_SEND_NOT_EVENT = 0x000000b8, // Counts send on the VGT_PA_clipp interface that are not events + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_STALLED = 0x000000b9, // ready to send a CLIPP transfer, but stalled by the PA (means the max number of primitives are in flight). If there are stalls on this interface we don't have a deep enough FIFO to hide VS latency from the start to position export or there is back pressure from downstream. Usually the SC in this case, but sometimes due to clipping. + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_STARVED_BUSY = 0x000000ba, // CLIPP interface is starved while the VGT is busy (most accurate with VS only tests since these have the least time between the VGT going busy and the CLIPP receiving work. If looking at counts from a single draw use vgt_perf_vgt_pa_clipp_starved_after_work) + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_STARVED_AFTER_WORK = 0x000000bb, // Counts number of cycles between non-event clipp_send and stop when clipp_send with eop. + GE_PERFCOUNT_SEL_SE3PA1_CLIPP_VALID_PRIM = 0x000000bc, // Counts send on the VGT_PA_clipp interface that are valid prims + GE_PERFCOUNT_SEL_SE3PA1_CLIPS_SEND = 0x000000bd, // number of transfers sent across the CLIPS interface (S stands for state data and there is a transfer per draw packet) + GE_PERFCOUNT_SEL_SE3PA1_CLIPS_STALLED = 0x000000be, // ready to send a CLIPS transfer, but stalled by the PA. If there are stalls here it means the draw calls are really small. + GE_PERFCOUNT_SEL_SE3PA1_CLIPV_SEND = 0x000000bf, // number of transfers sent across the clipv interface. V stands for vector as in vertex vector or vertex wave. When the VGT sends a VS wave to the SPI it also sends a clipv transfer to the PA. The PA uses data on this interface to know how many positions to fetch after they are exported from the corresponding VS. + GE_PERFCOUNT_SEL_SE3PA1_CLIPV_STALLED = 0x000000c0, // ready to send a CLIPV transfer, but stalled by the PA. + GE_PERFCOUNT_SEL_RBIU_DI_FIFO_STALLED = 0x000000c1, // rbiu draw initiator fifo is stalled + GE_PERFCOUNT_SEL_RBIU_DI_FIFO_STARVED = 0x000000c2, // rbiu draw initiator fifo is starved + GE_PERFCOUNT_SEL_RBIU_DR_FIFO_STALLED = 0x000000c3, // rbiu dma request fifo is stalled + GE_PERFCOUNT_SEL_RBIU_DR_FIFO_STARVED = 0x000000c4, // rbiu dma request fifo is starved + GE_PERFCOUNT_SEL_REUSED_ES_INDICES = 0x000000c5, // number of reuse buffer hits when ES is the first stage. i.e. the pipeline is configured to have a VS and GS with no tessellation. + GE_PERFCOUNT_SEL_REUSED_VS_INDICES = 0x000000c6, // number of reused indices, excluding GS scenario G and tessellation + GE_PERFCOUNT_SEL_SCLK_CORE_VLD = 0x000000c7, // Counts number of cycles sclk_core is valid + GE_PERFCOUNT_SEL_SCLK_GS_VLD = 0x000000c8, // Counts number of cycles sclk_gs is valid + GE_PERFCOUNT_SEL_SCLK_INPUT_VLD = 0x000000c9, // Counts number of cycles sclk_input is valid + GE_PERFCOUNT_SEL_SCLK_LEG_GS_ARB_VLD = 0x000000ca, // Counts number of cycles sclk_gs_arb is valid + GE_PERFCOUNT_SEL_SCLK_NGG_VLD = 0x000000cb, // Counts number of cycles sclk_ngg is valid + GE_PERFCOUNT_SEL_SCLK_REG_VLD = 0x000000cc, // Counts number of cycles sclk_reg is valid + GE_PERFCOUNT_SEL_SCLK_TE11_VLD = 0x000000cd, // number of clocks the tessellator is active + GE_PERFCOUNT_SEL_SCLK_VR_VLD = 0x000000ce, // Counts number of cycles sclk_vr is valid + GE_PERFCOUNT_SEL_SCLK_WD_TE11_VLD = 0x000000cf, // Counts number of cycles sclk_te11 is valid + GE_PERFCOUNT_SEL_SPI_ESVERT_EOV = 0x000000d0, // number of ES end of vectors (eov can count when valid is low). Vector and wavefront are interchangeable terms. + GE_PERFCOUNT_SEL_SPI_ESVERT_STALLED = 0x000000d1, // ready to send an ES vert but stalled by the SPI. + GE_PERFCOUNT_SEL_SPI_ESVERT_STARVED_BUSY = 0x000000d2, // ES vert interface is starved while the VGT is busy + GE_PERFCOUNT_SEL_SPI_ESVERT_VALID = 0x000000d3, // number of valid ES verts + GE_PERFCOUNT_SEL_SPI_ESWAVE_IS_EVENT = 0x000000d4, // Counts number of events on the eswave interface + GE_PERFCOUNT_SEL_SPI_ESWAVE_SEND = 0x000000d5, // Counts number of eswaves sent + GE_PERFCOUNT_SEL_SE0SPI_GSPRIM_CONT = 0x000000d6, // GS primitive continued transfers indicate the number of multi-cycle primitives to SE0 + GE_PERFCOUNT_SEL_SE1SPI_GSPRIM_CONT = 0x000000d7, // GS primitive continued transfers indicate the number of multi-cycle primitives to SE1 + GE_PERFCOUNT_SEL_SE2SPI_GSPRIM_CONT = 0x000000d8, // GS primitive continued transfers indicate the number of multi-cycle primitives to SE2 + GE_PERFCOUNT_SEL_SE3SPI_GSPRIM_CONT = 0x000000d9, // GS primitive continued transfers indicate the number of multi-cycle primitives to SE3 + GE_PERFCOUNT_SEL_SPI_GSPRIM_EOV = 0x000000da, // number of GS end of vectors (eov can count when valid is low). Vector and wavefront are interchangeable terms. + GE_PERFCOUNT_SEL_SPI_GSPRIM_STALLED = 0x000000db, // Counts the number of clocks the gsprim interface is stalled + GE_PERFCOUNT_SEL_SPI_GSPRIM_STARVED_BUSY = 0x000000dc, // GS prim interface is starved while the VGT is busy + GE_PERFCOUNT_SEL_SPI_GSPRIM_VALID = 0x000000dd, // number of valid GS prims + GE_PERFCOUNT_SEL_SPI_GSSUBGRP_IS_EVENT = 0x000000de, // Counts the number of events on the gssubgrp interface + GE_PERFCOUNT_SEL_SPI_GSSUBGRP_SEND = 0x000000df, // Counts the number of gssubgrp sends + GE_PERFCOUNT_SEL_SPI_HSVERT_EOV = 0x000000e0, // HS vert end of vector is active. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_SPI_HSVERT_STALLED = 0x000000e1, // HS vert pipe is stalled. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_SPI_HSVERT_STARVED_BUSY = 0x000000e2, // HS vert pipe is starved busy. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_SPI_HSVERT_VALID = 0x000000e3, // HS Vert is valid. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_SPI_HSWAVE_IS_EVENT = 0x000000e4, // Counts the number of events on the hswave interface + GE_PERFCOUNT_SEL_SPI_HSWAVE_SEND = 0x000000e5, // Counts the number of hswave sends + GE_PERFCOUNT_SEL_SPI_LSVERT_EOV = 0x000000e6, // LS vert end of vector is active. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_SPI_LSVERT_STALLED = 0x000000e7, // LS vert pipe is stalled. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_SPI_LSVERT_STARVED_BUSY = 0x000000e8, // LS vert pipe is starved busy. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_SPI_LSVERT_VALID = 0x000000e9, // LS Vert is valid. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_SPI_LSWAVE_IS_EVENT = 0x000000ea, // Counts the number of events on the lswave interface + GE_PERFCOUNT_SEL_SPI_LSWAVE_SEND = 0x000000eb, // Counts the number of lswave sends + GE_PERFCOUNT_SEL_SPI_VSVERT_EOV = 0x000000ec, // number of VS end of vector transfers. Vector and wavefront are interchangeable terms. + GE_PERFCOUNT_SEL_SPI_VSVERT_SEND = 0x000000ed, // number of VS verts, including null EOVs + GE_PERFCOUNT_SEL_SPI_VSVERT_STALLED = 0x000000ee, // ready to send a VS vert, but stalled by the SPI + GE_PERFCOUNT_SEL_SPI_VSVERT_STARVED_BUSY = 0x000000ef, // VS vert interface is starved while the VGT is busy + GE_PERFCOUNT_SEL_SPI_VSWAVE_IS_EVENT = 0x000000f0, // number of event transfers over the VS wave interface + GE_PERFCOUNT_SEL_SPI_VSWAVE_SEND = 0x000000f1, // number of VS wave transfers including events + GE_PERFCOUNT_SEL_STARVED_ON_HS_DONE = 0x000000f2, // Counts the number of clocks the WD TE11 is starved wating for HS done + GE_PERFCOUNT_SEL_STAT_BUSY = 0x000000f3, // GE block is busy with DMA and DRAWs + GE_PERFCOUNT_SEL_STAT_COMBINED_BUSY = 0x000000f4, // Counts the number of clocks ge2_combined_busy is active + GE_PERFCOUNT_SEL_STAT_NO_DMA_BUSY = 0x000000f5, // GE is busy with DMA active but no DRAW is pending or active + GE_PERFCOUNT_SEL_STRMOUT_STALLED = 0x000000f6, // Number of cycles vs waves are stalled by a streamout sync. + GE_PERFCOUNT_SEL_TE11_BUSY = 0x000000f7, // Counts number of cycles the TE11 block is busy. (DX11 Tessellation Fixed Function Logic) + GE_PERFCOUNT_SEL_TE11_STARVED = 0x000000f8, // Counts the number of clocks the te11 is starved for data + GE_PERFCOUNT_SEL_TFREQ_LAT_BIN_0 = 0x000000f9, // counts number of cycles when tf request latency is <64 + GE_PERFCOUNT_SEL_TFREQ_LAT_BIN_1 = 0x000000fa, // counts number of cycles when tf request latency is >64 <128 + GE_PERFCOUNT_SEL_TFREQ_LAT_BIN_2 = 0x000000fb, // counts number of cycles when tf request latency is >128 <192 + GE_PERFCOUNT_SEL_TFREQ_LAT_BIN_3 = 0x000000fc, // counts number of cycles when tf request latency is >192 <256 + GE_PERFCOUNT_SEL_TFREQ_LAT_BIN_4 = 0x000000fd, // counts number of cycles when tf request latency is >256 <320 + GE_PERFCOUNT_SEL_TFREQ_LAT_BIN_5 = 0x000000fe, // counts number of cycles when tf request latency is >320 <384 + GE_PERFCOUNT_SEL_TFREQ_LAT_BIN_6 = 0x000000ff, // counts number of cycles when tf request latency is >384 <512 + GE_PERFCOUNT_SEL_TFREQ_LAT_BIN_7 = 0x00000100, // counts number of cycles when tf request latency is >512 + GE_PERFCOUNT_SEL_TFREQ_UTCL1_CONSECUTIVE_RETRY_EVENT = 0x00000101, // UTCL2 consecutive (2 or more) retries + GE_PERFCOUNT_SEL_TFREQ_UTCL1_REQUEST_EVENT = 0x00000102, // Counts the number of TF requests to memory + GE_PERFCOUNT_SEL_TFREQ_UTCL1_RETRY_EVENT = 0x00000103, // UTCL2 translation retry + GE_PERFCOUNT_SEL_TFREQ_UTCL1_STALL_EVENT = 0x00000104, // UTCL1 translation stall + GE_PERFCOUNT_SEL_TFREQ_UTCL1_STALL_UTCL2_EVENT = 0x00000105, // UTCL2 stall + GE_PERFCOUNT_SEL_TFREQ_UTCL1_TRANSLATION_HIT_EVENT = 0x00000106, // UTCL1 translation hit + GE_PERFCOUNT_SEL_TFREQ_UTCL1_TRANSLATION_MISS_EVENT = 0x00000107, // UTCL1 translation miss + GE_PERFCOUNT_SEL_LS_THREAD_GROUP = 0x00000108, // remove + GE_PERFCOUNT_SEL_RCM_INDICIES_HIT = 0x00000109, // Counts the number of indicies hit in the RCM + GE_PERFCOUNT_SEL_VS_CACHE_HITS = 0x0000010a, // number of parameter cache hits due to an API VS + GE_PERFCOUNT_SEL_VS_DONE = 0x0000010b, // Counts number of VS DONES received by the VGT. Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_VS_PC_STALL = 0x0000010c, // PC alloc stall conditon feorder fifo is not empty but the requested alloc space is not available + GE_PERFCOUNT_SEL_VS_TABLE_HIGH_WATER_MARK = 0x0000010d, // Records maximum number of VS waves outstanding in the VS table. Counter select must be set to MAX mode + GE_PERFCOUNT_SEL_VS_THREAD_GROUPS = 0x0000010e, // Count of thread groups issued to the VS (these are Domain Shader Threadgroups). Sensitive to PERF_SEID_IGNORE_MASK + GE_PERFCOUNT_SEL_VSVERT_API_SEND = 0x0000010f, // number of API VS verts sent across the vsvert interface. only valid when tessellation and GS are off. + GE_PERFCOUNT_SEL_VSVERT_DS_SEND = 0x00000110, // number of DS verts sent across the vsvert interface. only valid when GS is off. + GE_PERFCOUNT_SEL_WAIT_FOR_ES_DONE_STALLED = 0x00000111, // GS thread SM is ready to move to the next stage as soon as the ES thread finishes + GE_PERFCOUNT_SEL_WAVEID_STALLED = 0x00000112, // Number of cycles vs waves are stalled waiting for a eop/eopg sync during the draw part of DispatchDraw. + GE_PERFCOUNT_SEL_SPI_VSVERT_VALID = 0x00000113, // number of valid VS verts + GE_PERFCOUNT_SEL_PC_FEORDER_FIFO_FULL = 0x00000114, // Counts the number of clocks PC FE reorder fifo is full + GE_PERFCOUNT_SEL_PC_GE_MANAGER_BUSY = 0x00000115, // Counts the number of clocks the PC Manager logic is busy + GE_PERFCOUNT_SEL_PC_REQ_STALL_SE0 = 0x00000116, // Counts the number of clocks the PC manager request to SE0 is stalled + GE_PERFCOUNT_SEL_PC_REQ_STALL_SE1 = 0x00000117, // Counts the number of clocks the PC manager request to SE1 is stalled + GE_PERFCOUNT_SEL_PC_REQ_STALL_SE2 = 0x00000118, // Counts the number of clocks the PC manager request to SE2 is stalled + GE_PERFCOUNT_SEL_PC_REQ_STALL_SE3 = 0x00000119, // Counts the number of clocks the PC manager request to SE3 is stalled + GE_PERFCOUNT_SEL_PIPE0_TO_PIPE1 = 0x0000011a, // Increments each time the GE pipe switches from pipe0 to pipe1 for anything that comes through the GRBM fifo (draws, events, etc.) + GE_PERFCOUNT_SEL_PIPE1_TO_PIPE0 = 0x0000011b, // Increments each time the GE pipe switches from pipe0 to pipe1 for anything that comes through the GRBM fifo (draws, events, etc.) + GE_PERFCOUNT_SEL_DMA_RETURN_SIZE_CL0 = 0x0000011c, // Increments by 64 bytes each time data is returned to the DMAs CL0 fifo + GE_PERFCOUNT_SEL_DMA_RETURN_SIZE_CL1 = 0x0000011d, // Increments by 64 bytes each time data is returned to the DMAs CL1 fifo + GE_PERFCOUNT_SEL_SPI_GSSUBGRP_EVENT_WINDOW_ACTIVE = 0x0000011e, // number of cycles the event window is active for a GS subgroup event + GE_PERFCOUNT_SEL_BYPASS_FIFO_FULL = 0x0000011f, // counts the number of times the bypass fifo in the frontend logic is full + GE_PERFCOUNT_SEL_HS_INPUT_STALL0 = 0x00000120, // In gen0 and gen1 BC modes the HS input (TG) FIFO hides the LS latency. In gen2 mode the FIFO serves as a buffer, that breaks the back pressure chain, prior to sending HS waves to the SPI. It is not an important counter for gen2. + GE_PERFCOUNT_SEL_HS_INPUT_STALL1 = 0x00000121, // In gen0 and gen1 BC modes the HS input (TG) FIFO hides the LS latency. In gen2 mode the FIFO serves as a buffer, that breaks the back pressure chain, prior to sending HS waves to the SPI. It is not an important counter for gen2. + GE_PERFCOUNT_SEL_PC_SPACE_ZERO = 0x00000122, // GE cannot launch a new wave because the Parameter cache has no space left + GE_PERFCOUNT_SEL_VGT_SE0PA0_CLIPV_STARVED_BUSY = 0x00000123, // PA clipv interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE0PA1_CLIPV_STARVED_BUSY = 0x00000124, // PA clipv interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE1PA0_CLIPV_STARVED_BUSY = 0x00000125, // PA clipv interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE1PA1_CLIPV_STARVED_BUSY = 0x00000126, // PA clipv interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE2PA0_CLIPV_STARVED_BUSY = 0x00000127, // PA clipv interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE2PA1_CLIPV_STARVED_BUSY = 0x00000128, // PA clipv interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE3PA0_CLIPV_STARVED_BUSY = 0x00000129, // PA clipv interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE3PA1_CLIPV_STARVED_BUSY = 0x0000012a, // PA clipv interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE0PA0_CLIPV_FIRSTVERT = 0x0000012b, // First ClipV vert + GE_PERFCOUNT_SEL_VGT_SE0PA1_CLIPV_FIRSTVERT = 0x0000012c, // First ClipV vert + GE_PERFCOUNT_SEL_VGT_SE1PA0_CLIPV_FIRSTVERT = 0x0000012d, // First ClipV vert + GE_PERFCOUNT_SEL_VGT_SE1PA1_CLIPV_FIRSTVERT = 0x0000012e, // First ClipV vert + GE_PERFCOUNT_SEL_VGT_SE2PA0_CLIPV_FIRSTVERT = 0x0000012f, // First ClipV vert + GE_PERFCOUNT_SEL_VGT_SE2PA1_CLIPV_FIRSTVERT = 0x00000130, // First ClipV vert + GE_PERFCOUNT_SEL_VGT_SE3PA0_CLIPV_FIRSTVERT = 0x00000131, // First ClipV vert + GE_PERFCOUNT_SEL_VGT_SE3PA1_CLIPV_FIRSTVERT = 0x00000132, // First ClipV vert + GE_PERFCOUNT_SEL_VGT_SE0PA0_CLIPS_STARVED_BUSY = 0x00000133, // PA clips interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE0PA1_CLIPS_STARVED_BUSY = 0x00000134, // PA clips interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE1PA0_CLIPS_STARVED_BUSY = 0x00000135, // PA clips interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE1PA1_CLIPS_STARVED_BUSY = 0x00000136, // PA clips interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE2PA0_CLIPS_STARVED_BUSY = 0x00000137, // PA clips interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE2PA1_CLIPS_STARVED_BUSY = 0x00000138, // PA clips interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE3PA0_CLIPS_STARVED_BUSY = 0x00000139, // PA clips interface is starved while GE is busy + GE_PERFCOUNT_SEL_VGT_SE3PA1_CLIPS_STARVED_BUSY = 0x0000013a, // PA clips interface is starved while GE is busy + GE_PERFCOUNT_SEL_SENDING_VERT_OR_PRIM_SE0 = 0x0000013b, // This is an efficiency counter for GE_SPI0 transfers. It counts when the GE makes either a vert or a prim transfer to SPI on NGG pipeline + GE_PERFCOUNT_SEL_SENDING_VERT_OR_PRIM_SE1 = 0x0000013c, // This is an efficiency counter for GE_SPI1 transfers. It counts when the GE makes either a vert or a prim transfer to SPI on NGG pipeline +} GE_PERFCOUNTER_SELECT; + +typedef enum GL1A_PERFCOUNTER_SELECT : unsigned int { + GL1A_PERF_SEL_BUSY = 0x00000000, // Number of cycles. Not windowable. + GL1A_PERF_SEL_STALL_GL1C0 = 0x00000001, // count stalled cycles. Not windowable. + GL1A_PERF_SEL_STALL_GL1C1 = 0x00000002, // count stalled cycles. Not windowable. + GL1A_PERF_SEL_STALL_GL1C2 = 0x00000003, // count stalled cycles. Not windowable. + GL1A_PERF_SEL_STALL_GL1C3 = 0x00000004, // count stalled cycles. Not windowable. + GL1A_PERF_SEL_REQUEST_GL1C0 = 0x00000005, // count request cycles. Not windowable. + GL1A_PERF_SEL_REQUEST_GL1C1 = 0x00000006, // count request cycles. Not windowable. + GL1A_PERF_SEL_REQUEST_GL1C2 = 0x00000007, // count request cycles. Not windowable. + GL1A_PERF_SEL_REQUEST_GL1C3 = 0x00000008, // count request cycles. Not windowable. + GL1A_PERF_SEL_MEM_32B_WDS_GL1C0 = 0x00000009, // count # of 32B words of memory xfers. Not windowable. + GL1A_PERF_SEL_MEM_32B_WDS_GL1C1 = 0x0000000a, // count # of 32B words of memory xfers. Not windowable. + GL1A_PERF_SEL_MEM_32B_WDS_GL1C2 = 0x0000000b, // count # of 32B words of memory xfers. Not windowable. + GL1A_PERF_SEL_MEM_32B_WDS_GL1C3 = 0x0000000c, // count # of 32B words of memory xfers. Not windowable. + GL1A_PERF_SEL_IO_32B_WDS_GL1C0 = 0x0000000d, // count # of 32B words of io xfers. Not windowable. + GL1A_PERF_SEL_IO_32B_WDS_GL1C1 = 0x0000000e, // count # of 32B words of io xfers. Not windowable. + GL1A_PERF_SEL_IO_32B_WDS_GL1C2 = 0x0000000f, // count # of 32B words of io xfers. Not windowable. + GL1A_PERF_SEL_IO_32B_WDS_GL1C3 = 0x00000010, // count # of 32B words of io xfers. Not windowable. + GL1A_PERF_SEL_MEM_BURST_COUNT_GL1C0 = 0x00000011, // count # of memory requests. Not windowable. + GL1A_PERF_SEL_MEM_BURST_COUNT_GL1C1 = 0x00000012, // count # of memory requests. Not windowable. + GL1A_PERF_SEL_MEM_BURST_COUNT_GL1C2 = 0x00000013, // count # of memory requests. Not windowable. + GL1A_PERF_SEL_MEM_BURST_COUNT_GL1C3 = 0x00000014, // count # of memory requests. Not windowable. + GL1A_PERF_SEL_IO_BURST_COUNT_GL1C0 = 0x00000015, // count # of io requests. Not windowable. + GL1A_PERF_SEL_IO_BURST_COUNT_GL1C1 = 0x00000016, // count # of io requests. Not windowable. + GL1A_PERF_SEL_IO_BURST_COUNT_GL1C2 = 0x00000017, // count # of io requests. Not windowable. + GL1A_PERF_SEL_IO_BURST_COUNT_GL1C3 = 0x00000018, // count # of io requests. Not windowable. + GL1A_PERF_SEL_ARB_REQUESTS = 0x00000019, // count # of total arbiter requests. Not windowable. + GL1A_PERF_SEL_REQ_INFLIGHT_LEVEL = 0x0000001a, // count # of total arbiter requests. Not windowable. + GL1A_PERF_SEL_STALL_RET_CONFLICT_GL1C0 = 0x0000001b, // count stalled return cycles. Not windowable. + GL1A_PERF_SEL_STALL_RET_CONFLICT_GL1C1 = 0x0000001c, // count stalled return cycles. Not windowable. + GL1A_PERF_SEL_STALL_RET_CONFLICT_GL1C2 = 0x0000001d, // count stalled return cycles. Not windowable. + GL1A_PERF_SEL_STALL_RET_CONFLICT_GL1C3 = 0x0000001e, // count stalled return cycles. Not windowable. + GL1A_PERF_SEL_CYCLE = 0x0000001f, // Number of cycles. Not windowable. +} GL1A_PERFCOUNTER_SELECT; + +typedef enum GL1C_PERFCOUNTER_SELECT : unsigned int { + GL1C_PERF_SEL_CYCLE = 0x00000000, // Number of cycles. Not windowable. + GL1C_PERF_SEL_BUSY = 0x00000001, // Number of cycles with a request pending. Not Windowed + GL1C_PERF_SEL_STARVE = 0x00000002, // Number of cycles without a pending request from the GL1A. Windowed. + GL1C_PERF_SEL_ARB_RET_LEVEL = 0x00000003, // The sum of the number of requests sent to the GL1A for output arbitration in flight. Average GL1A return arbitration latency = GL1C_PERF_SEL_GL1A_RET_LEVEL/GL1C_PERF_SEL_REQ + GL1C_PERF_SEL_GL2_REQ_READ = 0x00000004, // Sum of GL1C_PERF_SEL_GL2_REQ_READ_32B, GL1C_PERF_SEL_GL2_REQ_READ_64B, GL1C_PERF_SEL_GL2_REQ_READ_128B + GL1C_PERF_SEL_GL2_REQ_READ_128B = 0x00000005, // Reads requesting a 128B return from GL2 + GL1C_PERF_SEL_GL2_REQ_READ_32B = 0x00000006, // Reads requesting a 32B return from GL2 + GL1C_PERF_SEL_GL2_REQ_READ_64B = 0x00000007, // Reads requesting a 64B return from GL2 + GL1C_PERF_SEL_GL2_REQ_READ_LATENCY = 0x00000008, // Cycles in flight for reads, atomics w/ return, nop_rtn0 + GL1C_PERF_SEL_GL2_REQ_WRITE = 0x00000009, // Sum of GL1C_PERF_SEL_GL2_REQ_WRITE_32B, GL1C_PERF_SEL_GL2_REQ_WRITE_64B + GL1C_PERF_SEL_GL2_REQ_WRITE_32B = 0x0000000a, // Writes 32B in size to GL2 + GL1C_PERF_SEL_GL2_REQ_WRITE_64B = 0x0000000b, // Writes 64B in size to GL2 + GL1C_PERF_SEL_GL2_REQ_WRITE_LATENCY = 0x0000000c, // Cycles in flight for writes, atomics w/o return, nop_ack + GL1C_PERF_SEL_GL2_REQ_PREFETCH = 0x0000000d, // Count of 32B chunks of data prefetched via sector or line fills + GL1C_PERF_SEL_REQ = 0x0000000e, // Read, writes, atomics, nop. Invalids are not counted as requests. + GL1C_PERF_SEL_REQ_ATOMIC_WITH_RET = 0x0000000f, // Count of atomic requests with return + GL1C_PERF_SEL_REQ_ATOMIC_WITHOUT_RET = 0x00000010, // Count of atomic requests without returns + GL1C_PERF_SEL_REQ_SHADER_INV = 0x00000011, // Count of client invalidation requests + GL1C_PERF_SEL_REQ_MISS = 0x00000012, // Count of requests that miss in the cache. Writes and atomics always miss. Partial miss counts as miss. + GL1C_PERF_SEL_REQ_NOP_ACK = 0x00000013, // Count of nops that require an ack + GL1C_PERF_SEL_REQ_NOP_RTN0 = 0x00000014, // Count of nops that require a return + GL1C_PERF_SEL_REQ_READ = 0x00000015, // Sum of REQ_READ_32B, REQ_READ_64B, REQ_READ_128B + GL1C_PERF_SEL_REQ_READ_128B = 0x00000016, // Count of read requests for 128B of data + GL1C_PERF_SEL_REQ_READ_32B = 0x00000017, // Count of read requests for 32B of data + GL1C_PERF_SEL_REQ_READ_64B = 0x00000018, // Count of read requests for 64B of data + GL1C_PERF_SEL_REQ_READ_POLICY_HIT_EVICT = 0x00000019, // Count of read requests that can hit in the cache, but then must immediately invalidate the line + GL1C_PERF_SEL_REQ_READ_POLICY_HIT_LRU = 0x0000001a, // Count of read requests that have normal cache operation + GL1C_PERF_SEL_REQ_READ_POLICY_MISS_EVICT = 0x0000001b, // Count of requests that cannot hit in the cache, and must immediately invalidate the line + GL1C_PERF_SEL_REQ_WRITE = 0x0000001c, // Sum of REQ_WRITE_32B, REQ_WRITE_64B + GL1C_PERF_SEL_REQ_WRITE_32B = 0x0000001d, // Count of write requests containing 32B of data + GL1C_PERF_SEL_REQ_WRITE_64B = 0x0000001e, // Count of write requests containing 64B of data + GL1C_PERF_SEL_STALL_GL2_GL1 = 0x0000001f, // Number of cycles the cache was stalled due to backpressure from the GL2 + GL1C_PERF_SEL_STALL_LFIFO_FULL = 0x00000020, // Number of cycles the latency fifo was full. + GL1C_PERF_SEL_STALL_NO_AVAILABLE_ACK_ALLOC = 0x00000021, // Number of cycles the cache was stalled due to the lack of unused uncached write/atomic (ACK) tracking entries. + GL1C_PERF_SEL_STALL_NOTHING_REPLACEABLE = 0x00000022, // Number of cycles the cache was stalled due to a cache miss and unavailability of a replaceable cache line. + GL1C_PERF_SEL_STALL_GCR_INV = 0x00000023, // Number of cycles stalled while performing a GCR invalidate + GL1C_PERF_SEL_REQ_CLIENT0 = 0x00000024, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT1 = 0x00000025, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT2 = 0x00000026, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT3 = 0x00000027, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT4 = 0x00000028, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT5 = 0x00000029, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT6 = 0x0000002a, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT7 = 0x0000002b, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT8 = 0x0000002c, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT9 = 0x0000002d, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT10 = 0x0000002e, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT11 = 0x0000002f, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT12 = 0x00000030, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT13 = 0x00000031, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT14 = 0x00000032, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT15 = 0x00000033, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT16 = 0x00000034, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT17 = 0x00000035, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT18 = 0x00000036, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT19 = 0x00000037, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT20 = 0x00000038, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT21 = 0x00000039, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT22 = 0x0000003a, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT23 = 0x0000003b, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT24 = 0x0000003c, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT25 = 0x0000003d, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT26 = 0x0000003e, // Count of per client requests + GL1C_PERF_SEL_REQ_CLIENT27 = 0x0000003f, // Count of per client requests +} GL1C_PERFCOUNTER_SELECT; + +typedef enum GL2A_PERFCOUNTER_SELECT : unsigned int { + GL2A_PERF_SEL_NONE = 0x00000000, // Don't count anything. + GL2A_PERF_SEL_CYCLE = 0x00000001, // Number of cycles. Not windowable. + GL2A_PERF_SEL_BUSY = 0x00000002, // Number of cycles we have a request pending. Not windowable. + GL2A_PERF_SEL_REQ_GL2C0 = 0x00000003, // Number of requests sent to GL2C0. This should report the same thing as GL2C_PERF_SEL_REQ in the corresponding GL2C in the long run. It is only offered to create a deterministic counter in the GL2A so that the counters may be sanity tested. + GL2A_PERF_SEL_REQ_GL2C1 = 0x00000004, // Number of requests sent to GL2C1. This should report the same thing as GL2C_PERF_SEL_REQ in the corresponding GL2C in the long run. It is only offered to create a deterministic counter in the GL2A so that the counters may be sanity tested. + GL2A_PERF_SEL_REQ_GL2C2 = 0x00000005, // Number of requests sent to GL2C2. This should report the same thing as GL2C_PERF_SEL_REQ in the corresponding GL2C in the long run. It is only offered to create a deterministic counter in the GL2A so that the counters may be sanity tested. + GL2A_PERF_SEL_REQ_GL2C3 = 0x00000006, // Number of requests sent to GL2C3. This should report the same thing as GL2C_PERF_SEL_REQ in the corresponding GL2C in the long run. It is only offered to create a deterministic counter in the GL2A so that the counters may be sanity tested. + GL2A_PERF_SEL_REQ_GL2C4 = 0x00000007, // Reserved. + GL2A_PERF_SEL_REQ_GL2C5 = 0x00000008, // Reserved. + GL2A_PERF_SEL_REQ_GL2C6 = 0x00000009, // Reserved. + GL2A_PERF_SEL_REQ_GL2C7 = 0x0000000a, // Reserved. + GL2A_PERF_SEL_REQ_HI_PRIO_GL2C0 = 0x0000000b, // Number of high priority requests sent to GL2C0. + GL2A_PERF_SEL_REQ_HI_PRIO_GL2C1 = 0x0000000c, // Number of high priority requests sent to GL2C1. + GL2A_PERF_SEL_REQ_HI_PRIO_GL2C2 = 0x0000000d, // Number of high priority requests sent to GL2C2. + GL2A_PERF_SEL_REQ_HI_PRIO_GL2C3 = 0x0000000e, // Number of high priority requests sent to GL2C3. + GL2A_PERF_SEL_REQ_HI_PRIO_GL2C4 = 0x0000000f, // Reserved. + GL2A_PERF_SEL_REQ_HI_PRIO_GL2C5 = 0x00000010, // Reserved. + GL2A_PERF_SEL_REQ_HI_PRIO_GL2C6 = 0x00000011, // Reserved. + GL2A_PERF_SEL_REQ_HI_PRIO_GL2C7 = 0x00000012, // Reserved. + GL2A_PERF_SEL_REQ_BURST_GL2C0 = 0x00000013, // Number of bursts sent to GL2C0, including single cycle request + GL2A_PERF_SEL_REQ_BURST_GL2C1 = 0x00000014, // Number of bursts sent to GL2C1, including single cycle request. + GL2A_PERF_SEL_REQ_BURST_GL2C2 = 0x00000015, // Number of bursts sent to GL2C2, including single cycle request. + GL2A_PERF_SEL_REQ_BURST_GL2C3 = 0x00000016, // Number of bursts sent to GL2C3, including single cycle request. + GL2A_PERF_SEL_REQ_BURST_GL2C4 = 0x00000017, // Reserved. + GL2A_PERF_SEL_REQ_BURST_GL2C5 = 0x00000018, // Reserved. + GL2A_PERF_SEL_REQ_BURST_GL2C6 = 0x00000019, // Reserved. + GL2A_PERF_SEL_REQ_BURST_GL2C7 = 0x0000001a, // Reserved. + GL2A_PERF_SEL_REQ_STALL_GL2C0 = 0x0000001b, // Number of cycles no requests could be sent to GL2C0 because its fifos were expected to be full. + GL2A_PERF_SEL_REQ_STALL_GL2C1 = 0x0000001c, // Number of cycles no requests could be sent to GL2C1 because its fifos were expected to be full. + GL2A_PERF_SEL_REQ_STALL_GL2C2 = 0x0000001d, // Number of cycles no requests could be sent to GL2C2 because its fifos were expected to be full. + GL2A_PERF_SEL_REQ_STALL_GL2C3 = 0x0000001e, // Number of cycles no requests could be sent to GL2C3 because its fifos were expected to be full. + GL2A_PERF_SEL_REQ_STALL_GL2C4 = 0x0000001f, // Reserved. + GL2A_PERF_SEL_REQ_STALL_GL2C5 = 0x00000020, // Reserved. + GL2A_PERF_SEL_REQ_STALL_GL2C6 = 0x00000021, // Reserved. + GL2A_PERF_SEL_REQ_STALL_GL2C7 = 0x00000022, // Reserved. + GL2A_PERF_SEL_RTN_STALL_GL2C0 = 0x00000023, // Number of cycles no return could be issued from GL2C0 because its execution block has to stall for other logic to access ram. + GL2A_PERF_SEL_RTN_STALL_GL2C1 = 0x00000024, // Number of cycles no return could be issued from GL2C1 because its execution block has to stall for other logic to access ram. + GL2A_PERF_SEL_RTN_STALL_GL2C2 = 0x00000025, // Number of cycles no return could be issued from GL2C2 because its execution block has to stall for other logic to access ram. + GL2A_PERF_SEL_RTN_STALL_GL2C3 = 0x00000026, // Number of cycles no return could be issued from GL2C3 because its execution block has to stall for other logic to access ram. + GL2A_PERF_SEL_RTN_STALL_GL2C4 = 0x00000027, // Reserved. + GL2A_PERF_SEL_RTN_STALL_GL2C5 = 0x00000028, // Reserved. + GL2A_PERF_SEL_RTN_STALL_GL2C6 = 0x00000029, // Reserved. + GL2A_PERF_SEL_RTN_STALL_GL2C7 = 0x0000002a, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT0 = 0x0000002b, // Number of returns sent to client0. Not windowable. + GL2A_PERF_SEL_RTN_CLIENT1 = 0x0000002c, // Number of returns sent to client1. Not windowable. + GL2A_PERF_SEL_RTN_CLIENT2 = 0x0000002d, // Number of returns sent to client2. Not windowable. + GL2A_PERF_SEL_RTN_CLIENT3 = 0x0000002e, // Number of returns sent to client3. Not windowable. + GL2A_PERF_SEL_RTN_CLIENT4 = 0x0000002f, // Number of returns sent to client4. Not windowable. + GL2A_PERF_SEL_RTN_CLIENT5 = 0x00000030, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT6 = 0x00000031, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT7 = 0x00000032, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT8 = 0x00000033, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT9 = 0x00000034, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT10 = 0x00000035, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT11 = 0x00000036, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT12 = 0x00000037, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT13 = 0x00000038, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT14 = 0x00000039, // Reserved. + GL2A_PERF_SEL_RTN_CLIENT15 = 0x0000003a, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT0 = 0x0000003b, // Number of cycles that returns is avaliable to client0 but not granted due to arbitration collision. Not windowable. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT1 = 0x0000003c, // Number of cycles that returns is avaliable to client1 but not granted due to arbitration collision. Not windowable. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT2 = 0x0000003d, // Number of cycles that returns is avaliable to client2 but not granted due to arbitration collision. Not windowable. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT3 = 0x0000003e, // Number of cycles that returns is avaliable to client3 but not granted due to arbitration collision. Not windowable. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT4 = 0x0000003f, // Number of cycles that returns is avaliable to client4 but not granted due to arbitration collision. Not windowable. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT5 = 0x00000040, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT6 = 0x00000041, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT7 = 0x00000042, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT8 = 0x00000043, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT9 = 0x00000044, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT10 = 0x00000045, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT11 = 0x00000046, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT12 = 0x00000047, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT13 = 0x00000048, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT14 = 0x00000049, // Reserved. + GL2A_PERF_SEL_RTN_ARB_COLLISION_CLIENT15 = 0x0000004a, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT0 = 0x0000004b, // Number of bursts from client 0, including single cycle request. + GL2A_PERF_SEL_REQ_BURST_CLIENT1 = 0x0000004c, // Number of bursts from client 1, including single cycle request. + GL2A_PERF_SEL_REQ_BURST_CLIENT2 = 0x0000004d, // Number of bursts from client 2, including single cycle request. + GL2A_PERF_SEL_REQ_BURST_CLIENT3 = 0x0000004e, // Number of bursts from client 3, including single cycle request. + GL2A_PERF_SEL_REQ_BURST_CLIENT4 = 0x0000004f, // Number of bursts from client 4, including single cycle request. + GL2A_PERF_SEL_REQ_BURST_CLIENT5 = 0x00000050, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT6 = 0x00000051, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT7 = 0x00000052, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT8 = 0x00000053, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT9 = 0x00000054, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT10 = 0x00000055, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT11 = 0x00000056, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT12 = 0x00000057, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT13 = 0x00000058, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT14 = 0x00000059, // Reserved. + GL2A_PERF_SEL_REQ_BURST_CLIENT15 = 0x0000005a, // Reserved. +} GL2A_PERFCOUNTER_SELECT; + +typedef enum GL2C_PERFCOUNTER_SELECT : unsigned int { + GL2C_PERF_SEL_NONE = 0x00000000, // Don't count anything. + GL2C_PERF_SEL_CYCLE = 0x00000001, // Number of cycles. Not windowable. + GL2C_PERF_SEL_BUSY = 0x00000002, // Number of cycles we have a request pending. Not windowable. + GL2C_PERF_SEL_REQ = 0x00000003, // Number of requests of all types. This is measured at the tag block. This may be more than the number of requests arriving at the GL2C, but it is a good indication of the total amount of work that needs to be performed. + GL2C_PERF_SEL_VOL_REQ = 0x00000004, // Number of volatile requests. This is measured at the tag block. This may be more than the number of requests arriving at the GL2C, but it is a good indication of the total amount of work that needs to be performed. + GL2C_PERF_SEL_HIGH_PRIORITY_REQ = 0x00000005, // Number of requests of high priority type. This is measured at the tag block. + GL2C_PERF_SEL_READ = 0x00000006, // Number of read requests, including compressed reads and metadata reads. This is measured at output_fifos block. + GL2C_PERF_SEL_WRITE = 0x00000007, // Number of read requests, including compressed reads and metadata reads. This is measured at output_fifos block. + GL2C_PERF_SEL_ATOMIC = 0x00000008, // Number of atomic requests of all types. This is measured at output_fifos block. + GL2C_PERF_SEL_NOP_ACK = 0x00000009, // Number of NOP_ACK requests, including no_write_ack created by CM. This is measured at output_fifos block. + GL2C_PERF_SEL_NOP_RTN0 = 0x0000000a, // Number of NOP_RTN0 requests. This is measured at output_fifos block. + GL2C_PERF_SEL_PROBE = 0x0000000b, // Number of probe requests. Not windowable. + GL2C_PERF_SEL_PROBE_ALL = 0x0000000c, // Number of external probe requests with with EA_GL2C_preq_all== 1. Not windowable. + GL2C_PERF_SEL_INTERNAL_PROBE = 0x0000000d, // Number of self-probes spawned by GL2C for CC writes/atomic operations. Not windowable. + GL2C_PERF_SEL_COMPRESSED_READ_REQ = 0x0000000e, // Number of compressed requests. This includes requests that read compressed data(compressed read, cm compressed read and prefetch compressed read). Metadata requests are not included. This is measured at the tag block. + GL2C_PERF_SEL_METADATA_READ_REQ = 0x0000000f, // Number of metadata requests. This is measured at the tag block. + GL2C_PERF_SEL_CLIENT0_REQ = 0x00000010, // Number of cycles client0 sent a request to this GL2C. + GL2C_PERF_SEL_CLIENT1_REQ = 0x00000011, // Number of cycles client1 sent a request to this GL2C. + GL2C_PERF_SEL_CLIENT2_REQ = 0x00000012, // Number of cycles client2 sent a request to this GL2C. + GL2C_PERF_SEL_CLIENT3_REQ = 0x00000013, // Number of cycles client3 sent a request to this GL2C. + GL2C_PERF_SEL_CLIENT4_REQ = 0x00000014, // Number of cycles client4 sent a request to this GL2C. + GL2C_PERF_SEL_CLIENT5_REQ = 0x00000015, // Unused. + GL2C_PERF_SEL_CLIENT6_REQ = 0x00000016, // Unused. + GL2C_PERF_SEL_CLIENT7_REQ = 0x00000017, // Unused. + GL2C_PERF_SEL_C_RW_S_REQ = 0x00000018, // The number of C_RW_S requests. This is measured at the tag block. + GL2C_PERF_SEL_C_RW_US_REQ = 0x00000019, // The number of C_RW_US requests. This is measured at the tag block. + GL2C_PERF_SEL_C_RO_S_REQ = 0x0000001a, // The number of C_RO_S requests. This is measured at the tag block. + GL2C_PERF_SEL_C_RO_US_REQ = 0x0000001b, // The number of C_RO_US requests. This is measured at the tag block. + GL2C_PERF_SEL_UC_REQ = 0x0000001c, // The number of UnCached requests. This is measured at the tag block. + GL2C_PERF_SEL_LRU_REQ = 0x0000001d, // Number of lru requests. This is measured at the tag block. + GL2C_PERF_SEL_STREAM_REQ = 0x0000001e, // Number of stream requests. This is measured at the tag block. + GL2C_PERF_SEL_BYPASS_REQ = 0x0000001f, // Number of bypass requests. This is measured at the tag block. + GL2C_PERF_SEL_NOA_REQ = 0x00000020, // Number of NOA requests. This is measured at the tag block. + GL2C_PERF_SEL_SHARED_REQ = 0x00000021, // The number of shared requests(Cacheable & C_R*_S & !IO). This is measured at the tag block. + GL2C_PERF_SEL_HIT = 0x00000022, // Number of cache hits. + GL2C_PERF_SEL_MISS = 0x00000023, // Number of cache misses. UC reads count as misses. + GL2C_PERF_SEL_FULL_HIT = 0x00000024, // Number of full cache sector hits. + GL2C_PERF_SEL_PARTIAL_32B_HIT = 0x00000025, // Number of 32 byte cache sector hits. This measure excludes a full cache sector hit. + GL2C_PERF_SEL_PARTIAL_64B_HIT = 0x00000026, // Number of 64 byte cache sector hits. This measure excludes a full cache sector hit. + GL2C_PERF_SEL_PARTIAL_96B_HIT = 0x00000027, // Number of 96 byte cache sector hits. This measure excludes a full cache sector hit. + GL2C_PERF_SEL_DEWRITE_ALLOCATE_HIT = 0x00000028, // Number of times a read was performed on a cache line that had only been written into before. This can only occur once for the life of a cache line. + GL2C_PERF_SEL_FULLY_WRITTEN_HIT = 0x00000029, // Number of times a 32-byte read from the EA was avoided because the cache sector was already fully written with data. This can only occur once for the life of a cache sector. + GL2C_PERF_SEL_UNCACHED_WRITE = 0x0000002a, // Number of uncached write/atomic requests written back to main memory. + GL2C_PERF_SEL_WRITEBACK = 0x0000002b, // Number of dirty lines written back to main memory. + GL2C_PERF_SEL_NORMAL_WRITEBACK = 0x0000002c, // Number of writebacks due to requests that are not writeback requests. + GL2C_PERF_SEL_EVICT = 0x0000002d, // Number of evictions. Not windowable. + GL2C_PERF_SEL_NORMAL_EVICT = 0x0000002e, // Number of evictions due to requests that are not invalidate or probe requests. + GL2C_PERF_SEL_PROBE_EVICT = 0x0000002f, // Number of evictions/invalidations due to probes. Not windowable. + GL2C_PERF_SEL_REQ_TO_MISS_QUEUE = 0x00000030, // Number of requests are sent to miss queue. + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT0 = 0x00000031, // Number of hit requests passed earlier miss requests in client 0 channel. + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT1 = 0x00000032, // Number of hit requests passed earlier miss requests in client 1 channel. + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT2 = 0x00000033, // Number of hit requests passed earlier miss requests in client 2 channel. + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT3 = 0x00000034, // Number of hit requests passed earlier miss requests in client 3 channel. + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT4 = 0x00000035, // Number of hit requests passed earlier miss requests in client 4 channel. + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT5 = 0x00000036, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT6 = 0x00000037, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT7 = 0x00000038, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT8 = 0x00000039, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT9 = 0x0000003a, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT10 = 0x0000003b, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT11 = 0x0000003c, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT12 = 0x0000003d, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT13 = 0x0000003e, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT14 = 0x0000003f, + GL2C_PERF_SEL_HIT_PASS_MISS_IN_CLIENT15 = 0x00000040, + GL2C_PERF_SEL_READ_32_REQ = 0x00000041, // Number of uncompressed 32 byte read requests. This is measured at the output_fifos block. + GL2C_PERF_SEL_READ_64_REQ = 0x00000042, // Number of uncompressed 64 byte read requests. This is measured at the output_fifos block. + GL2C_PERF_SEL_READ_128_REQ = 0x00000043, // Number of uncompressed 128 byte read requests. This is measured at the output_fifos block. + GL2C_PERF_SEL_WRITE_32_REQ = 0x00000044, // Number of uncompressed 32 byte write requests. This is measured at the output_fifos block. + GL2C_PERF_SEL_WRITE_64_REQ = 0x00000045, // Number of uncompressed 64 byte write requests. This is measured at the output_fifos block. + GL2C_PERF_SEL_COMPRESSED_READ_0_REQ = 0x00000046, // Number of compressed requests that read 0 bytes of compressed data. Metadata requests are not included. This is measured at the output_fifos block. + GL2C_PERF_SEL_COMPRESSED_READ_32_REQ = 0x00000047, // Number of compressed requests that read 32 bytes of compressed data. Metadata requests are not included. This is measured at the output_fifos block. + GL2C_PERF_SEL_COMPRESSED_READ_64_REQ = 0x00000048, // Number of compressed read requests. This includes requests that read 64 byte contiguous or split compressed data. Metadata requests are not included. This is measured at the output_fifos block. + GL2C_PERF_SEL_COMPRESSED_READ_96_REQ = 0x00000049, // Number of compressed read requests. This includes requests that read 96 byte contiguous or split compressed data. Metadata requests are not included. This is measured at the output_fifos block. + GL2C_PERF_SEL_COMPRESSED_READ_128_REQ = 0x0000004a, // Number of compressed read requests. This includes requests that read 128 byte compressed data. Metadata requests are not included. This is measured at the output_fifos block. + GL2C_PERF_SEL_MC_WRREQ = 0x0000004b, // Number of transactions (either 32-byte or 64-byte) going over the GL2C_EA_wrreq interface. Atomics may travel over the same interface and are generally classified as write requests. This does not include probe commands. + GL2C_PERF_SEL_EA_WRREQ_SNOOP = 0x0000004c, // Number of snoop transactions (either 32-byte or 64-byte) going over the GL2C_EA_wrreq interface. + GL2C_PERF_SEL_EA_WRREQ_64B = 0x0000004d, // Number of 64-byte transactions going (64-byte write or CMPSWAP) over the TC_EA_wrreq interface. + GL2C_PERF_SEL_EA_WRREQ_PROBE_COMMAND = 0x0000004e, // Number of probe commands going over the TC_EA_wrreq interface. + GL2C_PERF_SEL_EA_WR_UNCACHED_32B = 0x0000004f, // Number of 32-byte write/atomic going over the TC_EA_wrreq interface due to uncached traffic. Note that CC mtypes can produce uncached requests, and those are included in this. A 64-byte request will be counted as 2 + GL2C_PERF_SEL_MC_WRREQ_STALL = 0x00000050, // Number of cycles a write request was stalled. + GL2C_PERF_SEL_EA_WRREQ_IO_CREDIT_STALL = 0x00000051, // Number of cycles a EA write request was stalled because the interface was out of IO credits. + GL2C_PERF_SEL_EA_WRREQ_GMI_CREDIT_STALL = 0x00000052, // Number of cycles a EA write request was stalled because the interface was out of GMI credits. + GL2C_PERF_SEL_EA_WRREQ_DRAM_CREDIT_STALL = 0x00000053, // Number of cycles a EA write request was stalled because the interface was out of DRAM credits. + GL2C_PERF_SEL_TOO_MANY_EA_WRREQS_STALL = 0x00000054, // Number of cycles the GL2C could not send a EA write request because it already reached its maximum number of pending EA write requests. + GL2C_PERF_SEL_MC_WRREQ_LEVEL = 0x00000055, // The sum of the number of EA write requests in flight. This is primarily meant for measure average EA write latency. Average write latency = GL2C_PERF_SEL_MC_WRREQ_LEVEL/GL2C_PERF_SEL_MC_WRREQ. + GL2C_PERF_SEL_EA_ATOMIC = 0x00000056, // Number of transactions going over the TC_EA_wrreq interface that are actually atomic requests. + GL2C_PERF_SEL_EA_ATOMIC_LEVEL = 0x00000057, // The sum of the number of EA atomics in flight. This is primarily meant for measure average EA atomic latency. Average atomic latency = GL2C_PERF_SEL_EA_WRREQ_ATOMIC_LEVEL/GL2C_PERF_SEL_EA_WRREQ_ATOMIC. + GL2C_PERF_SEL_MC_RDREQ = 0x00000058, // Number of GL2C/EA read requests (either 32-byte or 64-byte or 128-byte). + GL2C_PERF_SEL_EA_RDREQ_SNOOP = 0x00000059, // Number of GL2C/EA snoop read requests (either 32-byte or 64-byte or 128-byte). + GL2C_PERF_SEL_EA_RDREQ_SPLIT = 0x0000005a, // Number of GL2C/EA read requests split due to non-contiguous sectors. + GL2C_PERF_SEL_EA_RDREQ_32B = 0x0000005b, // Number of 32-byte GL2C/EA read requests + GL2C_PERF_SEL_EA_RDREQ_64B = 0x0000005c, // Number of 64-byte GL2C/EA read requests + GL2C_PERF_SEL_EA_RDREQ_96B = 0x0000005d, // Number of 96-byte GL2C/EA read requests + GL2C_PERF_SEL_EA_RDREQ_128B = 0x0000005e, // Number of 128-byte GL2C/EA read requests + GL2C_PERF_SEL_EA_RD_UNCACHED_32B = 0x0000005f, // Number of 32-byte GL2C/EA read due to uncached traffic. A 64-byte request will be counted as 2; 96-byte as 3 and 128-byte as 4. + GL2C_PERF_SEL_EA_RD_MDC_32B = 0x00000060, // Number of 32-byte GL2C/EA read due to MDC traffic. A 64-byte request will be counted as 2 + GL2C_PERF_SEL_EA_RD_COMPRESSED_32B = 0x00000061, // Number of 32-byte GL2C/EA read due to compressed data reads. This does not include MDC traffic. A 64-byte request will be counted as 2; 96-byte as 3 and 128-byte as 4. + GL2C_PERF_SEL_EA_RDREQ_IO_CREDIT_STALL = 0x00000062, // Number of cycles there was a stall because the read request interface was out of IO credits. Stalls occur regardless of whether a read needed to be performed or not. + GL2C_PERF_SEL_EA_RDREQ_GMI_CREDIT_STALL = 0x00000063, // Number of cycles there was a stall because the read request interface was out of GMI credits. Stalls occur regardless of whether a read needed to be performed or not. + GL2C_PERF_SEL_EA_RDREQ_DRAM_CREDIT_STALL = 0x00000064, // Number of cycles there was a stall because the read request interface was out of DRAM credits. Stalls occur regardless of whether a read needed to be performed or not. + GL2C_PERF_SEL_MC_RDREQ_LEVEL = 0x00000065, // The sum of the number of GL2C/EA read requests in flight. This is primarily meant for measure average EA read latency. Average read latency = GL2C_PERF_SEL_MC_RDREQ_LEVEL/GL2C_PERF_SEL_MC_RDREQ. + GL2C_PERF_SEL_EA_RDREQ_DRAM = 0x00000066, // Number of GL2C/EA read requests (either 32-byte, 64-byte, 96-byte or 128-byte) destined for DRAM (MC). + GL2C_PERF_SEL_EA_WRREQ_DRAM = 0x00000067, // Number of GL2C/EA write requests (either 32-byte, 64-byte, 96-byte or 128-byte) destined for DRAM (MC). + GL2C_PERF_SEL_EA_RDREQ_DRAM_32B = 0x00000068, // Number of 32-byte GL2C/EA read due to dram traffic. A 64-byte request will be counted as 2; 96-byte as 3 and 128-byte as 4. + GL2C_PERF_SEL_EA_WRREQ_DRAM_32B = 0x00000069, // Number of 32-byte GL2C/EA write due to dram traffic. A 64-byte request will be counted as 2. + GL2C_PERF_SEL_ONION_READ = 0x0000006a, // Number of read requests to GL2 onion VC (applies only in BC mode, bc=1 and spa=1 and snoop=1 and io=0). + GL2C_PERF_SEL_ONION_WRITE = 0x0000006b, // Number of write requests to GL2 onion VC (applies only in BC mode, bc=1 and spa=1 and snoop=1 and io=0). + GL2C_PERF_SEL_IO_READ = 0x0000006c, // Number of read requests to GL2 IO VC. + GL2C_PERF_SEL_IO_WRITE = 0x0000006d, // Number of write requests to GL2 IO VC. + GL2C_PERF_SEL_GARLIC_READ = 0x0000006e, // Number of read requests to GL2 garlic VC (~IO & ~ONION). + GL2C_PERF_SEL_GARLIC_WRITE = 0x0000006f, // Number of write requests to GL2 garlic VC (~IO & ~ONION). + GL2C_PERF_SEL_EA_OUTSTANDING = 0x00000070, // Number of cycles when there is any outstanding EA request. + GL2C_PERF_SEL_LATENCY_FIFO_FULL = 0x00000071, // Number of cycles the latency fifo was full. + GL2C_PERF_SEL_SRC_FIFO_FULL = 0x00000072, // Number of cycles the src fifo was expected to be full as measured at the IB block. + GL2C_PERF_SEL_TAG_STALL = 0x00000073, // Number of cycles the normal request pipeline in the tag was stalled for any reason. Normally, stalls of this nature are measured exactly from one point the pipeline, but that is not the case for this counter. Probes can stall the pipeline at a variety of places, and there is no single point that can reasonably measure the total stalls accurately. + GL2C_PERF_SEL_TAG_WRITEBACK_FIFO_FULL_STALL = 0x00000074, // Number of cycles the normal request pipeline in the tag was stalled due to the writeback fifo within the tag block being full. + GL2C_PERF_SEL_TAG_MISS_NOTHING_REPLACEABLE_STALL = 0x00000075, // Number of cycles the normal request pipeline in the tag was stalled due to a cache miss and unavailabiliyt of a replaceable cache line. + GL2C_PERF_SEL_TAG_UNCACHED_WRITE_ATOMIC_FIFO_FULL_STALL = 0x00000076, // Number of cycles the normal request pipeline in the tag was stalled due to the uncached write/atomic fifo being full. + GL2C_PERF_SEL_TAG_NO_UNCACHED_WRITE_ATOMIC_ENTRIES_STALL = 0x00000077, // Number of cycles the normal request pipeline in the tag was stalled due to the lack of unused uncached write/atomic tracking entries. + GL2C_PERF_SEL_TAG_PROBE_STALL = 0x00000078, // Number of cycles the normal request pipeline in the tag was stalled due to the presence of a probe. + GL2C_PERF_SEL_TAG_PROBE_FILTER_STALL = 0x00000079, // Number of cycles the normal request pipeline in the tag was stalled due to the probe filter being in an inappropriate state. + GL2C_PERF_SEL_TAG_PROBE_FIFO_FULL_STALL = 0x0000007a, // Number of cycles the normal request pipeline in the tag was stalled due to the probe fifo begin full. + GL2C_PERF_SEL_TAG_READ_DST_STALL = 0x0000007b, // Number of cycles the normal request pipeline in the tag was stalled due to the outstanding in-flight requests on an invalided cache line. + GL2C_PERF_SEL_READ_RETURN_TIMEOUT = 0x0000007c, // Number of bubbles requests sent to the GL2A because a EA read return waited so long for a cache ram port that it timed out. + GL2C_PERF_SEL_WRITEBACK_READ_TIMEOUT = 0x0000007d, // Number of bubbles requests sent to the GL2A because a writeback waited so long for a cache ram port that it timed out. + GL2C_PERF_SEL_READ_RETURN_FULL_BUBBLE = 0x0000007e, // Number of bubbles requests sent to the GL2A to prevent the EA read return fifos from overflowing. Not windowable. + GL2C_PERF_SEL_BUBBLE = 0x0000007f, // Total number of bubble requests sent to the GL2A + GL2C_PERF_SEL_IB_REQ = 0x00000080, // Number of requests through the IB. This measures the raw request count from graphics clients going to this GL2C. + GL2C_PERF_SEL_IB_STALL = 0x00000081, // Number of cycles the IB output was stalled. + GL2C_PERF_SEL_IB_TAG_STALL = 0x00000082, // Number of cycles the IB output was stalled on the tag. + GL2C_PERF_SEL_IB_CM_STALL = 0x00000083, // Number of cycles the IB output was stalled on the mdc. + GL2C_PERF_SEL_RETURN_ACK = 0x00000084, // Number of times only an ack was sent on the return bus. + GL2C_PERF_SEL_RETURN_DATA = 0x00000085, // Number of times only data was sent on the return bus. + GL2C_PERF_SEL_EA_RDRET_NACK = 0x00000086, // The number of EA read returns that were nacked. + GL2C_PERF_SEL_EA_WRRET_NACK = 0x00000087, // The number of EA write returns that were nacked. + GL2C_PERF_SEL_GL2A_LEVEL = 0x00000088, // The sum of the number of requests sent to the GL2A for output arbitration in flight. Average GL2A arbitration latency = GL2C_PERF_SEL_GL2A_LEVEL/GL2C_PERF_SEL_REQ. + GL2C_PERF_SEL_PROBE_FILTER_DISABLE_TRANSITION = 0x00000089, // Number of times the probe filter went from enabled to disabled. + GL2C_PERF_SEL_PROBE_FILTER_DISABLED = 0x0000008a, // Number of cycles the probe filter was disabled. The GL2C can get probes during these cycles. Not windowable. + GL2C_PERF_SEL_ALL_TC_OP_WB_OR_INV_START = 0x0000008b, // Number of gcr writeback or invalidate all requests started. + GL2C_PERF_SEL_ALL_TC_OP_WB_OR_INV_VOL_START = 0x0000008c, // Number of gcr writeback or invalidate all volatile requests started. + GL2C_PERF_SEL_GCR_INV = 0x0000008d, // Number of gcr requests has invalidate field set. + GL2C_PERF_SEL_GCR_WB = 0x0000008e, // Number of gcr requests has writeback field set. + GL2C_PERF_SEL_GCR_DISCARD = 0x0000008f, // Number of gcr requests has discard field set. + GL2C_PERF_SEL_GCR_RANGE = 0x00000090, // Number of gcr requests are range based. + GL2C_PERF_SEL_GCR_ALL = 0x00000091, // Number of gcr requests are targeting on all cache lines. + GL2C_PERF_SEL_GCR_VOL = 0x00000092, // Number of gcr requests are targeting on all volatile cache lines. + GL2C_PERF_SEL_GCR_UNSHARED = 0x00000093, // Number of gcr requests has unshared field set. + GL2C_PERF_SEL_GCR_MDC_INV = 0x00000094, // Number of gcr requests has metadata invalidation field set. + GL2C_PERF_SEL_GCR_GL2_INV_ALL = 0x00000095, // Number of gcr invalidate all gl2 requests. + GL2C_PERF_SEL_GCR_GL2_WB_ALL = 0x00000096, // Number of gcr writeback all gl2 requests. + GL2C_PERF_SEL_GCR_MDC_INV_ALL = 0x00000097, // Number of gcr metadata cache invalidate all requests. + GL2C_PERF_SEL_GCR_GL2_INV_RANGE = 0x00000098, // Number of gcr invalidate gl2 ranged requests. + GL2C_PERF_SEL_GCR_GL2_WB_RANGE = 0x00000099, // Number of gcr writeback gl2 ranged requests. + GL2C_PERF_SEL_GCR_GL2_WB_INV_RANGE = 0x0000009a, // Number of gcr writeback and invalidate gl2 ranged requests. + GL2C_PERF_SEL_GCR_MDC_INV_RANGE = 0x0000009b, // Number of gcr metadata cache invalidate ranged requests. + GL2C_PERF_SEL_ALL_GCR_INV_EVICT = 0x0000009c, // Number of cache line evictions/invalidations due to gcr request. + GL2C_PERF_SEL_ALL_GCR_INV_VOL_EVICT = 0x0000009d, // Number of volatile cache line evictions/invalidations due to gcr request. + GL2C_PERF_SEL_ALL_GCR_WB_OR_INV_CYCLE = 0x0000009e, // Number of cycles spent performing gcr requests in tag pipeline. + GL2C_PERF_SEL_ALL_GCR_WB_OR_INV_VOL_CYCLE = 0x0000009f, // Number of cycles spent performing gcr volatile requests in tag pipeline. + GL2C_PERF_SEL_ALL_GCR_WB_WRITEBACK = 0x000000a0, // Number of cache line writeback due to gcr request. + GL2C_PERF_SEL_GCR_INVL2_VOL_CYCLE = 0x000000a1, // Number of cycles spent performing gcr INVL2_VOL requests in tag pipeline. + GL2C_PERF_SEL_GCR_INVL2_VOL_EVICT = 0x000000a2, // Number of cache line evictions/invalidations due to INVL2_VOL requests. + GL2C_PERF_SEL_GCR_INVL2_VOL_START = 0x000000a3, // Number of gcr INVL2_VOL requests. + GL2C_PERF_SEL_GCR_WBL2_VOL_CYCLE = 0x000000a4, // Number of cycles spent performing gcr WBL2_VOL requests in tag pipeline. + GL2C_PERF_SEL_GCR_WBL2_VOL_EVICT = 0x000000a5, // Number of cache line evictions/invalidations due to WBL2_VOL requests. + GL2C_PERF_SEL_GCR_WBL2_VOL_START = 0x000000a6, // Number of gcr WBL2_VOL requests. + GL2C_PERF_SEL_GCR_WBINVL2_CYCLE = 0x000000a7, // Number of cycles spent performing gcr WBINVL2 requests in tag pipeline. + GL2C_PERF_SEL_GCR_WBINVL2_EVICT = 0x000000a8, // Number of cache line evictions/invalidations due to WBINVL2 requests. + GL2C_PERF_SEL_GCR_WBINVL2_START = 0x000000a9, // Number of gcr WBINVL2 requests. + GL2C_PERF_SEL_MDC_INV_METADATA = 0x000000aa, // Number of cycles spent performing gcr requests in metadata tag. + GL2C_PERF_SEL_MDC_REQ = 0x000000ab, // Number of requests passed through the metadata cache. + GL2C_PERF_SEL_MDC_LEVEL = 0x000000ac, // The sum of the number of mdc requests in flight. Average MDC latency=GL2C_PERF_SEL_MDC_LEVEL/GL2C_PERF_SEL_MDC_REQ. + GL2C_PERF_SEL_MDC_TAG_HIT = 0x000000ad, // Number of MDC tag hits. A tag contains multiple sectors, so many tag hits will be sector misses. + GL2C_PERF_SEL_MDC_SECTOR_HIT = 0x000000ae, // Number of MDC sector hits. A sector hit means that there actually is data in the cache for this request. + GL2C_PERF_SEL_MDC_SECTOR_MISS = 0x000000af, // Number of MDC sector misses. + GL2C_PERF_SEL_MDC_TAG_STALL = 0x000000b0, // Number of cycles that the mdc tag is stalled. + GL2C_PERF_SEL_MDC_TAG_REPLACEMENT_LINE_IN_USE_STALL = 0x000000b1, // Number of cycles that the mdc tag is stalled because the line to be replaced is stalled. + GL2C_PERF_SEL_MDC_TAG_DESECTORIZATION_FIFO_FULL_STALL = 0x000000b2, // Number of cycles that the mdc tag is stalled because the desctorization fifo is full. + GL2C_PERF_SEL_MDC_TAG_WAITING_FOR_INVALIDATE_COMPLETION_STALL = 0x000000b3, // Number of cycles that the mdc tag is stalled because it is waiting for the previous invalidate to complete. + GL2C_PERF_SEL_CM_CHANNEL0_REQ = 0x000000b4, // Number of compressed requests are distributed to channel0. + GL2C_PERF_SEL_CM_CHANNEL1_REQ = 0x000000b5, + GL2C_PERF_SEL_CM_CHANNEL2_REQ = 0x000000b6, + GL2C_PERF_SEL_CM_CHANNEL3_REQ = 0x000000b7, + GL2C_PERF_SEL_CM_CHANNEL4_REQ = 0x000000b8, + GL2C_PERF_SEL_CM_CHANNEL5_REQ = 0x000000b9, + GL2C_PERF_SEL_CM_CHANNEL6_REQ = 0x000000ba, + GL2C_PERF_SEL_CM_CHANNEL7_REQ = 0x000000bb, + GL2C_PERF_SEL_CM_CHANNEL8_REQ = 0x000000bc, + GL2C_PERF_SEL_CM_CHANNEL9_REQ = 0x000000bd, + GL2C_PERF_SEL_CM_CHANNEL10_REQ = 0x000000be, + GL2C_PERF_SEL_CM_CHANNEL11_REQ = 0x000000bf, + GL2C_PERF_SEL_CM_CHANNEL12_REQ = 0x000000c0, + GL2C_PERF_SEL_CM_CHANNEL13_REQ = 0x000000c1, + GL2C_PERF_SEL_CM_CHANNEL14_REQ = 0x000000c2, + GL2C_PERF_SEL_CM_CHANNEL15_REQ = 0x000000c3, + GL2C_PERF_SEL_CM_CHANNEL16_REQ = 0x000000c4, + GL2C_PERF_SEL_CM_CHANNEL17_REQ = 0x000000c5, + GL2C_PERF_SEL_CM_CHANNEL18_REQ = 0x000000c6, + GL2C_PERF_SEL_CM_CHANNEL19_REQ = 0x000000c7, + GL2C_PERF_SEL_CM_CHANNEL20_REQ = 0x000000c8, + GL2C_PERF_SEL_CM_CHANNEL21_REQ = 0x000000c9, + GL2C_PERF_SEL_CM_CHANNEL22_REQ = 0x000000ca, + GL2C_PERF_SEL_CM_CHANNEL23_REQ = 0x000000cb, + GL2C_PERF_SEL_CM_CHANNEL24_REQ = 0x000000cc, + GL2C_PERF_SEL_CM_CHANNEL25_REQ = 0x000000cd, + GL2C_PERF_SEL_CM_CHANNEL26_REQ = 0x000000ce, + GL2C_PERF_SEL_CM_CHANNEL27_REQ = 0x000000cf, + GL2C_PERF_SEL_CM_CHANNEL28_REQ = 0x000000d0, + GL2C_PERF_SEL_CM_CHANNEL29_REQ = 0x000000d1, + GL2C_PERF_SEL_CM_CHANNEL30_REQ = 0x000000d2, + GL2C_PERF_SEL_CM_CHANNEL31_REQ = 0x000000d3, + GL2C_PERF_SEL_CM_COMP_ATOMIC_COLOR_REQ = 0x000000d4, // Number of compressed atomic color requests. + GL2C_PERF_SEL_CM_COMP_ATOMIC_DEPTH16_REQ = 0x000000d5, // Number of compressed atomic depth16 requests. + GL2C_PERF_SEL_CM_COMP_ATOMIC_DEPTH32_REQ = 0x000000d6, // Number of compressed atomic depth32 requests. + GL2C_PERF_SEL_CM_COMP_ATOMIC_STENCIL_REQ = 0x000000d7, // Number of compressed atomic stencil requests. + GL2C_PERF_SEL_CM_COMP_WRITE_COLOR_REQ = 0x000000d8, // Number of compressed write color requests. + GL2C_PERF_SEL_CM_COMP_WRITE_DEPTH16_REQ = 0x000000d9, // Number of compressed write depth16 requests. + GL2C_PERF_SEL_CM_COMP_WRITE_DEPTH32_REQ = 0x000000da, // Number of compressed write depth32 requests. + GL2C_PERF_SEL_CM_COMP_WRITE_STENCIL_REQ = 0x000000db, // Number of compressed write stencil requests. + GL2C_PERF_SEL_CM_COMP_READ_REQ = 0x000000dc, // Number of compressed read requests. + GL2C_PERF_SEL_CM_READ_BACK_REQ = 0x000000dd, // Number of read-back requests sent by CM. + GL2C_PERF_SEL_CM_METADATA_WR_REQ = 0x000000de, // Number of metadata write requests sent by CM. + GL2C_PERF_SEL_CM_WR_ACK_REQ = 0x000000df, // Number of write with ack requests sent by CM. + GL2C_PERF_SEL_CM_NO_ACK_REQ = 0x000000e0, // Number of write no-ack requests sent by CM. + GL2C_PERF_SEL_CM_NOOP_REQ = 0x000000e1, // Number of noop requests sent by CM. + GL2C_PERF_SEL_CM_COMP_COLOR_EN_REQ = 0x000000e2, // Number of Color DCC operation with compression enabled requests. + GL2C_PERF_SEL_CM_COMP_COLOR_DIS_REQ = 0x000000e3, // Number of Color DCC operation with compression disabled requests. + GL2C_PERF_SEL_CM_COMP_STENCIL_REQ = 0x000000e4, // Number of Stencil DCC operation requests. + GL2C_PERF_SEL_CM_COMP_DEPTH16_REQ = 0x000000e5, // Number of Depth16 DCC operation requests. + GL2C_PERF_SEL_CM_COMP_DEPTH32_REQ = 0x000000e6, // Number of Depth32 DCC operation requests. + GL2C_PERF_SEL_CM_COMP_RB_SKIP_REQ = 0x000000e7, // Number of DCC operation with read-back skip requests. + GL2C_PERF_SEL_CM_COLOR_32B_WR_REQ = 0x000000e8, // Number of Color 32B compressed sector. + GL2C_PERF_SEL_CM_COLOR_64B_WR_REQ = 0x000000e9, // Number of Color 64B compressed sector. + GL2C_PERF_SEL_CM_FULL_WRITE_REQ = 0x000000ea, // Number of full over-write requests. + GL2C_PERF_SEL_CM_RVF_FULL = 0x000000eb, // Number of cycles RVF is full and there is incoming compressed request. + GL2C_PERF_SEL_CM_SDR_FULL = 0x000000ec, // Number of cycles SDR is full and there is incoming compressed write request. + GL2C_PERF_SEL_CM_MERGE_BUF_FULL = 0x000000ed, // Number of cycles merge data buffer is full and there is pending merge request. + GL2C_PERF_SEL_CM_DCC_STALL = 0x000000ee, // Number of cycles DCC compressor is stalled and there is pending compression request. +} GL2C_PERFCOUNTER_SELECT; + +typedef enum GRBM_PERFCOUNTER_SELECT : unsigned int { + GRBM_PERF_SEL_COUNT = 0x00000000, // Tie High - Count Number of Clocks + GRBM_PERF_SEL_USER_DEFINED = 0x00000001, // User defined performance select. + GRBM_PERF_SEL_GUI_ACTIVE = 0x00000002, // The GUI is Active + GRBM_PERF_SEL_CP_BUSY = 0x00000003, // Any of the Command Processor (CPG/CPC/CPF) blocks are busy. + GRBM_PERF_SEL_CP_COHER_BUSY = 0x00000004, // The Command Processor Graphics (CPG) Surface Coherency Logic is busy. + GRBM_PERF_SEL_CP_DMA_BUSY = 0x00000005, // The Command Processor Graphics (CPG) DMA Logic is busy. + GRBM_PERF_SEL_CB_BUSY = 0x00000006, // Any of the Color Blocks (CB) are busy in the shader engine(s). + GRBM_PERF_SEL_DB_BUSY = 0x00000007, // Any of the Depth Blocks (DB) are busy in the shader engine(s). + GRBM_PERF_SEL_PA_BUSY = 0x00000008, // Any of the Primitive Assembly Blocks (PA) are busy in the shader engine(s). + GRBM_PERF_SEL_SC_BUSY = 0x00000009, // Any of the Scan Converter Blocks (SC) are busy in the shader engine(s). + GRBM_PERF_SEL_RESERVED_6 = 0x0000000a, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_SPI_BUSY = 0x0000000b, // Any of the Shader Pipe Interpolators (SPI) are busy in the shader engine(s). + GRBM_PERF_SEL_SX_BUSY = 0x0000000c, // Any of the Shader Export Blocks (SX) are busy. + GRBM_PERF_SEL_TA_BUSY = 0x0000000d, // Any of the Texture Pipes (TA) are busy in the shader engine(s). + GRBM_PERF_SEL_CB_CLEAN = 0x0000000e, // Any of the Color Blocks (CB) are not clean in all shader engine(s). + GRBM_PERF_SEL_DB_CLEAN = 0x0000000f, // Any of the Depth Blocks (DB) are not clean in all shader engine(s). + GRBM_PERF_SEL_RESERVED_5 = 0x00000010, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_RESERVED_9 = 0x00000011, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_RESERVED_4 = 0x00000012, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_RESERVED_3 = 0x00000013, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_RESERVED_2 = 0x00000014, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_RESERVED_1 = 0x00000015, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_RESERVED_0 = 0x00000016, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_RESERVED_8 = 0x00000017, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_RESERVED_7 = 0x00000018, // Reserved to maintain backwards compatibility. + GRBM_PERF_SEL_GDS_BUSY = 0x00000019, // The Global Data Share (GDS) is busy. + GRBM_PERF_SEL_BCI_BUSY = 0x0000001a, // Any of the Barycentric Interpolators (BCI) are busy in the shader engine(s). + GRBM_PERF_SEL_RLC_BUSY = 0x0000001b, // The Ring List Controller (RLC) is busy. + GRBM_PERF_SEL_TCP_BUSY = 0x0000001c, // Any of the Texture Cache Blocks TCP are busy. + GRBM_PERF_SEL_CPG_BUSY = 0x0000001d, // The Command Processor Graphics (CPG) is busy. + GRBM_PERF_SEL_CPC_BUSY = 0x0000001e, // The Command Processor Compute (CPC) is busy. + GRBM_PERF_SEL_CPF_BUSY = 0x0000001f, // The Command Processor Fetchers (CPF) is busy. + GRBM_PERF_SEL_GE_BUSY = 0x00000020, // The Geometry Engine (GE) is busy. + GRBM_PERF_SEL_GE_NO_DMA_BUSY = 0x00000021, // The Geometry Engine (GE) is busy; Does not include the Index DMA engine status. + GRBM_PERF_SEL_UTCL2_BUSY = 0x00000022, // The Unified Translation Cache Level-2 (UTCL2) block is busy. + GRBM_PERF_SEL_EA_BUSY = 0x00000023, // The Efficiency Arbiter (EA) block is busy. + GRBM_PERF_SEL_RMI_BUSY = 0x00000024, // The Render Backend Memory Interface (RMI) block is busy. + GRBM_PERF_SEL_CPAXI_BUSY = 0x00000025, // The CPAXI block is busy. + GRBM_PERF_SEL_UTCL1_BUSY = 0x00000026, // The UTCL1 block is busy. + GRBM_PERF_SEL_GL2CC_BUSY = 0x00000027, // The GL2CC block is busy. + GRBM_PERF_SEL_SDMA_BUSY = 0x00000028, // The SDMA block is busy. + GRBM_PERF_SEL_CH_BUSY = 0x00000029, // The CH block is busy. + GRBM_PERF_SEL_PH_BUSY = 0x0000002a, // The PH block is busy. + GRBM_PERF_SEL_PMM_BUSY = 0x0000002b, // The PMM block is busy. + GRBM_PERF_SEL_GUS_BUSY = 0x0000002c, // The GUS block is busy. + GRBM_PERF_SEL_GL1CC_BUSY = 0x0000002d, // The GL1CC block is busy. +} GRBM_PERFCOUNTER_SELECT; + +typedef enum GRBMSE0_PERFCOUNTER_SELECT : unsigned int { + GRBM_SE0_PERF_SEL_COUNT = 0x00000000, // Tie High - Count Number of Clocks + GRBM_SE0_PERF_SEL_USER_DEFINED = 0x00000001, // User defined performance select. + GRBM_SE0_PERF_SEL_CB_BUSY = 0x00000002, // Any of the Color Blocks (CB) are busy in shader engine 0. + GRBM_SE0_PERF_SEL_DB_BUSY = 0x00000003, // Any of the Depth Blocks (DB) are busy in shader engine 0. + GRBM_SE0_PERF_SEL_SC_BUSY = 0x00000004, // Any of the Scan Converter Blocks (SC) are busy in shader engine 0. + GRBM_SE0_PERF_SEL_RESERVED_1 = 0x00000005, // Reserved to maintain backwards compatibility. + GRBM_SE0_PERF_SEL_SPI_BUSY = 0x00000006, // Any of the Shader Pipe Interpolators (SPI) are busy in shader engine 0. + GRBM_SE0_PERF_SEL_SX_BUSY = 0x00000007, // Any of the Shader Export Blocks (SX) are busy for shader engine 0. + GRBM_SE0_PERF_SEL_TA_BUSY = 0x00000008, // Any of the Texture Pipes (TA) are busy in shader engine 0. + GRBM_SE0_PERF_SEL_CB_CLEAN = 0x00000009, // Any of the Color Blocks (CB) are not clean in shader engine 0. + GRBM_SE0_PERF_SEL_DB_CLEAN = 0x0000000a, // Any of the Depth Blocks (DB) are not clean in shader engine 0. + GRBM_SE0_PERF_SEL_RESERVED_0 = 0x0000000b, // Reserved to maintain backwards compatibility. + GRBM_SE0_PERF_SEL_PA_BUSY = 0x0000000c, // The Primitive Assembly Block (PA) is busy in shader engine 0. + GRBM_SE0_PERF_SEL_RESERVED_2 = 0x0000000d, // Reserved to maintain backwards compatibility. + GRBM_SE0_PERF_SEL_BCI_BUSY = 0x0000000e, // Any of the Barycentric Interpolators (BCI) are busy in shader engine 0. + GRBM_SE0_PERF_SEL_RMI_BUSY = 0x0000000f, // Any of the Render Backend Memory Interface (RMI) are busy in shader engine 0. + GRBM_SE0_PERF_SEL_UTCL1_BUSY = 0x00000010, // Any of The Unified Translation Cache Level-1 are busy in shader engine 0. + GRBM_SE0_PERF_SEL_TCP_BUSY = 0x00000011, // Any of Texture Cache Blocks TCP are busy in shader engine 0. + GRBM_SE0_PERF_SEL_GL1CC_BUSY = 0x00000012, // Any of Texture Cache Blocks GL1CC are busy in shader engine 0. +} GRBMSE0_PERFCOUNTER_SELECT; + +typedef enum GRBMSE1_PERFCOUNTER_SELECT : unsigned int { + GRBM_SE1_PERF_SEL_COUNT = 0x00000000, // Tie High - Count Number of Clocks + GRBM_SE1_PERF_SEL_USER_DEFINED = 0x00000001, // User defined performance select. + GRBM_SE1_PERF_SEL_CB_BUSY = 0x00000002, // Any of the Color Blocks (CB) are busy in shader engine 1. + GRBM_SE1_PERF_SEL_DB_BUSY = 0x00000003, // Any of the Depth Blocks (DB) are busy in shader engine 1. + GRBM_SE1_PERF_SEL_SC_BUSY = 0x00000004, // Any of the Scan Converter Blocks (SC) are busy in shader engine 1. + GRBM_SE1_PERF_SEL_RESERVED_1 = 0x00000005, // Reserved to maintain backwards compatibility. + GRBM_SE1_PERF_SEL_SPI_BUSY = 0x00000006, // Any of the Shader Pipe Interpolators (SPI) are busy in shader engine 1. + GRBM_SE1_PERF_SEL_SX_BUSY = 0x00000007, // Any of the Shader Export Blocks (SX) are busy for shader engine 1. + GRBM_SE1_PERF_SEL_TA_BUSY = 0x00000008, // Any of the Texture Pipes (TA) are busy in shader engine 1. + GRBM_SE1_PERF_SEL_CB_CLEAN = 0x00000009, // Any of the Color Blocks (CB) are not clean in shader engine 1. + GRBM_SE1_PERF_SEL_DB_CLEAN = 0x0000000a, // Any of the Depth Blocks (DB) are not clean in shader engine 1. + GRBM_SE1_PERF_SEL_RESERVED_0 = 0x0000000b, // Reserved to maintain backwards compatibility. + GRBM_SE1_PERF_SEL_PA_BUSY = 0x0000000c, // The Primitive Assembly Block (PA) is busy in shader engine 1. + GRBM_SE1_PERF_SEL_RESERVED_2 = 0x0000000d, // Reserved to maintain backwards compatibility. + GRBM_SE1_PERF_SEL_BCI_BUSY = 0x0000000e, // Any of the Barycentric Interpolators (BCI) are busy in shader engine 1. + GRBM_SE1_PERF_SEL_RMI_BUSY = 0x0000000f, // Any of the Render Backend Memory Interface (RMI) are busy in shader engine 1. + GRBM_SE1_PERF_SEL_UTCL1_BUSY = 0x00000010, // Any of The Unified Translation Cache Level-1 are busy in shader engine 0. + GRBM_SE1_PERF_SEL_TCP_BUSY = 0x00000011, // Any of Texture Cache Blocks TCP are busy in shader engine 0. + GRBM_SE1_PERF_SEL_GL1CC_BUSY = 0x00000012, // Any of Texture Cache Blocks GL1CC are busy in shader engine 0. +} GRBMSE1_PERFCOUNTER_SELECT; + +typedef enum IH_PERFCOUNTER_SELECT : unsigned int { + IH_PERF_SEL_CYCLE = 0x00000000, // Cycle count + IH_PERF_SEL_IDLE = 0x00000001, // IH is idle + IH_PERF_SEL_INPUT_IDLE = 0x00000002, // IH input is idle + IH_PERF_SEL_BUFFER_IDLE = 0x00000003, // IH rb unit is idle + IH_PERF_SEL_RB0_FULL = 0x00000004, // PF Ring buffer is full + IH_PERF_SEL_RB0_OVERFLOW = 0x00000005, // Number of times the PF ring buffer overflow + IH_PERF_SEL_RB0_WPTR_WRITEBACK = 0x00000006, // Number of PF write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRAP = 0x00000007, // PF Ring buffer write pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP = 0x00000008, // PF Ring buffer read pointer wraps + IH_PERF_SEL_MC_WR_IDLE = 0x00000009, // IH mc_wr unit is idle + IH_PERF_SEL_MC_WR_COUNT = 0x0000000a, // Number of memory write requests issued + IH_PERF_SEL_MC_WR_STALL = 0x0000000b, // IH is stalled by MC + IH_PERF_SEL_MC_WR_CLEAN_PENDING = 0x0000000c, // IH MC write clean is pending + IH_PERF_SEL_MC_WR_CLEAN_STALL = 0x0000000d, // IH is stalled by MC pending a write clean + IH_PERF_SEL_BIF_LINE0_RISING = 0x0000000e, // Number of rising edges on PF BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING = 0x0000000f, // Number of ralling edges on PF BIF interrupt line + IH_PERF_SEL_RB1_FULL = 0x00000010, // PF Ring buffer is full + IH_PERF_SEL_RB1_OVERFLOW = 0x00000011, // Number of times the PF ring buffer overflow + IH_PERF_SEL_COOKIE_REC_ERROR = 0x00000012, // IH cookie receive burst error + IH_PERF_SEL_RB1_WPTR_WRAP = 0x00000013, // PF Ring buffer write pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP = 0x00000014, // PF Ring buffer read pointer wraps + IH_PERF_SEL_RB2_FULL = 0x00000015, // PF Ring buffer is full + IH_PERF_SEL_RB2_OVERFLOW = 0x00000016, // Number of times the PF ring buffer overflow + IH_PERF_SEL_CLIENT_CREDIT_ERROR = 0x00000017, // Client sends IH interrupt when it doesn't have credit + IH_PERF_SEL_RB2_WPTR_WRAP = 0x00000018, // PF Ring buffer write pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP = 0x00000019, // PF Ring buffer read pointer wraps + IH_PERF_SEL_STORM_CLIENT_INT_DROP = 0x0000001a, // Storm client's interrupt is dropped + IH_PERF_SEL_SELF_IV_VALID = 0x0000001b, // IH self IV is generated + IH_PERF_SEL_BUFFER_FIFO_FULL = 0x0000001c, // IH buffer fifo is full + IH_PERF_SEL_RB0_FULL_VF0 = 0x0000001d, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF1 = 0x0000001e, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF2 = 0x0000001f, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF3 = 0x00000020, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF4 = 0x00000021, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF5 = 0x00000022, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF6 = 0x00000023, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF7 = 0x00000024, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF8 = 0x00000025, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF9 = 0x00000026, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF10 = 0x00000027, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF11 = 0x00000028, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF12 = 0x00000029, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF13 = 0x0000002a, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF14 = 0x0000002b, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF15 = 0x0000002c, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF16 = 0x0000002d, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF17 = 0x0000002e, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF18 = 0x0000002f, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF19 = 0x00000030, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF20 = 0x00000031, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF21 = 0x00000032, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF22 = 0x00000033, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF23 = 0x00000034, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF24 = 0x00000035, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF25 = 0x00000036, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF26 = 0x00000037, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF27 = 0x00000038, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF28 = 0x00000039, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF29 = 0x0000003a, // Ring buffer is full + IH_PERF_SEL_RB0_FULL_VF30 = 0x0000003b, // Ring buffer is full + IH_PERF_SEL_RB0_OVERFLOW_VF0 = 0x0000003c, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF1 = 0x0000003d, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF2 = 0x0000003e, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF3 = 0x0000003f, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF4 = 0x00000040, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF5 = 0x00000041, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF6 = 0x00000042, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF7 = 0x00000043, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF8 = 0x00000044, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF9 = 0x00000045, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF10 = 0x00000046, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF11 = 0x00000047, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF12 = 0x00000048, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF13 = 0x00000049, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF14 = 0x0000004a, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF15 = 0x0000004b, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF16 = 0x0000004c, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF17 = 0x0000004d, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF18 = 0x0000004e, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF19 = 0x0000004f, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF20 = 0x00000050, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF21 = 0x00000051, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF22 = 0x00000052, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF23 = 0x00000053, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF24 = 0x00000054, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF25 = 0x00000055, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF26 = 0x00000056, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF27 = 0x00000057, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF28 = 0x00000058, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF29 = 0x00000059, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_OVERFLOW_VF30 = 0x0000005a, // Number of times the ring buffer overflow + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF0 = 0x0000005b, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF1 = 0x0000005c, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF2 = 0x0000005d, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF3 = 0x0000005e, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF4 = 0x0000005f, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF5 = 0x00000060, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF6 = 0x00000061, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF7 = 0x00000062, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF8 = 0x00000063, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF9 = 0x00000064, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF10 = 0x00000065, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF11 = 0x00000066, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF12 = 0x00000067, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF13 = 0x00000068, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF14 = 0x00000069, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF15 = 0x0000006a, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF16 = 0x0000006b, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF17 = 0x0000006c, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF18 = 0x0000006d, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF19 = 0x0000006e, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF20 = 0x0000006f, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF21 = 0x00000070, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF22 = 0x00000071, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF23 = 0x00000072, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF24 = 0x00000073, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF25 = 0x00000074, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF26 = 0x00000075, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF27 = 0x00000076, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF28 = 0x00000077, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF29 = 0x00000078, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRITEBACK_VF30 = 0x00000079, // Number of write pointer writebacks + IH_PERF_SEL_RB0_WPTR_WRAP_VF0 = 0x0000007a, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF1 = 0x0000007b, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF2 = 0x0000007c, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF3 = 0x0000007d, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF4 = 0x0000007e, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF5 = 0x0000007f, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF6 = 0x00000080, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF7 = 0x00000081, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF8 = 0x00000082, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF9 = 0x00000083, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF10 = 0x00000084, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF11 = 0x00000085, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF12 = 0x00000086, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF13 = 0x00000087, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF14 = 0x00000088, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF15 = 0x00000089, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF16 = 0x0000008a, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF17 = 0x0000008b, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF18 = 0x0000008c, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF19 = 0x0000008d, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF20 = 0x0000008e, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF21 = 0x0000008f, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF22 = 0x00000090, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF23 = 0x00000091, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF24 = 0x00000092, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF25 = 0x00000093, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF26 = 0x00000094, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF27 = 0x00000095, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF28 = 0x00000096, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF29 = 0x00000097, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_WPTR_WRAP_VF30 = 0x00000098, // Ring buffer write pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF0 = 0x00000099, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF1 = 0x0000009a, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF2 = 0x0000009b, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF3 = 0x0000009c, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF4 = 0x0000009d, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF5 = 0x0000009e, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF6 = 0x0000009f, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF7 = 0x000000a0, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF8 = 0x000000a1, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF9 = 0x000000a2, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF10 = 0x000000a3, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF11 = 0x000000a4, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF12 = 0x000000a5, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF13 = 0x000000a6, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF14 = 0x000000a7, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF15 = 0x000000a8, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF16 = 0x000000a9, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF17 = 0x000000aa, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF18 = 0x000000ab, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF19 = 0x000000ac, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF20 = 0x000000ad, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF21 = 0x000000ae, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF22 = 0x000000af, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF23 = 0x000000b0, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF24 = 0x000000b1, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF25 = 0x000000b2, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF26 = 0x000000b3, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF27 = 0x000000b4, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF28 = 0x000000b5, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF29 = 0x000000b6, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_RPTR_WRAP_VF30 = 0x000000b7, // Ring buffer read pointer wraps + IH_PERF_SEL_BIF_LINE0_RISING_VF0 = 0x000000b8, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF1 = 0x000000b9, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF2 = 0x000000ba, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF3 = 0x000000bb, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF4 = 0x000000bc, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF5 = 0x000000bd, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF6 = 0x000000be, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF7 = 0x000000bf, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF8 = 0x000000c0, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF9 = 0x000000c1, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF10 = 0x000000c2, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF11 = 0x000000c3, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF12 = 0x000000c4, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF13 = 0x000000c5, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF14 = 0x000000c6, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF15 = 0x000000c7, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF16 = 0x000000c8, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF17 = 0x000000c9, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF18 = 0x000000ca, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF19 = 0x000000cb, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF20 = 0x000000cc, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF21 = 0x000000cd, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF22 = 0x000000ce, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF23 = 0x000000cf, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF24 = 0x000000d0, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF25 = 0x000000d1, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF26 = 0x000000d2, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF27 = 0x000000d3, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF28 = 0x000000d4, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF29 = 0x000000d5, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_RISING_VF30 = 0x000000d6, // Number of rising edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF0 = 0x000000d7, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF1 = 0x000000d8, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF2 = 0x000000d9, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF3 = 0x000000da, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF4 = 0x000000db, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF5 = 0x000000dc, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF6 = 0x000000dd, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF7 = 0x000000de, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF8 = 0x000000df, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF9 = 0x000000e0, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF10 = 0x000000e1, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF11 = 0x000000e2, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF12 = 0x000000e3, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF13 = 0x000000e4, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF14 = 0x000000e5, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF15 = 0x000000e6, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF16 = 0x000000e7, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF17 = 0x000000e8, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF18 = 0x000000e9, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF19 = 0x000000ea, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF20 = 0x000000eb, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF21 = 0x000000ec, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF22 = 0x000000ed, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF23 = 0x000000ee, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF24 = 0x000000ef, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF25 = 0x000000f0, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF26 = 0x000000f1, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF27 = 0x000000f2, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF28 = 0x000000f3, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF29 = 0x000000f4, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_BIF_LINE0_FALLING_VF30 = 0x000000f5, // Number of ralling edges on BIF interrupt line + IH_PERF_SEL_CLIENT0_INT = 0x000000f6, // Receive interrupt from Client 1 + IH_PERF_SEL_CLIENT1_INT = 0x000000f7, // Receive interrupt from Client 1 + IH_PERF_SEL_CLIENT2_INT = 0x000000f8, // Receive interrupt from Client 2 + IH_PERF_SEL_CLIENT3_INT = 0x000000f9, // Receive interrupt from Client 3 + IH_PERF_SEL_CLIENT4_INT = 0x000000fa, // Receive interrupt from Client 4 + IH_PERF_SEL_CLIENT5_INT = 0x000000fb, // Receive interrupt from Client 5 + IH_PERF_SEL_CLIENT6_INT = 0x000000fc, // Receive interrupt from Client 6 + IH_PERF_SEL_CLIENT7_INT = 0x000000fd, // Receive interrupt from Client 7 + IH_PERF_SEL_CLIENT8_INT = 0x000000fe, // Receive interrupt from Client 8 + IH_PERF_SEL_CLIENT9_INT = 0x000000ff, // Receive interrupt from Client 9 + IH_PERF_SEL_CLIENT10_INT = 0x00000100, // Receive interrupt from Client 10 + IH_PERF_SEL_CLIENT11_INT = 0x00000101, // Receive interrupt from Client 11 + IH_PERF_SEL_CLIENT12_INT = 0x00000102, // Receive interrupt from Client 12 + IH_PERF_SEL_CLIENT13_INT = 0x00000103, // Receive interrupt from Client 13 + IH_PERF_SEL_CLIENT14_INT = 0x00000104, // Receive interrupt from Client 14 + IH_PERF_SEL_CLIENT15_INT = 0x00000105, // Receive interrupt from Client 15 + IH_PERF_SEL_CLIENT16_INT = 0x00000106, // Receive interrupt from Client 16 + IH_PERF_SEL_CLIENT17_INT = 0x00000107, // Receive interrupt from Client 17 + IH_PERF_SEL_CLIENT18_INT = 0x00000108, // Receive interrupt from Client 18 + IH_PERF_SEL_CLIENT19_INT = 0x00000109, // Receive interrupt from Client 19 + IH_PERF_SEL_CLIENT20_INT = 0x0000010a, // Receive interrupt from Client 20 + IH_PERF_SEL_CLIENT21_INT = 0x0000010b, // Receive interrupt from Client 21 + IH_PERF_SEL_CLIENT22_INT = 0x0000010c, // Receive interrupt from Client 22 + IH_PERF_SEL_CLIENT23_INT = 0x0000010d, // Receive interrupt from Client 23 + IH_PERF_SEL_CLIENT24_INT = 0x0000010e, // Receive interrupt from Client 24 + IH_PERF_SEL_CLIENT25_INT = 0x0000010f, // Receive interrupt from Client 25 + IH_PERF_SEL_CLIENT26_INT = 0x00000110, // Receive interrupt from Client 26 + IH_PERF_SEL_CLIENT27_INT = 0x00000111, // Receive interrupt from Client 27 + IH_PERF_SEL_CLIENT28_INT = 0x00000112, // Receive interrupt from Client 28 + IH_PERF_SEL_CLIENT29_INT = 0x00000113, // Receive interrupt from Client 29 + IH_PERF_SEL_CLIENT30_INT = 0x00000114, // Receive interrupt from Client 30 + IH_PERF_SEL_CLIENT31_INT = 0x00000115, // Receive interrupt from Client 31 + IH_PERF_SEL_RB1_FULL_VF0 = 0x00000116, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF1 = 0x00000117, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF2 = 0x00000118, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF3 = 0x00000119, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF4 = 0x0000011a, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF5 = 0x0000011b, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF6 = 0x0000011c, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF7 = 0x0000011d, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF8 = 0x0000011e, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF9 = 0x0000011f, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF10 = 0x00000120, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF11 = 0x00000121, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF12 = 0x00000122, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF13 = 0x00000123, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF14 = 0x00000124, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF15 = 0x00000125, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF16 = 0x00000126, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF17 = 0x00000127, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF18 = 0x00000128, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF19 = 0x00000129, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF20 = 0x0000012a, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF21 = 0x0000012b, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF22 = 0x0000012c, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF23 = 0x0000012d, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF24 = 0x0000012e, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF25 = 0x0000012f, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF26 = 0x00000130, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF27 = 0x00000131, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF28 = 0x00000132, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF29 = 0x00000133, // Ring buffer is full + IH_PERF_SEL_RB1_FULL_VF30 = 0x00000134, // Ring buffer is full + IH_PERF_SEL_RB1_OVERFLOW_VF0 = 0x00000135, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF1 = 0x00000136, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF2 = 0x00000137, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF3 = 0x00000138, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF4 = 0x00000139, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF5 = 0x0000013a, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF6 = 0x0000013b, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF7 = 0x0000013c, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF8 = 0x0000013d, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF9 = 0x0000013e, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF10 = 0x0000013f, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF11 = 0x00000140, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF12 = 0x00000141, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF13 = 0x00000142, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF14 = 0x00000143, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF15 = 0x00000144, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF16 = 0x00000145, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF17 = 0x00000146, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF18 = 0x00000147, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF19 = 0x00000148, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF20 = 0x00000149, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF21 = 0x0000014a, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF22 = 0x0000014b, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF23 = 0x0000014c, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF24 = 0x0000014d, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF25 = 0x0000014e, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF26 = 0x0000014f, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF27 = 0x00000150, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF28 = 0x00000151, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF29 = 0x00000152, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_OVERFLOW_VF30 = 0x00000153, // Number of times the ring buffer overflow + IH_PERF_SEL_RB1_WPTR_WRAP_VF0 = 0x00000154, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF1 = 0x00000155, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF2 = 0x00000156, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF3 = 0x00000157, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF4 = 0x00000158, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF5 = 0x00000159, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF6 = 0x0000015a, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF7 = 0x0000015b, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF8 = 0x0000015c, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF9 = 0x0000015d, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF10 = 0x0000015e, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF11 = 0x0000015f, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF12 = 0x00000160, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF13 = 0x00000161, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF14 = 0x00000162, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF15 = 0x00000163, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF16 = 0x00000164, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF17 = 0x00000165, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF18 = 0x00000166, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF19 = 0x00000167, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF20 = 0x00000168, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF21 = 0x00000169, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF22 = 0x0000016a, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF23 = 0x0000016b, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF24 = 0x0000016c, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF25 = 0x0000016d, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF26 = 0x0000016e, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF27 = 0x0000016f, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF28 = 0x00000170, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF29 = 0x00000171, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_WPTR_WRAP_VF30 = 0x00000172, // Ring buffer write pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF0 = 0x00000173, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF1 = 0x00000174, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF2 = 0x00000175, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF3 = 0x00000176, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF4 = 0x00000177, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF5 = 0x00000178, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF6 = 0x00000179, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF7 = 0x0000017a, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF8 = 0x0000017b, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF9 = 0x0000017c, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF10 = 0x0000017d, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF11 = 0x0000017e, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF12 = 0x0000017f, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF13 = 0x00000180, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF14 = 0x00000181, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF15 = 0x00000182, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF16 = 0x00000183, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF17 = 0x00000184, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF18 = 0x00000185, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF19 = 0x00000186, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF20 = 0x00000187, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF21 = 0x00000188, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF22 = 0x00000189, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF23 = 0x0000018a, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF24 = 0x0000018b, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF25 = 0x0000018c, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF26 = 0x0000018d, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF27 = 0x0000018e, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF28 = 0x0000018f, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF29 = 0x00000190, // Ring buffer read pointer wraps + IH_PERF_SEL_RB1_RPTR_WRAP_VF30 = 0x00000191, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_FULL_VF0 = 0x00000192, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF1 = 0x00000193, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF2 = 0x00000194, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF3 = 0x00000195, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF4 = 0x00000196, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF5 = 0x00000197, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF6 = 0x00000198, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF7 = 0x00000199, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF8 = 0x0000019a, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF9 = 0x0000019b, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF10 = 0x0000019c, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF11 = 0x0000019d, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF12 = 0x0000019e, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF13 = 0x0000019f, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF14 = 0x000001a0, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF15 = 0x000001a1, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF16 = 0x000001a2, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF17 = 0x000001a3, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF18 = 0x000001a4, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF19 = 0x000001a5, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF20 = 0x000001a6, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF21 = 0x000001a7, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF22 = 0x000001a8, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF23 = 0x000001a9, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF24 = 0x000001aa, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF25 = 0x000001ab, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF26 = 0x000001ac, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF27 = 0x000001ad, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF28 = 0x000001ae, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF29 = 0x000001af, // Ring buffer is full + IH_PERF_SEL_RB2_FULL_VF30 = 0x000001b0, // Ring buffer is full + IH_PERF_SEL_RB2_OVERFLOW_VF0 = 0x000001b1, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF1 = 0x000001b2, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF2 = 0x000001b3, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF3 = 0x000001b4, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF4 = 0x000001b5, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF5 = 0x000001b6, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF6 = 0x000001b7, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF7 = 0x000001b8, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF8 = 0x000001b9, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF9 = 0x000001ba, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF10 = 0x000001bb, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF11 = 0x000001bc, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF12 = 0x000001bd, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF13 = 0x000001be, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF14 = 0x000001bf, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF15 = 0x000001c0, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF16 = 0x000001c1, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF17 = 0x000001c2, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF18 = 0x000001c3, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF19 = 0x000001c4, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF20 = 0x000001c5, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF21 = 0x000001c6, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF22 = 0x000001c7, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF23 = 0x000001c8, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF24 = 0x000001c9, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF25 = 0x000001ca, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF26 = 0x000001cb, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF27 = 0x000001cc, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF28 = 0x000001cd, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF29 = 0x000001ce, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_OVERFLOW_VF30 = 0x000001cf, // Number of times the ring buffer overflow + IH_PERF_SEL_RB2_WPTR_WRAP_VF0 = 0x000001d0, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF1 = 0x000001d1, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF2 = 0x000001d2, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF3 = 0x000001d3, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF4 = 0x000001d4, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF5 = 0x000001d5, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF6 = 0x000001d6, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF7 = 0x000001d7, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF8 = 0x000001d8, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF9 = 0x000001d9, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF10 = 0x000001da, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF11 = 0x000001db, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF12 = 0x000001dc, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF13 = 0x000001dd, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF14 = 0x000001de, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF15 = 0x000001df, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF16 = 0x000001e0, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF17 = 0x000001e1, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF18 = 0x000001e2, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF19 = 0x000001e3, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF20 = 0x000001e4, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF21 = 0x000001e5, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF22 = 0x000001e6, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF23 = 0x000001e7, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF24 = 0x000001e8, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF25 = 0x000001e9, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF26 = 0x000001ea, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF27 = 0x000001eb, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF28 = 0x000001ec, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF29 = 0x000001ed, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_WPTR_WRAP_VF30 = 0x000001ee, // Ring buffer write pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF0 = 0x000001ef, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF1 = 0x000001f0, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF2 = 0x000001f1, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF3 = 0x000001f2, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF4 = 0x000001f3, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF5 = 0x000001f4, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF6 = 0x000001f5, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF7 = 0x000001f6, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF8 = 0x000001f7, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF9 = 0x000001f8, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF10 = 0x000001f9, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF11 = 0x000001fa, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF12 = 0x000001fb, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF13 = 0x000001fc, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF14 = 0x000001fd, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF15 = 0x000001fe, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF16 = 0x000001ff, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF17 = 0x00000200, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF18 = 0x00000201, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF19 = 0x00000202, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF20 = 0x00000203, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF21 = 0x00000204, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF22 = 0x00000205, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF23 = 0x00000206, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF24 = 0x00000207, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF25 = 0x00000208, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF26 = 0x00000209, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF27 = 0x0000020a, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF28 = 0x0000020b, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF29 = 0x0000020c, // Ring buffer read pointer wraps + IH_PERF_SEL_RB2_RPTR_WRAP_VF30 = 0x0000020d, // Ring buffer read pointer wraps + IH_PERF_SEL_RB0_FULL_DRAIN_DROP = 0x0000020e, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF0 = 0x0000020f, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF1 = 0x00000210, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF2 = 0x00000211, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF3 = 0x00000212, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF4 = 0x00000213, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF5 = 0x00000214, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF6 = 0x00000215, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF7 = 0x00000216, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF8 = 0x00000217, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF9 = 0x00000218, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF10 = 0x00000219, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF11 = 0x0000021a, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF12 = 0x0000021b, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF13 = 0x0000021c, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF14 = 0x0000021d, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF15 = 0x0000021e, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF16 = 0x0000021f, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF17 = 0x00000220, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF18 = 0x00000221, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF19 = 0x00000222, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF20 = 0x00000223, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF21 = 0x00000224, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF22 = 0x00000225, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF23 = 0x00000226, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF24 = 0x00000227, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF25 = 0x00000228, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF26 = 0x00000229, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF27 = 0x0000022a, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF28 = 0x0000022b, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF29 = 0x0000022c, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_FULL_DRAIN_DROP_VF30 = 0x0000022d, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP = 0x0000022e, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF0 = 0x0000022f, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF1 = 0x00000230, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF2 = 0x00000231, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF3 = 0x00000232, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF4 = 0x00000233, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF5 = 0x00000234, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF6 = 0x00000235, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF7 = 0x00000236, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF8 = 0x00000237, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF9 = 0x00000238, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF10 = 0x00000239, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF11 = 0x0000023a, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF12 = 0x0000023b, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF13 = 0x0000023c, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF14 = 0x0000023d, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF15 = 0x0000023e, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF16 = 0x0000023f, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF17 = 0x00000240, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF18 = 0x00000241, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF19 = 0x00000242, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF20 = 0x00000243, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF21 = 0x00000244, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF22 = 0x00000245, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF23 = 0x00000246, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF24 = 0x00000247, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF25 = 0x00000248, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF26 = 0x00000249, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF27 = 0x0000024a, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF28 = 0x0000024b, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF29 = 0x0000024c, // IV is dropped due to full drain happens + IH_PERF_SEL_RB1_FULL_DRAIN_DROP_VF30 = 0x0000024d, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP = 0x0000024e, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF0 = 0x0000024f, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF1 = 0x00000250, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF2 = 0x00000251, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF3 = 0x00000252, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF4 = 0x00000253, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF5 = 0x00000254, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF6 = 0x00000255, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF7 = 0x00000256, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF8 = 0x00000257, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF9 = 0x00000258, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF10 = 0x00000259, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF11 = 0x0000025a, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF12 = 0x0000025b, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF13 = 0x0000025c, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF14 = 0x0000025d, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF15 = 0x0000025e, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF16 = 0x0000025f, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF17 = 0x00000260, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF18 = 0x00000261, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF19 = 0x00000262, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF20 = 0x00000263, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF21 = 0x00000264, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF22 = 0x00000265, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF23 = 0x00000266, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF24 = 0x00000267, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF25 = 0x00000268, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF26 = 0x00000269, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF27 = 0x0000026a, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF28 = 0x0000026b, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF29 = 0x0000026c, // IV is dropped due to full drain happens + IH_PERF_SEL_RB2_FULL_DRAIN_DROP_VF30 = 0x0000026d, // IV is dropped due to full drain happens + IH_PERF_SEL_RB0_LOAD_RPTR = 0x0000026e, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF0 = 0x0000026f, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF1 = 0x00000270, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF2 = 0x00000271, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF3 = 0x00000272, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF4 = 0x00000273, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF5 = 0x00000274, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF6 = 0x00000275, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF7 = 0x00000276, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF8 = 0x00000277, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF9 = 0x00000278, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF10 = 0x00000279, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF11 = 0x0000027a, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF12 = 0x0000027b, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF13 = 0x0000027c, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF14 = 0x0000027d, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF15 = 0x0000027e, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF16 = 0x0000027f, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF17 = 0x00000280, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF18 = 0x00000281, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF19 = 0x00000282, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF20 = 0x00000283, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF21 = 0x00000284, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF22 = 0x00000285, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF23 = 0x00000286, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF24 = 0x00000287, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF25 = 0x00000288, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF26 = 0x00000289, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF27 = 0x0000028a, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF28 = 0x0000028b, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF29 = 0x0000028c, // RPTR load happens + IH_PERF_SEL_RB0_LOAD_RPTR_VF30 = 0x0000028d, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR = 0x0000028e, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF0 = 0x0000028f, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF1 = 0x00000290, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF2 = 0x00000291, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF3 = 0x00000292, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF4 = 0x00000293, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF5 = 0x00000294, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF6 = 0x00000295, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF7 = 0x00000296, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF8 = 0x00000297, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF9 = 0x00000298, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF10 = 0x00000299, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF11 = 0x0000029a, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF12 = 0x0000029b, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF13 = 0x0000029c, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF14 = 0x0000029d, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF15 = 0x0000029e, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF16 = 0x0000029f, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF17 = 0x000002a0, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF18 = 0x000002a1, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF19 = 0x000002a2, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF20 = 0x000002a3, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF21 = 0x000002a4, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF22 = 0x000002a5, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF23 = 0x000002a6, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF24 = 0x000002a7, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF25 = 0x000002a8, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF26 = 0x000002a9, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF27 = 0x000002aa, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF28 = 0x000002ab, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF29 = 0x000002ac, // RPTR load happens + IH_PERF_SEL_RB1_LOAD_RPTR_VF30 = 0x000002ad, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR = 0x000002ae, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF0 = 0x000002af, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF1 = 0x000002b0, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF2 = 0x000002b1, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF3 = 0x000002b2, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF4 = 0x000002b3, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF5 = 0x000002b4, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF6 = 0x000002b5, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF7 = 0x000002b6, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF8 = 0x000002b7, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF9 = 0x000002b8, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF10 = 0x000002b9, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF11 = 0x000002ba, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF12 = 0x000002bb, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF13 = 0x000002bc, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF14 = 0x000002bd, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF15 = 0x000002be, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF16 = 0x000002bf, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF17 = 0x000002c0, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF18 = 0x000002c1, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF19 = 0x000002c2, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF20 = 0x000002c3, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF21 = 0x000002c4, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF22 = 0x000002c5, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF23 = 0x000002c6, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF24 = 0x000002c7, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF25 = 0x000002c8, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF26 = 0x000002c9, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF27 = 0x000002ca, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF28 = 0x000002cb, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF29 = 0x000002cc, // RPTR load happens + IH_PERF_SEL_RB2_LOAD_RPTR_VF30 = 0x000002cd, // RPTR load happens +} IH_PERFCOUNTER_SELECT; + +typedef enum PH_PERFCOUNTER_SELECT : unsigned int { + PH_PERF_SEL_SC0_SRPS_WINDOW_VALID = 0x00000000, // PH_PERF_SEL_SC0_SRPS_WINDOW_VALID Counts PERFCOUNTER_START to PERFCOUNTER_STOP stop perfcounter enable window in PH Read Setup logic + PH_PERF_SEL_SC0_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES = 0x00000001, // PH_PERF_SEL_SC0_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES counts number of cycles of arb xfc's for all event or prims + PH_PERF_SEL_SC0_ARB_XFC_ONLY_PRIM_CYCLES = 0x00000002, // PH_PERF_SEL_SC0_ARB_XFC_ONLY_PRIM_CYCLES counts number of cycles of arb xfc's for only prims (events excluded) + PH_PERF_SEL_SC0_ARB_XFC_ONLY_ONE_INC_PER_PRIM = 0x00000003, // PH_PERF_SEL_SC0_ARB_XFC_ONLY_ONE_INC_PER_PRIM counts number of cycles of arb xfc's for one inc per prim only. Increments only for phase 0 of a multi-cycle primitive transfer + PH_PERF_SEL_SC0_ARB_STALLED_FROM_BELOW = 0x00000004, // PH_PERF_SEL_SC0_ARB_STALLED_FROM_BELOW counts number of cycles of stalled post arbiter for valid data + PH_PERF_SEL_SC0_ARB_STARVED_FROM_ABOVE = 0x00000005, // PH_PERF_SEL_SC0_ARB_STARVED_FROM_ABOVE counts number of cycles of PA starving SC in start-of-packet/eop range + PH_PERF_SEL_SC0_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY = 0x00000006, // PH_PERF_SEL_SC0_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY counts from above (pa) with an unselected pa fifo not empty (use if more than one pa only) + PH_PERF_SEL_SC0_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL = 0x00000007, // PH_PERF_SEL_SC0_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL counts starved by pa with a unselected pa fifo full (use if more than one pa only) This means that inside the draw packet the SC selected fifo has no valid data, and that one of the unselected fifo's has gone fifo's has gone full. + PH_PERF_SEL_SC0_ARB_BUSY = 0x00000008, // PH_PERF_SEL_SC0_ARB_BUSY counts number of cycles of PH_SC0 busy + PH_PERF_SEL_SC0_ARB_PA_BUSY_SOP = 0x00000009, // PH_PERF_SEL_SC0_ARB_PA_BUSY_SOP counts number of cycles in between start of packet/end of packet + PH_PERF_SEL_SC0_ARB_EOP_POP_SYNC_POP = 0x0000000a, // PH_PERF_SEL_SC0_ARB_EOP_POP_SYNC_POP counts number of cycles of of pa sc arbiter eop reads at the eop sync point with all fifos synced + PH_PERF_SEL_SC0_ARB_EVENT_SYNC_POP = 0x0000000b, // PH_PERF_SEL_SC0_ARB_EVENT_SYNC_POP counts number of cycles of pa sc event reads + PH_PERF_SEL_SC0_PS_ENG_MULTICYCLE_BUBBLE = 0x0000000c, // PH_PERF_SEL_SC0_PS_ENG_MULTICYCLE_BUBBLE counts number of cycles of multicycles prims sent with a empty fifo slot behind the current phase. + PH_PERF_SEL_SC0_EOP_SYNC_WINDOW = 0x0000000d, // PH_PERF_SEL_SC0_EOP_SYNC_WINDOW counts number of cycles of after end of packet is read from the selected pa sc fifo until end of packet broadcast synchronization is achieved across all pa sc fifos + PH_PERF_SEL_SC0_BUSY_PROCESSING_MULTICYCLE_PRIM = 0x0000000e, // PH_PERF_SEL_SC0_BUSY_PROCESSING_MULTICYCLE_PRIM counts number of cycles of sc arbiter busy processing multicycle prims (clipped, perspective linear gradient, line stipple) + PH_PERF_SEL_SC0_BUSY_CNT_NOT_ZERO = 0x0000000f, // PH_PERF_SEL_SC0_BUSY_CNT_NOT_ZERO counts number of cycles of ph-sc read setup busy counter non zero. + PH_PERF_SEL_SC0_SEND = 0x00000010, // PH_PERF_SEL_SC0_SEND counts interface sends to SC + PH_PERF_SEL_SC0_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x00000011, // PH_PERF_SEL_SC0_CREDIT_AT_ZERO_WITH_PENDING_SEND counts interface stalled for no SC credits with pending data available + PH_PERF_SEL_SC0_CREDIT_AT_MAX = 0x00000012, // PH_PERF_SEL_SC0_CREDIT_AT_MAX counts full PH_SC interface credit pool available (INTERFACE IDLE) + PH_PERF_SEL_SC0_CREDIT_AT_MAX_NO_PENDING_SEND = 0x00000013, // PH_PERF_SEL_SC0_CREDIT_AT_MAX_NO_PENDING_SEND counts full PH_SC interface credit pool available with no pending PH_SC data to send (FULL IDLE of PH_SC slice) + PH_PERF_SEL_SC0_GFX_PIPE_EVENT_PROVOKED_TRANSITION = 0x00000014, // PH_PERF_SEL_SC0_GFX_PIPE_EVENT_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by an EVENT associated with a new gfx pipe id + PH_PERF_SEL_SC0_GFX_PIPE_PRIM_PROVOKED_TRANSITION = 0x00000015, // PH_PERF_SEL_SC0_GFX_PIPE_PRIM_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by a primitive associated with a new gfx pipe id + PH_PERF_SEL_SC0_GFX_PIPE0_TO_1_TRANSITION = 0x00000016, // PH_PERF_SEL_SC0_GFX_PIPE0_TO_1_TRANSITION counts GFX PIPEID transitions from pipe0 to pipe1 + PH_PERF_SEL_SC0_GFX_PIPE1_TO_0_TRANSITION = 0x00000017, // PH_PERF_SEL_SC0_GFX_PIPE1_TO_0_TRANSITION counts GFX PIPEID transitions from pipe1 to pipe0 + PH_PERF_SEL_SC0_PA0_DATA_FIFO_RD = 0x00000018, // PH_PERF_SEL_SC0_PA0_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC0_PA0_DATA_FIFO_WE = 0x00000019, // PH_PERF_SEL_SC0_PA0_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC0_PA0_FIFO_EMPTY = 0x0000001a, // PH_PERF_SEL_SC0_PA0_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC0_PA0_FIFO_FULL = 0x0000001b, // PH_PERF_SEL_SC0_PA0_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC0_PA0_NULL_WE = 0x0000001c, // PH_PERF_SEL_SC0_PA0_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC0_PA0_EVENT_WE = 0x0000001d, // PH_PERF_SEL_SC0_PA0_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC0_PA0_FPOV_WE = 0x0000001e, // PH_PERF_SEL_SC0_PA0_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC0_PA0_LPOV_WE = 0x0000001f, // PH_PERF_SEL_SC0_PA0_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC0_PA0_EOP_WE = 0x00000020, // PH_PERF_SEL_SC0_PA0_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC0_PA0_DATA_FIFO_EOP_RD = 0x00000021, // PH_PERF_SEL_SC0_PA0_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC0_PA0_EOPG_WE = 0x00000022, // PH_PA0 PH_SC0_PA0_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC0_PA0_DEALLOC_4_0_RD = 0x00000023, // PH_PERF_SEL_SC0_PA0_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC0_PA1_DATA_FIFO_RD = 0x00000024, // PH_PERF_SEL_SC0_PA1_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC0_PA1_DATA_FIFO_WE = 0x00000025, // PH_PERF_SEL_SC0_PA1_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC0_PA1_FIFO_EMPTY = 0x00000026, // PH_PERF_SEL_SC0_PA1_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC0_PA1_FIFO_FULL = 0x00000027, // PH_PERF_SEL_SC0_PA1_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC0_PA1_NULL_WE = 0x00000028, // PH_PERF_SEL_SC0_PA1_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC0_PA1_EVENT_WE = 0x00000029, // PH_PERF_SEL_SC0_PA1_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC0_PA1_FPOV_WE = 0x0000002a, // PH_PERF_SEL_SC0_PA1_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC0_PA1_LPOV_WE = 0x0000002b, // PH_PERF_SEL_SC0_PA1_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC0_PA1_EOP_WE = 0x0000002c, // PH_PERF_SEL_SC0_PA1_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC0_PA1_DATA_FIFO_EOP_RD = 0x0000002d, // PH_PERF_SEL_SC0_PA1_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC0_PA1_EOPG_WE = 0x0000002e, // PH_PA1 PH_SC0_PA1_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC0_PA1_DEALLOC_4_0_RD = 0x0000002f, // PH_PERF_SEL_SC0_PA1_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC0_PA2_DATA_FIFO_RD = 0x00000030, // PH_PERF_SEL_SC0_PA2_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC0_PA2_DATA_FIFO_WE = 0x00000031, // PH_PERF_SEL_SC0_PA2_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC0_PA2_FIFO_EMPTY = 0x00000032, // PH_PERF_SEL_SC0_PA2_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC0_PA2_FIFO_FULL = 0x00000033, // PH_PERF_SEL_SC0_PA2_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC0_PA2_NULL_WE = 0x00000034, // PH_PERF_SEL_SC0_PA2_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC0_PA2_EVENT_WE = 0x00000035, // PH_PERF_SEL_SC0_PA2_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC0_PA2_FPOV_WE = 0x00000036, // PH_PERF_SEL_SC0_PA2_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC0_PA2_LPOV_WE = 0x00000037, // PH_PERF_SEL_SC0_PA2_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC0_PA2_EOP_WE = 0x00000038, // PH_PERF_SEL_SC0_PA2_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC0_PA2_DATA_FIFO_EOP_RD = 0x00000039, // PH_PERF_SEL_SC0_PA2_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC0_PA2_EOPG_WE = 0x0000003a, // PH_PA2 PH_SC0_PA2_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC0_PA2_DEALLOC_4_0_RD = 0x0000003b, // PH_PERF_SEL_SC0_PA2_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC0_PA3_DATA_FIFO_RD = 0x0000003c, // PH_PERF_SEL_SC0_PA3_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC0_PA3_DATA_FIFO_WE = 0x0000003d, // PH_PERF_SEL_SC0_PA3_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC0_PA3_FIFO_EMPTY = 0x0000003e, // PH_PERF_SEL_SC0_PA3_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC0_PA3_FIFO_FULL = 0x0000003f, // PH_PERF_SEL_SC0_PA3_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC0_PA3_NULL_WE = 0x00000040, // PH_PERF_SEL_SC0_PA3_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC0_PA3_EVENT_WE = 0x00000041, // PH_PERF_SEL_SC0_PA3_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC0_PA3_FPOV_WE = 0x00000042, // PH_PERF_SEL_SC0_PA3_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC0_PA3_LPOV_WE = 0x00000043, // PH_PERF_SEL_SC0_PA3_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC0_PA3_EOP_WE = 0x00000044, // PH_PERF_SEL_SC0_PA3_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC0_PA3_DATA_FIFO_EOP_RD = 0x00000045, // PH_PERF_SEL_SC0_PA3_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC0_PA3_EOPG_WE = 0x00000046, // PH_PA3 PH_SC0_PA3_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC0_PA3_DEALLOC_4_0_RD = 0x00000047, // PH_PERF_SEL_SC0_PA3_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC0_PA4_DATA_FIFO_RD = 0x00000048, // PH_PERF_SEL_SC0_PA4_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC0_PA4_DATA_FIFO_WE = 0x00000049, // PH_PERF_SEL_SC0_PA4_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC0_PA4_FIFO_EMPTY = 0x0000004a, // PH_PERF_SEL_SC0_PA4_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC0_PA4_FIFO_FULL = 0x0000004b, // PH_PERF_SEL_SC0_PA4_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC0_PA4_NULL_WE = 0x0000004c, // PH_PERF_SEL_SC0_PA4_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC0_PA4_EVENT_WE = 0x0000004d, // PH_PERF_SEL_SC0_PA4_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC0_PA4_FPOV_WE = 0x0000004e, // PH_PERF_SEL_SC0_PA4_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC0_PA4_LPOV_WE = 0x0000004f, // PH_PERF_SEL_SC0_PA4_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC0_PA4_EOP_WE = 0x00000050, // PH_PERF_SEL_SC0_PA4_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC0_PA4_DATA_FIFO_EOP_RD = 0x00000051, // PH_PERF_SEL_SC0_PA4_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC0_PA4_EOPG_WE = 0x00000052, // PH_PA4 PH_SC0_PA4_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC0_PA4_DEALLOC_4_0_RD = 0x00000053, // PH_PERF_SEL_SC0_PA4_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC0_PA5_DATA_FIFO_RD = 0x00000054, // PH_PERF_SEL_SC0_PA5_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC0_PA5_DATA_FIFO_WE = 0x00000055, // PH_PERF_SEL_SC0_PA5_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC0_PA5_FIFO_EMPTY = 0x00000056, // PH_PERF_SEL_SC0_PA5_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC0_PA5_FIFO_FULL = 0x00000057, // PH_PERF_SEL_SC0_PA5_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC0_PA5_NULL_WE = 0x00000058, // PH_PERF_SEL_SC0_PA5_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC0_PA5_EVENT_WE = 0x00000059, // PH_PERF_SEL_SC0_PA5_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC0_PA5_FPOV_WE = 0x0000005a, // PH_PERF_SEL_SC0_PA5_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC0_PA5_LPOV_WE = 0x0000005b, // PH_PERF_SEL_SC0_PA5_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC0_PA5_EOP_WE = 0x0000005c, // PH_PERF_SEL_SC0_PA5_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC0_PA5_DATA_FIFO_EOP_RD = 0x0000005d, // PH_PERF_SEL_SC0_PA5_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC0_PA5_EOPG_WE = 0x0000005e, // PH_PA5 PH_SC0_PA5_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC0_PA5_DEALLOC_4_0_RD = 0x0000005f, // PH_PERF_SEL_SC0_PA5_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC0_PA6_DATA_FIFO_RD = 0x00000060, // PH_PERF_SEL_SC0_PA6_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC0_PA6_DATA_FIFO_WE = 0x00000061, // PH_PERF_SEL_SC0_PA6_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC0_PA6_FIFO_EMPTY = 0x00000062, // PH_PERF_SEL_SC0_PA6_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC0_PA6_FIFO_FULL = 0x00000063, // PH_PERF_SEL_SC0_PA6_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC0_PA6_NULL_WE = 0x00000064, // PH_PERF_SEL_SC0_PA6_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC0_PA6_EVENT_WE = 0x00000065, // PH_PERF_SEL_SC0_PA6_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC0_PA6_FPOV_WE = 0x00000066, // PH_PERF_SEL_SC0_PA6_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC0_PA6_LPOV_WE = 0x00000067, // PH_PERF_SEL_SC0_PA6_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC0_PA6_EOP_WE = 0x00000068, // PH_PERF_SEL_SC0_PA6_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC0_PA6_DATA_FIFO_EOP_RD = 0x00000069, // PH_PERF_SEL_SC0_PA6_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC0_PA6_EOPG_WE = 0x0000006a, // PH_PA6 PH_SC0_PA6_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC0_PA6_DEALLOC_4_0_RD = 0x0000006b, // PH_PERF_SEL_SC0_PA6_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC0_PA7_DATA_FIFO_RD = 0x0000006c, // PH_PERF_SEL_SC0_PA7_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC0_PA7_DATA_FIFO_WE = 0x0000006d, // PH_PERF_SEL_SC0_PA7_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC0_PA7_FIFO_EMPTY = 0x0000006e, // PH_PERF_SEL_SC0_PA7_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC0_PA7_FIFO_FULL = 0x0000006f, // PH_PERF_SEL_SC0_PA7_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC0_PA7_NULL_WE = 0x00000070, // PH_PERF_SEL_SC0_PA7_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC0_PA7_EVENT_WE = 0x00000071, // PH_PERF_SEL_SC0_PA7_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC0_PA7_FPOV_WE = 0x00000072, // PH_PERF_SEL_SC0_PA7_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC0_PA7_LPOV_WE = 0x00000073, // PH_PERF_SEL_SC0_PA7_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC0_PA7_EOP_WE = 0x00000074, // PH_PERF_SEL_SC0_PA7_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC0_PA7_DATA_FIFO_EOP_RD = 0x00000075, // PH_PERF_SEL_SC0_PA7_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC0_PA7_EOPG_WE = 0x00000076, // PH_PA7 PH_SC0_PA7_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC0_PA7_DEALLOC_4_0_RD = 0x00000077, // PH_PERF_SEL_SC0_PA7_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC1_SRPS_WINDOW_VALID = 0x00000078, // PH_PERF_SEL_SC1_SRPS_WINDOW_VALID Counts PERFCOUNTER_START to PERFCOUNTER_STOP stop perfcounter enable window in PH Read Setup logic + PH_PERF_SEL_SC1_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES = 0x00000079, // PH_PERF_SEL_SC1_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES counts number of cycles of arb xfc's for all event or prims + PH_PERF_SEL_SC1_ARB_XFC_ONLY_PRIM_CYCLES = 0x0000007a, // PH_PERF_SEL_SC1_ARB_XFC_ONLY_PRIM_CYCLES counts number of cycles of arb xfc's for only prims (events excluded) + PH_PERF_SEL_SC1_ARB_XFC_ONLY_ONE_INC_PER_PRIM = 0x0000007b, // PH_PERF_SEL_SC1_ARB_XFC_ONLY_ONE_INC_PER_PRIM counts number of cycles of arb xfc's for one inc per prim only. Increments only for phase 0 of a multi-cycle primitive transfer + PH_PERF_SEL_SC1_ARB_STALLED_FROM_BELOW = 0x0000007c, // PH_PERF_SEL_SC1_ARB_STALLED_FROM_BELOW counts number of cycles of stalled post arbiter for valid data + PH_PERF_SEL_SC1_ARB_STARVED_FROM_ABOVE = 0x0000007d, // PH_PERF_SEL_SC1_ARB_STARVED_FROM_ABOVE counts number of cycles of PA starving SC in start-of-packet/eop range + PH_PERF_SEL_SC1_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY = 0x0000007e, // PH_PERF_SEL_SC1_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY counts from above (pa) with an unselected pa fifo not empty (use if more than one pa only) + PH_PERF_SEL_SC1_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL = 0x0000007f, // PH_PERF_SEL_SC1_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL counts starved by pa with a unselected pa fifo full (use if more than one pa only) This means that inside the draw packet the SC selected fifo has no valid data, and that one of the unselected fifo's has gone fifo's has gone full. + PH_PERF_SEL_SC1_ARB_BUSY = 0x00000080, // PH_PERF_SEL_SC1_ARB_BUSY counts number of cycles of PH_SC1 busy + PH_PERF_SEL_SC1_ARB_PA_BUSY_SOP = 0x00000081, // PH_PERF_SEL_SC1_ARB_PA_BUSY_SOP counts number of cycles in between start of packet/end of packet + PH_PERF_SEL_SC1_ARB_EOP_POP_SYNC_POP = 0x00000082, // PH_PERF_SEL_SC1_ARB_EOP_POP_SYNC_POP counts number of cycles of of pa sc arbiter eop reads at the eop sync point with all fifos synced + PH_PERF_SEL_SC1_ARB_EVENT_SYNC_POP = 0x00000083, // PH_PERF_SEL_SC1_ARB_EVENT_SYNC_POP counts number of cycles of pa sc event reads + PH_PERF_SEL_SC1_PS_ENG_MULTICYCLE_BUBBLE = 0x00000084, // PH_PERF_SEL_SC1_PS_ENG_MULTICYCLE_BUBBLE counts number of cycles of multicycles prims sent with a empty fifo slot behind the current phase. + PH_PERF_SEL_SC1_EOP_SYNC_WINDOW = 0x00000085, // PH_PERF_SEL_SC1_EOP_SYNC_WINDOW counts number of cycles of after end of packet is read from the selected pa sc fifo until end of packet broadcast synchronization is achieved across all pa sc fifos + PH_PERF_SEL_SC1_BUSY_PROCESSING_MULTICYCLE_PRIM = 0x00000086, // PH_PERF_SEL_SC1_BUSY_PROCESSING_MULTICYCLE_PRIM counts number of cycles of sc arbiter busy processing multicycle prims (clipped, perspective linear gradient, line stipple) + PH_PERF_SEL_SC1_BUSY_CNT_NOT_ZERO = 0x00000087, // PH_PERF_SEL_SC1_BUSY_CNT_NOT_ZERO counts number of cycles of ph-sc read setup busy counter non zero. + PH_PERF_SEL_SC1_SEND = 0x00000088, // PH_PERF_SEL_SC1_SEND counts interface sends to SC + PH_PERF_SEL_SC1_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x00000089, // PH_PERF_SEL_SC1_CREDIT_AT_ZERO_WITH_PENDING_SEND counts interface stalled for no SC credits with pending data available + PH_PERF_SEL_SC1_CREDIT_AT_MAX = 0x0000008a, // PH_PERF_SEL_SC1_CREDIT_AT_MAX counts full PH_SC interface credit pool available (INTERFACE IDLE) + PH_PERF_SEL_SC1_CREDIT_AT_MAX_NO_PENDING_SEND = 0x0000008b, // PH_PERF_SEL_SC1_CREDIT_AT_MAX_NO_PENDING_SEND counts full PH_SC interface credit pool available with no pending PH_SC data to send (FULL IDLE of PH_SC slice) + PH_PERF_SEL_SC1_GFX_PIPE_EVENT_PROVOKED_TRANSITION = 0x0000008c, // PH_PERF_SEL_SC1_GFX_PIPE_EVENT_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by an EVENT associated with a new gfx pipe id + PH_PERF_SEL_SC1_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION = 0x0000008d, // PH_PERF_SEL_SC1_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by a primitive associated with a new gfx pipe id + PH_PERF_SEL_SC1_GFX_PIPE0_TO_1_TRANSITION = 0x0000008e, // PH_PERF_SEL_SC1_GFX_PIPE0_TO_1_TRANSITION counts GFX PIPEID transitions from pipe0 to pipe1 + PH_PERF_SEL_SC1_GFX_PIPE1_TO_0_TRANSITION = 0x0000008f, // PH_PERF_SEL_SC1_GFX_PIPE1_TO_0_TRANSITION counts GFX PIPEID transitions from pipe1 to pipe0 + PH_PERF_SEL_SC1_PA0_DATA_FIFO_RD = 0x00000090, // PH_PERF_SEL_SC1_PA0_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC1_PA0_DATA_FIFO_WE = 0x00000091, // PH_PERF_SEL_SC1_PA0_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC1_PA0_FIFO_EMPTY = 0x00000092, // PH_PERF_SEL_SC1_PA0_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC1_PA0_FIFO_FULL = 0x00000093, // PH_PERF_SEL_SC1_PA0_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC1_PA0_NULL_WE = 0x00000094, // PH_PERF_SEL_SC1_PA0_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC1_PA0_EVENT_WE = 0x00000095, // PH_PERF_SEL_SC1_PA0_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC1_PA0_FPOV_WE = 0x00000096, // PH_PERF_SEL_SC1_PA0_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC1_PA0_LPOV_WE = 0x00000097, // PH_PERF_SEL_SC1_PA0_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC1_PA0_EOP_WE = 0x00000098, // PH_PERF_SEL_SC1_PA0_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC1_PA0_DATA_FIFO_EOP_RD = 0x00000099, // PH_PERF_SEL_SC1_PA0_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC1_PA0_EOPG_WE = 0x0000009a, // PH_PA0 PH_SC1_PA0_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC1_PA0_DEALLOC_4_0_RD = 0x0000009b, // PH_PERF_SEL_SC1_PA0_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC1_PA1_DATA_FIFO_RD = 0x0000009c, // PH_PERF_SEL_SC1_PA1_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC1_PA1_DATA_FIFO_WE = 0x0000009d, // PH_PERF_SEL_SC1_PA1_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC1_PA1_FIFO_EMPTY = 0x0000009e, // PH_PERF_SEL_SC1_PA1_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC1_PA1_FIFO_FULL = 0x0000009f, // PH_PERF_SEL_SC1_PA1_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC1_PA1_NULL_WE = 0x000000a0, // PH_PERF_SEL_SC1_PA1_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC1_PA1_EVENT_WE = 0x000000a1, // PH_PERF_SEL_SC1_PA1_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC1_PA1_FPOV_WE = 0x000000a2, // PH_PERF_SEL_SC1_PA1_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC1_PA1_LPOV_WE = 0x000000a3, // PH_PERF_SEL_SC1_PA1_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC1_PA1_EOP_WE = 0x000000a4, // PH_PERF_SEL_SC1_PA1_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC1_PA1_DATA_FIFO_EOP_RD = 0x000000a5, // PH_PERF_SEL_SC1_PA1_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC1_PA1_EOPG_WE = 0x000000a6, // PH_PA1 PH_SC1_PA1_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC1_PA1_DEALLOC_4_0_RD = 0x000000a7, // PH_PERF_SEL_SC1_PA1_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC1_PA2_DATA_FIFO_RD = 0x000000a8, // PH_PERF_SEL_SC1_PA2_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC1_PA2_DATA_FIFO_WE = 0x000000a9, // PH_PERF_SEL_SC1_PA2_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC1_PA2_FIFO_EMPTY = 0x000000aa, // PH_PERF_SEL_SC1_PA2_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC1_PA2_FIFO_FULL = 0x000000ab, // PH_PERF_SEL_SC1_PA2_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC1_PA2_NULL_WE = 0x000000ac, // PH_PERF_SEL_SC1_PA2_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC1_PA2_EVENT_WE = 0x000000ad, // PH_PERF_SEL_SC1_PA2_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC1_PA2_FPOV_WE = 0x000000ae, // PH_PERF_SEL_SC1_PA2_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC1_PA2_LPOV_WE = 0x000000af, // PH_PERF_SEL_SC1_PA2_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC1_PA2_EOP_WE = 0x000000b0, // PH_PERF_SEL_SC1_PA2_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC1_PA2_DATA_FIFO_EOP_RD = 0x000000b1, // PH_PERF_SEL_SC1_PA2_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC1_PA2_EOPG_WE = 0x000000b2, // PH_PA2 PH_SC1_PA2_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC1_PA2_DEALLOC_4_0_RD = 0x000000b3, // PH_PERF_SEL_SC1_PA2_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC1_PA3_DATA_FIFO_RD = 0x000000b4, // PH_PERF_SEL_SC1_PA3_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC1_PA3_DATA_FIFO_WE = 0x000000b5, // PH_PERF_SEL_SC1_PA3_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC1_PA3_FIFO_EMPTY = 0x000000b6, // PH_PERF_SEL_SC1_PA3_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC1_PA3_FIFO_FULL = 0x000000b7, // PH_PERF_SEL_SC1_PA3_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC1_PA3_NULL_WE = 0x000000b8, // PH_PERF_SEL_SC1_PA3_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC1_PA3_EVENT_WE = 0x000000b9, // PH_PERF_SEL_SC1_PA3_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC1_PA3_FPOV_WE = 0x000000ba, // PH_PERF_SEL_SC1_PA3_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC1_PA3_LPOV_WE = 0x000000bb, // PH_PERF_SEL_SC1_PA3_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC1_PA3_EOP_WE = 0x000000bc, // PH_PERF_SEL_SC1_PA3_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC1_PA3_DATA_FIFO_EOP_RD = 0x000000bd, // PH_PERF_SEL_SC1_PA3_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC1_PA3_EOPG_WE = 0x000000be, // PH_PA3 PH_SC1_PA3_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC1_PA3_DEALLOC_4_0_RD = 0x000000bf, // PH_PERF_SEL_SC1_PA3_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC1_PA4_DATA_FIFO_RD = 0x000000c0, // PH_PERF_SEL_SC1_PA4_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC1_PA4_DATA_FIFO_WE = 0x000000c1, // PH_PERF_SEL_SC1_PA4_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC1_PA4_FIFO_EMPTY = 0x000000c2, // PH_PERF_SEL_SC1_PA4_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC1_PA4_FIFO_FULL = 0x000000c3, // PH_PERF_SEL_SC1_PA4_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC1_PA4_NULL_WE = 0x000000c4, // PH_PERF_SEL_SC1_PA4_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC1_PA4_EVENT_WE = 0x000000c5, // PH_PERF_SEL_SC1_PA4_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC1_PA4_FPOV_WE = 0x000000c6, // PH_PERF_SEL_SC1_PA4_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC1_PA4_LPOV_WE = 0x000000c7, // PH_PERF_SEL_SC1_PA4_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC1_PA4_EOP_WE = 0x000000c8, // PH_PERF_SEL_SC1_PA4_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC1_PA4_DATA_FIFO_EOP_RD = 0x000000c9, // PH_PERF_SEL_SC1_PA4_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC1_PA4_EOPG_WE = 0x000000ca, // PH_PA4 PH_SC1_PA4_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC1_PA4_DEALLOC_4_0_RD = 0x000000cb, // PH_PERF_SEL_SC1_PA4_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC1_PA5_DATA_FIFO_RD = 0x000000cc, // PH_PERF_SEL_SC1_PA5_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC1_PA5_DATA_FIFO_WE = 0x000000cd, // PH_PERF_SEL_SC1_PA5_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC1_PA5_FIFO_EMPTY = 0x000000ce, // PH_PERF_SEL_SC1_PA5_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC1_PA5_FIFO_FULL = 0x000000cf, // PH_PERF_SEL_SC1_PA5_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC1_PA5_NULL_WE = 0x000000d0, // PH_PERF_SEL_SC1_PA5_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC1_PA5_EVENT_WE = 0x000000d1, // PH_PERF_SEL_SC1_PA5_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC1_PA5_FPOV_WE = 0x000000d2, // PH_PERF_SEL_SC1_PA5_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC1_PA5_LPOV_WE = 0x000000d3, // PH_PERF_SEL_SC1_PA5_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC1_PA5_EOP_WE = 0x000000d4, // PH_PERF_SEL_SC1_PA5_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC1_PA5_DATA_FIFO_EOP_RD = 0x000000d5, // PH_PERF_SEL_SC1_PA5_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC1_PA5_EOPG_WE = 0x000000d6, // PH_PA5 PH_SC1_PA5_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC1_PA5_DEALLOC_4_0_RD = 0x000000d7, // PH_PERF_SEL_SC1_PA5_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC1_PA6_DATA_FIFO_RD = 0x000000d8, // PH_PERF_SEL_SC1_PA6_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC1_PA6_DATA_FIFO_WE = 0x000000d9, // PH_PERF_SEL_SC1_PA6_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC1_PA6_FIFO_EMPTY = 0x000000da, // PH_PERF_SEL_SC1_PA6_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC1_PA6_FIFO_FULL = 0x000000db, // PH_PERF_SEL_SC1_PA6_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC1_PA6_NULL_WE = 0x000000dc, // PH_PERF_SEL_SC1_PA6_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC1_PA6_EVENT_WE = 0x000000dd, // PH_PERF_SEL_SC1_PA6_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC1_PA6_FPOV_WE = 0x000000de, // PH_PERF_SEL_SC1_PA6_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC1_PA6_LPOV_WE = 0x000000df, // PH_PERF_SEL_SC1_PA6_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC1_PA6_EOP_WE = 0x000000e0, // PH_PERF_SEL_SC1_PA6_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC1_PA6_DATA_FIFO_EOP_RD = 0x000000e1, // PH_PERF_SEL_SC1_PA6_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC1_PA6_EOPG_WE = 0x000000e2, // PH_PA6 PH_SC1_PA6_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC1_PA6_DEALLOC_4_0_RD = 0x000000e3, // PH_PERF_SEL_SC1_PA6_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC1_PA7_DATA_FIFO_RD = 0x000000e4, // PH_PERF_SEL_SC1_PA7_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC1_PA7_DATA_FIFO_WE = 0x000000e5, // PH_PERF_SEL_SC1_PA7_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC1_PA7_FIFO_EMPTY = 0x000000e6, // PH_PERF_SEL_SC1_PA7_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC1_PA7_FIFO_FULL = 0x000000e7, // PH_PERF_SEL_SC1_PA7_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC1_PA7_NULL_WE = 0x000000e8, // PH_PERF_SEL_SC1_PA7_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC1_PA7_EVENT_WE = 0x000000e9, // PH_PERF_SEL_SC1_PA7_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC1_PA7_FPOV_WE = 0x000000ea, // PH_PERF_SEL_SC1_PA7_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC1_PA7_LPOV_WE = 0x000000eb, // PH_PERF_SEL_SC1_PA7_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC1_PA7_EOP_WE = 0x000000ec, // PH_PERF_SEL_SC1_PA7_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC1_PA7_DATA_FIFO_EOP_RD = 0x000000ed, // PH_PERF_SEL_SC1_PA7_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC1_PA7_EOPG_WE = 0x000000ee, // PH_PA7 PH_SC1_PA7_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC1_PA7_DEALLOC_4_0_RD = 0x000000ef, // PH_PERF_SEL_SC1_PA7_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC2_SRPS_WINDOW_VALID = 0x000000f0, // PH_PERF_SEL_SC2_SRPS_WINDOW_VALID Counts PERFCOUNTER_START to PERFCOUNTER_STOP stop perfcounter enable window in PH Read Setup logic + PH_PERF_SEL_SC2_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES = 0x000000f1, // PH_PERF_SEL_SC2_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES counts number of cycles of arb xfc's for all event or prims + PH_PERF_SEL_SC2_ARB_XFC_ONLY_PRIM_CYCLES = 0x000000f2, // PH_PERF_SEL_SC2_ARB_XFC_ONLY_PRIM_CYCLES counts number of cycles of arb xfc's for only prims (events excluded) + PH_PERF_SEL_SC2_ARB_XFC_ONLY_ONE_INC_PER_PRIM = 0x000000f3, // PH_PERF_SEL_SC2_ARB_XFC_ONLY_ONE_INC_PER_PRIM counts number of cycles of arb xfc's for one inc per prim only. Increments only for phase 0 of a multi-cycle primitive transfer + PH_PERF_SEL_SC2_ARB_STALLED_FROM_BELOW = 0x000000f4, // PH_PERF_SEL_SC2_ARB_STALLED_FROM_BELOW counts number of cycles of stalled post arbiter for valid data + PH_PERF_SEL_SC2_ARB_STARVED_FROM_ABOVE = 0x000000f5, // PH_PERF_SEL_SC2_ARB_STARVED_FROM_ABOVE counts number of cycles of PA starving SC in start-of-packet/eop range + PH_PERF_SEL_SC2_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY = 0x000000f6, // PH_PERF_SEL_SC2_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY counts from above (pa) with an unselected pa fifo not empty (use if more than one pa only) + PH_PERF_SEL_SC2_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL = 0x000000f7, // PH_PERF_SEL_SC2_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL counts starved by pa with a unselected pa fifo full (use if more than one pa only) This means that inside the draw packet the SC selected fifo has no valid data, and that one of the unselected fifo's has gone fifo's has gone full. + PH_PERF_SEL_SC2_ARB_BUSY = 0x000000f8, // PH_PERF_SEL_SC2_ARB_BUSY counts number of cycles of PH_SC2 busy + PH_PERF_SEL_SC2_ARB_PA_BUSY_SOP = 0x000000f9, // PH_PERF_SEL_SC2_ARB_PA_BUSY_SOP counts number of cycles in between start of packet/end of packet + PH_PERF_SEL_SC2_ARB_EOP_POP_SYNC_POP = 0x000000fa, // PH_PERF_SEL_SC2_ARB_EOP_POP_SYNC_POP counts number of cycles of of pa sc arbiter eop reads at the eop sync point with all fifos synced + PH_PERF_SEL_SC2_ARB_EVENT_SYNC_POP = 0x000000fb, // PH_PERF_SEL_SC2_ARB_EVENT_SYNC_POP counts number of cycles of pa sc event reads + PH_PERF_SEL_SC2_PS_ENG_MULTICYCLE_BUBBLE = 0x000000fc, // PH_PERF_SEL_SC2_PS_ENG_MULTICYCLE_BUBBLE counts number of cycles of multicycles prims sent with a empty fifo slot behind the current phase. + PH_PERF_SEL_SC2_EOP_SYNC_WINDOW = 0x000000fd, // PH_PERF_SEL_SC2_EOP_SYNC_WINDOW counts number of cycles of after end of packet is read from the selected pa sc fifo until end of packet broadcast synchronization is achieved across all pa sc fifos + PH_PERF_SEL_SC2_BUSY_PROCESSING_MULTICYCLE_PRIM = 0x000000fe, // PH_PERF_SEL_SC2_BUSY_PROCESSING_MULTICYCLE_PRIM counts number of cycles of sc arbiter busy processing multicycle prims (clipped, perspective linear gradient, line stipple) + PH_PERF_SEL_SC2_BUSY_CNT_NOT_ZERO = 0x000000ff, // PH_PERF_SEL_SC2_BUSY_CNT_NOT_ZERO counts number of cycles of ph-sc read setup busy counter non zero. + PH_PERF_SEL_SC2_SEND = 0x00000100, // PH_PERF_SEL_SC2_SEND counts interface sends to SC + PH_PERF_SEL_SC2_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x00000101, // PH_PERF_SEL_SC2_CREDIT_AT_ZERO_WITH_PENDING_SEND counts interface stalled for no SC credits with pending data available + PH_PERF_SEL_SC2_CREDIT_AT_MAX = 0x00000102, // PH_PERF_SEL_SC2_CREDIT_AT_MAX counts full PH_SC interface credit pool available (INTERFACE IDLE) + PH_PERF_SEL_SC2_CREDIT_AT_MAX_NO_PENDING_SEND = 0x00000103, // PH_PERF_SEL_SC2_CREDIT_AT_MAX_NO_PENDING_SEND counts full PH_SC interface credit pool available with no pending PH_SC data to send (FULL IDLE of PH_SC slice) + PH_PERF_SEL_SC2_GFX_PIPE_EVENT_PROVOKED_TRANSITION = 0x00000104, // PH_PERF_SEL_SC2_GFX_PIPE_EVENT_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by an EVENT associated with a new gfx pipe id + PH_PERF_SEL_SC2_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION = 0x00000105, // PH_PERF_SEL_SC2_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by a primitive associated with a new gfx pipe id + PH_PERF_SEL_SC2_GFX_PIPE0_TO_1_TRANSITION = 0x00000106, // PH_PERF_SEL_SC2_GFX_PIPE0_TO_1_TRANSITION counts GFX PIPEID transitions from pipe0 to pipe1 + PH_PERF_SEL_SC2_GFX_PIPE1_TO_0_TRANSITION = 0x00000107, // PH_PERF_SEL_SC2_GFX_PIPE1_TO_0_TRANSITION counts GFX PIPEID transitions from pipe1 to pipe0 + PH_PERF_SEL_SC2_PA0_DATA_FIFO_RD = 0x00000108, // PH_PERF_SEL_SC2_PA0_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC2_PA0_DATA_FIFO_WE = 0x00000109, // PH_PERF_SEL_SC2_PA0_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC2_PA0_FIFO_EMPTY = 0x0000010a, // PH_PERF_SEL_SC2_PA0_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC2_PA0_FIFO_FULL = 0x0000010b, // PH_PERF_SEL_SC2_PA0_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC2_PA0_NULL_WE = 0x0000010c, // PH_PERF_SEL_SC2_PA0_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC2_PA0_EVENT_WE = 0x0000010d, // PH_PERF_SEL_SC2_PA0_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC2_PA0_FPOV_WE = 0x0000010e, // PH_PERF_SEL_SC2_PA0_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC2_PA0_LPOV_WE = 0x0000010f, // PH_PERF_SEL_SC2_PA0_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC2_PA0_EOP_WE = 0x00000110, // PH_PERF_SEL_SC2_PA0_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC2_PA0_DATA_FIFO_EOP_RD = 0x00000111, // PH_PERF_SEL_SC2_PA0_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC2_PA0_EOPG_WE = 0x00000112, // PH_PA0 PH_SC2_PA0_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC2_PA0_DEALLOC_4_0_RD = 0x00000113, // PH_PERF_SEL_SC2_PA0_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC2_PA1_DATA_FIFO_RD = 0x00000114, // PH_PERF_SEL_SC2_PA1_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC2_PA1_DATA_FIFO_WE = 0x00000115, // PH_PERF_SEL_SC2_PA1_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC2_PA1_FIFO_EMPTY = 0x00000116, // PH_PERF_SEL_SC2_PA1_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC2_PA1_FIFO_FULL = 0x00000117, // PH_PERF_SEL_SC2_PA1_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC2_PA1_NULL_WE = 0x00000118, // PH_PERF_SEL_SC2_PA1_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC2_PA1_EVENT_WE = 0x00000119, // PH_PERF_SEL_SC2_PA1_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC2_PA1_FPOV_WE = 0x0000011a, // PH_PERF_SEL_SC2_PA1_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC2_PA1_LPOV_WE = 0x0000011b, // PH_PERF_SEL_SC2_PA1_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC2_PA1_EOP_WE = 0x0000011c, // PH_PERF_SEL_SC2_PA1_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC2_PA1_DATA_FIFO_EOP_RD = 0x0000011d, // PH_PERF_SEL_SC2_PA1_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC2_PA1_EOPG_WE = 0x0000011e, // PH_PA1 PH_SC2_PA1_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC2_PA1_DEALLOC_4_0_RD = 0x0000011f, // PH_PERF_SEL_SC2_PA1_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC2_PA2_DATA_FIFO_RD = 0x00000120, // PH_PERF_SEL_SC2_PA2_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC2_PA2_DATA_FIFO_WE = 0x00000121, // PH_PERF_SEL_SC2_PA2_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC2_PA2_FIFO_EMPTY = 0x00000122, // PH_PERF_SEL_SC2_PA2_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC2_PA2_FIFO_FULL = 0x00000123, // PH_PERF_SEL_SC2_PA2_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC2_PA2_NULL_WE = 0x00000124, // PH_PERF_SEL_SC2_PA2_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC2_PA2_EVENT_WE = 0x00000125, // PH_PERF_SEL_SC2_PA2_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC2_PA2_FPOV_WE = 0x00000126, // PH_PERF_SEL_SC2_PA2_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC2_PA2_LPOV_WE = 0x00000127, // PH_PERF_SEL_SC2_PA2_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC2_PA2_EOP_WE = 0x00000128, // PH_PERF_SEL_SC2_PA2_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC2_PA2_DATA_FIFO_EOP_RD = 0x00000129, // PH_PERF_SEL_SC2_PA2_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC2_PA2_EOPG_WE = 0x0000012a, // PH_PA2 PH_SC2_PA2_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC2_PA2_DEALLOC_4_0_RD = 0x0000012b, // PH_PERF_SEL_SC2_PA2_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC2_PA3_DATA_FIFO_RD = 0x0000012c, // PH_PERF_SEL_SC2_PA3_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC2_PA3_DATA_FIFO_WE = 0x0000012d, // PH_PERF_SEL_SC2_PA3_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC2_PA3_FIFO_EMPTY = 0x0000012e, // PH_PERF_SEL_SC2_PA3_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC2_PA3_FIFO_FULL = 0x0000012f, // PH_PERF_SEL_SC2_PA3_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC2_PA3_NULL_WE = 0x00000130, // PH_PERF_SEL_SC2_PA3_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC2_PA3_EVENT_WE = 0x00000131, // PH_PERF_SEL_SC2_PA3_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC2_PA3_FPOV_WE = 0x00000132, // PH_PERF_SEL_SC2_PA3_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC2_PA3_LPOV_WE = 0x00000133, // PH_PERF_SEL_SC2_PA3_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC2_PA3_EOP_WE = 0x00000134, // PH_PERF_SEL_SC2_PA3_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC2_PA3_DATA_FIFO_EOP_RD = 0x00000135, // PH_PERF_SEL_SC2_PA3_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC2_PA3_EOPG_WE = 0x00000136, // PH_PA3 PH_SC2_PA3_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC2_PA3_DEALLOC_4_0_RD = 0x00000137, // PH_PERF_SEL_SC2_PA3_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC2_PA4_DATA_FIFO_RD = 0x00000138, // PH_PERF_SEL_SC2_PA4_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC2_PA4_DATA_FIFO_WE = 0x00000139, // PH_PERF_SEL_SC2_PA4_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC2_PA4_FIFO_EMPTY = 0x0000013a, // PH_PERF_SEL_SC2_PA4_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC2_PA4_FIFO_FULL = 0x0000013b, // PH_PERF_SEL_SC2_PA4_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC2_PA4_NULL_WE = 0x0000013c, // PH_PERF_SEL_SC2_PA4_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC2_PA4_EVENT_WE = 0x0000013d, // PH_PERF_SEL_SC2_PA4_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC2_PA4_FPOV_WE = 0x0000013e, // PH_PERF_SEL_SC2_PA4_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC2_PA4_LPOV_WE = 0x0000013f, // PH_PERF_SEL_SC2_PA4_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC2_PA4_EOP_WE = 0x00000140, // PH_PERF_SEL_SC2_PA4_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC2_PA4_DATA_FIFO_EOP_RD = 0x00000141, // PH_PERF_SEL_SC2_PA4_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC2_PA4_EOPG_WE = 0x00000142, // PH_PA4 PH_SC2_PA4_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC2_PA4_DEALLOC_4_0_RD = 0x00000143, // PH_PERF_SEL_SC2_PA4_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC2_PA5_DATA_FIFO_RD = 0x00000144, // PH_PERF_SEL_SC2_PA5_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC2_PA5_DATA_FIFO_WE = 0x00000145, // PH_PERF_SEL_SC2_PA5_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC2_PA5_FIFO_EMPTY = 0x00000146, // PH_PERF_SEL_SC2_PA5_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC2_PA5_FIFO_FULL = 0x00000147, // PH_PERF_SEL_SC2_PA5_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC2_PA5_NULL_WE = 0x00000148, // PH_PERF_SEL_SC2_PA5_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC2_PA5_EVENT_WE = 0x00000149, // PH_PERF_SEL_SC2_PA5_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC2_PA5_FPOV_WE = 0x0000014a, // PH_PERF_SEL_SC2_PA5_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC2_PA5_LPOV_WE = 0x0000014b, // PH_PERF_SEL_SC2_PA5_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC2_PA5_EOP_WE = 0x0000014c, // PH_PERF_SEL_SC2_PA5_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC2_PA5_DATA_FIFO_EOP_RD = 0x0000014d, // PH_PERF_SEL_SC2_PA5_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC2_PA5_EOPG_WE = 0x0000014e, // PH_PA5 PH_SC2_PA5_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC2_PA5_DEALLOC_4_0_RD = 0x0000014f, // PH_PERF_SEL_SC2_PA5_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC2_PA6_DATA_FIFO_RD = 0x00000150, // PH_PERF_SEL_SC2_PA6_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC2_PA6_DATA_FIFO_WE = 0x00000151, // PH_PERF_SEL_SC2_PA6_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC2_PA6_FIFO_EMPTY = 0x00000152, // PH_PERF_SEL_SC2_PA6_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC2_PA6_FIFO_FULL = 0x00000153, // PH_PERF_SEL_SC2_PA6_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC2_PA6_NULL_WE = 0x00000154, // PH_PERF_SEL_SC2_PA6_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC2_PA6_EVENT_WE = 0x00000155, // PH_PERF_SEL_SC2_PA6_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC2_PA6_FPOV_WE = 0x00000156, // PH_PERF_SEL_SC2_PA6_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC2_PA6_LPOV_WE = 0x00000157, // PH_PERF_SEL_SC2_PA6_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC2_PA6_EOP_WE = 0x00000158, // PH_PERF_SEL_SC2_PA6_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC2_PA6_DATA_FIFO_EOP_RD = 0x00000159, // PH_PERF_SEL_SC2_PA6_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC2_PA6_EOPG_WE = 0x0000015a, // PH_PA6 PH_SC2_PA6_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC2_PA6_DEALLOC_4_0_RD = 0x0000015b, // PH_PERF_SEL_SC2_PA6_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC2_PA7_DATA_FIFO_RD = 0x0000015c, // PH_PERF_SEL_SC2_PA7_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC2_PA7_DATA_FIFO_WE = 0x0000015d, // PH_PERF_SEL_SC2_PA7_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC2_PA7_FIFO_EMPTY = 0x0000015e, // PH_PERF_SEL_SC2_PA7_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC2_PA7_FIFO_FULL = 0x0000015f, // PH_PERF_SEL_SC2_PA7_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC2_PA7_NULL_WE = 0x00000160, // PH_PERF_SEL_SC2_PA7_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC2_PA7_EVENT_WE = 0x00000161, // PH_PERF_SEL_SC2_PA7_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC2_PA7_FPOV_WE = 0x00000162, // PH_PERF_SEL_SC2_PA7_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC2_PA7_LPOV_WE = 0x00000163, // PH_PERF_SEL_SC2_PA7_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC2_PA7_EOP_WE = 0x00000164, // PH_PERF_SEL_SC2_PA7_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC2_PA7_DATA_FIFO_EOP_RD = 0x00000165, // PH_PERF_SEL_SC2_PA7_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC2_PA7_EOPG_WE = 0x00000166, // PH_PA7 PH_SC2_PA7_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC2_PA7_DEALLOC_4_0_RD = 0x00000167, // PH_PERF_SEL_SC2_PA7_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC3_SRPS_WINDOW_VALID = 0x00000168, // PH_PERF_SEL_SC3_SRPS_WINDOW_VALID Counts PERFCOUNTER_START to PERFCOUNTER_STOP stop perfcounter enable window in PH Read Setup logic + PH_PERF_SEL_SC3_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES = 0x00000169, // PH_PERF_SEL_SC3_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES counts number of cycles of arb xfc's for all event or prims + PH_PERF_SEL_SC3_ARB_XFC_ONLY_PRIM_CYCLES = 0x0000016a, // PH_PERF_SEL_SC3_ARB_XFC_ONLY_PRIM_CYCLES counts number of cycles of arb xfc's for only prims (events excluded) + PH_PERF_SEL_SC3_ARB_XFC_ONLY_ONE_INC_PER_PRIM = 0x0000016b, // PH_PERF_SEL_SC3_ARB_XFC_ONLY_ONE_INC_PER_PRIM counts number of cycles of arb xfc's for one inc per prim only. Increments only for phase 0 of a multi-cycle primitive transfer + PH_PERF_SEL_SC3_ARB_STALLED_FROM_BELOW = 0x0000016c, // PH_PERF_SEL_SC3_ARB_STALLED_FROM_BELOW counts number of cycles of stalled post arbiter for valid data + PH_PERF_SEL_SC3_ARB_STARVED_FROM_ABOVE = 0x0000016d, // PH_PERF_SEL_SC3_ARB_STARVED_FROM_ABOVE counts number of cycles of PA starving SC in start-of-packet/eop range + PH_PERF_SEL_SC3_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY = 0x0000016e, // PH_PERF_SEL_SC3_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY counts from above (pa) with an unselected pa fifo not empty (use if more than one pa only) + PH_PERF_SEL_SC3_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL = 0x0000016f, // PH_PERF_SEL_SC3_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL counts starved by pa with a unselected pa fifo full (use if more than one pa only) This means that inside the draw packet the SC selected fifo has no valid data, and that one of the unselected fifo's has gone fifo's has gone full. + PH_PERF_SEL_SC3_ARB_BUSY = 0x00000170, // PH_PERF_SEL_SC3_ARB_BUSY counts number of cycles of PH_SC3 busy + PH_PERF_SEL_SC3_ARB_PA_BUSY_SOP = 0x00000171, // PH_PERF_SEL_SC3_ARB_PA_BUSY_SOP counts number of cycles in between start of packet/end of packet + PH_PERF_SEL_SC3_ARB_EOP_POP_SYNC_POP = 0x00000172, // PH_PERF_SEL_SC3_ARB_EOP_POP_SYNC_POP counts number of cycles of of pa sc arbiter eop reads at the eop sync point with all fifos synced + PH_PERF_SEL_SC3_ARB_EVENT_SYNC_POP = 0x00000173, // PH_PERF_SEL_SC3_ARB_EVENT_SYNC_POP counts number of cycles of pa sc event reads + PH_PERF_SEL_SC3_PS_ENG_MULTICYCLE_BUBBLE = 0x00000174, // PH_PERF_SEL_SC3_PS_ENG_MULTICYCLE_BUBBLE counts number of cycles of multicycles prims sent with a empty fifo slot behind the current phase. + PH_PERF_SEL_SC3_EOP_SYNC_WINDOW = 0x00000175, // PH_PERF_SEL_SC3_EOP_SYNC_WINDOW counts number of cycles of after end of packet is read from the selected pa sc fifo until end of packet broadcast synchronization is achieved across all pa sc fifos + PH_PERF_SEL_SC3_BUSY_PROCESSING_MULTICYCLE_PRIM = 0x00000176, // PH_PERF_SEL_SC3_BUSY_PROCESSING_MULTICYCLE_PRIM counts number of cycles of sc arbiter busy processing multicycle prims (clipped, perspective linear gradient, line stipple) + PH_PERF_SEL_SC3_BUSY_CNT_NOT_ZERO = 0x00000177, // PH_PERF_SEL_SC3_BUSY_CNT_NOT_ZERO counts number of cycles of ph-sc read setup busy counter non zero. + PH_PERF_SEL_SC3_SEND = 0x00000178, // PH_PERF_SEL_SC3_SEND counts interface sends to SC + PH_PERF_SEL_SC3_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x00000179, // PH_PERF_SEL_SC3_CREDIT_AT_ZERO_WITH_PENDING_SEND counts interface stalled for no SC credits with pending data available + PH_PERF_SEL_SC3_CREDIT_AT_MAX = 0x0000017a, // PH_PERF_SEL_SC3_CREDIT_AT_MAX counts full PH_SC interface credit pool available (INTERFACE IDLE) + PH_PERF_SEL_SC3_CREDIT_AT_MAX_NO_PENDING_SEND = 0x0000017b, // PH_PERF_SEL_SC3_CREDIT_AT_MAX_NO_PENDING_SEND counts full PH_SC interface credit pool available with no pending PH_SC data to send (FULL IDLE of PH_SC slice) + PH_PERF_SEL_SC3_GFX_PIPE_EVENT_PROVOKED_TRANSITION = 0x0000017c, // PH_PERF_SEL_SC3_GFX_PIPE_EVENT_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by an EVENT associated with a new gfx pipe id + PH_PERF_SEL_SC3_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION = 0x0000017d, // PH_PERF_SEL_SC3_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by a primitive associated with a new gfx pipe id + PH_PERF_SEL_SC3_GFX_PIPE0_TO_1_TRANSITION = 0x0000017e, // PH_PERF_SEL_SC3_GFX_PIPE0_TO_1_TRANSITION counts GFX PIPEID transitions from pipe0 to pipe1 + PH_PERF_SEL_SC3_GFX_PIPE1_TO_0_TRANSITION = 0x0000017f, // PH_PERF_SEL_SC3_GFX_PIPE1_TO_0_TRANSITION counts GFX PIPEID transitions from pipe1 to pipe0 + PH_PERF_SEL_SC3_PA0_DATA_FIFO_RD = 0x00000180, // PH_PERF_SEL_SC3_PA0_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC3_PA0_DATA_FIFO_WE = 0x00000181, // PH_PERF_SEL_SC3_PA0_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC3_PA0_FIFO_EMPTY = 0x00000182, // PH_PERF_SEL_SC3_PA0_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC3_PA0_FIFO_FULL = 0x00000183, // PH_PERF_SEL_SC3_PA0_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC3_PA0_NULL_WE = 0x00000184, // PH_PERF_SEL_SC3_PA0_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC3_PA0_EVENT_WE = 0x00000185, // PH_PERF_SEL_SC3_PA0_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC3_PA0_FPOV_WE = 0x00000186, // PH_PERF_SEL_SC3_PA0_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC3_PA0_LPOV_WE = 0x00000187, // PH_PERF_SEL_SC3_PA0_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC3_PA0_EOP_WE = 0x00000188, // PH_PERF_SEL_SC3_PA0_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC3_PA0_DATA_FIFO_EOP_RD = 0x00000189, // PH_PERF_SEL_SC3_PA0_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC3_PA0_EOPG_WE = 0x0000018a, // PH_PA0 PH_SC3_PA0_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC3_PA0_DEALLOC_4_0_RD = 0x0000018b, // PH_PERF_SEL_SC3_PA0_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC3_PA1_DATA_FIFO_RD = 0x0000018c, // PH_PERF_SEL_SC3_PA1_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC3_PA1_DATA_FIFO_WE = 0x0000018d, // PH_PERF_SEL_SC3_PA1_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC3_PA1_FIFO_EMPTY = 0x0000018e, // PH_PERF_SEL_SC3_PA1_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC3_PA1_FIFO_FULL = 0x0000018f, // PH_PERF_SEL_SC3_PA1_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC3_PA1_NULL_WE = 0x00000190, // PH_PERF_SEL_SC3_PA1_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC3_PA1_EVENT_WE = 0x00000191, // PH_PERF_SEL_SC3_PA1_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC3_PA1_FPOV_WE = 0x00000192, // PH_PERF_SEL_SC3_PA1_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC3_PA1_LPOV_WE = 0x00000193, // PH_PERF_SEL_SC3_PA1_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC3_PA1_EOP_WE = 0x00000194, // PH_PERF_SEL_SC3_PA1_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC3_PA1_DATA_FIFO_EOP_RD = 0x00000195, // PH_PERF_SEL_SC3_PA1_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC3_PA1_EOPG_WE = 0x00000196, // PH_PA1 PH_SC3_PA1_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC3_PA1_DEALLOC_4_0_RD = 0x00000197, // PH_PERF_SEL_SC3_PA1_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC3_PA2_DATA_FIFO_RD = 0x00000198, // PH_PERF_SEL_SC3_PA2_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC3_PA2_DATA_FIFO_WE = 0x00000199, // PH_PERF_SEL_SC3_PA2_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC3_PA2_FIFO_EMPTY = 0x0000019a, // PH_PERF_SEL_SC3_PA2_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC3_PA2_FIFO_FULL = 0x0000019b, // PH_PERF_SEL_SC3_PA2_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC3_PA2_NULL_WE = 0x0000019c, // PH_PERF_SEL_SC3_PA2_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC3_PA2_EVENT_WE = 0x0000019d, // PH_PERF_SEL_SC3_PA2_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC3_PA2_FPOV_WE = 0x0000019e, // PH_PERF_SEL_SC3_PA2_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC3_PA2_LPOV_WE = 0x0000019f, // PH_PERF_SEL_SC3_PA2_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC3_PA2_EOP_WE = 0x000001a0, // PH_PERF_SEL_SC3_PA2_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC3_PA2_DATA_FIFO_EOP_RD = 0x000001a1, // PH_PERF_SEL_SC3_PA2_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC3_PA2_EOPG_WE = 0x000001a2, // PH_PA2 PH_SC3_PA2_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC3_PA2_DEALLOC_4_0_RD = 0x000001a3, // PH_PERF_SEL_SC3_PA2_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC3_PA3_DATA_FIFO_RD = 0x000001a4, // PH_PERF_SEL_SC3_PA3_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC3_PA3_DATA_FIFO_WE = 0x000001a5, // PH_PERF_SEL_SC3_PA3_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC3_PA3_FIFO_EMPTY = 0x000001a6, // PH_PERF_SEL_SC3_PA3_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC3_PA3_FIFO_FULL = 0x000001a7, // PH_PERF_SEL_SC3_PA3_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC3_PA3_NULL_WE = 0x000001a8, // PH_PERF_SEL_SC3_PA3_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC3_PA3_EVENT_WE = 0x000001a9, // PH_PERF_SEL_SC3_PA3_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC3_PA3_FPOV_WE = 0x000001aa, // PH_PERF_SEL_SC3_PA3_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC3_PA3_LPOV_WE = 0x000001ab, // PH_PERF_SEL_SC3_PA3_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC3_PA3_EOP_WE = 0x000001ac, // PH_PERF_SEL_SC3_PA3_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC3_PA3_DATA_FIFO_EOP_RD = 0x000001ad, // PH_PERF_SEL_SC3_PA3_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC3_PA3_EOPG_WE = 0x000001ae, // PH_PA3 PH_SC3_PA3_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC3_PA3_DEALLOC_4_0_RD = 0x000001af, // PH_PERF_SEL_SC3_PA3_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC3_PA4_DATA_FIFO_RD = 0x000001b0, // PH_PERF_SEL_SC3_PA4_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC3_PA4_DATA_FIFO_WE = 0x000001b1, // PH_PERF_SEL_SC3_PA4_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC3_PA4_FIFO_EMPTY = 0x000001b2, // PH_PERF_SEL_SC3_PA4_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC3_PA4_FIFO_FULL = 0x000001b3, // PH_PERF_SEL_SC3_PA4_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC3_PA4_NULL_WE = 0x000001b4, // PH_PERF_SEL_SC3_PA4_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC3_PA4_EVENT_WE = 0x000001b5, // PH_PERF_SEL_SC3_PA4_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC3_PA4_FPOV_WE = 0x000001b6, // PH_PERF_SEL_SC3_PA4_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC3_PA4_LPOV_WE = 0x000001b7, // PH_PERF_SEL_SC3_PA4_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC3_PA4_EOP_WE = 0x000001b8, // PH_PERF_SEL_SC3_PA4_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC3_PA4_DATA_FIFO_EOP_RD = 0x000001b9, // PH_PERF_SEL_SC3_PA4_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC3_PA4_EOPG_WE = 0x000001ba, // PH_PA4 PH_SC3_PA4_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC3_PA4_DEALLOC_4_0_RD = 0x000001bb, // PH_PERF_SEL_SC3_PA4_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC3_PA5_DATA_FIFO_RD = 0x000001bc, // PH_PERF_SEL_SC3_PA5_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC3_PA5_DATA_FIFO_WE = 0x000001bd, // PH_PERF_SEL_SC3_PA5_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC3_PA5_FIFO_EMPTY = 0x000001be, // PH_PERF_SEL_SC3_PA5_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC3_PA5_FIFO_FULL = 0x000001bf, // PH_PERF_SEL_SC3_PA5_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC3_PA5_NULL_WE = 0x000001c0, // PH_PERF_SEL_SC3_PA5_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC3_PA5_EVENT_WE = 0x000001c1, // PH_PERF_SEL_SC3_PA5_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC3_PA5_FPOV_WE = 0x000001c2, // PH_PERF_SEL_SC3_PA5_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC3_PA5_LPOV_WE = 0x000001c3, // PH_PERF_SEL_SC3_PA5_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC3_PA5_EOP_WE = 0x000001c4, // PH_PERF_SEL_SC3_PA5_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC3_PA5_DATA_FIFO_EOP_RD = 0x000001c5, // PH_PERF_SEL_SC3_PA5_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC3_PA5_EOPG_WE = 0x000001c6, // PH_PA5 PH_SC3_PA5_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC3_PA5_DEALLOC_4_0_RD = 0x000001c7, // PH_PERF_SEL_SC3_PA5_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC3_PA6_DATA_FIFO_RD = 0x000001c8, // PH_PERF_SEL_SC3_PA6_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC3_PA6_DATA_FIFO_WE = 0x000001c9, // PH_PERF_SEL_SC3_PA6_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC3_PA6_FIFO_EMPTY = 0x000001ca, // PH_PERF_SEL_SC3_PA6_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC3_PA6_FIFO_FULL = 0x000001cb, // PH_PERF_SEL_SC3_PA6_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC3_PA6_NULL_WE = 0x000001cc, // PH_PERF_SEL_SC3_PA6_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC3_PA6_EVENT_WE = 0x000001cd, // PH_PERF_SEL_SC3_PA6_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC3_PA6_FPOV_WE = 0x000001ce, // PH_PERF_SEL_SC3_PA6_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC3_PA6_LPOV_WE = 0x000001cf, // PH_PERF_SEL_SC3_PA6_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC3_PA6_EOP_WE = 0x000001d0, // PH_PERF_SEL_SC3_PA6_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC3_PA6_DATA_FIFO_EOP_RD = 0x000001d1, // PH_PERF_SEL_SC3_PA6_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC3_PA6_EOPG_WE = 0x000001d2, // PH_PA6 PH_SC3_PA6_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC3_PA6_DEALLOC_4_0_RD = 0x000001d3, // PH_PERF_SEL_SC3_PA6_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC3_PA7_DATA_FIFO_RD = 0x000001d4, // PH_PERF_SEL_SC3_PA7_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC3_PA7_DATA_FIFO_WE = 0x000001d5, // PH_PERF_SEL_SC3_PA7_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC3_PA7_FIFO_EMPTY = 0x000001d6, // PH_PERF_SEL_SC3_PA7_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC3_PA7_FIFO_FULL = 0x000001d7, // PH_PERF_SEL_SC3_PA7_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC3_PA7_NULL_WE = 0x000001d8, // PH_PERF_SEL_SC3_PA7_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC3_PA7_EVENT_WE = 0x000001d9, // PH_PERF_SEL_SC3_PA7_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC3_PA7_FPOV_WE = 0x000001da, // PH_PERF_SEL_SC3_PA7_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC3_PA7_LPOV_WE = 0x000001db, // PH_PERF_SEL_SC3_PA7_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC3_PA7_EOP_WE = 0x000001dc, // PH_PERF_SEL_SC3_PA7_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC3_PA7_DATA_FIFO_EOP_RD = 0x000001dd, // PH_PERF_SEL_SC3_PA7_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC3_PA7_EOPG_WE = 0x000001de, // PH_PA7 PH_SC3_PA7_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC3_PA7_DEALLOC_4_0_RD = 0x000001df, // PH_PERF_SEL_SC3_PA7_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC4_SRPS_WINDOW_VALID = 0x000001e0, // PH_PERF_SEL_SC4_SRPS_WINDOW_VALID Counts PERFCOUNTER_START to PERFCOUNTER_STOP stop perfcounter enable window in PH Read Setup logic + PH_PERF_SEL_SC4_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES = 0x000001e1, // PH_PERF_SEL_SC4_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES counts number of cycles of arb xfc's for all event or prims + PH_PERF_SEL_SC4_ARB_XFC_ONLY_PRIM_CYCLES = 0x000001e2, // PH_PERF_SEL_SC4_ARB_XFC_ONLY_PRIM_CYCLES counts number of cycles of arb xfc's for only prims (events excluded) + PH_PERF_SEL_SC4_ARB_XFC_ONLY_ONE_INC_PER_PRIM = 0x000001e3, // PH_PERF_SEL_SC4_ARB_XFC_ONLY_ONE_INC_PER_PRIM counts number of cycles of arb xfc's for one inc per prim only. Increments only for phase 0 of a multi-cycle primitive transfer + PH_PERF_SEL_SC4_ARB_STALLED_FROM_BELOW = 0x000001e4, // PH_PERF_SEL_SC4_ARB_STALLED_FROM_BELOW counts number of cycles of stalled post arbiter for valid data + PH_PERF_SEL_SC4_ARB_STARVED_FROM_ABOVE = 0x000001e5, // PH_PERF_SEL_SC4_ARB_STARVED_FROM_ABOVE counts number of cycles of PA starving SC in start-of-packet/eop range + PH_PERF_SEL_SC4_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY = 0x000001e6, // PH_PERF_SEL_SC4_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY counts from above (pa) with an unselected pa fifo not empty (use if more than one pa only) + PH_PERF_SEL_SC4_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL = 0x000001e7, // PH_PERF_SEL_SC4_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL counts starved by pa with a unselected pa fifo full (use if more than one pa only) This means that inside the draw packet the SC selected fifo has no valid data, and that one of the unselected fifo's has gone fifo's has gone full. + PH_PERF_SEL_SC4_ARB_BUSY = 0x000001e8, // PH_PERF_SEL_SC4_ARB_BUSY counts number of cycles of PH_SC4 busy + PH_PERF_SEL_SC4_ARB_PA_BUSY_SOP = 0x000001e9, // PH_PERF_SEL_SC4_ARB_PA_BUSY_SOP counts number of cycles in between start of packet/end of packet + PH_PERF_SEL_SC4_ARB_EOP_POP_SYNC_POP = 0x000001ea, // PH_PERF_SEL_SC4_ARB_EOP_POP_SYNC_POP counts number of cycles of of pa sc arbiter eop reads at the eop sync point with all fifos synced + PH_PERF_SEL_SC4_ARB_EVENT_SYNC_POP = 0x000001eb, // PH_PERF_SEL_SC4_ARB_EVENT_SYNC_POP counts number of cycles of pa sc event reads + PH_PERF_SEL_SC4_PS_ENG_MULTICYCLE_BUBBLE = 0x000001ec, // PH_PERF_SEL_SC4_PS_ENG_MULTICYCLE_BUBBLE counts number of cycles of multicycles prims sent with a empty fifo slot behind the current phase. + PH_PERF_SEL_SC4_EOP_SYNC_WINDOW = 0x000001ed, // PH_PERF_SEL_SC4_EOP_SYNC_WINDOW counts number of cycles of after end of packet is read from the selected pa sc fifo until end of packet broadcast synchronization is achieved across all pa sc fifos + PH_PERF_SEL_SC4_BUSY_PROCESSING_MULTICYCLE_PRIM = 0x000001ee, // PH_PERF_SEL_SC4_BUSY_PROCESSING_MULTICYCLE_PRIM counts number of cycles of sc arbiter busy processing multicycle prims (clipped, perspective linear gradient, line stipple) + PH_PERF_SEL_SC4_BUSY_CNT_NOT_ZERO = 0x000001ef, // PH_PERF_SEL_SC4_BUSY_CNT_NOT_ZERO counts number of cycles of ph-sc read setup busy counter non zero. + PH_PERF_SEL_SC4_SEND = 0x000001f0, // PH_PERF_SEL_SC4_SEND counts interface sends to SC + PH_PERF_SEL_SC4_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x000001f1, // PH_PERF_SEL_SC4_CREDIT_AT_ZERO_WITH_PENDING_SEND counts interface stalled for no SC credits with pending data available + PH_PERF_SEL_SC4_CREDIT_AT_MAX = 0x000001f2, // PH_PERF_SEL_SC4_CREDIT_AT_MAX counts full PH_SC interface credit pool available (INTERFACE IDLE) + PH_PERF_SEL_SC4_CREDIT_AT_MAX_NO_PENDING_SEND = 0x000001f3, // PH_PERF_SEL_SC4_CREDIT_AT_MAX_NO_PENDING_SEND counts full PH_SC interface credit pool available with no pending PH_SC data to send (FULL IDLE of PH_SC slice) + PH_PERF_SEL_SC4_GFX_PIPE_EVENT_PROVOKED_TRANSITION = 0x000001f4, // PH_PERF_SEL_SC4_GFX_PIPE_EVENT_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by an EVENT associated with a new gfx pipe id + PH_PERF_SEL_SC4_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION = 0x000001f5, // PH_PERF_SEL_SC4_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by a primitive associated with a new gfx pipe id + PH_PERF_SEL_SC4_GFX_PIPE0_TO_1_TRANSITION = 0x000001f6, // PH_PERF_SEL_SC4_GFX_PIPE0_TO_1_TRANSITION counts GFX PIPEID transitions from pipe0 to pipe1 + PH_PERF_SEL_SC4_GFX_PIPE1_TO_0_TRANSITION = 0x000001f7, // PH_PERF_SEL_SC4_GFX_PIPE1_TO_0_TRANSITION counts GFX PIPEID transitions from pipe1 to pipe0 + PH_PERF_SEL_SC4_PA0_DATA_FIFO_RD = 0x000001f8, // PH_PERF_SEL_SC4_PA0_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC4_PA0_DATA_FIFO_WE = 0x000001f9, // PH_PERF_SEL_SC4_PA0_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC4_PA0_FIFO_EMPTY = 0x000001fa, // PH_PERF_SEL_SC4_PA0_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC4_PA0_FIFO_FULL = 0x000001fb, // PH_PERF_SEL_SC4_PA0_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC4_PA0_NULL_WE = 0x000001fc, // PH_PERF_SEL_SC4_PA0_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC4_PA0_EVENT_WE = 0x000001fd, // PH_PERF_SEL_SC4_PA0_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC4_PA0_FPOV_WE = 0x000001fe, // PH_PERF_SEL_SC4_PA0_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC4_PA0_LPOV_WE = 0x000001ff, // PH_PERF_SEL_SC4_PA0_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC4_PA0_EOP_WE = 0x00000200, // PH_PERF_SEL_SC4_PA0_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC4_PA0_DATA_FIFO_EOP_RD = 0x00000201, // PH_PERF_SEL_SC4_PA0_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC4_PA0_EOPG_WE = 0x00000202, // PH_PA0 PH_SC4_PA0_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC4_PA0_DEALLOC_4_0_RD = 0x00000203, // PH_PERF_SEL_SC4_PA0_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC4_PA1_DATA_FIFO_RD = 0x00000204, // PH_PERF_SEL_SC4_PA1_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC4_PA1_DATA_FIFO_WE = 0x00000205, // PH_PERF_SEL_SC4_PA1_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC4_PA1_FIFO_EMPTY = 0x00000206, // PH_PERF_SEL_SC4_PA1_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC4_PA1_FIFO_FULL = 0x00000207, // PH_PERF_SEL_SC4_PA1_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC4_PA1_NULL_WE = 0x00000208, // PH_PERF_SEL_SC4_PA1_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC4_PA1_EVENT_WE = 0x00000209, // PH_PERF_SEL_SC4_PA1_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC4_PA1_FPOV_WE = 0x0000020a, // PH_PERF_SEL_SC4_PA1_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC4_PA1_LPOV_WE = 0x0000020b, // PH_PERF_SEL_SC4_PA1_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC4_PA1_EOP_WE = 0x0000020c, // PH_PERF_SEL_SC4_PA1_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC4_PA1_DATA_FIFO_EOP_RD = 0x0000020d, // PH_PERF_SEL_SC4_PA1_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC4_PA1_EOPG_WE = 0x0000020e, // PH_PA1 PH_SC4_PA1_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC4_PA1_DEALLOC_4_0_RD = 0x0000020f, // PH_PERF_SEL_SC4_PA1_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC4_PA2_DATA_FIFO_RD = 0x00000210, // PH_PERF_SEL_SC4_PA2_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC4_PA2_DATA_FIFO_WE = 0x00000211, // PH_PERF_SEL_SC4_PA2_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC4_PA2_FIFO_EMPTY = 0x00000212, // PH_PERF_SEL_SC4_PA2_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC4_PA2_FIFO_FULL = 0x00000213, // PH_PERF_SEL_SC4_PA2_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC4_PA2_NULL_WE = 0x00000214, // PH_PERF_SEL_SC4_PA2_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC4_PA2_EVENT_WE = 0x00000215, // PH_PERF_SEL_SC4_PA2_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC4_PA2_FPOV_WE = 0x00000216, // PH_PERF_SEL_SC4_PA2_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC4_PA2_LPOV_WE = 0x00000217, // PH_PERF_SEL_SC4_PA2_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC4_PA2_EOP_WE = 0x00000218, // PH_PERF_SEL_SC4_PA2_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC4_PA2_DATA_FIFO_EOP_RD = 0x00000219, // PH_PERF_SEL_SC4_PA2_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC4_PA2_EOPG_WE = 0x0000021a, // PH_PA2 PH_SC4_PA2_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC4_PA2_DEALLOC_4_0_RD = 0x0000021b, // PH_PERF_SEL_SC4_PA2_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC4_PA3_DATA_FIFO_RD = 0x0000021c, // PH_PERF_SEL_SC4_PA3_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC4_PA3_DATA_FIFO_WE = 0x0000021d, // PH_PERF_SEL_SC4_PA3_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC4_PA3_FIFO_EMPTY = 0x0000021e, // PH_PERF_SEL_SC4_PA3_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC4_PA3_FIFO_FULL = 0x0000021f, // PH_PERF_SEL_SC4_PA3_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC4_PA3_NULL_WE = 0x00000220, // PH_PERF_SEL_SC4_PA3_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC4_PA3_EVENT_WE = 0x00000221, // PH_PERF_SEL_SC4_PA3_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC4_PA3_FPOV_WE = 0x00000222, // PH_PERF_SEL_SC4_PA3_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC4_PA3_LPOV_WE = 0x00000223, // PH_PERF_SEL_SC4_PA3_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC4_PA3_EOP_WE = 0x00000224, // PH_PERF_SEL_SC4_PA3_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC4_PA3_DATA_FIFO_EOP_RD = 0x00000225, // PH_PERF_SEL_SC4_PA3_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC4_PA3_EOPG_WE = 0x00000226, // PH_PA3 PH_SC4_PA3_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC4_PA3_DEALLOC_4_0_RD = 0x00000227, // PH_PERF_SEL_SC4_PA3_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC4_PA4_DATA_FIFO_RD = 0x00000228, // PH_PERF_SEL_SC4_PA4_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC4_PA4_DATA_FIFO_WE = 0x00000229, // PH_PERF_SEL_SC4_PA4_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC4_PA4_FIFO_EMPTY = 0x0000022a, // PH_PERF_SEL_SC4_PA4_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC4_PA4_FIFO_FULL = 0x0000022b, // PH_PERF_SEL_SC4_PA4_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC4_PA4_NULL_WE = 0x0000022c, // PH_PERF_SEL_SC4_PA4_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC4_PA4_EVENT_WE = 0x0000022d, // PH_PERF_SEL_SC4_PA4_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC4_PA4_FPOV_WE = 0x0000022e, // PH_PERF_SEL_SC4_PA4_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC4_PA4_LPOV_WE = 0x0000022f, // PH_PERF_SEL_SC4_PA4_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC4_PA4_EOP_WE = 0x00000230, // PH_PERF_SEL_SC4_PA4_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC4_PA4_DATA_FIFO_EOP_RD = 0x00000231, // PH_PERF_SEL_SC4_PA4_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC4_PA4_EOPG_WE = 0x00000232, // PH_PA4 PH_SC4_PA4_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC4_PA4_DEALLOC_4_0_RD = 0x00000233, // PH_PERF_SEL_SC4_PA4_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC4_PA5_DATA_FIFO_RD = 0x00000234, // PH_PERF_SEL_SC4_PA5_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC4_PA5_DATA_FIFO_WE = 0x00000235, // PH_PERF_SEL_SC4_PA5_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC4_PA5_FIFO_EMPTY = 0x00000236, // PH_PERF_SEL_SC4_PA5_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC4_PA5_FIFO_FULL = 0x00000237, // PH_PERF_SEL_SC4_PA5_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC4_PA5_NULL_WE = 0x00000238, // PH_PERF_SEL_SC4_PA5_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC4_PA5_EVENT_WE = 0x00000239, // PH_PERF_SEL_SC4_PA5_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC4_PA5_FPOV_WE = 0x0000023a, // PH_PERF_SEL_SC4_PA5_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC4_PA5_LPOV_WE = 0x0000023b, // PH_PERF_SEL_SC4_PA5_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC4_PA5_EOP_WE = 0x0000023c, // PH_PERF_SEL_SC4_PA5_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC4_PA5_DATA_FIFO_EOP_RD = 0x0000023d, // PH_PERF_SEL_SC4_PA5_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC4_PA5_EOPG_WE = 0x0000023e, // PH_PA5 PH_SC4_PA5_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC4_PA5_DEALLOC_4_0_RD = 0x0000023f, // PH_PERF_SEL_SC4_PA5_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC4_PA6_DATA_FIFO_RD = 0x00000240, // PH_PERF_SEL_SC4_PA6_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC4_PA6_DATA_FIFO_WE = 0x00000241, // PH_PERF_SEL_SC4_PA6_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC4_PA6_FIFO_EMPTY = 0x00000242, // PH_PERF_SEL_SC4_PA6_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC4_PA6_FIFO_FULL = 0x00000243, // PH_PERF_SEL_SC4_PA6_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC4_PA6_NULL_WE = 0x00000244, // PH_PERF_SEL_SC4_PA6_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC4_PA6_EVENT_WE = 0x00000245, // PH_PERF_SEL_SC4_PA6_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC4_PA6_FPOV_WE = 0x00000246, // PH_PERF_SEL_SC4_PA6_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC4_PA6_LPOV_WE = 0x00000247, // PH_PERF_SEL_SC4_PA6_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC4_PA6_EOP_WE = 0x00000248, // PH_PERF_SEL_SC4_PA6_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC4_PA6_DATA_FIFO_EOP_RD = 0x00000249, // PH_PERF_SEL_SC4_PA6_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC4_PA6_EOPG_WE = 0x0000024a, // PH_PA6 PH_SC4_PA6_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC4_PA6_DEALLOC_4_0_RD = 0x0000024b, // PH_PERF_SEL_SC4_PA6_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC4_PA7_DATA_FIFO_RD = 0x0000024c, // PH_PERF_SEL_SC4_PA7_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC4_PA7_DATA_FIFO_WE = 0x0000024d, // PH_PERF_SEL_SC4_PA7_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC4_PA7_FIFO_EMPTY = 0x0000024e, // PH_PERF_SEL_SC4_PA7_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC4_PA7_FIFO_FULL = 0x0000024f, // PH_PERF_SEL_SC4_PA7_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC4_PA7_NULL_WE = 0x00000250, // PH_PERF_SEL_SC4_PA7_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC4_PA7_EVENT_WE = 0x00000251, // PH_PERF_SEL_SC4_PA7_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC4_PA7_FPOV_WE = 0x00000252, // PH_PERF_SEL_SC4_PA7_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC4_PA7_LPOV_WE = 0x00000253, // PH_PERF_SEL_SC4_PA7_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC4_PA7_EOP_WE = 0x00000254, // PH_PERF_SEL_SC4_PA7_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC4_PA7_DATA_FIFO_EOP_RD = 0x00000255, // PH_PERF_SEL_SC4_PA7_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC4_PA7_EOPG_WE = 0x00000256, // PH_PA7 PH_SC4_PA7_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC4_PA7_DEALLOC_4_0_RD = 0x00000257, // PH_PERF_SEL_SC4_PA7_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC5_SRPS_WINDOW_VALID = 0x00000258, // PH_PERF_SEL_SC5_SRPS_WINDOW_VALID Counts PERFCOUNTER_START to PERFCOUNTER_STOP stop perfcounter enable window in PH Read Setup logic + PH_PERF_SEL_SC5_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES = 0x00000259, // PH_PERF_SEL_SC5_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES counts number of cycles of arb xfc's for all event or prims + PH_PERF_SEL_SC5_ARB_XFC_ONLY_PRIM_CYCLES = 0x0000025a, // PH_PERF_SEL_SC5_ARB_XFC_ONLY_PRIM_CYCLES counts number of cycles of arb xfc's for only prims (events excluded) + PH_PERF_SEL_SC5_ARB_XFC_ONLY_ONE_INC_PER_PRIM = 0x0000025b, // PH_PERF_SEL_SC5_ARB_XFC_ONLY_ONE_INC_PER_PRIM counts number of cycles of arb xfc's for one inc per prim only. Increments only for phase 0 of a multi-cycle primitive transfer + PH_PERF_SEL_SC5_ARB_STALLED_FROM_BELOW = 0x0000025c, // PH_PERF_SEL_SC5_ARB_STALLED_FROM_BELOW counts number of cycles of stalled post arbiter for valid data + PH_PERF_SEL_SC5_ARB_STARVED_FROM_ABOVE = 0x0000025d, // PH_PERF_SEL_SC5_ARB_STARVED_FROM_ABOVE counts number of cycles of PA starving SC in start-of-packet/eop range + PH_PERF_SEL_SC5_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY = 0x0000025e, // PH_PERF_SEL_SC5_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY counts from above (pa) with an unselected pa fifo not empty (use if more than one pa only) + PH_PERF_SEL_SC5_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL = 0x0000025f, // PH_PERF_SEL_SC5_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL counts starved by pa with a unselected pa fifo full (use if more than one pa only) This means that inside the draw packet the SC selected fifo has no valid data, and that one of the unselected fifo's has gone fifo's has gone full. + PH_PERF_SEL_SC5_ARB_BUSY = 0x00000260, // PH_PERF_SEL_SC5_ARB_BUSY counts number of cycles of PH_SC5 busy + PH_PERF_SEL_SC5_ARB_PA_BUSY_SOP = 0x00000261, // PH_PERF_SEL_SC5_ARB_PA_BUSY_SOP counts number of cycles in between start of packet/end of packet + PH_PERF_SEL_SC5_ARB_EOP_POP_SYNC_POP = 0x00000262, // PH_PERF_SEL_SC5_ARB_EOP_POP_SYNC_POP counts number of cycles of of pa sc arbiter eop reads at the eop sync point with all fifos synced + PH_PERF_SEL_SC5_ARB_EVENT_SYNC_POP = 0x00000263, // PH_PERF_SEL_SC5_ARB_EVENT_SYNC_POP counts number of cycles of pa sc event reads + PH_PERF_SEL_SC5_PS_ENG_MULTICYCLE_BUBBLE = 0x00000264, // PH_PERF_SEL_SC5_PS_ENG_MULTICYCLE_BUBBLE counts number of cycles of multicycles prims sent with a empty fifo slot behind the current phase. + PH_PERF_SEL_SC5_EOP_SYNC_WINDOW = 0x00000265, // PH_PERF_SEL_SC5_EOP_SYNC_WINDOW counts number of cycles of after end of packet is read from the selected pa sc fifo until end of packet broadcast synchronization is achieved across all pa sc fifos + PH_PERF_SEL_SC5_BUSY_PROCESSING_MULTICYCLE_PRIM = 0x00000266, // PH_PERF_SEL_SC5_BUSY_PROCESSING_MULTICYCLE_PRIM counts number of cycles of sc arbiter busy processing multicycle prims (clipped, perspective linear gradient, line stipple) + PH_PERF_SEL_SC5_BUSY_CNT_NOT_ZERO = 0x00000267, // PH_PERF_SEL_SC5_BUSY_CNT_NOT_ZERO counts number of cycles of ph-sc read setup busy counter non zero. + PH_PERF_SEL_SC5_SEND = 0x00000268, // PH_PERF_SEL_SC5_SEND counts interface sends to SC + PH_PERF_SEL_SC5_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x00000269, // PH_PERF_SEL_SC5_CREDIT_AT_ZERO_WITH_PENDING_SEND counts interface stalled for no SC credits with pending data available + PH_PERF_SEL_SC5_CREDIT_AT_MAX = 0x0000026a, // PH_PERF_SEL_SC5_CREDIT_AT_MAX counts full PH_SC interface credit pool available (INTERFACE IDLE) + PH_PERF_SEL_SC5_CREDIT_AT_MAX_NO_PENDING_SEND = 0x0000026b, // PH_PERF_SEL_SC5_CREDIT_AT_MAX_NO_PENDING_SEND counts full PH_SC interface credit pool available with no pending PH_SC data to send (FULL IDLE of PH_SC slice) + PH_PERF_SEL_SC5_GFX_PIPE_EVENT_PROVOKED_TRANSITION = 0x0000026c, // PH_PERF_SEL_SC5_GFX_PIPE_EVENT_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by an EVENT associated with a new gfx pipe id + PH_PERF_SEL_SC5_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION = 0x0000026d, // PH_PERF_SEL_SC5_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by a primitive associated with a new gfx pipe id + PH_PERF_SEL_SC5_GFX_PIPE0_TO_1_TRANSITION = 0x0000026e, // PH_PERF_SEL_SC5_GFX_PIPE0_TO_1_TRANSITION counts GFX PIPEID transitions from pipe0 to pipe1 + PH_PERF_SEL_SC5_GFX_PIPE1_TO_0_TRANSITION = 0x0000026f, // PH_PERF_SEL_SC5_GFX_PIPE1_TO_0_TRANSITION counts GFX PIPEID transitions from pipe1 to pipe0 + PH_PERF_SEL_SC5_PA0_DATA_FIFO_RD = 0x00000270, // PH_PERF_SEL_SC5_PA0_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC5_PA0_DATA_FIFO_WE = 0x00000271, // PH_PERF_SEL_SC5_PA0_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC5_PA0_FIFO_EMPTY = 0x00000272, // PH_PERF_SEL_SC5_PA0_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC5_PA0_FIFO_FULL = 0x00000273, // PH_PERF_SEL_SC5_PA0_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC5_PA0_NULL_WE = 0x00000274, // PH_PERF_SEL_SC5_PA0_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC5_PA0_EVENT_WE = 0x00000275, // PH_PERF_SEL_SC5_PA0_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC5_PA0_FPOV_WE = 0x00000276, // PH_PERF_SEL_SC5_PA0_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC5_PA0_LPOV_WE = 0x00000277, // PH_PERF_SEL_SC5_PA0_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC5_PA0_EOP_WE = 0x00000278, // PH_PERF_SEL_SC5_PA0_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC5_PA0_DATA_FIFO_EOP_RD = 0x00000279, // PH_PERF_SEL_SC5_PA0_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC5_PA0_EOPG_WE = 0x0000027a, // PH_PA0 PH_SC5_PA0_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC5_PA0_DEALLOC_4_0_RD = 0x0000027b, // PH_PERF_SEL_SC5_PA0_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC5_PA1_DATA_FIFO_RD = 0x0000027c, // PH_PERF_SEL_SC5_PA1_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC5_PA1_DATA_FIFO_WE = 0x0000027d, // PH_PERF_SEL_SC5_PA1_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC5_PA1_FIFO_EMPTY = 0x0000027e, // PH_PERF_SEL_SC5_PA1_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC5_PA1_FIFO_FULL = 0x0000027f, // PH_PERF_SEL_SC5_PA1_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC5_PA1_NULL_WE = 0x00000280, // PH_PERF_SEL_SC5_PA1_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC5_PA1_EVENT_WE = 0x00000281, // PH_PERF_SEL_SC5_PA1_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC5_PA1_FPOV_WE = 0x00000282, // PH_PERF_SEL_SC5_PA1_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC5_PA1_LPOV_WE = 0x00000283, // PH_PERF_SEL_SC5_PA1_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC5_PA1_EOP_WE = 0x00000284, // PH_PERF_SEL_SC5_PA1_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC5_PA1_DATA_FIFO_EOP_RD = 0x00000285, // PH_PERF_SEL_SC5_PA1_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC5_PA1_EOPG_WE = 0x00000286, // PH_PA1 PH_SC5_PA1_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC5_PA1_DEALLOC_4_0_RD = 0x00000287, // PH_PERF_SEL_SC5_PA1_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC5_PA2_DATA_FIFO_RD = 0x00000288, // PH_PERF_SEL_SC5_PA2_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC5_PA2_DATA_FIFO_WE = 0x00000289, // PH_PERF_SEL_SC5_PA2_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC5_PA2_FIFO_EMPTY = 0x0000028a, // PH_PERF_SEL_SC5_PA2_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC5_PA2_FIFO_FULL = 0x0000028b, // PH_PERF_SEL_SC5_PA2_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC5_PA2_NULL_WE = 0x0000028c, // PH_PERF_SEL_SC5_PA2_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC5_PA2_EVENT_WE = 0x0000028d, // PH_PERF_SEL_SC5_PA2_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC5_PA2_FPOV_WE = 0x0000028e, // PH_PERF_SEL_SC5_PA2_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC5_PA2_LPOV_WE = 0x0000028f, // PH_PERF_SEL_SC5_PA2_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC5_PA2_EOP_WE = 0x00000290, // PH_PERF_SEL_SC5_PA2_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC5_PA2_DATA_FIFO_EOP_RD = 0x00000291, // PH_PERF_SEL_SC5_PA2_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC5_PA2_EOPG_WE = 0x00000292, // PH_PA2 PH_SC5_PA2_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC5_PA2_DEALLOC_4_0_RD = 0x00000293, // PH_PERF_SEL_SC5_PA2_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC5_PA3_DATA_FIFO_RD = 0x00000294, // PH_PERF_SEL_SC5_PA3_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC5_PA3_DATA_FIFO_WE = 0x00000295, // PH_PERF_SEL_SC5_PA3_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC5_PA3_FIFO_EMPTY = 0x00000296, // PH_PERF_SEL_SC5_PA3_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC5_PA3_FIFO_FULL = 0x00000297, // PH_PERF_SEL_SC5_PA3_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC5_PA3_NULL_WE = 0x00000298, // PH_PERF_SEL_SC5_PA3_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC5_PA3_EVENT_WE = 0x00000299, // PH_PERF_SEL_SC5_PA3_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC5_PA3_FPOV_WE = 0x0000029a, // PH_PERF_SEL_SC5_PA3_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC5_PA3_LPOV_WE = 0x0000029b, // PH_PERF_SEL_SC5_PA3_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC5_PA3_EOP_WE = 0x0000029c, // PH_PERF_SEL_SC5_PA3_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC5_PA3_DATA_FIFO_EOP_RD = 0x0000029d, // PH_PERF_SEL_SC5_PA3_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC5_PA3_EOPG_WE = 0x0000029e, // PH_PA3 PH_SC5_PA3_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC5_PA3_DEALLOC_4_0_RD = 0x0000029f, // PH_PERF_SEL_SC5_PA3_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC5_PA4_DATA_FIFO_RD = 0x000002a0, // PH_PERF_SEL_SC5_PA4_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC5_PA4_DATA_FIFO_WE = 0x000002a1, // PH_PERF_SEL_SC5_PA4_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC5_PA4_FIFO_EMPTY = 0x000002a2, // PH_PERF_SEL_SC5_PA4_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC5_PA4_FIFO_FULL = 0x000002a3, // PH_PERF_SEL_SC5_PA4_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC5_PA4_NULL_WE = 0x000002a4, // PH_PERF_SEL_SC5_PA4_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC5_PA4_EVENT_WE = 0x000002a5, // PH_PERF_SEL_SC5_PA4_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC5_PA4_FPOV_WE = 0x000002a6, // PH_PERF_SEL_SC5_PA4_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC5_PA4_LPOV_WE = 0x000002a7, // PH_PERF_SEL_SC5_PA4_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC5_PA4_EOP_WE = 0x000002a8, // PH_PERF_SEL_SC5_PA4_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC5_PA4_DATA_FIFO_EOP_RD = 0x000002a9, // PH_PERF_SEL_SC5_PA4_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC5_PA4_EOPG_WE = 0x000002aa, // PH_PA4 PH_SC5_PA4_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC5_PA4_DEALLOC_4_0_RD = 0x000002ab, // PH_PERF_SEL_SC5_PA4_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC5_PA5_DATA_FIFO_RD = 0x000002ac, // PH_PERF_SEL_SC5_PA5_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC5_PA5_DATA_FIFO_WE = 0x000002ad, // PH_PERF_SEL_SC5_PA5_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC5_PA5_FIFO_EMPTY = 0x000002ae, // PH_PERF_SEL_SC5_PA5_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC5_PA5_FIFO_FULL = 0x000002af, // PH_PERF_SEL_SC5_PA5_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC5_PA5_NULL_WE = 0x000002b0, // PH_PERF_SEL_SC5_PA5_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC5_PA5_EVENT_WE = 0x000002b1, // PH_PERF_SEL_SC5_PA5_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC5_PA5_FPOV_WE = 0x000002b2, // PH_PERF_SEL_SC5_PA5_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC5_PA5_LPOV_WE = 0x000002b3, // PH_PERF_SEL_SC5_PA5_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC5_PA5_EOP_WE = 0x000002b4, // PH_PERF_SEL_SC5_PA5_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC5_PA5_DATA_FIFO_EOP_RD = 0x000002b5, // PH_PERF_SEL_SC5_PA5_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC5_PA5_EOPG_WE = 0x000002b6, // PH_PA5 PH_SC5_PA5_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC5_PA5_DEALLOC_4_0_RD = 0x000002b7, // PH_PERF_SEL_SC5_PA5_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC5_PA6_DATA_FIFO_RD = 0x000002b8, // PH_PERF_SEL_SC5_PA6_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC5_PA6_DATA_FIFO_WE = 0x000002b9, // PH_PERF_SEL_SC5_PA6_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC5_PA6_FIFO_EMPTY = 0x000002ba, // PH_PERF_SEL_SC5_PA6_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC5_PA6_FIFO_FULL = 0x000002bb, // PH_PERF_SEL_SC5_PA6_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC5_PA6_NULL_WE = 0x000002bc, // PH_PERF_SEL_SC5_PA6_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC5_PA6_EVENT_WE = 0x000002bd, // PH_PERF_SEL_SC5_PA6_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC5_PA6_FPOV_WE = 0x000002be, // PH_PERF_SEL_SC5_PA6_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC5_PA6_LPOV_WE = 0x000002bf, // PH_PERF_SEL_SC5_PA6_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC5_PA6_EOP_WE = 0x000002c0, // PH_PERF_SEL_SC5_PA6_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC5_PA6_DATA_FIFO_EOP_RD = 0x000002c1, // PH_PERF_SEL_SC5_PA6_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC5_PA6_EOPG_WE = 0x000002c2, // PH_PA6 PH_SC5_PA6_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC5_PA6_DEALLOC_4_0_RD = 0x000002c3, // PH_PERF_SEL_SC5_PA6_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC5_PA7_DATA_FIFO_RD = 0x000002c4, // PH_PERF_SEL_SC5_PA7_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC5_PA7_DATA_FIFO_WE = 0x000002c5, // PH_PERF_SEL_SC5_PA7_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC5_PA7_FIFO_EMPTY = 0x000002c6, // PH_PERF_SEL_SC5_PA7_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC5_PA7_FIFO_FULL = 0x000002c7, // PH_PERF_SEL_SC5_PA7_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC5_PA7_NULL_WE = 0x000002c8, // PH_PERF_SEL_SC5_PA7_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC5_PA7_EVENT_WE = 0x000002c9, // PH_PERF_SEL_SC5_PA7_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC5_PA7_FPOV_WE = 0x000002ca, // PH_PERF_SEL_SC5_PA7_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC5_PA7_LPOV_WE = 0x000002cb, // PH_PERF_SEL_SC5_PA7_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC5_PA7_EOP_WE = 0x000002cc, // PH_PERF_SEL_SC5_PA7_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC5_PA7_DATA_FIFO_EOP_RD = 0x000002cd, // PH_PERF_SEL_SC5_PA7_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC5_PA7_EOPG_WE = 0x000002ce, // PH_PA7 PH_SC5_PA7_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC5_PA7_DEALLOC_4_0_RD = 0x000002cf, // PH_PERF_SEL_SC5_PA7_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC6_SRPS_WINDOW_VALID = 0x000002d0, // PH_PERF_SEL_SC6_SRPS_WINDOW_VALID Counts PERFCOUNTER_START to PERFCOUNTER_STOP stop perfcounter enable window in PH Read Setup logic + PH_PERF_SEL_SC6_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES = 0x000002d1, // PH_PERF_SEL_SC6_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES counts number of cycles of arb xfc's for all event or prims + PH_PERF_SEL_SC6_ARB_XFC_ONLY_PRIM_CYCLES = 0x000002d2, // PH_PERF_SEL_SC6_ARB_XFC_ONLY_PRIM_CYCLES counts number of cycles of arb xfc's for only prims (events excluded) + PH_PERF_SEL_SC6_ARB_XFC_ONLY_ONE_INC_PER_PRIM = 0x000002d3, // PH_PERF_SEL_SC6_ARB_XFC_ONLY_ONE_INC_PER_PRIM counts number of cycles of arb xfc's for one inc per prim only. Increments only for phase 0 of a multi-cycle primitive transfer + PH_PERF_SEL_SC6_ARB_STALLED_FROM_BELOW = 0x000002d4, // PH_PERF_SEL_SC6_ARB_STALLED_FROM_BELOW counts number of cycles of stalled post arbiter for valid data + PH_PERF_SEL_SC6_ARB_STARVED_FROM_ABOVE = 0x000002d5, // PH_PERF_SEL_SC6_ARB_STARVED_FROM_ABOVE counts number of cycles of PA starving SC in start-of-packet/eop range + PH_PERF_SEL_SC6_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY = 0x000002d6, // PH_PERF_SEL_SC6_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY counts from above (pa) with an unselected pa fifo not empty (use if more than one pa only) + PH_PERF_SEL_SC6_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL = 0x000002d7, // PH_PERF_SEL_SC6_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL counts starved by pa with a unselected pa fifo full (use if more than one pa only) This means that inside the draw packet the SC selected fifo has no valid data, and that one of the unselected fifo's has gone fifo's has gone full. + PH_PERF_SEL_SC6_ARB_BUSY = 0x000002d8, // PH_PERF_SEL_SC6_ARB_BUSY counts number of cycles of PH_SC6 busy + PH_PERF_SEL_SC6_ARB_PA_BUSY_SOP = 0x000002d9, // PH_PERF_SEL_SC6_ARB_PA_BUSY_SOP counts number of cycles in between start of packet/end of packet + PH_PERF_SEL_SC6_ARB_EOP_POP_SYNC_POP = 0x000002da, // PH_PERF_SEL_SC6_ARB_EOP_POP_SYNC_POP counts number of cycles of of pa sc arbiter eop reads at the eop sync point with all fifos synced + PH_PERF_SEL_SC6_ARB_EVENT_SYNC_POP = 0x000002db, // PH_PERF_SEL_SC6_ARB_EVENT_SYNC_POP counts number of cycles of pa sc event reads + PH_PERF_SEL_SC6_PS_ENG_MULTICYCLE_BUBBLE = 0x000002dc, // PH_PERF_SEL_SC6_PS_ENG_MULTICYCLE_BUBBLE counts number of cycles of multicycles prims sent with a empty fifo slot behind the current phase. + PH_PERF_SEL_SC6_EOP_SYNC_WINDOW = 0x000002dd, // PH_PERF_SEL_SC6_EOP_SYNC_WINDOW counts number of cycles of after end of packet is read from the selected pa sc fifo until end of packet broadcast synchronization is achieved across all pa sc fifos + PH_PERF_SEL_SC6_BUSY_PROCESSING_MULTICYCLE_PRIM = 0x000002de, // PH_PERF_SEL_SC6_BUSY_PROCESSING_MULTICYCLE_PRIM counts number of cycles of sc arbiter busy processing multicycle prims (clipped, perspective linear gradient, line stipple) + PH_PERF_SEL_SC6_BUSY_CNT_NOT_ZERO = 0x000002df, // PH_PERF_SEL_SC6_BUSY_CNT_NOT_ZERO counts number of cycles of ph-sc read setup busy counter non zero. + PH_PERF_SEL_SC6_SEND = 0x000002e0, // PH_PERF_SEL_SC6_SEND counts interface sends to SC + PH_PERF_SEL_SC6_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x000002e1, // PH_PERF_SEL_SC6_CREDIT_AT_ZERO_WITH_PENDING_SEND counts interface stalled for no SC credits with pending data available + PH_PERF_SEL_SC6_CREDIT_AT_MAX = 0x000002e2, // PH_PERF_SEL_SC6_CREDIT_AT_MAX counts full PH_SC interface credit pool available (INTERFACE IDLE) + PH_PERF_SEL_SC6_CREDIT_AT_MAX_NO_PENDING_SEND = 0x000002e3, // PH_PERF_SEL_SC6_CREDIT_AT_MAX_NO_PENDING_SEND counts full PH_SC interface credit pool available with no pending PH_SC data to send (FULL IDLE of PH_SC slice) + PH_PERF_SEL_SC6_GFX_PIPE_EVENT_PROVOKED_TRANSITION = 0x000002e4, // PH_PERF_SEL_SC6_GFX_PIPE_EVENT_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by an EVENT associated with a new gfx pipe id + PH_PERF_SEL_SC6_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION = 0x000002e5, // PH_PERF_SEL_SC6_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by a primitive associated with a new gfx pipe id + PH_PERF_SEL_SC6_GFX_PIPE0_TO_1_TRANSITION = 0x000002e6, // PH_PERF_SEL_SC6_GFX_PIPE0_TO_1_TRANSITION counts GFX PIPEID transitions from pipe0 to pipe1 + PH_PERF_SEL_SC6_GFX_PIPE1_TO_0_TRANSITION = 0x000002e7, // PH_PERF_SEL_SC6_GFX_PIPE1_TO_0_TRANSITION counts GFX PIPEID transitions from pipe1 to pipe0 + PH_PERF_SEL_SC6_PA0_DATA_FIFO_RD = 0x000002e8, // PH_PERF_SEL_SC6_PA0_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC6_PA0_DATA_FIFO_WE = 0x000002e9, // PH_PERF_SEL_SC6_PA0_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC6_PA0_FIFO_EMPTY = 0x000002ea, // PH_PERF_SEL_SC6_PA0_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC6_PA0_FIFO_FULL = 0x000002eb, // PH_PERF_SEL_SC6_PA0_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC6_PA0_NULL_WE = 0x000002ec, // PH_PERF_SEL_SC6_PA0_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC6_PA0_EVENT_WE = 0x000002ed, // PH_PERF_SEL_SC6_PA0_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC6_PA0_FPOV_WE = 0x000002ee, // PH_PERF_SEL_SC6_PA0_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC6_PA0_LPOV_WE = 0x000002ef, // PH_PERF_SEL_SC6_PA0_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC6_PA0_EOP_WE = 0x000002f0, // PH_PERF_SEL_SC6_PA0_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC6_PA0_DATA_FIFO_EOP_RD = 0x000002f1, // PH_PERF_SEL_SC6_PA0_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC6_PA0_EOPG_WE = 0x000002f2, // PH_PA0 PH_SC6_PA0_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC6_PA0_DEALLOC_4_0_RD = 0x000002f3, // PH_PERF_SEL_SC6_PA0_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC6_PA1_DATA_FIFO_RD = 0x000002f4, // PH_PERF_SEL_SC6_PA1_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC6_PA1_DATA_FIFO_WE = 0x000002f5, // PH_PERF_SEL_SC6_PA1_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC6_PA1_FIFO_EMPTY = 0x000002f6, // PH_PERF_SEL_SC6_PA1_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC6_PA1_FIFO_FULL = 0x000002f7, // PH_PERF_SEL_SC6_PA1_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC6_PA1_NULL_WE = 0x000002f8, // PH_PERF_SEL_SC6_PA1_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC6_PA1_EVENT_WE = 0x000002f9, // PH_PERF_SEL_SC6_PA1_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC6_PA1_FPOV_WE = 0x000002fa, // PH_PERF_SEL_SC6_PA1_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC6_PA1_LPOV_WE = 0x000002fb, // PH_PERF_SEL_SC6_PA1_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC6_PA1_EOP_WE = 0x000002fc, // PH_PERF_SEL_SC6_PA1_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC6_PA1_DATA_FIFO_EOP_RD = 0x000002fd, // PH_PERF_SEL_SC6_PA1_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC6_PA1_EOPG_WE = 0x000002fe, // PH_PA1 PH_SC6_PA1_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC6_PA1_DEALLOC_4_0_RD = 0x000002ff, // PH_PERF_SEL_SC6_PA1_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC6_PA2_DATA_FIFO_RD = 0x00000300, // PH_PERF_SEL_SC6_PA2_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC6_PA2_DATA_FIFO_WE = 0x00000301, // PH_PERF_SEL_SC6_PA2_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC6_PA2_FIFO_EMPTY = 0x00000302, // PH_PERF_SEL_SC6_PA2_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC6_PA2_FIFO_FULL = 0x00000303, // PH_PERF_SEL_SC6_PA2_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC6_PA2_NULL_WE = 0x00000304, // PH_PERF_SEL_SC6_PA2_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC6_PA2_EVENT_WE = 0x00000305, // PH_PERF_SEL_SC6_PA2_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC6_PA2_FPOV_WE = 0x00000306, // PH_PERF_SEL_SC6_PA2_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC6_PA2_LPOV_WE = 0x00000307, // PH_PERF_SEL_SC6_PA2_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC6_PA2_EOP_WE = 0x00000308, // PH_PERF_SEL_SC6_PA2_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC6_PA2_DATA_FIFO_EOP_RD = 0x00000309, // PH_PERF_SEL_SC6_PA2_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC6_PA2_EOPG_WE = 0x0000030a, // PH_PA2 PH_SC6_PA2_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC6_PA2_DEALLOC_4_0_RD = 0x0000030b, // PH_PERF_SEL_SC6_PA2_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC6_PA3_DATA_FIFO_RD = 0x0000030c, // PH_PERF_SEL_SC6_PA3_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC6_PA3_DATA_FIFO_WE = 0x0000030d, // PH_PERF_SEL_SC6_PA3_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC6_PA3_FIFO_EMPTY = 0x0000030e, // PH_PERF_SEL_SC6_PA3_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC6_PA3_FIFO_FULL = 0x0000030f, // PH_PERF_SEL_SC6_PA3_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC6_PA3_NULL_WE = 0x00000310, // PH_PERF_SEL_SC6_PA3_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC6_PA3_EVENT_WE = 0x00000311, // PH_PERF_SEL_SC6_PA3_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC6_PA3_FPOV_WE = 0x00000312, // PH_PERF_SEL_SC6_PA3_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC6_PA3_LPOV_WE = 0x00000313, // PH_PERF_SEL_SC6_PA3_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC6_PA3_EOP_WE = 0x00000314, // PH_PERF_SEL_SC6_PA3_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC6_PA3_DATA_FIFO_EOP_RD = 0x00000315, // PH_PERF_SEL_SC6_PA3_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC6_PA3_EOPG_WE = 0x00000316, // PH_PA3 PH_SC6_PA3_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC6_PA3_DEALLOC_4_0_RD = 0x00000317, // PH_PERF_SEL_SC6_PA3_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC6_PA4_DATA_FIFO_RD = 0x00000318, // PH_PERF_SEL_SC6_PA4_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC6_PA4_DATA_FIFO_WE = 0x00000319, // PH_PERF_SEL_SC6_PA4_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC6_PA4_FIFO_EMPTY = 0x0000031a, // PH_PERF_SEL_SC6_PA4_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC6_PA4_FIFO_FULL = 0x0000031b, // PH_PERF_SEL_SC6_PA4_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC6_PA4_NULL_WE = 0x0000031c, // PH_PERF_SEL_SC6_PA4_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC6_PA4_EVENT_WE = 0x0000031d, // PH_PERF_SEL_SC6_PA4_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC6_PA4_FPOV_WE = 0x0000031e, // PH_PERF_SEL_SC6_PA4_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC6_PA4_LPOV_WE = 0x0000031f, // PH_PERF_SEL_SC6_PA4_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC6_PA4_EOP_WE = 0x00000320, // PH_PERF_SEL_SC6_PA4_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC6_PA4_DATA_FIFO_EOP_RD = 0x00000321, // PH_PERF_SEL_SC6_PA4_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC6_PA4_EOPG_WE = 0x00000322, // PH_PA4 PH_SC6_PA4_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC6_PA4_DEALLOC_4_0_RD = 0x00000323, // PH_PERF_SEL_SC6_PA4_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC6_PA5_DATA_FIFO_RD = 0x00000324, // PH_PERF_SEL_SC6_PA5_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC6_PA5_DATA_FIFO_WE = 0x00000325, // PH_PERF_SEL_SC6_PA5_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC6_PA5_FIFO_EMPTY = 0x00000326, // PH_PERF_SEL_SC6_PA5_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC6_PA5_FIFO_FULL = 0x00000327, // PH_PERF_SEL_SC6_PA5_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC6_PA5_NULL_WE = 0x00000328, // PH_PERF_SEL_SC6_PA5_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC6_PA5_EVENT_WE = 0x00000329, // PH_PERF_SEL_SC6_PA5_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC6_PA5_FPOV_WE = 0x0000032a, // PH_PERF_SEL_SC6_PA5_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC6_PA5_LPOV_WE = 0x0000032b, // PH_PERF_SEL_SC6_PA5_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC6_PA5_EOP_WE = 0x0000032c, // PH_PERF_SEL_SC6_PA5_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC6_PA5_DATA_FIFO_EOP_RD = 0x0000032d, // PH_PERF_SEL_SC6_PA5_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC6_PA5_EOPG_WE = 0x0000032e, // PH_PA5 PH_SC6_PA5_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC6_PA5_DEALLOC_4_0_RD = 0x0000032f, // PH_PERF_SEL_SC6_PA5_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC6_PA6_DATA_FIFO_RD = 0x00000330, // PH_PERF_SEL_SC6_PA6_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC6_PA6_DATA_FIFO_WE = 0x00000331, // PH_PERF_SEL_SC6_PA6_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC6_PA6_FIFO_EMPTY = 0x00000332, // PH_PERF_SEL_SC6_PA6_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC6_PA6_FIFO_FULL = 0x00000333, // PH_PERF_SEL_SC6_PA6_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC6_PA6_NULL_WE = 0x00000334, // PH_PERF_SEL_SC6_PA6_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC6_PA6_EVENT_WE = 0x00000335, // PH_PERF_SEL_SC6_PA6_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC6_PA6_FPOV_WE = 0x00000336, // PH_PERF_SEL_SC6_PA6_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC6_PA6_LPOV_WE = 0x00000337, // PH_PERF_SEL_SC6_PA6_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC6_PA6_EOP_WE = 0x00000338, // PH_PERF_SEL_SC6_PA6_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC6_PA6_DATA_FIFO_EOP_RD = 0x00000339, // PH_PERF_SEL_SC6_PA6_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC6_PA6_EOPG_WE = 0x0000033a, // PH_PA6 PH_SC6_PA6_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC6_PA6_DEALLOC_4_0_RD = 0x0000033b, // PH_PERF_SEL_SC6_PA6_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC6_PA7_DATA_FIFO_RD = 0x0000033c, // PH_PERF_SEL_SC6_PA7_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC6_PA7_DATA_FIFO_WE = 0x0000033d, // PH_PERF_SEL_SC6_PA7_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC6_PA7_FIFO_EMPTY = 0x0000033e, // PH_PERF_SEL_SC6_PA7_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC6_PA7_FIFO_FULL = 0x0000033f, // PH_PERF_SEL_SC6_PA7_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC6_PA7_NULL_WE = 0x00000340, // PH_PERF_SEL_SC6_PA7_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC6_PA7_EVENT_WE = 0x00000341, // PH_PERF_SEL_SC6_PA7_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC6_PA7_FPOV_WE = 0x00000342, // PH_PERF_SEL_SC6_PA7_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC6_PA7_LPOV_WE = 0x00000343, // PH_PERF_SEL_SC6_PA7_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC6_PA7_EOP_WE = 0x00000344, // PH_PERF_SEL_SC6_PA7_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC6_PA7_DATA_FIFO_EOP_RD = 0x00000345, // PH_PERF_SEL_SC6_PA7_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC6_PA7_EOPG_WE = 0x00000346, // PH_PA7 PH_SC6_PA7_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC6_PA7_DEALLOC_4_0_RD = 0x00000347, // PH_PERF_SEL_SC6_PA7_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC7_SRPS_WINDOW_VALID = 0x00000348, // PH_PERF_SEL_SC7_SRPS_WINDOW_VALID Counts PERFCOUNTER_START to PERFCOUNTER_STOP stop perfcounter enable window in PH Read Setup logic + PH_PERF_SEL_SC7_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES = 0x00000349, // PH_PERF_SEL_SC7_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES counts number of cycles of arb xfc's for all event or prims + PH_PERF_SEL_SC7_ARB_XFC_ONLY_PRIM_CYCLES = 0x0000034a, // PH_PERF_SEL_SC7_ARB_XFC_ONLY_PRIM_CYCLES counts number of cycles of arb xfc's for only prims (events excluded) + PH_PERF_SEL_SC7_ARB_XFC_ONLY_ONE_INC_PER_PRIM = 0x0000034b, // PH_PERF_SEL_SC7_ARB_XFC_ONLY_ONE_INC_PER_PRIM counts number of cycles of arb xfc's for one inc per prim only. Increments only for phase 0 of a multi-cycle primitive transfer + PH_PERF_SEL_SC7_ARB_STALLED_FROM_BELOW = 0x0000034c, // PH_PERF_SEL_SC7_ARB_STALLED_FROM_BELOW counts number of cycles of stalled post arbiter for valid data + PH_PERF_SEL_SC7_ARB_STARVED_FROM_ABOVE = 0x0000034d, // PH_PERF_SEL_SC7_ARB_STARVED_FROM_ABOVE counts number of cycles of PA starving SC in start-of-packet/eop range + PH_PERF_SEL_SC7_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY = 0x0000034e, // PH_PERF_SEL_SC7_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_NOT_EMPTY counts from above (pa) with an unselected pa fifo not empty (use if more than one pa only) + PH_PERF_SEL_SC7_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL = 0x0000034f, // PH_PERF_SEL_SC7_ARB_STARVED_FROM_ABOVE_WITH_UNSELECTED_FIFO_FULL counts starved by pa with a unselected pa fifo full (use if more than one pa only) This means that inside the draw packet the SC selected fifo has no valid data, and that one of the unselected fifo's has gone fifo's has gone full. + PH_PERF_SEL_SC7_ARB_BUSY = 0x00000350, // PH_PERF_SEL_SC7_ARB_BUSY counts number of cycles of PH_SC7 busy + PH_PERF_SEL_SC7_ARB_PA_BUSY_SOP = 0x00000351, // PH_PERF_SEL_SC7_ARB_PA_BUSY_SOP counts number of cycles in between start of packet/end of packet + PH_PERF_SEL_SC7_ARB_EOP_POP_SYNC_POP = 0x00000352, // PH_PERF_SEL_SC7_ARB_EOP_POP_SYNC_POP counts number of cycles of of pa sc arbiter eop reads at the eop sync point with all fifos synced + PH_PERF_SEL_SC7_ARB_EVENT_SYNC_POP = 0x00000353, // PH_PERF_SEL_SC7_ARB_EVENT_SYNC_POP counts number of cycles of pa sc event reads + PH_PERF_SEL_SC7_PS_ENG_MULTICYCLE_BUBBLE = 0x00000354, // PH_PERF_SEL_SC7_PS_ENG_MULTICYCLE_BUBBLE counts number of cycles of multicycles prims sent with a empty fifo slot behind the current phase. + PH_PERF_SEL_SC7_EOP_SYNC_WINDOW = 0x00000355, // PH_PERF_SEL_SC7_EOP_SYNC_WINDOW counts number of cycles of after end of packet is read from the selected pa sc fifo until end of packet broadcast synchronization is achieved across all pa sc fifos + PH_PERF_SEL_SC7_BUSY_PROCESSING_MULTICYCLE_PRIM = 0x00000356, // PH_PERF_SEL_SC7_BUSY_PROCESSING_MULTICYCLE_PRIM counts number of cycles of sc arbiter busy processing multicycle prims (clipped, perspective linear gradient, line stipple) + PH_PERF_SEL_SC7_BUSY_CNT_NOT_ZERO = 0x00000357, // PH_PERF_SEL_SC7_BUSY_CNT_NOT_ZERO counts number of cycles of ph-sc read setup busy counter non zero. + PH_PERF_SEL_SC7_SEND = 0x00000358, // PH_PERF_SEL_SC7_SEND counts interface sends to SC + PH_PERF_SEL_SC7_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x00000359, // PH_PERF_SEL_SC7_CREDIT_AT_ZERO_WITH_PENDING_SEND counts interface stalled for no SC credits with pending data available + PH_PERF_SEL_SC7_CREDIT_AT_MAX = 0x0000035a, // PH_PERF_SEL_SC7_CREDIT_AT_MAX counts full PH_SC interface credit pool available (INTERFACE IDLE) + PH_PERF_SEL_SC7_CREDIT_AT_MAX_NO_PENDING_SEND = 0x0000035b, // PH_PERF_SEL_SC7_CREDIT_AT_MAX_NO_PENDING_SEND counts full PH_SC interface credit pool available with no pending PH_SC data to send (FULL IDLE of PH_SC slice) + PH_PERF_SEL_SC7_GFX_PIPE_EVENT_PROVOKED_TRANSITION = 0x0000035c, // PH_PERF_SEL_SC7_GFX_PIPE_EVENT_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by an EVENT associated with a new gfx pipe id + PH_PERF_SEL_SC7_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION = 0x0000035d, // PH_PERF_SEL_SC7_GFX_PIPE_EOP_PRIM_PROVOKED_TRANSITION counts GFX PIPEID transition (pipe0 to pipe1 or pipe1 to pipe0) caused by a primitive associated with a new gfx pipe id + PH_PERF_SEL_SC7_GFX_PIPE0_TO_1_TRANSITION = 0x0000035e, // PH_PERF_SEL_SC7_GFX_PIPE0_TO_1_TRANSITION counts GFX PIPEID transitions from pipe0 to pipe1 + PH_PERF_SEL_SC7_GFX_PIPE1_TO_0_TRANSITION = 0x0000035f, // PH_PERF_SEL_SC7_GFX_PIPE1_TO_0_TRANSITION counts GFX PIPEID transitions from pipe1 to pipe0 + PH_PERF_SEL_SC7_PA0_DATA_FIFO_RD = 0x00000360, // PH_PERF_SEL_SC7_PA0_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC7_PA0_DATA_FIFO_WE = 0x00000361, // PH_PERF_SEL_SC7_PA0_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC7_PA0_FIFO_EMPTY = 0x00000362, // PH_PERF_SEL_SC7_PA0_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC7_PA0_FIFO_FULL = 0x00000363, // PH_PERF_SEL_SC7_PA0_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC7_PA0_NULL_WE = 0x00000364, // PH_PERF_SEL_SC7_PA0_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC7_PA0_EVENT_WE = 0x00000365, // PH_PERF_SEL_SC7_PA0_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC7_PA0_FPOV_WE = 0x00000366, // PH_PERF_SEL_SC7_PA0_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC7_PA0_LPOV_WE = 0x00000367, // PH_PERF_SEL_SC7_PA0_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC7_PA0_EOP_WE = 0x00000368, // PH_PERF_SEL_SC7_PA0_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC7_PA0_DATA_FIFO_EOP_RD = 0x00000369, // PH_PERF_SEL_SC7_PA0_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC7_PA0_EOPG_WE = 0x0000036a, // PH_PA0 PH_SC7_PA0_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC7_PA0_DEALLOC_4_0_RD = 0x0000036b, // PH_PERF_SEL_SC7_PA0_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC7_PA1_DATA_FIFO_RD = 0x0000036c, // PH_PERF_SEL_SC7_PA1_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC7_PA1_DATA_FIFO_WE = 0x0000036d, // PH_PERF_SEL_SC7_PA1_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC7_PA1_FIFO_EMPTY = 0x0000036e, // PH_PERF_SEL_SC7_PA1_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC7_PA1_FIFO_FULL = 0x0000036f, // PH_PERF_SEL_SC7_PA1_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC7_PA1_NULL_WE = 0x00000370, // PH_PERF_SEL_SC7_PA1_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC7_PA1_EVENT_WE = 0x00000371, // PH_PERF_SEL_SC7_PA1_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC7_PA1_FPOV_WE = 0x00000372, // PH_PERF_SEL_SC7_PA1_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC7_PA1_LPOV_WE = 0x00000373, // PH_PERF_SEL_SC7_PA1_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC7_PA1_EOP_WE = 0x00000374, // PH_PERF_SEL_SC7_PA1_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC7_PA1_DATA_FIFO_EOP_RD = 0x00000375, // PH_PERF_SEL_SC7_PA1_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC7_PA1_EOPG_WE = 0x00000376, // PH_PA1 PH_SC7_PA1_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC7_PA1_DEALLOC_4_0_RD = 0x00000377, // PH_PERF_SEL_SC7_PA1_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC7_PA2_DATA_FIFO_RD = 0x00000378, // PH_PERF_SEL_SC7_PA2_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC7_PA2_DATA_FIFO_WE = 0x00000379, // PH_PERF_SEL_SC7_PA2_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC7_PA2_FIFO_EMPTY = 0x0000037a, // PH_PERF_SEL_SC7_PA2_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC7_PA2_FIFO_FULL = 0x0000037b, // PH_PERF_SEL_SC7_PA2_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC7_PA2_NULL_WE = 0x0000037c, // PH_PERF_SEL_SC7_PA2_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC7_PA2_EVENT_WE = 0x0000037d, // PH_PERF_SEL_SC7_PA2_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC7_PA2_FPOV_WE = 0x0000037e, // PH_PERF_SEL_SC7_PA2_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC7_PA2_LPOV_WE = 0x0000037f, // PH_PERF_SEL_SC7_PA2_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC7_PA2_EOP_WE = 0x00000380, // PH_PERF_SEL_SC7_PA2_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC7_PA2_DATA_FIFO_EOP_RD = 0x00000381, // PH_PERF_SEL_SC7_PA2_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC7_PA2_EOPG_WE = 0x00000382, // PH_PA2 PH_SC7_PA2_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC7_PA2_DEALLOC_4_0_RD = 0x00000383, // PH_PERF_SEL_SC7_PA2_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC7_PA3_DATA_FIFO_RD = 0x00000384, // PH_PERF_SEL_SC7_PA3_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC7_PA3_DATA_FIFO_WE = 0x00000385, // PH_PERF_SEL_SC7_PA3_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC7_PA3_FIFO_EMPTY = 0x00000386, // PH_PERF_SEL_SC7_PA3_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC7_PA3_FIFO_FULL = 0x00000387, // PH_PERF_SEL_SC7_PA3_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC7_PA3_NULL_WE = 0x00000388, // PH_PERF_SEL_SC7_PA3_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC7_PA3_EVENT_WE = 0x00000389, // PH_PERF_SEL_SC7_PA3_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC7_PA3_FPOV_WE = 0x0000038a, // PH_PERF_SEL_SC7_PA3_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC7_PA3_LPOV_WE = 0x0000038b, // PH_PERF_SEL_SC7_PA3_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC7_PA3_EOP_WE = 0x0000038c, // PH_PERF_SEL_SC7_PA3_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC7_PA3_DATA_FIFO_EOP_RD = 0x0000038d, // PH_PERF_SEL_SC7_PA3_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC7_PA3_EOPG_WE = 0x0000038e, // PH_PA3 PH_SC7_PA3_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC7_PA3_DEALLOC_4_0_RD = 0x0000038f, // PH_PERF_SEL_SC7_PA3_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC7_PA4_DATA_FIFO_RD = 0x00000390, // PH_PERF_SEL_SC7_PA4_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC7_PA4_DATA_FIFO_WE = 0x00000391, // PH_PERF_SEL_SC7_PA4_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC7_PA4_FIFO_EMPTY = 0x00000392, // PH_PERF_SEL_SC7_PA4_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC7_PA4_FIFO_FULL = 0x00000393, // PH_PERF_SEL_SC7_PA4_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC7_PA4_NULL_WE = 0x00000394, // PH_PERF_SEL_SC7_PA4_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC7_PA4_EVENT_WE = 0x00000395, // PH_PERF_SEL_SC7_PA4_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC7_PA4_FPOV_WE = 0x00000396, // PH_PERF_SEL_SC7_PA4_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC7_PA4_LPOV_WE = 0x00000397, // PH_PERF_SEL_SC7_PA4_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC7_PA4_EOP_WE = 0x00000398, // PH_PERF_SEL_SC7_PA4_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC7_PA4_DATA_FIFO_EOP_RD = 0x00000399, // PH_PERF_SEL_SC7_PA4_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC7_PA4_EOPG_WE = 0x0000039a, // PH_PA4 PH_SC7_PA4_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC7_PA4_DEALLOC_4_0_RD = 0x0000039b, // PH_PERF_SEL_SC7_PA4_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC7_PA5_DATA_FIFO_RD = 0x0000039c, // PH_PERF_SEL_SC7_PA5_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC7_PA5_DATA_FIFO_WE = 0x0000039d, // PH_PERF_SEL_SC7_PA5_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC7_PA5_FIFO_EMPTY = 0x0000039e, // PH_PERF_SEL_SC7_PA5_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC7_PA5_FIFO_FULL = 0x0000039f, // PH_PERF_SEL_SC7_PA5_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC7_PA5_NULL_WE = 0x000003a0, // PH_PERF_SEL_SC7_PA5_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC7_PA5_EVENT_WE = 0x000003a1, // PH_PERF_SEL_SC7_PA5_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC7_PA5_FPOV_WE = 0x000003a2, // PH_PERF_SEL_SC7_PA5_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC7_PA5_LPOV_WE = 0x000003a3, // PH_PERF_SEL_SC7_PA5_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC7_PA5_EOP_WE = 0x000003a4, // PH_PERF_SEL_SC7_PA5_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC7_PA5_DATA_FIFO_EOP_RD = 0x000003a5, // PH_PERF_SEL_SC7_PA5_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC7_PA5_EOPG_WE = 0x000003a6, // PH_PA5 PH_SC7_PA5_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC7_PA5_DEALLOC_4_0_RD = 0x000003a7, // PH_PERF_SEL_SC7_PA5_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC7_PA6_DATA_FIFO_RD = 0x000003a8, // PH_PERF_SEL_SC7_PA6_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC7_PA6_DATA_FIFO_WE = 0x000003a9, // PH_PERF_SEL_SC7_PA6_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC7_PA6_FIFO_EMPTY = 0x000003aa, // PH_PERF_SEL_SC7_PA6_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC7_PA6_FIFO_FULL = 0x000003ab, // PH_PERF_SEL_SC7_PA6_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC7_PA6_NULL_WE = 0x000003ac, // PH_PERF_SEL_SC7_PA6_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC7_PA6_EVENT_WE = 0x000003ad, // PH_PERF_SEL_SC7_PA6_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC7_PA6_FPOV_WE = 0x000003ae, // PH_PERF_SEL_SC7_PA6_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC7_PA6_LPOV_WE = 0x000003af, // PH_PERF_SEL_SC7_PA6_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC7_PA6_EOP_WE = 0x000003b0, // PH_PERF_SEL_SC7_PA6_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC7_PA6_DATA_FIFO_EOP_RD = 0x000003b1, // PH_PERF_SEL_SC7_PA6_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC7_PA6_EOPG_WE = 0x000003b2, // PH_PA6 PH_SC7_PA6_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC7_PA6_DEALLOC_4_0_RD = 0x000003b3, // PH_PERF_SEL_SC7_PA6_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) + PH_PERF_SEL_SC7_PA7_DATA_FIFO_RD = 0x000003b4, // PH_PERF_SEL_SC7_PA7_DATA_FIFO_RD counts data FIFO reads + PH_PERF_SEL_SC7_PA7_DATA_FIFO_WE = 0x000003b5, // PH_PERF_SEL_SC7_PA7_DATA_FIFO_WE counts data FIFO writes + PH_PERF_SEL_SC7_PA7_FIFO_EMPTY = 0x000003b6, // PH_PERF_SEL_SC7_PA7_FIFO_EMPTY counts data FIFO empty + PH_PERF_SEL_SC7_PA7_FIFO_FULL = 0x000003b7, // PH_PERF_SEL_SC7_PA7_FIFO_FULL counts data FIFO full + PH_PERF_SEL_SC7_PA7_NULL_WE = 0x000003b8, // PH_PERF_SEL_SC7_PA7_NULL_WE counts data FIFO null primitive write + PH_PERF_SEL_SC7_PA7_EVENT_WE = 0x000003b9, // PH_PERF_SEL_SC7_PA7_EVENT_WE counts data FIFO event write + PH_PERF_SEL_SC7_PA7_FPOV_WE = 0x000003ba, // PH_PERF_SEL_SC7_PA7_FPOV_WE counts data FIFO first prim of vector write + PH_PERF_SEL_SC7_PA7_LPOV_WE = 0x000003bb, // PH_PERF_SEL_SC7_PA7_LPOV_WE counts data FIFO last prim of vector write + PH_PERF_SEL_SC7_PA7_EOP_WE = 0x000003bc, // PH_PERF_SEL_SC7_PA7_EOP_WE counts data FIFO end-of-packet write + PH_PERF_SEL_SC7_PA7_DATA_FIFO_EOP_RD = 0x000003bd, // PH_PERF_SEL_SC7_PA7_DATA_FIFO_EOP_RD counts data FIFO end-of-packet read + PH_PERF_SEL_SC7_PA7_EOPG_WE = 0x000003be, // PH_PA7 PH_SC7_PA7_EOPG_WE counts data FIFO end-of-primgroup write + PH_PERF_SEL_SC7_PA7_DEALLOC_4_0_RD = 0x000003bf, // PH_PERF_SEL_SC7_PA7_DEALLOC_4_0_RD counts data FIFO dealloc tokens bit 4 to 0 (full size dealloc is 11 bit so 10:5 bits are not part of the count) +} PH_PERFCOUNTER_SELECT; + +typedef enum RMI_PERFCOUNTER_SELECT : unsigned int { + RMI_PERF_SEL_NONE = 0x00000000, // Count nothing + RMI_PERF_SEL_BUSY = 0x00000001, // Number of busy cycles + RMI_PERF_SEL_REG_CLK_VLD = 0x00000002, // Number of cycles that the registre clock is enabled. + RMI_PERF_SEL_DYN_CLK_CMN_VLD = 0x00000003, // Number of cycles that the common core clock is enabled. + RMI_PERF_SEL_DYN_CLK_RB_VLD = 0x00000004, // Number of cycles that the RB0 clock is enabled. + RMI_PERF_SEL_DYN_CLK_PERF_VLD = 0x00000005, // Number of cycles that the perf clock is enabled. + RMI_PERF_SEL_PERF_WINDOW = 0x00000006, // This is performance window event. Window between perf start and perf end event using perf clk. Can be used as denominator for bandwidth calculation. + RMI_PERF_SEL_EVENT_SEND = 0x00000007, // Indicates RMI receiving an event. + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID0 = 0x00000008, // ATC invalidation event (rising edge of start) to RMI for VMID0. Can be used to calculate rmi_invalidation_atc_req for VMID0 bandwidth. + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID1 = 0x00000009, // same as above using VMID1. + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID2 = 0x0000000a, // same as above using VMID2 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID3 = 0x0000000b, // same as above using VMID3 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID4 = 0x0000000c, // same as above using VMID4 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID5 = 0x0000000d, // same as above using VMID5 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID6 = 0x0000000e, // same as above using VMID6 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID7 = 0x0000000f, // same as above using VMID7 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID8 = 0x00000010, // same as above using VMID8 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID9 = 0x00000011, // same as above using VMID9 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID10 = 0x00000012, // same as above using VMID10 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID11 = 0x00000013, // same as above using VMID11 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID12 = 0x00000014, // same as above using VMID12 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID13 = 0x00000015, // same as above using VMID13 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID14 = 0x00000016, // same as above using VMID14 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID15 = 0x00000017, // same as above using VMID15 + RMI_PERF_SEL_RMI_INVALIDATION_ATC_REQ_VMID_ALL = 0x00000018, // same as above using ALL VMID + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID0 = 0x00000019, // Start to Finish (ATC & GPUVM) Invalidation to RMI for VMID0. Can be used to calculate latency. + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID1 = 0x0000001a, // same as above using VMID1 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID2 = 0x0000001b, // same as above using VMID2 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID3 = 0x0000001c, // same as above using VMID3 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID4 = 0x0000001d, // same as above using VMID4 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID5 = 0x0000001e, // same as above using VMID5 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID6 = 0x0000001f, // same as above using VMID6 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID7 = 0x00000020, // same as above using VMID7 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID8 = 0x00000021, // same as above using VMID8 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID9 = 0x00000022, // same as above using VMID9 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID10 = 0x00000023, // same as above using VMID10 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID11 = 0x00000024, // same as above using VMID11 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID12 = 0x00000025, // same as above using VMID12 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID13 = 0x00000026, // same as above using VMID13 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID14 = 0x00000027, // same as above using VMID14 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID15 = 0x00000028, // same as above using VMID15 + RMI_PERF_SEL_RMI_INVALIDATION_REQ_START_FINISH_VMID_ALL = 0x00000029, // same as above using ALL VMID + RMI_PERF_SEL_UTCL1_TRANSLATION_MISS = 0x0000002a, // utcl1 translation misses + RMI_PERF_SEL_UTCL1_PERMISSION_MISS = 0x0000002b, // utcl1 permission misses + RMI_PERF_SEL_UTCL1_TRANSLATION_HIT = 0x0000002c, // utcl1 translation hits + RMI_PERF_SEL_UTCL1_REQUEST = 0x0000002d, // CLIENT_UTCL1 NORMAL requestes + RMI_PERF_SEL_UTCL1_STALL_INFLIGHT_MAX = 0x0000002e, // utcl1 stalls due to inflight counter saturation + RMI_PERF_SEL_UTCL1_STALL_LRU_INFLIGHT = 0x0000002f, // utcl1 stalls due to LRU cache line with traffic inflight + RMI_PERF_SEL_UTCL1_LFIFO_FULL = 0x00000030, // utcl1 utcl2 latency hiding fifo full cycles + RMI_PERF_SEL_UTCL1_STALL_LFIFO_NOT_RES = 0x00000031, // utcl1 stalls due to utcl2 latency hiding fifo output not resident + RMI_PERF_SEL_UTCL1_STALL_UTCL2_REQ_OUT_OF_CREDITS = 0x00000032, // utcl1 stalls due to utcl2_req out of credits + RMI_PERF_SEL_UTCL1_STALL_MISSFIFO_FULL = 0x00000033, // utcl1 stalls due to full miss fifo + RMI_PERF_SEL_UTCL1_HIT_FIFO_FULL = 0x00000034, // utcl1 hit fifo full cycles + RMI_PERF_SEL_UTCL1_STALL_MULTI_MISS = 0x00000035, // utcl1 stall due to arbitrated multiple misses + RMI_PERF_SEL_RB_RMI_WRREQ_ALL_CID = 0x00000036, // Counts the write requests in a specific channel for ALL CIDs + RMI_PERF_SEL_RB_RMI_WRREQ_TO_WRRET_BUSY = 0x00000037, // Number busy cycles from WRREQ to WRRET. + RMI_PERF_SEL_RB_RMI_WRREQ_CID0 = 0x00000038, // Counts the write requests in a specific channel with CID=0. + RMI_PERF_SEL_RB_RMI_WRREQ_CID1 = 0x00000039, // Counts the write requests in a specific channel with CID=1. + RMI_PERF_SEL_RB_RMI_WRREQ_CID2 = 0x0000003a, // Counts the write requests in a specific channel with CID=2. + RMI_PERF_SEL_RB_RMI_WRREQ_CID3 = 0x0000003b, // Counts the write requests in a specific channel with CID=3. + RMI_PERF_SEL_RB_RMI_WRREQ_CID4 = 0x0000003c, // Counts the write requests in a specific channel with CID=4. + RMI_PERF_SEL_RB_RMI_WRREQ_CID5 = 0x0000003d, // Counts the write requests in a specific channel with CID=5. + RMI_PERF_SEL_RB_RMI_WRREQ_CID6 = 0x0000003e, // Counts the write requests in a specific channel with CID=6. + RMI_PERF_SEL_RB_RMI_WRREQ_CID7 = 0x0000003f, // Counts the write requests in a specific channel with CID=7. + RMI_PERF_SEL_RB_RMI_32BWRREQ_INFLIGHT_ALL_ORONE_CID = 0x00000040, // Number of 32B request inflight from RB-RMI from ALL or ONE CID used to calculate average latency. CID to be defined by PERF_CID_SEL. + RMI_PERF_SEL_RB_RMI_WRREQ_BURST_LENGTH_ALL_ORONE_CID = 0x00000041, // Number of WRREQ from RB to RMI with burst=1 when length of burst is more than a threshold defined in register. Can be used to calculate average bursts length more than a threshold. CID to be defined by PERF_CID_SEL. + RMI_PERF_SEL_RB_RMI_WRREQ_BURST_ALL_ORONE_CID = 0x00000042, // WRREQ from RB to RMI with burst=1 with the length more than a threshold event. (How is this different from above?) + RMI_PERF_SEL_RB_RMI_WRREQ_RESIDENCY = 0x00000043, // Number of residency checks done on RB to RMI WRREQ interface. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_ALL_CID = 0x00000044, // Number of 32B write returns from RMI to RB for all CIDs. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_CID0 = 0x00000045, // Number of 32B write returns from RMI to RB for CID0. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_CID1 = 0x00000046, // Number of 32B write returns from RMI to RB for CID1. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_CID2 = 0x00000047, // Number of 32B write returns from RMI to RB for CID2. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_CID3 = 0x00000048, // Number of 32B write returns from RMI to RB for CID3. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_CID4 = 0x00000049, // Number of 32B write returns from RMI to RB for CID4. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_CID5 = 0x0000004a, // Number of 32B write returns from RMI to RB for CID5. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_CID6 = 0x0000004b, // Number of 32B write returns from RMI to RB for CID6. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_CID7 = 0x0000004c, // Number of 32B write returns from RMI to RB for CID7. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_NACK0 = 0x0000004d, // Number of write returns with nack=0. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_NACK1 = 0x0000004e, // Number of write returns with nack=1. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_NACK2 = 0x0000004f, // Number of write returns with nack=2. + RMI_PERF_SEL_RMI_RB_WRRET_VALID_NACK3 = 0x00000050, // Number of write returns with nack=3. + RMI_PERF_SEL_RB_RMI_32BRDREQ_ALL_CID = 0x00000051, // Number of 32B read requests from RB to RMI for all CIDs. + RMI_PERF_SEL_RB_RMI_RDREQ_ALL_CID = 0x00000052, // Number of read requests from RB to RMI for all CIDs. + RMI_PERF_SEL_RB_RMI_RDREQ_TO_RDRET_BUSY = 0x00000053, // Number busy cycles from RDREQ to RDRET. + RMI_PERF_SEL_RB_RMI_32BRDREQ_CID0 = 0x00000054, // Number of 32B read requests from RB to RMI for CID0. + RMI_PERF_SEL_RB_RMI_32BRDREQ_CID1 = 0x00000055, // Number of 32B read requests from RB to RMI for CID1. + RMI_PERF_SEL_RB_RMI_32BRDREQ_CID2 = 0x00000056, // Number of 32B read requests from RB to RMI for CID2. + RMI_PERF_SEL_RB_RMI_32BRDREQ_CID3 = 0x00000057, // Number of 32B read requests from RB to RMI for CID3. + RMI_PERF_SEL_RB_RMI_32BRDREQ_CID4 = 0x00000058, // Number of 32B read requests from RB to RMI for CID4. + RMI_PERF_SEL_RB_RMI_32BRDREQ_CID5 = 0x00000059, // Number of 32B read requests from RB to RMI for CID5. + RMI_PERF_SEL_RB_RMI_32BRDREQ_CID6 = 0x0000005a, // Number of 32B read requests from RB to RMI for CID6. + RMI_PERF_SEL_RB_RMI_32BRDREQ_CID7 = 0x0000005b, // Number of 32B read requests from RB to RMI for CID7. + RMI_PERF_SEL_RB_RMI_RDREQ_CID0 = 0x0000005c, // Number of read requests from RB to RMI for CID0. + RMI_PERF_SEL_RB_RMI_RDREQ_CID1 = 0x0000005d, // Number of read requests from RB to RMI for CID1. + RMI_PERF_SEL_RB_RMI_RDREQ_CID2 = 0x0000005e, // Number of read requests from RB to RMI for CID2. + RMI_PERF_SEL_RB_RMI_RDREQ_CID3 = 0x0000005f, // Number of read requests from RB to RMI for CID3. + RMI_PERF_SEL_RB_RMI_RDREQ_CID4 = 0x00000060, // Number of read requests from RB to RMI for CID4. + RMI_PERF_SEL_RB_RMI_RDREQ_CID5 = 0x00000061, // Number of read requests from RB to RMI for CID5. + RMI_PERF_SEL_RB_RMI_RDREQ_CID6 = 0x00000062, // Number of read requests from RB to RMI for CID6. + RMI_PERF_SEL_RB_RMI_RDREQ_CID7 = 0x00000063, // Number of read requests from RB to RMI for CID7. + RMI_PERF_SEL_RB_RMI_32BRDREQ_INFLIGHT_ALL_ORONE_CID = 0x00000064, // Number of 32B rdreq inflight for all or one CID. CID to be defined by PERF_CID_SEL. + RMI_PERF_SEL_RB_RMI_RDREQ_BURST_LENGTH_ALL_ORONE_CID = 0x00000065, // Number of RDREQ from RB to RMI with burst=1 when length of burst is more than a threshold defined in register. Can be used to calculate average bursts length more than a threshold. CID to be defined by PERF_CID_SEL. + RMI_PERF_SEL_RB_RMI_RDREQ_BURST_ALL_ORONE_CID = 0x00000066, // RDREQ from RB to RMI with burst=1 with the length more than a threshold event. (How is this different from above?) + RMI_PERF_SEL_RB_RMI_RDREQ_RESIDENCY = 0x00000067, // Number of residency checks done on RB to RMI RDREQ interface. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_ALL_CID = 0x00000068, // Number of 32B read returns from RMI to RB for all CIDs. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_CID0 = 0x00000069, // Number of 32B read returns from RMI to RB for CID0. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_CID1 = 0x0000006a, // Number of 32B read returns from RMI to RB for CID1. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_CID2 = 0x0000006b, // Number of 32B read returns from RMI to RB for CID2. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_CID3 = 0x0000006c, // Number of 32B read returns from RMI to RB for CID3. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_CID4 = 0x0000006d, // Number of 32B read returns from RMI to RB for CID4. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_CID5 = 0x0000006e, // Number of 32B read returns from RMI to RB for CID5. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_CID6 = 0x0000006f, // Number of 32B read returns from RMI to RB for CID6. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_CID7 = 0x00000070, // Number of 32B read returns from RMI to RB for CID7. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_NACK0 = 0x00000071, // Number of 32B read returns with nack=0. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_NACK1 = 0x00000072, // Number of 32B read returns with nack=1. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_NACK2 = 0x00000073, // Number of 32B read returns with nack=2. + RMI_PERF_SEL_RMI_RB_32BRDRET_VALID_NACK3 = 0x00000074, // Number of 32B read returns with nack=3. + RMI_PERF_SEL_RB_RMI_WR_FIFO_MAX = 0x00000075, // Number of cycles when RB to RMI write interface fifo is max. + RMI_PERF_SEL_RB_RMI_WR_FIFO_EMPTY = 0x00000076, // Number of cycles when RB to RMI write interface fifo is empty. + RMI_PERF_SEL_RB_RMI_WR_IDLE = 0x00000077, // Number of cycles when RB to RMI write interface fifo is idle. + RMI_PERF_SEL_RB_RMI_WR_STARVE = 0x00000078, // Number of cycles when RB to RMI write interface fifo is starved. + RMI_PERF_SEL_RB_RMI_WR_STALL = 0x00000079, // Number of cycles when RB to RMI write interface fifo is stalled. + RMI_PERF_SEL_RB_RMI_WR_BUSY = 0x0000007a, // Number of cycles when RB to RMI write interface fifo is busy. + RMI_PERF_SEL_RB_RMI_WR_INTF_BUSY = 0x0000007b, // Number of cycles when RB to RMI write interface is busy. + RMI_PERF_SEL_RB_RMI_RD_FIFO_MAX = 0x0000007c, // Number of cycles when RB to RMI read interface fifo is max. + RMI_PERF_SEL_RB_RMI_RD_FIFO_EMPTY = 0x0000007d, // Number of cycles when RB to RMI read interface fifo is empty. + RMI_PERF_SEL_RB_RMI_RD_IDLE = 0x0000007e, // Number of cycles when RB to RMI read interface fifo is idle. + RMI_PERF_SEL_RB_RMI_RD_STARVE = 0x0000007f, // Number of cycles when RB to RMI read interface fifo is starved. + RMI_PERF_SEL_RB_RMI_RD_STALL = 0x00000080, // Number of cycles when RB to RMI read interface fifo is stalled. + RMI_PERF_SEL_RB_RMI_RD_BUSY = 0x00000081, // Number of cycles when RB to RMI read interface fifo is busy. + RMI_PERF_SEL_RB_RMI_RD_INTF_BUSY = 0x00000082, // Number of cycles when RB to RMI read interface is busy. + RMI_PERF_SEL_RMI_TC_64BWRREQ_ALL_ORONE_CID = 0x00000083, // Number of 64B WRREQ from RMI to TC for ALL or ONE CID. CID to be defined by PERF_CID_SEL. + RMI_PERF_SEL_RMI_TC_64BRDREQ_ALL_ORONE_CID = 0x00000084, // Number of 64B RDREQ from RMI to TC for ALL or ONE CID. CID to be defined by PERF_CID_SEL. + RMI_PERF_SEL_RMI_TC_WRREQ_ALL_CID = 0x00000085, // Number of WRREQ from RMI to TC for all CIDs. + RMI_PERF_SEL_RMI_TC_REQ_BUSY = 0x00000086, // Number of busy cycles on an RMI to TC request over a given window. Can be used to calculate bandwidth. + RMI_PERF_SEL_RMI_TC_WRREQ_CID0 = 0x00000087, // Number of WRREQ from RMI to TC for CID0. + RMI_PERF_SEL_RMI_TC_WRREQ_CID1 = 0x00000088, // Number of WRREQ from RMI to TC for CID1. + RMI_PERF_SEL_RMI_TC_WRREQ_CID2 = 0x00000089, // Number of WRREQ from RMI to TC for CID2. + RMI_PERF_SEL_RMI_TC_WRREQ_CID3 = 0x0000008a, // Number of WRREQ from RMI to TC for CID3. + RMI_PERF_SEL_RMI_TC_WRREQ_CID4 = 0x0000008b, // Number of WRREQ from RMI to TC for CID4. + RMI_PERF_SEL_RMI_TC_WRREQ_CID5 = 0x0000008c, // Number of WRREQ from RMI to TC for CID5. + RMI_PERF_SEL_RMI_TC_WRREQ_CID6 = 0x0000008d, // Number of WRREQ from RMI to TC for CID6. + RMI_PERF_SEL_RMI_TC_WRREQ_CID7 = 0x0000008e, // Number of WRREQ from RMI to TC for CID7. + RMI_PERF_SEL_RMI_TC_WRREQ_INFLIGHT_ALL_CID = 0x0000008f, // Number of inflight WRREQs from RMI to TC for all CIDs. Use to calculate average latency. + RMI_PERF_SEL_TC_RMI_WRRET_VALID_ALL_CID = 0x00000090, // Number of valid write returns from TC to RMI over a given window. + RMI_PERF_SEL_RMI_TC_RDREQ_ALL_CID = 0x00000091, // Number of RDREQ from RMI to TC for all CIDs. + RMI_PERF_SEL_RMI_TC_RDREQ_CID0 = 0x00000092, // Number of RDREQ from RMI to TC for CID0. + RMI_PERF_SEL_RMI_TC_RDREQ_CID1 = 0x00000093, // Number of RDREQ from RMI to TC for CID1. + RMI_PERF_SEL_RMI_TC_RDREQ_CID2 = 0x00000094, // Number of RDREQ from RMI to TC for CID2. + RMI_PERF_SEL_RMI_TC_RDREQ_CID3 = 0x00000095, // Number of RDREQ from RMI to TC for CID3. + RMI_PERF_SEL_RMI_TC_RDREQ_CID4 = 0x00000096, // Number of RDREQ from RMI to TC for CID4. + RMI_PERF_SEL_RMI_TC_RDREQ_CID5 = 0x00000097, // Number of RDREQ from RMI to TC for CID5. + RMI_PERF_SEL_RMI_TC_RDREQ_CID6 = 0x00000098, // Number of RDREQ from RMI to TC for CID6. + RMI_PERF_SEL_RMI_TC_RDREQ_CID7 = 0x00000099, // Number of RDREQ from RMI to TC for CID7. + RMI_PERF_SEL_RMI_TC_STALL_RDREQ = 0x0000009a, // Number of cycles RMI to TC RDREQ is stalled. + RMI_PERF_SEL_RMI_TC_STALL_WRREQ = 0x0000009b, // Number of cycles RMI to TC WRREQ is stalled. + RMI_PERF_SEL_RMI_TC_STALL_ALLREQ = 0x0000009c, // Number of cycles RMI to TC a request is stalled. + RMI_PERF_SEL_RMI_TC_CREDIT_FULL_NO_PENDING_SEND = 0x0000009d, // Number of cycles TC is idle. + RMI_PERF_SEL_RMI_TC_CREDIT_ZERO_PENDING_SEND = 0x0000009e, // Number of cycles TC is stalled on all requests. + RMI_PERF_SEL_RMI_TC_RDREQ_INFLIGHT_ALL_CID = 0x0000009f, // Number of inflight RDREQs from RMI to TC for all CIDs. Use to calculate average latency. + RMI_PERF_SEL_TC_RMI_RDRET_VALID_ALL_CID = 0x000000a0, // Number of valid read returns from TC to RMI over a given window. + RMI_PERF_SEL_UTCL1_BUSY = 0x000000a1, // Number of cycles UTCL1 is busy in a certain window. Can be used in calculating bandwidth. + RMI_PERF_SEL_RMI_UTC_REQ = 0x000000a2, // Number of RMI to UTC requests from the Probegen output. Can be used to calculate average latencies. + RMI_PERF_SEL_RMI_UTC_BUSY = 0x000000a3, // Number of cycles UTC is busy in a certain window. Can be used in calculating bandwidth. + RMI_PERF_SEL_UTCL1_UTCL2_REQ = 0x000000a4, // Number of state cycle requests from UTCL1 to UTCL2. 5 state cycles = 1 request + RMI_PERF_SEL_LEVEL_ADD_UTCL1_TO_UTCL2 = 0x000000a5, // UTCL1 to UTCL2 requests level adder (inflight counts). + RMI_PERF_SEL_PROBE_UTCL1_XNACK_RETRY = 0x000000a6, // UTCL1 output XNACK RETRY event. + RMI_PERF_SEL_PROBE_UTCL1_ALL_FAULT = 0x000000a7, // All fault event. XNACK RETRY + XNACK NO_RETRY + PRT_FAULT. (looking at pop output) + RMI_PERF_SEL_PROBE_UTCL1_PRT_FAULT = 0x000000a8, // PRT fault event. (looking at pop output) + RMI_PERF_SEL_PROBE_UTCL1_VMID_BYPASS = 0x000000a9, // VMID BYPASS event. (looking at pop output) + RMI_PERF_SEL_PROBE_UTCL1_XNACK_NORETRY_FAULT = 0x000000aa, // XNACK NO_RETRY fault event. (looking at pop output) + RMI_PERF_SEL_XNACK_FIFO_NUM_USED = 0x000000ab, // Number of used entries in xnack fifo. + RMI_PERF_SEL_LAT_FIFO_NUM_USED = 0x000000ac, // Number of used entries on latency fifo. Also the number of inflight request from RMI (probegen) to UTCL1 which can be used to calculate average latency. + RMI_PERF_SEL_LAT_FIFO_BLOCKING_REQ = 0x000000ad, // Number of latency fifo blocking requests. + RMI_PERF_SEL_LAT_FIFO_NONBLOCKING_REQ = 0x000000ae, // Number of latency fifo non-blocking requests. + RMI_PERF_SEL_XNACK_FIFO_FULL = 0x000000af, // Number of XNACK fifo full event. + RMI_PERF_SEL_XNACK_FIFO_BUSY = 0x000000b0, // Number of cycles XNACKxnack fifo is busy. + RMI_PERF_SEL_LAT_FIFO_FULL = 0x000000b1, // Number of latency fifo full event. + RMI_PERF_SEL_SKID_FIFO_DEPTH = 0x000000b2, // SKID FIFO DEPTH event. Can be used to get average and max fifo depth count. + RMI_PERF_SEL_TCIW_INFLIGHT_COUNT = 0x000000b3, // Number of inflight entries to TCIW. Can be used to get average and max inflights to TCIW. + RMI_PERF_SEL_PRT_FIFO_NUM_USED = 0x000000b4, // Number of used entries in PRT FIFO. Can be used to get average, max PRTs as well as PRT FIFO average latencies. + RMI_PERF_SEL_PRT_FIFO_REQ = 0x000000b5, // Number of request events to PRT fifo. + RMI_PERF_SEL_PRT_FIFO_BUSY = 0x000000b6, // Number of PRT FIFO busy cycles in a given window. + RMI_PERF_SEL_TCIW_REQ = 0x000000b7, // Number of TCIW request event. + RMI_PERF_SEL_TCIW_BUSY = 0x000000b8, // Number of TCIW busy cycles in a given window. + RMI_PERF_SEL_SKID_FIFO_REQ = 0x000000b9, // Number of SKID-FIFO request event. + RMI_PERF_SEL_SKID_FIFO_BUSY = 0x000000ba, // Number of SKID-FIFO busy cycles in a given window. + RMI_PERF_SEL_DEMUX_TCIW_RESIDENCY_NACK0 = 0x000000bb, // DEMUX to TCIW residency(mask=0, rd+wr) check with NACK=0. (VMID from reg., internal precoding on VMID) + RMI_PERF_SEL_DEMUX_TCIW_RESIDENCY_NACK1 = 0x000000bc, // DEMUX to TCIW residency(mask=0, rd+wr) check with NACK=1. (VMID from reg., internal precoding on VMID) + RMI_PERF_SEL_DEMUX_TCIW_RESIDENCY_NACK2 = 0x000000bd, // DEMUX to TCIW residency(mask=0, rd+wr) check with NACK=2. (VMID from reg., internal precoding on VMID) + RMI_PERF_SEL_DEMUX_TCIW_RESIDENCY_NACK3 = 0x000000be, // DEMUX to TCIW residency(mask=0, rd+wr) check with NACK=3. (VMID from reg., internal precoding on VMID) + RMI_PERF_SEL_XBAR_PROBEGEN_RTS_RTR = 0x000000bf, // Blocking/Non-blocking event from XBAR to Probegen. + RMI_PERF_SEL_XBAR_PROBEGEN_RTSB_RTR = 0x000000c0, // Blocking/Non-blocking event from XBAR to Probegen. + RMI_PERF_SEL_XBAR_PROBEGEN_RTS_RTRB = 0x000000c1, // Blocking/Non-blocking event from XBAR to Probegen. + RMI_PERF_SEL_XBAR_PROBEGEN_RTSB_RTRB = 0x000000c2, // Blocking/Non-blocking event from XBAR to Probegen. + RMI_PERF_SEL_DEMUX_TCIW_FORMATTER_RTS_RTR = 0x000000c3, // Blocking/Non-blocking event from DEMUX to TCIW formatter. + RMI_PERF_SEL_DEMUX_TCIW_FORMATTER_RTSB_RTR = 0x000000c4, // Blocking/Non-blocking event from DEMUX to TCIW formatter. + RMI_PERF_SEL_DEMUX_TCIW_FORMATTER_RTS_RTRB = 0x000000c5, // Blocking/Non-blocking event from DEMUX to TCIW formatter. + RMI_PERF_SEL_DEMUX_TCIW_FORMATTER_RTSB_RTRB = 0x000000c6, // Blocking/Non-blocking event from DEMUX to TCIW formatter. + RMI_PERF_SEL_WRREQCONSUMER_XBAR_WRREQ_RTS_RTR = 0x000000c7, // Blocking/Non-blocking event from WRREQ Consumer to XBAR. + RMI_PERF_SEL_WRREQCONSUMER_XBAR_WRREQ_RTSB_RTR = 0x000000c8, // Blocking/Non-blocking event from WRREQ Consumer to XBAR. + RMI_PERF_SEL_WRREQCONSUMER_XBAR_WRREQ_RTS_RTRB = 0x000000c9, // Blocking/Non-blocking event from WRREQ Consumer to XBAR. + RMI_PERF_SEL_WRREQCONSUMER_XBAR_WRREQ_RTSB_RTRB = 0x000000ca, // Blocking/Non-blocking event from WRREQ Consumer to XBAR. + RMI_PERF_SEL_RDREQCONSUMER_XBAR_RDREQ_RTS_RTR = 0x000000cb, // Blocking/Non-blocking event from RDREQ Consumer to XBAR. + RMI_PERF_SEL_RDREQCONSUMER_XBAR_RDREQ_RTSB_RTR = 0x000000cc, // Blocking/Non-blocking event from RDREQ Consumer to XBAR. + RMI_PERF_SEL_RDREQCONSUMER_XBAR_RDREQ_RTS_RTRB = 0x000000cd, // Blocking/Non-blocking event from RDREQ Consumer to XBAR. + RMI_PERF_SEL_RDREQCONSUMER_XBAR_RDREQ_RTSB_RTRB = 0x000000ce, // Blocking/Non-blocking event from RDREQ Consumer to XBAR. + RMI_PERF_SEL_POP_DEMUX_RTS_RTR = 0x000000cf, // Blocking/Non-blocking event from POP to DEMUX. + RMI_PERF_SEL_POP_DEMUX_RTSB_RTR = 0x000000d0, // Blocking/Non-blocking event from POP to DEMUX. + RMI_PERF_SEL_POP_DEMUX_RTS_RTRB = 0x000000d1, // Blocking/Non-blocking event from POP to DEMUX. + RMI_PERF_SEL_POP_DEMUX_RTSB_RTRB = 0x000000d2, // Blocking/Non-blocking event from POP to DEMUX. + RMI_PERF_SEL_PROBEGEN_UTC_RTS_RTR = 0x000000d3, // Blocking/Non-blocking event from Probegen to UTC. + RMI_PERF_SEL_LEVEL_ADD_RMI_TO_UTC = 0x000000d4, // Level add (Number of inflights) count from RMI to UTC. + RMI_PERF_SEL_PROBEGEN_UTC_RTSB_RTR = 0x000000d5, // Blocking/Non-blocking event from Probegen to UTC. + RMI_PERF_SEL_PROBEGEN_UTC_RTS_RTRB = 0x000000d6, // Blocking/Non-blocking event from Probegen to UTC. + RMI_PERF_SEL_PROBEGEN_UTC_RTSB_RTRB = 0x000000d7, // Blocking/Non-blocking event from Probegen to UTC. + RMI_PERF_SEL_UTC_POP_RTS_RTR = 0x000000d8, // Blocking/Non-blocking event from UTC to POP. + RMI_PERF_SEL_UTC_POP_RTSB_RTR = 0x000000d9, // Blocking/Non-blocking event from UTC to POP. + RMI_PERF_SEL_UTC_POP_RTS_RTRB = 0x000000da, // Blocking/Non-blocking event from UTC to POP. + RMI_PERF_SEL_UTC_POP_RTSB_RTRB = 0x000000db, // Blocking/Non-blocking event from UTC to POP. + RMI_PERF_SEL_POP_XNACK_RTS_RTR = 0x000000dc, // Blocking/Non-blocking event from POP to XNACK. + RMI_PERF_SEL_POP_XNACK_RTSB_RTR = 0x000000dd, // Blocking/Non-blocking event from POP to XNACK. + RMI_PERF_SEL_POP_XNACK_RTS_RTRB = 0x000000de, // Blocking/Non-blocking event from POP to XNACK. + RMI_PERF_SEL_POP_XNACK_RTSB_RTRB = 0x000000df, // Blocking/Non-blocking event from POP to XNACK. + RMI_PERF_SEL_XNACK_PROBEGEN_RTS_RTR = 0x000000e0, // Blocking/Non-blocking event from XNACK to Probegen. + RMI_PERF_SEL_XNACK_PROBEGEN_RTSB_RTR = 0x000000e1, // Blocking/Non-blocking event from XNACK to Probegen. + RMI_PERF_SEL_XNACK_PROBEGEN_RTS_RTRB = 0x000000e2, // Blocking/Non-blocking event from XNACK to Probegen. + RMI_PERF_SEL_XNACK_PROBEGEN_RTSB_RTRB = 0x000000e3, // Blocking/Non-blocking event from XNACK to Probegen. + RMI_PERF_SEL_PRTFIFO_RTNFORMATTER_RTS_RTR = 0x000000e4, // Blocking/Non-blocking event from PRT FIFO to RTN Formatter. + RMI_PERF_SEL_PRTFIFO_RTNFORMATTER_RTSB_RTR = 0x000000e5, // Blocking/Non-blocking event from PRT FIFO to RTN Formatter. + RMI_PERF_SEL_PRTFIFO_RTNFORMATTER_RTS_RTRB = 0x000000e6, // Blocking/Non-blocking event from PRT FIFO to RTN Formatter. + RMI_PERF_SEL_PRTFIFO_RTNFORMATTER_RTSB_RTRB = 0x000000e7, // Blocking/Non-blocking event from PRT FIFO to RTN Formatter. + RMI_PERF_SEL_SKID_FIFO_IN_RTS = 0x000000e8, // Blocking/Non-blocking event TO Skid FIFO. + RMI_PERF_SEL_SKID_FIFO_IN_RTSB = 0x000000e9, // Blocking/Non-blocking event TO Skid FIFO. + RMI_PERF_SEL_SKID_FIFO_OUT_RTS = 0x000000ea, // Blocking/Non-blocking event FROM Skid FIFO. + RMI_PERF_SEL_SKID_FIFO_OUT_RTSB = 0x000000eb, // Blocking/Non-blocking event FROM Skid FIFO. + RMI_PERF_SEL_XBAR_PROBEGEN_READ_RTS_RTR = 0x000000ec, // Read transaction from XBAR to Probegen event. + RMI_PERF_SEL_XBAR_PROBEGEN_WRITE_RTS_RTR = 0x000000ed, // Write transaction from XBAR to Probegen event. + RMI_PERF_SEL_XBAR_PROBEGEN_IN0_RTS_RTR = 0x000000ee, // Transaction event between XBAR and Probegen from IN0. + RMI_PERF_SEL_XBAR_PROBEGEN_IN1_RTS_RTR = 0x000000ef, // Transaction event between XBAR and Probegen from IN1. + RMI_PERF_SEL_XBAR_PROBEGEN_CB_RTS_RTR = 0x000000f0, // Transaction event between XBAR and Probegen from CB. + RMI_PERF_SEL_XBAR_PROBEGEN_DB_RTS_RTR = 0x000000f1, // Transaction event between XBAR and Probegen from DB. + RMI_PERF_SEL_REORDER_FIFO_REQ = 0x000000f2, // Number of request event to reorder fifo. + RMI_PERF_SEL_REORDER_FIFO_BUSY = 0x000000f3, // Number of busy cycles on the reorder fifo in a given window. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_ALL_CID = 0x000000f4, // Number of early wracks for all CIDs. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_CID0 = 0x000000f5, // Number of early wracks for CID0. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_CID1 = 0x000000f6, // Number of early wracks for CID1. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_CID2 = 0x000000f7, // Number of early wracks for CID2. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_CID3 = 0x000000f8, // Number of early wracks for CID3. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_CID4 = 0x000000f9, // Number of early wracks for CID4. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_CID5 = 0x000000fa, // Number of early wracks for CID5. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_CID6 = 0x000000fb, // Number of early wracks for CID6. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_CID7 = 0x000000fc, // Number of early wracks for CID7. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_NACK0 = 0x000000fd, // Number of early wracks with NACK=0. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_NACK1 = 0x000000fe, // Number of early wracks with NACK=1. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_NACK2 = 0x000000ff, // Number of early wracks with NACK=2. + RMI_PERF_SEL_RMI_RB_EARLY_WRACK_NACK3 = 0x00000100, // Number of early wracks with NACK=3. + RMI_PERF_SEL_UTCL0_UTCL1_PERM_FAULT = 0x00000101, // utcl0-utcl1 permissoin fault +} RMI_PERFCOUNTER_SELECT; + +typedef enum SC_PERFCOUNTER_SELECT : unsigned int { + SC_SRPS_WINDOW_VALID = 0x00000000, // SC_PERF_SEL_SC_SRPS_WINDOW_VALID Counts PERFCOUNTER_START to PERFCOUNTER_STOP stop perfcounter enable window for specific points in the SC pipeline. Number of clocks event-window is valid ; Where measured: at stage register/primitive setup bottom (below pbb if present at push into sc_ps_eng); increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1, Data valid for INSTANCE_INDEX=0 only + SC_PSSW_WINDOW_VALID = 0x00000001, // SC_PERF_SEL_SC_PSSW_WINDOW_VALID Number of clocks event-window is valid at primitive setup/supertile walker ; Where measured: input to course walker; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1, Data valid for INSTANCE_INDEX=0 only + SC_TPQZ_WINDOW_VALID = 0x00000002, // SC_PERF_SEL_SC_TPQZ_WINDOW_VALID Number of clocks event-window is valid at tile picker/quad-z ; Where measured: Tile picker to quadmask-z interface; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1. + SC_QZQP_WINDOW_VALID = 0x00000003, // SC_PERF_SEL_SC_QZQP_WINDOW_VALID Number of clocks event-window is valid at quad-z/quad processor with SC busy ; Where measured: quadmask_z to quad processor interface. ; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1. + SC_TRPK_WINDOW_VALID = 0x00000004, // SC_PERF_SEL_SC_TRPK_WINDOW_VALID Number of clocks event-window is valid at tile reorder/packer ; Where measured: tile reorder (quad accum if only on3 DB per packer) to packer interface. ; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1. + SC_SRPS_WINDOW_VALID_BUSY = 0x00000005, // SC_PERF_SEL_SC_SRPS_WINDOW_VALID_BUSY Number of clocks event-window is valid at stage register/primitive setup with SC busy Where measured: at stage register/primitive setup bottom (below pbb if present at push into sc_ps_eng); increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1, Data valid for INSTANCE_INDEX=0 only + SC_PSSW_WINDOW_VALID_BUSY = 0x00000006, // SC_PERF_SEL_SC_PSSW_WINDOW_VALID_BUSY Number of clocks event-window is valid at primitive setup/supertile walker with SC busy ; Where measured: input to course walker; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1, Data valid for INSTANCE_INDEX=0 only + SC_TPQZ_WINDOW_VALID_BUSY = 0x00000007, // SC_PERF_SEL_SC_TPQZ_WINDOW_VALID_BUSY Number of clocks event-window is valid at tile picker/quad-z with SC busy ; Where measured: Tile picker to quadmask-z interface; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 only (window starts/stops when event PERFCOUNTER_START/PERFCOUNTER_STOP arrives in least significant db). + SC_QZQP_WINDOW_VALID_BUSY = 0x00000008, // SC_PERF_SEL_SC_QZQP_WINDOW_VALID_BUSY Number of clocks event-window is valid at quad-z/quad processor with SC busy ; Where measured: Tile picker to quadmask-z interface; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 only (window starts/stops when event PERFCOUNTER_START/PERFCOUNTER_STOP arrives in least significant db). + SC_TRPK_WINDOW_VALID_BUSY = 0x00000009, // SC_PERF_SEL_SC_TRPK_WINDOW_VALID_BUSY Number of clocks event-window is valid at tile reorder/packer with SC busy ; Where measured: tile reorder (sc_quadaccum if 1DB per packer) to packer interface ; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 only (window starts/stops when event PERFCOUNTER_START/PERFCOUNTER_STOP arrives in least significant db). + SC_STARVED_BY_PA = 0x0000000a, // RESERVED (see PH replacement PH_SC*_ARB_STARVED_FROM_ABOVE) SC_STARVED_BY_PA sc starved by pa, no valid data on prim_setup selected pa_sc fifo in SC_SRPS_WINDOW_VALID_BUSY and no backpressure from below prim setup top (pa_sc arbitration); Where measured: prim_setup top pa_sc arbitration or equivalent ; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1, Data valid for INSTANCE_INDEX=0 only + SC_STALLED_BY_PRIMFIFO = 0x0000000b, // SC_PERF_SEL_SC_STALLED_BY_PRIMFIFO SC course walker stalled by frontend primitive fifo full ; Where measured: SC Course walker output; increment rate-one per clock ; range-1/clk; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1, Data valid for INSTANCE_INDEX=0 only + SC_STALLED_BY_DB_TILE = 0x0000000c, // SC_PERF_SEL_SC_STALLED_BY_DB_TILE sc stalled by db tile. Tile picker(s) contain tiles to send in db_pipe(s) but is stalled by SC_DB_tile interface credits (Non-harvestable) ; Where measured: Tile picker to quadmask_z interface ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1 ; SC_DB_TILE efficiency = 1- (SC_STALLED_BY_DB_TILE/SC_TPQZ_WINDOW_VALID_BUSY) + SC_STARVED_BY_DB_TILE = 0x0000000d, // SC_PERF_SEL_SC_STARVED_BY_DB_TILE sc starved by db tile. SC is waiting for tiles back from the db. This will always be the case for the first few transactions (repeater delays + db transaction latency). (Non-harvestable) ; Where measured: SC internal tile fifo(s) not empty. ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1 + SC_STALLED_BY_TILEORDERFIFO = 0x0000000e, // SC_PERF_SEL_SC_STALLED_BY_TILEORDERFIFO sc stalled by tile order fifo. Only applicable to variants with 2 RB's per packer. ; Where measured: Between order picker and order cull logic ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; These stalls can be the result of a single DB pipe backing up the order cull fifo. Exceptions woul be if this logic is being backed up by the cooresponding packer interface (i.e stalled by bci or by spi) + SC_STALLED_BY_TILEFIFO = 0x0000000f, // SC_PERF_SEL_SC_STALLED_BY_TILEFIFO sc stalled by quadmask_z a tile fifo going full (logic or of DB0 and DB1 pipe condition if two dbs per packer). (Non harvestable). ; Where measured: sc_qdmsk_z(s) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_STALLED_BY_DB_QUAD = 0x00000010, // SC_PERF_SEL_SC_STALLED_BY_DB_QUAD sc stalled by SC to DB quad processor interface fifo full (credits PA_SC_IF_FIFO_SIZE_SC_DB_QUAD_IF_FIFO_SIZE). (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; SC_DB_QUAD efficiency = 1 -(SC_STALLED_BY_DB_QUAD/SC_QZQP_WINDOW_VALID_BUSY) + SC_STARVED_BY_DB_QUAD = 0x00000011, // SC_PERF_SEL_SC_STARVED_BY_DB_QUAD sc starved by db quad tilaccum (quadaccum if 1RB/packer) has quad entries, but no quads are being received back from the DB (Non harvestable); Where measured: sc_tileaccum ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_STALLED_BY_QUADFIFO = 0x00000012, // SC_PERF_SEL_SC_STALLED_BY_QUADFIFO sc stalled by quad fifo(s) full. (non Harvestable). ; Where measured: sc_quad_proc to sc_tileaccum (quadproc if 1RB/packer) interface ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; Depth adjustable by PA_SC_FIFO_SIZE_SC_EARLYZ_TILE_FIFO_SIZE + SC_STALLED_BY_BCI = 0x00000013, // SC_PERF_SEL_SC_STALLED_BY_BCI sc stalled by bci packer due to lack of free interface credits ; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; Efficiency = 1 -(SC_STALLED_BY_BCI /SC_TRPK_WINDOW_VALID_BUSY) ; Default Depth of 6 can be modified by PA_SC_IF_FIFO_SIZE_SC_BCI_IF_FIFO_SIZE + SC_STALLED_BY_SPI = 0x00000014, // SC_PERF_SEL_SC_STALLED_BY_SPI sc stalled by spi due to lack of free interface credits ; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1 ; Efficiency = 1 -(SC_STALLED_BY_SPI /SC_TRPK_WINDOW_VALID_BUSY) ; Default Depth of 6 can be modified by PA_SC_IF_FIFO_SIZE_SC_SPI_IF_FIFO_SIZE ; + SC_SCISSOR_DISCARD = 0x00000015, // SC_PERF_SEL_SC_SCISSOR_DISCARD primitive completely discarded by scissor ; Where measured: sc primative setup engine output (sc_ps_eng) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, results valid for sc frontend (INSTANCE_INDEX=0) only; + SC_BB_DISCARD = 0x00000016, // SC_PERF_SEL_SC_BB_DISCARD primitive discarded by bounding-box check, no pixels hit ; Where measured: sc primitive setup engine output (sc_ps_eng) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, results valid for sc frontend (INSTANCE_INDEX=0) only; + SC_SUPERTILE_COUNT = 0x00000017, // SC_PERF_SEL_SC_SUPERTILE_COUNT supertile (32x32 pixels) count ; Where measured: sc course walker output to backend mapper (sc_prim_walk) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, results valid for sc frontend (INSTANCE_INDEX=0) only; + SC_SUPERTILE_PER_PRIM_H0 = 0x00000018, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H0 prims with < 2 supertiles ; Applicable comments to all SC_SUPERTILE_PER_PRIM_H* histogram counters: Where measured: sc course walker output to backend mapper (sc_prim_walk) ; increment rate 1 per clock ; range-1/clk. SC_SUPERTILE_PER_PRIM_H* histogram counter bins limited to 20 bit binary count, regarless of selected perfcounter range; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, results valid for sc frontend (INSTANCE_INDEX=0) only; + SC_SUPERTILE_PER_PRIM_H1 = 0x00000019, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H1 prims with < 4 supertiles + SC_SUPERTILE_PER_PRIM_H2 = 0x0000001a, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H2 prims with < 8 supertiles + SC_SUPERTILE_PER_PRIM_H3 = 0x0000001b, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H3 prims with < 16 supertiles + SC_SUPERTILE_PER_PRIM_H4 = 0x0000001c, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H4 prims with < 32 supertiles + SC_SUPERTILE_PER_PRIM_H5 = 0x0000001d, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H5 prims with < 64 supertiles + SC_SUPERTILE_PER_PRIM_H6 = 0x0000001e, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H6 prims with < 128 supertiles + SC_SUPERTILE_PER_PRIM_H7 = 0x0000001f, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H7 prims with < 256 supertiles + SC_SUPERTILE_PER_PRIM_H8 = 0x00000020, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H8 prims with < 512 supertiles + SC_SUPERTILE_PER_PRIM_H9 = 0x00000021, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H9 prims with < 1K supertiles + SC_SUPERTILE_PER_PRIM_H10 = 0x00000022, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H10 prims with < 2K supertiles + SC_SUPERTILE_PER_PRIM_H11 = 0x00000023, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H11 prims with < 4K supertiles + SC_SUPERTILE_PER_PRIM_H12 = 0x00000024, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H12 prims with < 8K supertiles + SC_SUPERTILE_PER_PRIM_H13 = 0x00000025, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H13 prims with < 16K supertiles + SC_SUPERTILE_PER_PRIM_H14 = 0x00000026, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H14 prims with < 32K supertiles + SC_SUPERTILE_PER_PRIM_H15 = 0x00000027, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H15 prims with < 64K supertiles + SC_SUPERTILE_PER_PRIM_H16 = 0x00000028, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_H16 prims with < 1M supertiles + SC_TILE_PER_PRIM_H0 = 0x00000029, // SC_PERF_SEL_SC_TILE_PER_PRIM_H0 prims with < 2 tiles + SC_TILE_PER_PRIM_H1 = 0x0000002a, // SC_PERF_SEL_SC_TILE_PER_PRIM_H1 prims with < 4 tiles + SC_TILE_PER_PRIM_H2 = 0x0000002b, // SC_PERF_SEL_SC_TILE_PER_PRIM_H2 prims with < 8 tiles + SC_TILE_PER_PRIM_H3 = 0x0000002c, // SC_PERF_SEL_SC_TILE_PER_PRIM_H3 prims with < 16 tiles + SC_TILE_PER_PRIM_H4 = 0x0000002d, // SC_PERF_SEL_SC_TILE_PER_PRIM_H4 prims with < 32 tiles + SC_TILE_PER_PRIM_H5 = 0x0000002e, // SC_PERF_SEL_SC_TILE_PER_PRIM_H5 prims with < 64 tiles + SC_TILE_PER_PRIM_H6 = 0x0000002f, // SC_PERF_SEL_SC_TILE_PER_PRIM_H6 prims with < 128 tiles + SC_TILE_PER_PRIM_H7 = 0x00000030, // SC_PERF_SEL_SC_TILE_PER_PRIM_H7 prims with < 256 tiles + SC_TILE_PER_PRIM_H8 = 0x00000031, // SC_PERF_SEL_SC_TILE_PER_PRIM_H8 prims with < 512 tiles + SC_TILE_PER_PRIM_H9 = 0x00000032, // SC_PERF_SEL_SC_TILE_PER_PRIM_H9 prims with < 1K tiles + SC_TILE_PER_PRIM_H10 = 0x00000033, // SC_PERF_SEL_SC_TILE_PER_PRIM_H10 prims with < 2K tiles + SC_TILE_PER_PRIM_H11 = 0x00000034, // SC_PERF_SEL_SC_TILE_PER_PRIM_H11 prims with < 4K tiles + SC_TILE_PER_PRIM_H12 = 0x00000035, // SC_PERF_SEL_SC_TILE_PER_PRIM_H12 prims with < 8K tiles + SC_TILE_PER_PRIM_H13 = 0x00000036, // SC_PERF_SEL_SC_TILE_PER_PRIM_H13 prims with < 16K tiles + SC_TILE_PER_PRIM_H14 = 0x00000037, // SC_PERF_SEL_SC_TILE_PER_PRIM_H14 prims with < 32K tiles + SC_TILE_PER_PRIM_H15 = 0x00000038, // SC_PERF_SEL_SC_TILE_PER_PRIM_H15 prims with < 64K tiles + SC_TILE_PER_PRIM_H16 = 0x00000039, // SC_PERF_SEL_SC_TILE_PER_PRIM_H16 prims with < 1M tiles + SC_TILE_PER_SUPERTILE_H0 = 0x0000003a, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H0 supertiles walked with 0 tiles hit + SC_TILE_PER_SUPERTILE_H1 = 0x0000003b, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H1 supertiles walked with 1 tiles hit + SC_TILE_PER_SUPERTILE_H2 = 0x0000003c, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H2 supertiles walked with 2 tiles hit + SC_TILE_PER_SUPERTILE_H3 = 0x0000003d, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H3 supertiles walked with 3 tiles hit + SC_TILE_PER_SUPERTILE_H4 = 0x0000003e, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H4 supertiles walked with 4 tiles hit + SC_TILE_PER_SUPERTILE_H5 = 0x0000003f, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H5 supertiles walked with 5 tiles hit + SC_TILE_PER_SUPERTILE_H6 = 0x00000040, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H6 supertiles walked with 6 tiles hit + SC_TILE_PER_SUPERTILE_H7 = 0x00000041, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H7 supertiles walked with 7 tiles hit + SC_TILE_PER_SUPERTILE_H8 = 0x00000042, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H8 supertiles walked with 8 tiles hit + SC_TILE_PER_SUPERTILE_H9 = 0x00000043, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H9 supertiles walked with 9 tiles hit + SC_TILE_PER_SUPERTILE_H10 = 0x00000044, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H10 supertiles walked with 10 tiles hit + SC_TILE_PER_SUPERTILE_H11 = 0x00000045, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H11 supertiles walked with 11 tiles hit + SC_TILE_PER_SUPERTILE_H12 = 0x00000046, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H12 supertiles walked with 12 tiles hit + SC_TILE_PER_SUPERTILE_H13 = 0x00000047, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H13 supertiles walked with 13 tiles hit + SC_TILE_PER_SUPERTILE_H14 = 0x00000048, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H14 supertiles walked with 14 tiles hit + SC_TILE_PER_SUPERTILE_H15 = 0x00000049, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H15 supertiles walked with 15 tiles hit + SC_TILE_PER_SUPERTILE_H16 = 0x0000004a, // SC_PERF_SEL_SC_TILE_PER_SUPERTILE_H16 supertiles walked with 16 tiles hit + SC_TILE_PICKED_H1 = 0x0000004b, // SC_PERF_SEL_SC_TILE_PICKED_H1 number of times 1 tile picked out of 0 to num_rb_per_packer-1 ; Where measured: sc tile picker output to quadmaskz logic in db pipe ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1; + SC_TILE_PICKED_H2 = 0x0000004c, // SC_PERF_SEL_SC_TILE_PICKED_H2 number of times 2 tiles picked out of 0 to num_rb_per_packer-1 ; Where measured: sc tile picker output to quadmaskz logic in db pipe ; increment rate num_rb_per_se = 2 per clock else 1 per clock; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1; + SC_TILE_PICKED_H3 = 0x0000004d, // SC_PERF_SEL_SC_TILE_PICKED_H3 number of times 3 tile picked DEPRECATED (NUM_DB_PER_PACKER=4) + SC_TILE_PICKED_H4 = 0x0000004e, // SC_PERF_SEL_SC_TILE_PICKED_H4 number of times 4 tiles picked DEPRECATED (NUM_DB_PER_PACKER=4) + SC_QZ0_TILE_COUNT = 0x0000004f, // SC_PERF_SEL_SC_QZ0_TILE_COUNT non event tile count quad-z pipe 0 ; Where measured: sc quadmaskz to quad processor (sc_quad_proc) in db pipe 0; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1; + SC_QZ1_TILE_COUNT = 0x00000050, // SC_PERF_SEL_SC_QZ1_TILE_COUNT non event tile count quad-z pipe 1 ; Where measured: sc quadmaskz to quad processor (sc_quad_proc) in db pipe 1; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0, valid only if 2 DB per packer; + SC_QZ2_TILE_COUNT = 0x00000051, // SC_PERF_SEL_SC_QZ2_TILE_COUNT tile count; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_TILE_COUNT = 0x00000052, // SC_PERF_SEL_SC_QZ3_TILE_COUNT tile count; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ0_TILE_COVERED_COUNT = 0x00000053, // SC_PERF_SEL_SC_QZ0_TILE_COVERED_COUNT tile covered count; quad-z pipe 0 ; Where measured: sc quadmaskz to quad processor (sc_quad_proc) in db pipe 0; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1; + SC_QZ1_TILE_COVERED_COUNT = 0x00000054, // SC_PERF_SEL_SC_QZ1_TILE_COVERED_COUNT tile covered count; quad-z pipe 1 ; Where measured: sc quadmaskz to quad processor (sc_quad_proc) in db pipe 1; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0, valid only if 2 DB per packer; + SC_QZ2_TILE_COVERED_COUNT = 0x00000055, // SC_PERF_SEL_SC_QZ2_TILE_COVERED_COUNT tile covered count; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_TILE_COVERED_COUNT = 0x00000056, // SC_PERF_SEL_SC_QZ3_TILE_COVERED_COUNT tile covered count; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ0_TILE_NOT_COVERED_COUNT = 0x00000057, // SC_PERF_SEL_SC_QZ0_TILE_NOT_COVERED_COUNT tile not covered count; quad-z pipe 0 ; Where measured: sc quadmaskz to quad processor (sc_quad_proc) in db pipe 0; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1; + SC_QZ1_TILE_NOT_COVERED_COUNT = 0x00000058, // SC_PERF_SEL_SC_QZ1_TILE_NOT_COVERED_COUNT tile not covered count; quad-z pipe 1 ; Where measured: sc quadmaskz to quad processor (sc_quad_proc) in db pipe 1; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0, valid only if 2 DB per packer; + SC_QZ2_TILE_NOT_COVERED_COUNT = 0x00000059, // SC_PERF_SEL_SC_QZ2_TILE_NOT_COVERED_COUNT tile not covered count; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_TILE_NOT_COVERED_COUNT = 0x0000005a, // SC_PERF_SEL_SC_QZ3_TILE_NOT_COVERED_COUNT tile not covered count; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ0_QUAD_PER_TILE_H0 = 0x0000005b, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H0 tiles walked with 0 quads hit; quad-z pipe 0 Where measured: sc quadmaskz to quad processor (sc_quad_proc) in db pipe 0; increment rate-one per clock ; range-1/clk SC_QZ0_QUAD_PER_TILE_H* histogram counter bins limited to 20 bit binary count, regarless of selected perfcounter range ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1; + SC_QZ0_QUAD_PER_TILE_H1 = 0x0000005c, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H1 tiles walked with 1 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H2 = 0x0000005d, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H2 tiles walked with 2 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H3 = 0x0000005e, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H3 tiles walked with 3 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H4 = 0x0000005f, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H4 tiles walked with 4 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H5 = 0x00000060, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H5 tiles walked with 5 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H6 = 0x00000061, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H6 tiles walked with 6 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H7 = 0x00000062, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H7 tiles walked with 7 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H8 = 0x00000063, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H8 tiles walked with 8 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H9 = 0x00000064, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H9 tiles walked with 9 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H10 = 0x00000065, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H10 tiles walked with 10 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H11 = 0x00000066, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H11 tiles walked with 11 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H12 = 0x00000067, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H12 tiles walked with 12 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H13 = 0x00000068, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H13 tiles walked with 13 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H14 = 0x00000069, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H14 tiles walked with 14 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H15 = 0x0000006a, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H15 tiles walked with 15 quads hit; quad-z pipe 0 + SC_QZ0_QUAD_PER_TILE_H16 = 0x0000006b, // SC_PERF_SEL_SC_QZ0_QUAD_PER_TILE_H16 tiles walked with 16 quads hit; quad-z pipe 0 + SC_QZ1_QUAD_PER_TILE_H0 = 0x0000006c, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H0 tiles walked with 0 quads hit; quad-z pipe 1 Where measured: sc quadmaskz to quad processor (sc_quad_proc) in db pipe 1; increment rate-one per clock ; range-1/clk SC_QZ1_QUAD_PER_TILE_H* histogram counter bins limited to 20 bit binary count, regarless of selected perfcounter range ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 ; + SC_QZ1_QUAD_PER_TILE_H1 = 0x0000006d, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H1 tiles walked with 1 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H2 = 0x0000006e, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H2 tiles walked with 2 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H3 = 0x0000006f, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H3 tiles walked with 3 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H4 = 0x00000070, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H4 tiles walked with 4 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H5 = 0x00000071, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H5 tiles walked with 5 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H6 = 0x00000072, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H6 tiles walked with 6 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H7 = 0x00000073, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H7 tiles walked with 7 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H8 = 0x00000074, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H8 tiles walked with 8 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H9 = 0x00000075, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H9 tiles walked with 9 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H10 = 0x00000076, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H10 tiles walked with 10 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H11 = 0x00000077, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H11 tiles walked with 11 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H12 = 0x00000078, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H12 tiles walked with 12 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H13 = 0x00000079, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H13 tiles walked with 13 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H14 = 0x0000007a, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H14 tiles walked with 14 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H15 = 0x0000007b, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H15 tiles walked with 15 quads hit; quad-z pipe 1 + SC_QZ1_QUAD_PER_TILE_H16 = 0x0000007c, // SC_PERF_SEL_SC_QZ1_QUAD_PER_TILE_H16 tiles walked with 16 quads hit; quad-z pipe 1 + SC_QZ2_QUAD_PER_TILE_H0 = 0x0000007d, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H0 tiles walked with 0 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H1 = 0x0000007e, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H1 tiles walked with 1 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H2 = 0x0000007f, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H2 tiles walked with 2 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H3 = 0x00000080, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H3 tiles walked with 3 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H4 = 0x00000081, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H4 tiles walked with 4 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H5 = 0x00000082, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H5 tiles walked with 5 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H6 = 0x00000083, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H6 tiles walked with 6 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H7 = 0x00000084, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H7 tiles walked with 7 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H8 = 0x00000085, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H8 tiles walked with 8 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H9 = 0x00000086, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H9 tiles walked with 9 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H10 = 0x00000087, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H10 tiles walked with 10 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H11 = 0x00000088, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H11 tiles walked with 11 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H12 = 0x00000089, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H12 tiles walked with 12 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H13 = 0x0000008a, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H13 tiles walked with 13 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H14 = 0x0000008b, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H14 tiles walked with 14 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H15 = 0x0000008c, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H15 tiles walked with 15 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ2_QUAD_PER_TILE_H16 = 0x0000008d, // SC_PERF_SEL_SC_QZ2_QUAD_PER_TILE_H16 tiles walked with 16 quads hit; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H0 = 0x0000008e, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H0 tiles walked with 0 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H1 = 0x0000008f, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H1 tiles walked with 1 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H2 = 0x00000090, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H2 tiles walked with 2 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H3 = 0x00000091, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H3 tiles walked with 3 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H4 = 0x00000092, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H4 tiles walked with 4 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H5 = 0x00000093, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H5 tiles walked with 5 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H6 = 0x00000094, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H6 tiles walked with 6 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H7 = 0x00000095, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H7 tiles walked with 7 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H8 = 0x00000096, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H8 tiles walked with 8 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H9 = 0x00000097, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H9 tiles walked with 9 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H10 = 0x00000098, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H10 tiles walked with 10 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H11 = 0x00000099, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H11 tiles walked with 11 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H12 = 0x0000009a, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H12 tiles walked with 12 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H13 = 0x0000009b, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H13 tiles walked with 13 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H14 = 0x0000009c, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H14 tiles walked with 14 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H15 = 0x0000009d, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H15 tiles walked with 15 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_PER_TILE_H16 = 0x0000009e, // SC_PERF_SEL_SC_QZ3_QUAD_PER_TILE_H16 tiles walked with 16 quads hit; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ0_QUAD_COUNT = 0x0000009f, // SC_PERF_SEL_SC_QZ0_QUAD_COUNT quad count; quad-z pipe 0 ; Where measured: sc sc_qdmsk_z output to sc_z_interp in db pipe 0 ; increment rate-one to 16 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_QZ1_QUAD_COUNT = 0x000000a0, // SC_PERF_SEL_SC_QZ1_QUAD_COUNT quad count; quad-z pipe 1 ; Where measured: sc sc_qdmsk_z output to sc_z_interp in db pipe 1 ; increment rate-one to 16 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 + SC_QZ2_QUAD_COUNT = 0x000000a1, // SC_PERF_SEL_SC_QZ2_QUAD_COUNT quad count; quad-z pipe 2 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_QZ3_QUAD_COUNT = 0x000000a2, // SC_PERF_SEL_SC_QZ3_QUAD_COUNT quad count; quad-z pipe 3 DEPRECATED (NUM_DB_PER_PACKER=4 variants only) + SC_P0_HIZ_TILE_COUNT = 0x000000a3, // SC_PERF_SEL_SC_P0_HIZ_TILE_COUNT total tiles surviving hi-z; db pipe 0 Where measured: sc sc_quad_proc usc_tile_mask_return_fifo in db pipe 0 ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_P1_HIZ_TILE_COUNT = 0x000000a4, // SC_PERF_SEL_SC_P1_HIZ_TILE_COUNT total tiles surviving hi-z; db pipe 1 ; Where measured: sc sc_quad_proc usc_tile_mask_return_fifo in db pipe 1 ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 + SC_P2_HIZ_TILE_COUNT = 0x000000a5, // SC_PERF_SEL_SC_P2_HIZ_TILE_COUNT total tiles surviving hi-z + SC_P3_HIZ_TILE_COUNT = 0x000000a6, // SC_PERF_SEL_SC_P3_HIZ_TILE_COUNT total tiles surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H0 = 0x000000a7, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H0 tiles with 0 quads surviving hi-z; db pipe 0 Where measured: sc sc_quad_proc usc_tile_mask_return_fifo in db pipe 0 ; increment rate-one per clock ; range-1/clk, limited to 20 bits per histogram bin SC_P0_HIZ_QUAD_PER_TILE_H* regardless of perfcounter range selected ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_P0_HIZ_QUAD_PER_TILE_H1 = 0x000000a8, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H1 tiles with 1 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H2 = 0x000000a9, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H2 tiles with 2 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H3 = 0x000000aa, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H3 tiles with 3 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H4 = 0x000000ab, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H4 tiles with 4 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H5 = 0x000000ac, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H5 tiles with 5 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H6 = 0x000000ad, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H6 tiles with 6 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H7 = 0x000000ae, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H7 tiles with 7 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H8 = 0x000000af, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H8 tiles with 8 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H9 = 0x000000b0, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H9 tiles with 9 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H10 = 0x000000b1, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H10 tiles with 10 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H11 = 0x000000b2, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H11 tiles with 11 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H12 = 0x000000b3, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H12 tiles with 12 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H13 = 0x000000b4, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H13 tiles with 13 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H14 = 0x000000b5, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H14 tiles with 14 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H15 = 0x000000b6, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H15 tiles with 15 quads surviving hi-z + SC_P0_HIZ_QUAD_PER_TILE_H16 = 0x000000b7, // SC_PERF_SEL_SC_P0_HIZ_QUAD_PER_TILE_H16 tiles with 16 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H0 = 0x000000b8, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H0 tiles with 0 quads surviving hi-z; db pipe 1 ; Where measured: sc sc_quad_proc usc_tile_mask_return_fifo in db pipe 1 ; increment rate-one per clock ; range-1/clk, limited to 20 bits per histogram bin SC_P1_HIZ_QUAD_PER_TILE_H* regardless of perfcounter range selected ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 + SC_P1_HIZ_QUAD_PER_TILE_H1 = 0x000000b9, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H1 tiles with 1 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H2 = 0x000000ba, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H2 tiles with 2 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H3 = 0x000000bb, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H3 tiles with 3 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H4 = 0x000000bc, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H4 tiles with 4 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H5 = 0x000000bd, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H5 tiles with 5 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H6 = 0x000000be, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H6 tiles with 6 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H7 = 0x000000bf, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H7 tiles with 7 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H8 = 0x000000c0, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H8 tiles with 8 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H9 = 0x000000c1, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H9 tiles with 9 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H10 = 0x000000c2, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H10 tiles with 10 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H11 = 0x000000c3, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H11 tiles with 11 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H12 = 0x000000c4, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H12 tiles with 12 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H13 = 0x000000c5, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H13 tiles with 13 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H14 = 0x000000c6, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H14 tiles with 14 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H15 = 0x000000c7, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H15 tiles with 15 quads surviving hi-z + SC_P1_HIZ_QUAD_PER_TILE_H16 = 0x000000c8, // SC_PERF_SEL_SC_P1_HIZ_QUAD_PER_TILE_H16 tiles with 16 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H0 = 0x000000c9, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H0 tiles with 0 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H1 = 0x000000ca, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H1 tiles with 1 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H2 = 0x000000cb, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H2 tiles with 2 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H3 = 0x000000cc, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H3 tiles with 3 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H4 = 0x000000cd, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H4 tiles with 4 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H5 = 0x000000ce, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H5 tiles with 5 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H6 = 0x000000cf, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H6 tiles with 6 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H7 = 0x000000d0, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H7 tiles with 7 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H8 = 0x000000d1, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H8 tiles with 8 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H9 = 0x000000d2, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H9 tiles with 9 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H10 = 0x000000d3, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H10 tiles with 10 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H11 = 0x000000d4, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H11 tiles with 11 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H12 = 0x000000d5, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H12 tiles with 12 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H13 = 0x000000d6, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H13 tiles with 13 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H14 = 0x000000d7, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H14 tiles with 14 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H15 = 0x000000d8, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H15 tiles with 15 quads surviving hi-z + SC_P2_HIZ_QUAD_PER_TILE_H16 = 0x000000d9, // SC_PERF_SEL_SC_P2_HIZ_QUAD_PER_TILE_H16 tiles with 16 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H0 = 0x000000da, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H0 tiles with 0 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H1 = 0x000000db, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H1 tiles with 1 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H2 = 0x000000dc, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H2 tiles with 2 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H3 = 0x000000dd, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H3 tiles with 3 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H4 = 0x000000de, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H4 tiles with 4 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H5 = 0x000000df, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H5 tiles with 5 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H6 = 0x000000e0, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H6 tiles with 6 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H7 = 0x000000e1, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H7 tiles with 7 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H8 = 0x000000e2, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H8 tiles with 8 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H9 = 0x000000e3, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H9 tiles with 9 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H10 = 0x000000e4, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H10 tiles with 10 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H11 = 0x000000e5, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H11 tiles with 11 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H12 = 0x000000e6, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H12 tiles with 12 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H13 = 0x000000e7, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H13 tiles with 13 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H14 = 0x000000e8, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H14 tiles with 14 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H15 = 0x000000e9, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H15 tiles with 15 quads surviving hi-z + SC_P3_HIZ_QUAD_PER_TILE_H16 = 0x000000ea, // SC_PERF_SEL_SC_P3_HIZ_QUAD_PER_TILE_H16 tiles with 16 quads surviving hi-z + SC_P0_HIZ_QUAD_COUNT = 0x000000eb, // SC_PERF_SEL_SC_P0_HIZ_QUAD_COUNT total quads surviving hi-z; db pipe 0 ; Where measured: sc sc_quad_proc usc_tile_mask_return_fifo in db pipe 1 ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1; + SC_P1_HIZ_QUAD_COUNT = 0x000000ec, // SC_PERF_SEL_SC_P1_HIZ_QUAD_COUNT total quads surviving hi-z; db pipe 1 ; Where measured: sc sc_quad_proc usc_tile_mask_return_fifo in db pipe 1 ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 + SC_P2_HIZ_QUAD_COUNT = 0x000000ed, // SC_PERF_SEL_SC_P2_HIZ_QUAD_COUNT total quads surviving hi-z + SC_P3_HIZ_QUAD_COUNT = 0x000000ee, // SC_PERF_SEL_SC_P3_HIZ_QUAD_COUNT total quads surviving hi-z + SC_P0_DETAIL_QUAD_COUNT = 0x000000ef, // SC_PERF_SEL_SC_P0_DETAIL_QUAD_COUNT total quads surviving detail sampler; db pipe 0 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_P1_DETAIL_QUAD_COUNT = 0x000000f0, // SC_PERF_SEL_SC_P1_DETAIL_QUAD_COUNT total quads surviving detail sampler; db pipe 1 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 + SC_P2_DETAIL_QUAD_COUNT = 0x000000f1, // SC_PERF_SEL_SC_P2_DETAIL_QUAD_COUNT total quads surviving detail sampler + SC_P3_DETAIL_QUAD_COUNT = 0x000000f2, // SC_PERF_SEL_SC_P3_DETAIL_QUAD_COUNT total quads surviving detail sampler + SC_P0_DETAIL_QUAD_WITH_1_PIX = 0x000000f3, // SC_PERF_SEL_SC_P0_DETAIL_QUAD_WITH_1_PIX quads with 1 pixel surviving detail; db pipe 0 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_P0_DETAIL_QUAD_WITH_2_PIX = 0x000000f4, // SC_PERF_SEL_SC_P0_DETAIL_QUAD_WITH_2_PIX quads with 2 pixels surviving detail; db pipe 0 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_P0_DETAIL_QUAD_WITH_3_PIX = 0x000000f5, // SC_PERF_SEL_SC_P0_DETAIL_QUAD_WITH_3_PIX quads with 3 pixels surviving detail; db pipe 0 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_P0_DETAIL_QUAD_WITH_4_PIX = 0x000000f6, // SC_PERF_SEL_SC_P0_DETAIL_QUAD_WITH_4_PIX quads with 4 pixels surviving detail; db pipe 0 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_P1_DETAIL_QUAD_WITH_1_PIX = 0x000000f7, // SC_PERF_SEL_SC_P1_DETAIL_QUAD_WITH_1_PIX quads with 1 pixel surviving detail; db pipe 1 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 + SC_P1_DETAIL_QUAD_WITH_2_PIX = 0x000000f8, // SC_PERF_SEL_SC_P1_DETAIL_QUAD_WITH_2_PIX quads with 2 pixels surviving detail; db pipe 1 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 + SC_P1_DETAIL_QUAD_WITH_3_PIX = 0x000000f9, // SC_PERF_SEL_SC_P1_DETAIL_QUAD_WITH_3_PIX quads with 3 pixels surviving detail; db pipe 1 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 + SC_P1_DETAIL_QUAD_WITH_4_PIX = 0x000000fa, // SC_PERF_SEL_SC_P1_DETAIL_QUAD_WITH_4_PIX quads with 4 pixels surviving detail; db pipe 1 ; Where measured: sc sc_quad_proc/sc_sample_mask valid output to sc_tileaccum ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Valid only if NUM_DB_PER_PACKER=2 + SC_P2_DETAIL_QUAD_WITH_1_PIX = 0x000000fb, // SC_PERF_SEL_SC_P2_DETAIL_QUAD_WITH_1_PIX quads with 1 pixel surviving detail + SC_P2_DETAIL_QUAD_WITH_2_PIX = 0x000000fc, // SC_PERF_SEL_SC_P2_DETAIL_QUAD_WITH_2_PIX quads with 2 pixels surviving detail + SC_P2_DETAIL_QUAD_WITH_3_PIX = 0x000000fd, // SC_PERF_SEL_SC_P2_DETAIL_QUAD_WITH_3_PIX quads with 3 pixels surviving detail + SC_P2_DETAIL_QUAD_WITH_4_PIX = 0x000000fe, // SC_PERF_SEL_SC_P2_DETAIL_QUAD_WITH_4_PIX quads with 4 pixels surviving detail + SC_P3_DETAIL_QUAD_WITH_1_PIX = 0x000000ff, // SC_PERF_SEL_SC_P3_DETAIL_QUAD_WITH_1_PIX quads with 1 pixel surviving detail + SC_P3_DETAIL_QUAD_WITH_2_PIX = 0x00000100, // SC_PERF_SEL_SC_P3_DETAIL_QUAD_WITH_2_PIX quads with 2 pixels surviving detail + SC_P3_DETAIL_QUAD_WITH_3_PIX = 0x00000101, // SC_PERF_SEL_SC_P3_DETAIL_QUAD_WITH_3_PIX quads with 3 pixels surviving detail + SC_P3_DETAIL_QUAD_WITH_4_PIX = 0x00000102, // SC_PERF_SEL_SC_P3_DETAIL_QUAD_WITH_4_PIX quads with 4 pixels surviving detail + SC_EARLYZ_QUAD_COUNT = 0x00000103, // SC_PERF_SEL_SC_EARLYZ_QUAD_COUNT total quads surviving early-z ; Where measured: sc_tileaccum (sc_quadaccum if 1db per packer) inputs to packer ; increment rate 1 to 2 quads per clock; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_EARLYZ_QUAD_WITH_1_PIX = 0x00000104, // SC_PERF_SEL_SC_EARLYZ_QUAD_WITH_1_PIX quads with 1 pixel surviving early-z ; Where measured: sc_tileaccum (sc_quadaccum if 1db per packer) inputs to packer ; increment rate 1 to 2 quads per clock; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_EARLYZ_QUAD_WITH_2_PIX = 0x00000105, // SC_PERF_SEL_SC_EARLYZ_QUAD_WITH_2_PIX quads with 2 pixels surviving early-z ; Where measured: sc_tileaccum (sc_quadaccum if 1db per packer) inputs to packer ; increment rate 1 to 2 quads per clock; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_EARLYZ_QUAD_WITH_3_PIX = 0x00000106, // SC_PERF_SEL_SC_EARLYZ_QUAD_WITH_3_PIX quads with 3 pixels surviving early-z ; Where measured: sc_tileaccum (sc_quadaccum if 1db per packer) inputs to packer ; increment rate 1 to 2 quads per clock; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_EARLYZ_QUAD_WITH_4_PIX = 0x00000107, // SC_PERF_SEL_SC_EARLYZ_QUAD_WITH_4_PIX quads with 4 pixels surviving early-z ; Where measured: sc_tileaccum (sc_quadaccum if 1db per packer) inputs to packer ; increment rate 1 to 2 quads per clock; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PKR_QUAD_PER_ROW_H1 = 0x00000108, // SC_PERF_SEL_SC_PKR_QUAD_PER_ROW_H1 packer row outputs with 1 valid quad ; Where measured: sc_packer output increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PKR_QUAD_PER_ROW_H2 = 0x00000109, // SC_PERF_SEL_SC_PKR_QUAD_PER_ROW_H2 packer row outputs with 2 valid quad ; Where measured: sc_packer output increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PKR_4X2_QUAD_SPLIT = 0x0000010a, // SC_PERF_SEL_SC_PKR_4X2_QUAD_SPLIT packer row outputs the first 2x2 quad from a 4x2 quad that needed to be split to fit into a 16 quad wavefront ; Where measured: sc_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Applicable only to RB+ (GPU__GC__DBL_COLOR_WRITES__1) + SC_PKR_4X2_FILL_QUAD = 0x0000010b, // SC_PERF_SEL_SC_PKR_4X2_FILL_QUAD packer row outputs a empty fill 4x2 quads that needed to be inserted to realign the quad wavefront based on the setting of PA_SC_SHADER_CONTROL.REALIGN_DQUADS_AFTER_N_WAVES or PA_SC_ENHANCE_1.REALIGN_DQUADS_OVERRIDE ; Where measured: sc_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Applicable only to RB+ (GPU__GC__DBL_COLOR_WRITES__1) + SC_PKR_END_OF_VECTOR = 0x0000010c, // SC_PERF_SEL_SC_PKR_END_OF_VECTOR number of pixel vectors ; Where measured: sc_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PKR_CONTROL_XFER = 0x0000010d, // SC_PERF_SEL_SC_PKR_CONTROL_XFER number of control transfers ; Where measured: sc_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PKR_DBHANG_FORCE_EOV = 0x0000010e, // SC_PERF_SEL_SC_PKR_DBHANG_FORCE_EOV number of times partial vector ejected b/c of DB hang condition ; Where measured: sc_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_REG_SCLK_BUSY = 0x0000010f, // SC_PERF_SEL_SC_REG_SCLK_BUSY number of cycles register clock is busy + SC_GRP0_DYN_SCLK_BUSY = 0x00000110, // SC_PERF_SEL_SC_GRP0_DYN_SCLK_BUSY number of cycles group0 (if instance=0 sc frontend clock (sct), else scb tile common logic dynamic clock is busy (if RB+ DB pipe this is the same as the DB pipe dynamic clock) + SC_GRP1_DYN_SCLK_BUSY = 0x00000111, // SC_PERF_SEL_SC_GRP1_DYN_SCLK_BUSY number of cycles group1 dynamic clock db0 (db0 name is relative to backend packer instance) is busy + SC_GRP2_DYN_SCLK_BUSY = 0x00000112, // SC_PERF_SEL_SC_GRP2_DYN_SCLK_BUSY number of cycles group2 dynamic clock db1 db1 if present (db1 name is relative to backend packer instance) is busy + SC_GRP3_DYN_SCLK_BUSY = 0x00000113, // SC_PERF_SEL_SC_GRP3_DYN_SCLK_BUSY DEPRECATED number of cycles group3 dynamic clock is busy + SC_GRP4_DYN_SCLK_BUSY = 0x00000114, // SC_PERF_SEL_SC_GRP4_DYN_SCLK_BUSY DEPRECATED number of cycles group4 dynamic clock is busy + SC_PA0_SC_DATA_FIFO_RD = 0x00000115, // SC_PERF_SEL_SC_PA0_SC_DATA_FIFO_RD number of cycles of read of pa0 fifo ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PA0_SC_DATA_FIFO_WE = 0x00000116, // SC_PERF_SEL_SC_PA0_SC_DATA_FIFO_WE number of cycles of write of pa0 fifo ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PA1_SC_DATA_FIFO_RD = 0x00000117, // SC_PERF_SEL_SC_PA1_SC_DATA_FIFO_RD number of cycles of read of pa1 fifo ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PA1_SC_DATA_FIFO_WE = 0x00000118, // SC_PERF_SEL_SC_PA1_SC_DATA_FIFO_WE number of cycles of write of pa1 fifo ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PS_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES = 0x00000119, // SC_PERF_SEL_SC_PS_ARB_XFC_ALL_EVENT_OR_PRIM_CYCLES number of cycles of arb xfc's for all event or prims ; Where measured: sc_prim_setup to (pbb input if present) ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ARB_XFC_ONLY_PRIM_CYCLES = 0x0000011a, // SC_PERF_SEL_SC_PS_ARB_XFC_ONLY_PRIM_CYCLES number of cycles of arb xfc's for only prims (vents excluded) ; Where measured: sc_prim_setup to (pbb input if present) ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ARB_XFC_ONLY_ONE_INC_PER_PRIM = 0x0000011b, // SC_PERF_SEL_SC_PS_ARB_XFC_ONLY_ONE_INC_PER_PRIM number of cycles of arb xfc's for one inc per prim only. Increments only for phase 0 of a multi-cycle primitive transfer ; Where measured: sc_prim_setup to (pbb input if present) ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ARB_STALLED_FROM_BELOW = 0x0000011c, // RESERVED (see PH replacement PH_SC*_ARB_STALLED_FROM_BELOW) SC_PS_ARB_STALLED_FROM_BELOW number of cycles of stalled post arbiter for valid data ; Where measured: sc_prim_setup to (pbb input if present) ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ARB_STARVED_FROM_ABOVE = 0x0000011d, // SC_PERF_SEL_SC_PS_ARB_STARVED_FROM_ABOVE number of cycles of PA starving SC in sop/eop range ; Where measured: sc_prim_setup to (pbb input if present) ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only ; Course Walker Bottleneck = SC_PS_ARB_STALLED_FROM_BELOW / SC_PS_ARB_PA_SC_BUSY + SC_PS_ARB_SC_BUSY = 0x0000011e, // RESERVED (see PH replacement PH_SC0_ARB_BUSY ) SC_PS_ARB_SC_BUSY number of cycles of SC busy ; Where measured: sc_prim_setup ps_pa_sc_data_valid signal (at pbb input if present) ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ARB_PA_SC_BUSY = 0x0000011f, // RESERVED (see PH replacement PH_SC*_ARB_PA_BUSY_SOP) SC_PS_ARB_PA_SC_BUSY number of cycles in between start of packet/end of packet ; Where measured: sc_prim_setup dp_sop (start of primitives stick bit) (at pbb input if present) ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; Primitive Rate (single cycle prims): (SC_PA0_SC_DATA_FIFO_RD + SC_PA1_SC_DATA_FIFO_RD + SC_PA2_SC_DATA_FIFO_RD + SC_PA3_SC_DATA_FIFO_RD)/SC_PS_ARB_PA_SC_BUSY ; Primitive Rate (multi-cycle prims) = SC_PS_ARB_XFC_ONLY_ONE_INC_PER_PRIM / SC_PS_ARB_PA_SC_BUSY ; SC_Utilization = SC_PS_ARB_SC_BUSY/SC_PS_ARB_PA_SC_BUSY + SC_PA2_SC_DATA_FIFO_RD = 0x00000120, // SC_PERF_SEL_SC_PA2_SC_DATA_FIFO_RD number of cycles of read of pa2 fifo ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PA2_SC_DATA_FIFO_WE = 0x00000121, // SC_PERF_SEL_SC_PA2_SC_DATA_FIFO_WE number of cycles of write of pa2 fifo ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PA3_SC_DATA_FIFO_RD = 0x00000122, // SC_PERF_SEL_SC_PA3_SC_DATA_FIFO_RD number of cycles of read of pa3 fifo ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PA3_SC_DATA_FIFO_WE = 0x00000123, // SC_PERF_SEL_SC_PA3_SC_DATA_FIFO_WE number of cycles of write of pa3 fifo Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PA_SC_DEALLOC_0_0_WE = 0x00000124, // SC_PERF_SEL_SC_PA_SC_DEALLOC_0_0_WE number of cycles of pa (or ph if present) sc fifo write of pa0 dealloc binary bit 0 ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA_SC_DEALLOC_0_1_WE = 0x00000125, // SC_PERF_SEL_SC_PA_SC_DEALLOC_0_1_WE number of cycles of pa (or ph if present) sc fifo write of pa0 dealloc binary bit 1 ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA_SC_DEALLOC_1_0_WE = 0x00000126, // SC_PERF_SEL_SC_PA_SC_DEALLOC_1_0_WE Not valid if PH is present. SC_PA_SC_DEALLOC_1_0_WE number of cycles of pa sc fifo write of pa1 dealloc binary bit 0 ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA_SC_DEALLOC_1_1_WE = 0x00000127, // SC_PERF_SEL_SC_PA_SC_DEALLOC_1_1_WE Not valid if PH is present. SC_PA_SC_DEALLOC_1_1_WE number of cycles of pa sc fifo write of pa1 dealloc binary bit 1 ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA_SC_DEALLOC_2_0_WE = 0x00000128, // SC_PERF_SEL_SC_PA_SC_DEALLOC_2_0_WE Not valid if PH is present. SC_PA_SC_DEALLOC_2_0_WE number of cycles of pa sc fifo write of pa2 dealloc binary bit 0 ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA_SC_DEALLOC_2_1_WE = 0x00000129, // SC_PERF_SEL_SC_PA_SC_DEALLOC_2_1_WE Not valid if PH is present. SC_PA_SC_DEALLOC_2_1_WE number of cycles of pa sc fifo write of pa2 dealloc binary bit 1 ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA_SC_DEALLOC_3_0_WE = 0x0000012a, // SC_PERF_SEL_SC_PA_SC_DEALLOC_3_0_WE Not valid if PH is present. SC_PA_SC_DEALLOC_3_0_WE number of cycles of pa sc fifo write of pa3 dealloc binary bit 0 ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA_SC_DEALLOC_3_1_WE = 0x0000012b, // SC_PERF_SEL_SC_PA_SC_DEALLOC_3_1_WE Not valid if PH is present. SC_PA_SC_DEALLOC_3_1_WE number of cycles of pa sc fifo write of pa3 dealloc binary bit 1 ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA0_SC_EOP_WE = 0x0000012c, // SC_PERF_SEL_SC_PA0_SC_EOP_WE Not valid if PH is present. SC_PA0_SC_EOP_WE number of cycles of pa sc fifo write of pa0 end of packet ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA0_SC_EOPG_WE = 0x0000012d, // SC_PERF_SEL_SC_PA0_SC_EOPG_WE Not valid if PH is present. SC_PA0_SC_EOPG_WE number of cycles of pa sc fifo write of pa0 end of prim group ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only; + SC_PA0_SC_EVENT_WE = 0x0000012e, // SC_PERF_SEL_SC_PA0_SC_EVENT_WE number of cycles of pa sc fifo write of pa0 event ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA1_SC_EOP_WE = 0x0000012f, // SC_PERF_SEL_SC_PA1_SC_EOP_WE Not valid if PH is present. SC_PA1_SC_EOP_WE number of cycles of pa sc fifo write of pa1 end of packet ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA1_SC_EOPG_WE = 0x00000130, // SC_PERF_SEL_SC_PA1_SC_EOPG_WE Not valid if PH is present. SC_PA1_SC_EOPG_WE number of cycles of pa sc fifo write of pa1 end of prim group ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA1_SC_EVENT_WE = 0x00000131, // SC_PERF_SEL_SC_PA1_SC_EVENT_WE Not valid if PH is present. SC_PA1_SC_EVENT_WE number of cycles of pa sc fifo write of pa1 event ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA2_SC_EOP_WE = 0x00000132, // SC_PERF_SEL_SC_PA2_SC_EOP_WE Not valid if PH is present. SC_PA2_SC_EOP_WE number of cycles of pa sc fifo write of pa2 end of packet ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA2_SC_EOPG_WE = 0x00000133, // SC_PERF_SEL_SC_PA2_SC_EOPG_WE Not valid if PH is present. SC_PA2_SC_EOPG_WE number of cycles of pa sc fifo write of pa2 end of prim group ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only; + SC_PA2_SC_EVENT_WE = 0x00000134, // SC_PERF_SEL_SC_PA2_SC_EVENT_WE Not valid if PH is present. SC_PA2_SC_EVENT_WE number of cycles of pa sc fifo write of pa2 event ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA3_SC_EOP_WE = 0x00000135, // SC_PERF_SEL_SC_PA3_SC_EOP_WE Not valid if PH is present. SC_PA3_SC_EOP_WE number of cycles of pa sc fifo write of pa3 end of packet ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PA3_SC_EOPG_WE = 0x00000136, // SC_PERF_SEL_SC_PA3_SC_EOPG_WE Not valid if PH is present. SC_PA3_SC_EOPG_WE number of cycles of pa sc fifo write of pa3 end of prim group ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only + SC_PA3_SC_EVENT_WE = 0x00000137, // SC_PERF_SEL_SC_PA3_SC_EVENT_WE Not valid if PH is present. SC_PA3_SC_EVENT_WE number of cycles of pa sc fifo write of pa3 event ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug/comparison to corresponding counts on the spi interface only; + SC_PS_ARB_OOO_THRESHOLD_SWITCH_TO_DESIRED_FIFO = 0x00000138, // SC_PERF_SEL_SC_PS_ARB_OOO_THRESHOLD_SWITCH_TO_DESIRED_FIFO Not valid if PH is present. Number of cycles of pa sc arbiter front end switches based on hitting the out of order fifo skew threshold Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ARB_OOO_FIFO_EMPTY_SWITCH = 0x00000139, // SC_PERF_SEL_SC_PS_ARB_OOO_FIFO_EMPTY_SWITCH Not valid if PH is present. SC_PS_ARB_OOO_FIFO_EMPTY_SWITCH number of cycles of cycles of pa sc arbiter front end switches based on the currently selected fifo going empty ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ARB_NULL_PRIM_BUBBLE_POP = 0x0000013a, // SC_PERF_SEL_SC_PS_ARB_NULL_PRIM_BUBBLE_POP Not valid if PH is present. SC_PS_ARB_NULL_PRIM_BUBBLE_POP number of cycles of pa sc arbiter null prims without eop read in the eop braodcast window between eop on selected fifo and eop sync achieved across all fifos ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ARB_EOP_POP_SYNC_POP = 0x0000013b, // SC_PERF_SEL_SC_PS_ARB_EOP_POP_SYNC_POP Not valid if PH is present. SC_PS_ARB_EOP_POP_SYNC_POP number of cycles of of pa sc arbiter eop reads at the eop sync point with all fifos synced ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ARB_EVENT_SYNC_POP = 0x0000013c, // SC_PERF_SEL_SC_PS_ARB_EVENT_SYNC_POP Not valid if PH is present. SC_PS_ARB_EVENT_SYNC_POP number of cycles of pa sc event reads ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_ENG_MULTICYCLE_BUBBLE = 0x0000013d, // SC_PERF_SEL_SC_PS_ENG_MULTICYCLE_BUBBLE DEPRECATED number of cycles of multicycles prims sent with a empty fifo slot behind the current phase, this will not occur in gfx9 ; + SC_PA0_SC_FPOV_WE = 0x0000013e, // SC_PERF_SEL_SC_PA0_SC_FPOV_WE number of cycles of pa sc fifo write of pa0 first prim of vector ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PA1_SC_FPOV_WE = 0x0000013f, // SC_PERF_SEL_SC_PA1_SC_FPOV_WE Not valid if PH is present. SC_PA1_SC_FPOV_WE number of cycles of pa sc fifo write of pa1 first prim of vector ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PA2_SC_FPOV_WE = 0x00000140, // SC_PERF_SEL_SC_PA2_SC_FPOV_WE Not valid if PH is present. SC_PA2_SC_FPOV_WE number of cycles of pa sc fifo write of pa2 first prim of vector ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PA3_SC_FPOV_WE = 0x00000141, // SC_PERF_SEL_SC_PA3_SC_FPOV_WE Not valid if PH is present. SC_PA3_SC_FPOV_WE number of cycles of pa sc fifo write of pa3 first prim of vector ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PA0_SC_LPOV_WE = 0x00000142, // SC_PERF_SEL_SC_PA0_SC_LPOV_WE Not valid if PH is present. SC_PA0_SC_LPOV_WE number of cycles of pa sc fifo write of pa0 last prim of vector ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PA1_SC_LPOV_WE = 0x00000143, // SC_PERF_SEL_SC_PA1_SC_LPOV_WE Not valid if PH is present. SC_PA1_SC_LPOV_WE number of cycles of pa sc fifo write of pa1 last prim of vector ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PA2_SC_LPOV_WE = 0x00000144, // SC_PERF_SEL_SC_PA2_SC_LPOV_WE Not valid if PH is present. SC_PA2_SC_LPOV_WE number of cycles of pa sc fifo write of pa2 last prim of vector ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PA3_SC_LPOV_WE = 0x00000145, // SC_PERF_SEL_SC_PA3_SC_LPOV_WE Not valid if PH is present. SC_PA3_SC_LPOV_WE number of cycles of pa sc fifo write of pa3 last prim of vector ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_SPI_DEALLOC_0_0 = 0x00000146, // SC_PERF_SEL_SC_SPI_DEALLOC_0_0 number of spi cycles of pa0 originated dealloc bit 0 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SPI_DEALLOC_0_1 = 0x00000147, // SC_PERF_SEL_SC_SPI_DEALLOC_0_1 number of spi cycles of pa0 originated dealloc bit 1 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_0_2 = 0x00000148, // SC_PERF_SEL_SC_SPI_DEALLOC_0_2 number of spi cycles of pa0 originated dealloc bit 2 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_1_0 = 0x00000149, // SC_PERF_SEL_SC_SPI_DEALLOC_1_0 Not valid if PH is present. SC_SPI_DEALLOC_1_0 number of spi cycles of pa1 originated dealloc bit 0 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_1_1 = 0x0000014a, // SC_PERF_SEL_SC_SPI_DEALLOC_1_1 Not valid if PH is present. SC_SPI_DEALLOC_1_1 number of spi cycles of pa1 originated dealloc bit 1 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_1_2 = 0x0000014b, // SC_PERF_SEL_SC_SPI_DEALLOC_1_2 Not valid if PH is present. SC_SPI_DEALLOC_1_2 number of spi cycles of pa1 originated dealloc bit 2 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_2_0 = 0x0000014c, // SC_PERF_SEL_SC_SPI_DEALLOC_2_0 Not valid if PH is present. SC_SPI_DEALLOC_2_0 number of spi cycles of pa2 originated dealloc bit 0 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_2_1 = 0x0000014d, // SC_PERF_SEL_SC_SPI_DEALLOC_2_1 Not valid if PH is present. SC_SPI_DEALLOC_2_1 number of spi cycles of pa2 originated dealloc bit 1 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_2_2 = 0x0000014e, // SC_PERF_SEL_SC_SPI_DEALLOC_2_2 Not valid if PH is present. SC_SPI_DEALLOC_2_2 number of spi cycles of pa2 originated dealloc bit 2 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_3_0 = 0x0000014f, // SC_PERF_SEL_SC_SPI_DEALLOC_3_0 Not valid if PH is present. SC_SPI_DEALLOC_3_0 number of spi cycles of pa3 originated dealloc bit 0 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_3_1 = 0x00000150, // SC_PERF_SEL_SC_SPI_DEALLOC_3_1 Not valid if PH is present. SC_SPI_DEALLOC_3_1 number of spi cycles of pa3 originated dealloc bit 1 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_DEALLOC_3_2 = 0x00000151, // SC_PERF_SEL_SC_SPI_DEALLOC_3_2 Not valid if PH is present. SC_SPI_DEALLOC_3_2 number of spi cycles of pa3 originated dealloc bit 2 set ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_FPOV_0 = 0x00000152, // SC_PERF_SEL_SC_SPI_FPOV_0 number of spi cycles of pa0 originated first prim of vector ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_FPOV_1 = 0x00000153, // SC_PERF_SEL_SC_SPI_FPOV_1 Not valid if PH is present. SC_SPI_FPOV_1 number of spi cycles of pa1 originated first prim of vector ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_FPOV_2 = 0x00000154, // SC_PERF_SEL_SC_SPI_FPOV_2 Not valid if PH is present. SC_SPI_FPOV_2 number of spi cycles of pa2 originated first prim of vector Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_FPOV_3 = 0x00000155, // SC_PERF_SEL_SC_SPI_FPOV_3 Not valid if PH is present. SC_SPI_FPOV_3 number of spi cycles of pa3 originated first prim of vector ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_SPI_EVENT = 0x00000156, // SC_PERF_SEL_SC_SPI_EVENT number of spi cycles of events ; Where measured: sc_prim_packer ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa count only. + SC_PS_TS_EVENT_FIFO_PUSH = 0x00000157, // SC_PERF_SEL_SC_PS_TS_EVENT_FIFO_PUSH number of cycles of sc timestamp event fifo writes ; Where measured: sc_prim_setup timestamp event fifo; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug only. + SC_PS_TS_EVENT_FIFO_POP = 0x00000158, // SC_PERF_SEL_SC_PS_TS_EVENT_FIFO_POP number of cycles of sc timestamp event fifo reads ; Where measured: sc_prim_setup timestamp event fifo; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug only. + SC_PS_CTX_DONE_FIFO_PUSH = 0x00000159, // SC_PERF_SEL_SC_PS_CTX_DONE_FIFO_PUSH number of cycles of sc context done event fifo writes ; Where measured: sc_prim_setup context done event fifo; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug only. + SC_PS_CTX_DONE_FIFO_POP = 0x0000015a, // SC_PERF_SEL_SC_PS_CTX_DONE_FIFO_POP number of cycles of sc context done event fifo reads ; Where measured: sc_prim_setup context done event fifo; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug only. + SC_MULTICYCLE_BUBBLE_FREEZE = 0x0000015b, // SC_PERF_SEL_SC_MULTICYCLE_BUBBLE_FREEZE DEPRECATED + SC_EOP_SYNC_WINDOW = 0x0000015c, // SC_PERF_SEL_SC_EOP_SYNC_WINDOW Not applicable to GFX10, moved to PH (see PH_SC*_EOP_SYNC_WINDOW). SC_EOP_SYNC_WINDOW number of cycles of after end of packet is read from the selected pa sc fifo until end of packet broadcast synchronization is achieved across all pa sc fifos ; Where measured: sc_prim_setup top; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PA0_SC_NULL_WE = 0x0000015d, // SC_PERF_SEL_SC_PA0_SC_NULL_WE number of cycles of pa sc fifo write of pa0 null primitives ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only; + SC_PA0_SC_NULL_DEALLOC_WE = 0x0000015e, // SC_PERF_SEL_SC_PA0_SC_NULL_DEALLOC_WE number of cycles of pa sc fifo write of pa0 null primitives with dealloc tokens set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only; + SC_PA0_SC_DATA_FIFO_EOPG_RD = 0x0000015f, // SC_PERF_SEL_SC_PA0_SC_DATA_FIFO_EOPG_RD number of cycles of pa sc fifo read of pa0 end of prim group ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only; + SC_PA0_SC_DATA_FIFO_EOP_RD = 0x00000160, // SC_PERF_SEL_SC_PA0_SC_DATA_FIFO_EOP_RD number of cycles of pa sc fifo read of pa0 end of packet ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only + SC_PA0_SC_DEALLOC_0_RD = 0x00000161, // SC_PERF_SEL_SC_PA0_SC_DEALLOC_0_RD number of cycles of pa sc fifo read of pa0 dealloc bit 0 set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa we or spi count only. + SC_PA0_SC_DEALLOC_1_RD = 0x00000162, // SC_PERF_SEL_SC_PA0_SC_DEALLOC_1_RD number of cycles of pa sc fifo read of pa0 dealloc bit 1 set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa we or spi count only. + SC_PA1_SC_DATA_FIFO_EOPG_RD = 0x00000163, // SC_PERF_SEL_SC_PA1_SC_DATA_FIFO_EOPG_RD Not applicable to GFX10 (see PH_PERF). SC_PA1_SC_DATA_FIFO_EOPG_RD number of cycles of pa sc fifo read of pa1 end of prim group + SC_PA1_SC_DATA_FIFO_EOP_RD = 0x00000164, // SC_PERF_SEL_SC_PA1_SC_DATA_FIFO_EOP_RD Not applicable to GFX10 (see PH_PERF). SC_PA1_SC_DATA_FIFO_EOP_RD number of cycles of pa sc fifo read of pa1 end of packet Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only + SC_PA1_SC_DEALLOC_0_RD = 0x00000165, // SC_PERF_SEL_SC_PA1_SC_DEALLOC_0_RD Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA1_SC_DEALLOC_0_RD number of cycles of pa sc fifo read of pa1 dealloc bit 0 set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa we or spi count only. + SC_PA1_SC_DEALLOC_1_RD = 0x00000166, // SC_PERF_SEL_SC_PA1_SC_DEALLOC_1_RD Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA1_SC_DEALLOC_1_RD number of cycles of pa sc fifo read of pa1 dealloc bit 1 set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Intended for engineering dubug/consistency check with corresponding pa we or spi count only. + SC_PA1_SC_NULL_WE = 0x00000167, // SC_PERF_SEL_SC_PA1_SC_NULL_WE Not applicable to GFX10 (see PH_PERF). SC_PA1_SC_NULL_WE number of cycles of pa sc fifo write of pa1 null primitives ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only + SC_PA1_SC_NULL_DEALLOC_WE = 0x00000168, // SC_PERF_SEL_SC_PA1_SC_NULL_DEALLOC_WE Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA1_SC_NULL_DEALLOC_WE number of cycles of pa sc fifo write of pa1 null primitives with dealloc tokens set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only + SC_PA2_SC_DATA_FIFO_EOPG_RD = 0x00000169, // SC_PERF_SEL_SC_PA2_SC_DATA_FIFO_EOPG_RD Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA2_SC_DATA_FIFO_EOPG_RD number of cycles of pa sc fifo read of pa2 end of prim group ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering debug only + SC_PA2_SC_DATA_FIFO_EOP_RD = 0x0000016a, // SC_PERF_SEL_SC_PA2_SC_DATA_FIFO_EOP_RD Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA2_SC_DATA_FIFO_EOP_RD number of cycles of pa sc fifo read of pa2 end of packet ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa we. + SC_PA2_SC_DEALLOC_0_RD = 0x0000016b, // SC_PERF_SEL_SC_PA2_SC_DEALLOC_0_RD Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA2_SC_DEALLOC_0_RD number of cycles of pa sc fifo read of pa2 dealloc bit 0 set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa we or spi count only. + SC_PA2_SC_DEALLOC_1_RD = 0x0000016c, // SC_PERF_SEL_SC_PA2_SC_DEALLOC_1_RD Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA2_SC_DEALLOC_1_RD number of cycles of pa sc fifo read of pa2 dealloc bit 1 set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa we or spi count only. + SC_PA2_SC_NULL_WE = 0x0000016d, // SC_PERF_SEL_SC_PA2_SC_NULL_WE Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA2_SC_NULL_WE number of cycles of pa sc fifo write of pa2 null primitives ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa we. + SC_PA2_SC_NULL_DEALLOC_WE = 0x0000016e, // SC_PERF_SEL_SC_PA2_SC_NULL_DEALLOC_WE Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA2_SC_NULL_DEALLOC_WE number of cycles of pa sc fifo write of pa2 null primitives with dealloc tokens set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa rd. + SC_PA3_SC_DATA_FIFO_EOPG_RD = 0x0000016f, // SC_PERF_SEL_SC_PA3_SC_DATA_FIFO_EOPG_RD Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA3_SC_DATA_FIFO_EOPG_RD number of cycles of pa sc fifo read of pa3 end of prim group ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa wd. + SC_PA3_SC_DATA_FIFO_EOP_RD = 0x00000170, // SC_PERF_SEL_SC_PA3_SC_DATA_FIFO_EOP_RD Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA3_SC_DATA_FIFO_EOP_RD number of cycles of pa sc fifo read of pa3 end of packet ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa wd. + SC_PA3_SC_DEALLOC_0_RD = 0x00000171, // SC_PERF_SEL_SC_PA3_SC_DEALLOC_0_RD Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA3_SC_DEALLOC_0_RD number of cycles of pa sc fifo read of pa3 dealloc bit 0 set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa wd or spi. + SC_PA3_SC_DEALLOC_1_RD = 0x00000172, // SC_PERF_SEL_SC_PA3_SC_DEALLOC_1_RD Not valid if PH is present. SC_PA3_SC_DEALLOC_1_RD number of cycles of pa sc fifo read of pa3 dealloc bit 1 set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. Intended for engineering dubug/consistency check with corresponding pa wd or spi. + SC_PA3_SC_NULL_WE = 0x00000173, // SC_PERF_SEL_SC_PA3_SC_NULL_WE Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA3_SC_NULL_WE number of cycles of pa sc fifo write of pa3 null primitives ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PA3_SC_NULL_DEALLOC_WE = 0x00000174, // SC_PERF_SEL_SC_PA3_SC_NULL_DEALLOC_WE Not applicable to GFX10 (see PH_PERF). Not valid if PH is present. SC_PA3_SC_NULL_DEALLOC_WE number of cycles of pa sc fifo write of pa3 null primitives with dealloc tokens set ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_PA0_SC_FIFO_EMPTY = 0x00000175, // SC_PERF_SEL_SC_PS_PA0_SC_FIFO_EMPTY number of cycles of pa0_sc_fifo_empty. Note that behavior of this will differ for current generation variants with a Primitive Hub (PH) since if PH is present this only represents an interface skid buffer and most primitive storage buffers are in the PH.; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_PA0_SC_FIFO_FULL = 0x00000176, // SC_PERF_SEL_SC_PS_PA0_SC_FIFO_FULL number of cycles of pa0_sc_fifo_full. Note that behavior of this will differ for current generation variants with a Primitive Hub (PH) since if PH is present this only represents an interface skid buffer and most primitive storage buffers are in the PH.; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_RESERVED_0 = 0x00000177, // SC_PERF_SEL_SC_RESERVED_0 Reserved was redundanct count SC_PA0_PS_DATA_SEND + SC_PS_PA1_SC_FIFO_EMPTY = 0x00000178, // SC_PERF_SEL_SC_PS_PA1_SC_FIFO_EMPTY Not valid if PH is present. SC_PS_PA1_SC_FIFO_EMPTY number of cycles of pa1_sc_fifo_empty ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_PA1_SC_FIFO_FULL = 0x00000179, // SC_PERF_SEL_SC_PS_PA1_SC_FIFO_FULL Not valid if PH is present. SC_PS_PA1_SC_FIFO_FULL number of cycles of pa1_sc_fifo_full ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_RESERVED_1 = 0x0000017a, // Reserved was redundanct count SC_PA1_PS_DATA_SEND + SC_PS_PA2_SC_FIFO_EMPTY = 0x0000017b, // SC_PERF_SEL_SC_PS_PA2_SC_FIFO_EMPTY Not valid if PH is present. SC_PS_PA2_SC_FIFO_EMPTY number of cycles of pa2_sc_fifo_empty ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_PA2_SC_FIFO_FULL = 0x0000017c, // SC_PERF_SEL_SC_PS_PA2_SC_FIFO_FULL Not valid if PH is present. SC_PS_PA2_SC_FIFO_FULL number of cycles of pa2_sc_fifo_full ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_RESERVED_2 = 0x0000017d, // Reserved was redundant count SC_PA2_PS_DATA_SEND + SC_PS_PA3_SC_FIFO_EMPTY = 0x0000017e, // SC_PERF_SEL_SC_PS_PA3_SC_FIFO_EMPTY Not valid if PH is present. SC_PS_PA3_SC_FIFO_EMPTY number of cycles of pa3_sc_fifo_empty ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_PA3_SC_FIFO_FULL = 0x0000017f, // SC_PERF_SEL_SC_PS_PA3_SC_FIFO_FULL Not valid if PH is present. SC_PS_PA3_SC_FIFO_FULL number of cycles of pa3_sc_fifo_full ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_RESERVED_3 = 0x00000180, // SC_PERF_SEL_SC_RESERVED_3 Reserved was redundant count SC_PA3_PS_DATA_SEND + SC_BUSY_PROCESSING_MULTICYCLE_PRIM = 0x00000181, // SC_PERF_SEL_SC_BUSY_PROCESSING_MULTICYCLE_PRIM number of cycles of sc arbiter busy processing multicycle prims (clipped, perspective linear gradient, line stipple) ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_BUSY_CNT_NOT_ZERO = 0x00000182, // SC_PERF_SEL_SC_BUSY_CNT_NOT_ZERO number of cycles of sc prim setup busy counter non zero (busy above backend mapper) ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_BM_BUSY = 0x00000183, // SC_PERF_SEL_SC_BM_BUSY number of cycles of sc backend mapper busy ; Where measured: sc backend mapper ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_BACKEND_BUSY = 0x00000184, // SC_PERF_SEL_SC_BACKEND_BUSY number of cycles of sc backend busy ; Where measured: sc backend ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 only. (second backend busy is contributor to SC_SCB_BUSY). + SC_SCF_SCB_INTERFACE_BUSY = 0x00000185, // SC_PERF_SEL_SC_SCF_SCB_INTERFACE_BUSY number of cycles of sc backend(s) interface busy ; Where measured: sc backend ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_SCB_BUSY = 0x00000186, // SC_PERF_SEL_SC_SCB_BUSY number of cycles of scb busy (second sc backend tile if present) ; Where measured: scb interface; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_STARVED_BY_PA_WITH_UNSELECTED_PA_NOT_EMPTY = 0x00000187, // SC_PERF_SEL_SC_STARVED_BY_PA_WITH_UNSELECTED_PA_NOT_EMPTY sc starved by pa with a unselected pa fifo not empty (use if more than one pa only) ; Where measured: sc_prim_setup; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_STARVED_BY_PA_WITH_UNSELECTED_PA_FULL = 0x00000188, // SC_PERF_SEL_SC_STARVED_BY_PA_WITH_UNSELECTED_PA_FULL sc starved by pa with a unselected pa fifo full (use if more than one pa only) This means that inside the draw packet the SC selected fifo has no valid data, and that one of the unselected fifo's has gone full. ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; + SC_PBB_BIN_HIST_NUM_PRIMS = 0x00000189, // SC_PERF_SEL_SC_PBB_BIN_HIST_NUM_PRIMS histogram of the number of primitives in a bin ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_0::BIN_HIST_NUM_PRIMS_THRESHOLD + SC_PBB_BATCH_HIST_NUM_PRIMS = 0x0000018a, // SC_PERF_SEL_SC_PBB_BATCH_HIST_NUM_PRIMS histogram of the number of primitives in a batch.; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_0::BATCH_HIST_NUM_PRIMS_THRESHOLD + SC_PBB_BIN_HIST_NUM_CONTEXTS = 0x0000018b, // SC_PERF_SEL_SC_PBB_BIN_HIST_NUM_CONTEXTS histogram of the number of contexts in a bin. See PA_SC_BINNER_PERF_CNTL_0; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_0::BIN_HIST_NUM_CONTEXT_THRESHOLD + SC_PBB_BATCH_HIST_NUM_CONTEXTS = 0x0000018c, // SC_PERF_SEL_SC_PBB_BATCH_HIST_NUM_CONTEXTS histogram of the number of contexts in a batch.; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_0::BATCH_HIST_NUM_CONTEXT_THRESHOLD + SC_PBB_BIN_HIST_NUM_PERSISTENT_STATES = 0x0000018d, // SC_PERF_SEL_SC_PBB_BIN_HIST_NUM_PERSISTENT_STATES histogram of the number of persistent states in a bin.; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_1::BIN_HIST_NUM_PERSISTENT_STATE_THRESHOLD + SC_PBB_BATCH_HIST_NUM_PERSISTENT_STATES = 0x0000018e, // SC_PERF_SEL_SC_PBB_BATCH_HIST_NUM_PERSISTENT_STATES histogram of the number of persistent states in a batch .; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_1::BATCH_HIST_NUM_PERSISTENT_STATE_THRESHOLD + SC_PBB_BATCH_HIST_NUM_PS_WAVE_BREAKS = 0x0000018f, // SC_PERF_SEL_SC_PBB_BATCH_HIST_NUM_PS_WAVE_BREAKS histogram of the number of Pixel Shader waves breaks in a batch.; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_3::BATCH_HIST_NUM_PS_WAVE_BREAKS_THRESHOLD + SC_PBB_BATCH_HIST_NUM_TRIV_REJECTED_PRIMS = 0x00000190, // SC_PERF_SEL_SC_PBB_BATCH_HIST_NUM_TRIV_REJECTED_PRIMS histogram of the number of trivially rejected primitives in a batch.; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_1::BATCH_HIST_NUM_TRIV_REJECTED_PRIMS_THRESHOLD + SC_PBB_BATCH_HIST_NUM_ROWS_PER_PRIM = 0x00000191, // SC_PERF_SEL_SC_PBB_BATCH_HIST_NUM_ROWS_PER_PRIM histogram of the number of rows per primitive in a batch.; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_2::BATCH_HIST_NUM_ROWS_PER_PRIM_THRESHOLD + SC_PBB_BATCH_HIST_NUM_COLUMNS_PER_ROW = 0x00000192, // SC_PERF_SEL_SC_PBB_BATCH_HIST_NUM_COLUMNS_PER_ROW histogram of the number columns per row in a batch.; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. ; See register control PA_SC_BINNER_PERF_CNTL_2::BATCH_HIST_NUM_COLUMNS_PER_ROW_THRESHOLD + SC_PBB_BUSY = 0x00000193, // SC_PERF_SEL_SC_PBB_BUSY overall count of the clock cycles that the pbb is busy ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BUSY_AND_NO_SENDS = 0x00000194, // SC_PERF_SEL_SC_PBB_BUSY_AND_NO_SENDS the number of clocks when the binner doesn't send anything to the SC but PBB is busy ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_STALLS_PA_DUE_TO_NO_TILES = 0x00000195, // SC_PERF_SEL_SC_PBB_STALLS_PA_DUE_TO_NO_TILES the number of cycles the PBB stalls the PA because there is a backlog of work in the SC ; Where measured: sc_prim_setup ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_NUM_BINS = 0x00000196, // SC_PERF_SEL_SC_PBB_NUM_BINS overall count of the number of bins used by the pbb ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_END_OF_BIN = 0x00000197, // SC_PERF_SEL_SC_PBB_END_OF_BIN number of times the PBB hit the end of the current bin ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_END_OF_BATCH = 0x00000198, // SC_PERF_SEL_SC_PBB_END_OF_BATCH number of times the PBB hit the end of a current batch that was accumulated ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_PRIMBIN_PROCESSED = 0x00000199, // SC_PERF_SEL_SC_PBB_PRIMBIN_PROCESSED number of times a primitive was processed in a bin ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_PRIM_ADDED_TO_BATCH = 0x0000019a, // SC_PERF_SEL_SC_PBB_PRIM_ADDED_TO_BATCH number of times a primitive was added to a batch ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_NONBINNED_PRIM = 0x0000019b, // SC_PERF_SEL_SC_PBB_NONBINNED_PRIM number of non-binned primitives ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_TOTAL_REAL_PRIMS_OUT_OF_PBB = 0x0000019c, // SC_PERF_SEL_SC_PBB_TOTAL_REAL_PRIMS_OUT_OF_PBB number of real primitives out of the PBB ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_TOTAL_NULL_PRIMS_OUT_OF_PBB = 0x0000019d, // SC_PERF_SEL_SC_PBB_TOTAL_NULL_PRIMS_OUT_OF_PBB number of null primitives out of the PBB ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_IDLE_CLK_DUE_TO_ROW_TO_COLUMN_TRANSITION = 0x0000019e, // SC_PERF_SEL_SC_PBB_IDLE_CLK_DUE_TO_ROW_TO_COLUMN_TRANSITION number of idle clocks due to transition from VSpan machine to the HSpan machine ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_IDLE_CLK_DUE_TO_FALSE_POSITIVE_ON_ROW = 0x0000019f, // SC_PERF_SEL_SC_PBB_IDLE_CLK_DUE_TO_FALSE_POSITIVE_ON_ROW number of idle clocks due to false positive on row ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_IDLE_CLK_DUE_TO_FALSE_POSITIVE_ON_COLUMN = 0x000001a0, // SC_PERF_SEL_SC_PBB_IDLE_CLK_DUE_TO_FALSE_POSITIVE_ON_COLUMN number of idle clocks due to false positive on column ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_PERSISTENT_STATE = 0x000001a1, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_PERSISTENT_STATE number of batch breaks caused by persistent state ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_CONTEXT_STATE = 0x000001a2, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_CONTEXT_STATE number of batch breaks caused by context state ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_PRIM = 0x000001a3, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_PRIM number of batch breaks caused by primitives ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_PC_STORAGE = 0x000001a4, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_PC_STORAGE number of batch breaks caused by PC storage ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_EVENT = 0x000001a5, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_EVENT number of batch breaks caused by events ; Where measured: sc_prim_setup ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_FPOV_LIMIT = 0x000001a6, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_FPOV_LIMIT number of batch breaks caused by hitting the first_prim_of_vector limit ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_POPS_INTRA_WAVE_OVERLAPS = 0x000001a7, // SC_PERF_SEL_SC_POPS_INTRA_WAVE_OVERLAPS number of times there is an intra-wave overlap ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2, or RB+ (GPU__GC__DBL_COLOR_WRITES__1)) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_POPS_FORCE_EOV = 0x000001a8, // SC_PERF_SEL_SC_POPS_FORCE_EOV number of times the packer forces and end-of-vector due to an intra-wave overlap ; Where measured: sc backend packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PKR_QUAD_OVLP_NOT_FOUND_IN_WAVE_TABLE_AND_WAVES_SINCE_OVLP_SET_TO_MAX = 0x000001a9, // SC_PERF_SEL_SC_PKR_QUAD_OVLP_NOT_FOUND_IN_WAVE_TABLE_AND_WAVES_SINCE_OVLP_SET_TO_MAX number of times a quad overlap occurs but it is not found in the packer's wave table and there is not an intra-wave overlap. Waves_since_overlap set to the maximum value. ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2, or RB+ (GPU__GC__DBL_COLOR_WRITES__1)) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PKR_QUAD_OVLP_NOT_FOUND_IN_WAVE_TABLE_AND_NO_CHANGE_TO_WAVES_SINCE_OVLP = 0x000001aa, // SC_PERF_SEL_SC_PKR_QUAD_OVLP_NOT_FOUND_IN_WAVE_TABLE_AND_NO_CHANGE_TO_WAVES_SINCE_OVLP number of times a quad overlap occurs but it is not found in the packer's wave table and there is not an intra-wave overlap. Waves_since_overlap not changed due to a previously overlapping quad in the wavefront. ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2, or RB+ (GPU__GC__DBL_COLOR_WRITES__1)) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PKR_QUAD_OVLP_FOUND_IN_WAVE_TABLE = 0x000001ab, // SC_PERF_SEL_SC_PKR_QUAD_OVLP_FOUND_IN_WAVE_TABLE number of times a quad overlap occurs, it is found in the packer's wave table and there is not an intra-wave overlap ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2, or RB+ (GPU__GC__DBL_COLOR_WRITES__1)) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_FULL_FULL_QUAD = 0x000001ac, // SC_PERF_SEL_SC_FULL_FULL_QUAD disclosure INTERNAL SC_FULL_FULL_QUAD number of quads at log2_xscale=log2_yscale=0 ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_FULL_HALF_QUAD = 0x000001ad, // SC_PERF_SEL_SC_FULL_HALF_QUAD disclosure INTERNAL SC_FULL_HALF_QUAD number of quads at log2_xscale=0, log2_yscale=1 ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_FULL_QTR_QUAD = 0x000001ae, // SC_PERF_SEL_SC_FULL_QTR_QUAD disclosure INTERNAL SC_FULL_QTR_QUAD number of quads at log2_xscale=0, log2_yscale=2 ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_HALF_FULL_QUAD = 0x000001af, // SC_PERF_SEL_SC_HALF_FULL_QUAD disclosure INTERNAL SC_HALF_FULL_QUAD number of quads at log2_xscale=1, log2_yscale=0 ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_HALF_HALF_QUAD = 0x000001b0, // SC_PERF_SEL_SC_HALF_HALF_QUAD disclosure INTERNAL SC_HALF_HALF_QUAD number of quads at log2_xscale=1, log2_yscale=1 ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_HALF_QTR_QUAD = 0x000001b1, // SC_PERF_SEL_SC_HALF_QTR_QUAD disclosure INTERNAL SC_HALF_QTR_QUAD number of quads at log2_xscale=1, log2_yscale=2 ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_QTR_FULL_QUAD = 0x000001b2, // SC_PERF_SEL_SC_QTR_FULL_QUAD disclosure INTERNAL SC_QTR_FULL_QUAD number of quads at log2_xscale=2, log2_yscale=0 ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_QTR_HALF_QUAD = 0x000001b3, // SC_PERF_SEL_SC_QTR_HALF_QUAD disclosure INTERNAL SC_QTR_HALF_QUAD number of quads at log2_xscale=2, log2_yscale=1 ; Where measured: sc backend packer ; increment rate 1 or 2 (if num_db_per_packer=2) per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_QTR_QTR_QUAD = 0x000001b4, // SC_PERF_SEL_SC_QTR_QTR_QUAD disclosure INTERNAL SC_QTR_QTR_QUAD number of quads at log2_xscale=2, log2_yscale=2 ; Where measured: sct ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_GRP5_DYN_SCLK_BUSY = 0x000001b5, // SC_PERF_SEL_SC_GRP5_DYN_SCLK_BUSY number of cycles pbb dynamic clock is busy ; Where measured: sct ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_GRP6_DYN_SCLK_BUSY = 0x000001b6, // SC_PERF_SEL_SC_GRP6_DYN_SCLK_BUSY number of cycles pff_zff_mem dynamic clock is busy ; Where measured: sct ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_GRP7_DYN_SCLK_BUSY = 0x000001b7, // SC_PERF_SEL_SC_GRP7_DYN_SCLK_BUSY number of cycles vport_reg dynamic clock is busy ; Where measured: sct ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_GRP8_DYN_SCLK_BUSY = 0x000001b8, // SC_PERF_SEL_SC_GRP8_DYN_SCLK_BUSY number of cycles scrn_ext_reg dynamic clock is busy ; Where measured: sct ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_GRP9_DYN_SCLK_BUSY = 0x000001b9, // SC_PERF_SEL_SC_GRP9_DYN_SCLK_BUSY number of cycles other_special_reg dynamic clock is busy ; Where measured: sct ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PS_TO_BE_SCLK_GATE_STALL = 0x000001ba, // SC_PERF_SEL_SC_PS_TO_BE_SCLK_GATE_STALL clock gate stall (ps_to_be_stall) from output of pbb to SC output interface. Used to clock-gate on stall frontend prim setup clock group 0 ; Where measured: sct ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PA_TO_PBB_SCLK_GATE_STALL_STALL = 0x000001bb, // SC_PERF_SEL_SC_PA_TO_PBB_SCLK_GATE_STALL_STALL clock gate stall (pa_to_pbb_stall) from PA_SC interface to output of PBB. Used to clock-gate on stall frontend sc_pbb_dyn_sclk. ; Where measured: sct ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PK_BUSY = 0x000001bc, // SC_PERF_SEL_SC_PK_BUSY SC packer is busy with valid data in its fifo's and pipe stages. ; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PK_MAX_DEALLOC_FORCE_EOV = 0x000001bd, // SC_PERF_SEL_SC_PK_MAX_DEALLOC_FORCE_EOV SC Packer forced a end of vector cause by hitting accumulated max deallocs allowed in wave front as determined by MAX_DEALLOCS_IN_WAVE.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PK_DEALLOC_WAVE_BREAK = 0x000001be, // SC_PERF_SEL_SC_PK_DEALLOC_WAVE_BREAK SC Packer caused a PS wave break when prim dealloc could exceed the pixel row dealloc size.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_SPI_SEND = 0x000001bf, // SC_PERF_SEL_SC_SPI_SEND SC_SPI interface valid data send. ; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_SPI_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x000001c0, // SC_PERF_SEL_SC_SPI_CREDIT_AT_ZERO_WITH_PENDING_SEND SC has pending data to send to the SPI but is stalled by a zero interface free credits ; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_SPI_CREDIT_AT_MAX = 0x000001c1, // SC_PERF_SEL_SC_SPI_CREDIT_AT_MAX SC_SPI interface credit pool is at it's max value determined by PA_SC_IF_FIFO_SIZE::SC_SPI_IF_FIFO_SIZE; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_SPI_CREDIT_AT_MAX_NO_PENDING_SEND = 0x000001c2, // SC_PERF_SEL_SC_SPI_CREDIT_AT_MAX_NO_PENDING_SEND SC_SPI interface credit pool is at it's max value determined by PA_SC_IF_FIFO_SIZE::SC_SPI_IF_FIFO_SIZE and the sc has no pending data; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_BCI_SEND = 0x000001c3, // SC_PERF_SEL_SC_BCI_SEND SC_BCI interface valid data send. ; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_BCI_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x000001c4, // SC_PERF_SEL_SC_BCI_CREDIT_AT_ZERO_WITH_PENDING_SEND SC has pending data to send to the BCI but is stalled by a zero interface free credits ; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_BCI_CREDIT_AT_MAX = 0x000001c5, // SC_PERF_SEL_SC_BCI_CREDIT_AT_MAX SC_BCI interface credit pool is at it's max value determined by PA_SC_IF_FIFO_SIZE::SC_BCI_IF_FIFO_SIZE; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_BCI_CREDIT_AT_MAX_NO_PENDING_SEND = 0x000001c6, // SC_PERF_SEL_SC_BCI_CREDIT_AT_MAX_NO_PENDING_SEND SC_BCI interface credit pool is at it's max value determined by PA_SC_IF_FIFO_SIZE::SC_BCI_IF_FIFO_SIZE and the sc has no pending data; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_SPIBC_FULL_FREEZE = 0x000001c7, // SC_PERF_SEL_SC_SPIBC_FULL_FREEZE The logic or of spi and bci credit freeze due to either interface having no credits available.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PW_BM_PASS_EMPTY_PRIM = 0x000001c8, // SC_PERF_SEL_SC_PW_BM_PASS_EMPTY_PRIM Supertile walker is passing a empty/null prim as marked by the prim setup engine (null, flipped).; Where measured: sc_course_walker to backend mapper ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, valid for INSTANCE_INDEX=0 only. + SC_SUPERTILE_COUNT_EXCLUDE_PASS_EMPTY_PRIM = 0x000001c9, // SC_PERF_SEL_SC_SUPERTILE_COUNT_EXCLUDE_PASS_EMPTY_PRIM Count of supertiles generated excuding pass empty prims.; Where measured: sc_course_walker to backend mapper ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, valid for INSTANCE_INDEX=0 only. + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H0 = 0x000001ca, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H0 prims with < 2 supertiles ; Applicable comments to all SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H* histogram counters: Where measured: sc course walker output to backend mapper (sc_prim_walk) ; increment rate 1 per clock ; range-1/clk. SC_PERF_SEL_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H* histogram counter bins limited to 20 bit binary count, regarless of selected perfcounter range; CONTEXT_STATE_SENSITIVE=YES; Results reported per SE, results valid for sc frontend (INSTANCE_INDEX=0) only; + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H1 = 0x000001cb, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H1 prims with < 4 supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H2 = 0x000001cc, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H2 prims with < 8 supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H3 = 0x000001cd, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H3 prims with < 16 supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H4 = 0x000001ce, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H4 prims with < 32 supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H5 = 0x000001cf, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H5 prims with < 64 supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H6 = 0x000001d0, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H6 prims with < 128 supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H7 = 0x000001d1, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H7 prims with < 256 supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H8 = 0x000001d2, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H8 prims with < 512 supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H9 = 0x000001d3, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H9 prims with < 1K supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H10 = 0x000001d4, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H10 prims with < 2K supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H11 = 0x000001d5, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H11 prims with < 4K supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H12 = 0x000001d6, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H12 prims with < 8K supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H13 = 0x000001d7, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H13 prims with < 16K supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H14 = 0x000001d8, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H14 prims with < 32K supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H15 = 0x000001d9, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H15 prims with < 64K supertiles + SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H16 = 0x000001da, // SC_PERF_SEL_SC_SUPERTILE_PER_PRIM_EXCLUDE_PASS_EMPTY_PRIM_H16 prims with < 1M supertiles + SC_DB0_TILE_INTERFACE_BUSY = 0x000001db, // SC_PERF_SEL_SC_DB0_TILE_INTERFACE_BUSY Count of sc_db_tile interface busy clock cycles for db pipe0.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB0_TILE_INTERFACE_SEND = 0x000001dc, // SC_PERF_SEL_SC_DB0_TILE_INTERFACE_SEND Count of sc_db_tile send operations for db pipe0.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB0_TILE_INTERFACE_SEND_EVENT = 0x000001dd, // SC_PERF_SEL_SC_DB0_TILE_INTERFACE_SEND_EVENT Count of sc_db_tile send operations for events on db pipe0.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB0_TILE_INTERFACE_SEND_SOP_ONLY_EVENT = 0x000001de, // SC_PERF_SEL_SC_DB0_TILE_INTERFACE_SEND_SOP_ONLY_EVENT Count of sc_db_tile send start-of-primitive event operations for db pipe0.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB0_TILE_INTERFACE_SEND_SOP = 0x000001df, // SC_PERF_SEL_SC_DB0_TILE_INTERFACE_SEND_SOP Count of sc_db_tile start-of-primitive count operations for db pipe0.; Where measured: sc to db tile interface; increment rate 1-2 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB0_TILE_INTERFACE_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x000001e0, // SC_PERF_SEL_SC_DB0_TILE_INTERFACE_CREDIT_AT_ZERO_WITH_PENDING_SEND Count of sc_db_tile interface clocks with credits at zero with pending send date.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB0_TILE_INTERFACE_CREDIT_AT_MAX = 0x000001e1, // SC_PERF_SEL_SC_DB0_TILE_INTERFACE_CREDIT_AT_MAX Count of sc_db_tile interface clocks with interface credits at max for db pipe0.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB0_TILE_INTERFACE_CREDIT_AT_MAX_WITH_NO_PENDING_SEND = 0x000001e2, // SC_PERF_SEL_SC_DB0_TILE_INTERFACE_CREDIT_AT_MAX_WITH_NO_PENDING_SEND Count of sc_db_tile interface clocks with credit at max with no pending send for db pipe0.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB1_TILE_INTERFACE_BUSY = 0x000001e3, // SC_PERF_SEL_SC_DB1_TILE_INTERFACE_BUSY Count of sc_db_tile interface busy clock cycles for db pipe1.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB1_TILE_INTERFACE_SEND = 0x000001e4, // SC_PERF_SEL_SC_DB1_TILE_INTERFACE_SEND Count of sc_db_tile send operations for db pipe1.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB1_TILE_INTERFACE_SEND_EVENT = 0x000001e5, // SC_PERF_SEL_SC_DB1_TILE_INTERFACE_SEND_EVENT Count of sc_db_tile send operations for events on db pipe1.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB1_TILE_INTERFACE_SEND_SOP_ONLY_EVENT = 0x000001e6, // SC_PERF_SEL_SC_DB1_TILE_INTERFACE_SEND_SOP_ONLY_EVENT Count of sc_db_tile send start-of-primitive event operations for db pipe1.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB1_TILE_INTERFACE_SEND_SOP = 0x000001e7, // SC_PERF_SEL_SC_DB1_TILE_INTERFACE_SEND_SOP Count of sc_db_tile start-of-primitive count operations for db pipe1.; Where measured: sc to db tile interface; increment rate 1-2 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB1_TILE_INTERFACE_CREDIT_AT_ZERO_WITH_PENDING_SEND = 0x000001e8, // SC_PERF_SEL_SC_DB1_TILE_INTERFACE_CREDIT_AT_ZERO_WITH_PENDING_SEND Count of sc_db_tile interface clocks with credits at zero with pending send data for db pipe1.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB1_TILE_INTERFACE_CREDIT_AT_MAX = 0x000001e9, // SC_PERF_SEL_SC_DB1_TILE_INTERFACE_CREDIT_AT_MAX Count of sc_db_tile interface clocks with interface credits at max for db pipe1.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_DB1_TILE_INTERFACE_CREDIT_AT_MAX_WITH_NO_PENDING_SEND = 0x000001ea, // SC_PERF_SEL_SC_DB1_TILE_INTERFACE_CREDIT_AT_MAX_WITH_NO_PENDING_SEND Count of sc_db_tile interface clocks with credit at max with no pending send for db pipe1.; Where measured: sc to db tile interface; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, and per packer (instance_index indicates packer number). + SC_BACKEND_PRIM_FIFO_FULL = 0x000001eb, // SC_PERF_SEL_SC_BACKEND_PRIM_FIFO_FULL number of cycles of backend prim fifo full ; Where measured: sc_backend ; increment rate-one per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. + SC_PBB_BATCH_BREAK_DUE_TO_TIMEOUT_COUNTER = 0x000001ec, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_TIMEOUT_COUNTER timeout counter breaks the batch; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_NONBINNED_BATCH = 0x000001ed, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_NONBINNED_BATCH Non-binned batch break because input is empty and there is no back pressure; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_DEBUG_DATA_PER_DRAW_DISPATCH = 0x000001ee, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_DEBUG_DATA_PER_DRAW_DISPATCH Debug data per draw dispatch breaks the batch ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_OVERRIDE_REGISTER_PERSISTENT = 0x000001ef, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_OVERRIDE_REGISTER_PERSISTENT Override register limit persistent states ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_OVERRIDE_REGISTER_CONTEXT = 0x000001f0, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_OVERRIDE_REGISTER_CONTEXT Override register limit context states ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_OVERRIDE_REGISTER_FPOV = 0x000001f1, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_OVERRIDE_REGISTER_FPOV Override register limit FPOV ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_NEW_SC_MODE = 0x000001f2, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_NEW_SC_MODE Break batch because NEW_SC mode ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_BINNING_MODE_CHANGE = 0x000001f3, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_BINNING_MODE_CHANGE Break batch because of binning mode change ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_PIPELINE_EVENT_COUNT = 0x000001f4, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_PIPELINE_EVENT_COUNT Break batch because of pipeline event count ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_PIPE_RESET = 0x000001f5, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_PIPE_RESET Break batch because of pipe reset ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_PBB_BATCH_BREAK_DUE_TO_GFX_PIPE_CHANGE = 0x000001f6, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_GFX_PIPE_CHANGE Break batch because of gfx pipe change ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only. + SC_STALLED_BY_DB0_TILEFIFO = 0x000001f7, // SC_PERF_SEL_SC_STALLED_BY_DB0_TILEFIFO sc stalled by DB0 pipe's quadmask_z tile fifo going full. (Non harvestable). ; Where measured: sc_qdmsk_z(s) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB0_QUAD_INTF_SEND = 0x000001f8, // SC_PERF_SEL_SC_DB0_QUAD_INTF_SEND (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB0_QUAD_INTF_BUSY = 0x000001f9, // SC_PERF_SEL_SC_DB0_QUAD_INTF_BUSY sc_db0_quad_data interface credits at non-zero or pending send (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB0_QUAD_INTF_STALLED_BY_DB = 0x000001fa, // SC_PERF_SEL_SC_DB0_QUAD_INTF_STALLED_BY_DB sc_db0_quad_data interface credits at zero with pending data available to send (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB0_QUAD_INTF_CREDIT_AT_MAX = 0x000001fb, // SC_PERF_SEL_SC_DB0_QUAD_INTF_CREDIT_AT_MAX sc_db0_quad_data interface credits at maximum value (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB0_QUAD_INTF_IDLE = 0x000001fc, // SC_PERF_SEL_SC_DB0_QUAD_INTF_IDLE sc_db0_quad_data interface credits at maximum value with no pending send (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB1_QUAD_INTF_SEND = 0x000001fd, // SC_PERF_SEL_SC_DB1_QUAD_INTF_SEND (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_STALLED_BY_DB1_TILEFIFO = 0x000001fe, // SC_PERF_SEL_SC_STALLED_BY_DB1_TILEFIFO sc stalled by DB1 pipe's quadmask_z tile fifo going full. (Non harvestable). ; Where measured: sc_qdmsk_z(s) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB1_QUAD_INTF_BUSY = 0x000001ff, // SC_PERF_SEL_SC_DB1_QUAD_INTF_BUSY sc_db0_quad_data interface credits at non-zero or pending send (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB1_QUAD_INTF_STALLED_BY_DB = 0x00000200, // SC_PERF_SEL_SC_DB1_QUAD_INTF_STALLED_BY_DB sc_db1_quad_data interface credits at zero with pending data available to send (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB1_QUAD_INTF_CREDIT_AT_MAX = 0x00000201, // SC_PERF_SEL_SC_DB1_QUAD_INTF_CREDIT_AT_MAX sc_db1_quad_data interface credits at maximum value (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB1_QUAD_INTF_IDLE = 0x00000202, // SC_PERF_SEL_SC_DB1_QUAD_INTF_IDLE sc_db1_quad_data interface credits at maximum value with no pending send (Non Harvestable) ; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PKR_WAVE_BREAK_OUTSIDE_REGION = 0x00000203, // SC_PERF_SEL_SC_PKR_WAVE_BREAK_OUTSIDE_REGION SC Packer caused a wave break only due to XY of next quad slot being outside the region ; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PKR_WAVE_BREAK_FULL_TILE = 0x00000204, // SC_PERF_SEL_SC_PKR_WAVE_BREAK_FULL_TILE SC Packer caused a wave break only due to a valid fully covered tile being receieved ; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_FSR_WALKED = 0x00000205, // SC_PERF_SEL_SC_FSR_WALKED Compute the number of FBW bins walked by dividing SC_FSR_WALKED by SC_PBB_TOTAL_REAL_PRIMS_OUT_OF_PBB; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PBB_EMPTY_INPUT_CYCLE_WHEN_BATCH_OPEN = 0x00000206, // SC_PERF_SEL_SC_PBB_EMPTY_INPUT_CYCLE_WHEN_BATCH_OPEN This will count bubbles in input stream when PBB have binned batch open and it is ready to read more inputs (input stream is sparse) ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_PBB_BATCH_BREAK_DUE_TO_NULL_PRIM_BREAK_BATCH_LIMIT = 0x00000207, // SC_PERF_SEL_SC_PBB_BATCH_BREAK_DUE_TO_NULL_PRIM_BREAK_BATCH_LIMIT Break batch because of null prim break batch limit ; Where measured: sc primitive batch binner if present (PBB) ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO ; Results reported per SE, INSTANCE_INDEX=0 to num_packer_per_sc-1. Results valid for instance 0 only; + SC_DB0_WE_STALLED_BY_RSLT_FIFO_FULL = 0x00000208, // SC_PERF_SEL_SC_DB0_WE_STALLED_BY_RSLT_FIFO_FULL DB0 quad processsor stalled by tile cull result fifo full; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB0_WE_TILE_MASK_RETURN_FIFO_FULL_WITH_WE_RSLT_FIFO_STALL = 0x00000209, // SC_PERF_SEL_SC_DB0_WE_TILE_MASK_RETURN_FIFO_FULL_WITH_WE_RSLT_FIFO_STALL quad processsor stalled by tile cull result fifo full and dn_sc tile mask return FIFO full.; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB0_TILE_MASK_FIFO_FULL = 0x0000020a, // SC_PERF_SEL_SC_DB0_TILE_MASK_FIFO_FULL DB0 quad processsor db_sc_tile mask interface FIFO full; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB1_WE_STALLED_BY_RSLT_FIFO_FULL = 0x0000020b, // SC_PERF_SEL_SC_DB1_WE_STALLED_BY_RSLT_FIFO_FULL DB1 quad processsor stalled by tile cull result fifo full; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB1_WE_TILE_MASK_RETURN_FIFO_FULL_WITH_WE_RSLT_FIFO_STALL = 0x0000020c, // SC_PERF_SEL_SC_DB1_WE_TILE_MASK_RETURN_FIFO_FULL_WITH_WE_RSLT_FIFO_STALL quad processsor stalled by tile cull result fifo full and dn_sc tile mask return FIFO full.; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_DB1_TILE_MASK_FIFO_FULL = 0x0000020d, // SC_PERF_SEL_SC_DB1_TILE_MASK_FIFO_FULL DB1 quad processsor db_sc_tile mask interface FIFO full; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PS_PM_PBB_TO_PSE_FIFO_WE_STALL_BY_PFF_PW_FULL = 0x0000020e, // SC_PERF_SEL_SC_PS_PM_PBB_TO_PSE_FIFO_WE_STALL_BY_PFF_PW_FULL Prim setup PBB out stalled by prim fifo front full.; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PS_PM_PBB_TO_PSE_FIFO_WE_STALL_BY_ZFF_PW_FULL = 0x0000020f, // SC_PERF_SEL_SC_PS_PM_PBB_TO_PSE_FIFO_WE_STALL_BY_ZFF_PW_FULL Prim setup PBB out stalled by Z FIFO full.; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PS_PM_PBB_TO_PSE_FIFO_WE_STALL_BY_PBB_TO_PSE_FIFO_FULL = 0x00000210, // SC_PERF_SEL_SC_PS_PM_PBB_TO_PSE_FIFO_WE_STALL_BY_PBB_TO_PSE_FIFO_FULL Prim setup PBB out stalled by prim setup engine FIFO full.; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PS_PM_PFF_PW_FULL = 0x00000211, // SC_PERF_SEL_SC_PS_PM_PFF_PW_FULL Prim setup Prim FIFO FRONT FULL.; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PS_PM_ZFF_PW_FULL = 0x00000212, // SC_PERF_SEL_SC_PS_PM_ZFF_PW_FULL Prim setup ZFIFO FRONT FULL.; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PS_PM_PBB_TO_PSE_FIFO_FULL = 0x00000213, // SC_PERF_SEL_SC_PS_PM_PBB_TO_PSE_FIFO_FULL Prim setup Prim Setup Engine FIFO FULL.; Where measured: sc_quad_proc ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_QD1_FD_CONFLICT_WAVE_BRK_1H = 0x00000214, // SC_PERF_SEL_SC_PK_PM_QD1_FD_CONFLICT_WAVE_BRK_1H Packer One-Hot wave break QD1 slot (non RB+ only) First and Dealloc Conflict.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_QD1_FORCE_PARTIAL_FOR_DEALLOC_WAVE_BRK_1H = 0x00000215, // SC_PERF_SEL_SC_PK_PM_QD1_FORCE_PARTIAL_FOR_DEALLOC_WAVE_BRK_1H Packer One-Hot wave break QD1 slot (non RB+ only) force partail for dealloc.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_QD1_AVOID_DEALLOC_ADD_WAVE_BRK_1H = 0x00000216, // SC_PERF_SEL_SC_PK_PM_QD1_AVOID_DEALLOC_ADD_WAVE_BRK_1H Packer One-Hot wave break QD1 slot (non RB+ only) avaoid dealloc add.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_4X2_SPLIT_WAVE_BRK_1H = 0x00000217, // SC_PERF_SEL_SC_PK_PM_4X2_SPLIT_WAVE_BRK_1H Packer One-Hot wave break RB+ heuristic 4x2 quad Split (RB+ only).; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_PKR_FILL_4X2_WAVE_BRK_1H = 0x00000218, // SC_PERF_SEL_SC_PK_PM_PKR_FILL_4X2_WAVE_BRK_1H Packer One-Hot wave break RB+ heuristic 4x2 quad fill (RB+ only)..; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_SPLIT_OR_FILL_4X2_WAVE_BRK_1H = 0x00000219, // SC_PERF_SEL_SC_PK_PM_SPLIT_OR_FILL_4X2_WAVE_BRK_1H Packer One-Hot wave break RB+ heuristic 4x2 quad fill or split (RB+ only).; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_END_OF_VECTOR_WAVE_BRK_1H = 0x0000021a, // SC_PERF_SEL_SC_PK_PM_END_OF_VECTOR_WAVE_BRK_1H Packer One-Hot wave break from wave lenght quad count limit.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_LAST_AND_DEALLOC_WAVE_BRK_1H = 0x0000021b, // SC_PERF_SEL_SC_PK_PM_LAST_AND_DEALLOC_WAVE_BRK_1H Packer One-Hot wave break from last and dealloc conflict.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_CTL_ONLY_CMD_WAVE_BRK_1H = 0x0000021c, // SC_PERF_SEL_SC_PK_PM_CTL_ONLY_CMD_WAVE_BRK_1H Packer One-Hot wave break for control only command.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_AVOID_DEALLOC_ADD_WAVE_BRK_1H = 0x0000021d, // SC_PERF_SEL_SC_PK_PM_AVOID_DEALLOC_ADD_WAVE_BRK_1H Packer One-Hot wave break for avoid dealloc add.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_FD_CONFLICT_WAVE_BRK_1H = 0x0000021e, // SC_PERF_SEL_SC_PK_PM_FD_CONFLICT_WAVE_BRK_1H Packer One-Hot wave break for first and dealloc conflict.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_FORCE_PARTIAL_FOR_DEALLOC_WAVE_BRK_1H = 0x0000021f, // SC_PERF_SEL_SC_PK_PM_FORCE_PARTIAL_FOR_DEALLOC_WAVE_BRK_1H Packer One-Hot wave break for dealloc.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_AE_CONFLICT_WAVE_BRK_1H = 0x00000220, // SC_PERF_SEL_SC_PK_PM_AE_CONFLICT_WAVE_BRK_1H Packer One-Hot wave break for any event.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_EOP_OR_LAD_WAVE_BRK_1H = 0x00000221, // SC_PERF_SEL_SC_PK_PM_EOP_OR_LAD_WAVE_BRK_1H Packer One-Hot wave break for end of packet or lad and dealloc.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_FULL_TILE_WAVE_BRK_1H = 0x00000222, // SC_PERF_SEL_SC_PK_PM_FULL_TILE_WAVE_BRK_1H Packer One-Hot wave break for full tile bit set in full tile wave break mode.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_POPS_FORCE_EOV_WAVE_BRK_1H = 0x00000223, // SC_PERF_SEL_SC_PK_PM_POPS_FORCE_EOV_WAVE_BRK_1H Packer One-Hot wave break for POPS end-of-vector.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_MAX_DEALLOC_FORCE_EOV_WAVE_BRK_1H = 0x00000224, // SC_PERF_SEL_SC_PK_PM_MAX_DEALLOC_FORCE_EOV_WAVE_BRK_1H Packer One-Hot wave break for maximum dealloc value hit.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_WAVE_BREAK_OUTSIDE_REGION_WAVE_BRK_1H = 0x00000225, // SC_PERF_SEL_SC_PK_PM_WAVE_BREAK_OUTSIDE_REGION_WAVE_BRK_1H Packer One-Hot wave break for quad hit outside programmed region break area.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_MAX_CLK_CNT_FORCE_EOV_WAVE_BRK_1H = 0x00000226, // SC_PERF_SEL_SC_PK_PM_MAX_CLK_CNT_FORCE_EOV_WAVE_BRK_1H Packer One-Hot wave break for max clock cont timer.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_MAX_REZ_CNT_FORCE_EOV_WAVE_BRK_1H = 0x00000227, // SC_PERF_SEL_SC_PK_PM_MAX_REZ_CNT_FORCE_EOV_WAVE_BRK_1H Packer One-Hot wave break for db rez hang count timer hit.; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_00_Y_00_QUAD = 0x00000228, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_00_Y_00_QUAD quads with VRS_RATE_X=2'b00 and VRS_RATE_Y=2'b00; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_00_Y_01_QUAD = 0x00000229, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_00_Y_01_QUAD quads with VRS_RATE_X=2'b00 and VRS_RATE_Y=2'b01; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_00_Y_10_QUAD = 0x0000022a, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_00_Y_10_QUAD quads with VRS_RATE_X=2'b00 and VRS_RATE_Y=2'b10; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_00_Y_11_QUAD = 0x0000022b, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_00_Y_11_QUAD quads with VRS_RATE_X=2'b00 and VRS_RATE_Y=2'b11; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_01_Y_00_QUAD = 0x0000022c, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_01_Y_00_QUAD quads with VRS_RATE_X=2'b01 and VRS_RATE_Y=2'b00; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_01_Y_01_QUAD = 0x0000022d, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_01_Y_01_QUAD quads with VRS_RATE_X=2'b01 and VRS_RATE_Y=2'b01; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_01_Y_10_QUAD = 0x0000022e, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_01_Y_10_QUAD quads with VRS_RATE_X=2'b01 and VRS_RATE_Y=2'b10; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_01_Y_11_QUAD = 0x0000022f, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_01_Y_11_QUAD quads with VRS_RATE_X=2'b01 and VRS_RATE_Y=2'b11; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_10_Y_00_QUAD = 0x00000230, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_10_Y_00_QUAD quads with VRS_RATE_X=2'b10 and VRS_RATE_Y=2'b00; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_10_Y_01_QUAD = 0x00000231, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_10_Y_01_QUAD quads with VRS_RATE_X=2'b10 and VRS_RATE_Y=2'b01; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_10_Y_10_QUAD = 0x00000232, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_10_Y_10_QUAD quads with VRS_RATE_X=2'b10 and VRS_RATE_Y=2'b10; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_10_Y_11_QUAD = 0x00000233, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_10_Y_11_QUAD quads with VRS_RATE_X=2'b10 and VRS_RATE_Y=2'b11; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_11_Y_00_QUAD = 0x00000234, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_11_Y_00_QUAD quads with VRS_RATE_X=2'b11 and VRS_RATE_Y=2'b00; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_11_Y_01_QUAD = 0x00000235, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_11_Y_01_QUAD quads with VRS_RATE_X=2'b11 and VRS_RATE_Y=2'b01; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_11_Y_10_QUAD = 0x00000236, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_11_Y_10_QUAD quads with VRS_RATE_X=2'b11 and VRS_RATE_Y=2'b10; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; + SC_PK_PM_VRS_RATE_X_11_Y_11_QUAD = 0x00000237, // SC_PERF_SEL_SC_PK_PM_VRS_RATE_X_11_Y_11_QUAD quads with VRS_RATE_X=2'b11 and VRS_RATE_Y=2'b11; Where measured: sc_packer ; increment rate 1 per clock ; range-1/clk ; CONTEXT_STATE_SENSITIVE=NO; Results reported per SE and INSTANCE_INDEX 0 to num_packer_per_sc-1; +} SC_PERFCOUNTER_SELECT; + +typedef enum SDMA_PERFCOUNTER_SELECT : unsigned int { + SDMA_PERF_SEL_CYCLE = 0x00000000, + SDMA_PERF_SEL_IDLE = 0x00000001, + SDMA_PERF_SEL_REG_IDLE = 0x00000002, + SDMA_PERF_SEL_RB_EMPTY = 0x00000003, + SDMA_PERF_SEL_RB_FULL = 0x00000004, + SDMA_PERF_SEL_RB_WPTR_WRAP = 0x00000005, + SDMA_PERF_SEL_RB_RPTR_WRAP = 0x00000006, + SDMA_PERF_SEL_RB_WPTR_POLL_READ = 0x00000007, + SDMA_PERF_SEL_RB_RPTR_WB = 0x00000008, + SDMA_PERF_SEL_RB_CMD_IDLE = 0x00000009, + SDMA_PERF_SEL_RB_CMD_FULL = 0x0000000a, + SDMA_PERF_SEL_IB_CMD_IDLE = 0x0000000b, + SDMA_PERF_SEL_IB_CMD_FULL = 0x0000000c, + SDMA_PERF_SEL_EX_IDLE = 0x0000000d, + SDMA_PERF_SEL_SRBM_REG_SEND = 0x0000000e, + SDMA_PERF_SEL_EX_IDLE_POLL_TIMER_EXPIRE = 0x0000000f, + SDMA_PERF_SEL_MC_WR_IDLE = 0x00000010, + SDMA_PERF_SEL_MC_WR_COUNT = 0x00000011, + SDMA_PERF_SEL_MC_RD_IDLE = 0x00000012, + SDMA_PERF_SEL_MC_RD_COUNT = 0x00000013, + SDMA_PERF_SEL_MC_RD_RET_STALL = 0x00000014, + SDMA_PERF_SEL_MC_RD_NO_POLL_IDLE = 0x00000015, + SDMA_PERF_SEL_DRM_IDLE = 0x00000016, + SDMA_PERF_SEL_DRM_REQ_STALL = 0x00000017, + SDMA_PERF_SEL_SEM_IDLE = 0x00000018, + SDMA_PERF_SEL_SEM_REQ_STALL = 0x00000019, + SDMA_PERF_SEL_SEM_REQ_COUNT = 0x0000001a, + SDMA_PERF_SEL_SEM_RESP_INCOMPLETE = 0x0000001b, + SDMA_PERF_SEL_SEM_RESP_FAIL = 0x0000001c, + SDMA_PERF_SEL_SEM_RESP_PASS = 0x0000001d, + SDMA_PERF_SEL_INT_IDLE = 0x0000001e, + SDMA_PERF_SEL_INT_REQ_STALL = 0x0000001f, + SDMA_PERF_SEL_INT_REQ_COUNT = 0x00000020, + SDMA_PERF_SEL_INT_RESP_ACCEPTED = 0x00000021, + SDMA_PERF_SEL_INT_RESP_RETRY = 0x00000022, + SDMA_PERF_SEL_NUM_PACKET = 0x00000023, + SDMA_PERF_SEL_DRM1_REQ_STALL = 0x00000024, + SDMA_PERF_SEL_CE_WREQ_IDLE = 0x00000025, + SDMA_PERF_SEL_CE_WR_IDLE = 0x00000026, + SDMA_PERF_SEL_CE_SPLIT_IDLE = 0x00000027, + SDMA_PERF_SEL_CE_RREQ_IDLE = 0x00000028, + SDMA_PERF_SEL_CE_OUT_IDLE = 0x00000029, + SDMA_PERF_SEL_CE_IN_IDLE = 0x0000002a, + SDMA_PERF_SEL_CE_DST_IDLE = 0x0000002b, + SDMA_PERF_SEL_CE_DRM_IDLE = 0x0000002c, + SDMA_PERF_SEL_CE_DRM1_IDLE = 0x0000002d, + SDMA_PERF_SEL_CE_AFIFO_FULL = 0x0000002e, + SDMA_PERF_SEL_CE_DRM_FULL = 0x0000002f, + SDMA_PERF_SEL_CE_DRM1_FULL = 0x00000030, + SDMA_PERF_SEL_CE_INFO_FULL = 0x00000031, + SDMA_PERF_SEL_CE_INFO1_FULL = 0x00000032, + SDMA_PERF_SEL_CE_RD_STALL = 0x00000033, + SDMA_PERF_SEL_CE_WR_STALL = 0x00000034, + SDMA_PERF_SEL_GFX_SELECT = 0x00000035, + SDMA_PERF_SEL_RLC0_SELECT = 0x00000036, + SDMA_PERF_SEL_RLC1_SELECT = 0x00000037, + SDMA_PERF_SEL_PAGE_SELECT = 0x00000038, + SDMA_PERF_SEL_CTX_CHANGE = 0x00000039, + SDMA_PERF_SEL_CTX_CHANGE_EXPIRED = 0x0000003a, + SDMA_PERF_SEL_CTX_CHANGE_EXCEPTION = 0x0000003b, + SDMA_PERF_SEL_DOORBELL = 0x0000003c, + SDMA_PERF_SEL_RD_BA_RTR = 0x0000003d, + SDMA_PERF_SEL_WR_BA_RTR = 0x0000003e, + SDMA_PERF_SEL_F32_L1_WR_VLD = 0x0000003f, + SDMA_PERF_SEL_CE_L1_WR_VLD = 0x00000040, + SDMA_PERF_SEL_CPF_SDMA_INVREQ = 0x00000041, + SDMA_PERF_SEL_SDMA_CPF_INVACK = 0x00000042, + SDMA_PERF_SEL_UTCL2_SDMA_INVREQ = 0x00000043, + SDMA_PERF_SEL_SDMA_UTCL2_INVACK = 0x00000044, + SDMA_PERF_SEL_UTCL2_SDMA_INVREQ_ALL = 0x00000045, + SDMA_PERF_SEL_SDMA_UTCL2_INVACK_ALL = 0x00000046, + SDMA_PERF_SEL_UTCL2_RET_XNACK = 0x00000047, + SDMA_PERF_SEL_UTCL2_RET_ACK = 0x00000048, + SDMA_PERF_SEL_UTCL2_FREE = 0x00000049, + SDMA_PERF_SEL_SDMA_UTCL2_SEND = 0x0000004a, + SDMA_PERF_SEL_DMA_L1_WR_SEND = 0x0000004b, + SDMA_PERF_SEL_DMA_L1_RD_SEND = 0x0000004c, + SDMA_PERF_SEL_DMA_MC_WR_SEND = 0x0000004d, + SDMA_PERF_SEL_DMA_MC_RD_SEND = 0x0000004e, + SDMA_PERF_SEL_GPUVM_INVREQ_HIGH = 0x0000004f, + SDMA_PERF_SEL_GPUVM_INVREQ_LOW = 0x00000050, + SDMA_PERF_SEL_L1_WRL2_IDLE = 0x00000051, + SDMA_PERF_SEL_L1_RDL2_IDLE = 0x00000052, + SDMA_PERF_SEL_L1_WRMC_IDLE = 0x00000053, + SDMA_PERF_SEL_L1_RDMC_IDLE = 0x00000054, + SDMA_PERF_SEL_L1_WR_INV_IDLE = 0x00000055, + SDMA_PERF_SEL_L1_RD_INV_IDLE = 0x00000056, + SDMA_PERF_SEL_META_L2_REQ_SEND = 0x00000057, + SDMA_PERF_SEL_L2_META_RET_VLD = 0x00000058, + SDMA_PERF_SEL_SDMA_UTCL2_RD_SEND = 0x00000059, + SDMA_PERF_SEL_UTCL2_SDMA_RD_RTN = 0x0000005a, + SDMA_PERF_SEL_SDMA_UTCL2_WR_SEND = 0x0000005b, + SDMA_PERF_SEL_UTCL2_SDMA_WR_RTN = 0x0000005c, + SDMA_PERF_SEL_META_REQ_SEND = 0x0000005d, + SDMA_PERF_SEL_META_RTN_VLD = 0x0000005e, + SDMA_PERF_SEL_TLBI_SEND = 0x0000005f, + SDMA_PERF_SEL_TLBI_RTN = 0x00000060, + SDMA_PERF_SEL_GCR_SEND = 0x00000061, + SDMA_PERF_SEL_GCR_RTN = 0x00000062, + SDMA_PERF_SEL_UTCL1_TAG_DELAY_COUNTER = 0x00000063, + SDMA_PERF_SEL_MMHUB_TAG_DELAY_COUNTER = 0x00000064, +} SDMA_PERFCOUNTER_SELECT; + +typedef enum SPI_PERFCOUNTER_SELECT : unsigned int { + SPI_PERF_VS_WINDOW_VALID = 0x00000000, // Clock count enabled by perfcounter_start event. + SPI_PERF_VS_BUSY = 0x00000001, // Number of clocks with outstanding waves (SPI or SH). + SPI_PERF_VS_FIRST_WAVE = 0x00000002, // Number of VS_IS_DS first waves + SPI_PERF_VS_LAST_WAVE = 0x00000003, // Number of VS_IS_DS last waves. + SPI_PERF_VS_LSHS_DEALLOC = 0x00000004, // Number of VS_IS_DS lds dealloc waves. + SPI_PERF_VS_POS0_STALL = 0x00000005, // Number of clocks stalled due to pos buf space in SA0. + SPI_PERF_VS_POS1_STALL = 0x00000006, // Number of clocks stalled due to pos buf space in SA1. + SPI_PERF_VS_CRAWLER_STALL = 0x00000007, // Number of clocks event/wave order fifo is full. + SPI_PERF_VS_EVENT_WAVE = 0x00000008, // Number of events and waves. + SPI_PERF_VS_WAVE = 0x00000009, // Number of waves + SPI_PERF_VS_PERS_UPD_FULL0 = 0x0000000a, // Number of clks VS persistent state update fifo0 is full. + SPI_PERF_VS_PERS_UPD_FULL1 = 0x0000000b, // Number of clks VS persistent state update fifo1 is full. + SPI_PERF_VS_LATE_ALLOC_FULL = 0x0000000c, // Number of clks VS late alloc fifo is full (preservation position buffer is full, can not launch more waves). + SPI_PERF_VS_FIRST_SUBGRP = 0x0000000d, // Number of first of subgroup waves. + SPI_PERF_VS_LAST_SUBGRP = 0x0000000e, // Number of last of subgroup waves. + SPI_PERF_VS_ALLOC_CNT = 0x0000000f, // Number of launched VS waves that rasterize (alloc export space) + SPI_PERF_VS_LATE_ALLOC_ACCUM = 0x00000010, // Accumulation of number of VS waves pending export allocation + SPI_PERF_GS_WINDOW_VALID = 0x00000011, // Clock count enabled by perfcounter_start event. + SPI_PERF_GS_BUSY = 0x00000012, // Number of clocks with outstanding waves (SPI or SH). + SPI_PERF_GS_CRAWLER_STALL = 0x00000013, // Number of clocks event/wave order fifo is full. + SPI_PERF_GS_EVENT_WAVE = 0x00000014, // Number of events and waves + SPI_PERF_GS_WAVE = 0x00000015, // Number of waves. + SPI_PERF_GS_PERS_UPD_FULL0 = 0x00000016, // Number of clks GS persistent state update fifo0 is full. + SPI_PERF_GS_PERS_UPD_FULL1 = 0x00000017, // Number of clks GS persistent state update fifo1 is full. + SPI_PERF_GS_FIRST_SUBGRP = 0x00000018, // Number of first of subgroup waves. + SPI_PERF_GS_LAST_SUBGRP = 0x00000019, // Number of last of subgroup waves. + SPI_PERF_GS_HS_DEALLOC = 0x0000001a, // Number of offchip hs dealloc events read from crawler. + SPI_PERF_GS_NGG_SE_LATE_ALLOC_LIMIT = 0x0000001b, // Number of clks this SE has reached allocation position or index buffer pre-reservation limits (can't launch more waves). + SPI_PERF_GS_GRP_FIFO_FULL = 0x0000001c, // GS Group FIFO full count + SPI_PERF_GS_POS0_STALL = 0x0000001d, // Number of clocks stalled due to pos buf space in SA0. + SPI_PERF_GS_POS1_STALL = 0x0000001e, // Number of clocks stalled due to pos buf space in SA1. + SPI_PERF_GS_INDX0_STALL = 0x0000001f, // Number of clocks stalled due to index buf space in SA0. + SPI_PERF_GS_INDX1_STALL = 0x00000020, // Number of clocks stalled due to index buf space in SA1. + SPI_PERF_HS_WINDOW_VALID = 0x00000021, // Clock count enabled by perfcounter_start event. + SPI_PERF_HS_BUSY = 0x00000022, // Number of clocks with outstanding waves (SPI or SH). + SPI_PERF_HS_CRAWLER_STALL = 0x00000023, // Number of clocks event/wave order fifo is full. + SPI_PERF_HS_FIRST_WAVE = 0x00000024, // Number of first waves. + SPI_PERF_HS_LAST_WAVE = 0x00000025, // Number of last waves. + SPI_PERF_HS_LSHS_DEALLOC = 0x00000026, // Number of offchip HS lds dealloc waves. + SPI_PERF_HS_OFFCHIP_LDS_STALL = 0x00000027, // Number of clks HS waits to allocate offchip LDS space. + SPI_PERF_HS_EVENT_WAVE = 0x00000028, // Number of events and waves. + SPI_PERF_HS_WAVE = 0x00000029, // Number of waves. + SPI_PERF_HS_PERS_UPD_FULL0 = 0x0000002a, // Number of clks HS persistent state update fifo0 is full. + SPI_PERF_HS_PERS_UPD_FULL1 = 0x0000002b, // Number of clks HS persistent state update fifo1 is full. + SPI_PERF_CSGN_WINDOW_VALID = 0x0000002c, // Clock count enabled by perfcounter_start event. Requires SPI_DEBUG_CNTL.DEBUG_GFX_PIPE_SEL to select source, DEBUG_GFX_PIPE_SEL = 0 , source is CSG PIPE0; DEBUG_GFX_PIPE_SEL = 1 , source is CSG PIPE1; default , source is CSG PIPE0; + SPI_PERF_CSGN_BUSY = 0x0000002d, // Number of clocks with outstanding waves (SPI or SH)., Requires SPI_DEBUG_CNTL.DEBUG_GFX_PIPE_SEL to select source, DEBUG_GFX_PIPE_SEL = 0 , source is CSG PIPE0; DEBUG_GFX_PIPE_SEL = 1 , source is CSG PIPE1; default , source is CSG PIPE0; + SPI_PERF_CSGN_NUM_THREADGROUPS = 0x0000002e, // Number of threadgroups launched, Requires SPI_DEBUG_CNTL.DEBUG_GFX_PIPE_SEL to select source, DEBUG_GFX_PIPE_SEL = 0 , source is CSG PIPE0; DEBUG_GFX_PIPE_SEL = 1 , source is CSG PIPE1; default , source is CSG PIPE0; + SPI_PERF_CSGN_CRAWLER_STALL = 0x0000002f, // Number of clocks event/wave order fifo is full, Requires SPI_DEBUG_CNTL.DEBUG_GFX_PIPE_SEL to select source, DEBUG_GFX_PIPE_SEL = 0 , source is CSG PIPE0; DEBUG_GFX_PIPE_SEL = 1 , source is CSG PIPE1; default , source is CSG PIPE0; + SPI_PERF_CSGN_EVENT_WAVE = 0x00000030, // Number of events and waves, Requires SPI_DEBUG_CNTL.DEBUG_GFX_PIPE_SEL to select source, DEBUG_GFX_PIPE_SEL = 0 , source is CSG PIPE0; DEBUG_GFX_PIPE_SEL = 1 , source is CSG PIPE1; default , source is CSG PIPE0; + SPI_PERF_CSGN_WAVE = 0x00000031, // Number of waves, Requires SPI_DEBUG_CNTL.DEBUG_GFX_PIPE_SEL to select source, DEBUG_GFX_PIPE_SEL = 0 , source is CSG PIPE0; DEBUG_GFX_PIPE_SEL = 1 , source is CSG PIPE1; default , source is CSG PIPE0; + SPI_PERF_CSN_WINDOW_VALID = 0x00000032, // Clock count enabled by perfcounter_start event. Requires SPI_DEBUG_CNTL.DEBUG_PIPE_SEL to select source, DEBUG_PIPE_SEL = 0 , source is CS0; DEBUG_PIPE_SEL = 1 , source is CS1; DEBUG_PIPE_SEL = 2 , source is CS2; DEBUG_PIPE_SEL = 3 , source is CS3; DEBUG_PIPE_SEL = 4 , source is CS4; DEBUG_PIPE_SEL = 5 , source is CS5; DEBUG_PIPE_SEL = 6 , source is CS6; DEBUG_PIPE_SEL = 7 , source is CS7; default , source is CS0; + SPI_PERF_CSN_BUSY = 0x00000033, // Number of clocks with outstanding waves (SPI or SH). Requires SPI_DEBUG_CNTL.DEBUG_PIPE_SEL to select source, DEBUG_PIPE_SEL = 0 , source is CS0; DEBUG_PIPE_SEL = 1 , source is CS1; DEBUG_PIPE_SEL = 2 , source is CS2; DEBUG_PIPE_SEL = 3 , source is CS3; DEBUG_PIPE_SEL = 4 , source is CS4; DEBUG_PIPE_SEL = 5 , source is CS5; DEBUG_PIPE_SEL = 6 , source is CS6; DEBUG_PIPE_SEL = 7 , source is CS7; default , source is CS0; + SPI_PERF_CSN_NUM_THREADGROUPS = 0x00000034, // Number of threadgroups launched. Requires SPI_DEBUG_CNTL.DEBUG_PIPE_SEL to select source, DEBUG_PIPE_SEL = 0 , source is CS0; DEBUG_PIPE_SEL = 1 , source is CS1; DEBUG_PIPE_SEL = 2 , source is CS2; DEBUG_PIPE_SEL = 3 , source is CS3; DEBUG_PIPE_SEL = 4 , source is CS4; DEBUG_PIPE_SEL = 5 , source is CS5; DEBUG_PIPE_SEL = 6 , source is CS6; DEBUG_PIPE_SEL = 7 , source is CS7; default , source is CS0; + SPI_PERF_CSN_CRAWLER_STALL = 0x00000035, // Number of clocks event/wave order fifo is full. Requires SPI_DEBUG_CNTL.DEBUG_PIPE_SEL to select source, DEBUG_PIPE_SEL = 0 , source is CS0; DEBUG_PIPE_SEL = 1 , source is CS1; DEBUG_PIPE_SEL = 2 , source is CS2; DEBUG_PIPE_SEL = 3 , source is CS3; DEBUG_PIPE_SEL = 4 , source is CS4; DEBUG_PIPE_SEL = 5 , source is CS5; DEBUG_PIPE_SEL = 6 , source is CS6; DEBUG_PIPE_SEL = 7 , source is CS7; default , source is CS0; + SPI_PERF_CSN_EVENT_WAVE = 0x00000036, // Number of events and waves. Requires SPI_DEBUG_CNTL.DEBUG_PIPE_SEL to select source, DEBUG_PIPE_SEL = 0 , source is CS0; DEBUG_PIPE_SEL = 1 , source is CS1; DEBUG_PIPE_SEL = 2 , source is CS2; DEBUG_PIPE_SEL = 3 , source is CS3; DEBUG_PIPE_SEL = 4 , source is CS4; DEBUG_PIPE_SEL = 5 , source is CS5; DEBUG_PIPE_SEL = 6 , source is CS6; DEBUG_PIPE_SEL = 7 , source is CS7; default , source is CS0; + SPI_PERF_CSN_WAVE = 0x00000037, // Number of waves. Requires SPI_DEBUG_CNTL.DEBUG_PIPE_SEL to select source, DEBUG_PIPE_SEL = 0 , source is CS0; DEBUG_PIPE_SEL = 1 , source is CS1; DEBUG_PIPE_SEL = 2 , source is CS2; DEBUG_PIPE_SEL = 3 , source is CS3; DEBUG_PIPE_SEL = 4 , source is CS4; DEBUG_PIPE_SEL = 5 , source is CS5; DEBUG_PIPE_SEL = 6 , source is CS6; DEBUG_PIPE_SEL = 7 , source is CS7; default , source is CS0; + SPI_PERF_PS0_WINDOW_VALID = 0x00000038, // Clock count enabled by perfcounter_start event. PACKER0 + SPI_PERF_PS1_WINDOW_VALID = 0x00000039, // Clock count enabled by perfcounter_start event. PACKER1 + SPI_PERF_PS2_WINDOW_VALID = 0x0000003a, // Clock count enabled by perfcounter_start event. PACKER2 + SPI_PERF_PS3_WINDOW_VALID = 0x0000003b, // Clock count enabled by perfcounter_start event. PACKER3 + SPI_PERF_PS0_BUSY = 0x0000003c, // Number of clocks with outstanding waves (SPI or SH) , PACKER0 + SPI_PERF_PS1_BUSY = 0x0000003d, // Number of clocks with outstanding waves (SPI or SH) , PACKER1 + SPI_PERF_PS2_BUSY = 0x0000003e, // Number of clocks with outstanding waves (SPI or SH) , PACKER2 + SPI_PERF_PS3_BUSY = 0x0000003f, // Number of clocks with outstanding waves (SPI or SH) , PACKER3 + SPI_PERF_PS0_ACTIVE = 0x00000040, // Number of clks ptr_buff is processing waves. PACKER0 + SPI_PERF_PS1_ACTIVE = 0x00000041, // Number of clks ptr_buff is processing waves. PACKER1 + SPI_PERF_PS2_ACTIVE = 0x00000042, // Number of clks ptr_buff is processing waves. PACKER2 + SPI_PERF_PS3_ACTIVE = 0x00000043, // Number of clks ptr_buff is processing waves. PACKER3 + SPI_PERF_PS0_DEALLOC = 0x00000044, // Count deallocs for PACKER0. Uses a 17-bit increment so we can only use the 32-bit counters. + SPI_PERF_PS1_DEALLOC = 0x00000045, // Count deallocs for PACKER1. Uses a 17-bit increment so we can only use the 32-bit counters. + SPI_PERF_PS2_DEALLOC = 0x00000046, // Count deallocs for PACKER2. Uses a 17-bit increment so we can only use the 32-bit counters. + SPI_PERF_PS3_DEALLOC = 0x00000047, // Count deallocs for PACKER3. Uses a 17-bit increment so we can only use the 32-bit counters. + SPI_PERF_PS0_FPOS_STALL = 0x00000048, // Number of clks stalled waiting for a VS done for PACKER0 + SPI_PERF_PS1_FPOS_STALL = 0x00000049, // Number of clks stalled waiting for a VS done for PACKER1 + SPI_PERF_PS2_FPOS_STALL = 0x0000004a, // Number of clks stalled waiting for a VS done for PACKER2 + SPI_PERF_PS3_FPOS_STALL = 0x0000004b, // Number of clks stalled waiting for a VS done for PACKER3 + SPI_PERF_PS0_EVENT_WAVE = 0x0000004c, // Number of events and waves ,PACKER0 + SPI_PERF_PS1_EVENT_WAVE = 0x0000004d, // Number of events and waves ,PACKER1 + SPI_PERF_PS2_EVENT_WAVE = 0x0000004e, // Number of events and waves ,PACKER2 + SPI_PERF_PS3_EVENT_WAVE = 0x0000004f, // Number of events and waves ,PACKER3 + SPI_PERF_PS0_WAVE = 0x00000050, // Number of waves ,PACKER0 + SPI_PERF_PS1_WAVE = 0x00000051, // Number of waves ,PACKER1 + SPI_PERF_PS2_WAVE = 0x00000052, // Number of waves ,PACKER2 + SPI_PERF_PS3_WAVE = 0x00000053, // Number of waves ,PACKER3 + SPI_PERF_PS0_OPT_WAVE = 0x00000054, // Number of waves with center+centroid+bc_optimize ,PACKER0 + SPI_PERF_PS1_OPT_WAVE = 0x00000055, // Number of waves with center+centroid+bc_optimize ,PACKER1 + SPI_PERF_PS2_OPT_WAVE = 0x00000056, // Number of waves with center+centroid+bc_optimize ,PACKER2 + SPI_PERF_PS3_OPT_WAVE = 0x00000057, // Number of waves with center+centroid+bc_optimize ,PACKER3 + SPI_PERF_PS0_PASS_BIN0 = 0x00000058, // Count waves with bin0 pc reads / attr, range is 1-16. PACKER0 + SPI_PERF_PS1_PASS_BIN0 = 0x00000059, // Count waves with bin0 pc reads / attr, range is 1-16. PACKER1 + SPI_PERF_PS2_PASS_BIN0 = 0x0000005a, // Count waves with bin0 pc reads / attr, range is 1-16. PACKER2 + SPI_PERF_PS3_PASS_BIN0 = 0x0000005b, // Count waves with bin0 pc reads / attr, range is 1-16. PACKER3 + SPI_PERF_PS0_PASS_BIN1 = 0x0000005c, // Count waves with bin1 pc reads / attr, range is 1-16. PACKER0 + SPI_PERF_PS1_PASS_BIN1 = 0x0000005d, // Count waves with bin1 pc reads / attr, range is 1-16. PACKER1 + SPI_PERF_PS2_PASS_BIN1 = 0x0000005e, // Count waves with bin1 pc reads / attr, range is 1-16. PACKER2 + SPI_PERF_PS3_PASS_BIN1 = 0x0000005f, // Count waves with bin1 pc reads / attr, range is 1-16. PACKER3 + SPI_PERF_PS0_FPOS = 0x00000060, // Count fpos for PACKER0 + SPI_PERF_PS1_FPOS = 0x00000061, // Count fpos for PACKER1 + SPI_PERF_PS2_FPOS = 0x00000062, // Count fpos for PACKER2 + SPI_PERF_PS3_FPOS = 0x00000063, // Count fpos for PACKER3 + SPI_PERF_PS0_PRIM_BIN0 = 0x00000064, // Count waves with bin0 prims, range is 1-16. PACKER0 + SPI_PERF_PS1_PRIM_BIN0 = 0x00000065, // Count waves with bin0 prims, range is 1-16. PACKER1 + SPI_PERF_PS2_PRIM_BIN0 = 0x00000066, // Count waves with bin0 prims, range is 1-16. PACKER2 + SPI_PERF_PS3_PRIM_BIN0 = 0x00000067, // Count waves with bin0 prims, range is 1-16. PACKER3 + SPI_PERF_PS0_PRIM_BIN1 = 0x00000068, // Count waves with bin1 prims, range is 1-16. PACKER0 + SPI_PERF_PS1_PRIM_BIN1 = 0x00000069, // Count waves with bin1 prims, range is 1-16. PACKER1 + SPI_PERF_PS2_PRIM_BIN1 = 0x0000006a, // Count waves with bin1 prims, range is 1-16. PACKER2 + SPI_PERF_PS3_PRIM_BIN1 = 0x0000006b, // Count waves with bin1 prims, range is 1-16. PACKER3 + SPI_PERF_PS0_CNF_BIN2 = 0x0000006c, // Count waves with bin2 conflicts, range is 0-15 but max is 8. PACKER0 + SPI_PERF_PS1_CNF_BIN2 = 0x0000006d, // Count waves with bin2 conflicts, range is 0-15 but max is 8. PACKER1 + SPI_PERF_PS2_CNF_BIN2 = 0x0000006e, // Count waves with bin2 conflicts, range is 0-15 but max is 8. PACKER2 + SPI_PERF_PS3_CNF_BIN2 = 0x0000006f, // Count waves with bin2 conflicts, range is 0-15 but max is 8. PACKER3 + SPI_PERF_PS0_CNF_BIN3 = 0x00000070, // Count waves with bin3 conflicts, range is 0-15 but max is 8. PACKER0 + SPI_PERF_PS1_CNF_BIN3 = 0x00000071, // Count waves with bin3 conflicts, range is 0-15 but max is 8. PACKER1 + SPI_PERF_PS2_CNF_BIN3 = 0x00000072, // Count waves with bin3 conflicts, range is 0-15 but max is 8. PACKER2 + SPI_PERF_PS3_CNF_BIN3 = 0x00000073, // Count waves with bin3 conflicts, range is 0-15 but max is 8. PACKER3 + SPI_PERF_PS0_CRAWLER_STALL = 0x00000074, // Number of clocks event/wave order fifo is full ,PACKER0 + SPI_PERF_PS1_CRAWLER_STALL = 0x00000075, // Number of clocks event/wave order fifo is full ,PACKER1 + SPI_PERF_PS2_CRAWLER_STALL = 0x00000076, // Number of clocks event/wave order fifo is full ,PACKER2 + SPI_PERF_PS3_CRAWLER_STALL = 0x00000077, // Number of clocks event/wave order fifo is full ,PACKER3 + SPI_PERF_PS0_LDS_RES_FULL = 0x00000078, // Number of clks PS per-wavefront storage is full ,PACKER0 + SPI_PERF_PS1_LDS_RES_FULL = 0x00000079, // Number of clks PS per-wavefront storage is full ,PACKER1 + SPI_PERF_PS2_LDS_RES_FULL = 0x0000007a, // Number of clks PS per-wavefront storage is full ,PACKER2 + SPI_PERF_PS3_LDS_RES_FULL = 0x0000007b, // Number of clks PS per-wavefront storage is full ,PACKER3 + SPI_PERF_PS0_POPS_WAVE_SENT = 0x0000007c, // Number of PS POPS Waves that were issued by the PS wave controller ,PACKER0 + SPI_PERF_PS1_POPS_WAVE_SENT = 0x0000007d, // Number of PS POPS Waves that were issued by the PS wave controller ,PACKER1 + SPI_PERF_PS2_POPS_WAVE_SENT = 0x0000007e, // Number of PS POPS Waves that were issued by the PS wave controller ,PACKER2 + SPI_PERF_PS3_POPS_WAVE_SENT = 0x0000007f, // Number of PS POPS Waves that were issued by the PS wave controller ,PACKER3 + SPI_PERF_PS0_POPS_WAVE_EXIT = 0x00000080, // Number of POPS Enabled PS waves that exit the PS crawler ,PACKER0 + SPI_PERF_PS1_POPS_WAVE_EXIT = 0x00000081, // Number of POPS Enabled PS waves that exit the PS crawler ,PACKER1 + SPI_PERF_PS2_POPS_WAVE_EXIT = 0x00000082, // Number of POPS Enabled PS waves that exit the PS crawler ,PACKER2 + SPI_PERF_PS3_POPS_WAVE_EXIT = 0x00000083, // Number of POPS Enabled PS waves that exit the PS crawler ,PACKER3 + SPI_PERF_PS_PERS_UPD_FULL0 = 0x00000084, // Number of clks PS persistent state update fifo0 is full + SPI_PERF_PS_PERS_UPD_FULL1 = 0x00000085, // Number of clks PS persistent state update fifo1 is full + SPI_PERF_PS0_INTRA_PRIM_CNFLCT = 0x00000086, // Number of intra prim conflict per quad ,PACKER0 + SPI_PERF_PS1_INTRA_PRIM_CNFLCT = 0x00000087, // Number of intra prim conflict per quad ,PACKER1 + SPI_PERF_PS2_INTRA_PRIM_CNFLCT = 0x00000088, // Number of intra prim conflict per quad ,PACKER2 + SPI_PERF_PS3_INTRA_PRIM_CNFLCT = 0x00000089, // Number of intra prim conflict per quad ,PACKER3 + SPI_PERF_LDS0_PC_VALID = 0x0000008a, // Number of param cache reads sent to PC from SA0. + SPI_PERF_LDS1_PC_VALID = 0x0000008b, // Number of param cache reads sent to PC from SA1. + SPI_PERF_RA_PIPE_REQ_BIN2 = 0x0000008c, // Arb cycles with bin2 mqcs pipe_arb req =sum(csprobe0, csproben) + SPI_PERF_RA_TASK_REQ_BIN3 = 0x0000008d, // Arb cycles with bin3 requests =sum(mqcs0, mqcsn) + dxcs +sum(gfx) + SPI_PERF_RA_WR_CTL_FULL = 0x0000008e, // Arb cycles where RA is stalled due to wave launch fifo_full. + SPI_PERF_RA_REQ_NO_ALLOC = 0x0000008f, // Arb cycles with requests but no allocation. + SPI_PERF_RA_REQ_NO_ALLOC_PS = 0x00000090, // Arb cycles with PS req and no PS alloc. + SPI_PERF_RA_REQ_NO_ALLOC_VS = 0x00000091, // Arb cycles with VS req and no VS alloc. + SPI_PERF_RA_REQ_NO_ALLOC_ES = 0x00000092, // Arb cycles with ES req and no ES alloc. + SPI_PERF_RA_REQ_NO_ALLOC_GS = 0x00000093, // Arb cycles with GS req and no GS alloc. + SPI_PERF_RA_REQ_NO_ALLOC_LS = 0x00000094, // Arb cycles with LS req and no LS alloc. + SPI_PERF_RA_REQ_NO_ALLOC_HS = 0x00000095, // Arb cycles with HS req and no HS alloc. + SPI_PERF_RA_REQ_NO_ALLOC_CSG = 0x00000096, // Arb cycles with CSg req and no CSg alloc. + SPI_PERF_RA_REQ_NO_ALLOC_CSN = 0x00000097, // Arb cycles with CSn req and no CSn alloc. + SPI_PERF_RA_RES_STALL_PS = 0x00000098, // Arb cycles with PS req and no PS fits. + SPI_PERF_RA_RES_STALL_VS = 0x00000099, // Arb cycles with VS req and no VS fits. + SPI_PERF_RA_RES_STALL_ES = 0x0000009a, // Arb cycles with ES req and no ES fits. + SPI_PERF_RA_RES_STALL_GS = 0x0000009b, // Arb cycles with GS req and no GS fits. + SPI_PERF_RA_RES_STALL_LS = 0x0000009c, // Arb cycles with LS req and no LS fits. + SPI_PERF_RA_RES_STALL_HS = 0x0000009d, // Arb cycles with HS req and no HS fits. + SPI_PERF_RA_RES_STALL_CSG = 0x0000009e, // Arb cycles with CSg req and no CSg fits. + SPI_PERF_RA_RES_STALL_CSN = 0x0000009f, // Arb cycles with CSn req and no CSn fits. + SPI_PERF_RA_TMP_STALL_PS = 0x000000a0, // Cycles where ps wants to req but does not fit in temp space. + SPI_PERF_RA_TMP_STALL_VS = 0x000000a1, // Cycles where vs wants to req but does not fit in temp space. + SPI_PERF_RA_TMP_STALL_ES = 0x000000a2, // Cycles where es wants to req but does not fit in temp space. + SPI_PERF_RA_TMP_STALL_GS = 0x000000a3, // Cycles where gs wants to req but does not fit in temp space. + SPI_PERF_RA_TMP_STALL_LS = 0x000000a4, // Cycles where ls wants to req but does not fit in temp space. + SPI_PERF_RA_TMP_STALL_HS = 0x000000a5, // Cycles where hs wants to req but does not fit in temp space. + SPI_PERF_RA_TMP_STALL_CSG = 0x000000a6, // Cycles where csg wants to req but does not fit in temp space. + SPI_PERF_RA_TMP_STALL_CSN = 0x000000a7, // Cycles where csn wants to req but does not fit in temp space. + SPI_PERF_RA_WAVE_SIMD_FULL_PS = 0x000000a8, // Sum of SIMD where WAVE resource full when !ps_fits. + SPI_PERF_RA_WAVE_SIMD_FULL_VS = 0x000000a9, // Sum of SIMD where WAVE resource full when !vs_fits. + SPI_PERF_RA_WAVE_SIMD_FULL_ES = 0x000000aa, // Sum of SIMD where WAVE resource full when !es_fits. + SPI_PERF_RA_WAVE_SIMD_FULL_GS = 0x000000ab, // Sum of SIMD where WAVE resource full when !gs_fits. + SPI_PERF_RA_WAVE_SIMD_FULL_LS = 0x000000ac, // Sum of SIMD where WAVE can't take ls wave when !fits. + SPI_PERF_RA_WAVE_SIMD_FULL_HS = 0x000000ad, // Sum of SIMD where WAVE can't take hs wave when !fits. + SPI_PERF_RA_WAVE_SIMD_FULL_CSG = 0x000000ae, // Sum of SIMD where WAVE can't take csg wave when !fits. + SPI_PERF_RA_WAVE_SIMD_FULL_CSN = 0x000000af, // Sum of SIMD where WAVE can't take csn wave when !fits. + SPI_PERF_RA_VGPR_SIMD_FULL_PS = 0x000000b0, // Sum of SIMD where VGPR can't take ps wave when !fits. + SPI_PERF_RA_VGPR_SIMD_FULL_VS = 0x000000b1, // Sum of SIMD where VGPR can't take vs wave when !fits. + SPI_PERF_RA_VGPR_SIMD_FULL_ES = 0x000000b2, // Sum of SIMD where VGPR can't take es wave when !fits. + SPI_PERF_RA_VGPR_SIMD_FULL_GS = 0x000000b3, // Sum of SIMD where VGPR can't take gs wave when !fits. + SPI_PERF_RA_VGPR_SIMD_FULL_HS = 0x000000b4, // Sum of SIMD where VGPR can't take hs wave when !fits. + SPI_PERF_RA_VGPR_SIMD_FULL_LS = 0x000000b5, // Sum of SIMD where VGPR can't take ls wave when !fits. + SPI_PERF_RA_VGPR_SIMD_FULL_CSG = 0x000000b6, // Sum of SIMD where VGPR can't take csg wave when !fits. + SPI_PERF_RA_VGPR_SIMD_FULL_CSN = 0x000000b7, // Sum of SIMD where VGPR can't take csn wave when !fits. + SPI_PERF_RA_SGPR_SIMD_FULL_PS = 0x000000b8, // Sum of SIMD where SGPR can't take ps wave when !fits. + SPI_PERF_RA_SGPR_SIMD_FULL_VS = 0x000000b9, // Sum of SIMD where SGPR can't take vs wave when !fits. + SPI_PERF_RA_SGPR_SIMD_FULL_ES = 0x000000ba, // Sum of SIMD where SGPR can't take es wave when !fits. + SPI_PERF_RA_SGPR_SIMD_FULL_GS = 0x000000bb, // Sum of SIMD where SGPR can't take gs wave when !fits. + SPI_PERF_RA_SGPR_SIMD_FULL_LS = 0x000000bc, // Sum of SIMD where SGPR can't take ls wave when !fits. + SPI_PERF_RA_SGPR_SIMD_FULL_HS = 0x000000bd, // Sum of SIMD where SGPR can't take hs wave when !fits. + SPI_PERF_RA_SGPR_SIMD_FULL_CSG = 0x000000be, // Sum of SIMD where SGPR can't take csg wave when !fits. + SPI_PERF_RA_SGPR_SIMD_FULL_CSN = 0x000000bf, // Sum of SIMD where SGPR can't take csn wave when !fits. + SPI_PERF_RA_LDS_CU_FULL_PS = 0x000000c0, // Sum of CU where LDS can't take ps wave when !fits. + SPI_PERF_RA_LDS_CU_FULL_LS = 0x000000c1, // Sum of CU where LDS can't take ls wave when !fits. + SPI_PERF_RA_LDS_CU_FULL_HS = 0x000000c2, // Sum of CU where LDS can't take hs wave when !fits. + SPI_PERF_RA_LDS_CU_FULL_ES = 0x000000c3, // Sum of CU where LDS can't take es wave when !fits. + SPI_PERF_RA_LDS_CU_FULL_GS = 0x000000c4, // Sum of CU where LDS can't take gs wave when !fits. + SPI_PERF_RA_LDS_CU_FULL_CSG = 0x000000c5, // Sum of CU where LDS can't take csg wave when !fits. + SPI_PERF_RA_LDS_CU_FULL_CSN = 0x000000c6, // Sum of CU where LDS can't take csn wave when !fits. + SPI_PERF_RA_BAR_CU_FULL_HS = 0x000000c7, // Sum of CU where BARRIER can't take hs wave when !fits. + SPI_PERF_RA_BAR_CU_FULL_CSG = 0x000000c8, // Sum of CU where BARRIER can't take csg wave when !fits. + SPI_PERF_RA_BAR_CU_FULL_CSN = 0x000000c9, // Sum of CU where BARRIER can't take csn wave when !fits. + SPI_PERF_RA_BULKY_CU_FULL_CSG = 0x000000ca, // Sum of CU where BULKY can't take csg wave when !fits. + SPI_PERF_RA_BULKY_CU_FULL_CSN = 0x000000cb, // Sum of CU where BULKY can't take csn wave when !fits. + SPI_PERF_RA_TGLIM_CU_FULL_CSG = 0x000000cc, // Cycles where csg wants to req but all CU are at tg_limit + SPI_PERF_RA_TGLIM_CU_FULL_CSN = 0x000000cd, // Cycles where csn wants to req but all CU are at tg_limit + SPI_PERF_RA_WVLIM_STALL_PS = 0x000000ce, // Number of clocks ps is stalled due to WAVE LIMIT. + SPI_PERF_RA_WVLIM_STALL_VS = 0x000000cf, // Number of clocks vs is stalled due to WAVE LIMIT. + SPI_PERF_RA_WVLIM_STALL_ES = 0x000000d0, // Number of clocks es is stalled due to WAVE LIMIT. + SPI_PERF_RA_WVLIM_STALL_GS = 0x000000d1, // Number of clocks gs is stalled due to WAVE LIMIT. + SPI_PERF_RA_WVLIM_STALL_LS = 0x000000d2, // Number of clocks ls is stalled due to WAVE LIMIT. + SPI_PERF_RA_WVLIM_STALL_HS = 0x000000d3, // Number of clocks hs is stalled due to WAVE LIMIT. + SPI_PERF_RA_WVLIM_STALL_CSG = 0x000000d4, // Number of clocks csg is stalled due to WAVE LIMIT. + SPI_PERF_RA_WVLIM_STALL_CSN = 0x000000d5, // Number of clocks csn is stalled due to WAVE LIMIT. + SPI_PERF_RA_VS_LOCK = 0x000000d6, // Arb cycles VS has a CU locked when !fits and active_cnt < threshold. + SPI_PERF_RA_PS_LOCK = 0x000000d7, // Arb cycles PS has a CU locked when !fits and active_cnt < threshold. + SPI_PERF_RA_ES_LOCK = 0x000000d8, // Arb cycles ES has a CU locked when !fits and active_cnt < threshold. + SPI_PERF_RA_GS_LOCK = 0x000000d9, // Arb cycles GS has a CU locked when !fits and active_cnt < threshold. + SPI_PERF_RA_LS_LOCK = 0x000000da, // Arb cycles LS has a CU locked when !fits and active_cnt < threshold. + SPI_PERF_RA_HS_LOCK = 0x000000db, // Arb cycles HS has a CU locked when !fits and active_cnt < threshold. + SPI_PERF_RA_CSG_LOCK = 0x000000dc, // Arb cycles CSG has a CU locked when !fits and active_cnt < threshold. + SPI_PERF_RA_CSN_LOCK = 0x000000dd, // Arb cycles CSN has a CU locked when !fits and active_cnt < threshold. + SPI_PERF_RA_RSV_UPD = 0x000000de, // Cycles spent doing updates for reservation changes + SPI_PERF_RA_PRE_ALLOC_STALL = 0x000000df, // Number of clocks csn is stalled because pre alloc buffer is full or wave count > DEDICATED_PREALLOCATION_BUFFER_LIMIT + SPI_PERF_RA_GFX_UNDER_TUNNEL = 0x000000e0, // Arb cycles with gfx or dxcs req while CS tunnel is enabled + SPI_PERF_RA_CSC_UNDER_TUNNEL = 0x000000e1, // Arb cycles with csc req while CS tunnel of another pipe is enabled + SPI_PERF_RA_WVALLOC_STALL = 0x000000e2, // Number of clocks wave allocation interface is stalled + SPI_PERF_RA_ACCUM0_SIMD_FULL_PS = 0x000000e3, // Sum of SIMD where User resource accumlator 0 can't take ps wave when !fits. + SPI_PERF_RA_ACCUM1_SIMD_FULL_PS = 0x000000e4, // Sum of SIMD where User resource accumlator 1 can't take ps wave when !fits. + SPI_PERF_RA_ACCUM2_SIMD_FULL_PS = 0x000000e5, // Sum of SIMD where User resource accumlator 2 can't take ps wave when !fits. + SPI_PERF_RA_ACCUM3_SIMD_FULL_PS = 0x000000e6, // Sum of SIMD where User resource accumlator 3 can't take ps wave when !fits. + SPI_PERF_RA_ACCUM0_SIMD_FULL_VS = 0x000000e7, // Sum of SIMD where User resource accumlator 0 can't take vs wave when !fits. + SPI_PERF_RA_ACCUM1_SIMD_FULL_VS = 0x000000e8, // Sum of SIMD where User resource accumlator 1 can't take vs wave when !fits. + SPI_PERF_RA_ACCUM2_SIMD_FULL_VS = 0x000000e9, // Sum of SIMD where User resource accumlator 2 can't take vs wave when !fits. + SPI_PERF_RA_ACCUM3_SIMD_FULL_VS = 0x000000ea, // Sum of SIMD where User resource accumlator 3 can't take vs wave when !fits. + SPI_PERF_RA_ACCUM0_SIMD_FULL_GS = 0x000000eb, // Sum of SIMD where User resource accumlator 0 can't take gs wave when !fits. + SPI_PERF_RA_ACCUM1_SIMD_FULL_GS = 0x000000ec, // Sum of SIMD where User resource accumlator 1 can't take gs wave when !fits. + SPI_PERF_RA_ACCUM2_SIMD_FULL_GS = 0x000000ed, // Sum of SIMD where User resource accumlator 2 can't take gs wave when !fits. + SPI_PERF_RA_ACCUM3_SIMD_FULL_GS = 0x000000ee, // Sum of SIMD where User resource accumlator 3 can't take gs wave when !fits. + SPI_PERF_RA_ACCUM0_SIMD_FULL_HS = 0x000000ef, // Sum of SIMD where User resource accumlator 0 can't take hs wave when !fits. + SPI_PERF_RA_ACCUM1_SIMD_FULL_HS = 0x000000f0, // Sum of SIMD where User resource accumlator 1 can't take hs wave when !fits. + SPI_PERF_RA_ACCUM2_SIMD_FULL_HS = 0x000000f1, // Sum of SIMD where User resource accumlator 2 can't take hs wave when !fits. + SPI_PERF_RA_ACCUM3_SIMD_FULL_HS = 0x000000f2, // Sum of SIMD where User resource accumlator 3 can't take hs wave when !fits. + SPI_PERF_RA_ACCUM0_SIMD_FULL_CSG = 0x000000f3, // Sum of SIMD where User resource accumlator 0 can't take csg wave when !fits. + SPI_PERF_RA_ACCUM1_SIMD_FULL_CSG = 0x000000f4, // Sum of SIMD where User resource accumlator 1 can't take csg wave when !fits. + SPI_PERF_RA_ACCUM2_SIMD_FULL_CSG = 0x000000f5, // Sum of SIMD where User resource accumlator 2 can't take csg wave when !fits. + SPI_PERF_RA_ACCUM3_SIMD_FULL_CSG = 0x000000f6, // Sum of SIMD where User resource accumlator 3 can't take csg wave when !fits. + SPI_PERF_RA_ACCUM0_SIMD_FULL_CSN = 0x000000f7, // Sum of SIMD where User resource accumlator 0 can't take csn wave when !fits. + SPI_PERF_RA_ACCUM1_SIMD_FULL_CSN = 0x000000f8, // Sum of SIMD where User resource accumlator 1 can't take csn wave when !fits. + SPI_PERF_RA_ACCUM2_SIMD_FULL_CSN = 0x000000f9, // Sum of SIMD where User resource accumlator 2 can't take csn wave when !fits. + SPI_PERF_RA_ACCUM3_SIMD_FULL_CSN = 0x000000fa, // Sum of SIMD where User resource accumlator 3 can't take csn wave when !fits. + SPI_PERF_EXP_ARB_COL_CNT = 0x000000fb, // Sum of number of color exp requests pending each clk + SPI_PERF_EXP_ARB_PAR_CNT = 0x000000fc, // Sum of number of parameter exp requests pending each clk + SPI_PERF_EXP_ARB_POS_CNT = 0x000000fd, // Sum of number of position exp requests pending each clk + SPI_PERF_EXP_ARB_GDS_CNT = 0x000000fe, // Sum of number of gds exp requests pending each clk + SPI_PERF_NUM_PS_COL_SA0SQ0_EXPORTS = 0x000000ff, // Number of PS color export grants in dwords for SA0 , Columns0 + SPI_PERF_NUM_PS_COL_SA0SQ1_EXPORTS = 0x00000100, // Number of PS color export grants in dwords for SA0 , Columns1 + SPI_PERF_NUM_PS_COL_SA1SQ0_EXPORTS = 0x00000101, // Number of PS color export grants in dwords for SA1 , Columns0 + SPI_PERF_NUM_PS_COL_SA1SQ1_EXPORTS = 0x00000102, // Number of PS color export grants in dwords for SA1 , Columns1 + SPI_PERF_NUM_VS_POS_SA0SQ0_EXPORTS = 0x00000103, // Number of VS position export grants in dwords for SA0 , Columns0 + SPI_PERF_NUM_VS_POS_SA0SQ1_EXPORTS = 0x00000104, // Number of VS position export grants in dwords for SA0 , Columns1 + SPI_PERF_NUM_VS_POS_SA1SQ0_EXPORTS = 0x00000105, // Number of VS position export grants in dwords for SA1 , Columns0 + SPI_PERF_NUM_VS_POS_SA1SQ1_EXPORTS = 0x00000106, // Number of VS position export grants in dwords for SA1 , Columns1 + SPI_PERF_NUM_VS_PARAM_SA0SQ0_EXPORTS = 0x00000107, // Number of VS parameter export grants in dwords for SA0 , Columns0 + SPI_PERF_NUM_VS_PARAM_SA0SQ1_EXPORTS = 0x00000108, // Number of VS parameter export grants in dwords for SA0 , Columns1 + SPI_PERF_NUM_VS_PARAM_SA1SQ0_EXPORTS = 0x00000109, // Number of VS parameter export grants in dwords for SA1 , Columns0 + SPI_PERF_NUM_VS_PARAM_SA1SQ1_EXPORTS = 0x0000010a, // Number of VS parameter export grants in dwords for SA1 , Columns1 + SPI_PERF_NUM_VS_GDS_SA0SQ0_EXPORTS = 0x0000010b, // Number of gds export grants in dwords for SA0 , Columns0 + SPI_PERF_NUM_VS_GDS_SA0SQ1_EXPORTS = 0x0000010c, // Number of gds export grants in dwords for SA0 , Columns1 + SPI_PERF_NUM_VS_GDS_SA1SQ0_EXPORTS = 0x0000010d, // Number of gds export grants in dwords for SA1 , Columns0 + SPI_PERF_NUM_VS_GDS_SA1SQ1_EXPORTS = 0x0000010e, // Number of gds export grants in dwords for SA1 , Columns1 + SPI_PERF_NUM_EXPGRANT_EXPORTS = 0x0000010f, // Number of cycles export bus is busy + SPI_PERF_CLKGATE_BUSY_STALL = 0x00000110, // Number of clocks with spi busy and not all_clocks_on + SPI_PERF_CLKGATE_ACTIVE_STALL = 0x00000111, // Number of clocks with spim_active and not all_clocks_on. + SPI_PERF_CLKGATE_ALL_CLOCKS_ON = 0x00000112, // Number of clocks with all_clocks_on. + SPI_PERF_CLKGATE_CGTT_DYN_ON = 0x00000113, // Number of clocks with spi cgtt dyn clk on. + SPI_PERF_CLKGATE_CGTT_REG_ON = 0x00000114, // Number of clocks with spi cgtt reg clk on. + SPI_PERF_PIX_ALLOC_PEND_CNT = 0x00000115, // Sum of number of pixel alloc requests pending per clk. Requires SPI_DEBUG_CNTL.DEBUG_PIXEL_PIPE_SEL to select source. DEBUG_PIXEL_PIPE_SEL = 0 , source is PACKER0; DEBUG_PIXEL_PIPE_SEL = 1 , source is PACKER1; DEBUG_PIXEL_PIPE_SEL = 2 , source is PACKER2; DEBUG_PIXEL_PIPE_SEL = 3 , source is PACKER3; default , source is PACKER0; + SPI_PERF_PIX_ALLOC_SCB0_STALL = 0x00000116, // Number of clks pix alloc stalled due to color scoreboard , source is PACKER0. + SPI_PERF_PIX_ALLOC_SCB1_STALL = 0x00000117, // Number of clks pix alloc stalled due to color scoreboard , source is PACKER1. + SPI_PERF_PIX_ALLOC_SCB2_STALL = 0x00000118, // Number of clks pix alloc stalled due to color scoreboard , source is PACKER2. + SPI_PERF_PIX_ALLOC_SCB3_STALL = 0x00000119, // Number of clks pix alloc stalled due to color scoreboard , source is PACKER3. + SPI_PERF_PIX_ALLOC_DB0_STALL = 0x0000011a, // Number of clks pix alloc stalled due to db0 color buffer. + SPI_PERF_PIX_ALLOC_DB1_STALL = 0x0000011b, // Number of clks pix alloc stalled due to db1 color buffer. + SPI_PERF_PIX_ALLOC_DB2_STALL = 0x0000011c, // Number of clks pix alloc stalled due to db2 color buffer. + SPI_PERF_PIX_ALLOC_DB3_STALL = 0x0000011d, // Number of clks pix alloc stalled due to db3 color buffer. + SPI_PERF_PIX_ALLOC_DB4_STALL = 0x0000011e, // Number of clks pix alloc stalled due to db4 color buffer. + SPI_PERF_PIX_ALLOC_DB5_STALL = 0x0000011f, // Number of clks pix alloc stalled due to db5 color buffer. + SPI_PERF_PIX_ALLOC_DB6_STALL = 0x00000120, // Number of clks pix alloc stalled due to db6 color buffer. + SPI_PERF_PIX_ALLOC_DB7_STALL = 0x00000121, // Number of clks pix alloc stalled due to db7 color buffer. + SPI_PERF_GS_NGG_SE_SEND_GS_ALLOC = 0x00000122, // GS granting PC allocations per surviving wave on this SE + SPI_PERF_SWC_PS_WR = 0x00000123, // Number of clocks to write PS waves to SGPRs + SPI_PERF_SWC_VS_WR = 0x00000124, // Number of clocks to write VS waves to SGPRs + SPI_PERF_SWC_ES_WR = 0x00000125, // Number of clocks to write ES waves to SGPRs + SPI_PERF_SWC_GS_WR = 0x00000126, // Number of clocks to write GS waves to SGPRs + SPI_PERF_SWC_LS_WR = 0x00000127, // Number of clocks to write LS waves to SGPRs + SPI_PERF_SWC_HS_WR = 0x00000128, // Number of clocks to write HS waves to SGPRs + SPI_PERF_SWC_CSGN_WR = 0x00000129, // Number of clocks to write CSG waves to SGPRs, Requires SPI_DEBUG_CNTL.DEBUG_GFX_PIPE_SEL to select source, DEBUG_GFX_PIPE_SEL = 0 , source is CSG PIPE0; DEBUG_GFX_PIPE_SEL = 1 , source is CSG PIPE1; default , source is CSG PIPE0; + SPI_PERF_SWC_CSN_WR = 0x0000012a, // Number of clocks to write CSC waves to SGPRs Requires SPI_DEBUG_CNTL.DEBUG_PIPE_SEL to select source, DEBUG_PIPE_SEL = 0 , source is CS0; DEBUG_PIPE_SEL = 1 , source is CS1; DEBUG_PIPE_SEL = 2 , source is CS2; DEBUG_PIPE_SEL = 3 , source is CS3; DEBUG_PIPE_SEL = 4 , source is CS4; DEBUG_PIPE_SEL = 5 , source is CS5; DEBUG_PIPE_SEL = 6 , source is CS6; DEBUG_PIPE_SEL = 7 , source is CS7; default , source is CS0; + SPI_PERF_VWC_PS_WR = 0x0000012b, // Number of clocks to write PS waves to VGPRs (need to multiply this value by 4) + SPI_PERF_VWC_VS_WR = 0x0000012c, // Number of clocks to write VS waves to VGPRs (need to multiply this value by 4) + SPI_PERF_VWC_ES_WR = 0x0000012d, // Number of clocks to write ES waves to VGPRs (need to multiply this value by 4) + SPI_PERF_VWC_GS_WR = 0x0000012e, // Number of clocks to write GS waves to VGPRs (need to multiply this value by 4) + SPI_PERF_VWC_LS_WR = 0x0000012f, // Number of clocks to write LS waves to VGPRs (need to multiply this value by 4) + SPI_PERF_VWC_HS_WR = 0x00000130, // Number of clocks to write HS waves to VGPRs (need to multiply this value by 4) + SPI_PERF_VWC_CSGN_WR = 0x00000131, // Number of clocks to write CSG waves to VGPRs (need to multiply this value by 4), Requires SPI_DEBUG_CNTL.DEBUG_GFX_PIPE_SEL to select source, DEBUG_GFX_PIPE_SEL = 0 , source is CSG PIPE0; DEBUG_GFX_PIPE_SEL = 1 , source is CSG PIPE1; default , source is CSG PIPE0; + SPI_PERF_VWC_CSN_WR = 0x00000132, // Number of clocks to write CSC waves to VGPRs (need to multiply this value by 4) Requires SPI_DEBUG_CNTL.DEBUG_PIPE_SEL to select source, DEBUG_PIPE_SEL = 1 , source is CS1; DEBUG_PIPE_SEL = 2 , source is CS2; DEBUG_PIPE_SEL = 3 , source is CS3; DEBUG_PIPE_SEL = 4 , source is CS4; DEBUG_PIPE_SEL = 5 , source is CS5; DEBUG_PIPE_SEL = 6 , source is CS6; DEBUG_PIPE_SEL = 7 , source is CS7; default , source is CS0; + SPI_PERF_ES_WINDOW_VALID = 0x00000133, // Clock count enabled by perfcounter_start event. + SPI_PERF_ES_BUSY = 0x00000134, // Number of clocks with outstanding waves (SPI or SH). + SPI_PERF_ES_CRAWLER_STALL = 0x00000135, // Number of clocks event/wave order fifo is full. + SPI_PERF_ES_FIRST_WAVE = 0x00000136, // Number of ES_IS_DS first waves + SPI_PERF_ES_LAST_WAVE = 0x00000137, // Number of ES_IS_DS last waves + SPI_PERF_ES_LSHS_DEALLOC = 0x00000138, // Number of ES_IS_DS lds dealloc waves + SPI_PERF_ES_EVENT_WAVE = 0x00000139, // Number of events and waves + SPI_PERF_ES_WAVE = 0x0000013a, // Number of waves. + SPI_PERF_ES_PERS_UPD_FULL0 = 0x0000013b, // Number of clks ES persistent state update fifo0 is full. + SPI_PERF_ES_PERS_UPD_FULL1 = 0x0000013c, // Number of clks ES persistent state update fifo1 is full. + SPI_PERF_ES_FIRST_SUBGRP = 0x0000013d, // Number of first of subgroup waves. + SPI_PERF_ES_LAST_SUBGRP = 0x0000013e, // Number of last of subgroup waves. + SPI_PERF_LS_WINDOW_VALID = 0x0000013f, // Clock count enabled by perfcounter_start event. + SPI_PERF_LS_BUSY = 0x00000140, // Number of clocks with outstanding waves (SPI or SH). + SPI_PERF_LS_CRAWLER_STALL = 0x00000141, // Number of clocks event/wave order fifo is full. + SPI_PERF_LS_FIRST_WAVE = 0x00000142, // Number of first waves. + SPI_PERF_LS_LAST_WAVE = 0x00000143, // Number of last waves. + SPI_PERF_LS_OFFCHIP_LDS_STALL = 0x00000144, // Number of clocks ls is stalled due to offchip LDS. + SPI_PERF_LS_EVENT_WAVE = 0x00000145, // Number of events and waves. + SPI_PERF_LS_WAVE = 0x00000146, // Number of waves. + SPI_PERF_LS_PERS_UPD_FULL0 = 0x00000147, // Number of clks LS persistent state update fifo0 is full. + SPI_PERF_LS_PERS_UPD_FULL1 = 0x00000148, // Number of clks LS persistent state update fifo1 is full. +} SPI_PERFCOUNTER_SELECT; + +typedef enum SQ_PERFCOUNTER_SELECT : unsigned int { + SQ_PERF_SEL_NONE = 0x00000000, // Don't count anything. Perf counter is disabled. + SQ_PERF_SEL_ACCUM_PREV = 0x00000001, // For counter N, increment by the value of counter N-1. + SQ_PERF_SEL_CYCLES = 0x00000002, // Total Clock cycles. {nondeterministic, global} + SQ_PERF_SEL_BUSY_CYCLES = 0x00000003, // Clock cycles while all SQs in SE reporting busy. {nondeterministic, global, C2} + SQ_PERF_SEL_WAVES = 0x00000004, // Count number of waves sent to SQs. {emulated, global, C1} + SQ_PERF_SEL_WAVES_32 = 0x00000005, // Count number of wave32s sent to SQs. {emulated, global, C1} + SQ_PERF_SEL_WAVES_64 = 0x00000006, // Count number of waves64s sent to SQs. {emulated, global, C1} + SQ_PERF_SEL_LEVEL_WAVES = 0x00000007, // Track the aggregated number of waves over certain period of time, Set next counter to ACCUM_PREV and divide by SQ_PERF_SEL_WAVES for average wave life cycle. {level, global, C1} + SQ_PERF_SEL_ITEMS = 0x00000008, // Number of valid work items in SQs. {emulated, global, C1} + SQ_PERF_SEL_WAVE32_ITEMS = 0x00000009, // Number of valid wave32 work items in SQs. {emulated, global, C1} + SQ_PERF_SEL_WAVE64_ITEMS = 0x0000000a, // Number of valid wave64 work items in SQs. {emulated, global, C1} + SQ_PERF_SEL_QUADS = 0x0000000b, // Number of completely or partially covered pixel quads in SQs, note: not all kinds of quads. {emulated, global, C1} + SQ_PERF_SEL_EVENTS = 0x0000000c, // Number of events in SQs. {unwindowed, emulated, global} + SQ_PERF_SEL_WAVES_EQ_64 = 0x0000000d, // Count number of waves with exactly 64 active items sent to SQs. {emulated, global, C1} + SQ_PERF_SEL_WAVES_LT_64 = 0x0000000e, // Count number of waves with <64 active items sent to SQs. {emulated, global, C1} + SQ_PERF_SEL_WAVES_LT_48 = 0x0000000f, // Count number of waves with <48 active items sent to SQs. {emulated, global, C1} + SQ_PERF_SEL_WAVES_LT_32 = 0x00000010, // Count number of waves sent <32 active items sent to SQs. {emulated, global, C1} + SQ_PERF_SEL_WAVES_LT_16 = 0x00000011, // Count number of waves sent <16 active items sent to SQs. {emulated, global, C1} + SQ_PERF_SEL_WAVES_RESTORED = 0x00000012, // Count number of context-restored waves sent to SQs. {emulated, global} + SQ_PERF_SEL_WAVES_SAVED = 0x00000013, // Count number of context-saved waves sent to SQs. {emulated, global} + SQ_PERF_SEL_MSG = 0x00000014, // Number of messages sent, of all types (not including end-program). {nondeterministic, unwindowed, global} + SQ_PERF_SEL_MSG_GSCNT = 0x00000015, // Number of GSCNT messages. {emulated, unwindowed, global} + SQ_PERF_SEL_MSG_INTERRUPT = 0x00000016, // Number of interrupt messages. {emulated, unwindowed, global} + SQ_PERF_SEL_Reserved_1 = 0x00000017, // counter removed + SQ_PERF_SEL_Reserved_2 = 0x00000018, // counter removed + SQ_PERF_SEL_Reserved_3 = 0x00000019, // counter removed + SQ_PERF_SEL_WAVE_CYCLES = 0x0000001a, // Number of clock cycles spent by waves in the SQs. Incremented by # of living (valid) waves each cycle. {nondeterministic, C1} + SQ_PERF_SEL_WAVE_READY = 0x0000001b, // Number of clock cycles waves were ready to execute the next instruction. Incremented by # of waves ready to issue an instruction each cycle. This READY counter will be equal to the sum of: WAIT_INST_* (arb stall) + INST_* (issuing) or INST_WAVE32. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_INST_ANY = 0x0000001c, // Number of clock cycles spent waiting for any instruction issue. In units of cycles. {nondeterministic} + SQ_PERF_SEL_WAIT_INST_VALU = 0x0000001d, // Number of clock cycles spent waiting for VALU instrution issue. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_INST_SCA = 0x0000001e, // Number of clock cycles spent waiting for SALU or SMEM instruction issue. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_INST_LDS = 0x0000001f, // Number of clock cycles spent waiting for LDS (indexed) instruction issue. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_INST_TEX = 0x00000020, // Number of clock cycles spent waiting for TEX (TA) instruction issue. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_INST_FLAT = 0x00000021, // Number of clock cycles spent waiting for flat instruction issue. In units of cycles. {nondeterministic, C2} + SQ_PERF_SEL_WAIT_INST_VMEM = 0x00000022, // Sum of wait_inst_tex + wait_inst_flat + wait_inst_lds {nondeterministic} + SQ_PERF_SEL_WAIT_INST_EXP_GDS = 0x00000023, // Number of clock cycles spent waiting for EXPORT or GDS instruction issue. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_INST_BR_MSG = 0x00000024, // Number of clock cycles spent waiting for BRANCH or SENDMSG instruction issue. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_ANY = 0x00000025, // Number of clock cycles spent waiting for anything. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_CNT_ANY = 0x00000026, // Number of clock cycles spent waiting for any counter. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_CNT_VMVS = 0x00000027, // Number of clock cycles spent waiting for VM or VS counter. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_CNT_LGKM = 0x00000028, // Number of clock cycles spent waiting for LGKM counter. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_CNT_EXP = 0x00000029, // Number of clock cycles spent waiting for EXP counter. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_TTRACE = 0x0000002a, // Number of clock cycles spent waiting for thread trace stalls. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_IFETCH = 0x0000002b, // Number of clock cycles spent waiting for instructions to arrive. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_BARRIER = 0x0000002c, // Number of clock cycles spent waiting for a barrier. In units of cycles. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_EXP_ALLOC = 0x0000002d, // Number of clock cycles spent waiting for export allocation. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_SLEEP = 0x0000002e, // Number of clock cycles spent waiting for sleep to finish. {nondeterministic, C1} + SQ_PERF_SEL_WAIT_SLEEP_XNACK = 0x0000002f, // Number of clock cycles spent waiting for xnack sleep to finish {nondeterministic} + SQ_PERF_SEL_WAIT_OTHER = 0x00000030, // Number of clock cycles spent waiting for halt, waitcnt, trap, host read, etc. {nondeterministic, C1} + SQ_PERF_SEL_INSTS_ALL = 0x00000031, // Number of all instructions issued. {emulated, C1} + SQ_PERF_SEL_INSTS_BRANCH = 0x00000032, // Number of Branch instructions issued. {emulated, C1} + SQ_PERF_SEL_INSTS_CBRANCH_NOT_TAKEN = 0x00000033, // Number of Conditional-Branch instructions issued which were not taken. {emulated} + SQ_PERF_SEL_INSTS_CBRANCH_TAKEN = 0x00000034, // Number of Conditional-Branch instructions issued which were taken. {emulated} + SQ_PERF_SEL_INSTS_CBRANCH_TAKEN_HIT_IS = 0x00000035, // Number of Conditional-Branch instructions issued which were taken and hit in the IS memory. + SQ_PERF_SEL_INSTS_EXP_GDS = 0x00000036, // Number of EXP and GDS instructions issued, excluding skipped export instructions. {emulated, C1} + SQ_PERF_SEL_INSTS_GDS = 0x00000037, // Number of GDS instructions issued. {emulated, C1} + SQ_PERF_SEL_INSTS_EXP = 0x00000038, // Number of EXP instructions issued, excluding skipped export instructions. {emulated, C1} + SQ_PERF_SEL_INSTS_FLAT = 0x00000039, // Number of FLAT instructions issued. {emulated, C2} + SQ_PERF_SEL_Reserved_4 = 0x0000003a, // counter removed + SQ_PERF_SEL_INSTS_LDS = 0x0000003b, // Number of LDS indexed instructions issued. {emulated, C1} + SQ_PERF_SEL_INSTS_SALU = 0x0000003c, // Number of SALU instructions issued. {emulated, C1} + SQ_PERF_SEL_INSTS_SMEM = 0x0000003d, // Number of SMEM instructions issued. {emulated, C1} + SQ_PERF_SEL_INSTS_SMEM_NORM = 0x0000003e, // Number of SMEM instructions issued normalized to match smem_level. It is paired with INST_LEVEL_SMEM. They both increment by 1, 2 or 4, depending on the SMEM instruction. cache inv/wb: inc by # of SQC D$ banks (2); atc probe: 0; all others: 2 {emulated} + SQ_PERF_SEL_INSTS_SENDMSG = 0x0000003f, // Number of Sendmsg instructions issued. {emulated, C1} + SQ_PERF_SEL_INSTS_VALU = 0x00000040, // Number of VALU instructions issued excluding skipped instructions. {emulated, C1} + SQ_PERF_SEL_Reserved_17 = 0x00000041, // counter removed + SQ_PERF_SEL_INSTS_VALU_TRANS32 = 0x00000042, // Number of 32-bit transcendental VALU instructions issued (the type which can be co-executed with main-pipe instructions) excluding skipped instructions. {emulated} + SQ_PERF_SEL_INSTS_VALU_NO_COEXEC = 0x00000043, // Number of VALU instructions issued which can't co-executed in both math pipelines excluding skipped instructions. {emulated} + SQ_PERF_SEL_INSTS_TEX = 0x00000044, // Number of image and buffer instructions issued. {emulated, C1} + SQ_PERF_SEL_INSTS_TEX_LOAD = 0x00000045, // Number of buffer load, image load, sample, or atomic (with return) instructions issued. In GEN0/1, counts both loads and stores. {emulated, C1} + SQ_PERF_SEL_INSTS_TEX_STORE = 0x00000046, // Number of buffer store, image store, or atomic (without return) instructions issued. In GEN0/1, is unused (zero). {emulated, C1} + SQ_PERF_SEL_INSTS_WAVE32 = 0x00000047, // Number of wave32 instructions issued, for flat, lds, valu, tex. {emulated, C1} + SQ_PERF_SEL_INSTS_WAVE32_FLAT = 0x00000048, // Number of wave32 Flat instructions issued. Wave64 may count 1 or 2, depending on what gets issued. {emulated, C2} + SQ_PERF_SEL_Reserved_5 = 0x00000049, // counter removed + SQ_PERF_SEL_INSTS_WAVE32_LDS = 0x0000004a, // Number of wave32 LDS indexed instructions issued. Wave64 may count 1 or 2, depending on what gets issued. {emulated, C1} + SQ_PERF_SEL_INSTS_WAVE32_VALU = 0x0000004b, // Number of wave32 valu instructions issued. Wave64 may count 1 or 2, depending on what gets issued. {emulated, C1} + SQ_PERF_SEL_INSTS_WAVE32_EXP_GDS = 0x0000004c, // Number of wave32 export and GDS instructions issued. {emulated, C1} + SQ_PERF_SEL_INSTS_WAVE32_VALU_TRANS32 = 0x0000004d, // Number of wave32 valu instructions issued using the trans32 pipe only. Wave64 may count 1 or 2, depending on what gets issued. {emulated} + SQ_PERF_SEL_INSTS_WAVE32_VALU_NO_COEXEC = 0x0000004e, // Number of wave32 valu instructions which can't be co-executed in both math pipelines. Wave64 may count 1 or 2, depending on what gets issued. {emulated} + SQ_PERF_SEL_INSTS_WAVE32_TEX = 0x0000004f, // Number of wave32 buffer or image instructions issued. Wave64 may count 1 or 2, depending on what gets issued. {emulated, C1} + SQ_PERF_SEL_INSTS_WAVE32_TEX_LOAD = 0x00000050, // Number of wave32 buffer load, image load, sample, or atomic (with return) instructions issued. Wave64 may count 1 or 2, depending on what gets issued. {emulated} + SQ_PERF_SEL_INSTS_WAVE32_TEX_STORE = 0x00000051, // Number of wave32 buffer store, image store, or atomic (without return) instructions issued. Wave64 may count 1 or 2, depending on what gets issued. {emulated} + SQ_PERF_SEL_ITEM_CYCLES_VALU = 0x00000052, // Number of item-cycles used to execute VALU operations (similar to INST_CYCLES_VALU but multiplied by # of active workitems). {emulated, C1} + SQ_PERF_SEL_VALU_READWRITELANE_CYCLES = 0x00000053, // Number of cycles of readlane and writelane instructions issued. Counts 1 for readlane; counts 1 for writelane in wave32, 2 for writelane in wave64. For writelane instruction, count V_WRITELANE_B32 only excluding V_WRITELANE_REGWR_B32 as it only used during debug. {emulated} + SQ_PERF_SEL_WAVE32_INSTS = 0x00000054, // Number of instructions issued by wave32 waves. Skipped instructions are not counted. {emulated} + SQ_PERF_SEL_WAVE64_INSTS = 0x00000055, // Number of instructions issued by wave64 waves. Skipped instructions are not counted. {emulated} + SQ_PERF_SEL_Reserved_18 = 0x00000056, // counter removed + SQ_PERF_SEL_INSTS_VALU_EXEC_SKIPPED = 0x00000057, // Number of valu instructions completely skipped (wave32, or both halves of a wave64). {emulated} + SQ_PERF_SEL_WAVE64_HALF_SKIP = 0x00000058, // Number of wave64 instructions where half of the instruction was skipped due to EXEC==0 for one half. Does not count fully skipped instructions {emulated} + SQ_PERF_SEL_INSTS_TEX_REPLAY = 0x00000059, // Number of image and buffer instructions replayed. (excluding instructions issued). {emulated, nondeterministic} + SQ_PERF_SEL_INSTS_SMEM_REPLAY = 0x0000005a, // Number of SMEM instructions replayed. (excluding instructions issued). {emulated, nondeterministic} + SQ_PERF_SEL_Reserved_20 = 0x0000005b, // counter removed + SQ_PERF_SEL_INSTS_FLAT_REPLAY = 0x0000005c, // Number of FLAT instructions replayed. (excluding instructions issued). {emulated, nondeterministic} + SQ_PERF_SEL_TA_XNACK_ALL = 0x0000005d, // Number of all xnack from TA. + SQ_PERF_SEL_TA_XNACK_FIRST = 0x0000005e, // Number of first xnack from TA. {emulated} + SQ_PERF_SEL_INSTS_VALU_LDS_DIRECT_RD = 0x0000005f, // Number of VALU instructions (in units of wave32's, so wave64 may count twice) that use LDS_DIRECT_RD (not interpolation) excluding skipped instructions. {emulated, C1} + SQ_PERF_SEL_INSTS_VALU_VINTRP_OP = 0x00000060, // Number of VALU instructions (in units of wave32's, so wave64 may count twice) that use parameter interpolation excluding skipped instructions. {emulated, C1} + SQ_PERF_SEL_INST_LEVEL_EXP = 0x00000061, // Number of in-flight EXP instructions. Set next counter to ACCUM_PREV and divide by INSTS_EXP for average latency. {level, nondeterministic, C1} + SQ_PERF_SEL_INST_LEVEL_GDS = 0x00000062, // Number of in-flight GDS instructions. Set next counter to ACCUM_PREV and divide by INSTS_GDS for average latency. {level, nondeterministic, C1} + SQ_PERF_SEL_INST_LEVEL_LDS = 0x00000063, // Number of in-flight LDS instructions. Set next counter to ACCUM_PREV and divide by INSTS_LDS for average latency. Includes FLAT instructions. {level, nondeterministic, C1} + SQ_PERF_SEL_INST_LEVEL_SMEM = 0x00000064, // Number of in-flight SMEM instructions. Set next counter to ACCUM_PREV and divide by INSTS_SMEM for average latency per smem request. Falls slightly short of total request latency because some fetches are divided into two requests that may finish at different times and this counter collects the average latency of the two. {level, nondeterministic, C1} + SQ_PERF_SEL_INST_LEVEL_TEX_LOAD = 0x00000065, // Number of in-flight buffer load, image load, sample, or atomic (with return) instructions. Set next counter to ACCUM_PREV and divide by INST_TEX_LOAD for average latency. Includes FLAT instructions. {level, nondeterministic, C2} + SQ_PERF_SEL_INST_LEVEL_TEX_STORE = 0x00000066, // Number of in-flight buffer store, image store, or atomic (without return) instructions. Set next counter to ACCUM_PREV and divide by INSTS_TEX_STORE for average latency. Includes FLAT instructions. {level, nondeterministic, C2} + SQ_PERF_SEL_IFETCH_REQS = 0x00000067, // Number of instruction fetch requests to SQC cache. {emulated, C1} + SQ_PERF_SEL_IFETCH_LEVEL = 0x00000068, // Number of in-flight instruction fetch requests to SQC cache. Set next counter to ACCUM_PREV and divide by SQ_PERF_SEL_IFETCH_REQS for average latency. {level, C1} + SQ_PERF_SEL_IFETCH_XNACK = 0x00000069, // Number of instruction fetch xnack from SQC. {per-simd} + SQ_PERF_SEL_Reserved_6 = 0x0000006a, // counter removed + SQ_PERF_SEL_Reserved_7 = 0x0000006b, // counter removed + SQ_PERF_SEL_LDS_DIRECT_CMD_FIFO_FULL_STALL = 0x0000006c, // Number of cycles LDS-direct command from SQ was stalled due to LDS-direct cmd fifo full + SQ_PERF_SEL_VALU_SGATHER_STALL = 0x0000006d, // Cycles where SQ SGPR gather stalled for VALU. + SQ_PERF_SEL_VALU_FWD_BUFFER_FULL_STALL = 0x0000006e, // Cycles where SQ SGPR gather stalled for VALU due to VALU FWD buffer full + SQ_PERF_SEL_VALU_SGPR_RD_FIFO_FULL_STALL = 0x0000006f, // Cycles where SQ SGPR gather stalled for VALU due to an SGPR read FIFO being full + SQ_PERF_SEL_VALU_SGATHER_FULL_STALL = 0x00000070, // Cycles where SQ SGPR gather stalled for VALU due to gatherer stages full + SQ_PERF_SEL_SALU_SGATHER_STALL = 0x00000071, // Cycles where SQ SGPR gather stalled for SALU. + SQ_PERF_SEL_SALU_SGPR_RD_FIFO_FULL_STALL = 0x00000072, // Cycles where SQ SGPR gather stalled for SALU due to an SGPR read FIFO being full + SQ_PERF_SEL_SALU_GATHER_FULL_STALL = 0x00000073, // Cycles where SQ SGPR gather stalled for SALU due to gatherer stages full + SQ_PERF_SEL_SMEM_DCACHE_FIFO_FULL_STALL = 0x00000074, // Cycles where arbiter wanted to issue SMEM but couldn't because DCACHE input fifo was full + SQ_PERF_SEL_INST_CYCLES_VALU = 0x00000075, // Number of cycles needed to execute VALU operations (SIMD cycles), where there is overlapping V_OP32_1 and V_OP32_T instruction, count them seperately. {emulated, C1} + SQ_PERF_SEL_INST_CYCLES_VALU_TRANS32 = 0x00000076, // Number of cycles needed to execute VALU trans32 operations (SIMD cycles). {emulated} + SQ_PERF_SEL_INST_CYCLES_VALU_NO_COEXEC = 0x00000077, // Number of cycles which can't co-executed in both math pipelines (SIMD cycles). {emulated} + SQ_PERF_SEL_INST_CYCLES_VMEM = 0x00000078, // Number of cycles needed to send addr and data for VMEM (lds, buffer, image, flat, scratch, global) instructions, windowed by perf_en. {emulated, C1} + SQ_PERF_SEL_INST_CYCLES_VMEM_LOAD = 0x00000079, // Number of cycles needed to send addr and data for VMEM loads (lds, buffer, image, flat, scratch, global) instructions. {emulated, C1} + SQ_PERF_SEL_INST_CYCLES_VMEM_STORE = 0x0000007a, // Number of cycles needed to send addr and data for VMEM stores & atomics (lds, buffer, image, flat, scratch, global) instructions. {emulated, C1} + SQ_PERF_SEL_INST_CYCLES_LDS = 0x0000007b, // Number of cycles needed to send addr and data for LDS indexed instructions. {emulated, C2} + SQ_PERF_SEL_INST_CYCLES_TEX = 0x0000007c, // Number of cycles needed to send addr and data for TEX (buffer, image) instructions. {emulated} + SQ_PERF_SEL_INST_CYCLES_FLAT = 0x0000007d, // Number of cycles needed to send addr and data for FLAT (flat, scratch, global) instructions. {emulated} + SQ_PERF_SEL_INST_CYCLES_EXP_GDS = 0x0000007e, // Number of cycles needed to export data for EXP and GDS instructions. It counts the grant cycles from SPI, each instruction could have 1-8 grants. EXP and GDS instruction share the same path and hardware. {emulated, C2} + SQ_PERF_SEL_INST_CYCLES_EXP = 0x0000007f, // Number of cycles needed to export data for EXP instructions. {emulated, C1} + SQ_PERF_SEL_INST_CYCLES_GDS = 0x00000080, // Number of cycles needed to export data for GDS instructions. {emulated, C1} + SQ_PERF_SEL_VALU_STARVE = 0x00000081, // Number of cycles VALU is starved while waves are present (cycles in which no sq_sp_cmd credits are in use). {nondeterministic, C1} + SQ_PERF_SEL_VMEM_ARB_FIFO_FULL = 0x00000082, // Number of cycles instruction arbiter was stalled trying to issue a VMEM op but the vmem-arbiter's input fifo was full. + SQ_PERF_SEL_MSG_FIFO_FULL_STALL = 0x00000083, // Number of cycles the instruction arbiter was stalled trying to issue a message because SQCs message fifo was full. + SQ_PERF_SEL_EXP_REQ_FIFO_FULL = 0x00000084, // Number of cycles the instruction arbiter was stalled from issuing an export request (or GDS) because the export-request buffer was full. {C1} + SQ_PERF_SEL_Reserved_11 = 0x00000085, // counter removed + SQ_PERF_SEL_Reserved_12 = 0x00000086, // counter removed + SQ_PERF_SEL_Reserved_13 = 0x00000087, // counter removed + SQ_PERF_SEL_Reserved_14 = 0x00000088, // counter removed + SQ_PERF_SEL_VMEM_BUS_ACTIVE = 0x00000089, // Cycles sending address/data to LDS/TA, not windowed by perf_en + SQ_PERF_SEL_VMEM_BUS_STALL = 0x0000008a, // Cycles stalled from sending address/data to LDS/TA + SQ_PERF_SEL_VMEM_BUS_STALL_TA_ADDR_FIFO_FULL = 0x0000008b, // Cycles stalled due to TA addr/data fifo full. {nondeterministic, C1} + SQ_PERF_SEL_VMEM_BUS_STALL_TA_CMD_FIFO_FULL = 0x0000008c, // Cycles stalled due to TA cmd fifo full. {nondeterministic, C1} + SQ_PERF_SEL_VMEM_BUS_STALL_LDS_ADDR_FIFO_FULL = 0x0000008d, // Cycles stalled due to LDS addr/data fifo full. {nondeterministic, C1} + SQ_PERF_SEL_VMEM_BUS_STALL_LDS_CMD_FIFO_FULL = 0x0000008e, // Cycles stalled due to LDS cmd fifo full. {nondeterministic, C1} + SQ_PERF_SEL_VMEM_STARVE_TA_ADDR_EMPTY = 0x0000008f, // Cycles starved due to LDS addr/data fifo empty + SQ_PERF_SEL_VMEM_STARVE_LDS_ADDR_EMPTY = 0x00000090, // Cycles starved due to LDS addr/data fifo empty + SQ_PERF_SEL_Reserved_15 = 0x00000091, // counter removed + SQ_PERF_SEL_SALU_PIPE_STALL = 0x00000092, // Cycles that SALU math pipeline is stalled due to SGPR-write-back. + SQ_PERF_SEL_SMEM_DCACHE_RETURN_CYCLES = 0x00000093, // Cycles that SQC-D$ is returning data to SQ + SQ_PERF_SEL_Reserved_21 = 0x00000094, // counter removed + SQ_PERF_SEL_MSG_BUS_BUSY = 0x00000095, // Cycles in which a valid message (other than token) is on the message bus. (measured in SQG) + SQ_PERF_SEL_EXP_REQ_BUS_STALL = 0x00000096, // Cycles in which SQ wants to send an export request but is blocked due the bus already being busy. + SQ_PERF_SEL_EXP_REQ0_BUS_BUSY = 0x00000097, // Cycles in which export request bus 0 is busy. (measured in SQG) + SQ_PERF_SEL_EXP_REQ1_BUS_BUSY = 0x00000098, // Cycles in which export request bus 0 is busy. (measured in SQG) + SQ_PERF_SEL_EXP_BUS0_BUSY = 0x00000099, // Cycles in which export data bus is busy (measured in SQG by looking at export grant. wave64 grant counts for 2) + SQ_PERF_SEL_EXP_BUS1_BUSY = 0x0000009a, // Cycles in which export data bus is busy (measured in SQG by looking at export grant. wave64 grant counts for 2) + SQ_PERF_SEL_Reserved_19 = 0x0000009b, // counter removed + SQ_PERF_SEL_INST_CACHE_REQ_STALL = 0x0000009c, // Number of cycles SQ was stalled from making an instruction request due to SQC's input fifo full + SQ_PERF_SEL_MIXED_SUBSEQUENT_ISSUES_VALU = 0x0000009d, // Number of cycles in which SQ issued a VALU instruction in one compat-mode immediately followed by another VALU instruction in a different compat mode. + SQ_PERF_SEL_MIXED_SUBSEQUENT_ISSUES_SALU = 0x0000009e, // Number of cycles in which SQ issued a SALU instruction in one compat-mode immediately followed by another SALU instruction in a different compat mode. + SQ_PERF_SEL_MIXED_SUBSEQUENT_ISSUES_VMEM = 0x0000009f, // Number of cycles in which SQ issued a VMEM instruction in one compat-mode immediately followed by another VMEM instruction in a different compat mode. + SQ_PERF_SEL_USER0 = 0x000000a0, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 0. {emulated, C2} + SQ_PERF_SEL_USER1 = 0x000000a1, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 1. {emulated, C2} + SQ_PERF_SEL_USER2 = 0x000000a2, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 2. {emulated, C2} + SQ_PERF_SEL_USER3 = 0x000000a3, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 3. {emulated, C2} + SQ_PERF_SEL_USER4 = 0x000000a4, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 4. {emulated, C2} + SQ_PERF_SEL_USER5 = 0x000000a5, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 5. {emulated, C2} + SQ_PERF_SEL_USER6 = 0x000000a6, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 6. {emulated, C2} + SQ_PERF_SEL_USER7 = 0x000000a7, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 7. {emulated, C2} + SQ_PERF_SEL_USER8 = 0x000000a8, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 8. {emulated, C2} + SQ_PERF_SEL_USER9 = 0x000000a9, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 9. {emulated, C2} + SQ_PERF_SEL_USER10 = 0x000000aa, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 10. {emulated, C2} + SQ_PERF_SEL_USER11 = 0x000000ab, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 11. {emulated, C2} + SQ_PERF_SEL_USER12 = 0x000000ac, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 12. {emulated, C2} + SQ_PERF_SEL_USER13 = 0x000000ad, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 13. {emulated, C2} + SQ_PERF_SEL_USER14 = 0x000000ae, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 14. {emulated, C2} + SQ_PERF_SEL_USER15 = 0x000000af, // User counter. Incremented by S_INCPERFLEVEL when SIMM16[3:0] == 15. {emulated, C2} + SQ_PERF_SEL_USER_LEVEL0 = 0x000000b0, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 0. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL1 = 0x000000b1, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 1. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL2 = 0x000000b2, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 2. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL3 = 0x000000b3, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 3. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL4 = 0x000000b4, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 4. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL5 = 0x000000b5, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 5. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL6 = 0x000000b6, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 6. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL7 = 0x000000b7, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 7. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL8 = 0x000000b8, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 8. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL9 = 0x000000b9, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 9. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL10 = 0x000000ba, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 10. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL11 = 0x000000bb, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 11. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL12 = 0x000000bc, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 12. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL13 = 0x000000bd, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 13. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL14 = 0x000000be, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 14. {level, emulated, C2} + SQ_PERF_SEL_USER_LEVEL15 = 0x000000bf, // User level counter. Incremented by S_INCPERFLEVEL, decremented by S_DECPERFLEVEL when SIMM16[3:0] == 15. {level, emulated, C2} + SQ_PERF_SEL_VALU_RETURN_SDST = 0x000000c0, // Count the number of VALU instructions issued which return data to the SQ (EXEC or SGPR/VCC). This is also equal to the number of dwords sent from SP to SQ. {emulated} + SQ_PERF_SEL_VMEM_SECOND_TRY_USED = 0x000000c1, // Number of times the second-try buffer was loaded with a new value. + SQ_PERF_SEL_VMEM_SECOND_TRY_STALL = 0x000000c2, // Number of times the second-try buffer was already full and this caused a VMEM stall. {C2} + SQ_PERF_SEL_INSTS_VALU_TRANS = 0x000000c3, // Number transcendental VALU instructions issued {emulated} + SQ_PERF_SEL_DUMMY_END = 0x000000c4, // Just a placeholding enum to indicate the end of real SQ performance counter. Not a real performance counter. + SQ_PERF_SEL_DUMMY_LAST = 0x000000ff, // Just a placeholding enum to separate SQ from SQC/SQG counters. Not a real performance counter. + SQG_PERF_SEL_UTCL0_TRANSLATION_MISS = 0x00000100, // Total UTCL0 translation misses {C1} + SQG_PERF_SEL_UTCL0_PERMISSION_MISS = 0x00000101, // Total UTCL0 permission misses + SQG_PERF_SEL_UTCL0_TRANSLATION_HIT = 0x00000102, // Total UTCL0 translation hit events {C1} + SQG_PERF_SEL_UTCL0_REQUEST = 0x00000103, // Total UTCL0 NORMAL requests + SQG_PERF_SEL_UTCL0_STALL_MISSFIFO_FULL = 0x00000104, // Total UTCL0 stall due to full miss fifo {C1} + SQG_PERF_SEL_UTCL0_STALL_INFLIGHT_MAX = 0x00000105, // Total UTCL0 stalls due to inflight counter saturation + SQG_PERF_SEL_UTCL0_STALL_LRU_INFLIGHT = 0x00000106, // Total UTCL0 stalls due to LRU cache line with traffic inflight + SQG_PERF_SEL_UTCL0_LFIFO_FULL = 0x00000107, // Total UTCL0 latency hiding fifo full cycles + SQG_PERF_SEL_UTCL0_STALL_LFIFO_NOT_RES = 0x00000108, // Total UTCL0 stalls due to latency latency hiding fifo output not resident + SQG_PERF_SEL_UTCL0_STALL_UTCL1_REQ_OUT_OF_CREDITS = 0x00000109, // Total UTCL1 stalls due to UTCL1 requests out of credits + SQG_PERF_SEL_UTCL0_HIT_FIFO_FULL = 0x0000010a, // Total UTCL0 hit fifo full cycles + SQG_PERF_SEL_UTCL0_UTCL1_REQ = 0x0000010b, // Total UTCL0 to UTCL1 requests {C1} + SQG_PERF_SEL_TLB_SHOOTDOWN = 0x0000010c, // Number of TLB shootdowns. {unwindowed, emulated, global} + SQG_PERF_SEL_TLB_SHOOTDOWN_CYCLES = 0x0000010d, // Number of cycles in which a TLB shootdown is active. {unwindowed, global} + SQG_PERF_SEL_TTRACE_REQS = 0x0000010e, // Number of thread trace requests. {unwindowed, global, nondeterministic, C2} + SQG_PERF_SEL_TTRACE_INFLIGHT_REQS = 0x0000010f, // Number of in-flight thread trace requests. {nondeterministic, unwindowed, global, C2} + SQG_PERF_SEL_TTRACE_STALL = 0x00000110, // Number of cycles thread trace stalls stalled execution. {nondeterministic, unwindowed, global, C2} + SQG_PERF_SEL_TTRACE_LOST_PACKETS = 0x00000111, // Number of thread trace lost packets. {unwindowed, global, nondeterministic} + SQG_PERF_SEL_DUMMY_LAST = 0x00000112, // Just a placeholding enum to indicate the last SQG performance counter. Not a real performance counter. + SQC_PERF_SEL_POWER_VALU = 0x00000113, // Number of CAC pulses for ALU instructions {nondeterministic, unwindowed} + SQC_PERF_SEL_POWER_VALU0 = 0x00000114, // Number of CAC pulses for ALU instructions in group 0 {nondeterministic, unwindowed} + SQC_PERF_SEL_POWER_VALU1 = 0x00000115, // Number of CAC pulses for ALU instructions in group 1 {nondeterministic, unwindowed} + SQC_PERF_SEL_POWER_VALU2 = 0x00000116, // Number of CAC pulses for ALU instructions in group 2 {nondeterministic, unwindowed} + SQC_PERF_SEL_POWER_GPR_RD = 0x00000117, // Number of CAC pulses for GPR reads {nondeterministic, unwindowed} + SQC_PERF_SEL_POWER_GPR_WR = 0x00000118, // Number of CAC pulses for GPR writes {nondeterministic, unwindowed} + SQC_PERF_SEL_POWER_LDS_BUSY = 0x00000119, // Number of CAC pulses for cycles LDS clocks are active {nondeterministic, unwindowed} + SQC_PERF_SEL_POWER_ALU_BUSY = 0x0000011a, // Number of CAC pulses for cycles ALU clocks are active {nondeterministic, unwindowed} + SQC_PERF_SEL_POWER_TEX_BUSY = 0x0000011b, // Number of CAC pulses for cycles texture clocks are active {nondeterministic, unwindowed} + SQC_PERF_SEL_PT_POWER_STALL = 0x0000011c, // Number of cycles the power throttle indicated ALU should stall (ignores whether something actually got stalled). {nondeterministic, unwindowed} + SQC_PERF_SEL_LDS_BANK_CONFLICT = 0x0000011d, // Number of cycles LDS is stalled by bank conflicts. {emulated, C1} + SQC_PERF_SEL_LDS_ADDR_CONFLICT = 0x0000011e, // Number of cycles LDS is stalled by address conflicts. {emulated, nondeterministic, C1} + SQC_PERF_SEL_LDS_UNALIGNED_STALL = 0x0000011f, // Number of cycles LDS is stalled processing flat unaligned load/store ops. {emulated, C2} + SQC_PERF_SEL_LDS_MEM_VIOLATIONS = 0x00000120, // Number of threads that have a memory violation in the LDS. {emulated, C1} + SQC_PERF_SEL_LDS_ATOMIC_RETURN = 0x00000121, // Number of atomic return cycles in LDS. {per-simd, emulated, C1} + SQC_PERF_SEL_LDS_IDX_ACTIVE = 0x00000122, // Number of cycles LDS is used for indexed (non-direct,non-interpolation) operations. {per-simd, emulated, C1} + SQC_PERF_SEL_LDS_ADDR_STALL = 0x00000123, // WGP addressing stall clocks for each DS (one DS stalled to allow other DS to access local bank rams) + SQC_PERF_SEL_LDS_ADDR_ACTIVE = 0x00000124, // WGP addressing active clocks for each DS (active DS with at least one valid address in non-local bank rams getting access) + SQC_PERF_SEL_LDS_DIRECT_FIFO_FULL_STALL = 0x00000125, // Direct read stalled because of no credit available for each SIMD (SP) + SQC_PERF_SEL_LDS_PC_LDS_WRITE_STALL_TD = 0x00000126, // Direct TD_LDS write stalled clocks because of PC_LDS writes for each TD + SQC_PERF_SEL_LDS_SPI_VGPR_WRITE_STALL_TD = 0x00000127, // TD_SP writes stalled clocks because of SPI_SP bank match for each TD + SQC_PERF_SEL_LDS_LDS_VGPR_WRITE_STALL = 0x00000128, // LDS_SP writes stalled clocks because of SPI_SP or TD_SP bank match for each DS + SQC_PERF_SEL_LDS_FP_ADD_CYCLES = 0x00000129, // Number of cycles spent performing floating point adds in LDS + SQC_PERF_SEL_ICACHE_BUSY_CYCLES = 0x0000012a, // Clock cycles while cache is reporting that it is busy. {No-Masking, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_REQ = 0x0000012b, // Number of requests. {emulated, per-Bank, C1} + SQC_PERF_SEL_ICACHE_HITS = 0x0000012c, // Number of cache hits. {per-Bank, nondeterministic, C2} + SQC_PERF_SEL_ICACHE_MISSES = 0x0000012d, // Number of cache misses, includes uncached requests. {per-Bank, nondeterministic, C2} + SQC_PERF_SEL_ICACHE_MISSES_DUPLICATE = 0x0000012e, // Number of misses that were duplicates (access to a non-resident, miss pending CL). {per-Bank, nondeterministic, C2} + SQC_PERF_SEL_ICACHE_INVAL_INST = 0x0000012f, // Number of cache invalidations caused by instructions {No-Masking, C2} + SQC_PERF_SEL_ICACHE_INVAL_ASYNC = 0x00000130, // Number of asynchronous invalidates (surface sync, register write, etc.) {No-Masking, unwindowed, C2} + SQC_PERF_SEL_ICACHE_INFLIGHT_LEVEL = 0x00000131, // Level Counter: # total outstanding transactions in instruction cache {nondeterministic, C2} + SQC_PERF_SEL_DCACHE_INFLIGHT_LEVEL = 0x00000132, // Level Counter: # total outstanding transactions in data cache {nondeterministic, C2} + SQC_PERF_SEL_TC_INFLIGHT_LEVEL = 0x00000133, // Level Counter: total outstanding requests to TC {No-Masking, nondeterministic, C2} + SQC_PERF_SEL_ICACHE_TC_INFLIGHT_LEVEL = 0x00000134, // Level Counter: # of outstanding instruction requests to TC {No-Masking, nondeterministic, C2} + SQC_PERF_SEL_DCACHE_TC_INFLIGHT_LEVEL = 0x00000135, // Level Counter: # of outstanding data requests to TC {No-Masking, nondeterministic, C2} + SQC_PERF_SEL_ICACHE_INPUT_VALID_READY = 0x00000136, // Successful Transaction {nondeterministic, unwindowed} + SQC_PERF_SEL_ICACHE_INPUT_VALID_READYB = 0x00000137, // Input stalled by SQC {nondeterministic, unwindowed} + SQC_PERF_SEL_ICACHE_INPUT_VALIDB = 0x00000138, // SQC starved {nondeterministic, unwindowed} + SQC_PERF_SEL_DCACHE_INPUT_VALID_READY = 0x00000139, // Successful Transaction {nondeterministic, unwindowed} + SQC_PERF_SEL_DCACHE_INPUT_VALID_READYB = 0x0000013a, // Input stalled by SQC {nondeterministic, unwindowed} + SQC_PERF_SEL_DCACHE_INPUT_VALIDB = 0x0000013b, // SQC starved {nondeterministic, unwindowed} + SQC_PERF_SEL_TC_REQ = 0x0000013c, // Total number of TC requests that were issued by instruction and constant caches. {No-Masking, nondeterministic, C2} + SQC_PERF_SEL_TC_INST_REQ = 0x0000013d, // Number of insruction requests to the TC {No-Masking, nondeterministic, C2} + SQC_PERF_SEL_TC_DATA_READ_REQ = 0x0000013e, // Number of data read requests to the TC {No-Masking, nondeterministic, C2} + SQC_PERF_SEL_Reserved_0x13f = 0x0000013f, // Reserved. + SQC_PERF_SEL_Reserved_0x140 = 0x00000140, // Reserved. + SQC_PERF_SEL_TC_STALL = 0x00000141, // Valid request stalled TC request interface (no-credits). {No-Masking, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_TC_STARVE = 0x00000142, // No requests sent to TC while credits available. {No-Masking, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_INPUT_STALL_ARB_NO_GRANT = 0x00000143, // Number of arbitration stalls due to lost arbitration to other SQs. {nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_INPUT_STALL_BANK_READYB = 0x00000144, // Number of arbitration stalls due to bank stalling. {nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_CACHE_STALLED = 0x00000145, // Number of cache stalls. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_CACHE_STALL_INFLIGHT_NONZERO = 0x00000146, // Number of cycles stalled because allocated line has nonzero inflight. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_CACHE_STALL_INFLIGHT_MAX = 0x00000147, // Number of cycles stalled on a hit CL but inflight counter is maxed out. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_CACHE_STALL_OUTPUT = 0x00000148, // Number of cycles stalled at cache controller output. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_CACHE_STALL_OUTPUT_MISS_FIFO = 0x00000149, // Number of cycles stalled because the miss FIFO is full. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_CACHE_STALL_OUTPUT_HIT_FIFO = 0x0000014a, // Number of cycles stalled because a hit FIFO is full. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_CACHE_STALL_OUTPUT_TC_IF = 0x0000014b, // Number of cycles stalled because the TC request interface is stalled. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_ICACHE_STALL_OUTXBAR_ARB_NO_GRANT = 0x0000014c, // Number of arbitration stalls due to lost arbitration for the output port. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_BUSY_CYCLES = 0x0000014d, // Clock cycles while cache is reporting that it is busy. {No-Masking, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_REQ = 0x0000014e, // Number of requests (post-bank-serialization). {per-Bank, C1} + SQC_PERF_SEL_DCACHE_HITS = 0x0000014f, // Number of cache hits. {per-Bank, nondeterministic, C2} + SQC_PERF_SEL_DCACHE_MISSES = 0x00000150, // Number of cache misses, includes uncached requests. {per-Bank, nondeterministic, C2} + SQC_PERF_SEL_DCACHE_MISSES_DUPLICATE = 0x00000151, // Number of misses that were duplicates (access to a non-resident, miss pending CL). {per-Bank, nondeterministic, C2} + SQC_PERF_SEL_DCACHE_INVAL_INST = 0x00000152, // Number of cache invalidations caused by instructions {No-Masking, C2} + SQC_PERF_SEL_DCACHE_INVAL_ASYNC = 0x00000153, // Number of asynchronous invalidates (surface sync, register write, etc.) {No-Masking, unwindowed, C2} + SQC_PERF_SEL_DCACHE_HIT_LRU_READ = 0x00000154, // Number of HIT_LRU read requests. (per-Bank) + SQC_PERF_SEL_Reserved_0x155 = 0x00000155, // Reserved. + SQC_PERF_SEL_Reserved_0x156 = 0x00000156, // Reserved. + SQC_PERF_SEL_Reserved_0x157 = 0x00000157, // Reserved. + SQC_PERF_SEL_Reserved_0x158 = 0x00000158, // Reserved. + SQC_PERF_SEL_Reserved_0x159 = 0x00000159, // Reserved. + SQC_PERF_SEL_DCACHE_INPUT_STALL_ARB_NO_GRANT = 0x0000015a, // Number of arbitration stalls due to lost arbitration to other SQs. {nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_INPUT_STALL_BANK_READYB = 0x0000015b, // Number of arbitration stalls due to bank stalling. {nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_CACHE_STALLED = 0x0000015c, // Number of cache stalls. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_CACHE_STALL_INFLIGHT_MAX = 0x0000015d, // Number of cycles stalled on a hit CL but inflight counter is maxed out. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_CACHE_STALL_OUTPUT = 0x0000015e, // Number of cycles stalled at cache controller output. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_CACHE_STALL_EVICT = 0x0000015f, // Number of cycles stalled trying to do an evict. {per-Bank, nondeterministic, unwindowed} + SQC_PERF_SEL_DCACHE_CACHE_STALL_UNORDERED = 0x00000160, // Number of cycles stalled due to an unordered access conflict. {per-Bank, nondeterministic, unwindowed} + SQC_PERF_SEL_DCACHE_CACHE_STALL_ALLOC_UNAVAILABLE = 0x00000161, // Number of cycles stalled due to not being able to allocate a line. {per-Bank, nondeterministic, unwindowed} + SQC_PERF_SEL_DCACHE_CACHE_STALL_FORCE_EVICT = 0x00000162, // Number of cycles stalled due to having to force an eviction. {per-Bank, nondeterministic, unwindowed} + SQC_PERF_SEL_DCACHE_CACHE_STALL_MULTI_FLUSH = 0x00000163, // Number of cycles stalled due to multiple flushes. {per-Bank, nondeterministic, unwindowed} + SQC_PERF_SEL_DCACHE_CACHE_STALL_FLUSH_DONE = 0x00000164, // Number of cycles stalled inserting flush done tokens into pipe. {per-Bank, nondeterministic, unwindowed} + SQC_PERF_SEL_DCACHE_CACHE_STALL_OUTPUT_MISS_FIFO = 0x00000165, // Number of cycles stalled because the miss FIFO is full. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_CACHE_STALL_OUTPUT_HIT_FIFO = 0x00000166, // Number of cycles stalled because a hit FIFO is full. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_CACHE_STALL_OUTPUT_TC_IF = 0x00000167, // Number of cycles stalled because the TC request interface is stalled. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_STALL_OUTXBAR_ARB_NO_GRANT = 0x00000168, // Number of arbitration stalls due to lost arbitration for the output port. {per-Bank, nondeterministic, unwindowed, C2} + SQC_PERF_SEL_DCACHE_REQ_READ_1 = 0x00000169, // Number of constant cache 1 dw read requests. {C2} + SQC_PERF_SEL_DCACHE_REQ_READ_2 = 0x0000016a, // Number of constant cache 2 dw read requests. {C2} + SQC_PERF_SEL_DCACHE_REQ_READ_4 = 0x0000016b, // Number of constant cache 4 dw read requests. {C2} + SQC_PERF_SEL_DCACHE_REQ_READ_8 = 0x0000016c, // Number of constant cache 8 dw read requests. {C2} + SQC_PERF_SEL_DCACHE_REQ_READ_16 = 0x0000016d, // Number of constant cache 16 dw read requests. {C2} + SQC_PERF_SEL_DCACHE_REQ_TIME = 0x0000016e, // Number of constant cache timestamp requests. {C2} + SQC_PERF_SEL_Reserved_0x16f = 0x0000016f, // Reserved. + SQC_PERF_SEL_Reserved_0x170 = 0x00000170, // Reserved. + SQC_PERF_SEL_Reserved_0x171 = 0x00000171, // Reserved. + SQC_PERF_SEL_DCACHE_REQ_ATC_PROBE = 0x00000172, // Number of constant cache atc probe requests. + SQC_PERF_SEL_SQ_DCACHE_REQS = 0x00000173, // Number of constant requests from SQ before any serialization. {C1} + SQC_PERF_SEL_DCACHE_FLAT_REQ = 0x00000174, // Number of constant flat requests. + SQC_PERF_SEL_DCACHE_NONFLAT_REQ = 0x00000175, // Number of constant non-flat requests. {C2} + SQC_PERF_SEL_ICACHE_UTCL0_TRANSLATION_MISS = 0x00000176, // Total ICACHE utcl0 translation misses {C1} + SQC_PERF_SEL_ICACHE_UTCL0_PERMISSION_MISS = 0x00000177, // Total ICACHE utcl0 permission misses + SQC_PERF_SEL_ICACHE_UTCL0_TRANSLATION_HIT = 0x00000178, // Total ICACHE utcl0 translation hits {C1} + SQC_PERF_SEL_ICACHE_UTCL0_REQUEST = 0x00000179, // Total ICACHE CLIENT_UTCL0 NORMAL requests + SQC_PERF_SEL_ICACHE_UTCL0_XNACK = 0x0000017a, // Total ICACHE CLIENT_UTCL0 XNACKs returned from UTCL0 + SQC_PERF_SEL_ICACHE_UTCL0_STALL_INFLIGHT_MAX = 0x0000017b, // Total ICACHE utcl0 stalls due to inflight counter saturation + SQC_PERF_SEL_ICACHE_UTCL0_STALL_LRU_INFLIGHT = 0x0000017c, // Total ICACHE utcl0 stalls due to LRU cache line with traffic inflight + SQC_PERF_SEL_ICACHE_UTCL0_LFIFO_FULL = 0x0000017d, // Total ICACHE utcl0 utcl1 latency hiding fifo full cycles + SQC_PERF_SEL_ICACHE_UTCL0_STALL_LFIFO_NOT_RES = 0x0000017e, // Total ICACHE utcl0 stalls due to utcl1 latency hiding fifo output not resident + SQC_PERF_SEL_ICACHE_UTCL0_STALL_UTCL1_REQ_OUT_OF_CREDITS = 0x0000017f, // Total ICACHE utcl0 stalls due to utcl1_req out of credits + SQC_PERF_SEL_ICACHE_UTCL0_UTCL1_INFLIGHT = 0x00000180, // The sum of ICACHE inflight UTCL0_UTCL1 requests per cycle + SQC_PERF_SEL_ICACHE_UTCL0_STALL_MISSFIFO_FULL = 0x00000181, // Total ICACHE utcl0 stalls due to full miss fifo {C1} + SQC_PERF_SEL_DCACHE_UTCL0_TRANSLATION_MISS = 0x00000182, // Total DCACHE utcl0 translation misses {C1} + SQC_PERF_SEL_DCACHE_UTCL0_PERMISSION_MISS = 0x00000183, // Total DCACHE utcl0 permission misses + SQC_PERF_SEL_DCACHE_UTCL0_TRANSLATION_HIT = 0x00000184, // Total DCACHE utcl0 translation hits {C1} + SQC_PERF_SEL_DCACHE_UTCL0_REQUEST = 0x00000185, // Total DCACHE CLIENT_UTCL0 NORMAL requests + SQC_PERF_SEL_DCACHE_UTCL0_XNACK = 0x00000186, // Total DCACHE CLIENT_UTCL0 XNACKs returned from UTCL0 + SQC_PERF_SEL_DCACHE_UTCL0_STALL_INFLIGHT_MAX = 0x00000187, // Total DCACHE utcl0 stalls due to inflight counter saturation + SQC_PERF_SEL_DCACHE_UTCL0_STALL_LRU_INFLIGHT = 0x00000188, // Total DCACHE utcl0 stalls due to LRU cache line with traffic inflight + SQC_PERF_SEL_DCACHE_UTCL0_LFIFO_FULL = 0x00000189, // Total DCACHE utcl0 utcl1 latency hiding fifo full cycles + SQC_PERF_SEL_DCACHE_UTCL0_STALL_LFIFO_NOT_RES = 0x0000018a, // Total DCACHE utcl0 stalls due to utcl1 latency hiding fifo output not resident + SQC_PERF_SEL_DCACHE_UTCL0_STALL_UTCL1_REQ_OUT_OF_CREDITS = 0x0000018b, // Total DCACHE utcl0 stalls due to utcl1_req out of credits + SQC_PERF_SEL_DCACHE_UTCL0_UTCL1_INFLIGHT = 0x0000018c, // The sum of DCACHE inflight UTCL0_UTCL1 requests per cycle + SQC_PERF_SEL_DCACHE_UTCL0_STALL_MISSFIFO_FULL = 0x0000018d, // Total DCACHE utcl0 stalls due to full miss fifo {C1} + SQC_PERF_SEL_DCACHE_UTCL0_STALL_MULTI_MISS = 0x0000018e, // Total DCACHE utcl0 stalls due to arbitrated multiple misses + SQC_PERF_SEL_DCACHE_UTCL0_HIT_FIFO_FULL = 0x0000018f, // Total DCACHE utcl0 hit fifo full cycles + SQC_PERF_SEL_ICACHE_UTCL0_INFLIGHT_LEVEL = 0x00000190, // Level Counter: # total transactions that are outstanding in UTC01 of instruction cache {nondeterministic} + SQC_PERF_SEL_ICACHE_UTCL0_ALL_REQ = 0x00000191, // Total number of requests (all types) going to UTCL0 of instruction cache {C1} + SQC_PERF_SEL_ICACHE_UTCL1_INFLIGHT_LEVEL = 0x00000192, // Level Counter: # total transactions that are outstanding in UTCL1 and originating from instruction cache {nondeterministic} + SQC_PERF_SEL_ICACHE_UTCL1_ALL_REQ = 0x00000193, // Total number of requests (all types) going to UTCL1 and originating from instruction cache {C1} + SQC_PERF_SEL_ICACHE_UTCL0_UTCL1_PERM_FAULT = 0x00000194, // Number of faults in response from UTCL1/UTCL2 caused by permission only (that is, PTE has a permision miss) and originating from instruction cache + SQC_PERF_SEL_DCACHE_UTCL0_INFLIGHT_LEVEL = 0x00000195, // Level Counter: # total transactions that are outstanding in UTCL0 of data cache {nondeterministic} + SQC_PERF_SEL_DCACHE_UTCL0_ALL_REQ = 0x00000196, // Total number of requests (all types) going to UTCL0 of data cache {C1} + SQC_PERF_SEL_DCACHE_UTCL1_INFLIGHT_LEVEL = 0x00000197, // Level Counter: # total transactions that are outstanding in UTCL1 and originating from data cache {nondeterministic} + SQC_PERF_SEL_DCACHE_UTCL1_ALL_REQ = 0x00000198, // Total number of requests (all types) going to UTCL1 and originating from data cache {C1} + SQC_PERF_SEL_DCACHE_UTCL0_UTCL1_PERM_FAULT = 0x00000199, // Number of faults in response from UTCL1/UTCL2 caused by permission only (that is, PTE has a permision miss) and originating from data cache + SQC_PERF_SEL_ICACHE_GCR = 0x0000019a, // Total number of GCR requests for Icache + SQC_PERF_SEL_ICACHE_GCR_HITS = 0x0000019b, // Total number of GCR requests which hit for Icache {per-Bank} + SQC_PERF_SEL_DCACHE_GCR = 0x0000019c, // Total number of GCR requests for Dcache + SQC_PERF_SEL_DCACHE_GCR_HITS = 0x0000019d, // Total number of GCR requests which hit for Dcache {per-Bank} + SQC_PERF_SEL_ICACHE_GCR_INVALIDATE = 0x0000019e, // Number of GCR requests which caused an icache invalidate + SQC_PERF_SEL_DCACHE_GCR_INVALIDATE = 0x0000019f, // Number of GCR requests which caused an dcache invalidate + SQC_PERF_SEL_Reserved_0x1a0 = 0x000001a0, // Reserved. + SQC_PERF_SEL_DCACHE_SPI_RETURN_STALL = 0x000001a1, // Dcache was stalled from writing back data to SQ because of SPI also writing to SQ in that same cycle. + SQC_PERF_SEL_DUMMY_LAST = 0x000001a2, // Just a placeholding enum to indicate the last SQC performance counter. Not a real performance counter. + SP_PERF_SEL_DCACHE_WB_CNT = 0x000001c0, // destination cache write back connter + SP_PERF_SEL_DCACHE_STALL = 0x000001c1, // destination cache stall + SP_PERF_SEL_DCACHE_HIT = 0x000001c2, // destination cache hit + SP_PERF_SEL_DCACHE_HIT_DIRTY = 0x000001c3, // destination cache hit the dirty line + SP_PERF_SEL_DCACHE_WB_CONF_W_LDS = 0x000001c4, // destination cache write back conflict with LDS data write + SP_PERF_SEL_DCACHE_WB_CONF_W_TD = 0x000001c5, // destination cache write back conflict with TD data write + SP_PERF_SEL_DCACHE_WB_CONF_W_SPI = 0x000001c6, // destination cache write back conflict with SPI data write + SP_PERF_SEL_DCACHE_WB_CONF_W_EXP_VMEM = 0x000001c7, // destination cache write back conflict with EXP/VMEM read + SP_PERF_SEL_DCACHE_EVEN_DIRTY_CNT = 0x000001c8, // destination cache even bank dirty count + SP_PERF_SEL_DCACHE_ODD_DIRTY_CNT = 0x000001c9, // destination cache odd bank dirty count + SP_PERF_SEL_DCACHE_INVALIDATE_BY_VEC = 0x000001ca, // destination cacheline is invalidated by the VECIO write + SP_PERF_SEL_GATHER_SRCA_FWD = 0x000001cb, // SRCA comes from vgpr fwd + SP_PERF_SEL_GATHER_SRCB_FWD = 0x000001cc, // SRCB comes from vgpr fwd + SP_PERF_SEL_GATHER_SRCC_FWD = 0x000001cd, // SRCC comes from vgpr fwd + SP_PERF_SEL_GATHER_SRCA_REDUNDANT = 0x000001ce, // SRCA's vgpr read request killed by the redundant request + SP_PERF_SEL_GATHER_SRCB_REDUNDANT = 0x000001cf, // SRCB's vgpr read request killed by the redundant request + SP_PERF_SEL_GATHER_SRCC_REDUNDANT = 0x000001d0, // SRCC's vgpr read request killed by the redundant request + SP_PERF_SEL_GATHER_SRCA_DIRECT = 0x000001d1, // SRCA's data will skip the writing into gather + SP_PERF_SEL_GATHER_SRCB_DIRECT = 0x000001d2, // SRCB's data will skip the writing into gather + SP_PERF_SEL_GATHER_SRCC_DIRECT = 0x000001d3, // SRCC's data will skip the writing into gather + SP_PERF_SEL_VGPR_VALU_BANK0_RD = 0x000001d4, // VALU VGPR read count from bank0 + SP_PERF_SEL_VGPR_VALU_BANK1_RD = 0x000001d5, // VALU VGPR read count from bank1 + SP_PERF_SEL_VGPR_VALU_BANK2_RD = 0x000001d6, // VALU VGPR read count from bank2 + SP_PERF_SEL_VGPR_VALU_BANK3_RD = 0x000001d7, // VALU VGPR read count from bank3 + SP_PERF_SEL_VGPR_VMEM_BANK_RD = 0x000001d8, // VMEM VGPR read count + SP_PERF_SEL_VGPR_EXP_BANK_RD = 0x000001d9, // EXP VGPR read count + SP_PERF_SEL_VGPR_TDDATA_WR = 0x000001da, // TDdata VGPR write count + SP_PERF_SEL_VGPR_LDSDATA_WR = 0x000001db, // LDSdata VGPR write count + SP_PERF_SEL_PB_STALL = 0x000001dc, // Pending buffer stall, SP send back pressure to SQ + SP_PERF_SEL_PB_SEND = 0x000001dd, // SP receive one VALU cmd from SQ + SP_PERF_SEL_LDS_DIRECT_FIFO_FULL = 0x000001de, // LDS_DIRECT fifo full + SP_PERF_SEL_LDS_DIRECT_FIFO_SEND = 0x000001df, // SP receive one direct read data transaction from LDS + SP_PERF_SEL_SQ_SP_CONST_FIFO_FULL = 0x000001e0, // SQ_SP_CONST fifo full + SP_PERF_SEL_SQ_SP_CONST_FIFO_SEND = 0x000001e1, // SP receice one SGPR data transaction from SQ + SP_PERF_SEL_SGPR_FULL = 0x000001e2, // SGPR data storage inside SP is full + SP_PERF_SEL_VALU_CONFLICT_WITH_EXP = 0x000001e3, // VALU read conf with EXP read + SP_PERF_SEL_VALU_CONFLICT_WITH_VMEM_LDS = 0x000001e4, // VALU read conf with LDS read + SP_PERF_SEL_VALU_CONFLICT_WITH_VMEM_NON_LDS = 0x000001e5, // VALU read conf with non_lds read + SP_PERF_SEL_VALU_STALL_DUE_CONST_NOT_READY = 0x000001e6, // VALU stall due to const data from SQ is not ready + SP_PERF_SEL_VALU_STALL_DUE_VDST_FWD = 0x000001e7, // VALU stall due to VGPR fwd + SP_PERF_SEL_VALU_STALL_DUE_SDST_FWD = 0x000001e8, // VALU stall due to SGPR fwd + SP_PERF_SEL_VALU_STALL_DUE_LDS_DIR_NOT_READY = 0x000001e9, // VALU stall due to LDS direct data is not ready + SP_PERF_SEL_VALU_STALL_DUE_VGPR_NOT_READY = 0x000001ea, // VALU stall due to VGPR gather not ready + SP_PERF_SEL_VALU_STALL_DUE_DST_STALL = 0x000001eb, // VALU stall due to destination cache is stalled + SP_PERF_SEL_VALU_STALL_DUE_DST_CACHE_WRITE_CONF = 0x000001ec, // VALU stall due to destination cache write port conf + SP_PERF_SEL_VALU_STALL = 0x000001ed, // VALU stall happen + SP_PERF_SEL_PERF_MEM_RD_CNT = 0x000001ee, // VGPR read cnt + SP_PERF_SEL_PERF_MEM_WR_CNT = 0x000001ef, // VGPR write cnt + SP_PERF_SEL_PERF_THREAD_REDUNDANT = 0x000001f0, // Threads inside one macc4 have the same inputs + SP_PERF_SEL_PERF_OP_W_1_PASS = 0x000001f1, // SP is executing 1 pass instruction + SP_PERF_SEL_PERF_OP_W_2_PASS = 0x000001f2, // SP is executing 2 pass instruction + SP_PERF_SEL_PERF_OP_W_4_PASS = 0x000001f3, // SP is executing 4 pass instruction + SP_PERF_SEL_PERF_OP_W_16_PASS = 0x000001f4, // SP is executing 16 pass instruction + SP_PERF_SEL_PERF_COEXEC = 0x000001f5, // Trans coexec happened + SP_PERF_SEL_PERF_ACTIVE_THREAD = 0x000001f6, // Number of active threads out of 32 + SP_PERF_SEL_PERF_ALL_ACTIVE = 0x000001f7, // All the threads are active + SP_PERF_SEL_PERF_ZERO_P_ZERO = 0x000001f8, // Zero input for multiplier(FP instructions) + SP_PERF_SEL_PERF_TRANS_OP = 0x000001f9, // SP is executing trans instruction(trans_f16/32/64) + SP_PERF_SEL_PERF_OP_W_MAD = 0x000001fa, // SP is executing MAD instruction(MAD/FMA/INTERP/MADMIX_F16/32) + SP_PERF_SEL_PERF_OP_W_MUL = 0x000001fb, // SP is executing MUL instruction(MUL_F16/32) + SP_PERF_SEL_PERF_OP_W_ADD = 0x000001fc, // SP is executing ADD instruction(ADD_F16/32) + SP_PERF_SEL_DUMMY_LAST = 0x000001ff, // Just a placeholding enum to indicate the end of SP's performance counter space. This enum cannot be used. +} SQ_PERFCOUNTER_SELECT; + +typedef enum SU_PERFCOUNTER_SELECT : unsigned int { + PERF_PAPC_PASX_REQ = 0x00000000, // PAPC_PERF_SEL_PASX_REQ Number of PA->SX requests; increment rate-one per clock (each req leads to 4 cycles of data from SX); range-1/clk, it does not indicate bad performance; it cannot be used to locate bottlenecks; all instances report the same result; can be combined with PASX_FIRST_VECTOR,PASX_SECOND_VECTOR, PASX_VTX_KILL_DISCARD, PASX_VTX_NAN_DISCARD, PASX_FIRST_DEAD, PASX_FIRST_DEAD + PERF_PAPC_PASX_DISABLE_PIPE = 0x00000001, // PAPC_PERF_SEL_PASX_DISABLE_PIPE Number of transfers lost due to disabled pipe; increment rate-one per clock ; range-1/clk ; does not indicate bad performance; cannot be used for bottleneck location; all instances report the same result; no combinations + PERF_PAPC_PASX_FIRST_VECTOR = 0x00000002, // PAPC_PERF_SEL_PASX_FIRST_VECTOR Number of First Vectors from SX to PA; increment rate-one per clock ; range-1/clk ; it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_SECOND_VECTOR = 0x00000003, // PAPC_PERF_SEL_PASX_SECOND_VECTOR Number of Second Vectors from SX to PA; increment rate-one per clock ; range-1/clk ; it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_FIRST_DEAD = 0x00000004, // PAPC_PERF_SEL_PASX_FIRST_DEAD Number of Unused First Vectors (due to granularity of 4); increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_SECOND_DEAD = 0x00000005, // PAPC_PERF_SEL_PASX_SECOND_DEAD Number of Unused Second Vectors (due to granularity of 4); increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_VTX_KILL_DISCARD = 0x00000006, // PAPC_PERF_SEL_PASX_VTX_KILL_DISCARD Number of vertices which have VTX KILL Enabled and Set; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_VTX_NAN_DISCARD = 0x00000007, // PAPC_PERF_SEL_PASX_VTX_NAN_DISCARD Number of vertices which have NaN and corresponding NaN discard; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PA_INPUT_PRIM = 0x00000008, // PAPC_PERF_SEL_PA_INPUT_PRIM Number of Primitives input to PA; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PA_INPUT_NULL_PRIM = 0x00000009, // PAPC_PERF_SEL_PA_INPUT_NULL_PRIM Number of Null Primitives input to PA; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _PA_INPUT_PRIM + PERF_PAPC_PA_INPUT_EVENT_FLAG = 0x0000000a, // PAPC_PERF_SEL_PA_INPUT_EVENT_FLAG Number of Events input to PA; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PA_INPUT_FIRST_PRIM_SLOT = 0x0000000b, // PAPC_PERF_SEL_PA_INPUT_FIRST_PRIM_SLOT Number of First-Prim-Of-Slots input to PA; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PA_INPUT_END_OF_PACKET = 0x0000000c, // PAPC_PERF_SEL_PA_INPUT_END_OF_PACKET Number of End-Of-Packets input to PA; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PA_INPUT_EXTENDED_EVENT = 0x0000000d, // PAPC_PERF_SEL_PA_INPUT_EXTENDED_EVENT Number of Extended Events input to PA; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; combined with _PA_INPUT_EVENT_FLAG + PERF_PAPC_CLPR_CULL_PRIM = 0x0000000e, // PAPC_PERF_SEL_CLPR_CULL_PRIM Number of Prims Culled by Clipper for VV, UCP, VTX_KILL, VTX_NAN; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; combined with _CLPR_VVUCP_CULL_PRIM , _CLPR_VV_CULL_PRIM, _VV_CULL_PRIM ,_UCP_CULL_PRIM, _VTX_KILL_CULL_PRIM, _VTX_NAN_CULL_PRIM + PERF_PAPC_CLPR_VVUCP_CULL_PRIM = 0x0000000f, // PAPC_PERF_SEL_CLPR_VVUCP_CULL_PRIM Number of Prims Culled by Clipper for VV and UCP; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_VV_CULL_PRIM = 0x00000010, // PAPC_PERF_SEL_CLPR_VV_CULL_PRIM Number of Prims Culled by Clipper for VV; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_UCP_CULL_PRIM = 0x00000011, // PAPC_PERF_SEL_CLPR_UCP_CULL_PRIM Number of Prims Culled by Clipper for UCP; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_VTX_KILL_CULL_PRIM = 0x00000012, // PAPC_PERF_SEL_CLPR_VTX_KILL_CULL_PRIM Number of Prims Culled by Clipper for VTX_KILL; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_VTX_NAN_CULL_PRIM = 0x00000013, // PAPC_PERF_SEL_CLPR_VTX_NAN_CULL_PRIM Number of Prims Culled by Clipper for VTX_NAN; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_CULL_TO_NULL_PRIM = 0x00000014, // PAPC_PERF_SEL_CLPR_CULL_TO_NULL_PRIM Number of Clipper Culled Prims Retained for Pipe Info; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_VVUCP_CLIP_PRIM = 0x00000015, // PAPC_PERF_SEL_CLPR_VVUCP_CLIP_PRIM Number of Prims Clipped by Clipper for VV and/or UCP; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_VV_CLIP_PRIM = 0x00000016, // PAPC_PERF_SEL_CLPR_VV_CLIP_PRIM Number of Prims Clipped by Clipper for VV; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_UCP_CLIP_PRIM = 0x00000017, // PAPC_PERF_SEL_CLPR_UCP_CLIP_PRIM Number of Prims Clipped by Clipper for UCP; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_POINT_CLIP_CANDIDATE = 0x00000018, // PAPC_PERF_SEL_CLPR_POINT_CLIP_CANDIDATE Number of Points which require detailed clip checked ; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_CLIP_PLANE_CNT_1 = 0x00000019, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_CNT_1 Number of Prims with 1 Clip Plane Intersection (includes VV and UCP); increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_CNT_2 = 0x0000001a, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_CNT_2 Number of Prims with 2 Clip Plane Intersections (includes VV and UCP); increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_CNT_3 = 0x0000001b, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_CNT_3 Number of Prims with 3 Clip Plane Intersections (includes VV and UCP); increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_CNT_4 = 0x0000001c, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_CNT_4 Number of Prims with 4 Clip Plane Intersections (includes VV and UCP); increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_CNT_5_8 = 0x0000001d, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_CNT_5_8 Number of Prims with 5-8 Clip Plane Intersections (includes VV and UCP); increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_CNT_9_12 = 0x0000001e, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_CNT_9_12 Number of Prims with 9-12 Clip Plane Intersections (includes VV and UCP); increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_NEAR = 0x0000001f, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_NEAR Number of Prims which intersect the NEAR VV Plane; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_FAR = 0x00000020, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_FAR Number of Prims which intersect the FAR VV Plane; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_LEFT = 0x00000021, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_LEFT Number of Prims which intersect the LEFT VV Plane; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_RIGHT = 0x00000022, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_RIGHT Number of Prims which intersect the RIGHT VV Plane; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_TOP = 0x00000023, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_TOP Number of Prims which intersect the TOP VV Plane ; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_CLIP_PLANE_BOTTOM = 0x00000024, // PAPC_PERF_SEL_CLPR_CLIP_PLANE_BOTTOM Number of Prims which intersect the BOTTOM VV Plane ; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with _CLPR_POINT_CLIP_CANDIDATE + PERF_PAPC_CLPR_GSC_KILL_CULL_PRIM = 0x00000025, // PAPC_PERF_SEL_CLPR_GSC_KILL_CULL_PRIM Number of Prims Culled by Clipper for Geometry Shader Scenario C Cuts; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPR_RASTER_KILL_CULL_PRIM = 0x00000026, // PAPC_PERF_SEL_CLPR_RASTER_KILL_CULL_PRIM Number of Prims Culled by Clipper for DX10 Rasterization Kill (null PS); increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLSM_NULL_PRIM = 0x00000027, // PAPC_PERF_SEL_CLSM_NULL_PRIM Number of null primitives at Clip State Machine pipe stage; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combination + PERF_PAPC_CLSM_TOTALLY_VISIBLE_PRIM = 0x00000028, // PAPC_PERF_SEL_CLSM_TOTALLY_VISIBLE_PRIM Number of totally visible (no-clipping) prims; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; can be combined with PERF_PAPC_CLPR_GSC_KILL_CULL_PRIM,PERF_PAPC_CLPR_RASTER_KILL_CULL_PRIM + PERF_PAPC_CLSM_CULL_TO_NULL_PRIM = 0x00000029, // PAPC_PERF_SEL_CLSM_CULL_TO_NULL_PRIM Number of primitives which are culled during clip process; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLSM_OUT_PRIM_CNT_1 = 0x0000002a, // PAPC_PERF_SEL_CLSM_OUT_PRIM_CNT_1 Number of primitives which were clipped and result in 1 primitive; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLSM_OUT_PRIM_CNT_2 = 0x0000002b, // PAPC_PERF_SEL_CLSM_OUT_PRIM_CNT_2 Number of primitives which were clipped and result in 2 primitives; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLSM_OUT_PRIM_CNT_3 = 0x0000002c, // PAPC_PERF_SEL_CLSM_OUT_PRIM_CNT_3 Number of primitives which were clipped and result in 3 primitives; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLSM_OUT_PRIM_CNT_4 = 0x0000002d, // PAPC_PERF_SEL_CLSM_OUT_PRIM_CNT_4 Number of primitives which were clipped and result in 4 primitives; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLSM_OUT_PRIM_CNT_5_8 = 0x0000002e, // PAPC_PERF_SEL_CLSM_OUT_PRIM_CNT_5_8 Number of primitives which were clipped and result in 5-8 primitives; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLSM_OUT_PRIM_CNT_9_13 = 0x0000002f, // PAPC_PERF_SEL_CLSM_OUT_PRIM_CNT_9_13 Number of primitives which were clipped and result in 9-13 primitives; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLIPGA_VTE_KILL_PRIM = 0x00000030, // PAPC_PERF_SEL_CLIPGA_VTE_KILL_PRIM Number of primitives which are culled by VTE nan/inf logic; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_INPUT_PRIM = 0x00000031, // PAPC_PERF_SEL_SU_INPUT_PRIM Number of primitives input to the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_INPUT_CLIP_PRIM = 0x00000032, // PAPC_PERF_SEL_SU_INPUT_CLIP_PRIM Number of clipped primitives input to the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_INPUT_NULL_PRIM = 0x00000033, // PAPC_PERF_SEL_SU_INPUT_NULL_PRIM Number of null primitives input to the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_INPUT_PRIM_DUAL = 0x00000034, // PAPC_PERF_SEL_SU_INPUT_PRIM_DUAL Number of dual gradient primitives input to the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_INPUT_CLIP_PRIM_DUAL = 0x00000035, // PAPC_PERF_SEL_SU_INPUT_CLIP_PRIM_DUAL Number of dual gradient clipped primitives input to the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_ZERO_AREA_CULL_PRIM = 0x00000036, // PAPC_PERF_SEL_SU_ZERO_AREA_CULL_PRIM Number of primitives culled due to zero area; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_BACK_FACE_CULL_PRIM = 0x00000037, // PAPC_PERF_SEL_SU_BACK_FACE_CULL_PRIM Number of back-face primitives culled due to facedness; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_FRONT_FACE_CULL_PRIM = 0x00000038, // PAPC_PERF_SEL_SU_FRONT_FACE_CULL_PRIM Number of front-face primitives culled due to facedness; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_POLYMODE_FACE_CULL = 0x00000039, // PAPC_PERF_SEL_SU_POLYMODE_FACE_CULL Number of polymode cull-determination primitives culled; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_POLYMODE_BACK_CULL = 0x0000003a, // PAPC_PERF_SEL_SU_POLYMODE_BACK_CULL Number of polymode primitives discarded due to Back-Face Cull; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_POLYMODE_FRONT_CULL = 0x0000003b, // PAPC_PERF_SEL_SU_POLYMODE_FRONT_CULL Number of polymode primitives discarded due to Front-Face Cull; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_POLYMODE_INVALID_FILL = 0x0000003c, // PAPC_PERF_SEL_SU_POLYMODE_INVALID_FILL Number of polymode lines and/or points which are culled because they are an internal edge or point; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_PRIM = 0x0000003d, // PAPC_PERF_SEL_SU_OUTPUT_PRIM Number of primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_CLIP_PRIM = 0x0000003e, // PAPC_PERF_SEL_SU_OUTPUT_CLIP_PRIM Number of clipped primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_NULL_PRIM = 0x0000003f, // PAPC_PERF_SEL_SU_OUTPUT_NULL_PRIM Number of null primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_EVENT_FLAG = 0x00000040, // PAPC_PERF_SEL_SU_OUTPUT_EVENT_FLAG Number of events output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_FIRST_PRIM_SLOT = 0x00000041, // PAPC_PERF_SEL_SU_OUTPUT_FIRST_PRIM_SLOT Number of First-Prim-Of-Slots output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_END_OF_PACKET = 0x00000042, // PAPC_PERF_SEL_SU_OUTPUT_END_OF_PACKET Number of End-Of-Packets output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_POLYMODE_FACE = 0x00000043, // PAPC_PERF_SEL_SU_OUTPUT_POLYMODE_FACE Number of polymode facing primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_POLYMODE_BACK = 0x00000044, // PAPC_PERF_SEL_SU_OUTPUT_POLYMODE_BACK Number of polymode back-face primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_POLYMODE_FRONT = 0x00000045, // PAPC_PERF_SEL_SU_OUTPUT_POLYMODE_FRONT Number of polymode front-face primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUT_CLIP_POLYMODE_FACE = 0x00000046, // PAPC_PERF_SEL_SU_OUT_CLIP_POLYMODE_FACE Number of clipped polymode facing primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUT_CLIP_POLYMODE_BACK = 0x00000047, // PAPC_PERF_SEL_SU_OUT_CLIP_POLYMODE_BACK Number of clipped polymode back-face primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUT_CLIP_POLYMODE_FRONT = 0x00000048, // PAPC_PERF_SEL_SU_OUT_CLIP_POLYMODE_FRONT Number of clipped polymode front-face primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_PRIM_DUAL = 0x00000049, // PAPC_PERF_SEL_SU_OUTPUT_PRIM_DUAL Number of dual gradient primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_CLIP_PRIM_DUAL = 0x0000004a, // PAPC_PERF_SEL_SU_OUTPUT_CLIP_PRIM_DUAL Number of dual gradient clipped primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_POLYMODE_DUAL = 0x0000004b, // PAPC_PERF_SEL_SU_OUTPUT_POLYMODE_DUAL Number of dual gradient polymode primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_OUTPUT_CLIP_POLYMODE_DUAL = 0x0000004c, // PAPC_PERF_SEL_SU_OUTPUT_CLIP_POLYMODE_DUAL Number of dual gradient clip polymode primitives output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_REQ_IDLE = 0x0000004d, // PAPC_PERF_SEL_PASX_REQ_IDLE Number of clocks PASX Requestor is Idle; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with a perf counter which indicates the number of clocks required to complete the test + PERF_PAPC_PASX_REQ_BUSY = 0x0000004e, // PAPC_PERF_SEL_PASX_REQ_BUSY Number of clocks PASX Requestor is Busy; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_REQ_STALLED = 0x0000004f, // PAPC_PERF_SEL_PASX_REQ_STALLED Number of clocks PASX Requestor is Stalled; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with a perf counter which indicates the number of clocks required to complete the test + PERF_PAPC_PASX_REC_IDLE = 0x00000050, // PAPC_PERF_SEL_PASX_REC_IDLE Number of clocks PASX Receiver is Idle; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with a perf counter which indicates the number of clocks required to complete the test + PERF_PAPC_PASX_REC_BUSY = 0x00000051, // PAPC_PERF_SEL_PASX_REC_BUSY Number of clocks PASX Receiver is Busy; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_REC_STARVED_SX = 0x00000052, // PAPC_PERF_SEL_PASX_REC_STARVED_SX Number of clocks PASX Receiver is Stalled by SX; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with a perf counter which indicates the number of clocks required to complete the test + PERF_PAPC_PASX_REC_STALLED = 0x00000053, // PAPC_PERF_SEL_PASX_REC_STALLED Number of clocks PASX Reciever is Stalled by Position Memory or Clip Code Generator; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with- + PERF_PAPC_PASX_REC_STALLED_POS_MEM = 0x00000054, // PAPC_PERF_SEL_PASX_REC_STALLED_POS_MEM Number of clocks PASX Reciever is Stalled by Position Memory; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with- + PERF_PAPC_PASX_REC_STALLED_CCGSM_IN = 0x00000055, // PAPC_PERF_SEL_PASX_REC_STALLED_CCGSM_IN Number of clocks PASX Reciever is Stalled by Clip Code Generator ; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with- the other CLIP counters + PERF_PAPC_CCGSM_IDLE = 0x00000056, // PAPC_PERF_SEL_CCGSM_IDLE Number of clocks Clip Code Gen is Idle; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with- + PERF_PAPC_CCGSM_BUSY = 0x00000057, // PAPC_PERF_SEL_CCGSM_BUSY Number of clocks Clip Code Gen is Busy; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CCGSM_STALLED = 0x00000058, // PAPC_PERF_SEL_CCGSM_STALLED Number of clocks Clip Code Gen is Stalled; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with- + PERF_PAPC_CLPRIM_IDLE = 0x00000059, // PAPC_PERF_SEL_CLPRIM_IDLE Number of clocks Clip Primitive Machine is Idle; increment rate-one per clock ; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with- + PERF_PAPC_CLPRIM_BUSY = 0x0000005a, // PAPC_PERF_SEL_CLPRIM_BUSY Number of clocks Clip Primitive Machine is Busy; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLPRIM_STALLED = 0x0000005b, // PAPC_PERF_SEL_CLPRIM_STALLED Number of clocks Clip Primitive Machine is stalled by Clip State Machines; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with- + PERF_PAPC_CLPRIM_STARVED_CCGSM = 0x0000005c, // PAPC_PERF_SEL_CLPRIM_STARVED_CCGSM Number of clocks Clip Primitive Machine is starved by Clip Code Generator; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with- + PERF_PAPC_CLIPSM_IDLE = 0x0000005d, // PAPC_PERF_SEL_CLIPSM_IDLE Number of clocks Clip State Machines are Idle; range-1/clk;it can indicate bad performance (depending on the test); can be used for bottleneck detection;all instances report the same result; can be combined with- + PERF_PAPC_CLIPSM_BUSY = 0x0000005e, // PAPC_PERF_SEL_CLIPSM_BUSY Number of clocks Clip State Machines are Busy; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLIPSM_WAIT_CLIP_VERT_ENGH = 0x0000005f, // PAPC_PERF_SEL_CLIPSM_WAIT_CLIP_VERT_ENGH Number of clocks Clip State Mahcines are waiting for Clip Vert storage resources; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLIPSM_WAIT_HIGH_PRI_SEQ = 0x00000060, // PAPC_PERF_SEL_CLIPSM_WAIT_HIGH_PRI_SEQ Number of clocks Clip State Machines are waiting for High Priority Sequencer; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLIPSM_WAIT_CLIPGA = 0x00000061, // PAPC_PERF_SEL_CLIPSM_WAIT_CLIPGA Number of clocks Clip State Machines are waiting for ClipGA; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLIPSM_WAIT_AVAIL_VTE_CLIP = 0x00000062, // PAPC_PERF_SEL_CLIPSM_WAIT_AVAIL_VTE_CLIP Number of clocks Clip State Machines are waiting for VTE cycles; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLIPSM_WAIT_CLIP_OUTSM = 0x00000063, // PAPC_PERF_SEL_CLIPSM_WAIT_CLIP_OUTSM Number of clocks Clip State Machines are waiting for Clip Output State Machine; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLIPGA_IDLE = 0x00000064, // PAPC_PERF_SEL_CLIPGA_IDLE Number of clocks Clip Ga is Idle; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLIPGA_BUSY = 0x00000065, // PAPC_PERF_SEL_CLIPGA_BUSY Number of clocks Clip Ga is Busy; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_CLIPGA_STARVED_VTE_CLIP = 0x00000066, // PAPC_PERF_SEL_CLIPGA_STARVED_VTE_CLIP Number of clocks Clip Ga is Starved by VTE or Clipper; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result + PERF_PAPC_CLIPGA_STALLED = 0x00000067, // PAPC_PERF_SEL_CLIPGA_STALLED Number of clocks Clip Ga is stalled; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result + PERF_PAPC_CLIP_IDLE = 0x00000068, // PAPC_PERF_SEL_CLIP_IDLE Number of clocks Clip is Idle; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result; can be used to detect bottlenecks in combination with other signals + PERF_PAPC_CLIP_BUSY = 0x00000069, // PAPC_PERF_SEL_CLIP_BUSY Number of clocks Clip is Busy; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result; can be used to detect bottlenecks in combination with other signals + PERF_PAPC_SU_IDLE = 0x0000006a, // PAPC_PERF_SEL_SU_IDLE Number of clocks Setup is Idle; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result; can be used to detect bottlenecks in combination with other signals + PERF_PAPC_SU_BUSY = 0x0000006b, // PAPC_PERF_SEL_SU_BUSY Number of clocks Setup is Busy; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result; can be used to detect bottlenecks in combination with other signals + PERF_PAPC_SU_STARVED_CLIP = 0x0000006c, // PAPC_PERF_SEL_SU_STARVED_CLIP Number of clocks Setup is starved by Clipper; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result + PERF_PAPC_SU_STALLED_SC = 0x0000006d, // PAPC_PERF_SEL_SU_STALLED_SC Number of clocks Setup is stalled by SC; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result + PERF_PAPC_CL_DYN_SCLK_VLD = 0x0000006e, // PAPC_PERF_SEL_CL_DYN_SCLK_VLD Number of clocks the CL dynamic clock is active;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_DYN_SCLK_VLD = 0x0000006f, // PAPC_PERF_SEL_SU_DYN_SCLK_VLD Number of clocks the SU dynamic clock is active;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PA_REG_SCLK_VLD = 0x00000070, // PAPC_PERF_SEL_PA_REG_SCLK_VLD Number of clocks the PA register clock is active;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_MULTI_GPU_PRIM_FILTER_CULL = 0x00000071, // PAPC_PERF_SEL_SU_MULTI_GPU_PRIM_FILTER_CULL Number of primitives culled by multi-gpu filter;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_SE0_REQ = 0x00000072, // PAPC_PERF_SEL_PASX_SE0_REQ Number of PA to SX requests to shader engine 0;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_SE1_REQ = 0x00000073, // PAPC_PERF_SEL_PASX_SE1_REQ Number of PA to SX requests to shader engine 1;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_SE0_FIRST_VECTOR = 0x00000074, // PAPC_PERF_SEL_PASX_SE0_FIRST_VECTOR Number of Shader engine 0 first vectors (position);range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_SE0_SECOND_VECTOR = 0x00000075, // PAPC_PERF_SEL_PASX_SE0_SECOND_VECTOR Number of Shader engine 0 second vectors (position);range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_SE1_FIRST_VECTOR = 0x00000076, // PAPC_PERF_SEL_PASX_SE1_FIRST_VECTOR Number of Shader engine 1 first vectors (position);range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_PASX_SE1_SECOND_VECTOR = 0x00000077, // PAPC_PERF_SEL_PASX_SE1_SECOND_VECTOR Number of Shader engine 1 second vectors (position);range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE0_PRIM_FILTER_CULL = 0x00000078, // PAPC_PERF_SEL_SU_SE0_PRIM_FILTER_CULL Number of primitives culled by shader engine 0 filter;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE1_PRIM_FILTER_CULL = 0x00000079, // PAPC_PERF_SEL_SU_SE1_PRIM_FILTER_CULL Number of primitives culled by shader engine 1 filter;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE01_PRIM_FILTER_CULL = 0x0000007a, // PAPC_PERF_SEL_SU_SE01_PRIM_FILTER_CULL Number of primitives culled by SE0 and SE1 filter;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE0_OUTPUT_PRIM = 0x0000007b, // PAPC_PERF_SEL_SU_SE0_OUTPUT_PRIM Number of primitives output to shader engine 0;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE1_OUTPUT_PRIM = 0x0000007c, // PAPC_PERF_SEL_SU_SE1_OUTPUT_PRIM Number of primitives output to shader engine 1;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE01_OUTPUT_PRIM = 0x0000007d, // PAPC_PERF_SEL_SU_SE01_OUTPUT_PRIM Number of primitives output to SE0 and SE1;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE0_OUTPUT_NULL_PRIM = 0x0000007e, // PAPC_PERF_SEL_SU_SE0_OUTPUT_NULL_PRIM Number of null primitives output to shader engine 0;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE1_OUTPUT_NULL_PRIM = 0x0000007f, // PAPC_PERF_SEL_SU_SE1_OUTPUT_NULL_PRIM Number of null primitives output to shader engine 1;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE01_OUTPUT_NULL_PRIM = 0x00000080, // PAPC_PERF_SEL_SU_SE01_OUTPUT_NULL_PRIM Number of null primitives output to SE0 and SE1;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE0_OUTPUT_FIRST_PRIM_SLOT = 0x00000081, // PAPC_PERF_SEL_SU_SE0_OUTPUT_FIRST_PRIM_SLOT Number of shader engine 0 first primitive of slot;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE1_OUTPUT_FIRST_PRIM_SLOT = 0x00000082, // PAPC_PERF_SEL_SU_SE1_OUTPUT_FIRST_PRIM_SLOT Number of shader engine 1 first primitive of slot;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE0_STALLED_SC = 0x00000083, // PAPC_PERF_SEL_SU_SE0_STALLED_SC Number of clocks stalled by shader engine 0 scan converter; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result + PERF_PAPC_SU_SE1_STALLED_SC = 0x00000084, // PAPC_PERF_SEL_SU_SE1_STALLED_SC Number of clocks stalled by shader engine 1 scan converter; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result + PERF_PAPC_SU_SE01_STALLED_SC = 0x00000085, // PAPC_PERF_SEL_SU_SE01_STALLED_SC Number of clocks stalled by SE0 and SE1 scan converter; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result + PERF_PAPC_CLSM_CLIPPING_PRIM = 0x00000086, // PAPC_PERF_SEL_CLSM_CLIPPING_PRIM Number of clocks the PA is actively clipping primitives on any of the clipper state machines; range-1/clk; cannot be used to detect bad performance + PERF_PAPC_SU_CULLED_PRIM = 0x00000087, // PAPC_PERF_SEL_SU_CULLED_PRIM Number of prims culled in the SU due to zero area, front or back facing, small prim filter cull, polymode invalid, or polymode front or back facing; range-1/clk; cannot be used to detect bad performance + PERF_PAPC_SU_OUTPUT_EOPG = 0x00000088, // PAPC_PERF_SEL_SU_OUTPUT_EOPG Number of EOPGs output from the Setup block; increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE2_PRIM_FILTER_CULL = 0x00000089, // PAPC_PERF_SEL_SU_SE2_PRIM_FILTER_CULL Number of primitives culled by shader engine 2 filter;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE3_PRIM_FILTER_CULL = 0x0000008a, // PAPC_PERF_SEL_SU_SE3_PRIM_FILTER_CULL Number of primitives culled by shader engine 3 filter;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE2_OUTPUT_PRIM = 0x0000008b, // PAPC_PERF_SEL_SU_SE2_OUTPUT_PRIM Number of primitives output to shader engine 2;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE3_OUTPUT_PRIM = 0x0000008c, // PAPC_PERF_SEL_SU_SE3_OUTPUT_PRIM Number of primitives output to shader engine 3;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE2_OUTPUT_NULL_PRIM = 0x0000008d, // PAPC_PERF_SEL_SU_SE2_OUTPUT_NULL_PRIM Number of null primitives output to shader engine 2;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE3_OUTPUT_NULL_PRIM = 0x0000008e, // PAPC_PERF_SEL_SU_SE3_OUTPUT_NULL_PRIM Number of null primitives output to shader engine 3;range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE0_OUTPUT_END_OF_PACKET = 0x0000008f, // PAPC_PERF_SEL_SU_SE0_OUTPUT_END_OF_PACKET Number of End-Of-Packets output to shader engine 0;increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE1_OUTPUT_END_OF_PACKET = 0x00000090, // PAPC_PERF_SEL_SU_SE1_OUTPUT_END_OF_PACKET Number of End-Of-Packets output to shader engine 1;increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE2_OUTPUT_END_OF_PACKET = 0x00000091, // PAPC_PERF_SEL_SU_SE2_OUTPUT_END_OF_PACKET Number of End-Of-Packets output to shader engine 2;increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE3_OUTPUT_END_OF_PACKET = 0x00000092, // PAPC_PERF_SEL_SU_SE3_OUTPUT_END_OF_PACKET Number of End-Of-Packets output to shader engine 3;increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE0_OUTPUT_EOPG = 0x00000093, // PAPC_PERF_SEL_SU_SE0_OUTPUT_EOPG Number of EOPGs output to shader engine 0;increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE1_OUTPUT_EOPG = 0x00000094, // PAPC_PERF_SEL_SU_SE1_OUTPUT_EOPG Number of EOPGs output to shader engine 1;increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE2_OUTPUT_EOPG = 0x00000095, // PAPC_PERF_SEL_SU_SE2_OUTPUT_EOPG Number of EOPGs output to shader engine 2;increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE3_OUTPUT_EOPG = 0x00000096, // PAPC_PERF_SEL_SU_SE3_OUTPUT_EOPG Number of EOPGs output to shader engine 3;increment rate-one per clock ; range-1/clk;it does not indicate bad performance; no bottleneck detection;all instances report the same result; no combinations + PERF_PAPC_SU_SE2_STALLED_SC = 0x00000097, // PAPC_PERF_SEL_SU_SE2_STALLED_SC Number of clocks stalled by shader engine 2 scan converter; range-1/clk;it can potentially be used to detect bad performance;all instances report the same result + PERF_PAPC_SU_SE3_STALLED_SC = 0x00000098, // PAPC_PERF_SEL_SU_SE3_STALLED_SC Number of clocks stalled by shader engine 3 scan converter; range-1/clk; it can potentially be used to detect bad performance; all instances report the same result; no combinations + PERF_SU_SMALL_PRIM_FILTER_CULL_CNT = 0x00000099, // PAPC_PERF_SEL_SU_SMALL_PRIM_FILTER_CULL_CNT Number of primitives that have been culled by the Small Prim Filter; range-1/clk; it can be used to measure the reduction of unnecessary traffic to the Scan Converter; all instances report the same result; can be combined with the PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_1X1 = 0x0000009a, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_1X1 Number of pixels that have been culled by small prim filter whose bounding box fits within 1 pixel; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_2X1 = 0x0000009b, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_2X1 Number of pixels that have been culled by small prim filter whose bounding box fits within 2 horizontal by 1 vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_1X2 = 0x0000009c, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_1X2 Number of pixels that have been culled by small prim filter whose bounding box fits within 1 horizontal by 2 vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_2X2 = 0x0000009d, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_2X2 Number of pixels that have been culled by small prim filter whose bounding box fits within 2 horizontal by 2 vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_3X1 = 0x0000009e, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_3X1 Number of pixels that have been culled by small prim filter whose bounding box fits within 3 horizontal by 1 vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_1X3 = 0x0000009f, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_1X3 Number of pixels that have been culled by small prim filter whose bounding box fits within 1 horizontal by 3 vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_3X2 = 0x000000a0, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_3X2 Number of pixels that have been culled by small prim filter whose bounding box fits within 3 horizontal by 2 vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_2X3 = 0x000000a1, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_2X3 Number of pixels that have been culled by small prim filter whose bounding box fits within 2 horizontal by 3 vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_NX1 = 0x000000a2, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_NX1 Number of pixels that have been culled by small prim filter whose bounding box fits within 4 or more horizontal by 1 vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_1XN = 0x000000a3, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_1XN Number of pixels that have been culled by small prim filter whose bounding box fits within 1 horizontal by 4 or more vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_NX2 = 0x000000a4, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_NX2 Number of pixels that have been culled by small prim filter whose bounding box fits within 4 or more horizontal by 2 vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_2XN = 0x000000a5, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_2XN Number of pixels that have been culled by small prim filter whose bounding box fits within 2 horizontal by 4 or more vertical pixels; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive size; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the other PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_FULL_RES_EVENT = 0x000000a6, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_FULL_RES_EVENT Number of pixels that have been culled by small prim filter whose bounding box lies fully within the full resolution region, and/or the foveated region; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive location; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_HALF_RES_EVENT = 0x000000a7, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_HALF_RES_EVENT Number of pixels that have been culled by small prim filter whose bounding box lies fully within one of the eight regions that surround the center region; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive location; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SMALL_PRIM_CULL_PRIM_QUARTER_RES_EVENT = 0x000000a8, // PAPC_PERF_SEL_SMALL_PRIM_CULL_PRIM_QUARTER_RES_EVENT Number of pixels that have been culled by small prim filter whose bounding box lies fully within one of the remaining 16 outer regions; range-1/clk; it can be used as a subset of PERF_SU_SMALL_PRIM_FILTER_CULL_CNT to measure the number of culled prims as a function of primitive location; all instances report the same result; can be combined with the PERF_SU_SMALL_PRIM_FILTER_CULL_CNT and the PERF_SMALL_PRIM_CULL_PRIM_nXn counts + PERF_SC0_QUALIFIED_SEND_BUSY_EVENT = 0x000000a9, // PAPC_PERF_SEL_SC0_QUALIFIED_SEND_BUSY_EVENT Number of PA_SC0 transactions that have occurred between the time a PERFCOUNTER_START and PERFCOUNTER_STOP event have been sent to the SC; range-1/clk; this can be used with PERF_SC0_QUALIFIED_SEND_NOT_BUSY_EVENT to measure primitive transfer rate between PA and SC; all instances report the same result; the sum of PERF_SC0_QUALIFIED_SEND_BUSY_EVENT and PERF_SC0_QUALIFIED_SEND_NOT_BUSY_EVENT is equal to the total number of clocks between START/STOP events, after the first transaction following PERFCOUNTER_START has occurred + PERF_SC0_QUALIFIED_SEND_NOT_BUSY_EVENT = 0x000000aa, // PAPC_PERF_SEL_SC0_QUALIFIED_SEND_NOT_BUSY_EVENT Number of clocks where a PA_SC0 transactions does NOT occurred between the time a PERFCOUNTER_START and PERFCOUNTER_STOP event have been sent to the SC, starting AFTER the first prim following the PERFCOUNTER_START; range-1/clk; this can be used with PERF_SC0_QUALIFIED_SEND_BUSY_EVENT to measure primitive transfer rate between PA and SC; all instances report the same result; the sum of PERF_SC0_QUALIFIED_SEND_BUSY_EVENT and PERF_SC0_QUALIFIED_SEND_NOT_BUSY_EVENT is equal to the total number of clocks between START/STOP events, after the first transaction following PERFCOUNTER_START has occurred + PERF_SC1_QUALIFIED_SEND_BUSY_EVENT = 0x000000ab, // PAPC_PERF_SEL_SC1_QUALIFIED_SEND_BUSY_EVENT Number of PA_SC1 transactions that have occurred between the time a PERFCOUNTER_START and PERFCOUNTER_STOP event have been sent to the SC; range-1/clk; this can be used with PERF_SC1_QUALIFIED_SEND_NOT_BUSY_EVENT to measure primitive transfer rate between PA and SC; all instances report the same result; the sum of PERF_SC1_QUALIFIED_SEND_BUSY_EVENT and PERF_SC1_QUALIFIED_SEND_NOT_BUSY_EVENT is equal to the total number of clocks between START/STOP events, after the first transaction following PERFCOUNTER_START has occurred + PERF_SC1_QUALIFIED_SEND_NOT_BUSY_EVENT = 0x000000ac, // PAPC_PERF_SEL_SC1_QUALIFIED_SEND_NOT_BUSY_EVENT Number of clocks where a PA_SC1 transactions does NOT occurred between the time a PERFCOUNTER_START and PERFCOUNTER_STOP event have been sent to the SC, starting AFTER the first prim following the PERFCOUNTER_START; range-1/clk; this can be used with PERF_SC1_QUALIFIED_SEND_BUSY_EVENT to measure primitive transfer rate between PA and SC; all instances report the same result; the sum of PERF_SC1_QUALIFIED_SEND_BUSY_EVENT and PERF_SC1_QUALIFIED_SEND_NOT_BUSY_EVENT is equal to the total number of clocks between START/STOP events, after the first transaction following PERFCOUNTER_START has occurred + PERF_SC2_QUALIFIED_SEND_BUSY_EVENT = 0x000000ad, // PAPC_PERF_SEL_SC2_QUALIFIED_SEND_BUSY_EVENT Number of PA_SC2 transactions that have occurred between the time a PERFCOUNTER_START and PERFCOUNTER_STOP event have been sent to the SC; range-1/clk; this can be used with PERF_SC2_QUALIFIED_SEND_NOT_BUSY_EVENT to measure primitive transfer rate between PA and SC; all instances report the same result; the sum of PERF_SC2_QUALIFIED_SEND_BUSY_EVENT and PERF_SC2_QUALIFIED_SEND_NOT_BUSY_EVENT is equal to the total number of clocks between START/STOP events, after the first transaction following PERFCOUNTER_START has occurred + PERF_SC2_QUALIFIED_SEND_NOT_BUSY_EVENT = 0x000000ae, // PAPC_PERF_SEL_SC2_QUALIFIED_SEND_NOT_BUSY_EVENT Number of clocks where a PA_SC2 transactions does NOT occurred between the time a PERFCOUNTER_START and PERFCOUNTER_STOP event have been sent to the SC, starting AFTER the first prim following the PERFCOUNTER_START; range-1/clk; this can be used with PERF_SC2_QUALIFIED_SEND_BUSY_EVENT to measure primitive transfer rate between PA and SC; all instances report the same result; the sum of PERF_SC2_QUALIFIED_SEND_BUSY_EVENT and PERF_SC2_QUALIFIED_SEND_NOT_BUSY_EVENT is equal to the total number of clocks between START/STOP events, after the first transaction following PERFCOUNTER_START has occurred + PERF_SC3_QUALIFIED_SEND_BUSY_EVENT = 0x000000af, // PAPC_PERF_SEL_SC3_QUALIFIED_SEND_BUSY_EVENT Number of PA_SC3 transactions that have occurred between the time a PERFCOUNTER_START and PERFCOUNTER_STOP event have been sent to the SC; range-1/clk; this can be used with PERF_SC3_QUALIFIED_SEND_NOT_BUSY_EVENT to measure primitive transfer rate between PA and SC; all instances report the same result; the sum of PERF_SC3_QUALIFIED_SEND_BUSY_EVENT and PERF_SC3_QUALIFIED_SEND_NOT_BUSY_EVENT is equal to the total number of clocks between START/STOP events, after the first transaction following PERFCOUNTER_START has occurred + PERF_SC3_QUALIFIED_SEND_NOT_BUSY_EVENT = 0x000000b0, // PAPC_PERF_SEL_SC3_QUALIFIED_SEND_NOT_BUSY_EVENT Number of clocks where a PA_SC3 transactions does NOT occurred between the time a PERFCOUNTER_START and PERFCOUNTER_STOP event have been sent to the SC, starting AFTER the first prim following the PERFCOUNTER_START; range-1/clk; this can be used with PERF_SC3_QUALIFIED_SEND_BUSY_EVENT to measure primitive transfer rate between PA and SC; all instances report the same result; the sum of PERF_SC3_QUALIFIED_SEND_BUSY_EVENT and PERF_SC3_QUALIFIED_SEND_NOT_BUSY_EVENT is equal to the total number of clocks between START/STOP events, after the first transaction following PERFCOUNTER_START has occurred + PERF_PA_VERTEX_FIFO_FULL = 0x000000b1, // PAPC_PERF_SEL_PA_VERTEX_FIFO_FULL Number of clocks when the vertex fifo in the legacy PA is full; range-1/clk; it can be used to help in NGG performance analysis by indicating backpressure from the vertex path of the legacy PA. all instances report the same result; can be combined with PERF_PA_PRIMIC_TO_CLPRIM_FIFO_FULL count + PERF_PA_PRIMIC_TO_CLPRIM_FIFO_FULL = 0x000000b2, // PAPC_PERF_SEL_PA_PRIMIC_TO_CLPRIM_FIFO_FULL Number of clocks when the primic_to_clprimx fifo in the legacy PA is full; range-1/clk; it can be used to help in NGG performance analysis by indicating backpressure from the position path of the legacy PA. all instances report the same result; can be combined with PERF_PA_VERTEX_FIFO_FULL count + PERF_PA_FETCH_TO_PRIMIC_P_FIFO_FULL = 0x000000b3, // PAPC_PERF_SEL_PA_FETCH_TO_PRIMIC_P_FIFO_FULL Number of clocks when the NGG prim output fifo is full; range-1/clk; it can be used in perfornamce analysis and to help in finding the source of hangs. all instances report the same result + PERF_PA_FETCH_TO_SXIF_FIFO_FULL = 0x000000b4, // PAPC_PERF_SEL_PA_FETCH_TO_SXIF_FIFO_FULL Number of clocks when the NGG position output fifo is full; range-1/clk; it can be used in perfornamce analysis and to help in finding the source of hangs. all instances report the same result + PERF_PA_PIPE0_SWITCHED_GEN = 0x000000b5, // PAPC_PERF_SEL_PA_PIPE0_SWITCHED_GEN Number of times the PA has processed a pipe0 primitive that belongs to a different GEN than did the previously processed primitive; range-1/generation_switch; all instances report the same result + PERF_PA_PIPE1_SWITCHED_GEN = 0x000000b6, // PAPC_PERF_SEL_PA_PIPE1_SWITCHED_GEN Number of times the PA has processed a pipe1 primitive that belongs to a different GEN than did the previously processed primitive; range-1/generation_switch; all instances report the same result + PERF_ENGG_CSB_MACHINE_IS_STARVED = 0x000000b7, // PAPC_PERF_SEL_ENGG_CSB_MACHINE_IS_STARVED Number of clocks when the PA CSB machine is starved for work; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_MACHINE_STALLED_BY_CSB_MEMORY = 0x000000b8, // PAPC_PERF_SEL_ENGG_CSB_MACHINE_STALLED_BY_CSB_MEMORY Number of clocks when the PA CSB machine has a control sideband ready to be written to CSB memory, but the memory is full; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_MACHINE_STALLED_BY_SPI = 0x000000b9, // PAPC_PERF_SEL_ENGG_CSB_MACHINE_STALLED_BY_SPI Number of clocks when the PA CSB machine has a control sideband and payload from the GE but is waiting on the SPI to provide vert/prim counts; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_GE_INPUT_FIFO_FULL = 0x000000ba, // PAPC_PERF_SEL_ENGG_CSB_GE_INPUT_FIFO_FULL Number of clocks when the PA CSB GE input fifo is full, and the PA will now be appying backpressure to the GE; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_INPUT_FIFO_FULL = 0x000000bb, // PAPC_PERF_SEL_ENGG_CSB_SPI_INPUT_FIFO_FULL Number of clocks when the PA CSB SPI input fifo is full; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_PAYLOAD_INPUT_FIFO_FULL = 0x000000bc, // PAPC_PERF_SEL_ENGG_CSB_PAYLOAD_INPUT_FIFO_FULL Number of clocks when the PA payload input fifo is full; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_GE_INPUT_FIFO_POP_BIT = 0x000000bd, // PAPC_PERF_SEL_ENGG_CSB_GE_INPUT_FIFO_POP_BIT Number of times when the PA receives a subgroup that contains a pop bit to the payload fifo. Events are not counted; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_PRIM_COUNT_EQ0 = 0x000000be, // PAPC_PERF_SEL_ENGG_CSB_PRIM_COUNT_EQ0 Number of times when the PA recieves a CSB with a prim count of zero; range-1/csb; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_NULL_SUBGROUP = 0x000000bf, // PAPC_PERF_SEL_ENGG_CSB_NULL_SUBGROUP Number of times when the PA recieves a CSB that has been marked as a null subgroup. Events are not counted.; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_GE_SENDING_SUBGROUP = 0x000000c0, // PAPC_PERF_SEL_ENGG_CSB_GE_SENDING_SUBGROUP Number of times when the PA recieves a CSB from the GE that represents a subgroup; range-1/csb; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_GE_MEMORY_FULL = 0x000000c1, // PAPC_PERF_SEL_ENGG_CSB_GE_MEMORY_FULL Number of clocks when the GE CSB memory is full.; range-1/csb; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_GE_MEMORY_EMPTY = 0x000000c2, // PAPC_PERF_SEL_ENGG_CSB_GE_MEMORY_EMPTY Number of clocks when the GE CSB memory is empty.; range-1/csb; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_MEMORY_FULL = 0x000000c3, // PAPC_PERF_SEL_ENGG_CSB_SPI_MEMORY_FULL Number of clocks when the SPI CSB memory is full.; range-1/csb; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_MEMORY_EMPTY = 0x000000c4, // PAPC_PERF_SEL_ENGG_CSB_SPI_MEMORY_EMPTY Number of clocks when the SPI CSB memory is empty.; range-1/csb; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN00 = 0x000000c5, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN00 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of R/2 clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN01 = 0x000000c6, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN01 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN02 = 0x000000c7, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN02 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 2*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN03 = 0x000000c8, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN03 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 3*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN04 = 0x000000c9, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN04 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 4*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN05 = 0x000000ca, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN05 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 5*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN06 = 0x000000cb, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN06 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 6*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN07 = 0x000000cc, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN07 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 7*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN08 = 0x000000cd, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN08 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 8*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN09 = 0x000000ce, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN09 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 9*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN10 = 0x000000cf, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN10 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 10*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN11 = 0x000000d0, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN11 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 11*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN12 = 0x000000d1, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN12 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 12*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN13 = 0x000000d2, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN13 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 13*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN14 = 0x000000d3, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN14 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 14*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_DELAY_BIN15 = 0x000000d4, // PAPC_PERF_SEL_ENGG_CSB_DELAY_BIN15 Number of clocks on average between GE_PA_csb_send signals. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 15*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN00 = 0x000000d5, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN00 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of R/2 clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN01 = 0x000000d6, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN01 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN02 = 0x000000d7, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN02 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 2*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN03 = 0x000000d8, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN03 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 3*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN04 = 0x000000d9, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN04 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 4*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN05 = 0x000000da, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN05 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 5*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN06 = 0x000000db, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN06 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 6*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN07 = 0x000000dc, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN07 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 7*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN08 = 0x000000dd, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN08 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 8*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN09 = 0x000000de, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN09 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 9*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_CSB_SPI_DELAY_BIN10 = 0x000000df, // PAPC_PERF_SEL_ENGG_CSB_SPI_DELAY_BIN10 Number of clocks on average between GE_PA_csb_send and write to CSB memory. Not implemented at this time. Resolution R set by PA_CL_ENHANCE.TC_LATENCY_TIME_STAMP_RESOLUTION. Each count represents an average of 10*R clocks; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_REQ_NULL_REQUEST = 0x000000e0, // PERF_ENGG_INDEX_REQ_NULL_REQUEST Number of NGG subgroups where a null request is made to the SX to free up buffer space.; range-1/prim; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_REQ_0_NEW_VERTS_THIS_PRIM = 0x000000e1, // PERF_ENGG_INDEX_REQ_0_NEW_VERTS_THIS_PRIM, Number of prims that contain zero new vertices.; range-1/prim; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_REQ_1_NEW_VERTS_THIS_PRIM = 0x000000e2, // PERF_ENGG_INDEX_REQ_1_NEW_VERTS_THIS_PRIM, Number of prims that contain one new vertices.; range-1/prim; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_REQ_2_NEW_VERTS_THIS_PRIM = 0x000000e3, // PERF_ENGG_INDEX_REQ_2_NEW_VERTS_THIS_PRIM, Number of prims that contain two new vertices.; range-1/prim; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_REQ_3_NEW_VERTS_THIS_PRIM = 0x000000e4, // PERF_ENGG_INDEX_REQ_3_NEW_VERTS_THIS_PRIM, Number of prims that contain three new vertices.; range-1/prim; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_REQ_STARVED = 0x000000e5, // PAPC_PERF_SEL_ENGG_INDEX_REQ_STARVED Number of clocks when the PA index request machine is starved for work; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_REQ_IDLE_AND_STALLED_BY_REQ2RTN_FIFO_FULL = 0x000000e6, // PAPC_PERF_SEL_ENGG_INDEX_REQ_IDLE_AND_STALLED_BY_REQ2RTN_FIFO_FULL Number of clocks when the NGG index request machine has a CSB, but is can't start requesting because the req2rtn fifo is full; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_REQ_BUSY_AND_STALLED_BY_REQ2RTN_FIFO_FULL = 0x000000e7, // PAPC_PERF_SEL_ENGG_INDEX_REQ_BUSY_AND_STALLED_BY_REQ2RTN_FIFO_FULL Number of clocks when the NGG index request machine is busy, but is stalled because the req2rtn fifo is full; range-1/csb; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_REQ_STALLED_BY_SX_CREDITS = 0x000000e8, // PAPC_PERF_SEL_ENGG_INDEX_REQ_STALLED_BY_SX_CREDITS Number of clocks when the NGG index request machine is busy, but is stalled because it has run out of credits; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_REQ2RTN_FIFO_FULL = 0x000000e9, // PAPC_PERF_SEL_ENGG_INDEX_RET_REQ2RTN_FIFO_FULL Number of clocks when the index req2rtn fifo is full; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_REQ2RTN_FIFO_EMPTY = 0x000000ea, // PAPC_PERF_SEL_ENGG_INDEX_RET_REQ2RTN_FIFO_EMPTY Number of clocks when the index req2rtn fifo is empty; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SX_RECEIVE_FIFO_FULL = 0x000000eb, // PAPC_PERF_SEL_ENGG_INDEX_RET_SX_RECEIVE_FIFO_FULL Number of clocks when the index SX return fifo is full; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_STARVED_BY_CSB = 0x000000ec, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_STARVED_BY_CSB Number of clocks when the index return logic is idle and waiting for a CSB from the index request machine; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_STARVED_BY_PRIMS = 0x000000ed, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_STARVED_BY_PRIMS Number of clocks when the index return logic has received a CSB from the index request machine but is waiting on prim data from the SX; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_STALLED_BY_PRIM_INDICES_CSB_FIFO = 0x000000ee, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_STALLED_BY_PRIM_INDICES_CSB_FIFO Number of clocks when the index return logic has been stalled by a full prim indices csb fifo; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_STALLED_BY_PRIM_INDICES_FIFO = 0x000000ef, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_STALLED_BY_PRIM_INDICES_FIFO Number of clocks when the index return logic has been stalled by a full prim indices fifo; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_EVENT = 0x000000f0, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_EVENT Number of times the index receive logic is consuming an event from the index req2rtn fifo; range-1/event; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_NULL_SUBGROUP = 0x000000f1, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_NULL_SUBGROUP Number of times the index receive logic is consuming a subgroup csb from the index req2rtn fifo; range-1/csb; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_SUBGROUP_PRIMCOUNT_EQ0 = 0x000000f2, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_SUBGROUP_PRIMCOUNT_EQ0 Number of times the index receive logic is consuming a subgroup csb from the index req2rtn fifo where the prim count is zero; range-1/csb; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_0_VALID_PRIMS_NOPL = 0x000000f3, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_0_VALID_PRIMS_NOPL Number of times the index sx return logic has received a qdword from the SX with no valid prims, and there is no accompanying payload; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_1_VALID_PRIMS_NOPL = 0x000000f4, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_1_VALID_PRIMS_NOPL Number of times the index sx return logic has received a qdword from the SX with 1 valid prim, and there is no accompanying payload; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_2_VALID_PRIMS_NOPL = 0x000000f5, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_2_VALID_PRIMS_NOPL Number of times the index sx return logic has received a qdword from the SX with 2 valid prims, and there is no palyload. Note that payload is irrelevent for performance measuring; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_3_VALID_PRIMS_NOPL = 0x000000f6, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_3_VALID_PRIMS_NOPL Number of times the index sx return logic has received a qdword from the SX with 3 valid prims, and there is no palyload. Note that payload is irrelevent for performance measuring; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_4_VALID_PRIMS_NOPL = 0x000000f7, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_4_VALID_PRIMS_NOPL Number of times the index sx return logic has received a qdword from the SX with 4 valid prims, and there is no palyload. Note that payload is irrelevent for performance measuring; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_0_VALID_PRIMS_PL = 0x000000f8, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_0_VALID_PRIMS_PL Number of times the index sx return logic has received a qdword from the SX with no valid prims, and there is an accompanying payload; range-1/qdword;can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_1_VALID_PRIMS_PL = 0x000000f9, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_1_VALID_PRIMS_PL Number of times the index sx return logic has received a qdword from the SX with 1 valid prim, and there is an accompanying payload; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_2_VALID_PRIMS_PL = 0x000000fa, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_2_VALID_PRIMS_PL Number of times the index sx return logic has received a qdword from the SX with 2 valid prims, and there is an accompanying payload. Note that payload is irrelevent for performance measuring; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_3_VALID_PRIMS_PL = 0x000000fb, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_3_VALID_PRIMS_PL Number of times the index sx return logic has received a qdword from the SX with 3 valid prims, and there is an accompanying payload. Note that payload is irrelevent for performance measuring; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_4_VALID_PRIMS_PL = 0x000000fc, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_4_VALID_PRIMS_PL Number of times the index sx return logic has received a qdword from the SX with 4 valid prims, and there is an accompanying payload. Note that payload is irrelevent for performance measuring; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_0_NULL_PRIMS = 0x000000fd, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_0_NULL_PRIMS Number of times the index sx return logic has received a qdword from the SX with 0 valid prims. ; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_1_NULL_PRIMS = 0x000000fe, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_1_NULL_PRIMS Number of times the index sx return logic has received a qdword from the SX with 1 valid prims. ; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_2_NULL_PRIMS = 0x000000ff, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_2_NULL_PRIMS Number of times the index sx return logic has received a qdword from the SX with 2 valid prims. ; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_3_NULL_PRIMS = 0x00000100, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_3_NULL_PRIMS Number of times the index sx return logic has received a qdword from the SX with 3 valid prims. ; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_RET_SXRX_READING_QDWORD_4_NULL_PRIMS = 0x00000101, // PAPC_PERF_SEL_ENGG_INDEX_RET_SXRX_READING_QDWORD_4_NULL_PRIMS Number of times the index sx return logic has received a qdword from the SX with 4 valid prims. ; range-1/qdword; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_PRIM_IF_STALLED_BY_FULL_FETCH_TO_PRIMIC_P_FIFO = 0x00000102, // PAPC_PERF_SEL_ENGG_INDEX_PRIM_IF_STALLED_BY_FULL_FETCH_TO_PRIMIC_P_FIFO Number of clocks when the index prim interface logic is being stalled by a full fetch_to_primic_p fifo; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_PRIM_IF_STALLED_BY_FULL_FETCH_TO_PRIMIC_S_FIFO = 0x00000103, // PAPC_PERF_SEL_ENGG_INDEX_PRIM_IF_STALLED_BY_FULL_FETCH_TO_PRIMIC_S_FIFO Number of clocks when the index prim interface logic is being stalled by a full fetch_to_primic_s fifo; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_PRIM_IF_STARVED_BY_NO_CSB = 0x00000104, // PAPC_PERF_SEL_ENGG_INDEX_PRIM_IF_STARVED_BY_NO_CSB Number of clocks when the index prim interface logic is being starved and is waiting for a control sideband from the index sx receive logic; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_PRIM_IF_STARVED_BY_NO_PRIM = 0x00000105, // PAPC_PERF_SEL_ENGG_INDEX_PRIM_IF_STARVED_BY_NO_PRIM Number of clocks when the index prim interface logic is being starved and is waiting for a prim from the index sx receive logic; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_PRIM_IF_FETCH_TO_PRIMIC_P_FIFO_WRITE = 0x00000106, // PAPC_PERF_SEL_ENGG_INDEX_PRIM_IF_FETCH_TO_PRIMIC_P_FIFO_WRITE Number of clocks the index prim interface logic is writing a prim the the legacy PA prim interface, and qualified by busy; range-1/clock; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_INDEX_PRIM_IF_FETCH_TO_PRIMIC_P_FIFO_NO_WRITE = 0x00000107, // PAPC_PERF_SEL_ENGG_INDEX_PRIM_IF_FETCH_TO_PRIMIC_P_FIFO_NO_WRITE Number of clocks the index prim interface logic is not writing a prim the the legacy PA prim interface, and qualified by busy; range-1/clock; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_POS_REQ_STARVED = 0x00000108, // PAPC_PERF_SEL_ENGG_POS_REQ_STARVED Number of clocks the NGG position request machine is starved waiting for a valid CSB; range-1/clk; can be used in NGG perf analysis. All instances report the same result + PERF_ENGG_POS_REQ_STALLED_BY_FULL_CLIPV_FIFO = 0x00000109, // PAPC_PERF_SEL_ENGG_POS_REQ_STALLED_BY_FULL_CLIPV_FIFO Number of clocks the NGG position request machine is being stalled by a full NGG clipv fifo; range-1/clk; can be used in NGG perf analysis. All instances report the same result +} SU_PERFCOUNTER_SELECT; + +typedef enum SX_PERFCOUNTER_SELECT : unsigned int { + SX_PERF_SEL_PA_IDLE_CYCLES = 0x00000000, // Nr of cycles where PA was idle waiting to accept vectors from SX + SX_PERF_SEL_PA_REQ = 0x00000001, // Nr of PA requests received + SX_PERF_SEL_PA_POS = 0x00000002, // Nr of positions sent to the PA + SX_PERF_SEL_CLOCK = 0x00000003, // Nr of clocks where SX was busy in any way shape or form + SX_PERF_SEL_GATE_EN1 = 0x00000004, // Nr of clocks for register accesses + SX_PERF_SEL_GATE_EN2 = 0x00000005, // Nr of clocks for bus destination sort module + SX_PERF_SEL_GATE_EN3 = 0x00000006, // Nr of clocks for color exports + SX_PERF_SEL_GATE_EN4 = 0x00000007, // Nr of clocks for position exports + SX_PERF_SEL_SH_POS_STARVE = 0x00000008, // Nr of clocks SX is starved for Position data + SX_PERF_SEL_SH_COLOR_STARVE = 0x00000009, // Nr of clocks SX is starved for Color data + SX_PERF_SEL_SH_POS_STALL = 0x0000000a, // Nr of clocks SX is being stalled by PA + SX_PERF_SEL_SH_COLOR_STALL = 0x0000000b, // Nr of clocks SX is being stalled by at least one DB + SX_PERF_SEL_DB0_PIXELS = 0x0000000c, // Number of pixels sent to the DB0 + SX_PERF_SEL_DB0_HALF_QUADS = 0x0000000d, // Number of half quads sent to the DB0 + SX_PERF_SEL_DB0_PIXEL_STALL = 0x0000000e, // Number of cycles where pixel traffic is stalled due to the DB0 + SX_PERF_SEL_DB0_PIXEL_IDLE = 0x0000000f, // Number of cycles where the pixel traffic was idle to DB0 + SX_PERF_SEL_DB0_PRED_PIXELS = 0x00000010, // Nr of non predicated pixels sent to the DB0 + SX_PERF_SEL_DB1_PIXELS = 0x00000011, // Number of pixels sent to the DB1 + SX_PERF_SEL_DB1_HALF_QUADS = 0x00000012, // Number of half quads sent to the DB1 + SX_PERF_SEL_DB1_PIXEL_STALL = 0x00000013, // Number of cycles where pixel traffic is stalled due to the DB1 + SX_PERF_SEL_DB1_PIXEL_IDLE = 0x00000014, // Number of cycles where the pixel traffic was idle to DB1 + SX_PERF_SEL_DB1_PRED_PIXELS = 0x00000015, // Nr of non predicated pixels sent to the DB1 + SX_PERF_SEL_DB2_PIXELS = 0x00000016, // Number of pixels sent to the DB2 + SX_PERF_SEL_DB2_HALF_QUADS = 0x00000017, // Number of half quads sent to the DB2 + SX_PERF_SEL_DB2_PIXEL_STALL = 0x00000018, // Number of cycles where pixel traffic is stalled due to the DB2 + SX_PERF_SEL_DB2_PIXEL_IDLE = 0x00000019, // Number of cycles where the pixel traffic was idle to DB2 + SX_PERF_SEL_DB2_PRED_PIXELS = 0x0000001a, // Nr of non predicated pixels sent to the DB2 + SX_PERF_SEL_DB3_PIXELS = 0x0000001b, // Number of pixels sent to the DB3 + SX_PERF_SEL_DB3_HALF_QUADS = 0x0000001c, // Number of half quads sent to the DB3 + SX_PERF_SEL_DB3_PIXEL_STALL = 0x0000001d, // Number of cycles where pixel traffic is stalled due to the DB3 + SX_PERF_SEL_DB3_PIXEL_IDLE = 0x0000001e, // Number of cycles where the pixel traffic was idle to DB3 + SX_PERF_SEL_DB3_PRED_PIXELS = 0x0000001f, // Nr of non predicated pixels sent to the DB3 + SX_PERF_SEL_COL_BUSY = 0x00000020, // Number of cycles of color module's busy + SX_PERF_SEL_POS_BUSY = 0x00000021, // Number of cycles of position module's busy + SX_PERF_SEL_DB0_A2M_DISCARD_QUADS = 0x00000022, // Number of a2m_discard quads sent to the DB0 + SX_PERF_SEL_DB0_MRT0_BLEND_BYPASS = 0x00000023, // Number of mrt0 blend_bypass quads sent to the DB0 + SX_PERF_SEL_DB0_MRT0_DONT_RD_DEST = 0x00000024, // Number of mrt0 dont_rd_dest quads sent to the DB0 + SX_PERF_SEL_DB0_MRT0_DISCARD_SRC = 0x00000025, // Number of mrt0 discard_src quads sent to the DB0 + SX_PERF_SEL_DB0_MRT0_SINGLE_QUADS = 0x00000026, // Number of mrt0 single quads sent to the DB0 + SX_PERF_SEL_DB0_MRT0_DOUBLE_QUADS = 0x00000027, // Number of mrt0 double quads sent to the DB0 + SX_PERF_SEL_DB0_MRT1_BLEND_BYPASS = 0x00000028, // Number of mrt1 blend_bypass quads sent to the DB0 + SX_PERF_SEL_DB0_MRT1_DONT_RD_DEST = 0x00000029, // Number of mrt1 dont_rd_dest quads sent to the DB0 + SX_PERF_SEL_DB0_MRT1_DISCARD_SRC = 0x0000002a, // Number of mrt1 discard_src quads sent to the DB0 + SX_PERF_SEL_DB0_MRT1_SINGLE_QUADS = 0x0000002b, // Number of mrt1 single quads sent to the DB0 + SX_PERF_SEL_DB0_MRT1_DOUBLE_QUADS = 0x0000002c, // Number of mrt1 double quads sent to the DB0 + SX_PERF_SEL_DB0_MRT2_BLEND_BYPASS = 0x0000002d, // Number of mrt2 blend_bypass quads sent to the DB0 + SX_PERF_SEL_DB0_MRT2_DONT_RD_DEST = 0x0000002e, // Number of mrt2 dont_rd_dest quads sent to the DB0 + SX_PERF_SEL_DB0_MRT2_DISCARD_SRC = 0x0000002f, // Number of mrt2 discard_src quads sent to the DB0 + SX_PERF_SEL_DB0_MRT2_SINGLE_QUADS = 0x00000030, // Number of mrt2 single quads sent to the DB0 + SX_PERF_SEL_DB0_MRT2_DOUBLE_QUADS = 0x00000031, // Number of mrt2 double quads sent to the DB0 + SX_PERF_SEL_DB0_MRT3_BLEND_BYPASS = 0x00000032, // Number of mrt3 blend_bypass quads sent to the DB0 + SX_PERF_SEL_DB0_MRT3_DONT_RD_DEST = 0x00000033, // Number of mrt3 dont_rd_dest quads sent to the DB0 + SX_PERF_SEL_DB0_MRT3_DISCARD_SRC = 0x00000034, // Number of mrt3 discard_src quads sent to the DB0 + SX_PERF_SEL_DB0_MRT3_SINGLE_QUADS = 0x00000035, // Number of mrt3 single quads sent to the DB0 + SX_PERF_SEL_DB0_MRT3_DOUBLE_QUADS = 0x00000036, // Number of mrt3 double quads sent to the DB0 + SX_PERF_SEL_DB0_MRT4_BLEND_BYPASS = 0x00000037, // Number of mrt4 blend_bypass quads sent to the DB0 + SX_PERF_SEL_DB0_MRT4_DONT_RD_DEST = 0x00000038, // Number of mrt4 dont_rd_dest quads sent to the DB0 + SX_PERF_SEL_DB0_MRT4_DISCARD_SRC = 0x00000039, // Number of mrt4 discard_src quads sent to the DB0 + SX_PERF_SEL_DB0_MRT4_SINGLE_QUADS = 0x0000003a, // Number of mrt4 single quads sent to the DB0 + SX_PERF_SEL_DB0_MRT4_DOUBLE_QUADS = 0x0000003b, // Number of mrt4 double quads sent to the DB0 + SX_PERF_SEL_DB0_MRT5_BLEND_BYPASS = 0x0000003c, // Number of mrt5 blend_bypass quads sent to the DB0 + SX_PERF_SEL_DB0_MRT5_DONT_RD_DEST = 0x0000003d, // Number of mrt5 dont_rd_dest quads sent to the DB0 + SX_PERF_SEL_DB0_MRT5_DISCARD_SRC = 0x0000003e, // Number of mrt5 discard_src quads sent to the DB0 + SX_PERF_SEL_DB0_MRT5_SINGLE_QUADS = 0x0000003f, // Number of mr5 single quads sent to the DB0 + SX_PERF_SEL_DB0_MRT5_DOUBLE_QUADS = 0x00000040, // Number of mrt5 double quads sent to the DB0 + SX_PERF_SEL_DB0_MRT6_BLEND_BYPASS = 0x00000041, // Number of mrt6 blend_bypass quads sent to the DB0 + SX_PERF_SEL_DB0_MRT6_DONT_RD_DEST = 0x00000042, // Number of mrt6 dont_rd_dest quads sent to the DB0 + SX_PERF_SEL_DB0_MRT6_DISCARD_SRC = 0x00000043, // Number of mrt6 discard_src quads sent to the DB0 + SX_PERF_SEL_DB0_MRT6_SINGLE_QUADS = 0x00000044, // Number of mrt6 single quads sent to the DB0 + SX_PERF_SEL_DB0_MRT6_DOUBLE_QUADS = 0x00000045, // Number of mrt6 double quads sent to the DB0 + SX_PERF_SEL_DB0_MRT7_BLEND_BYPASS = 0x00000046, // Number of mrt7 blend_bypass quads sent to the DB0 + SX_PERF_SEL_DB0_MRT7_DONT_RD_DEST = 0x00000047, // Number of mrt7 dont_rd_dest quads sent to the DB0 + SX_PERF_SEL_DB0_MRT7_DISCARD_SRC = 0x00000048, // Number of mrt7 discard_src quads sent to the DB0 + SX_PERF_SEL_DB0_MRT7_SINGLE_QUADS = 0x00000049, // Number of mrt7 single quads sent to the DB0 + SX_PERF_SEL_DB0_MRT7_DOUBLE_QUADS = 0x0000004a, // Number of mrt7 double quads sent to the DB0 + SX_PERF_SEL_DB1_A2M_DISCARD_QUADS = 0x0000004b, // Number of a2m_discard quads sent to the DB1 + SX_PERF_SEL_DB1_MRT0_BLEND_BYPASS = 0x0000004c, // Number of mrt0 blend_bypass quads sent to the DB1 + SX_PERF_SEL_DB1_MRT0_DONT_RD_DEST = 0x0000004d, // Number of mrt0 dont_rd_dest quads sent to the DB1 + SX_PERF_SEL_DB1_MRT0_DISCARD_SRC = 0x0000004e, // Number of mrt0 discard_src quads sent to the DB1 + SX_PERF_SEL_DB1_MRT0_SINGLE_QUADS = 0x0000004f, // Number of mrt0 single quads sent to the DB1 + SX_PERF_SEL_DB1_MRT0_DOUBLE_QUADS = 0x00000050, // Number of mrt0 double quads sent to the DB1 + SX_PERF_SEL_DB1_MRT1_BLEND_BYPASS = 0x00000051, // Number of mrt1 blend_bypass quads sent to the DB1 + SX_PERF_SEL_DB1_MRT1_DONT_RD_DEST = 0x00000052, // Number of mrt1 dont_rd_dest quads sent to the DB1 + SX_PERF_SEL_DB1_MRT1_DISCARD_SRC = 0x00000053, // Number of mrt1 discard_src quads sent to the DB1 + SX_PERF_SEL_DB1_MRT1_SINGLE_QUADS = 0x00000054, // Number of mrt1 single quads sent to the DB1 + SX_PERF_SEL_DB1_MRT1_DOUBLE_QUADS = 0x00000055, // Number of mrt1 double quads sent to the DB1 + SX_PERF_SEL_DB1_MRT2_BLEND_BYPASS = 0x00000056, // Number of mrt2 blend_bypass quads sent to the DB1 + SX_PERF_SEL_DB1_MRT2_DONT_RD_DEST = 0x00000057, // Number of mrt2 dont_rd_dest quads sent to the DB1 + SX_PERF_SEL_DB1_MRT2_DISCARD_SRC = 0x00000058, // Number of mrt2 discard_src quads sent to the DB1 + SX_PERF_SEL_DB1_MRT2_SINGLE_QUADS = 0x00000059, // Number of mrt2 single quads sent to the DB1 + SX_PERF_SEL_DB1_MRT2_DOUBLE_QUADS = 0x0000005a, // Number of mrt2 double quads sent to the DB1 + SX_PERF_SEL_DB1_MRT3_BLEND_BYPASS = 0x0000005b, // Number of mrt3 blend_bypass quads sent to the DB1 + SX_PERF_SEL_DB1_MRT3_DONT_RD_DEST = 0x0000005c, // Number of mrt3 dont_rd_dest quads sent to the DB1 + SX_PERF_SEL_DB1_MRT3_DISCARD_SRC = 0x0000005d, // Number of mrt3 discard_src quads sent to the DB1 + SX_PERF_SEL_DB1_MRT3_SINGLE_QUADS = 0x0000005e, // Number of mrt3 single quads sent to the DB1 + SX_PERF_SEL_DB1_MRT3_DOUBLE_QUADS = 0x0000005f, // Number of mrt3 double quads sent to the DB1 + SX_PERF_SEL_DB1_MRT4_BLEND_BYPASS = 0x00000060, // Number of mrt4 blend_bypass quads sent to the DB1 + SX_PERF_SEL_DB1_MRT4_DONT_RD_DEST = 0x00000061, // Number of mrt4 dont_rd_dest quads sent to the DB1 + SX_PERF_SEL_DB1_MRT4_DISCARD_SRC = 0x00000062, // Number of mrt4 discard_src quads sent to the DB1 + SX_PERF_SEL_DB1_MRT4_SINGLE_QUADS = 0x00000063, // Number of mrt4 single quads sent to the DB1 + SX_PERF_SEL_DB1_MRT4_DOUBLE_QUADS = 0x00000064, // Number of mrt4 double quads sent to the DB1 + SX_PERF_SEL_DB1_MRT5_BLEND_BYPASS = 0x00000065, // Number of mrt5 blend_bypass quads sent to the DB1 + SX_PERF_SEL_DB1_MRT5_DONT_RD_DEST = 0x00000066, // Number of mrt5 dont_rd_dest quads sent to the DB1 + SX_PERF_SEL_DB1_MRT5_DISCARD_SRC = 0x00000067, // Number of mrt5 discard_src quads sent to the DB1 + SX_PERF_SEL_DB1_MRT5_SINGLE_QUADS = 0x00000068, // Number of mr5 single quads sent to the DB1 + SX_PERF_SEL_DB1_MRT5_DOUBLE_QUADS = 0x00000069, // Number of mrt5 double quads sent to the DB1 + SX_PERF_SEL_DB1_MRT6_BLEND_BYPASS = 0x0000006a, // Number of mrt6 blend_bypass quads sent to the DB1 + SX_PERF_SEL_DB1_MRT6_DONT_RD_DEST = 0x0000006b, // Number of mrt6 dont_rd_dest quads sent to the DB1 + SX_PERF_SEL_DB1_MRT6_DISCARD_SRC = 0x0000006c, // Number of mrt6 discard_src quads sent to the DB1 + SX_PERF_SEL_DB1_MRT6_SINGLE_QUADS = 0x0000006d, // Number of mrt6 single quads sent to the DB1 + SX_PERF_SEL_DB1_MRT6_DOUBLE_QUADS = 0x0000006e, // Number of mrt6 double quads sent to the DB1 + SX_PERF_SEL_DB1_MRT7_BLEND_BYPASS = 0x0000006f, // Number of mrt7 blend_bypass quads sent to the DB1 + SX_PERF_SEL_DB1_MRT7_DONT_RD_DEST = 0x00000070, // Number of mrt7 dont_rd_dest quads sent to the DB1 + SX_PERF_SEL_DB1_MRT7_DISCARD_SRC = 0x00000071, // Number of mrt7 discard_src quads sent to the DB1 + SX_PERF_SEL_DB1_MRT7_SINGLE_QUADS = 0x00000072, // Number of mrt7 single quads sent to the DB1 + SX_PERF_SEL_DB1_MRT7_DOUBLE_QUADS = 0x00000073, // Number of mrt7 double quads sent to the DB1 + SX_PERF_SEL_DB2_A2M_DISCARD_QUADS = 0x00000074, // Number of a2m_discard quads sent to the DB2 + SX_PERF_SEL_DB2_MRT0_BLEND_BYPASS = 0x00000075, // Number of mrt0 blend_bypass quads sent to the DB2 + SX_PERF_SEL_DB2_MRT0_DONT_RD_DEST = 0x00000076, // Number of mrt0 dont_rd_dest quads sent to the DB2 + SX_PERF_SEL_DB2_MRT0_DISCARD_SRC = 0x00000077, // Number of mrt0 discard_src quads sent to the DB2 + SX_PERF_SEL_DB2_MRT0_SINGLE_QUADS = 0x00000078, // Number of mrt0 single quads sent to the DB2 + SX_PERF_SEL_DB2_MRT0_DOUBLE_QUADS = 0x00000079, // Number of mrt0 double quads sent to the DB2 + SX_PERF_SEL_DB2_MRT1_BLEND_BYPASS = 0x0000007a, // Number of mrt1 blend_bypass quads sent to the DB2 + SX_PERF_SEL_DB2_MRT1_DONT_RD_DEST = 0x0000007b, // Number of mrt1 dont_rd_dest quads sent to the DB2 + SX_PERF_SEL_DB2_MRT1_DISCARD_SRC = 0x0000007c, // Number of mrt1 discard_src quads sent to the DB2 + SX_PERF_SEL_DB2_MRT1_SINGLE_QUADS = 0x0000007d, // Number of mrt1 single quads sent to the DB2 + SX_PERF_SEL_DB2_MRT1_DOUBLE_QUADS = 0x0000007e, // Number of mrt1 double quads sent to the DB2 + SX_PERF_SEL_DB2_MRT2_BLEND_BYPASS = 0x0000007f, // Number of mrt2 blend_bypass quads sent to the DB2 + SX_PERF_SEL_DB2_MRT2_DONT_RD_DEST = 0x00000080, // Number of mrt2 dont_rd_dest quads sent to the DB2 + SX_PERF_SEL_DB2_MRT2_DISCARD_SRC = 0x00000081, // Number of mrt2 discard_src quads sent to the DB2 + SX_PERF_SEL_DB2_MRT2_SINGLE_QUADS = 0x00000082, // Number of mrt2 single quads sent to the DB2 + SX_PERF_SEL_DB2_MRT2_DOUBLE_QUADS = 0x00000083, // Number of mrt2 double quads sent to the DB2 + SX_PERF_SEL_DB2_MRT3_BLEND_BYPASS = 0x00000084, // Number of mrt3 blend_bypass quads sent to the DB2 + SX_PERF_SEL_DB2_MRT3_DONT_RD_DEST = 0x00000085, // Number of mrt3 dont_rd_dest quads sent to the DB2 + SX_PERF_SEL_DB2_MRT3_DISCARD_SRC = 0x00000086, // Number of mrt3 discard_src quads sent to the DB2 + SX_PERF_SEL_DB2_MRT3_SINGLE_QUADS = 0x00000087, // Number of mrt3 single quads sent to the DB2 + SX_PERF_SEL_DB2_MRT3_DOUBLE_QUADS = 0x00000088, // Number of mrt3 double quads sent to the DB2 + SX_PERF_SEL_DB2_MRT4_BLEND_BYPASS = 0x00000089, // Number of mrt4 blend_bypass quads sent to the DB2 + SX_PERF_SEL_DB2_MRT4_DONT_RD_DEST = 0x0000008a, // Number of mrt4 dont_rd_dest quads sent to the DB2 + SX_PERF_SEL_DB2_MRT4_DISCARD_SRC = 0x0000008b, // Number of mrt4 discard_src quads sent to the DB2 + SX_PERF_SEL_DB2_MRT4_SINGLE_QUADS = 0x0000008c, // Number of mrt4 single quads sent to the DB2 + SX_PERF_SEL_DB2_MRT4_DOUBLE_QUADS = 0x0000008d, // Number of mrt4 double quads sent to the DB2 + SX_PERF_SEL_DB2_MRT5_BLEND_BYPASS = 0x0000008e, // Number of mrt5 blend_bypass quads sent to the DB2 + SX_PERF_SEL_DB2_MRT5_DONT_RD_DEST = 0x0000008f, // Number of mrt5 dont_rd_dest quads sent to the DB2 + SX_PERF_SEL_DB2_MRT5_DISCARD_SRC = 0x00000090, // Number of mrt5 discard_src quads sent to the DB2 + SX_PERF_SEL_DB2_MRT5_SINGLE_QUADS = 0x00000091, // Number of mr5 single quads sent to the DB2 + SX_PERF_SEL_DB2_MRT5_DOUBLE_QUADS = 0x00000092, // Number of mrt5 double quads sent to the DB2 + SX_PERF_SEL_DB2_MRT6_BLEND_BYPASS = 0x00000093, // Number of mrt6 blend_bypass quads sent to the DB2 + SX_PERF_SEL_DB2_MRT6_DONT_RD_DEST = 0x00000094, // Number of mrt6 dont_rd_dest quads sent to the DB2 + SX_PERF_SEL_DB2_MRT6_DISCARD_SRC = 0x00000095, // Number of mrt6 discard_src quads sent to the DB2 + SX_PERF_SEL_DB2_MRT6_SINGLE_QUADS = 0x00000096, // Number of mrt6 single quads sent to the DB2 + SX_PERF_SEL_DB2_MRT6_DOUBLE_QUADS = 0x00000097, // Number of mrt6 double quads sent to the DB2 + SX_PERF_SEL_DB2_MRT7_BLEND_BYPASS = 0x00000098, // Number of mrt7 blend_bypass quads sent to the DB2 + SX_PERF_SEL_DB2_MRT7_DONT_RD_DEST = 0x00000099, // Number of mrt7 dont_rd_dest quads sent to the DB2 + SX_PERF_SEL_DB2_MRT7_DISCARD_SRC = 0x0000009a, // Number of mrt7 discard_src quads sent to the DB2 + SX_PERF_SEL_DB2_MRT7_SINGLE_QUADS = 0x0000009b, // Number of mrt7 single quads sent to the DB2 + SX_PERF_SEL_DB2_MRT7_DOUBLE_QUADS = 0x0000009c, // Number of mrt7 double quads sent to the DB2 + SX_PERF_SEL_DB3_A2M_DISCARD_QUADS = 0x0000009d, // Number of a2m_discard quads sent to the DB3 + SX_PERF_SEL_DB3_MRT0_BLEND_BYPASS = 0x0000009e, // Number of mrt0 blend_bypass quads sent to the DB3 + SX_PERF_SEL_DB3_MRT0_DONT_RD_DEST = 0x0000009f, // Number of mrt0 dont_rd_dest quads sent to the DB3 + SX_PERF_SEL_DB3_MRT0_DISCARD_SRC = 0x000000a0, // Number of mrt0 discard_src quads sent to the DB3 + SX_PERF_SEL_DB3_MRT0_SINGLE_QUADS = 0x000000a1, // Number of mrt0 single quads sent to the DB3 + SX_PERF_SEL_DB3_MRT0_DOUBLE_QUADS = 0x000000a2, // Number of mrt0 double quads sent to the DB3 + SX_PERF_SEL_DB3_MRT1_BLEND_BYPASS = 0x000000a3, // Number of mrt1 blend_bypass quads sent to the DB3 + SX_PERF_SEL_DB3_MRT1_DONT_RD_DEST = 0x000000a4, // Number of mrt1 dont_rd_dest quads sent to the DB3 + SX_PERF_SEL_DB3_MRT1_DISCARD_SRC = 0x000000a5, // Number of mrt1 discard_src quads sent to the DB3 + SX_PERF_SEL_DB3_MRT1_SINGLE_QUADS = 0x000000a6, // Number of mrt1 single quads sent to the DB3 + SX_PERF_SEL_DB3_MRT1_DOUBLE_QUADS = 0x000000a7, // Number of mrt1 double quads sent to the DB3 + SX_PERF_SEL_DB3_MRT2_BLEND_BYPASS = 0x000000a8, // Number of mrt2 blend_bypass quads sent to the DB3 + SX_PERF_SEL_DB3_MRT2_DONT_RD_DEST = 0x000000a9, // Number of mrt2 dont_rd_dest quads sent to the DB3 + SX_PERF_SEL_DB3_MRT2_DISCARD_SRC = 0x000000aa, // Number of mrt2 discard_src quads sent to the DB3 + SX_PERF_SEL_DB3_MRT2_SINGLE_QUADS = 0x000000ab, // Number of mrt2 single quads sent to the DB3 + SX_PERF_SEL_DB3_MRT2_DOUBLE_QUADS = 0x000000ac, // Number of mrt2 double quads sent to the DB3 + SX_PERF_SEL_DB3_MRT3_BLEND_BYPASS = 0x000000ad, // Number of mrt3 blend_bypass quads sent to the DB3 + SX_PERF_SEL_DB3_MRT3_DONT_RD_DEST = 0x000000ae, // Number of mrt3 dont_rd_dest quads sent to the DB3 + SX_PERF_SEL_DB3_MRT3_DISCARD_SRC = 0x000000af, // Number of mrt3 discard_src quads sent to the DB3 + SX_PERF_SEL_DB3_MRT3_SINGLE_QUADS = 0x000000b0, // Number of mrt3 single quads sent to the DB3 + SX_PERF_SEL_DB3_MRT3_DOUBLE_QUADS = 0x000000b1, // Number of mrt3 double quads sent to the DB3 + SX_PERF_SEL_DB3_MRT4_BLEND_BYPASS = 0x000000b2, // Number of mrt4 blend_bypass quads sent to the DB3 + SX_PERF_SEL_DB3_MRT4_DONT_RD_DEST = 0x000000b3, // Number of mrt4 dont_rd_dest quads sent to the DB3 + SX_PERF_SEL_DB3_MRT4_DISCARD_SRC = 0x000000b4, // Number of mrt4 discard_src quads sent to the DB3 + SX_PERF_SEL_DB3_MRT4_SINGLE_QUADS = 0x000000b5, // Number of mrt4 single quads sent to the DB3 + SX_PERF_SEL_DB3_MRT4_DOUBLE_QUADS = 0x000000b6, // Number of mrt4 double quads sent to the DB3 + SX_PERF_SEL_DB3_MRT5_BLEND_BYPASS = 0x000000b7, // Number of mrt5 blend_bypass quads sent to the DB3 + SX_PERF_SEL_DB3_MRT5_DONT_RD_DEST = 0x000000b8, // Number of mrt5 dont_rd_dest quads sent to the DB3 + SX_PERF_SEL_DB3_MRT5_DISCARD_SRC = 0x000000b9, // Number of mrt5 discard_src quads sent to the DB3 + SX_PERF_SEL_DB3_MRT5_SINGLE_QUADS = 0x000000ba, // Number of mr5 single quads sent to the DB3 + SX_PERF_SEL_DB3_MRT5_DOUBLE_QUADS = 0x000000bb, // Number of mrt5 double quads sent to the DB3 + SX_PERF_SEL_DB3_MRT6_BLEND_BYPASS = 0x000000bc, // Number of mrt6 blend_bypass quads sent to the DB3 + SX_PERF_SEL_DB3_MRT6_DONT_RD_DEST = 0x000000bd, // Number of mrt6 dont_rd_dest quads sent to the DB3 + SX_PERF_SEL_DB3_MRT6_DISCARD_SRC = 0x000000be, // Number of mrt6 discard_src quads sent to the DB3 + SX_PERF_SEL_DB3_MRT6_SINGLE_QUADS = 0x000000bf, // Number of mrt6 single quads sent to the DB3 + SX_PERF_SEL_DB3_MRT6_DOUBLE_QUADS = 0x000000c0, // Number of mrt6 double quads sent to the DB3 + SX_PERF_SEL_DB3_MRT7_BLEND_BYPASS = 0x000000c1, // Number of mrt7 blend_bypass quads sent to the DB3 + SX_PERF_SEL_DB3_MRT7_DONT_RD_DEST = 0x000000c2, // Number of mrt7 dont_rd_dest quads sent to the DB3 + SX_PERF_SEL_DB3_MRT7_DISCARD_SRC = 0x000000c3, // Number of mrt7 discard_src quads sent to the DB3 + SX_PERF_SEL_DB3_MRT7_SINGLE_QUADS = 0x000000c4, // Number of mrt7 single quads sent to the DB3 + SX_PERF_SEL_DB3_MRT7_DOUBLE_QUADS = 0x000000c5, // Number of mrt7 double quads sent to the DB3 + SX_PERF_SEL_PA_REQ_LATENCY = 0x000000c6, // Number of all pa request latency + SX_PERF_SEL_POS_SCBD_STALL = 0x000000c7, // Number of cycles SX is being stalled by position scoreboard + SX_PERF_SEL_COL_SCBD_STALL = 0x000000c8, // Number of cycles SX is being stalled by color scoreboard + SX_PERF_SEL_CLOCK_DROP_STALL = 0x000000c9, // Number of cycles where SX was busy in any way shape or form excluding stall cycles + SX_PERF_SEL_GATE_EN5 = 0x000000ca, // Number of cycles for color exports excluding stall cycles + SX_PERF_SEL_GATE_EN6 = 0x000000cb, // Number of cycles for position exports excluding stall cycles + SX_PERF_SEL_DB0_SIZE = 0x000000cc, // Number of dw (current smallest unit) send to DB0 + SX_PERF_SEL_DB1_SIZE = 0x000000cd, // Number of dw (current smallest unit) send to DB1 + SX_PERF_SEL_DB2_SIZE = 0x000000ce, // Number of dw (current smallest unit) send to DB2 + SX_PERF_SEL_DB3_SIZE = 0x000000cf, // Number of dw (current smallest unit) send to DB3 + SX_PERF_SEL_SPLITMODE = 0x000000d0, // Number of compat level switching in splitmode + SX_PERF_SEL_COL_SCBD0_STALL = 0x000000d1, // Number of cycles SX is being stalled by color scoreboard for packer0 + SX_PERF_SEL_COL_SCBD1_STALL = 0x000000d2, // Number of cycles SX is being stalled by color scoreboard for packer1 + SX_PERF_SEL_IDX_STALL_CYCLES = 0x000000d3, // Nr of clocks SX is being stalled by PA index request + SX_PERF_SEL_IDX_IDLE_CYCLES = 0x000000d4, // Nr of cycles where PA was idle waiting to accept index vectors from SX + SX_PERF_SEL_IDX_REQ = 0x000000d5, // Nr of PA index requests received + SX_PERF_SEL_IDX_RET = 0x000000d6, // Nr of index sent to the PA + SX_PERF_SEL_IDX_REQ_LATENCY = 0x000000d7, // Number of all index request latency + SX_PERF_SEL_IDX_SCBD_STALL = 0x000000d8, // Number of cycles SX is being stalled by index scoreboard + SX_PERF_SEL_GATE_EN7 = 0x000000d9, // Number of cycles for index exports including stall cycles + SX_PERF_SEL_GATE_EN8 = 0x000000da, // Number of cycles for index exports excluding stall cycles + SX_PERF_SEL_SH_IDX_STARVE = 0x000000db, // Nr of clocks SX is starved for index data + SX_PERF_SEL_IDX_BUSY = 0x000000dc, // Number of cycles of index module's busy + SX_PERF_SEL_RB0_STALL_DUE_TO_ORDERING = 0x000000dd, // Number of cycles of RB0 is stalled due to color scoreboard ordering + SX_PERF_SEL_RB1_STALL_DUE_TO_ORDERING = 0x000000de, // Number of cycles of RB1 is stalled due to color scoreboard ordering + SX_PERF_SEL_RB2_STALL_DUE_TO_ORDERING = 0x000000df, // Number of cycles of RB2 is stalled due to color scoreboard ordering + SX_PERF_SEL_RB3_STALL_DUE_TO_ORDERING = 0x000000e0, // Number of cycles of RB3 is stalled due to color scoreboard ordering +} SX_PERFCOUNTER_SELECT; + +typedef enum TA_PERFCOUNTER_SELECT : unsigned int { + TA_PERF_SEL_NULL = 0x00000000, // NULL + TA_PERF_SEL_RESERVED_1 = 0x00000001, // RESERVED 1. + TA_PERF_SEL_RESERVED_2 = 0x00000002, // RESERVED 2. + TA_PERF_SEL_RESERVED_3 = 0x00000003, // RESERVED 3. + TA_PERF_SEL_RESERVED_4 = 0x00000004, // RESERVED 4. + TA_PERF_SEL_RESERVED_5 = 0x00000005, // RESERVED 5. + TA_PERF_SEL_RESERVED_6 = 0x00000006, // RESERVED 6. + TA_PERF_SEL_gradient_busy = 0x00000007, // Gradient subblocks are busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_gradient_fifo_busy = 0x00000008, // Gradient FIFO subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_lod_busy = 0x00000009, // Aniso subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_lod_fifo_busy = 0x0000000a, // LOD FIFO subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_addresser_busy = 0x0000000b, // Addresser subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_addresser_fifo_busy = 0x0000000c, // Addresser FIFO subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_aligner_busy = 0x0000000d, // Aligner subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_write_path_busy = 0x0000000e, // Write Path subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_ta_busy = 0x0000000f, // TA block is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_RESERVED_16 = 0x00000010, // RESERVED 16. + TA_PERF_SEL_RESERVED_17 = 0x00000011, // RESERVED 17. + TA_PERF_SEL_RESERVED_18 = 0x00000012, // RESERVED 18. + TA_PERF_SEL_RESERVED_19 = 0x00000013, // RESERVED 19. + TA_PERF_SEL_RESERVED_20 = 0x00000014, // RESERVED 20. + TA_PERF_SEL_RESERVED_21 = 0x00000015, // RESERVED 21. + TA_PERF_SEL_RESERVED_22 = 0x00000016, // RESERVED 22. + TA_PERF_SEL_RESERVED_23 = 0x00000017, // RESERVED 23. + TA_PERF_SEL_RESERVED_24 = 0x00000018, // RESERVED 24. + TA_PERF_SEL_RESERVED_25 = 0x00000019, // RESERVED 25. + TA_PERF_SEL_RESERVED_26 = 0x0000001a, // RESERVED 26. + TA_PERF_SEL_RESERVED_27 = 0x0000001b, // RESERVED 27. + TA_PERF_SEL_RESERVED_28 = 0x0000001c, // RESERVED 28. + TA_PERF_SEL_RESERVED_29 = 0x0000001d, // RESERVED 29. + TA_PERF_SEL_RESERVED_30 = 0x0000001e, // RESERVED 30. + TA_PERF_SEL_RESERVED_31 = 0x0000001f, // RESERVED 31. + TA_PERF_SEL_total_wavefronts = 0x00000020, // Total number of wavefronts processed by TA. + TA_PERF_SEL_gradient_cycles = 0x00000021, // Number of cycles issued by the per-pixel-gradient state machine. + TA_PERF_SEL_walker_cycles = 0x00000022, // Number of cycles issued by the sampler state machine. + TA_PERF_SEL_aligner_cycles = 0x00000023, // Number of cycles issued by the aligner state machine. + TA_PERF_SEL_image_wavefronts = 0x00000024, // Number of image vec32 packets processed by TA. + TA_PERF_SEL_image_read_wavefronts = 0x00000025, // Number of image read (sample*, load*, gather4*) vec32 packets processed by TA. + TA_PERF_SEL_image_write_wavefronts = 0x00000026, // Number of image write (store*) vec32 packets processed by TA. + TA_PERF_SEL_image_atomic_wavefronts = 0x00000027, // Number of image atomic vec32 packets processed by TA. + TA_PERF_SEL_image_sampler_total_cycles = 0x00000028, // Number of image sampler cycles issued to TC. + TA_PERF_SEL_image_nosampler_total_cycles = 0x00000029, // Number of image no-sampler cycles issued to TC. + TA_PERF_SEL_flat_total_cycles = 0x0000002a, // Number of flat cycles issued to TC. + TA_PERF_SEL_bvh_total_cycles = 0x0000002b, // Number of bvh cycles issued to TC. + TA_PERF_SEL_buffer_wavefronts = 0x0000002c, // Number of buffer vec32 packets processed by TA. + TA_PERF_SEL_buffer_read_wavefronts = 0x0000002d, // Number of buffer read (load*) vec32 packets processed by TA. + TA_PERF_SEL_buffer_write_wavefronts = 0x0000002e, // Number of buffer write (store*) vec32 packets processed by TA. + TA_PERF_SEL_buffer_atomic_wavefronts = 0x0000002f, // Number of buffer atomic vec32 packets processed by TA. + TA_PERF_SEL_RESERVED_48 = 0x00000030, // RESERVED 48. + TA_PERF_SEL_buffer_total_cycles = 0x00000031, // Number of buffer cycles issued to TC. + TA_PERF_SEL_RESERVED_50 = 0x00000032, // RESERVED 50. + TA_PERF_SEL_RESERVED_51 = 0x00000033, // RESERVED 51. + TA_PERF_SEL_RESERVED_52 = 0x00000034, // RESERVED 52. + TA_PERF_SEL_RESERVED_53 = 0x00000035, // RESERVED 53. + TA_PERF_SEL_addr_stalled_by_tc_cycles = 0x00000036, // Number of cycles addr path stalled by TC. Perf_Windowing not supported for this counter. + TA_PERF_SEL_addr_stalled_by_td_cycles = 0x00000037, // Number of cycles addr path stalled by TD. Perf_Windowing not supported for this counter. + TA_PERF_SEL_RESERVED_56 = 0x00000038, // RESERVED 56. + TA_PERF_SEL_addresser_stalled_by_aligner_only_cycles = 0x00000039, // Number of cycles Addresser stalled by Aligner and not further down the pipe. Perf_Windowing not supported for this counter. + TA_PERF_SEL_addresser_stalled_cycles = 0x0000003a, // Number of cycles Addresser stalled. Perf_Windowing not supported for this counter. + TA_PERF_SEL_aniso_stalled_by_addresser_only_cycles = 0x0000003b, // Number of cycles Aniso stalled by Addresser and not further down the pipe. Perf_Windowing not supported for this counter. + TA_PERF_SEL_aniso_stalled_cycles = 0x0000003c, // Number of cycles Aniso stalled. Perf_Windowing not supported for this counter. + TA_PERF_SEL_deriv_stalled_by_aniso_only_cycles = 0x0000003d, // Number of cycles Gradient stalled by Aniso and not further down the pipe. Perf_Windowing not supported for this counter. + TA_PERF_SEL_deriv_stalled_cycles = 0x0000003e, // Number of cycles Gradient stalled. Perf_Windowing not supported for this counter. + TA_PERF_SEL_aniso_gt1_cycle_quads = 0x0000003f, // Number of quads requiring more than 1 aniso sample. + TA_PERF_SEL_color_1_cycle_pixels = 0x00000040, // Number of pixels requiring sampler state machine to take 1 cycle due to format. + TA_PERF_SEL_color_2_cycle_pixels = 0x00000041, // Number of pixels requiring sampler state machine to take 2 cycles due to format. + TA_PERF_SEL_color_3_cycle_pixels = 0x00000042, // Number of pixels requiring sampler state machine to take 3 cycles due to format. + TA_PERF_SEL_RESERVED_67 = 0x00000043, // RESERVED 67. + TA_PERF_SEL_mip_1_cycle_pixels = 0x00000044, // Number of pixels requiring sampler state machine to take 1 cycle due to mip filter. + TA_PERF_SEL_mip_2_cycle_pixels = 0x00000045, // Number of pixels requiring sampler state machine to take 2 cycles due to mip filter. + TA_PERF_SEL_vol_1_cycle_pixels = 0x00000046, // Number of pixels requiring sampler state machine to take 1 cycle due to z filter. + TA_PERF_SEL_vol_2_cycle_pixels = 0x00000047, // Number of pixels requiring sampler state machine to take 2 cycles due to z filter. + TA_PERF_SEL_bilin_point_1_cycle_pixels = 0x00000048, // Number of pixels requiring sampler state machine to take 1 cycle due to xy filter. + TA_PERF_SEL_mipmap_lod_0_samples = 0x00000049, // Number of samples fetched from mip 0. + TA_PERF_SEL_mipmap_lod_1_samples = 0x0000004a, // Number of samples fetched from mip 1. + TA_PERF_SEL_mipmap_lod_2_samples = 0x0000004b, // Number of samples fetched from mip 2. + TA_PERF_SEL_mipmap_lod_3_samples = 0x0000004c, // Number of samples fetched from mip 3. + TA_PERF_SEL_mipmap_lod_4_samples = 0x0000004d, // Number of samples fetched from mip 4. + TA_PERF_SEL_mipmap_lod_5_samples = 0x0000004e, // Number of samples fetched from mip 5. + TA_PERF_SEL_mipmap_lod_6_samples = 0x0000004f, // Number of samples fetched from mip 6. + TA_PERF_SEL_mipmap_lod_7_samples = 0x00000050, // Number of samples fetched from mip 7. + TA_PERF_SEL_mipmap_lod_8_samples = 0x00000051, // Number of samples fetched from mip 8. + TA_PERF_SEL_mipmap_lod_9_samples = 0x00000052, // Number of samples fetched from mip 9. + TA_PERF_SEL_mipmap_lod_10_samples = 0x00000053, // Number of samples fetched from mip 10. + TA_PERF_SEL_mipmap_lod_11_samples = 0x00000054, // Number of samples fetched from mip 11. + TA_PERF_SEL_mipmap_lod_12_samples = 0x00000055, // Number of samples fetched from mip 12. + TA_PERF_SEL_mipmap_lod_13_samples = 0x00000056, // Number of samples fetched from mip 13. + TA_PERF_SEL_mipmap_lod_14_samples = 0x00000057, // Number of samples fetched from mip 14. + TA_PERF_SEL_mipmap_invalid_samples = 0x00000058, // Number of samples marked invalid using mip 15 method. + TA_PERF_SEL_aniso_1_cycle_quads = 0x00000059, // Number of quads requiring 1 aniso sample. + TA_PERF_SEL_aniso_2_cycle_quads = 0x0000005a, // Number of quads requiring 2 aniso sample. + TA_PERF_SEL_aniso_4_cycle_quads = 0x0000005b, // Number of quads requiring 4 aniso sample. + TA_PERF_SEL_aniso_6_cycle_quads = 0x0000005c, // Number of quads requiring 6 aniso sample. + TA_PERF_SEL_aniso_8_cycle_quads = 0x0000005d, // Number of quads requiring 8 aniso sample. + TA_PERF_SEL_aniso_10_cycle_quads = 0x0000005e, // Number of quads requiring 10 aniso sample. + TA_PERF_SEL_aniso_12_cycle_quads = 0x0000005f, // Number of quads requiring 12 aniso sample. + TA_PERF_SEL_aniso_14_cycle_quads = 0x00000060, // Number of quads requiring 14 aniso sample. + TA_PERF_SEL_aniso_16_cycle_quads = 0x00000061, // Number of quads requiring 16 aniso sample. + TA_PERF_SEL_write_path_input_cycles = 0x00000062, // Number of cycles received from write datapath from ta_input. + TA_PERF_SEL_write_path_output_cycles = 0x00000063, // Number of cycles sent from write datapath to TC. + TA_PERF_SEL_flat_wavefronts = 0x00000064, // Number of flat opcode vec32 packets processed by the TA. + TA_PERF_SEL_flat_read_wavefronts = 0x00000065, // Number of flat opcode read vec32 packets processed by the TA. + TA_PERF_SEL_flat_write_wavefronts = 0x00000066, // Number of flat opcode write vec32 packets processed by the TA. + TA_PERF_SEL_flat_atomic_wavefronts = 0x00000067, // Number of flat opcode atomic vec32 packets processed by the TA. + TA_PERF_SEL_RESERVED_104 = 0x00000068, // RESERVED 104. + TA_PERF_SEL_reg_sclk_vld = 0x00000069, // Number of cycles reg_sclk is active. Perf_Windowing not supported for this counter. + TA_PERF_SEL_local_cg_dyn_sclk_grp0_en = 0x0000006a, // Number of cycles grp0 sclk is active. Perf_Windowing not supported for this counter. + TA_PERF_SEL_local_cg_dyn_sclk_grp1_en = 0x0000006b, // Number of cycles grp1 sclk is active. Perf_Windowing not supported for this counter. + TA_PERF_SEL_local_cg_dyn_sclk_grp1_mems_en = 0x0000006c, // Number of cycles grp1_mems sclk is active. Perf_Windowing not supported for this counter. + TA_PERF_SEL_local_cg_dyn_sclk_grp4_en = 0x0000006d, // Number of cycles grp4 sclk is active. Perf_Windowing not supported for this counter. + TA_PERF_SEL_local_cg_dyn_sclk_grp5_en = 0x0000006e, // Number of cycles grp5 sclk is active. Perf_Windowing not supported for this counter. + TA_PERF_SEL_xnack = 0x0000006f, // Non-zero Xnack mask returned. This counter is always 0x0 for configurations that do not support XNACKs. Perf_Windowing not supported for this counter. + TA_PERF_SEL_RESERVED_112 = 0x00000070, // RESERVED 112. + TA_PERF_SEL_RESERVED_113 = 0x00000071, // RESERVED 113. + TA_PERF_SEL_RESERVED_114 = 0x00000072, // RESERVED 114. + TA_PERF_SEL_first_xnack = 0x00000073, // First Xnack of an instruction. This counter is always 0x0 for configurations that do not support XNACKs. Perf_Windowing not supported for this counter. + TA_PERF_SEL_RESERVED_116 = 0x00000074, // RESERVED 116. + TA_PERF_SEL_RESERVED_117 = 0x00000075, // RESERVED 117. + TA_PERF_SEL_RESERVED_118 = 0x00000076, // RESERVED 118. + TA_PERF_SEL_RESERVED_119 = 0x00000077, // RESERVED 119. + TA_PERF_SEL_RESERVED_120 = 0x00000078, // RESERVED 120. + TA_PERF_SEL_RESERVED_121 = 0x00000079, // RESERVED 121. + TA_PERF_SEL_RESERVED_122 = 0x0000007a, // RESERVED 122. + TA_PERF_SEL_RESERVED_123 = 0x0000007b, // RESERVED 123. + TA_PERF_SEL_RESERVED_124 = 0x0000007c, // RESERVED 124. + TA_PERF_SEL_RESERVED_125 = 0x0000007d, // RESERVED 125. + TA_PERF_SEL_RESERVED_126 = 0x0000007e, // RESERVED 126. + TA_PERF_SEL_RESERVED_127 = 0x0000007f, // RESERVED 127. + TA_PERF_SEL_in_busy = 0x00000080, // Input subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_in_fifos_busy = 0x00000081, // Input subblock fifos are busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_in_cfifo_busy = 0x00000082, // Input subblock cmd fifo is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_in_qfifo_busy = 0x00000083, // Input subblock request fifo busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_in_wfifo_busy = 0x00000084, // Input subblock write control fifo busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_in_rfifo_busy = 0x00000085, // Input subblock read control fifo busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_bf_busy = 0x00000086, // Buffer/Flat Addressing subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_ns_busy = 0x00000087, // Image no-sampler Addressing subblock is busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_smp_busy_ns_idle = 0x00000088, // sampler path is busy but all of the no-sampler blocks are idle. Perf_Windowing not supported for this counter. + TA_PERF_SEL_smp_idle_ns_busy = 0x00000089, // sampler path is idle but all of the no-sampler blocks are busy. Perf_Windowing not supported for this counter. + TA_PERF_SEL_RESERVED_138 = 0x0000008a, // RESERVED 138. + TA_PERF_SEL_RESERVED_139 = 0x0000008b, // RESERVED 139 + TA_PERF_SEL_RESERVED_140 = 0x0000008c, // RESERVED 140. + TA_PERF_SEL_RESERVED_141 = 0x0000008d, // RESERVED 141. + TA_PERF_SEL_RESERVED_142 = 0x0000008e, // RESERVED 142. + TA_PERF_SEL_RESERVED_143 = 0x0000008f, // RESERVED 143. + TA_PERF_SEL_vmemcmd_cycles = 0x00000090, // Number of cycles on vmemcmd destined for TA. Perf_Windowing not supported for this counter. + TA_PERF_SEL_vmemreq_cycles = 0x00000091, // Number of cycles on vmemreq destined for TA. Perf_Windowing not supported for this counter. + TA_PERF_SEL_in_waiting_on_req_cycles = 0x00000092, // Input block waiting on req cycles only. Perf_Windowing not supported for this counter. + TA_PERF_SEL_in_waiting_on_cmd_cycles = 0x00000093, // Input block waiting on cmd cycles only. Perf_Windowing not supported for this counter. + TA_PERF_SEL_in_waiting_on_any_cycles = 0x00000094, // Input block waiting on req or cmd cycles. Perf_Windowing not supported for this counter. + TA_PERF_SEL_RESERVED_149 = 0x00000095, // RESERVED 149. + TA_PERF_SEL_in_addr_cycles = 0x00000096, // Number of address cycles output from ta_input. Perf_Windowing not supported for this counter. + TA_PERF_SEL_in_data_cycles = 0x00000097, // Number of write data cycles output from ta_input. Perf_Windowing not supported for this counter. + TA_PERF_SEL_addr_stalled_by_xnack_cycles = 0x00000098, // Number of cycles addr path stalled by TA nack fifo. Perf_Windowing not supported for this counter. + TA_PERF_SEL_RESERVED_153 = 0x00000099, // RESERVED 153. + TA_PERF_SEL_RESERVED_154 = 0x0000009a, // RESERVED 154. + TA_PERF_SEL_RESERVED_155 = 0x0000009b, // RESERVED 155. + TA_PERF_SEL_RESERVED_156 = 0x0000009c, // RESERVED 156. + TA_PERF_SEL_RESERVED_157 = 0x0000009d, // RESERVED 157. + TA_PERF_SEL_RESERVED_158 = 0x0000009e, // RESERVED 158. + TA_PERF_SEL_RESERVED_159 = 0x0000009f, // RESERVED 159. + TA_PERF_SEL_point_sampled_quads = 0x000000a0, // Number of quads requiring only point-sampling. + TA_PERF_SEL_RESERVED_161 = 0x000000a1, // RESERVED 161. + TA_PERF_SEL_RESERVED_162 = 0x000000a2, // RESERVED 162. + TA_PERF_SEL_RESERVED_163 = 0x000000a3, // RESERVED 163. + TA_PERF_SEL_RESERVED_164 = 0x000000a4, // RESERVED 164. + TA_PERF_SEL_RESERVED_165 = 0x000000a5, // RESERVED 165. + TA_PERF_SEL_RESERVED_166 = 0x000000a6, // RESERVED 166. + TA_PERF_SEL_RESERVED_167 = 0x000000a7, // RESERVED 167. + TA_PERF_SEL_RESERVED_168 = 0x000000a8, // RESERVED 168. + TA_PERF_SEL_RESERVED_169 = 0x000000a9, // RESERVED 169. + TA_PERF_SEL_RESERVED_170 = 0x000000aa, // RESERVED 170. + TA_PERF_SEL_RESERVED_171 = 0x000000ab, // RESERVED 171. + TA_PERF_SEL_RESERVED_172 = 0x000000ac, // RESERVED 172. + TA_PERF_SEL_RESERVED_173 = 0x000000ad, // RESERVED 173. + TA_PERF_num_nodes_invalidated_due_to_bad_input = 0x000000ae, // Number of nodes invalidated to to inf/nan input or RESERVED node_type. + TA_PERF_num_nodes_invalidated_due_to_oob = 0x000000af, // Number of nodes invalidated due to OOB result in address check. + TA_PERF_num_of_bvh_valid_first_tri = 0x000000b0, // Number of valid BVH first triangles sent out of the TA. + TA_PERF_num_of_bvh_valid_second_tri = 0x000000b1, // Number of valid BVH second triangles sent out of the TA. + TA_PERF_num_of_bvh_valid_third_tri = 0x000000b2, // Number of valid BVH third triangles sent out of the TA. + TA_PERF_num_of_bvh_valid_fourth_tri = 0x000000b3, // Number of valid BVH fourth triangles sent out of the TA. + TA_PERF_num_of_bvh_valid_fp16_box = 0x000000b4, // Number of valid BVH fp16 boxes sent out of the TA. + TA_PERF_num_of_bvh_valid_fp32_box = 0x000000b5, // Number of valid BVH fp32 boxes sent out of the TA. + TA_PERF_num_of_bvh_invalidated_first_tri = 0x000000b6, // Number of invalidated BVH first triangles sent out of the TA. + TA_PERF_num_of_bvh_invalidated_second_tri = 0x000000b7, // Number of invalidated BVH second triangles sent out of the TA. + TA_PERF_num_of_bvh_invalidated_third_tri = 0x000000b8, // Number of invalidated BVH third triangles sent out of the TA. + TA_PERF_num_of_bvh_invalidated_fourth_tri = 0x000000b9, // Number of invalidated BVH fourth triangles sent out of the TA. + TA_PERF_num_of_bvh_invalidated_fp16_box = 0x000000ba, // Number of invalidated BVH fp16 boxes sent out of the TA. + TA_PERF_num_of_bvh_invalidated_fp32_box = 0x000000bb, // Number of invalidated BVH fp32 boxes sent out of the TA. + TA_PERF_SEL_RESERVED_188 = 0x000000bc, // RESERVED 188. + TA_PERF_SEL_RESERVED_189 = 0x000000bd, // RESERVED 189. + TA_PERF_SEL_RESERVED_190 = 0x000000be, // RESERVED 190. + TA_PERF_SEL_RESERVED_191 = 0x000000bf, // RESERVED 191. + TA_PERF_SEL_RESERVED_192 = 0x000000c0, // RESERVED 192. + TA_PERF_SEL_RESERVED_193 = 0x000000c1, // RESERVED 193. + TA_PERF_SEL_RESERVED_194 = 0x000000c2, // RESERVED 194. + TA_PERF_SEL_RESERVED_195 = 0x000000c3, // RESERVED 195. + TA_PERF_SEL_RESERVED_196 = 0x000000c4, // RESERVED 196. + TA_PERF_SEL_RESERVED_197 = 0x000000c5, // RESERVED 197. + TA_PERF_SEL_RESERVED_198 = 0x000000c6, // RESERVED 198. + TA_PERF_SEL_RESERVED_199 = 0x000000c7, // RESERVED 199. + TA_PERF_SEL_RESERVED_200 = 0x000000c8, // RESERVED 200. + TA_PERF_SEL_RESERVED_201 = 0x000000c9, // RESERVED 201. + TA_PERF_SEL_RESERVED_202 = 0x000000ca, // RESERVED 202. + TA_PERF_SEL_RESERVED_203 = 0x000000cb, // RESERVED 203. + TA_PERF_SEL_RESERVED_204 = 0x000000cc, // RESERVED 204. + TA_PERF_SEL_RESERVED_205 = 0x000000cd, // RESERVED 205. + TA_PERF_SEL_RESERVED_206 = 0x000000ce, // RESERVED 206. + TA_PERF_SEL_RESERVED_207 = 0x000000cf, // RESERVED 207. + TA_PERF_SEL_RESERVED_208 = 0x000000d0, // RESERVED 208. + TA_PERF_SEL_RESERVED_209 = 0x000000d1, // RESERVED 209. + TA_PERF_SEL_RESERVED_210 = 0x000000d2, // RESERVED 210. + TA_PERF_SEL_RESERVED_211 = 0x000000d3, // RESERVED 211. + TA_PERF_SEL_RESERVED_212 = 0x000000d4, // RESERVED 212. + TA_PERF_SEL_RESERVED_213 = 0x000000d5, // RESERVED 213. + TA_PERF_SEL_RESERVED_214 = 0x000000d6, // RESERVED 214. + TA_PERF_SEL_RESERVED_215 = 0x000000d7, // RESERVED 215. + TA_PERF_SEL_RESERVED_216 = 0x000000d8, // RESERVED 216. + TA_PERF_SEL_RESERVED_217 = 0x000000d9, // RESERVED 217. + TA_PERF_SEL_RESERVED_218 = 0x000000da, // RESERVED 218. + TA_PERF_SEL_RESERVED_219 = 0x000000db, // RESERVED 219. + TA_PERF_SEL_RESERVED_220 = 0x000000dc, // RESERVED 220. + TA_PERF_SEL_RESERVED_221 = 0x000000dd, // RESERVED 221. + TA_PERF_SEL_RESERVED_222 = 0x000000de, // RESERVED 222. + TA_PERF_SEL_RESERVED_223 = 0x000000df, // RESERVED 223. + TA_PERF_SEL_sample_path_cycles = 0x000000e0, // Number of clock cycles the TA sampler path is enabled. Perf_Windowing not supported for this counter. + TA_PERF_SEL_nosample_path_cycles = 0x000000e1, // Number of clock cycles the TA no_sampler path is enabled. Perf_Windowing not supported for this counter. +} TA_PERFCOUNTER_SELECT; + +typedef enum TCP_PERFCOUNTER_SELECT : unsigned int { + TCP_PERF_SEL_GATE_EN1 = 0x00000000, // TCP interface clocks are turned on. Not Windowed. + TCP_PERF_SEL_GATE_EN2 = 0x00000001, // TCP core clocks are turned on. Not Windowed. + TCP_PERF_SEL_TA_REQ = 0x00000002, // Total reqs from TA + TCP_PERF_SEL_TA_REQ_STATE_READ = 0x00000003, // Number of state reads (start of a wave instruction) + TCP_PERF_SEL_TA_REQ_READ = 0x00000004, // Total reqs from TA using read opcodes + TCP_PERF_SEL_TA_REQ_WRITE = 0x00000005, // Total reqs from TA using write opcodes + TCP_PERF_SEL_TA_REQ_ATOMIC_WITH_RET = 0x00000006, // Total reqs from TA using atomic with return opcodes + TCP_PERF_SEL_TA_REQ_ATOMIC_WITHOUT_RET = 0x00000007, // Total reqs from TA using atomic without return opcodes + TCP_PERF_SEL_TA_REQ_GL0_INV = 0x00000008, // Total reqs from TA using GL0_INV opcode + TCP_PERF_SEL_REQ = 0x00000009, // Total cache line accesses + TCP_PERF_SEL_REQ_READ = 0x0000000a, // Total cache read requests + TCP_PERF_SEL_REQ_READ_HIT_EVICT = 0x0000000b, // Total cache reads using HIT_EVICT policy + TCP_PERF_SEL_REQ_READ_HIT_LRU = 0x0000000c, // Total cache reads using HIT_LRU policy + TCP_PERF_SEL_REQ_READ_MISS_EVICT = 0x0000000d, // Total cache reads using MISS_EVICT policy + TCP_PERF_SEL_REQ_WRITE = 0x0000000e, // Total cache write requests + TCP_PERF_SEL_REQ_WRITE_MISS_EVICT = 0x0000000f, // Total cache writes using MISS_EVICT policy + TCP_PERF_SEL_REQ_WRITE_MISS_LRU = 0x00000010, // Total cache writes using MISS_LRU policy + TCP_PERF_SEL_REQ_NON_READ = 0x00000011, // Total cache non-read requests + TCP_PERF_SEL_REQ_MISS = 0x00000012, // Total cache requests that missed + TCP_PERF_SEL_REQ_TAGBANK0 = 0x00000013, // Total cache requests for tag bank 0 + TCP_PERF_SEL_REQ_TAGBANK1 = 0x00000014, // Total cache requests for tag bank 1 + TCP_PERF_SEL_REQ_TAGBANK2 = 0x00000015, // Total cache requests for tag bank 2 + TCP_PERF_SEL_REQ_TAGBANK3 = 0x00000016, // Total cache requests for tag bank 3 + TCP_PERF_SEL_REQ_MISS_TAGBANK0 = 0x00000017, // Total cache requests that missed for tag bank 0 + TCP_PERF_SEL_REQ_MISS_TAGBANK1 = 0x00000018, // Total cache requests that missed for tag bank 1 + TCP_PERF_SEL_REQ_MISS_TAGBANK2 = 0x00000019, // Total cache requests that missed for tag bank 2 + TCP_PERF_SEL_REQ_MISS_TAGBANK3 = 0x0000001a, // Total cache requests that missed for tag bank 3 + TCP_PERF_SEL_GL1_REQ_READ = 0x0000001b, // Total read requests to GL1. + TCP_PERF_SEL_GL1_REQ_READ_128B = 0x0000001c, // Total read requests to GL1 with 128B size. + TCP_PERF_SEL_GL1_REQ_READ_64B = 0x0000001d, // Total read requests to GL1 with 64B size. + TCP_PERF_SEL_GL1_REQ_WRITE = 0x0000001e, // Total write requests to GL1. + TCP_PERF_SEL_GL1_REQ_ATOMIC_WITH_RET = 0x0000001f, // Total atomic with return requests to GL1. + TCP_PERF_SEL_GL1_REQ_ATOMIC_WITHOUT_RET = 0x00000020, // Total atomic without return requests to GL1. + TCP_PERF_SEL_GL1_READ_LATENCY = 0x00000021, // Total latency for reads and atomics with return. Not windowed. + TCP_PERF_SEL_GL1_WRITE_LATENCY = 0x00000022, // Total TC->GL1 request latency for reads and atomics with return. Not windowed. + TCP_PERF_SEL_TCP_LATENCY = 0x00000023, // Total TCP instruction latency (from first clock of instruction entering to first clock of instruction leaving), divide by TA_TCP_STATE_READ to average instruction latency. + TCP_PERF_SEL_TCP_TA_REQ_STALL = 0x00000024, // TCP stalls TA req interface. + TCP_PERF_SEL_TA_TCP_REQ_STARVE = 0x00000025, // TA starves TA req interface. Not Windowed. + TCP_PERF_SEL_TA_TCP_XNACK_STALL = 0x00000026, // Total number of cycles TA stalled the TCP_TA_xnack interface. Not Windowed. + TCP_PERF_SEL_DATA_FIFO_STALL = 0x00000027, // TPCP stalls TA req due to data fifo full + TCP_PERF_SEL_LOD_STALL = 0x00000028, // Per-element LOD stall (TCP supports one mip level per cycle) + TCP_PERF_SEL_POWER_STALL = 0x00000029, // Count of stalls due to power throttling + TCP_PERF_SEL_ALLOC_STALL = 0x0000002a, // Alloc stall on inflight cache line + TCP_PERF_SEL_UNORDERED_MTYPE_STALL = 0x0000002b, // Total stalls to maintain coherency for UC/CC mtype (GL2 unordered) + TCP_PERF_SEL_READ_TAGCONFLICT_STALL = 0x0000002c, // Tag conflict stall on a read + TCP_PERF_SEL_WRITE_TAGCONFLICT_STALL = 0x0000002d, // Tag conflict stall on a write + TCP_PERF_SEL_ATOMIC_TAGCONFLICT_STALL = 0x0000002e, // Tag conflict stall on an atomic + TCP_PERF_SEL_LFIFO_STALL = 0x0000002f, // Memory latency fifos full stall + TCP_PERF_SEL_MEM_REQ_FIFO_STALL = 0x00000030, // Stall due to memory request fifo full + TCP_PERF_SEL_GL1_TCP_STALL = 0x00000031, // TCP_GL1 request interface stalled by GL1 + TCP_PERF_SEL_TCP_GL1_STARVE = 0x00000032, // TCP starves GL1 req interface. + TCP_PERF_SEL_GL1_TCP_RDRET_STALL = 0x00000033, // Write to cache stalled by read return from GL1. + TCP_PERF_SEL_GL1_GRANT_READ_STALL = 0x00000034, // Read from cache stalled due to GL1 write data bus grant + TCP_PERF_SEL_GL1_PENDING_STALL = 0x00000035, // Stall due to waiting for response from GL1 + TCP_PERF_SEL_OFIFO_INCOMPLETE_STALL = 0x00000036, // Stall in ofifo due to waiting for incomplete (split) non-sampler instruction + TCP_PERF_SEL_OFIFO_AGE_ORDER_STALL = 0x00000037, // Stall in ofifo due to age order enforcement for incomplete instructions + TCP_PERF_SEL_TD_DATA_CYCLE_STALL = 0x00000038, // Read pipe stall due to TC_TD data interface cycling + TCP_PERF_SEL_COMP_TEX_LOAD_STALL = 0x00000039, // Read pipe stall due to block-compressed format load cycling + TCP_PERF_SEL_READ_DATACONFLICT_STALL = 0x0000003a, // Read stall due to cache data bank conflict + TCP_PERF_SEL_WRITE_DATACONFLICT_STALL = 0x0000003b, // Write stall due to cache data bank conflict + TCP_PERF_SEL_TD_TCP_STALL = 0x0000003c, // TD stalls TCP + TCP_PERF_SEL_UTCL0_REQUEST = 0x0000003d, // Total CLIENT_UTCL0 NORMAL requests + TCP_PERF_SEL_UTCL0_TRANSLATION_MISS = 0x0000003e, // Total UTCL0 translation misses + TCP_PERF_SEL_UTCL0_TRANSLATION_HIT = 0x0000003f, // Total UTCL0 translation hits + TCP_PERF_SEL_UTCL0_PERMISSION_MISS = 0x00000040, // Total UTCL0 permission misses + TCP_PERF_SEL_UTCL0_SERIALIZATION_STALL = 0x00000041, // Total stalls due to serializing translation requests through the UTCL0. + TCP_PERF_SEL_UTCL0_STALL_INFLIGHT_MAX = 0x00000042, // Total UTCL0 stalls due to inflight counter saturation + TCP_PERF_SEL_UTCL0_STALL_LRU_INFLIGHT = 0x00000043, // Total UTCL0 stalls due to LRU cache line with traffic inflight + TCP_PERF_SEL_UTCL0_STALL_MULTI_MISS = 0x00000044, // Total UTCL0 stalls due to arbitrated multiple misses + TCP_PERF_SEL_UTCL0_STALL_LFIFO_FULL = 0x00000045, // Total UTCL0 latency hiding fifo full cycles + TCP_PERF_SEL_UTCL0_STALL_MISSFIFO_FULL = 0x00000046, // Total UTCL0 stalls due to full miss fifo + TCP_PERF_SEL_UTCL0_STALL_LFIFO_NOT_RES = 0x00000047, // Total UTCL0 stalls due to latency hiding fifo output waiting on translation responses + TCP_PERF_SEL_UTCL0_STALL_UTCL1_REQ_OUT_OF_CREDITS = 0x00000048, // Total UTCL0 stalls due to out of credits for UTCL1 req + TCP_PERF_SEL_CLIENT_UTCL0_INFLIGHT = 0x00000049, // The sum of inflight client to UTCL0 requests per cycle + TCP_PERF_SEL_UTCL0_UTCL1_INFLIGHT = 0x0000004a, // The sum of inflight UTCL0_UTCL1 requests per cycle + TCP_PERF_SEL_UTCL0_UTCL1_PERM_FAULT = 0x0000004b, // Total UTCL0 to UTCL1 permission fault + TCP_PERF_SEL_BACK_COMPAT_SWITCH = 0x0000004c, // Count of cases where compatibility level changes back-to-back (split mode). +} TCP_PERFCOUNTER_SELECT; + +typedef enum TD_PERFCOUNTER_SELECT : unsigned int { + TD_PERF_SEL_none = 0x00000000, // Won't count anything. + TD_PERF_SEL_td_busy = 0x00000001, // TD is processing or waiting for data. Perf_Windowing not supported for this counter. + TD_PERF_SEL_input_busy = 0x00000002, // TD input subblock is busy or waiting for data. This means the instruction, state or TC data fifos may not be empty or the TD is processing a wave. Perf_Windowing not supported for this counter. + TD_PERF_SEL_sampler_lerp_busy = 0x00000003, // TD filter subblock is busy, which means any of the four lerps has pixel data flowing down its pipeline (blend, accumulation, format). Perf_Windowing not supported for this counter. + TD_PERF_SEL_sampler_out_busy = 0x00000004, // TD sampler output subblock is busy. This means the TD's sampler output pipeline (accumulation, data swizzle, data packing) could be processing pixel data. Perf_Windowing not supported for this counter. + TD_PERF_SEL_nofilter_busy = 0x00000005, // TD no_filter subblock is busy. This means the TD's no_filter pipeline (decode, format, data swizzle, data packing) could be processing non-sampler data. Perf_Windowing not supported for this counter. + TD_PERF_SEL_sampler_sclk_on_nofilter_sclk_off = 0x00000006, // Number of cycles the sampler sclk is on while the no_filter sclk is off. Perf_Windowing not supported for this counter. + TD_PERF_SEL_nofilter_sclk_on_sampler_sclk_off = 0x00000007, // Number of cycles the no_filter sclk is on while the sampler sclk is off. Perf_Windowing not supported for this counter. + TD_PERF_SEL_core_state_ram_max_cnt = 0x00000008, // Denotes the maximum number of entries ever used in the TA_TD latency RAM for core state. In order to get an accurate count, this counter must be enabled soon after reset. Also, once the counter is read the value of the counter is no longer accurate. A chip reset is required to get another accurate count. Perf_Windowing not supported for this counter. + TD_PERF_SEL_core_state_rams_read = 0x00000009, // Number of times the RAMS that store core state are read. + TD_PERF_SEL_weight_data_rams_read = 0x0000000a, // Number of times the RAMs that store the weight data are read. + TD_PERF_SEL_reference_data_rams_read = 0x0000000b, // Number of times the RAMS that store the sample_c/gather4_c reference data are read. + TD_PERF_SEL_tc_td_ram_fifo_full = 0x0000000c, // TC_TD_ram input FIFO is full. This counter could denote a stall in the TD pipeline, which could come from data cycling or power throttling from the SMU. Perf_Windowing not supported for this counter. + TD_PERF_SEL_tc_td_ram_fifo_max_cnt = 0x0000000d, // Denotes the maximum number of TC_TD_ram requests ever stored in the TC_TD_ram fifo. In order to get an accurate count, this counter must be enabled soon after reset. Also, once the counter is read the value of the counter is no longer accurate. A chip reset is required to get another accurate count. Perf_Windowing not supported for this counter. + TD_PERF_SEL_tc_td_data_fifo_full = 0x0000000e, // TC_TD_data input FIFO is full. This counter could denote a stall from either TD pipeline (sampler or no_filter), which could come from data cycling or power throttling from the SMU. Perf_Windowing not supported for this counter. + TD_PERF_SEL_input_state_fifo_full = 0x0000000f, // TD input state FIFO is full. This counter could denote there is no data from the TC or a stall in the TD pipeline. Perf_Windowing not supported for this counter. + TD_PERF_SEL_ta_data_stall = 0x00000010, // TD is stalled waiting for TA data. Perf_Windowing not supported for this counter. + TD_PERF_SEL_tc_data_stall = 0x00000011, // TD is stalled waiting for TC data. + TD_PERF_SEL_tc_ram_stall = 0x00000012, // TD is stalled waiting for a TC ram request. Perf_Windowing not supported for this counter. + TD_PERF_SEL_lds_stall = 0x00000013, // TD is stalled because it has run out of credits and it has data waiting to be sent out to the LDS. + TD_PERF_SEL_sampler_pkr_full = 0x00000014, // Both portions of the sampler's packer are full. Could be caused by arbritation or lack of credits from the LDS. + TD_PERF_SEL_nofilter_pkr_full = 0x00000015, // Both portions of the no_filter's packer is full. Could be caused by arbritation or lack of credits from the LDS. + TD_PERF_SEL_gather4_wavefront = 0x00000016, // Count the wavefronts with opcode = gather4, includes gather4_c. + TD_PERF_SEL_gather4h_wavefront = 0x00000017, // Count the wavefronts with opcode = gather4h. + TD_PERF_SEL_gather4h_packed_wavefront = 0x00000018, // Count the wavefronts with opcode = gather4h_packed. + TD_PERF_SEL_gather8h_packed_wavefront = 0x00000019, // Count the wavefronts with opcode = gather8h_packed. + TD_PERF_SEL_sample_c_wavefront = 0x0000001a, // Count the wavefronts with opcode = sample_c, includes gather4_c. + TD_PERF_SEL_load_wavefront = 0x0000001b, // Count the wavefronts with opcode = load. Includes atomics. + TD_PERF_SEL_ldfptr_wavefront = 0x0000001c, // Count the wavefronts with LDFPTR formats. + TD_PERF_SEL_RESERVED_29 = 0x0000001d, // RESERVED_29 + TD_PERF_SEL_write_ack_wavefront = 0x0000001e, // Count write acknowledgments (no data return). + TD_PERF_SEL_d16_en_wavefront = 0x0000001f, // Count the wavefronts that use d16 conversion + TD_PERF_SEL_bypassLerp_wavefront = 0x00000020, // Count the sampler wavefronts that bypass the bilinear interpolator. Includes gather4, point-sample instructions and unfilterable formats. + TD_PERF_SEL_min_max_filter_wavefront = 0x00000021, // Count the wavefronts that use min/max filtering. + TD_PERF_SEL_one_comp_wavefront = 0x00000022, // dmask=1,2,4,8 (post d16 packing), one component wavefront sent to the LDS. + TD_PERF_SEL_two_comp_wavefront = 0x00000023, // dmask=3,5,6,9,a,c (post d16 packing), two component wavefront sent to the LDS. + TD_PERF_SEL_three_comp_wavefront = 0x00000024, // dmask=7,b,d,e (post d16 packing), three component wavefront sent to the LDS. + TD_PERF_SEL_four_comp_wavefront = 0x00000025, // dmask=f (post d16 packing), four component wavefront sent to the LDS. + TD_PERF_SEL_user_defined_border = 0x00000026, // Count the wavefronts that user defined border color was used. + TD_PERF_SEL_white_border = 0x00000027, // Count the wavefronts that white border color was used. + TD_PERF_SEL_opaque_black_border = 0x00000028, // Count the wavefronts that opaque black border color was used. + TD_PERF_SEL_lod_warn_from_ta = 0x00000029, // Count the number of cycles the TA sends the TD at least one LOD warning. + TD_PERF_SEL_wavefront_dest_is_lds = 0x0000002a, // Count the number of times this TD sends data to the LDS. This is a count of the LDS-only instructions, not all traffic on the TD_LDS_return interface. + TD_PERF_SEL_td_cycling_of_nofilter_instr = 0x0000002b, // Count the number of no-filter instructions where the TD has to cycle due to the data format and the number of available formatters. + TD_PERF_SEL_tc_cycling_of_nofilter_instr = 0x0000002c, // Count the number of no-filter instructions where the TC has to cycle data to the TD. + TD_PERF_SEL_out_of_order_instr = 0x0000002d, // Count the number of out-of-order instructions from the TA. + TD_PERF_SEL_total_num_instr = 0x0000002e, // The total number of instructions seen by this TD. + TD_PERF_SEL_mixmode_instruction = 0x0000002f, // For modes that align with the instruction, count the times the TD processes requests from the following compat levels: GEN_TWO->GEN_ONE, GEN_ONE->GEN_TWO, GEN_TWO->GEN_ZERO, GEN_ZERO->GEN_TWO. The instructions don't have to be back-to-back. When the hardware is reset, the TD will bootup in GEN_TWO mode. + TD_PERF_SEL_mixmode_resource = 0x00000030, // For modes that align with the resource, count the times the TD processes requests from the following compat levels: GEN_TWO->GEN_ONE, GEN_ONE->GEN_TWO, GEN_TWO->GEN_ZERO, GEN_ZERO->GEN_TWO. The instructions don't have to be back-to-back. When the hardware is reset, the TD will bootup in GEN_TWO mode. + TD_PERF_SEL_status_packet = 0x00000031, // Count the number of times a nack packet was generated and sent to the LDS. Includes both nack and LOD warning packets. + TD_PERF_SEL_address_cmd_poison = 0x00000032, // Count the wavefronts that had poisoned address or command. + TD_PERF_SEL_data_poison = 0x00000033, // Count the wavefronts that had poisoned data. + TD_PERF_SEL_done_scoreboard_max_stored_cnt = 0x00000034, // Denotes the maximum amount of instructions that ever get stored in the TD done scoreboard. In order to get an accurate count, this counter must be enabled soon after reset. Also, once the counter is read the value of the counter is no longer accurate. A chip reset is required to get another accurate count. Perf_Windowing not supported for this counter. + TD_PERF_SEL_done_scoreboard_max_waiting_cnt = 0x00000035, // Denotes the maximum amount of instructions that have had their data sent to the LDS but their dones have not been sent. In order to get an accurate count, this counter must be enabled soon after reset. Also, once the counter is read the value of the counter is no longer accurate. A chip reset is required to get another accurate count. Perf_Windowing not supported for this counter. + TD_PERF_SEL_done_scoreboard_not_empty = 0x00000036, // TD done scoreboard fifo is not empty. This fifo is used to reorder instructions so the dones leave the TD in-order. Perf_Windowing not supported for this counter. + TD_PERF_SEL_done_scoreboard_is_full = 0x00000037, // TD done scoreboard fifo is full. Perf_Windowing not supported for this counter. + TD_PERF_SEL_done_scoreboard_bp_due_to_ooo = 0x00000038, // TD done scoreboard is back pressured by out-of-order instructions. Perf_Windowing not supported for this counter. + TD_PERF_SEL_done_scoreboard_bp_due_to_lds = 0x00000039, // TD done scoreboard is back pressured by lack of credits on the TD_LDS_return interface. Perf_Windowing not supported for this counter. + TD_PERF_SEL_nofilter_formatters_turned_on = 0x0000003a, // Count the number of formatters in the no-filter pipeline that are not clock-gated off due to fixed destination selects and dmask. + TD_PERF_SEL_nofilter_popcount_dmask_gt_num_comp_of_fmt = 0x0000003b, // Count the number of no-filter instructions that have a dmask with more components lit than the number of components of the data format. + TD_PERF_SEL_nofilter_popcount_dmask_lt_num_comp_of_fmt = 0x0000003c, // Count the number of no-filter instructions that have a dmask with less components lit than the number of components of the data format. + TD_PERF_SEL_msaa_load_wavefront = 0x0000003d, // Count the wavefronts with opcode = msaa_load. + TD_PERF_SEL_blend_prt_with_prt_default_0 = 0x0000003e, // Count the number of sampler instructions that enable blend_prt and the prt default is 0. + TD_PERF_SEL_blend_prt_with_prt_default_1 = 0x0000003f, // Count the number of sampler instructions that enable blend_prt and the prt default is 1. + TD_PERF_SEL_resmap_wavefront = 0x00000040, // Count the wavefronts that are residency maps. + TD_PERF_SEL_prt_ack_wavefront = 0x00000041, // Count the number of wavefronts that are prt acks. These acks could be residency maps or status maps. The TD does not know when it gets the ack from the TA. + TD_PERF_SEL_resmap_with_volume_filtering = 0x00000042, // Count the number of pixels that have a residency map with volume filtering. + TD_PERF_SEL_resmap_with_aniso_filtering = 0x00000043, // Count the number of pixels that have a residency map with aniso filtering. + TD_PERF_SEL_resmap_with_no_more_filtering = 0x00000044, // Count the number of pixels that have a residency map that requires no extra filtering (neither volume or aniso). + TD_PERF_SEL_resmap_with_cubemap_corner = 0x00000045, // Count the number of pixels that have a residency map with a cubemap corner. + TD_PERF_SEL_ray_tracing_bvh4_wavefront = 0x00000046, // Count the wavefronts with opcode = bvh_intersect_ray. + TD_PERF_SEL_ray_tracing_bvh4_threads_per_wavefront_is_0 = 0x00000047, // Number of times a bvh4 wavefront had no valid threads written out to LDS. + TD_PERF_SEL_ray_tracing_bvh4_threads_per_wavefront_is_1 = 0x00000048, // Number of times a bvh4 wavefront had only 1 thread written out to LDS. + TD_PERF_SEL_ray_tracing_bvh4_threads_per_wavefront_is_2 = 0x00000049, // Number of times a bvh4 wavefront had 2 threads total written out to LDS. + TD_PERF_SEL_ray_tracing_bvh4_threads_per_wavefront_is_3to4 = 0x0000004a, // Number of times a bvh4 wavefront had 3 or 4 threads total written out to LDS. + TD_PERF_SEL_ray_tracing_bvh4_threads_per_wavefront_is_5to8 = 0x0000004b, // Number of times a bvh4 wavefront had between 5 and 8 threads total written out to LDS. + TD_PERF_SEL_ray_tracing_bvh4_threads_per_wavefront_is_9to16 = 0x0000004c, // Number of times a bvh4 wavefront had between 9 and 16 threads total written out to LDS. + TD_PERF_SEL_ray_tracing_bvh4_threads_per_wavefront_is_17to31 = 0x0000004d, // Number of times a bvh4 wavefront had between 17 and 31 threads total written out to LDS. + TD_PERF_SEL_ray_tracing_bvh4_threads_per_wavefront_is_32 = 0x0000004e, // Number of times a bvh4 wavefront had all 32 threads written out to LDS. + TD_PERF_SEL_ray_tracing_bvh4_fp16_box_node = 0x0000004f, // Count the number of FP16 box nodes seen in all bvh4 wavefronts. + TD_PERF_SEL_ray_tracing_bvh4_fp32_box_node = 0x00000050, // Count the number of FP32 box nodes seen in all bvh4 wavefronts. + TD_PERF_SEL_ray_tracing_bvh4_tri_node = 0x00000051, // Count the number of triangle nodes seen in all bvh4 wavefronts. + TD_PERF_SEL_ray_tracing_bvh4_box_sort_en = 0x00000052, // Count the number of bvh4 wavefronts that had box nodes that needed to be sorted. + TD_PERF_SEL_ray_tracing_bvh4_box_grow_val_nonzero = 0x00000053, // Count the number of bvh4 wavefronts that had box nodes with non-zero grow values. + TD_PERF_SEL_ray_tracing_bvh4_num_box_with_inf_or_nan_vtx = 0x00000054, // Count the number of boxes that have a vertex with the value of infinity or NaN. + TD_PERF_SEL_ray_tracing_bvh4_num_tri_with_inf_or_nan_vtx = 0x00000055, // Count the number of triangles that have a vertex with the value of infinity or NaN. + TD_PERF_SEL_ray_tracing_bvh4_num_box_that_squashed_a_nan = 0x00000056, // Count the number of boxes that had either their min or max value set to NaN (which will cause (min,max) to be set to (inf,-inf)). + TD_PERF_SEL_ray_tracing_bvh4_num_box_misses = 0x00000057, // Number of times a box node missed. + TD_PERF_SEL_ray_tracing_bvh4_num_tri_misses = 0x00000058, // Number of times a triangle node missed. + TD_PERF_SEL_ray_tracing_bvh4_num_tri_tie_breakers = 0x00000059, // Number of times a triangle node missed due to a tie breaker. + TD_PERF_SEL_ray_tracing_bvh4_pkr_full = 0x0000005a, // Both portions of the bvh4's packer are full. Could be caused by arbritation or lack of credits from the LDS. + TD_PERF_SEL_ray_tracing_bvh4_busy = 0x0000005b, // TD ray tracing subblock is busy. This means the TD's raytracing pipeline (box and triangle test pipeline) could be processing pixel data. Perf_Windowing not supported for this counter. +} TD_PERFCOUNTER_SELECT; + +typedef enum GCMC_VM_L2_PERFCOUNTER_SELECT : unsigned int { + GCMC_VM_L2_PERF_SEL_count_cycles = 0x00000000, + GCMC_VM_L2_PERF_SEL_side0_bank0_pte_cache_bigk0_request = 0x00000001, + GCMC_VM_L2_PERF_SEL_side0_bank0_pte_cache_bigk0_hit = 0x00000002, + GCMC_VM_L2_PERF_SEL_side0_bank0_pte_cache_bigk0_miss = 0x00000003, + GCMC_VM_L2_PERF_SEL_side0_bank0_pte_cache_bigk0_update = 0x00000004, + GCMC_VM_L2_PERF_SEL_side0_bank0_pte_cache_4k0_request = 0x00000005, + GCMC_VM_L2_PERF_SEL_side0_bank0_pte_cache_4k0_hit = 0x00000006, + GCMC_VM_L2_PERF_SEL_side0_bank0_pte_cache_4k0_miss = 0x00000007, + GCMC_VM_L2_PERF_SEL_side0_bank0_pte_cache_4k0_update = 0x00000008, + GCMC_VM_L2_PERF_SEL_side0_bank0_aggregate_request = 0x00000009, + GCMC_VM_L2_PERF_SEL_side0_bank0_aggregate_hit = 0x0000000a, + GCMC_VM_L2_PERF_SEL_side0_bank0_aggregate_miss = 0x0000000b, + GCMC_VM_L2_PERF_SEL_side0_bank0_aggregate_update = 0x0000000c, + GCMC_VM_L2_PERF_SEL_side0_bank1_pte_cache_bigk0_request = 0x0000000d, + GCMC_VM_L2_PERF_SEL_side0_bank1_pte_cache_bigk0_hit = 0x0000000e, + GCMC_VM_L2_PERF_SEL_side0_bank1_pte_cache_bigk0_miss = 0x0000000f, + GCMC_VM_L2_PERF_SEL_side0_bank1_pte_cache_bigk0_update = 0x00000010, + GCMC_VM_L2_PERF_SEL_side0_bank1_pte_cache_4k0_request = 0x00000011, + GCMC_VM_L2_PERF_SEL_side0_bank1_pte_cache_4k0_hit = 0x00000012, + GCMC_VM_L2_PERF_SEL_side0_bank1_pte_cache_4k0_miss = 0x00000013, + GCMC_VM_L2_PERF_SEL_side0_bank1_pte_cache_4k0_update = 0x00000014, + GCMC_VM_L2_PERF_SEL_side0_bank1_aggregate_request = 0x00000015, + GCMC_VM_L2_PERF_SEL_side0_bank1_aggregate_hit = 0x00000016, + GCMC_VM_L2_PERF_SEL_side0_bank1_aggregate_miss = 0x00000017, + GCMC_VM_L2_PERF_SEL_side0_bank1_aggregate_update = 0x00000018, + GCMC_VM_L2_PERF_SEL_side0_bank2_pte_cache_bigk0_request = 0x00000019, + GCMC_VM_L2_PERF_SEL_side0_bank2_pte_cache_bigk0_hit = 0x0000001a, + GCMC_VM_L2_PERF_SEL_side0_bank2_pte_cache_bigk0_miss = 0x0000001b, + GCMC_VM_L2_PERF_SEL_side0_bank2_pte_cache_bigk0_update = 0x0000001c, + GCMC_VM_L2_PERF_SEL_side0_bank2_pte_cache_4k0_request = 0x0000001d, + GCMC_VM_L2_PERF_SEL_side0_bank2_pte_cache_4k0_hit = 0x0000001e, + GCMC_VM_L2_PERF_SEL_side0_bank2_pte_cache_4k0_miss = 0x0000001f, + GCMC_VM_L2_PERF_SEL_side0_bank2_pte_cache_4k0_update = 0x00000020, + GCMC_VM_L2_PERF_SEL_side0_bank2_aggregate_request = 0x00000021, + GCMC_VM_L2_PERF_SEL_side0_bank2_aggregate_hit = 0x00000022, + GCMC_VM_L2_PERF_SEL_side0_bank2_aggregate_miss = 0x00000023, + GCMC_VM_L2_PERF_SEL_side0_bank2_aggregate_update = 0x00000024, + GCMC_VM_L2_PERF_SEL_side0_bank3_pte_cache_bigk0_request = 0x00000025, + GCMC_VM_L2_PERF_SEL_side0_bank3_pte_cache_bigk0_hit = 0x00000026, + GCMC_VM_L2_PERF_SEL_side0_bank3_pte_cache_bigk0_miss = 0x00000027, + GCMC_VM_L2_PERF_SEL_side0_bank3_pte_cache_bigk0_update = 0x00000028, + GCMC_VM_L2_PERF_SEL_side0_bank3_pte_cache_4k0_request = 0x00000029, + GCMC_VM_L2_PERF_SEL_side0_bank3_pte_cache_4k0_hit = 0x0000002a, + GCMC_VM_L2_PERF_SEL_side0_bank3_pte_cache_4k0_miss = 0x0000002b, + GCMC_VM_L2_PERF_SEL_side0_bank3_pte_cache_4k0_update = 0x0000002c, + GCMC_VM_L2_PERF_SEL_side0_bank3_aggregate_request = 0x0000002d, + GCMC_VM_L2_PERF_SEL_side0_bank3_aggregate_hit = 0x0000002e, + GCMC_VM_L2_PERF_SEL_side0_bank3_aggregate_miss = 0x0000002f, + GCMC_VM_L2_PERF_SEL_side0_bank3_aggregate_update = 0x00000030, + GCMC_VM_L2_PERF_SEL_fault_retry = 0x00000031, + GCMC_VM_L2_PERF_SEL_fault_no_retry = 0x00000032, + GCMC_VM_L2_PERF_SEL_fault_interrupt = 0x00000033, + GCMC_VM_L2_PERF_SEL_walker_pde0_cache_request = 0x00000034, + GCMC_VM_L2_PERF_SEL_walker_pde0_cache_hit = 0x00000035, + GCMC_VM_L2_PERF_SEL_walker_pde0_cache_miss = 0x00000036, + GCMC_VM_L2_PERF_SEL_walker_pde0_cache_update = 0x00000037, + GCMC_VM_L2_PERF_SEL_walker_pde0_cache_pte = 0x00000038, + GCMC_VM_L2_PERF_SEL_walker_pde1_cache_request = 0x00000039, + GCMC_VM_L2_PERF_SEL_walker_pde1_cache_hit = 0x0000003a, + GCMC_VM_L2_PERF_SEL_walker_pde1_cache_miss = 0x0000003b, + GCMC_VM_L2_PERF_SEL_walker_pde1_cache_update = 0x0000003c, + GCMC_VM_L2_PERF_SEL_walker_pde1_cache_pte = 0x0000003d, + GCMC_VM_L2_PERF_SEL_walker_pde2_cache_request = 0x0000003e, + GCMC_VM_L2_PERF_SEL_walker_pde2_cache_hit = 0x0000003f, + GCMC_VM_L2_PERF_SEL_walker_pde2_cache_miss = 0x00000040, + GCMC_VM_L2_PERF_SEL_walker_pde2_cache_update = 0x00000041, + GCMC_VM_L2_PERF_SEL_walker_pde2_cache_pte = 0x00000042, + GCMC_VM_L2_PERF_SEL_walker_log_inval = 0x00000043, + GCMC_VM_L2_PERF_SEL_walker_log_trans = 0x00000044, + GCMC_VM_L2_PERF_SEL_walker_log_trans_skipped = 0x00000045, + GCMC_VM_L2_PERF_SEL_walker_rdif_request_physical_system = 0x00000046, + GCMC_VM_L2_PERF_SEL_walker_rdif_request_physical_system_start_latency = 0x00000047, + GCMC_VM_L2_PERF_SEL_walker_rdif_request_physical_system_stop_latency = 0x00000048, + GCMC_VM_L2_PERF_SEL_walker_rdif_request_other = 0x00000049, + GCMC_VM_L2_PERF_SEL_walker_rdif_request_other_start_latency = 0x0000004a, + GCMC_VM_L2_PERF_SEL_walker_rdif_request_other_stop_latency = 0x0000004b, + GCMC_VM_L2_PERF_SEL_walker_qos_request = 0x0000004c, + GCMC_VM_L2_PERF_SEL_walker_qos_miss_fetch_issued = 0x0000004d, + GCMC_VM_L2_PERF_SEL_walker_qos_hit_fetch_skipped = 0x0000004e, + GCMC_VM_L2_PERF_SEL_walker_level0_request = 0x0000004f, + GCMC_VM_L2_PERF_SEL_walker_level1_request = 0x00000050, + GCMC_VM_L2_PERF_SEL_walker_level2_request = 0x00000051, + GCMC_VM_L2_PERF_SEL_walker_level3_request = 0x00000052, + GCMC_VM_L2_PERF_SEL_walker_level0_request_start_latency = 0x00000053, + GCMC_VM_L2_PERF_SEL_walker_level0_request_stop_latency = 0x00000054, + GCMC_VM_L2_PERF_SEL_walker_level1_request_start_latency = 0x00000055, + GCMC_VM_L2_PERF_SEL_walker_level1_request_stop_latency = 0x00000056, + GCMC_VM_L2_PERF_SEL_walker_level2_request_start_latency = 0x00000057, + GCMC_VM_L2_PERF_SEL_walker_level2_request_stop_latency = 0x00000058, + GCMC_VM_L2_PERF_SEL_walker_level3_request_start_latency = 0x00000059, + GCMC_VM_L2_PERF_SEL_walker_level3_request_stop_latency = 0x0000005a, +} GCMC_VM_L2_PERFCOUNTER_SELECT; + +}; + +static const UINT D3D12XBOX_COUNTER_SET_DESC_VERSION = 4; + +typedef struct D3D12XBOX_COUNTER_SET_DESC +{ + UINT Size; + UINT Version; + + UINT MC_CITF_CID; + UINT SQ_SHADER_MASK; + + // Dimension is number of counters which can be simultaneously retrieved. + UINT CB [4]; + UINT CHA [4]; + UINT CHC [4]; + UINT CP [2]; + UINT CPC [2]; + UINT CPF [2]; + UINT DB [4]; + UINT GCR [2]; + UINT GDS [4]; + UINT GE [12]; + UINT GL1A [4]; + UINT GL1C [4]; + UINT GL2A [4]; + UINT GL2C [4]; + UINT GRBM [1]; + UINT GRBMSE0 [1]; + UINT GRBMSE1 [1]; + UINT IH [1]; + UINT PH [8]; + UINT RMI [4]; + UINT SC [8]; + UINT SDMA [1]; + UINT SPI [4]; + UINT SQ [16]; + UINT SU [4]; + UINT SX [4]; + UINT TA [5]; + UINT TCP [8]; + UINT TD [1]; + UINT EA [1]; + UINT ATCL2 [1]; + UINT VML2 [2]; +} D3D12XBOX_COUNTER_SET_DESC; + +#define D3D12XBOX_COUNTER_INVALID ( 0xffffffffU ) + +typedef struct D3D12XBOX_COUNTER_DATA +{ + UINT Size; + UINT Version; + + // First dimension is number of counters which can be simultaneously retrieved. + // Second dimension is number of hardware instances of the component (for Anaconda). + UINT64 CB [4] [8]; + UINT64 CHA [4] [1]; + UINT64 CHC [4] [4]; + UINT64 CP [2] [1]; + UINT64 CPC [2] [1]; + UINT64 CPF [2] [1]; + UINT64 DB [4] [8]; + UINT64 GCR [2] [1]; + UINT64 GDS [4] [1]; + UINT64 GE [12] [1]; + UINT64 GL1A [4] [4]; + UINT64 GL1C [4] [16]; + UINT64 GL2A [4] [4]; + UINT64 GL2C [4] [20]; + UINT64 GRBM [1] [1]; + UINT64 GRBMSE0 [1] [1]; + UINT64 GRBMSE1 [1] [1]; + UINT64 IH [1] [1]; + UINT64 PH [8] [1]; + UINT64 RMI [4] [4]; + UINT64 SC [8] [8]; + UINT64 SDMA [1] [1]; + UINT64 SPI [4] [2]; + UINT64 SQ [16][2]; + UINT64 SU [4] [4]; + UINT64 SX [4] [4]; + UINT64 TA [5] [52]; + UINT64 TCP [8] [52]; + UINT64 TD [1] [52]; + UINT64 EA [1] [20]; + UINT64 ATCL2 [1] [1]; + UINT64 VML2 [2] [1]; +} D3D12XBOX_COUNTER_DATA; + +typedef struct D3D12XBOX_COUNTER_LOCKHART_DATA +{ + UINT Size; + UINT Version; + + // First dimension is number of counters which can be simultaneously retrieved. + // Second dimension is number of hardware instances of the component (for Lockhart). + UINT64 CB [4] [4]; + UINT64 CHA [4] [1]; + UINT64 CHC [4] [4]; + UINT64 CP [2] [1]; + UINT64 CPC [2] [1]; + UINT64 CPF [2] [1]; + UINT64 DB [4] [4]; + UINT64 GCR [2] [1]; + UINT64 GDS [4] [1]; + UINT64 GE [12][1]; + UINT64 GL1A [4] [2]; + UINT64 GL1C [4] [8]; + UINT64 GL2A [4] [4]; + UINT64 GL2C [4] [8]; + UINT64 GRBM [1] [1]; + UINT64 GRBMSE0 [1] [1]; + UINT64 GRBMSE1 [1] [1]; + UINT64 IH [1] [1]; + UINT64 PH [8] [1]; + UINT64 RMI [4] [2]; + UINT64 SC [8] [4]; + UINT64 SDMA [1] [1]; + UINT64 SPI [4] [1]; + UINT64 SQ [16][1]; + UINT64 SU [4] [2]; + UINT64 SX [4] [2]; + UINT64 TA [5] [20]; + UINT64 TCP [8] [20]; + UINT64 TD [1] [20]; + UINT64 EA [1] [8]; + UINT64 ATCL2 [1] [1]; + UINT64 VML2 [2] [1]; +} D3D12XBOX_COUNTER_LOCKHART_DATA; + +#define D3D12XBOX_COUNTER_DATA_INVALID ( 0xffffffffffffffffU ) + +}; + +extern "C" +{ + +// +// Forward Declarations +// + +// 12.n + +struct ID3D12Object; +struct ID3D12DeviceChild; +struct ID3D12RootSignature; +struct ID3D12RootSignatureDeserializer; +struct ID3D12Pageable; +struct ID3D12Heap; +struct ID3D12Resource; +struct ID3D12CommandAllocator; +struct ID3D12Fence; +struct ID3D12PipelineState; +struct ID3D12DescriptorHeap; +struct ID3D12QueryHeap; +struct ID3D12CommandSignature; +struct ID3D12CommandList; +struct ID3D12GraphicsCommandList; +struct ID3D12CommandQueue; +struct ID3D12Device; +struct ID3D12Device1; +struct ID3D12Debug; +struct ID3D12Debug1; +struct ID3D12Debug2; +struct ID3D12Debug3; +struct ID3D12Debug4; +struct ID3D12Debug5; +struct ID3D12Debug6; +struct ID3D12DebugCommandList; +struct ID3D12DebugCommandList1; +struct ID3D12DebugCommandList2; +struct ID3D12DebugCommandQueue; +struct ID3D12DebugDevice; +struct ID3D12DebugDevice1; +struct ID3D12DebugDevice2; +struct ID3D12PipelineLibrary; +struct ID3D12VersionedRootSignatureDeserializer; +struct ID3D12Fence1; +struct ID3D12GraphicsCommandList1; +struct ID3D12GraphicsCommandList2; +struct ID3D12PipelineLibrary1; +struct ID3D12Device2; +struct ID3D12Device3; +struct ID3D12SharingContract; +struct ID3D12VirtualizationGuestDevice; +struct ID3D12Tools; + +struct ID3D12Device4; +struct ID3D12ShaderBytecode; +struct ID3D12DevicePartnerComposition; +struct ID3D12ProtectedSession; +struct ID3D12ProtectedResourceSession; +struct ID3D12LifetimeOwner; +struct ID3D12SwapChainAssistant; +struct ID3D12LifetimeTracker; +struct ID3D12StateObject; +struct ID3D12StateObjectProperties; +struct ID3D12Device5; +struct ID3D12Resource1; +struct ID3D12Resource2; +struct ID3D12Heap1; +struct ID3D12GraphicsCommandList3; +struct ID3D12MetaCommand; +struct ID3D12GraphicsCommandList4; +struct ID3D12CommandPool; +struct ID3D12CommandRecorder; +struct ID3D12BackingCommandAllocator; +struct ID3D12GraphicsCommandList5; +struct ID3D12Device6; +struct ID3D12Device7; +struct ID3D12Device8; +struct ID3D12Device9; +struct ID3D12Device10; +struct ID3D12Device11; +struct ID3D12GraphicsCommandList6; +struct ID3D12GraphicsCommandList7; +struct ID3D12GraphicsCommandList8; +struct ID3D12ShaderCacheSession; +struct ID3D12ProtectedResourceSession1; +struct ID3D12DeviceRemovedExtendedData; +struct ID3D12DeviceRemovedExtendedData1; +struct ID3D12DeviceRemovedExtendedData2; +struct ID3D12DeviceRemovedExtendedDataSettings; +struct ID3D12DeviceRemovedExtendedDataSettings1; + +// 12.X + +struct ID3D12XboxDmaCommandList; + + + +struct ID3D12XboxCounterSet; + +} + +extern "C" +{ +#ifndef _D3D12_CONSTANTS +#define _D3D12_CONSTANTS + +#define D3D12_16BIT_INDEX_STRIP_CUT_VALUE ( 0xffff ) + +#define D3D12_32BIT_INDEX_STRIP_CUT_VALUE ( 0xffffffff ) + +#define D3D12_8BIT_INDEX_STRIP_CUT_VALUE ( 0xff ) + +#define D3D12_APPEND_ALIGNED_ELEMENT ( 0xffffffff ) + +#define D3D12_ARRAY_AXIS_ADDRESS_RANGE_BIT_COUNT ( 9 ) + +#define D3D12_CLIP_OR_CULL_DISTANCE_COUNT ( 8 ) + +#define D3D12_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT ( 2 ) + +#define D3D12_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ( 14 ) + +#define D3D12_COMMONSHADER_CONSTANT_BUFFER_COMPONENTS ( 4 ) + +#define D3D12_COMMONSHADER_CONSTANT_BUFFER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_COMMONSHADER_CONSTANT_BUFFER_HW_SLOT_COUNT ( 15 ) + +#define D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT ( 16 ) + +#define D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COUNT ( 15 ) + +#define D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READS_PER_INST ( 1 ) + +#define D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_COMMONSHADER_FLOWCONTROL_NESTING_LIMIT ( 64 ) + +#define D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COUNT ( 1 ) + +#define D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READS_PER_INST ( 1 ) + +#define D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_COMMONSHADER_IMMEDIATE_VALUE_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT ( 128 ) + +#define D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_READS_PER_INST ( 1 ) + +#define D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ( 128 ) + +#define D3D12_COMMONSHADER_SAMPLER_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_COMMONSHADER_SAMPLER_REGISTER_COUNT ( 16 ) + +#define D3D12_COMMONSHADER_SAMPLER_REGISTER_READS_PER_INST ( 1 ) + +#define D3D12_COMMONSHADER_SAMPLER_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_COMMONSHADER_SAMPLER_SLOT_COUNT ( 16 ) + +#define D3D12_COMMONSHADER_SUBROUTINE_NESTING_LIMIT ( 32 ) + +#define D3D12_COMMONSHADER_TEMP_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_COMMONSHADER_TEMP_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_COMMONSHADER_TEMP_REGISTER_COUNT ( 4096 ) + +#define D3D12_COMMONSHADER_TEMP_REGISTER_READS_PER_INST ( 3 ) + +#define D3D12_COMMONSHADER_TEMP_REGISTER_READ_PORTS ( 3 ) + +#define D3D12_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MAX ( 10 ) + +#define D3D12_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MIN ( -10 ) + +#define D3D12_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE ( -8 ) + +#define D3D12_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE ( 7 ) + +#define D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT ( 16 ) + +#define D3D12_CS_4_X_BUCKET00_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 256 ) + +#define D3D12_CS_4_X_BUCKET00_MAX_NUM_THREADS_PER_GROUP ( 64 ) + +#define D3D12_CS_4_X_BUCKET01_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 240 ) + +#define D3D12_CS_4_X_BUCKET01_MAX_NUM_THREADS_PER_GROUP ( 68 ) + +#define D3D12_CS_4_X_BUCKET02_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 224 ) + +#define D3D12_CS_4_X_BUCKET02_MAX_NUM_THREADS_PER_GROUP ( 72 ) + +#define D3D12_CS_4_X_BUCKET03_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 208 ) + +#define D3D12_CS_4_X_BUCKET03_MAX_NUM_THREADS_PER_GROUP ( 76 ) + +#define D3D12_CS_4_X_BUCKET04_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 192 ) + +#define D3D12_CS_4_X_BUCKET04_MAX_NUM_THREADS_PER_GROUP ( 84 ) + +#define D3D12_CS_4_X_BUCKET05_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 176 ) + +#define D3D12_CS_4_X_BUCKET05_MAX_NUM_THREADS_PER_GROUP ( 92 ) + +#define D3D12_CS_4_X_BUCKET06_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 160 ) + +#define D3D12_CS_4_X_BUCKET06_MAX_NUM_THREADS_PER_GROUP ( 100 ) + +#define D3D12_CS_4_X_BUCKET07_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 144 ) + +#define D3D12_CS_4_X_BUCKET07_MAX_NUM_THREADS_PER_GROUP ( 112 ) + +#define D3D12_CS_4_X_BUCKET08_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 128 ) + +#define D3D12_CS_4_X_BUCKET08_MAX_NUM_THREADS_PER_GROUP ( 128 ) + +#define D3D12_CS_4_X_BUCKET09_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 112 ) + +#define D3D12_CS_4_X_BUCKET09_MAX_NUM_THREADS_PER_GROUP ( 144 ) + +#define D3D12_CS_4_X_BUCKET10_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 96 ) + +#define D3D12_CS_4_X_BUCKET10_MAX_NUM_THREADS_PER_GROUP ( 168 ) + +#define D3D12_CS_4_X_BUCKET11_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 80 ) + +#define D3D12_CS_4_X_BUCKET11_MAX_NUM_THREADS_PER_GROUP ( 204 ) + +#define D3D12_CS_4_X_BUCKET12_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 64 ) + +#define D3D12_CS_4_X_BUCKET12_MAX_NUM_THREADS_PER_GROUP ( 256 ) + +#define D3D12_CS_4_X_BUCKET13_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 48 ) + +#define D3D12_CS_4_X_BUCKET13_MAX_NUM_THREADS_PER_GROUP ( 340 ) + +#define D3D12_CS_4_X_BUCKET14_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 32 ) + +#define D3D12_CS_4_X_BUCKET14_MAX_NUM_THREADS_PER_GROUP ( 512 ) + +#define D3D12_CS_4_X_BUCKET15_MAX_BYTES_TGSM_WRITABLE_PER_THREAD ( 16 ) + +#define D3D12_CS_4_X_BUCKET15_MAX_NUM_THREADS_PER_GROUP ( 768 ) + +#define D3D12_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION ( 1 ) + +#define D3D12_CS_4_X_RAW_UAV_BYTE_ALIGNMENT ( 256 ) + +#define D3D12_CS_4_X_THREAD_GROUP_MAX_THREADS_PER_GROUP ( 768 ) + +#define D3D12_CS_4_X_THREAD_GROUP_MAX_X ( 768 ) + +#define D3D12_CS_4_X_THREAD_GROUP_MAX_Y ( 768 ) + +#define D3D12_CS_4_X_UAV_REGISTER_COUNT ( 1 ) + +#define D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION ( 65535 ) + +#define D3D12_CS_TGSM_REGISTER_COUNT ( 8192 ) + +#define D3D12_CS_TGSM_REGISTER_READS_PER_INST ( 1 ) + +#define D3D12_CS_TGSM_RESOURCE_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_CS_TGSM_RESOURCE_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_CS_THREADGROUPID_REGISTER_COMPONENTS ( 3 ) + +#define D3D12_CS_THREADGROUPID_REGISTER_COUNT ( 1 ) + +#define D3D12_CS_THREADIDINGROUPFLATTENED_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_CS_THREADIDINGROUPFLATTENED_REGISTER_COUNT ( 1 ) + +#define D3D12_CS_THREADIDINGROUP_REGISTER_COMPONENTS ( 3 ) + +#define D3D12_CS_THREADIDINGROUP_REGISTER_COUNT ( 1 ) + +#define D3D12_CS_THREADID_REGISTER_COMPONENTS ( 3 ) + +#define D3D12_CS_THREADID_REGISTER_COUNT ( 1 ) + +#define D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP ( 1024 ) + +#define D3D12_CS_THREAD_GROUP_MAX_X ( 1024 ) + +#define D3D12_CS_THREAD_GROUP_MAX_Y ( 1024 ) + +#define D3D12_CS_THREAD_GROUP_MAX_Z ( 64 ) + +#define D3D12_CS_THREAD_GROUP_MIN_X ( 1 ) + +#define D3D12_CS_THREAD_GROUP_MIN_Y ( 1 ) + +#define D3D12_CS_THREAD_GROUP_MIN_Z ( 1 ) + +#define D3D12_CS_THREAD_LOCAL_TEMP_REGISTER_POOL ( 16384 ) + +#define D3D12_DEFAULT_BLEND_FACTOR_ALPHA ( 1.0f ) +#define D3D12_DEFAULT_BLEND_FACTOR_BLUE ( 1.0f ) +#define D3D12_DEFAULT_BLEND_FACTOR_GREEN ( 1.0f ) +#define D3D12_DEFAULT_BLEND_FACTOR_RED ( 1.0f ) +#define D3D12_DEFAULT_BORDER_COLOR_COMPONENT ( 0.0f ) +#define D3D12_DEFAULT_DEPTH_BIAS ( 0 ) + +#define D3D12_DEFAULT_DEPTH_BIAS_CLAMP ( 0.0f ) +#define D3D12_DEFAULT_MAX_ANISOTROPY ( 16 ) + +#define D3D12_DEFAULT_MIP_LOD_BIAS ( 0.0f ) +#define D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT ( 4194304 ) + +#define D3D12_DEFAULT_RENDER_TARGET_ARRAY_INDEX ( 0 ) + +#define D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT ( 65536 ) + +#define D3D12_DEFAULT_SAMPLE_MASK ( 0xffffffff ) + +#define D3D12_DEFAULT_SCISSOR_ENDX ( 0 ) + +#define D3D12_DEFAULT_SCISSOR_ENDY ( 0 ) + +#define D3D12_DEFAULT_SCISSOR_STARTX ( 0 ) + +#define D3D12_DEFAULT_SCISSOR_STARTY ( 0 ) + +#define D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS ( 0.0f ) +#define D3D12_DEFAULT_STENCIL_READ_MASK ( 0xff ) + +#define D3D12_DEFAULT_STENCIL_REFERENCE ( 0 ) + +#define D3D12_DEFAULT_STENCIL_WRITE_MASK ( 0xff ) + +#define D3D12_DEFAULT_VIEWPORT_AND_SCISSORRECT_INDEX ( 0 ) + +#define D3D12_DEFAULT_VIEWPORT_HEIGHT ( 0 ) + +#define D3D12_DEFAULT_VIEWPORT_MAX_DEPTH ( 0.0f ) +#define D3D12_DEFAULT_VIEWPORT_MIN_DEPTH ( 0.0f ) +#define D3D12_DEFAULT_VIEWPORT_TOPLEFTX ( 0 ) + +#define D3D12_DEFAULT_VIEWPORT_TOPLEFTY ( 0 ) + +#define D3D12_DEFAULT_VIEWPORT_WIDTH ( 0 ) + +#define D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ( 0xffffffff ) + +#define D3D12_DRIVER_RESERVED_REGISTER_SPACE_VALUES_END ( 0xfffffff7 ) + +#define D3D12_DRIVER_RESERVED_REGISTER_SPACE_VALUES_START ( 0xfffffff0 ) + +#define D3D12_DS_INPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS ( 3968 ) + +#define D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COUNT ( 32 ) + +#define D3D12_DS_INPUT_CONTROL_POINT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_DS_INPUT_CONTROL_POINT_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENTS ( 3 ) + +#define D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COUNT ( 1 ) + +#define D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COUNT ( 32 ) + +#define D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COUNT ( 1 ) + +#define D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_DS_OUTPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_DS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_DS_OUTPUT_REGISTER_COUNT ( 32 ) + +#define D3D12_FLOAT16_FUSED_TOLERANCE_IN_ULP ( 0.6 ) +#define D3D12_FLOAT32_MAX ( 3.402823466e+38f ) +#define D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP ( 0.6f ) +#define D3D12_FLOAT_TO_SRGB_EXPONENT_DENOMINATOR ( 2.4f ) +#define D3D12_FLOAT_TO_SRGB_EXPONENT_NUMERATOR ( 1.0f ) +#define D3D12_FLOAT_TO_SRGB_OFFSET ( 0.055f ) +#define D3D12_FLOAT_TO_SRGB_SCALE_1 ( 12.92f ) +#define D3D12_FLOAT_TO_SRGB_SCALE_2 ( 1.055f ) +#define D3D12_FLOAT_TO_SRGB_THRESHOLD ( 0.0031308f ) +#define D3D12_FTOI_INSTRUCTION_MAX_INPUT ( 2147483647.999f ) +#define D3D12_FTOI_INSTRUCTION_MIN_INPUT ( -2147483648.999f ) +#define D3D12_FTOU_INSTRUCTION_MAX_INPUT ( 4294967295.999f ) +#define D3D12_FTOU_INSTRUCTION_MIN_INPUT ( 0.0f ) +#define D3D12_GS_INPUT_INSTANCE_ID_READS_PER_INST ( 2 ) + +#define D3D12_GS_INPUT_INSTANCE_ID_READ_PORTS ( 1 ) + +#define D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COUNT ( 1 ) + +#define D3D12_GS_INPUT_PRIM_CONST_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_GS_INPUT_PRIM_CONST_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_GS_INPUT_PRIM_CONST_REGISTER_COUNT ( 1 ) + +#define D3D12_GS_INPUT_PRIM_CONST_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_GS_INPUT_PRIM_CONST_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_GS_INPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_GS_INPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_GS_INPUT_REGISTER_COUNT ( 32 ) + +#define D3D12_GS_INPUT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_GS_INPUT_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_GS_INPUT_REGISTER_VERTICES ( 32 ) + +#define D3D12_GS_MAX_INSTANCE_COUNT ( 32 ) + +#define D3D12_GS_MAX_OUTPUT_VERTEX_COUNT_ACROSS_INSTANCES ( 1024 ) + +#define D3D12_GS_OUTPUT_ELEMENTS ( 32 ) + +#define D3D12_GS_OUTPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_GS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_GS_OUTPUT_REGISTER_COUNT ( 32 ) + +#define D3D12_HS_CONTROL_POINT_PHASE_INPUT_REGISTER_COUNT ( 32 ) + +#define D3D12_HS_CONTROL_POINT_PHASE_OUTPUT_REGISTER_COUNT ( 32 ) + +#define D3D12_HS_CONTROL_POINT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_HS_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_HS_CONTROL_POINT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_HS_CONTROL_POINT_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_HS_FORK_PHASE_INSTANCE_COUNT_UPPER_BOUND ( 0xffffffff ) + +#define D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COUNT ( 1 ) + +#define D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COUNT ( 1 ) + +#define D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COUNT ( 1 ) + +#define D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_HS_JOIN_PHASE_INSTANCE_COUNT_UPPER_BOUND ( 0xffffffff ) + +#define D3D12_HS_MAXTESSFACTOR_LOWER_BOUND ( 1.0f ) +#define D3D12_HS_MAXTESSFACTOR_UPPER_BOUND ( 64.0f ) +#define D3D12_HS_OUTPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS ( 3968 ) + +#define D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COUNT ( 1 ) + +#define D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COUNT ( 32 ) + +#define D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_SCALAR_COMPONENTS ( 128 ) + +#define D3D12_IA_DEFAULT_INDEX_BUFFER_OFFSET_IN_BYTES ( 0 ) + +#define D3D12_IA_DEFAULT_PRIMITIVE_TOPOLOGY ( 0 ) + +#define D3D12_IA_DEFAULT_VERTEX_BUFFER_OFFSET_IN_BYTES ( 0 ) + +#define D3D12_IA_INDEX_INPUT_RESOURCE_SLOT_COUNT ( 1 ) + +#define D3D12_IA_INSTANCE_ID_BIT_COUNT ( 32 ) + +#define D3D12_IA_INTEGER_ARITHMETIC_BIT_COUNT ( 32 ) + +#define D3D12_IA_PATCH_MAX_CONTROL_POINT_COUNT ( 32 ) + +#define D3D12_IA_PRIMITIVE_ID_BIT_COUNT ( 32 ) + +#define D3D12_IA_VERTEX_ID_BIT_COUNT ( 32 ) + +#define D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT ( 32 ) + +#define D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENTS_COMPONENTS ( 128 ) + +#define D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT ( 32 ) + +#define D3D12_INTEGER_DIVIDE_BY_ZERO_QUOTIENT ( 0xffffffff ) + +#define D3D12_INTEGER_DIVIDE_BY_ZERO_REMAINDER ( 0xffffffff ) + +#define D3D12_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL ( 0xffffffff ) + +#define D3D12_KEEP_UNORDERED_ACCESS_VIEWS ( 0xffffffff ) + +#define D3D12_LINEAR_GAMMA ( 1.0f ) +#define D3D12_MAJOR_VERSION ( 12 ) + +#define D3D12_MAX_BORDER_COLOR_COMPONENT ( 1.0f ) +#define D3D12_MAX_DEPTH ( 1.0f ) +#define D3D12_MAX_LIVE_STATIC_SAMPLERS ( 2032 ) + +#define D3D12_MAX_MAXANISOTROPY ( 16 ) + +#define D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT ( 32 ) + +#define D3D12_MAX_POSITION_VALUE ( 3.402823466e+34f ) +#define D3D12_MAX_ROOT_COST ( 64 ) + +#define D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_1 ( 1000000 ) + +#define D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2 ( 1000000 ) + +#define D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE ( 2048 ) + +#define D3D12_MAX_TEXTURE_DIMENSION_2_TO_EXP ( 17 ) + +#define D3D12_MAX_VIEW_INSTANCE_COUNT ( 4 ) + +#define D3D12_MINOR_VERSION ( 0 ) + +#define D3D12_MIN_BORDER_COLOR_COMPONENT ( 0.0f ) +#define D3D12_MIN_DEPTH ( 0.0f ) +#define D3D12_MIN_MAXANISOTROPY ( 0 ) + +#define D3D12_MIP_LOD_BIAS_MAX ( 15.99f ) +#define D3D12_MIP_LOD_BIAS_MIN ( -16.0f ) +#define D3D12_MIP_LOD_FRACTIONAL_BIT_COUNT ( 8 ) + +#define D3D12_MIP_LOD_RANGE_BIT_COUNT ( 8 ) + +#define D3D12_MULTISAMPLE_ANTIALIAS_LINE_WIDTH ( 1.4f ) +#define D3D12_NONSAMPLE_FETCH_OUT_OF_RANGE_ACCESS_RESULT ( 0 ) + +#define D3D12_OS_RESERVED_REGISTER_SPACE_VALUES_END ( 0xffffffff ) + +#define D3D12_OS_RESERVED_REGISTER_SPACE_VALUES_START ( 0xfffffff8 ) + +#define D3D12_PACKED_TILE ( 0xffffffff ) + +#define D3D12_PIXEL_ADDRESS_RANGE_BIT_COUNT ( 15 ) + +#define D3D12_PRE_SCISSOR_PIXEL_ADDRESS_RANGE_BIT_COUNT ( 16 ) + +#define D3D12_PS_CS_UAV_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_PS_CS_UAV_REGISTER_COUNT ( 8 ) + +#define D3D12_PS_CS_UAV_REGISTER_READS_PER_INST ( 1 ) + +#define D3D12_PS_CS_UAV_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_PS_FRONTFACING_DEFAULT_VALUE ( 0xffffffff ) + +#define D3D12_PS_FRONTFACING_FALSE_VALUE ( 0 ) + +#define D3D12_PS_FRONTFACING_TRUE_VALUE ( 0xffffffff ) + +#define D3D12_PS_INPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_PS_INPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_PS_INPUT_REGISTER_COUNT ( 32 ) + +#define D3D12_PS_INPUT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_PS_INPUT_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_PS_LEGACY_PIXEL_CENTER_FRACTIONAL_COMPONENT ( 0.0f ) +#define D3D12_PS_OUTPUT_DEPTH_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_PS_OUTPUT_DEPTH_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_PS_OUTPUT_DEPTH_REGISTER_COUNT ( 1 ) + +#define D3D12_PS_OUTPUT_MASK_REGISTER_COMPONENTS ( 1 ) + +#define D3D12_PS_OUTPUT_MASK_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_PS_OUTPUT_MASK_REGISTER_COUNT ( 1 ) + +#define D3D12_PS_OUTPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_PS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_PS_OUTPUT_REGISTER_COUNT ( 8 ) + +#define D3D12_PS_PIXEL_CENTER_FRACTIONAL_COMPONENT ( 0.5f ) +#define D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT ( 16 ) + +#define D3D12_RAYTRACING_AABB_BYTE_ALIGNMENT ( 8 ) + +#define D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT ( 256 ) + +#define D3D12_RAYTRACING_INSTANCE_DESCS_BYTE_ALIGNMENT ( 16 ) + +#define D3D12_RAYTRACING_MAX_ATTRIBUTE_SIZE_IN_BYTES ( 32 ) + +#define D3D12_RAYTRACING_MAX_DECLARABLE_TRACE_RECURSION_DEPTH ( 31 ) + +#define D3D12_RAYTRACING_MAX_GEOMETRIES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE ( 16777216 ) + +#define D3D12_RAYTRACING_MAX_INSTANCES_PER_TOP_LEVEL_ACCELERATION_STRUCTURE ( 16777216 ) + +#define D3D12_RAYTRACING_MAX_PRIMITIVES_PER_BOTTOM_LEVEL_ACCELERATION_STRUCTURE ( 536870912 ) + +#define D3D12_RAYTRACING_MAX_RAY_GENERATION_SHADER_THREADS ( 1073741824 ) + +#define D3D12_RAYTRACING_MAX_SHADER_RECORD_STRIDE ( 4096 ) + +#define D3D12_RAYTRACING_SHADER_RECORD_BYTE_ALIGNMENT ( 32 ) + +#define D3D12_RAYTRACING_SHADER_TABLE_BYTE_ALIGNMENT ( 64 ) + +#define D3D12_RAYTRACING_TRANSFORM3X4_BYTE_ALIGNMENT ( 16 ) + +#define D3D12XBOX_RAYTRACING_UNUSED_PRIMITIVE_INDEX (0xFFFFFFFF) + +#define D3D12_REQ_BLEND_OBJECT_COUNT_PER_DEVICE ( 4096 ) + +#define D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP ( 27 ) + +#define D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT ( 4096 ) + +#define D3D12_REQ_DEPTH_STENCIL_OBJECT_COUNT_PER_DEVICE ( 4096 ) + +#define D3D12_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP ( 32 ) + +#define D3D12_REQ_DRAW_VERTEX_COUNT_2_TO_EXP ( 32 ) + +#define D3D12_REQ_FILTERING_HW_ADDRESSABLE_RESOURCE_DIMENSION ( 16384 ) + +#define D3D12_REQ_GS_INVOCATION_32BIT_OUTPUT_COMPONENT_LIMIT ( 1024 ) + +#define D3D12_REQ_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT ( 4096 ) + +#define D3D12_REQ_MAXANISOTROPY ( 16 ) + +#define D3D12_REQ_MIP_LEVELS ( 15 ) + +#define D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES ( 2048 ) + +#define D3D12_REQ_RASTERIZER_OBJECT_COUNT_PER_DEVICE ( 4096 ) + +#define D3D12_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH ( 16384 ) + +#define D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM ( 128 ) + +#define D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_B_TERM ( 0.25f ) +#define D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_C_TERM ( 2048 ) + +#define D3D12_REQ_RESOURCE_VIEW_COUNT_PER_DEVICE_2_TO_EXP ( 20 ) + +#define D3D12_REQ_SAMPLER_OBJECT_COUNT_PER_DEVICE ( 4096 ) + +#define D3D12_REQ_SUBRESOURCES ( 30720 ) + +#define D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION ( 2048 ) +#define D3D12XBOX_REQ_TEXTURE1D_NON_RT_ARRAY_AXIS_DIMENSION ( 8192 ) + +#define D3D12_REQ_TEXTURE1D_U_DIMENSION ( 16384 ) + +#define D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION ( 2048 ) +#define D3D12XBOX_REQ_TEXTURE2D_NON_RT_ARRAY_AXIS_DIMENSION ( 8192 ) + +#define D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION ( 16384 ) + +#define D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION ( 2048 ) + +#define D3D12_REQ_TEXTURECUBE_DIMENSION ( 16384 ) + +#define D3D12_RESINFO_INSTRUCTION_MISSING_COMPONENT_RETVAL ( 0 ) + +#define D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES ( 0xffffffff ) + +#define D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES ( 32 ) + +#define D3D12_SHADER_MAJOR_VERSION ( 5 ) + +#define D3D12_SHADER_MAX_INSTANCES ( 65535 ) + +#define D3D12_SHADER_MAX_INTERFACES ( 253 ) + +#define D3D12_SHADER_MAX_INTERFACE_CALL_SITES ( 4096 ) + +#define D3D12_SHADER_MAX_TYPES ( 65535 ) + +#define D3D12_SHADER_MINOR_VERSION ( 1 ) + +#define D3D12_SHIFT_INSTRUCTION_PAD_VALUE ( 0 ) + +#define D3D12_SHIFT_INSTRUCTION_SHIFT_VALUE_BIT_COUNT ( 5 ) + +#define D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT ( 8 ) + +#define D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT ( 65536 ) + +#define D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT ( 4096 ) + +#define D3D12_SO_BUFFER_MAX_STRIDE_IN_BYTES ( 2048 ) + +#define D3D12_SO_BUFFER_MAX_WRITE_WINDOW_IN_BYTES ( 512 ) + +#define D3D12_SO_BUFFER_SLOT_COUNT ( 4 ) + +#define D3D12_SO_DDI_REGISTER_INDEX_DENOTING_GAP ( 0xffffffff ) + +#define D3D12_SO_NO_RASTERIZED_STREAM ( 0xffffffff ) + +#define D3D12_SO_OUTPUT_COMPONENT_COUNT ( 128 ) + +#define D3D12_SO_STREAM_COUNT ( 4 ) + +#define D3D12_SPEC_DATE_DAY ( 14 ) + +#define D3D12_SPEC_DATE_MONTH ( 11 ) + +#define D3D12_SPEC_DATE_YEAR ( 2014 ) + +#define D3D12_SPEC_VERSION ( 1.16 ) +#define D3D12_SRGB_GAMMA ( 2.2f ) +#define D3D12_SRGB_TO_FLOAT_DENOMINATOR_1 ( 12.92f ) +#define D3D12_SRGB_TO_FLOAT_DENOMINATOR_2 ( 1.055f ) +#define D3D12_SRGB_TO_FLOAT_EXPONENT ( 2.4f ) +#define D3D12_SRGB_TO_FLOAT_OFFSET ( 0.055f ) +#define D3D12_SRGB_TO_FLOAT_THRESHOLD ( 0.04045f ) +#define D3D12_SRGB_TO_FLOAT_TOLERANCE_IN_ULP ( 0.5f ) +#define D3D12_STANDARD_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_STANDARD_COMPONENT_BIT_COUNT_DOUBLED ( 64 ) + +#define D3D12_STANDARD_MAXIMUM_ELEMENT_ALIGNMENT_BYTE_MULTIPLE ( 4 ) + +#define D3D12_STANDARD_PIXEL_COMPONENT_COUNT ( 128 ) + +#define D3D12_STANDARD_PIXEL_ELEMENT_COUNT ( 32 ) + +#define D3D12_STANDARD_VECTOR_SIZE ( 4 ) + +#define D3D12_STANDARD_VERTEX_ELEMENT_COUNT ( 32 ) + +#define D3D12_STANDARD_VERTEX_TOTAL_COMPONENT_COUNT ( 64 ) + +#define D3D12_SUBPIXEL_FRACTIONAL_BIT_COUNT ( 8 ) + +#define D3D12_SUBTEXEL_FRACTIONAL_BIT_COUNT ( 8 ) + +#define D3D12_SYSTEM_RESERVED_REGISTER_SPACE_VALUES_END ( 0xffffffff ) + +#define D3D12_SYSTEM_RESERVED_REGISTER_SPACE_VALUES_START ( 0xfffffff0 ) + +#define D3D12_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR ( 64 ) + +#define D3D12_TESSELLATOR_MAX_ISOLINE_DENSITY_TESSELLATION_FACTOR ( 64 ) + +#define D3D12_TESSELLATOR_MAX_ODD_TESSELLATION_FACTOR ( 63 ) + +#define D3D12_TESSELLATOR_MAX_TESSELLATION_FACTOR ( 64 ) + +#define D3D12_TESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR ( 2 ) + +#define D3D12_TESSELLATOR_MIN_ISOLINE_DENSITY_TESSELLATION_FACTOR ( 1 ) + +#define D3D12_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR ( 1 ) + +#define D3D12_TEXEL_ADDRESS_RANGE_BIT_COUNT ( 16 ) + +#define D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT ( 256 ) + +#define D3D12_TEXTURE_DATA_PITCH_ALIGNMENT ( 256 ) + +#define D3D12XBOX_ROOT_PARAMETER_MAX_INDEX ( 127 ) + +#define D3D12XBOX_GPU_INSTRUCTIONS_ALIGNMENT ( 256 ) + +#define D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT ( 256 ) + +#define D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES ( 65536 ) + +#define D3D12_TRACKED_WORKLOAD_MAX_INSTANCES ( 32 ) + +#define D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT ( 4096 ) + +#define D3D12_UAV_SLOT_COUNT ( 64 ) + +#define D3D12_UNBOUND_MEMORY_ACCESS_RESULT ( 0 ) + +#define D3D12_VIEWPORT_AND_SCISSORRECT_MAX_INDEX ( 15 ) + +#define D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE ( 16 ) + +#define D3D12_VIEWPORT_BOUNDS_MAX ( 32767 ) + +#define D3D12_VIEWPORT_BOUNDS_MIN ( -32768 ) + +#define D3D12_VS_INPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_VS_INPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_VS_INPUT_REGISTER_COUNT ( 32 ) + +#define D3D12_VS_INPUT_REGISTER_READS_PER_INST ( 2 ) + +#define D3D12_VS_INPUT_REGISTER_READ_PORTS ( 1 ) + +#define D3D12_VS_OUTPUT_REGISTER_COMPONENTS ( 4 ) + +#define D3D12_VS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT ( 32 ) + +#define D3D12_VS_OUTPUT_REGISTER_COUNT ( 32 ) + +#define D3D12_WHQL_CONTEXT_COUNT_FOR_RESOURCE_LIMIT ( 10 ) + +#define D3D12_WHQL_DRAWINDEXED_INDEX_COUNT_2_TO_EXP ( 25 ) + +#define D3D12_WHQL_DRAW_VERTEX_COUNT_2_TO_EXP ( 25 ) + +#endif + +#define D3D12XBOX_NODE_MASK (1) + +typedef UINT64 D3D12_GPU_VIRTUAL_ADDRESS; +#define D3D12_GPU_VIRTUAL_ADDRESS_NULL ((D3D12_GPU_VIRTUAL_ADDRESS)0) +#define D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN ((D3D12_GPU_VIRTUAL_ADDRESS)-1) + +typedef enum D3D12_COMMAND_LIST_TYPE +{ + D3D12_COMMAND_LIST_TYPE_DIRECT = 0, + D3D12_COMMAND_LIST_TYPE_BUNDLE = 1, + D3D12_COMMAND_LIST_TYPE_COMPUTE = 2, + D3D12_COMMAND_LIST_TYPE_COPY = 3, + D3D12_COMMAND_LIST_TYPE_VIDEO_DECODE = 4, + D3D12_COMMAND_LIST_TYPE_VIDEO_PROCESS = 5, + D3D12XBOX_COMMAND_LIST_TYPE_DMA = 16 +} D3D12_COMMAND_LIST_TYPE; + +typedef enum D3D12XBOX_COMMAND_LIST_FLAGS +{ + D3D12XBOX_COMMAND_LIST_FLAG_NONE = 0, + D3D12XBOX_COMMAND_LIST_FLAG_DISABLE_AUTOMATIC_KICKOFFS = 0x2, + D3D12XBOX_COMMAND_LIST_FLAG_ENABLE_IB_CHAINING = 0x4 +} D3D12XBOX_COMMAND_LIST_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_COMMAND_LIST_FLAGS ); + +typedef struct D3D12XBOX_COMMAND_LIST_DESC +{ + D3D12_COMMAND_LIST_TYPE Type; + D3D12XBOX_COMMAND_LIST_FLAGS Flags; + UINT NodeMask; + UINT ResourceBarrierBatchSize; +} D3D12XBOX_COMMAND_LIST_DESC; + +// D3D12XBOX_COMMAND_QUEUE_PRIORITY defines the compute queue priority relative to other queues in the same pipe. +typedef enum D3D12XBOX_COMMAND_QUEUE_PRIORITY +{ + D3D12XBOX_COMMAND_QUEUE_PRIORITY_LOWEST = 0x8, + D3D12XBOX_COMMAND_QUEUE_PRIORITY_LOWER = 0xa, + D3D12XBOX_COMMAND_QUEUE_PRIORITY_LOW = 0xd, + D3D12XBOX_COMMAND_QUEUE_PRIORITY_MEDIUM = 0x0, + D3D12XBOX_COMMAND_QUEUE_PRIORITY_HIGH = 0x3, + D3D12XBOX_COMMAND_QUEUE_PRIORITY_HIGHER = 0x5, + D3D12XBOX_COMMAND_QUEUE_PRIORITY_HIGHEST = 0x7, + D3D12XBOX_COMMAND_QUEUE_PRIORITY_DEFAULT = D3D12XBOX_COMMAND_QUEUE_PRIORITY_MEDIUM, +} D3D12XBOX_COMMAND_QUEUE_PRIORITY; + +typedef enum D3D12_COMMAND_QUEUE_FLAGS +{ + D3D12_COMMAND_QUEUE_FLAG_NONE = 0, + D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT = 0x1, + + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_MASK = 0x0f000000, + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_SHIFT = 24, + + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_LOWEST = D3D12XBOX_COMMAND_QUEUE_PRIORITY_LOWEST << D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_SHIFT, + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_LOWER = D3D12XBOX_COMMAND_QUEUE_PRIORITY_LOWER << D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_SHIFT, + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_LOW = D3D12XBOX_COMMAND_QUEUE_PRIORITY_LOW << D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_SHIFT, + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_MEDIUM = D3D12XBOX_COMMAND_QUEUE_PRIORITY_MEDIUM << D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_SHIFT, + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_HIGH = D3D12XBOX_COMMAND_QUEUE_PRIORITY_HIGH << D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_SHIFT, + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_HIGHER = D3D12XBOX_COMMAND_QUEUE_PRIORITY_HIGHER << D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_SHIFT, + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_HIGHEST = D3D12XBOX_COMMAND_QUEUE_PRIORITY_HIGHEST << D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_SHIFT, + D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_DEFAULT = D3D12XBOX_COMMAND_QUEUE_PRIORITY_DEFAULT << D3D12XBOX_COMMAND_QUEUE_FLAG_PRIORITY_SHIFT, +} D3D12_COMMAND_QUEUE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_COMMAND_QUEUE_FLAGS ); + +typedef enum D3D12_COMMAND_QUEUE_PRIORITY +{ + D3D12_COMMAND_QUEUE_PRIORITY_NORMAL = 0, + D3D12_COMMAND_QUEUE_PRIORITY_HIGH = 100, + D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME = 10000 +} D3D12_COMMAND_QUEUE_PRIORITY; + +typedef struct D3D12_COMMAND_QUEUE_DESC +{ + D3D12_COMMAND_LIST_TYPE Type; + INT Priority; + D3D12_COMMAND_QUEUE_FLAGS Flags; + UINT NodeMask; +} D3D12_COMMAND_QUEUE_DESC; + +typedef struct D3D12XBOX_COMMAND_QUEUE_DESC +{ + D3D12_COMMAND_LIST_TYPE Type; + D3D12_COMMAND_QUEUE_FLAGS Flags; + UINT EngineOrPipeIndex; + UINT QueueIndex; +} D3D12XBOX_COMMAND_QUEUE_DESC; + +typedef enum D3D12_PRIMITIVE_TOPOLOGY_TYPE +{ + D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED = 0, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT = 1, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE = 2, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE = 3, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH = 4, + D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT = 19, + D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_QUAD = 32, +} D3D12_PRIMITIVE_TOPOLOGY_TYPE; + +typedef UINT (*D3D12XBOX_HANGBEGINCALLBACK) ( UINT64 Flags ); +typedef void (*D3D12XBOX_HANGPRINTCALLBACK) ( const CHAR* strLine ); +typedef void (*D3D12XBOX_HANGDUMPCALLBACK) ( const WCHAR* strFileName ); + +typedef enum D3D12XBOX_REPORT_GPU_HANG_FLAGS +{ + D3D12XBOX_REPORT_GPU_HANG_FLAG_NONE = 0x0, + D3D12XBOX_REPORT_GPU_HANG_FLAG_DO_NOT_REBOOT = 0x1, +} D3D12XBOX_REPORT_GPU_HANG_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_REPORT_GPU_HANG_FLAGS ); + +typedef enum D3D12XBOX_REPORT_GPU_HALT_FLAGS +{ + D3D12XBOX_REPORT_GPU_HALT_FLAG_ALL = 0x0, + D3D12XBOX_REPORT_GPU_HALT_FLAG_NO_TERMINATION = 0x1, + D3D12XBOX_REPORT_GPU_HALT_FLAG_NO_LIVE_DEBUG = 0x2, + D3D12XBOX_REPORT_GPU_HALT_FLAG_NO_DUMP = 0x4, + D3D12XBOX_REPORT_GPU_HALT_FLAG_NO_BREAK = 0x8, +} D3D12XBOX_REPORT_GPU_HALT_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_REPORT_GPU_HALT_FLAGS); + +typedef enum D3D12XBOX_LIVE_DEBUGGING_TYPE +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_STAGE_ANY = 0, + D3D12XBOX_LIVE_DEBUGGING_SHADER_STAGE_COMPUTE = 1, + D3D12XBOX_LIVE_DEBUGGING_SHADER_STAGE_VERTEX = 2, + D3D12XBOX_LIVE_DEBUGGING_SHADER_STAGE_PIXEL = 3, + D3D12XBOX_LIVE_DEBUGGING_SHADER_STAGE_GEOMETRY = 4, + D3D12XBOX_LIVE_DEBUGGING_SHADER_STAGE_HULL = 5, + D3D12XBOX_LIVE_DEBUGGING_SHADER_STAGE_DOMAIN = 6, + D3D12XBOX_LIVE_DEBUGGING_SHADER_STAGE_AMPLIFICATION = 7, + D3D12XBOX_LIVE_DEBUGGING_SHADER_STAGE_MESH = 8, + D3D12XBOX_LIVE_DEBUGGING_NONE = 0xFFFFFFFF, +} D3D12XBOX_LIVE_DEBUGGING_TYPE; + +typedef enum D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS_NONE = 0x00, + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS_ANY = 0x01, +} D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_ANY_SHADER_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS Flags; +} D3D12XBOX_LIVE_DEBUGGING_ANY_SHADER_PARAMETERS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_COMPUTE_SHADER_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS Flags; + UINT ThreadID_X; + UINT ThreadID_Y; + UINT ThreadID_Z; +} D3D12XBOX_LIVE_DEBUGGING_COMPUTE_SHADER_PARAMETERS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_VERTEX_SHADER_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS Flags; + UINT VertexID; + UINT InstanceID; +} D3D12XBOX_LIVE_DEBUGGING_VERTEX_SHADER_PARAMETERS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_PIXEL_SHADER_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS Flags; + UINT X; + UINT Y; +} D3D12XBOX_LIVE_DEBUGGING_PIXEL_SHADER_PARAMETERS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_GEOMETRY_SHADER_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS Flags; + UINT PrimitiveID; + UINT InstanceID; +} D3D12XBOX_LIVE_DEBUGGING_GEOMETRY_SHADER_PARAMETERS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_HULL_SHADER_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS Flags; + UINT PrimitiveID; + UINT ControlPointID; +} D3D12XBOX_LIVE_DEBUGGING_HULL_SHADER_PARAMETERS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_DOMAIN_SHADER_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS Flags; + UINT PrimitiveID; +} D3D12XBOX_LIVE_DEBUGGING_DOMAIN_SHADER_PARAMETERS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_AMPLIFICATION_SHADER_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS Flags; + UINT ThreadID_X; + UINT ThreadID_Y; + UINT ThreadID_Z; +} D3D12XBOX_LIVE_DEBUGGING_AMPLIFICATION_SHADER_PARAMETERS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_MESH_SHADER_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_FLAGS Flags; + UINT ThreadID_X; + UINT ThreadID_Y; + UINT ThreadID_Z; +} D3D12XBOX_LIVE_DEBUGGING_MESH_SHADER_PARAMETERS; + +typedef struct D3D12XBOX_LIVE_DEBUGGING_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_TYPE Type; + union + { + D3D12XBOX_LIVE_DEBUGGING_ANY_SHADER_PARAMETERS ANY; + D3D12XBOX_LIVE_DEBUGGING_COMPUTE_SHADER_PARAMETERS CS; + D3D12XBOX_LIVE_DEBUGGING_PIXEL_SHADER_PARAMETERS PS; + D3D12XBOX_LIVE_DEBUGGING_VERTEX_SHADER_PARAMETERS VS; + D3D12XBOX_LIVE_DEBUGGING_GEOMETRY_SHADER_PARAMETERS GS; + D3D12XBOX_LIVE_DEBUGGING_HULL_SHADER_PARAMETERS HS; + D3D12XBOX_LIVE_DEBUGGING_DOMAIN_SHADER_PARAMETERS DS; + D3D12XBOX_LIVE_DEBUGGING_AMPLIFICATION_SHADER_PARAMETERS AS; + D3D12XBOX_LIVE_DEBUGGING_MESH_SHADER_PARAMETERS MS; + }; +} D3D12XBOX_LIVE_DEBUGGING_PARAMETERS; + +typedef enum D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS +{ + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_NAN = 0x02, + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_FLOAT_DIVIDE_BY_ZERO = 0x04, + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_INTEGER_DIVIDE_BY_ZERO = 0x08, + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_OVERFLOW = 0x10, + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_UNDERFLOW = 0x20, + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_MEMORY_EXCEPTION = 0x40, + + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_NUMERIC_EXCEPTIONS = + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_NAN | + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_FLOAT_DIVIDE_BY_ZERO | + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_INTEGER_DIVIDE_BY_ZERO | + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_OVERFLOW | + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_UNDERFLOW, + + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_ALL_EXCEPTIONS = + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_NAN | + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_FLOAT_DIVIDE_BY_ZERO | + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_INTEGER_DIVIDE_BY_ZERO | + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_OVERFLOW | + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_UNDERFLOW | + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS_MEMORY_EXCEPTION, + +} D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS); + +typedef struct D3D12XBOX_LIVE_DEBUGGING_GLOBAL_PARAMETERS +{ + D3D12XBOX_LIVE_DEBUGGING_TYPE Type; + D3D12XBOX_LIVE_DEBUGGING_SHADER_GLOBAL_FLAGS Flags; +} D3D12XBOX_LIVE_DEBUGGING_GLOBAL_PARAMETERS; +} + +extern "C" +{ + +typedef enum D3D12_INPUT_CLASSIFICATION +{ + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA = 0, + D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA = 1 +} D3D12_INPUT_CLASSIFICATION; + +typedef struct D3D12_INPUT_ELEMENT_DESC +{ + LPCSTR SemanticName; + UINT SemanticIndex; + DXGI_FORMAT Format; + UINT InputSlot; + UINT AlignedByteOffset; + D3D12_INPUT_CLASSIFICATION InputSlotClass; + UINT InstanceDataStepRate; +} D3D12_INPUT_ELEMENT_DESC; + +typedef enum D3D12_FILL_MODE +{ + D3D12_FILL_MODE_WIREFRAME = 2, + D3D12_FILL_MODE_SOLID = 3 +} D3D12_FILL_MODE; + +typedef D3D_PRIMITIVE_TOPOLOGY D3D12_PRIMITIVE_TOPOLOGY; + +typedef D3D_PRIMITIVE D3D12_PRIMITIVE; + +typedef enum D3D12_CULL_MODE +{ + D3D12_CULL_MODE_NONE = 1, + D3D12_CULL_MODE_FRONT = 2, + D3D12_CULL_MODE_BACK = 3 +} D3D12_CULL_MODE; + +typedef struct D3D12_SO_DECLARATION_ENTRY +{ + UINT Stream; + LPCSTR SemanticName; + UINT SemanticIndex; + BYTE StartComponent; + BYTE ComponentCount; + BYTE OutputSlot; +} D3D12_SO_DECLARATION_ENTRY; + +typedef struct D3D12_VIEWPORT +{ + FLOAT TopLeftX; + FLOAT TopLeftY; + FLOAT Width; + FLOAT Height; + FLOAT MinDepth; + FLOAT MaxDepth; +} D3D12_VIEWPORT; + +} + + +extern "C" +{ +typedef RECT D3D12_RECT; +} + +extern "C" +{ + +typedef struct D3D12_BOX +{ + UINT left; + UINT top; + UINT front; + UINT right; + UINT bottom; + UINT back; +} D3D12_BOX; + +} + +extern "C" +{ + +typedef enum D3D12_COMPARISON_FUNC +{ + D3D12_COMPARISON_FUNC_NEVER = 1, + D3D12_COMPARISON_FUNC_LESS = 2, + D3D12_COMPARISON_FUNC_EQUAL = 3, + D3D12_COMPARISON_FUNC_LESS_EQUAL = 4, + D3D12_COMPARISON_FUNC_GREATER = 5, + D3D12_COMPARISON_FUNC_NOT_EQUAL = 6, + D3D12_COMPARISON_FUNC_GREATER_EQUAL = 7, + D3D12_COMPARISON_FUNC_ALWAYS = 8 +} D3D12_COMPARISON_FUNC; + +typedef enum D3D12_DEPTH_WRITE_MASK +{ + D3D12_DEPTH_WRITE_MASK_ZERO = 0, + D3D12_DEPTH_WRITE_MASK_ALL = 1 +} D3D12_DEPTH_WRITE_MASK; + +typedef enum D3D12_STENCIL_OP +{ + D3D12_STENCIL_OP_KEEP = 1, + D3D12_STENCIL_OP_ZERO = 2, + D3D12_STENCIL_OP_REPLACE = 3, + D3D12_STENCIL_OP_INCR_SAT = 4, + D3D12_STENCIL_OP_DECR_SAT = 5, + D3D12_STENCIL_OP_INVERT = 6, + D3D12_STENCIL_OP_INCR = 7, + D3D12_STENCIL_OP_DECR = 8, + + D3D12XBOX_STENCIL_OP_ONE = 9, + D3D12XBOX_STENCIL_OP_REPLACE_OP = 10, + D3D12XBOX_STENCIL_OP_AND = 11, + D3D12XBOX_STENCIL_OP_OR = 12, + D3D12XBOX_STENCIL_OP_XOR = 13, + D3D12XBOX_STENCIL_OP_NAND = 14, + D3D12XBOX_STENCIL_OP_NOR = 15, + D3D12XBOX_STENCIL_OP_XNOR = 16, +} D3D12_STENCIL_OP; + +typedef struct D3D12_DEPTH_STENCILOP_DESC +{ + D3D12_STENCIL_OP StencilFailOp; + D3D12_STENCIL_OP StencilDepthFailOp; + D3D12_STENCIL_OP StencilPassOp; + D3D12_COMPARISON_FUNC StencilFunc; +} D3D12_DEPTH_STENCILOP_DESC; + +typedef struct D3D12_DEPTH_STENCIL_DESC +{ + BOOL DepthEnable; + D3D12_DEPTH_WRITE_MASK DepthWriteMask; + D3D12_COMPARISON_FUNC DepthFunc; + BOOL StencilEnable; + UINT8 StencilReadMask; + UINT8 StencilWriteMask; + D3D12_DEPTH_STENCILOP_DESC FrontFace; + D3D12_DEPTH_STENCILOP_DESC BackFace; +} D3D12_DEPTH_STENCIL_DESC; + +typedef struct D3D12_DEPTH_STENCIL_DESC1 +{ + BOOL DepthEnable; + D3D12_DEPTH_WRITE_MASK DepthWriteMask; + D3D12_COMPARISON_FUNC DepthFunc; + BOOL StencilEnable; + UINT8 StencilReadMask; + UINT8 StencilWriteMask; + D3D12_DEPTH_STENCILOP_DESC FrontFace; + D3D12_DEPTH_STENCILOP_DESC BackFace; + BOOL DepthBoundsTestEnable; +} D3D12_DEPTH_STENCIL_DESC1; + +typedef struct D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC +{ + BOOL BackFaceDisable; + BOOL DepthBoundsDisable; + BOOL ColorWritesOnDepthFailEnable; + BOOL ColorWritesOnDepthPassDisable; + UINT8 StencilReadMaskBack; + UINT8 StencilWriteMaskBack; + UINT8 StencilTestRefValueFront; + UINT8 StencilTestRefValueBack; + UINT8 StencilOpRefValueFront; + UINT8 StencilOpRefValueBack; +} D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC; + +} + +extern "C" +{ + +typedef enum D3D12_BLEND +{ + D3D12_BLEND_ZERO = 1, + D3D12_BLEND_ONE = 2, + D3D12_BLEND_SRC_COLOR = 3, + D3D12_BLEND_INV_SRC_COLOR = 4, + D3D12_BLEND_SRC_ALPHA = 5, + D3D12_BLEND_INV_SRC_ALPHA = 6, + D3D12_BLEND_DEST_ALPHA = 7, + D3D12_BLEND_INV_DEST_ALPHA = 8, + D3D12_BLEND_DEST_COLOR = 9, + D3D12_BLEND_INV_DEST_COLOR = 10, + D3D12_BLEND_SRC_ALPHA_SAT = 11, + D3D12_BLEND_BLEND_FACTOR = 14, + D3D12_BLEND_INV_BLEND_FACTOR = 15, + D3D12_BLEND_SRC1_COLOR = 16, + D3D12_BLEND_INV_SRC1_COLOR = 17, + D3D12_BLEND_SRC1_ALPHA = 18, + D3D12_BLEND_INV_SRC1_ALPHA = 19 +} D3D12_BLEND; + +typedef enum D3D12_BLEND_OP +{ + D3D12_BLEND_OP_ADD = 1, + D3D12_BLEND_OP_SUBTRACT = 2, + D3D12_BLEND_OP_REV_SUBTRACT = 3, + D3D12_BLEND_OP_MIN = 4, + D3D12_BLEND_OP_MAX = 5 +} D3D12_BLEND_OP; + +typedef enum D3D12_COLOR_WRITE_ENABLE +{ + D3D12_COLOR_WRITE_ENABLE_RED = 1, + D3D12_COLOR_WRITE_ENABLE_GREEN = 2, + D3D12_COLOR_WRITE_ENABLE_BLUE = 4, + D3D12_COLOR_WRITE_ENABLE_ALPHA = 8, + D3D12_COLOR_WRITE_ENABLE_ALL = ( ( ( D3D12_COLOR_WRITE_ENABLE_RED | D3D12_COLOR_WRITE_ENABLE_GREEN ) | D3D12_COLOR_WRITE_ENABLE_BLUE ) | D3D12_COLOR_WRITE_ENABLE_ALPHA ) +} D3D12_COLOR_WRITE_ENABLE; + +typedef enum D3D12_LOGIC_OP +{ + // Operation: + // (s == PS output, d = RTV contents) + D3D12_LOGIC_OP_CLEAR = 0, // 0 + D3D12_LOGIC_OP_SET, // 1 + D3D12_LOGIC_OP_COPY, // s + D3D12_LOGIC_OP_COPY_INVERTED, // ~s + D3D12_LOGIC_OP_NOOP, // d + D3D12_LOGIC_OP_INVERT, // ~d + D3D12_LOGIC_OP_AND, // s & d + D3D12_LOGIC_OP_NAND, // ~(s & d) + D3D12_LOGIC_OP_OR, // s | d + D3D12_LOGIC_OP_NOR, // ~(s | d) + D3D12_LOGIC_OP_XOR, // s ^ d + D3D12_LOGIC_OP_EQUIV, // ~(s ^ d) + D3D12_LOGIC_OP_AND_REVERSE, // s & ~d + D3D12_LOGIC_OP_AND_INVERTED, // ~s & d + D3D12_LOGIC_OP_OR_REVERSE, // s | ~d + D3D12_LOGIC_OP_OR_INVERTED, // ~s | d +} D3D12_LOGIC_OP; + +typedef struct D3D12_RENDER_TARGET_BLEND_DESC +{ + BOOL BlendEnable; + BOOL LogicOpEnable; // LogicOpEnable and BlendEnable can't both be true + D3D12_BLEND SrcBlend; + D3D12_BLEND DestBlend; + D3D12_BLEND_OP BlendOp; + D3D12_BLEND SrcBlendAlpha; + D3D12_BLEND DestBlendAlpha; + D3D12_BLEND_OP BlendOpAlpha; + D3D12_LOGIC_OP LogicOp; // applies to RGBA + UINT8 RenderTargetWriteMask; // D3D12_COLOR_WRITE_ENABLE +} D3D12_RENDER_TARGET_BLEND_DESC; + +typedef struct D3D12_BLEND_DESC +{ + BOOL AlphaToCoverageEnable; // relevant to multisample antialiasing only + BOOL IndependentBlendEnable; // if FALSE, then replicate the first entry in RenderTarget array to other entries + D3D12_RENDER_TARGET_BLEND_DESC RenderTarget[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; +} D3D12_BLEND_DESC; + +} + +/* Note, the array size for RenderTarget[] above is D3D12_SIMULTANEOUS_RENDERTARGET_COUNT. + IDL processing/generation of this header replaces the define; this comment is merely explaining what happened. */ + +extern "C" +{ + +typedef enum D3D12_CONSERVATIVE_RASTERIZATION_MODE +{ + D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF = 0, + D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON = 1, +} D3D12_CONSERVATIVE_RASTERIZATION_MODE; + +typedef struct D3D12_RASTERIZER_DESC +{ + D3D12_FILL_MODE FillMode; + D3D12_CULL_MODE CullMode; + BOOL FrontCounterClockwise; + INT DepthBias; + FLOAT DepthBiasClamp; + FLOAT SlopeScaledDepthBias; + BOOL DepthClipEnable; + BOOL MultisampleEnable; + BOOL AntialiasedLineEnable; + UINT ForcedSampleCount; + D3D12_CONSERVATIVE_RASTERIZATION_MODE ConservativeRaster; +} D3D12_RASTERIZER_DESC; + +} + +#define D3D12XBOX_OFFCHIP_TESSELLATION_BUFFER_SIZE ( 126 * 32 * 1024 ) +#define D3D12XBOX_TESSELLATION_FACTORS_BUFFER_SIZE ( 32 * 1024 ) + +#define D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_OWORDS 1 +#define D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_QWORDS 2 +#define D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_DWORDS 4 +#define D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_BYTES 16 +#define D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_OWORDS 2 +#define D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_QWORDS 4 +#define D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_DWORDS 8 +#define D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_BYTES 32 +#define D3D12XBOX_DESCRIPTOR_SHADER_RESOURCE_VIEW_SIZE_IN_OWORDS D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_OWORDS +#define D3D12XBOX_DESCRIPTOR_SHADER_RESOURCE_VIEW_SIZE_IN_QWORDS D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_QWORDS +#define D3D12XBOX_DESCRIPTOR_SHADER_RESOURCE_VIEW_SIZE_IN_DWORDS D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_DWORDS +#define D3D12XBOX_DESCRIPTOR_SHADER_RESOURCE_VIEW_SIZE_IN_BYTES D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_BYTES +#define D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_OWORDS 2 +#define D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_QWORDS 4 +#define D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_DWORDS 8 +#define D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_BYTES 32 +#define D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_SIZE_IN_OWORDS D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_OWORDS +#define D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_SIZE_IN_QWORDS D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_QWORDS +#define D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_SIZE_IN_DWORDS D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_DWORDS +#define D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_SIZE_IN_BYTES D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_BYTES +#define D3D12XBOX_DESCRIPTOR_VERTEX_BUFFER_VIEW_SIZE_IN_OWORDS D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_OWORDS +#define D3D12XBOX_DESCRIPTOR_VERTEX_BUFFER_VIEW_SIZE_IN_QWORDS D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_QWORDS +#define D3D12XBOX_DESCRIPTOR_VERTEX_BUFFER_VIEW_SIZE_IN_DWORDS D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_DWORDS +#define D3D12XBOX_DESCRIPTOR_VERTEX_BUFFER_VIEW_SIZE_IN_BYTES D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_BYTES +#define D3D12XBOX_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_OWORDS 1 +#define D3D12XBOX_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_QWORDS 2 +#define D3D12XBOX_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_DWORDS 4 +#define D3D12XBOX_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_BYTES 16 +#define D3D12XBOX_DESCRIPTOR_RENDER_TARGET_VIEW_SIZE_IN_BYTES 112 +#define D3D12XBOX_DESCRIPTOR_RENDER_TARGET_VIEW_SIZE_IN_OWORDS 7 +#define D3D12XBOX_DESCRIPTOR_DEPTH_STENCIL_VIEW_SIZE_IN_BYTES 128 +#define D3D12XBOX_DESCRIPTOR_DEPTH_STENCIL_VIEW_SIZE_IN_OWORDS 8 + +extern "C" +{ + +typedef enum D3D12XBOX_GDS_OPERATION +{ + D3D12XBOX_GDS_OPERATION_DEFAULT = 0, // Reads are D3D11X_GDS_OPERATION_READ_PIPELINED_AT_EOS and writes are always at top of pipe with a copy (DX11 SetUAV style), insert synchronization as needed + D3D12XBOX_GDS_OPERATION_READ_AT_EOS = 1, // Read GDS contents at end of shader, pipelined with rendering, but fences or WaitUntilIdle may be needed to ensure the read reached memory + D3D12XBOX_GDS_OPERATION_READ_AT_TOP = 2, // Read GDS at the top of pipe + D3D12XBOX_GDS_OPERATION_WRITE_COPY_DATA_TO_CB = 3, // Write GDS at the top of pipe, but first copy the counter data to CB + D3D12XBOX_GDS_OPERATION_WRITE_USE_DATA_BY_POINTER = 4, // Write GDS at the top of pipe, but the pointer is used, so its lifetime and hazards must be tracked by the title + D3D12XBOX_GDS_OPERATION_COMPUTE = 8, // For EOS operations, specify whether it EOS compute or EOS graphics +} D3D12XBOX_GDS_OPERATION; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_GDS_OPERATION); + +typedef enum D3D12XBOX_ORDERED_APPEND_SHADER_STAGE +{ + D3D12XBOX_ORDERED_APPEND_SHADER_STAGE_VS = 0, + D3D12XBOX_ORDERED_APPEND_SHADER_STAGE_PS = 1, + D3D12XBOX_ORDERED_APPEND_SHADER_STAGE_CS = 2 +} D3D12XBOX_ORDERED_APPEND_SHADER_STAGE; + +typedef enum D3D12XBOX_DISPATCH_FLAGS : UINT +{ + D3D12XBOX_DISPATCH_FLAG_NONE = 0x00000000, + D3D12XBOX_DISPATCH_FLAG_FORCE_START_AT_000 = 0x00000004, // If 1, override each of COMPUTE_START_X/Y/Z to 0 + D3D12XBOX_DISPATCH_FLAG_ENABLE_ORDERED_APPEND = 0x00000008, // If 1, support ordered append + D3D12XBOX_DISPATCH_FLAG_ORDERED_APPEND_WAVEID_PER_THREADGROUP = 0x00000010, // 0: Unique wave-id per wave. 1: Unique wave-id per Threadgroup + D3D12XBOX_DISPATCH_FLAG_USE_THREAD_DIMENSIONS = 0x00000020, // If 1, Interpret ThreadGroupCount* parameters as total thread counts to dispatch in each dimension. + D3D12XBOX_DISPATCH_FLAG_ENABLE_OUT_OF_ORDER = 0x00000040, // 0: All CS waves in the SPI need to be launched in order. 1: CS Waves can be launched out of order in the SPI. + D3D12XBOX_DISPATCH_FLAG_DISABLE_VOLATILE_VECTOR_L1 = 0x00000080, // Enable or disable vector L1 + D3D12XBOX_DISPATCH_FLAG_DISABLE_VOLATILE_SCALAR_L1 = 0x00000200, // Enable or disable scalar L1 + D3D12XBOX_DISPATCH_FLAG_INVALIDATE_VOLATILE_SCALAR_L1 = 0x00000400, // Invalidate all volatile tagged lines from scalar L1 + D3D12XBOX_DISPATCH_FLAG_INVALIDATE_VOLATILE_VECTOR_L1 = 0x00000800, // Invalidate all volatile tagged lines from vector L1 + D3D12XBOX_DISPATCH_FLAG_W32 = 0x00008000, // Wave32 +} D3D12XBOX_DISPATCH_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_DISPATCH_FLAGS); + + +typedef enum D3D12_STANDARD_MULTISAMPLE_QUALITY_LEVELS +{ + D3D12_STANDARD_MULTISAMPLE_PATTERN = 0xffffffff, + D3D12_CENTER_MULTISAMPLE_PATTERN = 0xfffffffe +} D3D12_STANDARD_MULTISAMPLE_QUALITY_LEVELS; + +// Sample positions stored as one byte per component, X then Y +// There are up to 16 possible sample positions per pixel +// They can be set independently for each pixel in a 2x2 quad +typedef struct D3D12XBOX_MSAA_SAMPLE_LOCATIONS +{ + INT8 TopLeft[16][2]; + INT8 TopRight[16][2]; + INT8 BottomLeft[16][2]; + INT8 BottomRight[16][2]; +} D3D12XBOX_MSAA_SAMPLE_LOCATIONS; + +typedef struct D3D12XBOX_MSAA_CENTROID_PRIORITIES +{ + UINT8 Values[16]; +} D3D12XBOX_MSAA_CENTROID_PRIORITIES; + +typedef struct D3D12XBOX_MSAA_PARAMETERS +{ + union + { + struct + { + UINT NumSamplesMsaaLog2 : 3; + UINT MaxSampleDistanceInSubpixels : 4; + UINT NumSamplesMsaaExposedToPSLog2 : 3; + UINT DetailToExposedMode : 2; + UINT ApplyMaskAfterCentroid : 1; + }; + UINT Dword0; + }; + + union + { + struct + { + UINT MaxAnchorSamplesLog2 : 3; + UINT NumSamplesForPSIterationLog2 : 3; + UINT NumSamplesForMaskExportLog2 : 3; + UINT NumSamplesForAlphaToMaskLog2 : 3; + UINT Reserved2 : 1; + UINT Reserved0 : 1; + UINT InterpolateCompZ : 1; + UINT InterpolateSrcZ : 1; + UINT StaticAnchorAssociations : 1; + UINT Reserved1 : 1; + UINT OverrasterizationAmount : 3; + UINT EnablePostZOverrasterization : 1; + }; + UINT Dword1; + }; +} D3D12XBOX_MSAA_PARAMETERS; + + +typedef struct D3D12XBOX_QUERY_PREDICATION_STATUS +{ + D3D12_GPU_VIRTUAL_ADDRESS BufferLocation; + UINT Offset; + UINT State; +} D3D12XBOX_QUERY_PREDICATION_STATUS; + +} + +// Maximum index that can be passed into SetupOrderedAppendCounterX is 7 +#define D3D12XBOX_ORDERED_APPEND_NUM_INDICES 8 + +// GDS size allocated for ERA +#define D3D12XBOX_GDS_SIZE_DWORDS 16128 + +// Maximum gds offset that can be passed into gdsAddressOfTheCounterDwords +#define D3D12XBOX_ORDERED_APPEND_GDS_OFFSET_MAX_VALUE_DWORDS D3D12XBOX_GDS_SIZE_DWORDS + +typedef enum D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETER_FLAGS : UINT +{ + D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETER_FLAG_BULKY = 0x000000001, + D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETER_FLAG_BULKY_ENABLE = 0x000000002, + D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETER_FLAG_LDS_SIZE = 0x000000004, + D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETER_FLAG_NUM_THREADS = 0x000000008, + D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETER_FLAG_WGP_MODE = 0x000000020, + D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETER_FLAG_WGP_MODE_ENABLE = 0x000000040, +} D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETER_FLAGS; + +typedef struct D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETERS +{ + union + { + struct + { + UINT Flags : 7; + UINT LDSSize : 9; + UINT NumThreadZ : 16; + }; + UINT Dword0; + }; + union + { + struct + { + UINT NumThreadX : 16; + UINT NumThreadY : 16; + }; + UINT Dword1; + }; +} D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETERS; + +extern "C" +{ + +static const UINT64 D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_NATIVE_FORMAT = 0x0002403C00000000ull; +static const UINT64 D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_NATIVE_STRIDE = 0x0010000000000000ull; + +typedef struct D3D12XBOX_DESCRIPTOR_BUFFER_VIEW +{ + union + { + __m128i Oword; + UINT64 Qword[D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_QWORDS]; + UINT32 Dword[D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_DWORDS]; + }; + + static const UINT32 DescriptorSize = D3D12XBOX_DESCRIPTOR_BUFFER_VIEW_SIZE_IN_BYTES; + +} D3D12XBOX_DESCRIPTOR_BUFFER_VIEW; + +typedef struct D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW +{ + union + { + __m128i Oword[D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_OWORDS]; + UINT64 Qword[D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_QWORDS]; + UINT32 Dword[D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_DWORDS]; + }; + + static const UINT32 DescriptorSize = D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW_SIZE_IN_BYTES; + +} D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW; + +typedef D3D12XBOX_DESCRIPTOR_TEXTURE_VIEW D3D12XBOX_DESCRIPTOR_SHADER_RESOURCE_VIEW; + +typedef struct D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW +{ + union + { + __m128i Oword[D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_OWORDS]; + UINT64 Qword[D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_QWORDS]; + UINT32 Dword[D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_DWORDS]; + }; + + static const UINT32 DescriptorSize = D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW_SIZE_IN_BYTES; + +} D3D12XBOX_DESCRIPTOR_UNORDERED_ACCESS_VIEW; + +typedef D3D12XBOX_DESCRIPTOR_BUFFER_VIEW D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW; + +typedef D3D12XBOX_DESCRIPTOR_BUFFER_VIEW D3D12XBOX_DESCRIPTOR_VERTEX_BUFFER_VIEW; + +typedef struct D3D12XBOX_DESCRIPTOR_SAMPLER_STATE +{ + union + { + __m128i Oword; + UINT64 Qword[D3D12XBOX_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_QWORDS]; + UINT32 Dword[D3D12XBOX_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_DWORDS]; + }; + + static const UINT32 DescriptorSize = D3D12XBOX_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_BYTES; + +} D3D12XBOX_DESCRIPTOR_SAMPLER_STATE; + +// This is the Command Processor packet/descriptor for setting a Pipeline State object. Always +// query this via GetDescriptorX at run-time from the Pipeline State object created by D3D +// as it cannot be pre-created offline. +// +// The ContextHash field, in conjunction with ExecuteIndirect, allows for the potential to run +// a GPU sort and thereby perfectly minimize context rolls. ContextHash is relevant only for +// Graphics Pipeline State objects, not Compute. +typedef struct D3D12XBOX_DESCRIPTOR_PIPELINE_STATE +{ + union + { + struct + { + UINT32 Data[7]; + }; + struct + { + UINT32 Header; + UINT32 ContextHash; + UINT32 Data2; + UINT32 Data3; + UINT32 Data4; + UINT32 Data5; + UINT32 Data6; // Graphics doesn't use this, only Compute does + }; + }; +} D3D12XBOX_DESCRIPTOR_PIPELINE_STATE; + +} + +#define D3D12_XBOX_FLUSH_GPU_CACHE_RANGE_ALL 0xFFFFFFFFFF00ull + +extern "C" +{ + +// +// D3D Memory Routines +// + +enum D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION_FLAGS +{ + D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION_FLAG_NONE = 0, + + // Graphics lower virtual address bound is 1GB instead of 2GB: + D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION_FLAG_ENABLE_LEGACY_LOWER_BOUND = 0x0001, + +}; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION_FLAGS ); + +#define D3D12XBOX_PAGE_TABLE_MEMORY_4MB_PAGE_COUNT_DEFAULT 0 + +struct D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION +{ + // Input parameters: + D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION_FLAGS Flags; + + // Size of the GPU page table memory allocation, in units of 4MB. + // Value must be at least 1 and will be clamped to no larger than 33. + // Specify D3D12XBOX_PAGE_TABLE_MEMORY_4MB_PAGE_COUNT_DEFAULT for the default value (5 4MB pages). + UINT PageTableMemory4MBPageCount; + + // Size of the cross-process frame buffer preserve allocation, in bytes. + // This memory is allocated out of the title's memory partition at the time of the first title process launch. + // Subsequent title processes cannot change the size of the allocation or deallocate the allocation. + // Specify 0 for no memory (default) or -1 for the legacy default value (approx. 10 MB). Value will be clamped to no larger than 64 MB. + UINT FrameBufferPreserveMemorySizeBytes; + + // Output parameters: + D3D12_GPU_VIRTUAL_ADDRESS MinimumValidGraphicsAddress; + D3D12_GPU_VIRTUAL_ADDRESS MaximumValidGraphicsAddress; +}; + +/////////////////////////////////////////////////////////////////////////// +// D3D12ConfigureVirtualMemoryX +// ----------------- +// This function configures the graphics virtual memory system. +// You must call this API before allocating any graphics memory or creating +// a Direct3D device. +// +// pVMConfiguration +// Input and output parameters for virtual memory configuration. +// +// Return values +// S_OK if the virtual memory system was configured with the given configuration. +// E_FAIL if the virtual memory system was not configured successfully (i.e. +// one or more graphics allocations were created before calling this API). +// E_INVALIDARG if pVMConfiguration is NULL. +// +// Note that even if D3D12ConfigureVirtualMemoryX returns E_FAIL, the output +// parameters of pVMConfiguration will be written. +// +/////////////////////////////////////////////////////////////////////////// +HRESULT WINAPI D3D12ConfigureVirtualMemoryX( + _Inout_ D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION* pVMConfiguration ); + +} +enum D3D12XBOX_ZERO_MEMORY_FLAGS +{ + D3D12XBOX_ZERO_MEMORY_FLAG_NONE = 0, + D3D12XBOX_ZERO_MEMORY_FLAG_CPU_MEMSET_ONLY = 1, +}; + +struct D3D12XBOX_ZERO_MEMORY_RANGE +{ + void* pBaseAddress; + SIZE_T SizeBytes; +}; + +struct D3D12XBOX_ZERO_MEMORY_BUFFERS +{ + // ExecutableMemoryBuffer must point to at least 64 KB of XALLOC_MEMTYPE_GRAPHICS_COMMAND_BUFFER_WRITECOMBINE memory. + D3D12_GPU_VIRTUAL_ADDRESS ExecutableMemoryBuffer; + UINT ExecutableMemoryBufferSizeBytes; + + // UncachedMemoryBuffer must point to at least 256 bytes of XALLOC_MEMTYPE_GRAPHICS_GPU_UNCACHED memory. + D3D12_GPU_VIRTUAL_ADDRESS UncachedMemoryBuffer; + UINT UncachedMemoryBufferSizeBytes; +}; + +HRESULT D3D12ZeroMemoryX( + _In_ UINT RangeCount, + _In_reads_(RangeCount) const D3D12XBOX_ZERO_MEMORY_RANGE* pRanges, + _In_opt_ const D3D12XBOX_ZERO_MEMORY_BUFFERS* pTitleProvidedMemory, + _In_ D3D12XBOX_ZERO_MEMORY_FLAGS Flags +); + +extern "C" +{ + +typedef enum D3D12XBOX_DRIVER_HINT +{ + D3D12XBOX_DRIVER_HINT_VRAM_SPILL_ENABLE = 1, + D3D12XBOX_DRIVER_HINT_MEMORY_STATISTICS_ENABLE = 2, + D3D12XBOX_DRIVER_HINT_STALL_STATISTICS_ENABLE = 3, + D3D12XBOX_DRIVER_HINT_SYSMON_STATISTICS_ENABLE = 4, + D3D12XBOX_DRIVER_HINT_CONSTANT_BUFFER_OFFSETS_IN_CONSTANTS = 6, + D3D12XBOX_DRIVER_HINT_CPU_SINGLE_STEPPER_ENABLE = 9, + D3D12XBOX_DRIVER_HINT_GPU_SINGLE_STEPPER_ENABLE = 10, + D3D12XBOX_DRIVER_HINT_7_CONTEXT_ENABLE = 11, + D3D12XBOX_DRIVER_HINT_OPTIMIZE_GPU_BLOCK_MEMORY_PRIORITIES = 12, + D3D12XBOX_DRIVER_HINT_DEBUG_BREAK_ON_SHADER_COMPILATION = 13, + D3D12XBOX_DRIVER_HINT_REDUCE_KICKOFF_CONTEXT_ROLLS = 14, + D3D12XBOX_DRIVER_HINT_LEGACY_TILE_MODE_SELECTIONS = 15, + D3D12XBOX_DRIVER_HINT_ENABLE_D3D12_DMA_CMDQUEUE_FENCE_VALIDATION = 21, + D3D12XBOX_DRIVER_HINT_CORRUPT_CMD_BUF = 22, + D3D12XBOX_DRIVER_HINT_DEBUG_DUMP_RESOURCE_DATABASE = 23, // Only works on Instrumented and Validated drivers + D3D12XBOX_DRIVER_HINT_SET_DCC_CLEAR_CACHE_HASH = 24, + D3D12XBOX_DRIVER_HINT_CLEAR_CAPTURE_ACCELERATION_STRUCTURES = 26, + D3D12XBOX_DRIVER_HINT_MINIMAL_INSTRUMENTATION_TIMING_CAPTURE = 27, // No timestamps for high frequency calls in timing captures (low overhead) + D3D12XBOX_DRIVER_HINT_NO_TIMING_CAPTURE_STATE_CHANGE_FROM_ECL = 28, // Disable changing timing capture state from ExecuteCommandLists + + D3D12XBOX_DRIVER_HINT_CONTEXT_BUGFIX_ENABLE = 279, // Bugfix for rendering context utilization on Scarlett. Only needed for 2106 and 2110 GDKs + D3D12XBOX_DRIVER_HINT_ENABLE_ATC_FIX = 281, // Only needed for GDK releases before 2210 + D3D12XBOX_DRIVER_HINT_SET_ATC_BANK_SELECT = 282, // specify ATC Bank Select for performance tuning. Valid values are between 0 (4KB) and 18 (1GB). + + + XBOX_DRIVER_HINT_VRAM_SPILL_ENABLE = D3D12XBOX_DRIVER_HINT_VRAM_SPILL_ENABLE, + XBOX_DRIVER_HINT_MEMORY_STATISTICS_ENABLE = D3D12XBOX_DRIVER_HINT_MEMORY_STATISTICS_ENABLE, + XBOX_DRIVER_HINT_STALL_STATISTICS_ENABLE = D3D12XBOX_DRIVER_HINT_STALL_STATISTICS_ENABLE, + XBOX_DRIVER_HINT_SYSMON_STATISTICS_ENABLE = D3D12XBOX_DRIVER_HINT_SYSMON_STATISTICS_ENABLE, + XBOX_DRIVER_HINT_CONSTANT_BUFFER_OFFSETS_IN_CONSTANTS = D3D12XBOX_DRIVER_HINT_CONSTANT_BUFFER_OFFSETS_IN_CONSTANTS, + XBOX_DRIVER_HINT_CPU_SINGLE_STEPPER_ENABLE = D3D12XBOX_DRIVER_HINT_CPU_SINGLE_STEPPER_ENABLE, + XBOX_DRIVER_HINT_GPU_SINGLE_STEPPER_ENABLE = D3D12XBOX_DRIVER_HINT_GPU_SINGLE_STEPPER_ENABLE, + XBOX_DRIVER_HINT_7_CONTEXT_ENABLE = D3D12XBOX_DRIVER_HINT_7_CONTEXT_ENABLE, + XBOX_DRIVER_HINT_OPTIMIZE_GPU_BLOCK_MEMORY_PRIORITIES = D3D12XBOX_DRIVER_HINT_OPTIMIZE_GPU_BLOCK_MEMORY_PRIORITIES, + XBOX_DRIVER_HINT_DEBUG_BREAK_ON_SHADER_COMPILATION = D3D12XBOX_DRIVER_HINT_DEBUG_BREAK_ON_SHADER_COMPILATION, + XBOX_DRIVER_HINT_REDUCE_KICKOFF_CONTEXT_ROLLS = D3D12XBOX_DRIVER_HINT_REDUCE_KICKOFF_CONTEXT_ROLLS, + XBOX_DRIVER_HINT_LEGACY_TILE_MODE_SELECTIONS = D3D12XBOX_DRIVER_HINT_LEGACY_TILE_MODE_SELECTIONS, + XBOX_DRIVER_HINT_ENABLE_D3D12_DMA_CMDQUEUE_FENCE_VALIDATION = D3D12XBOX_DRIVER_HINT_ENABLE_D3D12_DMA_CMDQUEUE_FENCE_VALIDATION, + XBOX_DRIVER_HINT_CORRUPT_CMD_BUF = D3D12XBOX_DRIVER_HINT_CORRUPT_CMD_BUF, + XBOX_DRIVER_HINT_CONTEXT_BUGFIX_ENABLE = D3D12XBOX_DRIVER_HINT_CONTEXT_BUGFIX_ENABLE, + XBOX_DRIVER_HINT_SET_DYNAMIC_POWER = 0xEFF1C1E7, +} D3D12XBOX_DRIVER_HINT; + + +typedef D3D12XBOX_DRIVER_HINT XBOX_DRIVER_HINT; + + +enum D3D12XBOX_CMDLIST_DRIVER_HINT +{ + D3D12XBOX_CMDLIST_DRIVER_HINT_BEGIN_ALTERNATIVE_COMPUTE_PSO_RENDERING, + D3D12XBOX_CMDLIST_DRIVER_HINT_END_ALTERNATIVE_COMPUTE_PSO_RENDERING, + D3D12XBOX_CMDLIST_DRIVER_HINT_DONT_SYNC_ON_CLEAR, + D3D12XBOX_CMDLIST_DRIVER_HINT_DONT_SYNC_ON_COPY, + D3D12XBOX_CMDLIST_DRIVER_HINT_DONT_SYNC_ON_CLEAR_OR_COPY, + D3D12XBOX_CMDLIST_DRIVER_HINT_FORCE_HIGH_PRECISION_GUARDBAND, + +}; + +struct D3D12XBOX_PRT_LOD_REPORT_DESC +{ + UINT DestinationSizeBytes; + D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress; + + union + { + struct + { + UINT : 2; + UINT ReportingInterval : 8; + UINT ResetCount : 8; + UINT ForceReset : 1; + UINT ReportAndReset : 1; + UINT : 12; + }; + + UINT Parameters; + }; +}; + +struct D3D12XBOX_PRT_LOD_REPORT_GPU_HEADER +{ + union + { + struct + { + UINT64 : 5; + UINT64 SampleOffset : 27; + UINT64 NumSamplesWithoutReset : 8; + UINT64 : 23; + UINT64 Reset : 1; + }; + + UINT64 Value; + }; +}; + +struct D3D12XBOX_PRT_LOD_REPORT_GPU_SAMPLE +{ + union + { + struct + { + UINT64 ClampedCount : 24; + UINT64 CounterID : 8; + UINT64 MinLODCount : 24; + UINT64 MinLOD : 4; + UINT64 Zero : 4; + }; + + UINT64 Value; + }; +}; + +} + + +extern "C" +{ + +// +// ID3D12Object +// + +struct D3D12Object_Function_Table +{ + GraphicsUnknown_Function_Table UnknownFunction; + + HRESULT (D3DAPI* GetPrivateData)( + _Inout_ ID3D12Object* pObject, + _In_ REFGUID guid, + _Inout_ UINT* pDataSize, + _Out_writes_bytes_opt_(*pDataSize) void* pData); + + HRESULT (D3DAPI* SetPrivateData)( + _Inout_ ID3D12Object* pObject, + _In_ REFGUID guid, + _In_ UINT DataSize, + _In_reads_bytes_opt_(DataSize) const void* pData); + + HRESULT (D3DAPI* SetPrivateDataInterface)( + _Inout_ ID3D12Object* pObject, + _In_ REFGUID guid, + _In_opt_ const IUnknown* pData); + + HRESULT (D3DAPI* SetName)( + _Inout_ ID3D12Object* pObject, + _In_z_ LPCWSTR pName); +}; + + +} + +DEFINE_D3DGUID(WKPDID_D3DDebugObjectNameW, 0x4cca5fd8, 0x921f, 0x42c8, 0x85, 0x66, 0x70, 0xca, 0xf2, 0xa9, 0xb7, 0x41); +DEFINE_GUID(WKPDID_D3DAutoDebugObjectNameW, 0xd4902e36, 0x757a, 0x4942, 0x95, 0x94, 0xb6, 0x76, 0x9a, 0xfa, 0x43, 0xcd); +DEFINE_GUID(WKPDID_D3DDebugObjectName, 0x429b8c22, 0x9188, 0x4b0c, 0x87, 0x42, 0xac, 0xb0, 0xbf, 0x85, 0xc2, 0x00); +#define D3D_SET_OBJECT_NAME_N_A(pObject, Chars, pName) (pObject)->SetPrivateData(WKPDID_D3DDebugObjectName, Chars, pName) +#define D3D_SET_OBJECT_NAME_A(pObject, pName) D3D_SET_OBJECT_NAME_N_A(pObject, lstrlenA(pName), pName) +#define D3D_SET_OBJECT_NAME_N_W(pObject, Chars, pName) (pObject)->SetPrivateData(WKPDID_D3DDebugObjectNameW, Chars*2, pName) +#define D3D_SET_OBJECT_NAME_W(pObject, pName) D3D_SET_OBJECT_NAME_N_W(pObject, wcslen(pName), pName) + +D3DINTERFACE(ID3D12Object, c4fec28f,7966,4e95,9f,94,f4,31,cb,56,c3,b8) : public IGraphicsUnknown +{ +public: + + D3DINLINE D3D12Object_Function_Table* ObjectFunction() + { + return (D3D12Object_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetPrivateData( + _In_ REFGUID guid, + _Inout_ UINT* pDataSize, + _Out_writes_bytes_opt_(*pDataSize) void* pData) + { + return ObjectFunction()->GetPrivateData(this, guid, pDataSize, pData); + } + + D3DINLINE HRESULT D3DAPI SetPrivateData( + _In_ REFGUID guid, + _In_ UINT DataSize, + _In_reads_bytes_opt_(DataSize) const void* pData) + { + return ObjectFunction()->SetPrivateData(this, guid, DataSize, pData); + } + + D3DINLINE HRESULT D3DAPI SetPrivateDataInterface( + _In_ REFGUID guid, + _In_opt_ const IUnknown* pData) + { + return ObjectFunction()->SetPrivateDataInterface(this, guid, pData); + } + + D3DINLINE HRESULT D3DAPI SetName( + _In_z_ LPCWSTR pName) + { + return ObjectFunction()->SetName(this, pName); + } + + D3DINLINE HRESULT D3DAPI GetNameX( + _Out_writes_opt_(*pNameLength) LPWSTR pName, + _Inout_opt_ UINT* pNameLength) + { + UINT SizeBytes = 0; + if (pNameLength != nullptr) + { + SizeBytes = *pNameLength * 2; + } + HRESULT hr = ObjectFunction()->GetPrivateData(this, WKPDID_D3DDebugObjectNameW, &SizeBytes, pName); + if (pNameLength != nullptr) + { + *pNameLength = SizeBytes >> 1; + } + return hr; + } +}; + + +extern "C" +{ + +// +// ID3D12DeviceChild +// + +struct D3D12DeviceChild_Function_Table +{ + D3D12Object_Function_Table ObjectFunction; + + void (D3DAPI* GetDevice)( + _Inout_ ID3D12DeviceChild* pDeviceChild, + _In_ REFIID riid, + _Out_ void** ppDevice); +}; + + +} + +D3DINTERFACE(ID3D12DeviceChild, 905db94b,a00c,4140,9d,f5,2b,64,ca,9e,a3,57) : public ID3D12Object +{ +public: + + D3DINLINE D3D12DeviceChild_Function_Table* DeviceChildFunction() + { + return (D3D12DeviceChild_Function_Table*)m_pFunction; + } + + D3DINLINE void D3DAPI GetDevice( + REFIID riid, + _Out_ void** ppDevice) + { + DeviceChildFunction()->GetDevice(this, riid, ppDevice); + } +}; + +// +// ID3D12ShaderCacheSession +// + +extern "C" +{ + +typedef enum D3D12_SHADER_CACHE_MODE +{ + D3D12_SHADER_CACHE_MODE_MEMORY = 0, + D3D12_SHADER_CACHE_MODE_DISK = ( D3D12_SHADER_CACHE_MODE_MEMORY + 1 ) +} D3D12_SHADER_CACHE_MODE; + +typedef enum D3D12_SHADER_CACHE_FLAGS +{ + D3D12_SHADER_CACHE_FLAG_NONE = 0, + D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED = 0x1, + D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR = 0x2 +} D3D12_SHADER_CACHE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_SHADER_CACHE_FLAGS ); + +typedef struct D3D12_SHADER_CACHE_SESSION_DESC +{ + GUID Identifier; + D3D12_SHADER_CACHE_MODE Mode; + D3D12_SHADER_CACHE_FLAGS Flags; + UINT MaximumInMemoryCacheSizeBytes; + UINT MaximumInMemoryCacheEntries; + UINT MaximumValueFileSizeBytes; + UINT64 Version; +} D3D12_SHADER_CACHE_SESSION_DESC; + +typedef enum D3D12_SHADER_CACHE_CONTROL_FLAGS +{ + D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE = 1, + D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE = 2, + D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR = 4, +} D3D12_SHADER_CACHE_CONTROL_FLAGS; + +typedef enum D3D12_SHADER_CACHE_KIND_FLAGS +{ + D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER = 1, + D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CONVERSIONS = 2, + D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED = 4, + D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED = 8, +} D3D12_SHADER_CACHE_KIND_FLAGS; + +struct D3D12ShaderCacheSession_Function_Table +{ + D3D12DeviceChild_Function_Table ParentFunction; + + HRESULT (D3DAPI *FindValue)( + _Inout_ ID3D12ShaderCacheSession* pShaderCacheSession, + _In_reads_bytes_(KeySize) const void * pKey, + UINT KeySize, + _Out_writes_bytes_(*pValueSize) void * pValue, + _Inout_ UINT * pValueSize + ); + + D3D12_SHADER_CACHE_SESSION_DESC (D3DAPI *GetDesc)( + _Inout_ ID3D12ShaderCacheSession* pShaderCacheSession + ); + + void (D3DAPI *SetDeleteOnDestroy)( + _Inout_ ID3D12ShaderCacheSession* pShaderCacheSession + ); + + HRESULT (D3DAPI *StoreValue)( + _Inout_ ID3D12ShaderCacheSession* pShaderCacheSession, + _In_reads_bytes_(KeySize) const void * pKey, + UINT KeySize, + _In_reads_bytes_(ValueSize) const void * pValue, + UINT ValueSize + ); +}; + +#if DECLARE_UMD_EXPORTS_D3D12X + +HRESULT D3d12ShaderCacheSession_FindValue( + _Inout_ ID3D12ShaderCacheSession* pShaderCacheSession, + _In_reads_bytes_(KeySize) const void * pKey, + UINT KeySize, + _Out_writes_bytes_(*pValueSize) void * pValue, + _Inout_ UINT * pValueSize +); + +D3D12_SHADER_CACHE_SESSION_DESC D3d12ShaderCacheSession_GetDesc( + _Inout_ ID3D12ShaderCacheSession* pShaderCacheSession +); + +void D3d12ShaderCacheSession_SetDeleteOnDestroy( + _Inout_ ID3D12ShaderCacheSession* pShaderCacheSession +); + +HRESULT D3d12ShaderCacheSession_StoreValue( + _Inout_ ID3D12ShaderCacheSession* pShaderCacheSession, + _In_reads_bytes_(KeySize) const void * pKey, + UINT KeySize, + _In_reads_bytes_(ValueSize) const void * pValue, + UINT ValueSize +); + +D3DCONST D3D12ShaderCacheSession_Function_Table D3D__D3d12ShaderCacheSession_Function_Table = +{ + D3D__D3d12DeviceChild_Function_Table, + + D3d12ShaderCacheSession_FindValue, + D3d12ShaderCacheSession_GetDesc, + D3d12ShaderCacheSession_SetDeleteOnDestroy, + D3d12ShaderCacheSession_StoreValue, +}; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12ShaderCacheSession, 28e2495d,0f64,4ae4,a6,ec,12,92,55,dc,49,a8) : public ID3D12DeviceChild +{ +public: + D3DINLINE D3D12ShaderCacheSession_Function_Table* ShaderCacheSessionFunction() + { + return (D3D12ShaderCacheSession_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT FindValue( + _In_reads_bytes_(KeySize) const void * pKey, + UINT KeySize, + _Out_writes_bytes_(*pValueSize) void * pValue, + _Inout_ UINT * pValueSize + ) + { + return ShaderCacheSessionFunction()->FindValue(this, pKey, KeySize, pValue, pValueSize); + } + + D3DINLINE D3D12_SHADER_CACHE_SESSION_DESC GetDesc( + ) + { + return ShaderCacheSessionFunction()->GetDesc(this); + } + + D3DINLINE void SetDeleteOnDestroy( + ) + { + ShaderCacheSessionFunction()->SetDeleteOnDestroy(this); + } + + D3DINLINE HRESULT StoreValue( + _In_reads_bytes_(KeySize) const void * pKey, + UINT KeySize, + _In_reads_bytes_(ValueSize) const void * pValue, + UINT ValueSize + ) + { + return ShaderCacheSessionFunction()->StoreValue(this, pKey, KeySize, pValue, ValueSize); + } +}; + +extern "C" +{ + +// +// ID3D12RootSignature +// + +struct D3D12RootSignature_Function_Table +{ + D3D12DeviceChild_Function_Table DeviceChildFunction; + + HRESULT (D3DAPI* GetComputeDescriptorX)( + _Inout_ ID3D12RootSignature* pRootSignature, + _Out_writes_bytes_to_opt_(*pDescriptorSize, *pDescriptorSize) void* pDescriptor, _Inout_ UINT* pDescriptorSize); +}; + + +} + +D3DINTERFACE(ID3D12RootSignature, c54a6b66,72df,4ee8,8b,e5,a9,46,a1,42,92,14) : public ID3D12DeviceChild +{ +public: + + D3DINLINE D3D12RootSignature_Function_Table* RootSignatureFunction() + { + return (D3D12RootSignature_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetComputeDescriptorX( + _Out_writes_bytes_to_opt_(*pDescriptorSize, *pDescriptorSize) void* pDescriptor, _Inout_ UINT* pDescriptorSize) + { + return RootSignatureFunction()->GetComputeDescriptorX(this, pDescriptor, pDescriptorSize); + } +}; + + +extern "C" +{ + +typedef struct D3D12_SHADER_BYTECODE +{ + _Field_size_bytes_full_(BytecodeLength) const void* pShaderBytecode; + SIZE_T BytecodeLength; +} D3D12_SHADER_BYTECODE; + +typedef struct D3D12_STREAM_OUTPUT_DESC +{ + _Field_size_full_(NumEntries) const D3D12_SO_DECLARATION_ENTRY* pSODeclaration; + UINT NumEntries; + _Field_size_full_(NumStrides) const UINT* pBufferStrides; + UINT NumStrides; + UINT RasterizedStream; +} D3D12_STREAM_OUTPUT_DESC; + +typedef struct D3D12_INPUT_LAYOUT_DESC +{ + _Field_size_full_(NumElements) const D3D12_INPUT_ELEMENT_DESC* pInputElementDescs; + UINT NumElements; +} D3D12_INPUT_LAYOUT_DESC; + +typedef enum D3D12_INDEX_BUFFER_STRIP_CUT_VALUE +{ + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED = 0, + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF = 1, + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF = 2 +} D3D12_INDEX_BUFFER_STRIP_CUT_VALUE; + +typedef struct D3D12_CACHED_PIPELINE_STATE +{ + const void* pCachedBlob; + SIZE_T CachedBlobSizeInBytes; +} D3D12_CACHED_PIPELINE_STATE; + +typedef enum D3D12_PIPELINE_STATE_FLAGS { + D3D12_PIPELINE_STATE_FLAG_NONE = 0, + D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG = 0x80000000, + + + D3D12XBOX_PIPELINE_STATE_FLAG_DISABLE_RB_PLUS = 0x00008000, + D3D12XBOX_PIPELINE_STATE_FLAG_VS_NGG = 0x00100000, + D3D12XBOX_PIPELINE_STATE_FLAG_DISABLE_AUTO_DPBB = 0x00200000, + D3D12XBOX_PIPELINE_STATE_FLAG_DELETE_UNUSED_PARAMS = 0x00400000 + +} D3D12_PIPELINE_STATE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_PIPELINE_STATE_FLAGS ); + +typedef struct D3D12_GRAPHICS_PIPELINE_STATE_DESC +{ + ID3D12RootSignature* pRootSignature; + D3D12_SHADER_BYTECODE VS; + D3D12_SHADER_BYTECODE PS; + D3D12_SHADER_BYTECODE DS; + D3D12_SHADER_BYTECODE HS; + D3D12_SHADER_BYTECODE GS; + D3D12_STREAM_OUTPUT_DESC StreamOutput; + D3D12_BLEND_DESC BlendState; + UINT SampleMask; + D3D12_RASTERIZER_DESC RasterizerState; + D3D12_DEPTH_STENCIL_DESC DepthStencilState; + D3D12_INPUT_LAYOUT_DESC InputLayout; + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE IBStripCutValue; + D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType; + UINT NumRenderTargets; + DXGI_FORMAT RTVFormats[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; + DXGI_FORMAT DSVFormat; + DXGI_SAMPLE_DESC SampleDesc; + UINT NodeMask; + D3D12_CACHED_PIPELINE_STATE CachedPSO; + D3D12_PIPELINE_STATE_FLAGS Flags; +} D3D12_GRAPHICS_PIPELINE_STATE_DESC; + +typedef struct D3D12_COMPUTE_PIPELINE_STATE_DESC +{ + ID3D12RootSignature* pRootSignature; + D3D12_SHADER_BYTECODE CS; + UINT NodeMask; + D3D12_CACHED_PIPELINE_STATE CachedPSO; + D3D12_PIPELINE_STATE_FLAGS Flags; +} D3D12_COMPUTE_PIPELINE_STATE_DESC; + +typedef enum D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER +{ + D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER_DEFAULT = 0, + D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER_LATE_Z = 1, + D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER_EARLY_Z_THEN_LATE_Z = 2, + D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER_RE_Z = 3, + D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER_EARLY_Z_THEN_RE_Z = 4 +} D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER; + +typedef enum D3D12XBOX_PIXEL_SHADER_OPTION_TEXKILL +{ + D3D12XBOX_PIXEL_SHADER_OPTION_TEXKILL_DEFAULT = 0, + D3D12XBOX_PIXEL_SHADER_OPTION_TEXKILL_ENABLE = 1, + D3D12XBOX_PIXEL_SHADER_OPTION_TEXKILL_DISABLE = 2 +} D3D12XBOX_PIXEL_SHADER_OPTION_TEXKILL; + +typedef enum D3D12XBOX_PIXEL_SHADER_OPTION_PER_SAMPLE_ITERATION +{ + D3D12XBOX_PIXEL_SHADER_OPTION_PER_SAMPLE_ITERATION_DEFAULT = 0, + D3D12XBOX_PIXEL_SHADER_OPTION_PER_SAMPLE_ITERATION_ENABLE = 1, + D3D12XBOX_PIXEL_SHADER_OPTION_PER_SAMPLE_ITERATION_DISABLE = 2 +} D3D12XBOX_PIXEL_SHADER_OPTION_PER_SAMPLE_ITERATION; + +typedef enum D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_HIER_FAIL +{ + D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_HIER_FAIL_DEFAULT = 0, + D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_HIER_FAIL_ENABLE = 1, + D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_HIER_FAIL_DISABLE = 2 +} D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_HIER_FAIL; + +typedef enum D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_NOOP +{ + D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_NOOP_DEFAULT = 0, + D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_NOOP_ENABLE = 1, + D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_NOOP_DISABLE = 2 +} D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_NOOP; + +typedef enum D3D12XBOX_PIXEL_SHADER_OPTION_DEPTH_BEFORE_SHADER +{ + D3D12XBOX_PIXEL_SHADER_OPTION_DEPTH_BEFORE_SHADER_DEFAULT = 0, + D3D12XBOX_PIXEL_SHADER_OPTION_DEPTH_BEFORE_SHADER_ENABLE = 1, + D3D12XBOX_PIXEL_SHADER_OPTION_DEPTH_BEFORE_SHADER_DISABLE = 2 +} D3D12XBOX_PIXEL_SHADER_OPTION_DEPTH_BEFORE_SHADER; + +typedef enum D3D12XBOX_PIXEL_SHADER_OPTION_CONSERVATIVE_Z_EXPORT +{ + D3D12XBOX_PIXEL_SHADER_OPTION_CONSERVATIVE_Z_EXPORT_DEFAULT = 0, + D3D12XBOX_PIXEL_SHADER_OPTION_CONSERVATIVE_Z_EXPORT_ANY_Z = 1, + D3D12XBOX_PIXEL_SHADER_OPTION_CONSERVATIVE_Z_EXPORT_LESS_THAN_Z = 2, + D3D12XBOX_PIXEL_SHADER_OPTION_CONSERVATIVE_Z_EXPORT_GREATER_THAN_Z = 3 +} D3D12XBOX_PIXEL_SHADER_OPTION_CONSERVATIVE_Z_EXPORT; + +typedef enum D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION +{ + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_DISABLED = 0, + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_ENABLED_WATER_MARK_0 = 1, + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_ENABLED_WATER_MARK_1 = 2, + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_ENABLED_WATER_MARK_2 = 3, + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_ENABLED_WATER_MARK_3 = 4, + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_ENABLED_WATER_MARK_4 = 5, + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_ENABLED_WATER_MARK_5 = 6, + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_ENABLED_WATER_MARK_6 = 7, + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_ENABLED_WATER_MARK_7 = 8, +} D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION; + +typedef struct D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC +{ + D3D12XBOX_PIXEL_SHADER_OPTION_PER_SAMPLE_ITERATION PerSampleIteration; + D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER ZOrder; + D3D12XBOX_PIXEL_SHADER_OPTION_TEXKILL TexKill; + D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_HIER_FAIL ExecOnHierFail; + D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_NOOP ExecOnNoop; + D3D12XBOX_PIXEL_SHADER_OPTION_DEPTH_BEFORE_SHADER DepthBeforeShader; + D3D12XBOX_PIXEL_SHADER_OPTION_CONSERVATIVE_Z_EXPORT ConservativeZExport; + D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION OutOfOrderRasterization; +} D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC; + + +#define D3D12XBOX_NUM_SAS_PER_SE 2u +#define D3D12XBOX_NUM_SIMD32S_PER_CU 2u +#define D3D12XBOX_MAX_WAVES_PER_SIMD32 20u +#define D3D12XBOX_ANACONDA_NUM_SES 2u +#define D3D12XBOX_LOCKHART_NUM_SES 1u + +// Anaconda SAs are not uniform. +// Each SE has one SA with 7 WGPs and one with 6 WGPs. +// Here just consider the maximum value of 7 WGPs = 14 CUs, but be careful not to extrapolate from this to per-SE values. +#define D3D12XBOX_ANACONDA_NUM_CUS_PER_SA 14u +#define D3D12XBOX_LOCKHART_NUM_CUS_PER_SA 10u +#define D3D12XBOX_MAX_WAVES_PER_CU (D3D12XBOX_MAX_WAVES_PER_SIMD32 * D3D12XBOX_NUM_SIMD32S_PER_CU) + +// Don't use D3D12XBOX_ANACONDA_NUM_CUS_PER_SA for this calculation as it's a maximum. +// 7 WGPs + 6 WGPs = 13 WGPs = 26 CUs +#define D3D12XBOX_ANACONDA_NUM_CUS_PER_SE 26u +#define D3D12XBOX_LOCKHART_NUM_CUS_PER_SE (D3D12XBOX_LOCKHART_NUM_CUS_PER_SA * D3D12XBOX_NUM_SAS_PER_SE) + +// These values are per SE for graphics and per SA for compute. +// For compute the driver will divide these by 2 to get from per-SE to per-SA value and round down with a max with 1 (because 0 disables the limit). +// For graphics there aren't enough bits anymore to encode this so the granularity is set to 16. The driver will divide the value by 16 with a clamp to 1. +// For compute this is COMPUTE_RESOURCE_LIMITS.WAVES_PER_SH +// For graphics this is SPI_SHADER_PGM_RSRC3_*.WAVE_LIMIT, using SPI_WAVE_LIMIT_CNTL +#define D3D12XBOX_SHADER_MAX_WAVES_DISABLE 0U +#define D3D12XBOX_SHADER_MAX_WAVES_ANACONDA_PER_SA (D3D12XBOX_ANACONDA_NUM_CUS_PER_SA * D3D12XBOX_MAX_WAVES_PER_CU) +#define D3D12XBOX_SHADER_MAX_WAVES_LOCKHART_PER_SA (D3D12XBOX_LOCKHART_NUM_CUS_PER_SA * D3D12XBOX_MAX_WAVES_PER_CU) +#define D3D12XBOX_SHADER_MAX_WAVES_ANACONDA_PER_SE (D3D12XBOX_ANACONDA_NUM_CUS_PER_SE * D3D12XBOX_MAX_WAVES_PER_CU) +#define D3D12XBOX_SHADER_MAX_WAVES_LOCKHART_PER_SE (D3D12XBOX_LOCKHART_NUM_CUS_PER_SE * D3D12XBOX_MAX_WAVES_PER_CU) +#define D3D12XBOX_SHADER_MAX_WAVES_DEFAULT D3D12XBOX_SHADER_MAX_WAVES_DISABLE + +#define D3D12XBOX_ANACONDA_MAX_OFFCHIP_TESSELLATION_BUFFER_SIZE (512 * 32 * 1024) +#define D3D12XBOX_LOCKHART_MAX_OFFCHIP_TESSELLATION_BUFFER_SIZE (256 * 32 * 1024) + +// These are per CU, COMPUTE_RESOURCE_LIMITS.TG_PER_CU +#define D3D12XBOX_COMPUTE_SHADER_MAX_THREADGROUPS_PER_CU_DISABLE 0U +#define D3D12XBOX_COMPUTE_SHADER_MAX_THREADGROUPS_PER_CU 15U +#define D3D12XBOX_COMPUTE_SHADER_MAX_THREADGROUPS_PER_CU_DEFAULT D3D12XBOX_COMPUTE_SHADER_MAX_THREADGROUPS_PER_CU_DISABLE + +#define D3D12XBOX_SHADER_NUM_THREADGROUPS_WALKED_PER_CU_DEFAULT 0U +#define D3D12XBOX_SHADER_NUM_THREADGROUPS_WALKED_PER_CU 8U + +#define D3D12XBOX_SHADER_MAX_LATE_ALLOC_PARAMETER_CACHE_LINES_DISABLE 0U +#define D3D12XBOX_SHADER_MAX_LATE_ALLOC_PARAMETER_CACHE_LINES_DEFAULT 0xFFFFFFFF + +#define D3D12XBOX_ANACONDA_SHADER_MAX_LATE_ALLOC_PARAMETER_CACHE_LINES 0x3FF +#define D3D12XBOX_LOCKHART_SHADER_MAX_LATE_ALLOC_PARAMETER_CACHE_LINES 0x1FF + +#define D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DISABLE 0U +#define D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_GFX_LOCKHART 120U +#define D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_CS_LOCKHART 480U +#define D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_GFX_ANACONDA 400U +#define D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_CS_ANACONDA 1600U +#define D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DISABLE + + +#define D3D12XBOX_SCARLETT_NUM_SES D3D12XBOX_ANACONDA_NUM_SES +#define D3D12XBOX_SCARLETT_NUM_CUS_PER_SA D3D12XBOX_ANACONDA_NUM_CUS_PER_SA +#define D3D12XBOX_SCARLETT_NUM_CUS_PER_SE D3D12XBOX_ANACONDA_NUM_CUS_PER_SE +#define D3D12XBOX_SHADER_MAX_WAVES_SCARLETT_PER_SA D3D12XBOX_SHADER_MAX_WAVES_ANACONDA_PER_SA +#define D3D12XBOX_SHADER_MAX_WAVES_SCARLETT_PER_SE D3D12XBOX_SHADER_MAX_WAVES_ANACONDA_PER_SE +#define D3D12XBOX_SCARLETT_SHADER_MAX_LATE_ALLOC_PARAMETER_CACHE_LINES D3D12XBOX_ANACONDA_SHADER_MAX_LATE_ALLOC_PARAMETER_CACHE_LINES +#define D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_GFX_SCARLETT D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_GFX_ANACONDA +#define D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_CS_SCARLETT D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_CS_ANACONDA + + +// These are logical CU's per SE, virtualized +// Only entries up to D3D12XBOX_(ANACONDA|LOCKHART)_NUM_CUS_PER_SA have an effect on Scarlett consoles. +#define D3D12XBOX_SHADER_DISABLE_CU(cu) ( 1U << (cu) ) +typedef enum D3D12XBOX_SHADER_UNIT_DISABLE_FLAGS : UINT +{ + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_NONE = 0, + + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_0 = D3D12XBOX_SHADER_DISABLE_CU(0), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_1 = D3D12XBOX_SHADER_DISABLE_CU(1), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_2 = D3D12XBOX_SHADER_DISABLE_CU(2), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_3 = D3D12XBOX_SHADER_DISABLE_CU(3), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_4 = D3D12XBOX_SHADER_DISABLE_CU(4), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_5 = D3D12XBOX_SHADER_DISABLE_CU(5), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_6 = D3D12XBOX_SHADER_DISABLE_CU(6), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_7 = D3D12XBOX_SHADER_DISABLE_CU(7), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_8 = D3D12XBOX_SHADER_DISABLE_CU(8), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_9 = D3D12XBOX_SHADER_DISABLE_CU(9), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_10 = D3D12XBOX_SHADER_DISABLE_CU(10), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_11 = D3D12XBOX_SHADER_DISABLE_CU(11), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_12 = D3D12XBOX_SHADER_DISABLE_CU(12), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_13 = D3D12XBOX_SHADER_DISABLE_CU(13), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_14 = D3D12XBOX_SHADER_DISABLE_CU(14), + // Deprecated: entries maintained for compatibility, values treated as Per-SA + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_15 = D3D12XBOX_SHADER_DISABLE_CU(15), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_16 = D3D12XBOX_SHADER_DISABLE_CU(16), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_17 = D3D12XBOX_SHADER_DISABLE_CU(17), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_18 = D3D12XBOX_SHADER_DISABLE_CU(18), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_19 = D3D12XBOX_SHADER_DISABLE_CU(19), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_20 = D3D12XBOX_SHADER_DISABLE_CU(20), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_21 = D3D12XBOX_SHADER_DISABLE_CU(21), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_22 = D3D12XBOX_SHADER_DISABLE_CU(22), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_23 = D3D12XBOX_SHADER_DISABLE_CU(23), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_24 = D3D12XBOX_SHADER_DISABLE_CU(24), + D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_CU_25 = D3D12XBOX_SHADER_DISABLE_CU(25), +} D3D12XBOX_SHADER_UNIT_DISABLE_FLAGS; + +#undef D3D12XBOX_SHADER_DISABLE_CU + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_SHADER_UNIT_DISABLE_FLAGS ); + +typedef enum D3D12XBOX_SHADER_CS_SIMD_WALK_ALGORITHM : UINT +{ + D3D12XBOX_SHADER_CS_SIMD_WALK_ALGORITHM_DEFAULT = 0, + D3D12XBOX_SHADER_CS_SIMD_WALK_ALGORITHM_GLOBAL_BALANCED = 1, // Walk the SIMDs across CUs but maintaining a balanced distribution per CU. + D3D12XBOX_SHADER_CS_SIMD_WALK_ALGORITHM_GLOBAL_STRICT = 2, // Walk the SIMDs across CUs disregarding wave distribution within each CU. + D3D12XBOX_SHADER_CS_SIMD_WALK_ALGORITHM_PER_CU = 3, // Walk SIMDs independently for each CU. +} D3D12XBOX_SHADER_CS_SIMD_WALK_ALGORITHM; + +typedef struct D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC +{ + UINT MaxLateAllocParameterCacheLines; + + // Per SA disable flags + // Note: Known issues for non VS-PS pipelines. Tesselation or geometry-shader usage may result in un-applied or miss-applied limits. + D3D12XBOX_SHADER_UNIT_DISABLE_FLAGS VSDisableFlags; + // Note: HS must run in the same CU as VS, so it has no flags of its own. + UINT reserved0; + D3D12XBOX_SHADER_UNIT_DISABLE_FLAGS GSDisableFlags; + D3D12XBOX_SHADER_UNIT_DISABLE_FLAGS PSDisableFlags; + + // Per SE max waves + UINT VSMaxWaves; + UINT HSMaxWaves; + UINT reserved1; + UINT GSMaxWaves; + UINT PSMaxWaves; + + // Per CU locking + UINT VSMaxWavesForCuLocking; + UINT HSMaxWavesForCuLocking; + UINT reserved2; + UINT GSMaxWavesForCuLocking; + UINT PSMaxWavesForCuLocking; +} D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC; + +D3DINLINE void D3D12XboxInitializeDefaultGraphicsShaderLimits( + D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC* pDesc) +{ + pDesc->MaxLateAllocParameterCacheLines = D3D12XBOX_SHADER_MAX_LATE_ALLOC_PARAMETER_CACHE_LINES_DEFAULT; + pDesc->VSDisableFlags = D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_NONE; + pDesc->reserved0 = 0; + pDesc->GSDisableFlags = D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_NONE; + pDesc->PSDisableFlags = D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_NONE; + pDesc->VSMaxWaves = D3D12XBOX_SHADER_MAX_WAVES_DEFAULT; + pDesc->HSMaxWaves = D3D12XBOX_SHADER_MAX_WAVES_DEFAULT; + pDesc->reserved1 = 0; + pDesc->GSMaxWaves = D3D12XBOX_SHADER_MAX_WAVES_DEFAULT; + pDesc->PSMaxWaves = D3D12XBOX_SHADER_MAX_WAVES_DEFAULT; + pDesc->VSMaxWavesForCuLocking = D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT; + pDesc->HSMaxWavesForCuLocking = D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT; + pDesc->reserved2 = 0; + pDesc->GSMaxWavesForCuLocking = D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT; + pDesc->PSMaxWavesForCuLocking = D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT; +} + +typedef struct D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC +{ + // Per SA (half SE) disable flags, symmetrically set + D3D12XBOX_SHADER_UNIT_DISABLE_FLAGS DisableFlagsPerSa; + + union + { + // Max waves per SE (two SAs) + UINT MaxWavesPerSe; + + // Deprecated: entry maintained for compatibility, value treated as Per-SE + UINT MaxWavesPerSa; + }; + + // Per CU threadgroups, locking and walk mode + UINT MaxThreadgroupsPerCu; + UINT MaxWavesForCuLocking; + UINT NumThreadgroupsWalkedPerCu; + D3D12XBOX_SHADER_CS_SIMD_WALK_ALGORITHM SimdWalkAlgorithm; +} D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC; + + +D3DINLINE void D3D12XboxInitializeDefaultComputeShaderLimits( + D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC* pDesc) +{ + pDesc->DisableFlagsPerSa = D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_NONE; + pDesc->MaxWavesPerSe = D3D12XBOX_SHADER_MAX_WAVES_DEFAULT; + pDesc->MaxThreadgroupsPerCu = D3D12XBOX_COMPUTE_SHADER_MAX_THREADGROUPS_PER_CU_DEFAULT; + pDesc->MaxWavesForCuLocking = D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT; + pDesc->NumThreadgroupsWalkedPerCu = D3D12XBOX_SHADER_NUM_THREADGROUPS_WALKED_PER_CU_DEFAULT; + pDesc->SimdWalkAlgorithm = D3D12XBOX_SHADER_CS_SIMD_WALK_ALGORITHM_DEFAULT; +} + + +#define D3D12XBOX_TESSELLATION_PARAMETERS_PATCHES_PER_THREADGROUP_DEFAULT 0 +#define D3D12XBOX_TESSELLATION_PARAMETERS_TESSELLATION_FACTOR_THRESHOLD_DEFAULT 0 +#define D3D12XBOX_TESSELLATION_PARAMETERS_DS_WAVE_THRESHOLD_DEFAULT 0 + +typedef struct D3D12XBOX_TESSELLATION_PARAMETERS_DESC +{ + UINT PatchesPerThreadgroup; + FLOAT TessellationFactorThreshold; + UINT DsWaveThreshold; +} D3D12XBOX_TESSELLATION_PARAMETERS_DESC; + +D3DINLINE void D3D12XboxInitializeDefaultTessellationParameters( + D3D12XBOX_TESSELLATION_PARAMETERS_DESC* pDesc) +{ + pDesc->PatchesPerThreadgroup = D3D12XBOX_TESSELLATION_PARAMETERS_PATCHES_PER_THREADGROUP_DEFAULT; + pDesc->TessellationFactorThreshold = D3D12XBOX_TESSELLATION_PARAMETERS_TESSELLATION_FACTOR_THRESHOLD_DEFAULT; + pDesc->DsWaveThreshold = D3D12XBOX_TESSELLATION_PARAMETERS_DS_WAVE_THRESHOLD_DEFAULT; +} + +typedef enum D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE +{ + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE_DEPTH_STENCIL = 0, + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE_RASTERIZER = 1, + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE_BLEND = 2, + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE_SAMPLE_MASK = 3, + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE_PIXEL_SHADER_OPTIONS = 4, + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE_DEPTH_STENCIL_OPTIONS = 5, + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE_SHADER_LIMITS = 6, + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE_TESSELLATION_PARAMETERS = 7, + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE_COUNT, +} D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE; + +typedef struct D3D12XBOX_DERIVED_GRAPHICS_STATE_DESC +{ + D3D12XBOX_DERIVED_GRAPHICS_STATE_TYPE Type; + union + { + D3D12_DEPTH_STENCIL_DESC DepthStencilDesc; + D3D12_RASTERIZER_DESC RasterizerDesc; + D3D12_BLEND_DESC BlendDesc; + UINT SampleMask; + D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC PixelShaderOptions; + D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC DepthStencilOptions; + D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC ShaderLimitsDesc; + D3D12XBOX_TESSELLATION_PARAMETERS_DESC TessellationParameters; + }; +} D3D12XBOX_DERIVED_GRAPHICS_STATE_DESC; + +typedef enum D3D12XBOX_DERIVED_COMPUTE_STATE_TYPE +{ + D3D12XBOX_DERIVED_COMPUTE_STATE_TYPE_SHADER_LIMITS = 0 +} D3D12XBOX_DERIVED_COMPUTE_STATE_TYPE; + +typedef struct D3D12XBOX_DERIVED_COMPUTE_STATE_DESC +{ + D3D12XBOX_DERIVED_COMPUTE_STATE_TYPE Type; + union + { + D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC ShaderLimitsDesc; + }; +} D3D12XBOX_DERIVED_COMPUTE_STATE_DESC; + +typedef struct D3D12XBOX_SERIALIZE_SHADER +{ + ID3DBlob* pGpuInstructions; + ID3DBlob* pMetaData; +} D3D12XBOX_SERIALIZE_SHADER; + +typedef enum D3D12XBOX_SERIALIZE_FLAGS +{ + D3D12XBOX_SERIALIZE_FLAGS_NONE = 0x0L, +} D3D12XBOX_SERIALIZE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_SERIALIZE_FLAGS ); + +typedef struct D3D12XBOX_SERIALIZE_GRAPHICS_PIPELINE_STATE +{ + ID3DBlob* pPacket; + ID3DBlob* pMetaData; + D3D12XBOX_SERIALIZE_SHADER PS; + D3D12XBOX_SERIALIZE_SHADER VS; + D3D12XBOX_SERIALIZE_SHADER GS; + D3D12XBOX_SERIALIZE_SHADER ES; + D3D12XBOX_SERIALIZE_SHADER HS; + D3D12XBOX_SERIALIZE_SHADER LS; + D3D12XBOX_SERIALIZE_SHADER FS; +} D3D12XBOX_SERIALIZE_GRAPHICS_PIPELINE_STATE; + +typedef struct D3D12XBOX_DESERIALIZE_SHADER +{ + _Field_size_bytes_full_(GpuInstructionsSize) const void* pGpuInstructions; + SIZE_T GpuInstructionsSize; + _Field_size_bytes_full_(MetaDataSize) const void* pMetaData; + SIZE_T MetaDataSize; +} D3D12XBOX_DESERIALIZE_SHADER; + +typedef struct D3D12XBOX_DESERIALIZE_GRAPHICS_PIPELINE_STATE +{ + ID3D12RootSignature* pRootSignature; + _Field_size_bytes_full_(PacketSize) void* pPacket; + SIZE_T PacketSize; + _Field_size_bytes_full_(MetaDataSize) void* pMetaData; + SIZE_T MetaDataSize; + D3D12XBOX_DESERIALIZE_SHADER PS; + D3D12XBOX_DESERIALIZE_SHADER VS; + D3D12XBOX_DESERIALIZE_SHADER GS; + D3D12XBOX_DESERIALIZE_SHADER ES; + D3D12XBOX_DESERIALIZE_SHADER HS; + D3D12XBOX_DESERIALIZE_SHADER LS; + D3D12XBOX_DESERIALIZE_SHADER FS; +} D3D12XBOX_DESERIALIZE_GRAPHICS_PIPELINE_STATE; + +typedef struct D3D12XBOX_SERIALIZE_COMPUTE_PIPELINE_STATE +{ + ID3DBlob* pPacket; + ID3DBlob* pMetaData; + D3D12XBOX_SERIALIZE_SHADER CS; +} D3D12XBOX_SERIALIZE_COMPUTE_PIPELINE_STATE; + +typedef struct D3D12XBOX_DESERIALIZE_COMPUTE_PIPELINE_STATE +{ + ID3D12RootSignature* pRootSignature; + _Field_size_bytes_full_(PacketSize) void* pPacket; + SIZE_T PacketSize; + _Field_size_bytes_full_(MetaDataSize) void* pMetaData; + SIZE_T MetaDataSize; + D3D12XBOX_DESERIALIZE_SHADER CS; +} D3D12XBOX_DESERIALIZE_COMPUTE_PIPELINE_STATE; + +typedef enum D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_TYPE +{ + D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_PIXEL_SHADER_OPTIONS = 0, + D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_DEPTH_STENCIL_OPTIONS = 1, + D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_SHADER_LIMITS = 2, + D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_TESSELLATION_PARAMETERS = 3 +} D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_TYPE; + +typedef struct D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_DESC +{ + D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_TYPE Type; + + union + { + D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC PixelShaderOptions; + D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC DepthStencilOptions; + D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC ShaderLimitsDesc; + D3D12XBOX_TESSELLATION_PARAMETERS_DESC TessellationParameters; + }; +} D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_DESC; + +typedef enum D3D12XBOX_EXTENDED_COMPUTE_PIPELINE_STATE_TYPE +{ + D3D12XBOX_EXTENDED_COMPUTE_PIPELINE_STATE_SHADER_LIMITS = 0 +} D3D12XBOX_EXTENDED_COMPUTE_PIPELINE_STATE_TYPE; + +typedef struct D3D12XBOX_EXTENDED_COMPUTE_PIPELINE_STATE_DESC +{ + D3D12XBOX_EXTENDED_COMPUTE_PIPELINE_STATE_TYPE Type; + + union + { + D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC ShaderLimitsDesc; + }; +} D3D12XBOX_EXTENDED_COMPUTE_PIPELINE_STATE_DESC; + + +struct D3D12_RT_FORMAT_ARRAY +{ + DXGI_FORMAT RTFormats[8]; + UINT NumRenderTargets; +}; + +typedef struct D3D12_PIPELINE_STATE_STREAM_DESC +{ + _In_ SIZE_T SizeInBytes; + _In_reads_(_Inexpressible_("Dependent on size of subobjects")) void* pPipelineStateSubobjectStream; +} D3D12_PIPELINE_STATE_STREAM_DESC; + +typedef enum D3D12_PIPELINE_STATE_SUBOBJECT_TYPE +{ + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE = 0, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC = ( D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS + 1), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING = (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 + 1), + + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS = 23, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS = 24, + + // Xbox specific chunks + D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_PIXEL_SHADER_OPTIONS = 25, // D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC + D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_OPTIONS = 26, // D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC + D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_GRAPHICS_SHADER_LIMITS = 27, // D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC + D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_TESSELLATION_PARAMETERS = 28, // D3D12XBOX_TESSELLATION_PARAMETERS_DESC + D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_COMPUTE_SHADER_LIMITS = 29, // D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC + + + // New subobjects must not renumber the released Xbox stream ABI. + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2 = 100, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1 = 101, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2 = 102, + + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2 + 1, +} D3D12_PIPELINE_STATE_SUBOBJECT_TYPE; + +typedef enum D3D12_FEATURE +{ + D3D12_FEATURE_D3D12_OPTIONS = 0, + D3D12_FEATURE_ARCHITECTURE = 1, + D3D12_FEATURE_FEATURE_LEVELS = 2, + D3D12_FEATURE_FORMAT_SUPPORT = 3, + D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS = 4, + D3D12_FEATURE_FORMAT_INFO = 5, + D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT = 6, + D3D12_FEATURE_SHADER_MODEL = 7, + D3D12_FEATURE_D3D12_OPTIONS1 = 8, + D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT = 10, + D3D12_FEATURE_ROOT_SIGNATURE = 12, + D3D12_FEATURE_ARCHITECTURE1 = 16, + D3D12_FEATURE_D3D12_OPTIONS2 = 18, + D3D12_FEATURE_SHADER_CACHE = 19, + D3D12_FEATURE_COMMAND_QUEUE_PRIORITY = 20, + D3D12_FEATURE_D3D12_OPTIONS3 = 21, + D3D12_FEATURE_EXISTING_HEAPS = 22, + D3D12_FEATURE_D3D12_OPTIONS4 = 23, + D3D12_FEATURE_SERIALIZATION = 24, + D3D12_FEATURE_CROSS_NODE = 25, + D3D12_FEATURE_D3D12_OPTIONS5 = 27, + D3D12_FEATURE_DISPLAYABLE = 28, + D3D12_FEATURE_D3D12_OPTIONS6 = 30, + D3D12_FEATURE_QUERY_META_COMMAND = 31, + D3D12_FEATURE_D3D12_OPTIONS7 = 32, + D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPE_COUNT = 33, + D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPES = 34, + D3D12_FEATURE_D3D12_OPTIONS8 = 36, + D3D12_FEATURE_D3D12_OPTIONS9 = 37, + D3D12_FEATURE_D3D12_OPTIONS10 = 39, + D3D12_FEATURE_D3D12_OPTIONS11 = 40, + D3D12_FEATURE_D3D12_OPTIONS12 = 41, + D3D12_FEATURE_D3D12_OPTIONS13 = 42, + D3D12_FEATURE_D3D12_OPTIONS14 = 43 +} D3D12_FEATURE; + +typedef enum D3D12_SHADER_MIN_PRECISION_SUPPORT +{ + D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE = 0, + D3D12_SHADER_MIN_PRECISION_SUPPORT_10_BIT = 0x1, + D3D12_SHADER_MIN_PRECISION_SUPPORT_16_BIT = 0x2 +} D3D12_SHADER_MIN_PRECISION_SUPPORT; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_SHADER_MIN_PRECISION_SUPPORT ); + +typedef enum D3D12_TILED_RESOURCES_TIER +{ + D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED = 0, + D3D12_TILED_RESOURCES_TIER_1 = 1, + D3D12_TILED_RESOURCES_TIER_2 = 2, + D3D12_TILED_RESOURCES_TIER_3 = 3, + D3D12_TILED_RESOURCES_TIER_4 = 4 +} D3D12_TILED_RESOURCES_TIER; + +typedef enum D3D12_RESOURCE_BINDING_TIER +{ + D3D12_RESOURCE_BINDING_TIER_1 = 1, + D3D12_RESOURCE_BINDING_TIER_2 = 2, + D3D12_RESOURCE_BINDING_TIER_3 = 3, +} D3D12_RESOURCE_BINDING_TIER; + +typedef enum D3D12_CONSERVATIVE_RASTERIZATION_TIER +{ + D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED = 0, + D3D12_CONSERVATIVE_RASTERIZATION_TIER_1 = 1, + D3D12_CONSERVATIVE_RASTERIZATION_TIER_2 = 2, + D3D12_CONSERVATIVE_RASTERIZATION_TIER_3 = 3, +} D3D12_CONSERVATIVE_RASTERIZATION_TIER; + +typedef enum D3D12_ASTC_PROFILE +{ + D3D12_ASTC_PROFILE_NOT_SUPPORTED = 0, + D3D12_ASTC_PROFILE_LDR = 1, + D3D12_ASTC_PROFILE_HDR = 2, + D3D12_ASTC_PROFILE_FULL = 3 +} D3D12_ASTC_PROFILE; + +typedef enum D3D12_FORMAT_SUPPORT1 +{ + D3D12_FORMAT_SUPPORT1_NONE = 0, + D3D12_FORMAT_SUPPORT1_BUFFER = 0x1, + D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER = 0x2, + D3D12_FORMAT_SUPPORT1_IA_INDEX_BUFFER = 0x4, + D3D12_FORMAT_SUPPORT1_SO_BUFFER = 0x8, + D3D12_FORMAT_SUPPORT1_TEXTURE1D = 0x10, + D3D12_FORMAT_SUPPORT1_TEXTURE2D = 0x20, + D3D12_FORMAT_SUPPORT1_TEXTURE3D = 0x40, + D3D12_FORMAT_SUPPORT1_TEXTURECUBE = 0x80, + D3D12_FORMAT_SUPPORT1_SHADER_LOAD = 0x100, + D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE = 0x200, + D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON = 0x400, + D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_MONO_TEXT = 0x800, + D3D12_FORMAT_SUPPORT1_MIP = 0x1000, + D3D12_FORMAT_SUPPORT1_RENDER_TARGET = 0x4000, + D3D12_FORMAT_SUPPORT1_BLENDABLE = 0x8000, + D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL = 0x10000, + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE = 0x40000, + D3D12_FORMAT_SUPPORT1_DISPLAY = 0x80000, + D3D12_FORMAT_SUPPORT1_CAST_WITHIN_BIT_LAYOUT = 0x100000, + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET = 0x200000, + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD = 0x400000, + D3D12_FORMAT_SUPPORT1_SHADER_GATHER = 0x800000, + D3D12_FORMAT_SUPPORT1_BACK_BUFFER_CAST = 0x1000000, + D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW = 0x2000000, + D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON = 0x4000000, + D3D12_FORMAT_SUPPORT1_DECODER_OUTPUT = 0x8000000, + D3D12_FORMAT_SUPPORT1_VIDEO_PROCESSOR_OUTPUT = 0x10000000, + D3D12_FORMAT_SUPPORT1_VIDEO_PROCESSOR_INPUT = 0x20000000, + D3D12_FORMAT_SUPPORT1_VIDEO_ENCODER = 0x40000000, +} D3D12_FORMAT_SUPPORT1; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_FORMAT_SUPPORT1 ); + +typedef enum D3D12_FORMAT_SUPPORT2 +{ + D3D12_FORMAT_SUPPORT2_NONE = 0, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD = 0x1, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS = 0x2, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_COMPARE_STORE_OR_COMPARE_EXCHANGE = 0x4, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_EXCHANGE = 0x8, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX = 0x10, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX = 0x20, + D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD = 0x40, + D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE = 0x80, + D3D12_FORMAT_SUPPORT2_OUTPUT_MERGER_LOGIC_OP = 0x100, + D3D12_FORMAT_SUPPORT2_TILED = 0x200, + D3D12_FORMAT_SUPPORT2_MULTIPLANE_OVERLAY = 0x4000 +} D3D12_FORMAT_SUPPORT2; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_FORMAT_SUPPORT2 ); + +typedef enum D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG +{ + D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE = 0, + D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE = 0x1 +} D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG ); + +typedef enum D3D12_CROSS_NODE_SHARING_TIER +{ + D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED = 0, + D3D12_CROSS_NODE_SHARING_TIER_1_EMULATED = 1, + D3D12_CROSS_NODE_SHARING_TIER_1 = 2, + D3D12_CROSS_NODE_SHARING_TIER_2 = 3, + D3D12_CROSS_NODE_SHARING_TIER_3 = 4 +} D3D12_CROSS_NODE_SHARING_TIER; + + +typedef enum D3D12_RESOURCE_HEAP_TIER +{ + D3D12_RESOURCE_HEAP_TIER_1 = 1, + D3D12_RESOURCE_HEAP_TIER_2 = 2, +} D3D12_RESOURCE_HEAP_TIER; + +typedef enum D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER +{ + D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED = 0, + D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_1 = 1, + D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_2 = 2 +} D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER; + +typedef enum D3D12_VIEW_INSTANCING_TIER +{ + D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED = 0, + D3D12_VIEW_INSTANCING_TIER_1 = 1, + D3D12_VIEW_INSTANCING_TIER_2 = 2, + D3D12_VIEW_INSTANCING_TIER_3 = 3 +} D3D12_VIEW_INSTANCING_TIER; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS +{ + _Out_ BOOL DoublePrecisionFloatShaderOps; + _Out_ BOOL OutputMergerLogicOp; + _Out_ D3D12_SHADER_MIN_PRECISION_SUPPORT MinPrecisionSupport; + _Out_ D3D12_TILED_RESOURCES_TIER TiledResourcesTier; + _Out_ D3D12_RESOURCE_BINDING_TIER ResourceBindingTier; + _Out_ BOOL PSSpecifiedStencilRefSupported; + _Out_ BOOL TypedUAVLoadAdditionalFormats; + _Out_ BOOL ROVsSupported; + _Out_ D3D12_CONSERVATIVE_RASTERIZATION_TIER ConservativeRasterizationTier; + _Out_ UINT MaxGPUVirtualAddressBitsPerResource; + _Out_ BOOL StandardSwizzle64KBSupported; + _Out_ D3D12_ASTC_PROFILE ASTCProfile; + _Out_ D3D12_CROSS_NODE_SHARING_TIER CrossNodeSharingTier; + _Out_ BOOL CrossAdapterRowMajorTextureSupported; + _Out_ BOOL VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation; + _Out_ D3D12_RESOURCE_HEAP_TIER ResourceHeapTier; +} D3D12_FEATURE_DATA_D3D12_OPTIONS; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS1 +{ + _Out_ BOOL WaveOps; + _Out_ UINT WaveLaneCountMin; + _Out_ UINT WaveLaneCountMax; + _Out_ UINT TotalLaneCount; + _Out_ BOOL ExpandedComputeResourceStates; + _Out_ BOOL Int64ShaderOps; +} D3D12_FEATURE_DATA_D3D12_OPTIONS1; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS2 +{ + _Out_ BOOL DepthBoundsTestSupported; + _Out_ D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER ProgrammableSamplePositionsTier; +} D3D12_FEATURE_DATA_D3D12_OPTIONS2; + +typedef enum D3D_ROOT_SIGNATURE_VERSION +{ + D3D_ROOT_SIGNATURE_VERSION_1 = 0x1, + D3D_ROOT_SIGNATURE_VERSION_1_0 = 0x1, + D3D_ROOT_SIGNATURE_VERSION_1_1 = 0x2, +} D3D_ROOT_SIGNATURE_VERSION; + +typedef struct D3D12_FEATURE_DATA_ROOT_SIGNATURE +{ + _Inout_ D3D_ROOT_SIGNATURE_VERSION HighestVersion; +} D3D12_FEATURE_DATA_ROOT_SIGNATURE; + +typedef struct D3D12_FEATURE_DATA_ARCHITECTURE +{ + _In_ UINT NodeIndex; + _Out_ BOOL TileBasedRenderer; + _Out_ BOOL UMA; + _Out_ BOOL CacheCoherentUMA; +} D3D12_FEATURE_DATA_ARCHITECTURE; + +typedef struct D3D12_FEATURE_DATA_ARCHITECTURE1 +{ + _In_ UINT NodeIndex; + _Out_ BOOL TileBasedRenderer; + _Out_ BOOL UMA; + _Out_ BOOL CacheCoherentUMA; + _Out_ BOOL IsolatedMMU; +} D3D12_FEATURE_DATA_ARCHITECTURE1; + +typedef struct D3D12_FEATURE_DATA_FEATURE_LEVELS +{ + _In_ UINT NumFeatureLevels; + _In_reads_(NumFeatureLevels) const D3D_FEATURE_LEVEL* pFeatureLevelsRequested; + _Out_ D3D_FEATURE_LEVEL MaxSupportedFeatureLevel; +} D3D12_FEATURE_DATA_FEATURE_LEVELS; + +typedef enum D3D_SHADER_MODEL +{ + D3D_SHADER_MODEL_5_1 = 0x51, + D3D_SHADER_MODEL_6_0 = 0x60, + D3D_SHADER_MODEL_6_1 = 0x61, + D3D_SHADER_MODEL_6_2 = 0x62, + D3D_SHADER_MODEL_6_3 = 0x63, + D3D_SHADER_MODEL_6_4 = 0x64, + D3D_SHADER_MODEL_6_5 = 0x65, + D3D_SHADER_MODEL_6_6 = 0x66, + D3D_SHADER_MODEL_6_7 = 0x67, + D3D_HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_7 +} D3D_SHADER_MODEL; + +typedef struct D3D12_FEATURE_DATA_SHADER_MODEL +{ + _Inout_ D3D_SHADER_MODEL HighestShaderModel; +} D3D12_FEATURE_DATA_SHADER_MODEL; + +typedef struct D3D12_FEATURE_DATA_FORMAT_SUPPORT +{ + _In_ DXGI_FORMAT Format; + _Out_ D3D12_FORMAT_SUPPORT1 Support1; + _Out_ D3D12_FORMAT_SUPPORT2 Support2; +} D3D12_FEATURE_DATA_FORMAT_SUPPORT; + +typedef struct D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS +{ + _In_ DXGI_FORMAT Format; + _In_ UINT SampleCount; + _In_ D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG Flags; + _Out_ UINT NumQualityLevels; +} D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS; + +typedef struct D3D12_FEATURE_DATA_FORMAT_INFO +{ + DXGI_FORMAT Format; + UINT8 PlaneCount; +} D3D12_FEATURE_DATA_FORMAT_INFO; + +typedef struct D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT +{ + UINT MaxGPUVirtualAddressBitsPerResource; + UINT MaxGPUVirtualAddressBitsPerProcess; +} D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT; + +typedef enum D3D12_SHADER_CACHE_SUPPORT_FLAGS +{ + D3D12_SHADER_CACHE_SUPPORT_NONE = 0, + D3D12_SHADER_CACHE_SUPPORT_SINGLE_PSO = 0x1, + D3D12_SHADER_CACHE_SUPPORT_LIBRARY = 0x2, + D3D12_SHADER_CACHE_SUPPORT_AUTOMATIC_INPROC_CACHE = 0x4, + D3D12_SHADER_CACHE_SUPPORT_AUTOMATIC_DISK_CACHE = 0x8 +} D3D12_SHADER_CACHE_SUPPORT_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_SHADER_CACHE_SUPPORT_FLAGS ); + +typedef struct D3D12_FEATURE_DATA_SHADER_CACHE +{ + _Out_ D3D12_SHADER_CACHE_SUPPORT_FLAGS SupportFlags; +} D3D12_FEATURE_DATA_SHADER_CACHE; + +typedef struct D3D12_FEATURE_DATA_COMMAND_QUEUE_PRIORITY +{ + _In_ D3D12_COMMAND_LIST_TYPE CommandListType; + _In_ UINT Priority; + _Out_ BOOL PriorityForTypeIsSupported; +} D3D12_FEATURE_DATA_COMMAND_QUEUE_PRIORITY; + +typedef enum D3D12_COMMAND_LIST_SUPPORT_FLAGS +{ + D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE = 0, + D3D12_COMMAND_LIST_SUPPORT_FLAG_DIRECT = (1 << D3D12_COMMAND_LIST_TYPE_DIRECT), + D3D12_COMMAND_LIST_SUPPORT_FLAG_BUNDLE = (1 << D3D12_COMMAND_LIST_TYPE_BUNDLE), + D3D12_COMMAND_LIST_SUPPORT_FLAG_COMPUTE = (1 << D3D12_COMMAND_LIST_TYPE_COMPUTE), + D3D12_COMMAND_LIST_SUPPORT_FLAG_COPY = (1 << D3D12_COMMAND_LIST_TYPE_COPY) +} D3D12_COMMAND_LIST_SUPPORT_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_COMMAND_LIST_SUPPORT_FLAGS ); + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS3 +{ + _Out_ BOOL CopyQueueTimestampQueriesSupported; + _Out_ BOOL CastingFullyTypedFormatSupported; + _Out_ D3D12_COMMAND_LIST_SUPPORT_FLAGS WriteBufferImmediateSupportFlags; + _Out_ D3D12_VIEW_INSTANCING_TIER ViewInstancingTier; + _Out_ BOOL BarycentricsSupported; +} D3D12_FEATURE_DATA_D3D12_OPTIONS3; + +typedef struct D3D12_FEATURE_DATA_EXISTING_HEAPS +{ + _Out_ BOOL Supported; +} D3D12_FEATURE_DATA_EXISTING_HEAPS; + +typedef +enum D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER +{ + D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0 = 0, + D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_1 = ( D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0 + 1 ), +} D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS4 +{ + _Out_ BOOL MSAA64KBAlignedTextureSupported; + _Out_ D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER SharedResourceCompatibilityTier; + _Out_ BOOL Native16BitShaderOpsSupported; +} D3D12_FEATURE_DATA_D3D12_OPTIONS4; + +typedef +enum D3D12_HEAP_SERIALIZATION_TIER +{ + D3D12_HEAP_SERIALIZATION_TIER_0 = 0, + D3D12_HEAP_SERIALIZATION_TIER_10 = 10 +} D3D12_HEAP_SERIALIZATION_TIER; + +typedef struct D3D12_FEATURE_DATA_SERIALIZATION +{ + _In_ UINT NodeIndex; + _Out_ D3D12_HEAP_SERIALIZATION_TIER HeapSerializationTier; +} D3D12_FEATURE_DATA_SERIALIZATION; + +typedef struct D3D12_FEATURE_DATA_CROSS_NODE +{ + D3D12_CROSS_NODE_SHARING_TIER SharingTier; + BOOL AtomicShaderInstructions; +} D3D12_FEATURE_DATA_CROSS_NODE; + + +typedef +enum D3D12_RENDER_PASS_TIER +{ + D3D12_RENDER_PASS_TIER_0 = 0, + D3D12_RENDER_PASS_TIER_1 = 1, + D3D12_RENDER_PASS_TIER_2 = 2 +} D3D12_RENDER_PASS_TIER; + +typedef +enum D3D12_RAYTRACING_TIER +{ + D3D12_RAYTRACING_TIER_NOT_SUPPORTED = 0, + D3D12_RAYTRACING_TIER_1_0 = 10, + D3D12_RAYTRACING_TIER_1_1 = 11 +} D3D12_RAYTRACING_TIER; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS5 +{ + _Out_ BOOL SRVOnlyTiledResourceTier3; + _Out_ D3D12_RENDER_PASS_TIER RenderPassesTier; + _Out_ D3D12_RAYTRACING_TIER RaytracingTier; +} D3D12_FEATURE_DATA_D3D12_OPTIONS5; + +typedef struct D3D12_RESOURCE_ALLOCATION_INFO +{ + UINT64 SizeInBytes; + UINT64 Alignment; +} D3D12_RESOURCE_ALLOCATION_INFO; + +typedef struct D3D12_RESOURCE_ALLOCATION_INFO1 +{ + UINT64 Offset; + UINT64 Alignment; + UINT64 SizeInBytes; +} D3D12_RESOURCE_ALLOCATION_INFO1; + + +typedef enum D3D12_VARIABLE_SHADING_RATE_TIER +{ + D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED = 0, + D3D12_VARIABLE_SHADING_RATE_TIER_1 = 1, + D3D12_VARIABLE_SHADING_RATE_TIER_2 = 2, +} D3D12_VARIABLE_SHADING_RATE_TIER; + +// D3D12_FEATURE_D3D12_OPTIONS5 +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS6 +{ + BOOL AdditionalShadingRatesSupported; // Always FALSE on Xbox + BOOL PerPrimitiveShadingRateSupportedWithViewportIndexing; // Always TRUE on Xbox + D3D12_VARIABLE_SHADING_RATE_TIER VariableShadingRateTier; // Always TIER_2+ on Xbox + UINT ShadingRateImageTileSize; // Always 8x8 on Xbox + BOOL BackgroundProcessingSupported; // Always FALSE on Xbox +} D3D12_FEATURE_DATA_D3D12_OPTIONS6; + +typedef enum D3D12_MESH_SHADER_TIER +{ + D3D12_MESH_SHADER_TIER_NOT_SUPPORTED = 0, + D3D12_MESH_SHADER_TIER_1 = 10, +} D3D12_MESH_SHADER_TIER; + +typedef enum D3D12_SAMPLER_FEEDBACK_TIER +{ + D3D12_SAMPLER_FEEDBACK_TIER_NOT_SUPPORTED = 0, + D3D12_SAMPLER_FEEDBACK_TIER_0_9 = 90, + D3D12_SAMPLER_FEEDBACK_TIER_1_0 = 100, + D3D12_SAMPLER_FEEDBACK_TIER_1_X = 101, +} D3D12_SAMPLER_FEEDBACK_TIER; + +// D3D12_FEATURE_D3D12_OPTIONS7 +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS7 +{ + _Out_ D3D12_MESH_SHADER_TIER MeshShaderTier; + _Out_ D3D12_SAMPLER_FEEDBACK_TIER SamplerFeedbackTier; + +} D3D12_FEATURE_DATA_D3D12_OPTIONS7; + +} + +extern "C" +{ + +typedef enum D3D12_HEAP_TYPE +{ + D3D12_HEAP_TYPE_DEFAULT = 1, + D3D12_HEAP_TYPE_UPLOAD = 2, + D3D12_HEAP_TYPE_READBACK = 3, + D3D12_HEAP_TYPE_CUSTOM = 4, +} D3D12_HEAP_TYPE; + +typedef enum D3D12_CPU_PAGE_PROPERTY +{ + D3D12_CPU_PAGE_PROPERTY_UNKNOWN = 0, + D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE = 1, + D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE = 2, + D3D12_CPU_PAGE_PROPERTY_WRITE_BACK = 3, +} D3D12_CPU_PAGE_PROPERTY; + +typedef enum D3D12_MEMORY_POOL +{ + D3D12_MEMORY_POOL_UNKNOWN = 0, + D3D12_MEMORY_POOL_L0 = 1, // Maximum bandwidth for CPU + D3D12_MEMORY_POOL_L1 = 2, // More bandwidth for GPU, less for CPU +} D3D12_MEMORY_POOL; + +typedef struct D3D12_HEAP_PROPERTIES +{ + D3D12_HEAP_TYPE Type; + D3D12_CPU_PAGE_PROPERTY CPUPageProperty; + D3D12_MEMORY_POOL MemoryPoolPreference; + UINT CreationNodeMask; + UINT VisibleNodeMask; +} D3D12_HEAP_PROPERTIES; + +} + +extern "C" +{ + +typedef enum D3D12_HEAP_FLAGS +{ + D3D12_HEAP_FLAG_NONE = 0x0, + D3D12_HEAP_FLAG_SHARED = 0x1, + D3D12XBOX_HEAP_FLAG_ALLOW_INDIRECT_BUFFERS = 0x2, + D3D12_HEAP_FLAG_DENY_BUFFERS = 0x4, + D3D12_HEAP_FLAG_ALLOW_DISPLAY = 0x8, + D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER = 0x20, + D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES = 0x40, + D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES = 0x80, + D3D12_HEAP_FLAG_HARDWARE_PROTECTED = 0x100, + D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH = 0x200, + D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS = 0x400, + + + // These are convenience aliases to manage resource heap tier restrictions. They cannot be bitwise OR'ed together cleanly. + D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES = 0x0, + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS = 0xC0, + D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES = 0x44, + D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES = 0x84, + +} D3D12_HEAP_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_HEAP_FLAGS ); + +typedef struct D3D12_HEAP_DESC +{ + UINT64 SizeInBytes; + D3D12_HEAP_PROPERTIES Properties; + UINT64 Alignment; + D3D12_HEAP_FLAGS Flags; +} D3D12_HEAP_DESC; + +} + +extern "C" +{ + +typedef enum D3D12_RESOURCE_DIMENSION +{ + D3D12_RESOURCE_DIMENSION_UNKNOWN = 0, + D3D12_RESOURCE_DIMENSION_BUFFER = 1, + D3D12_RESOURCE_DIMENSION_TEXTURE1D = 2, + D3D12_RESOURCE_DIMENSION_TEXTURE2D = 3, + D3D12_RESOURCE_DIMENSION_TEXTURE3D = 4, +} D3D12_RESOURCE_DIMENSION; + +typedef enum D3D12_TEXTURE_LAYOUT +{ + D3D12_TEXTURE_LAYOUT_UNKNOWN = 0, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR = 1, + D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE = 2, + D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE = 3, + + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR = 0x00000100, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_256B_S = 0x00000101, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_256B_D = 0x00000102, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_256B_R = 0x00000103, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_Z = 0x00000104, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_S = 0x00000105, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_D = 0x00000106, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_R = 0x00000107, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_Z = 0x00000108, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S = 0x00000109, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_D = 0x0000010a, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_R = 0x0000010b, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_Z = 0x0000010c, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_S = 0x0000010d, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_D = 0x0000010e, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_R = 0x0000010f, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_Z_T = 0x00000110, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S_T = 0x00000111, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_D_T = 0x00000112, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_R_T = 0x00000113, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_Z_X = 0x00000114, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_S_X = 0x00000115, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_D_X = 0x00000116, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_R_X = 0x00000117, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_Z_X = 0x00000118, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S_X = 0x00000119, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_D_X = 0x0000011a, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_R_X = 0x0000011b, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_Z_X = 0x0000011c, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_S_X = 0x0000011d, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_D_X = 0x0000011e, + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_R_X = 0x0000011f, + + D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_MASK = 0x11F, + +} D3D12_TEXTURE_LAYOUT; + +#define D3D12XBOX_BANK_ROTATED_SWIZZLE_MODE(SM, R) ((D3D12_TEXTURE_LAYOUT)((((R) & 0xF) << 12) | ((SM) & D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_MASK))) + +typedef enum D3D12XBOX_IMAGE_FORMAT : UINT +{ + D3D12XBOX_IMAGE_FORMAT_INVALID = 0x00000000, + D3D12XBOX_IMAGE_FORMAT_8_UNORM = 0x00000001, + D3D12XBOX_IMAGE_FORMAT_8_SNORM = 0x00000002, + D3D12XBOX_IMAGE_FORMAT_8_USCALED = 0x00000003, + D3D12XBOX_IMAGE_FORMAT_8_SSCALED = 0x00000004, + D3D12XBOX_IMAGE_FORMAT_8_UINT = 0x00000005, + D3D12XBOX_IMAGE_FORMAT_8_SINT = 0x00000006, + D3D12XBOX_IMAGE_FORMAT_16_UNORM = 0x00000007, + D3D12XBOX_IMAGE_FORMAT_16_SNORM = 0x00000008, + D3D12XBOX_IMAGE_FORMAT_16_USCALED = 0x00000009, + D3D12XBOX_IMAGE_FORMAT_16_SSCALED = 0x0000000a, + D3D12XBOX_IMAGE_FORMAT_16_UINT = 0x0000000b, + D3D12XBOX_IMAGE_FORMAT_16_SINT = 0x0000000c, + D3D12XBOX_IMAGE_FORMAT_16_FLOAT = 0x0000000d, + D3D12XBOX_IMAGE_FORMAT_8_8_UNORM = 0x0000000e, + D3D12XBOX_IMAGE_FORMAT_8_8_SNORM = 0x0000000f, + D3D12XBOX_IMAGE_FORMAT_8_8_USCALED = 0x00000010, + D3D12XBOX_IMAGE_FORMAT_8_8_SSCALED = 0x00000011, + D3D12XBOX_IMAGE_FORMAT_8_8_UINT = 0x00000012, + D3D12XBOX_IMAGE_FORMAT_8_8_SINT = 0x00000013, + D3D12XBOX_IMAGE_FORMAT_32_UINT = 0x00000014, + D3D12XBOX_IMAGE_FORMAT_32_SINT = 0x00000015, + D3D12XBOX_IMAGE_FORMAT_32_FLOAT = 0x00000016, + D3D12XBOX_IMAGE_FORMAT_16_16_UNORM = 0x00000017, + D3D12XBOX_IMAGE_FORMAT_16_16_SNORM = 0x00000018, + D3D12XBOX_IMAGE_FORMAT_16_16_USCALED = 0x00000019, + D3D12XBOX_IMAGE_FORMAT_16_16_SSCALED = 0x0000001a, + D3D12XBOX_IMAGE_FORMAT_16_16_UINT = 0x0000001b, + D3D12XBOX_IMAGE_FORMAT_16_16_SINT = 0x0000001c, + D3D12XBOX_IMAGE_FORMAT_16_16_FLOAT = 0x0000001d, + D3D12XBOX_IMAGE_FORMAT_10_11_11_UNORM = 0x0000001e, + D3D12XBOX_IMAGE_FORMAT_10_11_11_SNORM = 0x0000001f, + D3D12XBOX_IMAGE_FORMAT_10_11_11_USCALED = 0x00000020, + D3D12XBOX_IMAGE_FORMAT_10_11_11_SSCALED = 0x00000021, + D3D12XBOX_IMAGE_FORMAT_10_11_11_UINT = 0x00000022, + D3D12XBOX_IMAGE_FORMAT_10_11_11_SINT = 0x00000023, + D3D12XBOX_IMAGE_FORMAT_10_11_11_FLOAT = 0x00000024, + D3D12XBOX_IMAGE_FORMAT_11_11_10_UNORM = 0x00000025, + D3D12XBOX_IMAGE_FORMAT_11_11_10_SNORM = 0x00000026, + D3D12XBOX_IMAGE_FORMAT_11_11_10_USCALED = 0x00000027, + D3D12XBOX_IMAGE_FORMAT_11_11_10_SSCALED = 0x00000028, + D3D12XBOX_IMAGE_FORMAT_11_11_10_UINT = 0x00000029, + D3D12XBOX_IMAGE_FORMAT_11_11_10_SINT = 0x0000002a, + D3D12XBOX_IMAGE_FORMAT_11_11_10_FLOAT = 0x0000002b, + D3D12XBOX_IMAGE_FORMAT_10_10_10_2_UNORM = 0x0000002c, + D3D12XBOX_IMAGE_FORMAT_10_10_10_2_SNORM = 0x0000002d, + D3D12XBOX_IMAGE_FORMAT_10_10_10_2_USCALED = 0x0000002e, + D3D12XBOX_IMAGE_FORMAT_10_10_10_2_SSCALED = 0x0000002f, + D3D12XBOX_IMAGE_FORMAT_10_10_10_2_UINT = 0x00000030, + D3D12XBOX_IMAGE_FORMAT_10_10_10_2_SINT = 0x00000031, + D3D12XBOX_IMAGE_FORMAT_2_10_10_10_UNORM = 0x00000032, + D3D12XBOX_IMAGE_FORMAT_2_10_10_10_SNORM = 0x00000033, + D3D12XBOX_IMAGE_FORMAT_2_10_10_10_USCALED = 0x00000034, + D3D12XBOX_IMAGE_FORMAT_2_10_10_10_SSCALED = 0x00000035, + D3D12XBOX_IMAGE_FORMAT_2_10_10_10_UINT = 0x00000036, + D3D12XBOX_IMAGE_FORMAT_2_10_10_10_SINT = 0x00000037, + D3D12XBOX_IMAGE_FORMAT_8_8_8_8_UNORM = 0x00000038, + D3D12XBOX_IMAGE_FORMAT_8_8_8_8_SNORM = 0x00000039, + D3D12XBOX_IMAGE_FORMAT_8_8_8_8_USCALED = 0x0000003a, + D3D12XBOX_IMAGE_FORMAT_8_8_8_8_SSCALED = 0x0000003b, + D3D12XBOX_IMAGE_FORMAT_8_8_8_8_UINT = 0x0000003c, + D3D12XBOX_IMAGE_FORMAT_8_8_8_8_SINT = 0x0000003d, + D3D12XBOX_IMAGE_FORMAT_32_32_UINT = 0x0000003e, + D3D12XBOX_IMAGE_FORMAT_32_32_SINT = 0x0000003f, + D3D12XBOX_IMAGE_FORMAT_32_32_FLOAT = 0x00000040, + D3D12XBOX_IMAGE_FORMAT_16_16_16_16_UNORM = 0x00000041, + D3D12XBOX_IMAGE_FORMAT_16_16_16_16_SNORM = 0x00000042, + D3D12XBOX_IMAGE_FORMAT_16_16_16_16_USCALED = 0x00000043, + D3D12XBOX_IMAGE_FORMAT_16_16_16_16_SSCALED = 0x00000044, + D3D12XBOX_IMAGE_FORMAT_16_16_16_16_UINT = 0x00000045, + D3D12XBOX_IMAGE_FORMAT_16_16_16_16_SINT = 0x00000046, + D3D12XBOX_IMAGE_FORMAT_16_16_16_16_FLOAT = 0x00000047, + D3D12XBOX_IMAGE_FORMAT_32_32_32_UINT = 0x00000048, + D3D12XBOX_IMAGE_FORMAT_32_32_32_SINT = 0x00000049, + D3D12XBOX_IMAGE_FORMAT_32_32_32_FLOAT = 0x0000004a, + D3D12XBOX_IMAGE_FORMAT_32_32_32_32_UINT = 0x0000004b, + D3D12XBOX_IMAGE_FORMAT_32_32_32_32_SINT = 0x0000004c, + D3D12XBOX_IMAGE_FORMAT_32_32_32_32_FLOAT = 0x0000004d, + D3D12XBOX_IMAGE_FORMAT_8_SRGB = 0x00000080, + D3D12XBOX_IMAGE_FORMAT_8_8_SRGB = 0x00000081, + D3D12XBOX_IMAGE_FORMAT_8_8_8_8_SRGB = 0x00000082, + D3D12XBOX_IMAGE_FORMAT_6E4_FLOAT = 0x00000083, + D3D12XBOX_IMAGE_FORMAT_5_9_9_9_FLOAT = 0x00000084, + D3D12XBOX_IMAGE_FORMAT_5_6_5_UNORM = 0x00000085, + D3D12XBOX_IMAGE_FORMAT_1_5_5_5_UNORM = 0x00000086, + D3D12XBOX_IMAGE_FORMAT_5_5_5_1_UNORM = 0x00000087, + D3D12XBOX_IMAGE_FORMAT_4_4_4_4_UNORM = 0x00000088, + D3D12XBOX_IMAGE_FORMAT_4_4_UNORM = 0x00000089, + D3D12XBOX_IMAGE_FORMAT_1_UNORM = 0x0000008a, + D3D12XBOX_IMAGE_FORMAT_1_REVERSED_UNORM = 0x0000008b, + D3D12XBOX_IMAGE_FORMAT_32_FLOAT_CLAMP = 0x0000008c, + D3D12XBOX_IMAGE_FORMAT_8_24_UNORM = 0x0000008d, + D3D12XBOX_IMAGE_FORMAT_8_24_UINT = 0x0000008e, + D3D12XBOX_IMAGE_FORMAT_24_8_UNORM = 0x0000008f, + D3D12XBOX_IMAGE_FORMAT_24_8_UINT = 0x00000090, + D3D12XBOX_IMAGE_FORMAT_X24_8_32_UINT = 0x00000091, + D3D12XBOX_IMAGE_FORMAT_X24_8_32_FLOAT = 0x00000092, + D3D12XBOX_IMAGE_FORMAT_GB_GR_UNORM = 0x00000093, + D3D12XBOX_IMAGE_FORMAT_GB_GR_SNORM = 0x00000094, + D3D12XBOX_IMAGE_FORMAT_GB_GR_UINT = 0x00000095, + D3D12XBOX_IMAGE_FORMAT_GB_GR_SRGB = 0x00000096, + D3D12XBOX_IMAGE_FORMAT_BG_RG_UNORM = 0x00000097, + D3D12XBOX_IMAGE_FORMAT_BG_RG_SNORM = 0x00000098, + D3D12XBOX_IMAGE_FORMAT_BG_RG_UINT = 0x00000099, + D3D12XBOX_IMAGE_FORMAT_BG_RG_SRGB = 0x0000009a, + D3D12XBOX_IMAGE_FORMAT_RESERVED_155 = 0x0000009b, + D3D12XBOX_IMAGE_FORMAT_FMASK8_S2_F1 = 0x0000009c, + D3D12XBOX_IMAGE_FORMAT_FMASK8_S4_F1 = 0x0000009d, + D3D12XBOX_IMAGE_FORMAT_FMASK8_S8_F1 = 0x0000009e, + D3D12XBOX_IMAGE_FORMAT_FMASK8_S2_F2 = 0x0000009f, + D3D12XBOX_IMAGE_FORMAT_FMASK8_S4_F2 = 0x000000a0, + D3D12XBOX_IMAGE_FORMAT_FMASK8_S4_F4 = 0x000000a1, + D3D12XBOX_IMAGE_FORMAT_FMASK16_S16_F1 = 0x000000a2, + D3D12XBOX_IMAGE_FORMAT_FMASK16_S8_F2 = 0x000000a3, + D3D12XBOX_IMAGE_FORMAT_FMASK32_S16_F2 = 0x000000a4, + D3D12XBOX_IMAGE_FORMAT_FMASK32_S8_F4 = 0x000000a5, + D3D12XBOX_IMAGE_FORMAT_FMASK32_S8_F8 = 0x000000a6, + D3D12XBOX_IMAGE_FORMAT_FMASK64_S16_F4 = 0x000000a7, + D3D12XBOX_IMAGE_FORMAT_FMASK64_S16_F8 = 0x000000a8, + D3D12XBOX_IMAGE_FORMAT_BC1_UNORM = 0x000000a9, + D3D12XBOX_IMAGE_FORMAT_BC1_SRGB = 0x000000aa, + D3D12XBOX_IMAGE_FORMAT_BC2_UNORM = 0x000000ab, + D3D12XBOX_IMAGE_FORMAT_BC2_SRGB = 0x000000ac, + D3D12XBOX_IMAGE_FORMAT_BC3_UNORM = 0x000000ad, + D3D12XBOX_IMAGE_FORMAT_BC3_SRGB = 0x000000ae, + D3D12XBOX_IMAGE_FORMAT_BC4_UNORM = 0x000000af, + D3D12XBOX_IMAGE_FORMAT_BC4_SNORM = 0x000000b0, + D3D12XBOX_IMAGE_FORMAT_BC5_UNORM = 0x000000b1, + D3D12XBOX_IMAGE_FORMAT_BC5_SNORM = 0x000000b2, + D3D12XBOX_IMAGE_FORMAT_BC6_UFLOAT = 0x000000b3, + D3D12XBOX_IMAGE_FORMAT_BC6_SFLOAT = 0x000000b4, + D3D12XBOX_IMAGE_FORMAT_BC7_UNORM = 0x000000b5, + D3D12XBOX_IMAGE_FORMAT_BC7_SRGB = 0x000000b6, + D3D12XBOX_IMAGE_FORMAT_MM_8_UNORM = 0x00000109, + D3D12XBOX_IMAGE_FORMAT_MM_8_UINT = 0x0000010a, + D3D12XBOX_IMAGE_FORMAT_MM_8_8_UNORM = 0x0000010b, + D3D12XBOX_IMAGE_FORMAT_MM_8_8_UINT = 0x0000010c, + D3D12XBOX_IMAGE_FORMAT_MM_8_8_8_8_UNORM = 0x0000010d, + D3D12XBOX_IMAGE_FORMAT_MM_8_8_8_8_UINT = 0x0000010e, + D3D12XBOX_IMAGE_FORMAT_MM_VYUY8_UNORM = 0x0000010f, + D3D12XBOX_IMAGE_FORMAT_MM_VYUY8_UINT = 0x00000110, + D3D12XBOX_IMAGE_FORMAT_MM_10_11_11_UNORM = 0x00000111, + D3D12XBOX_IMAGE_FORMAT_MM_10_11_11_UINT = 0x00000112, + D3D12XBOX_IMAGE_FORMAT_MM_2_10_10_10_UNORM = 0x00000113, + D3D12XBOX_IMAGE_FORMAT_MM_2_10_10_10_UINT = 0x00000114, + D3D12XBOX_IMAGE_FORMAT_MM_16_16_16_16_UNORM = 0x00000115, + D3D12XBOX_IMAGE_FORMAT_MM_16_16_16_16_UINT = 0x00000116, + D3D12XBOX_IMAGE_FORMAT_MM_10_IN_16_UNORM = 0x00000117, + D3D12XBOX_IMAGE_FORMAT_MM_10_IN_16_UINT = 0x00000118, + D3D12XBOX_IMAGE_FORMAT_MM_10_IN_16_16_UNORM = 0x00000119, + D3D12XBOX_IMAGE_FORMAT_MM_10_IN_16_16_UINT = 0x0000011a, + D3D12XBOX_IMAGE_FORMAT_MM_10_IN_16_16_16_16_UNORM = 0x0000011b, + D3D12XBOX_IMAGE_FORMAT_MM_10_IN_16_16_16_16_UINT = 0x0000011c, + D3D12XBOX_IMAGE_FORMAT_7E3_FLOAT = 0x0000011d, + D3D12XBOX_IMAGE_FORMAT_YCBCR_UNORM = 0x0000011e, + D3D12XBOX_IMAGE_FORMAT_YCBCR_SRGB = 0x0000011f, +} D3D12XBOX_IMAGE_FORMAT; + +typedef enum D3D12_RESOURCE_FLAGS +{ + D3D12_RESOURCE_FLAG_NONE = 0, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET = 0x1, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL = 0x2, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS = 0x4, + D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE = 0x8, + D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER = 0x10, + D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS = 0x20, + D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE = 0x80, + D3D12XBOX_RESOURCE_FLAG_PREFER_INDEX_BUFFER = 0x10000, + D3D12XBOX_RESOURCE_FLAG_ALLOW_INDIRECT_BUFFER = 0x20000, + D3D12XBOX_RESOURCE_FLAG_PREFER_INDIRECT_BUFFER = D3D12XBOX_RESOURCE_FLAG_ALLOW_INDIRECT_BUFFER, + D3D12XBOX_RESOURCE_FLAG_PREFER_PREDICATION_BUFFER = 0x40000, + D3D12XBOX_RESOURCE_FLAG_PREFER_STREAM_OUTPUT = 0x80000, + D3D12XBOX_RESOURCE_FLAG_DENY_COLOR_COMPRESSION_DATA = 0x100000, + D3D12XBOX_RESOURCE_FLAG_DENY_DEPTH_COMPRESSION_DATA = 0x100000, + D3D12XBOX_RESOURCE_FLAG_DENY_STENCIL_COMPRESSION_DATA = 0x200000, + D3D12XBOX_RESOURCE_FLAG_DENY_COMPRESSION_DATA = + D3D12XBOX_RESOURCE_FLAG_DENY_COLOR_COMPRESSION_DATA | + D3D12XBOX_RESOURCE_FLAG_DENY_DEPTH_COMPRESSION_DATA | + D3D12XBOX_RESOURCE_FLAG_DENY_STENCIL_COMPRESSION_DATA, + D3D12XBOX_RESOURCE_FLAG_ALLOW_DCC = 0x400000, + D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY = 0x00800000, + D3D12XBOX_RESOURCE_FLAG_FORCE_DCC_TEXTURE_COMPATIBILITY = 0x00000100, + D3D12XBOX_RESOURCE_FLAG_FORCE_HTILE_TEXTURE_COMPATIBILITY = 0x00000100, + D3D12XBOX_RESOURCE_FLAG_FORCE_FMASK_TEXTURE_COMPATIBILITY = 0x00000200, + D3D12XBOX_RESOURCE_FLAG_DENY_DEPTH_COMPRESSION_EXPCLEAR = 0x1000000, + D3D12XBOX_RESOURCE_FLAG_DENY_DEPTH_COMPRESSION_PLANES = 0x2000000, + D3D12XBOX_RESOURCE_FLAG_DENY_STENCIL_COMPRESSION_SMEM = 0x4000000, + D3D12XBOX_RESOURCE_FLAG_DENY_DEPTH_STENCIL_HTILE = 0x80000000, + D3D12XBOX_RESOURCE_FLAG_DENY_DEPTH_EXPCLEAR = D3D12XBOX_RESOURCE_FLAG_DENY_DEPTH_COMPRESSION_EXPCLEAR, + D3D12XBOX_RESOURCE_FLAG_ALLOW_AUTOMATIC_GAMEDVR_TONE_MAP = 0x40000000, +} D3D12_RESOURCE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_RESOURCE_FLAGS ); + +typedef struct D3D12_MIP_REGION +{ + UINT Width; + UINT Height; + UINT Depth; +} D3D12_MIP_REGION; + +typedef struct D3D12_RESOURCE_DESC +{ + D3D12_RESOURCE_DIMENSION Dimension; + UINT64 Alignment; + UINT64 Width; + UINT Height; + UINT16 DepthOrArraySize; + UINT16 MipLevels; + DXGI_FORMAT Format; + DXGI_SAMPLE_DESC SampleDesc; + D3D12_TEXTURE_LAYOUT Layout; + D3D12_RESOURCE_FLAGS Flags; +} D3D12_RESOURCE_DESC; + +typedef struct D3D12_RESOURCE_DESC1 +{ + D3D12_RESOURCE_DIMENSION Dimension; + UINT64 Alignment; + UINT64 Width; + UINT Height; + UINT16 DepthOrArraySize; + UINT16 MipLevels; + DXGI_FORMAT Format; + DXGI_SAMPLE_DESC SampleDesc; + D3D12_TEXTURE_LAYOUT Layout; + D3D12_RESOURCE_FLAGS Flags; + D3D12_MIP_REGION SamplerFeedbackMipRegion; +} D3D12_RESOURCE_DESC1; + + +typedef struct D3D12XBOX_COMPONENT_PLACED_ADDRESSES +{ + union + { + struct + { + D3D12_GPU_VIRTUAL_ADDRESS BaseAddress; + } Resource; + struct + { + D3D12_GPU_VIRTUAL_ADDRESS ColorSamples; + D3D12_GPU_VIRTUAL_ADDRESS CMask; + D3D12_GPU_VIRTUAL_ADDRESS DCC; + } NonAARenderTarget; + struct + { + D3D12_GPU_VIRTUAL_ADDRESS ColorSamples; + D3D12_GPU_VIRTUAL_ADDRESS CMask; + D3D12_GPU_VIRTUAL_ADDRESS FragmentMask; + D3D12_GPU_VIRTUAL_ADDRESS DCC; + } AARenderTarget; + struct + { + D3D12_GPU_VIRTUAL_ADDRESS DepthSamples; + D3D12_GPU_VIRTUAL_ADDRESS HTile; + } DepthTarget; + struct + { + D3D12_GPU_VIRTUAL_ADDRESS DepthSamples; + D3D12_GPU_VIRTUAL_ADDRESS HTile; + D3D12_GPU_VIRTUAL_ADDRESS StencilSamples; + } DepthStencilTarget; + }; +} D3D12XBOX_COMPONENT_PLACED_ADDRESSES; + +typedef enum D3D12XBOX_DCC_COMPRESSION_LEVEL +{ + D3D12XBOX_DCC_COMPRESSION_LEVEL_64B = 0, + D3D12XBOX_DCC_COMPRESSION_LEVEL_128B_TEXTURE_COMPATIBLE = 1, + D3D12XBOX_DCC_COMPRESSION_LEVEL_256B = 2, + D3D12XBOX_DCC_COMPRESSION_LEVEL_DEFAULT = 3, +} D3D12XBOX_DCC_COMPRESSION_LEVEL; + +typedef enum D3D12XBOX_DCC_COLOR_TRANSFORM +{ + D3D12XBOX_DCC_COLOR_TRANSFORM_AUTO_TEXTURE_COMPATIBLE = 0, + D3D12XBOX_DCC_COLOR_TRANSFORM_NONE_TEXTURE_COMPATIBLE = 1, + D3D12XBOX_DCC_COLOR_TRANSFORM_LSC_CORRELATED = 2, + D3D12XBOX_DCC_COLOR_TRANSFORM_MSC_CORRELATED = 3 +} D3D12XBOX_DCC_COLOR_TRANSFORM; + +typedef struct D3D12XBOX_DCC_OPTIONS +{ + D3D12XBOX_DCC_COMPRESSION_LEVEL CompressionLevel; + D3D12XBOX_DCC_COLOR_TRANSFORM ColorTransform; +} D3D12XBOX_DCC_OPTIONS; + +#define D3D12XBOX_DCC_KEY_CLEAR_VALUE_UNCOMPRESSED (0xFF) +#define D3D12XBOX_DCC_KEY_CLEAR_VALUE_RGBA_0000 (0x00) +#define D3D12XBOX_DCC_KEY_CLEAR_VALUE_RGBA_0001 (0x40) +#define D3D12XBOX_DCC_KEY_CLEAR_VALUE_RGBA_1110 (0x80) +#define D3D12XBOX_DCC_KEY_CLEAR_VALUE_RGBA_1111 (0xC0) + +typedef struct D3D12XBOX_RESOURCE_DESC +{ + D3D12_RESOURCE_DIMENSION Dimension; + UINT64 Alignment; + UINT64 Width; + UINT Height; + UINT16 DepthOrArraySize; + UINT16 MipLevels; + DXGI_FORMAT Format; + DXGI_SAMPLE_DESC SampleDesc; + D3D12_TEXTURE_LAYOUT Layout; + D3D12_RESOURCE_FLAGS Flags; + D3D12XBOX_DCC_OPTIONS DccOptions; +} D3D12XBOX_RESOURCE_DESC; + +} + +extern "C" +{ + +typedef struct D3D12_DEPTH_STENCIL_VALUE +{ + FLOAT Depth; + UINT8 Stencil; +} D3D12_DEPTH_STENCIL_VALUE; + +typedef struct D3D12_CLEAR_VALUE +{ + DXGI_FORMAT Format; + union + { + FLOAT Color[ 4 ]; + D3D12_DEPTH_STENCIL_VALUE DepthStencil; + }; +} D3D12_CLEAR_VALUE; + +} + +extern "C" +{ + +typedef struct D3D12_RANGE +{ + SIZE_T Begin; + SIZE_T End; // One past end, so (End - Begin) = Size +} D3D12_RANGE; + +typedef struct D3D12_RANGE_UINT64 +{ + UINT64 Begin; + UINT64 End; +} D3D12_RANGE_UINT64; + +typedef struct D3D12_SUBRESOURCE_RANGE_UINT64 +{ + UINT Subresource; + D3D12_RANGE_UINT64 Range; +} D3D12_SUBRESOURCE_RANGE_UINT64; + +} + +extern "C" +{ + +typedef struct D3D12_SUBRESOURCE_INFO +{ + UINT64 Offset; + UINT RowPitch; + UINT DepthPitch; +} D3D12_SUBRESOURCE_INFO; + +typedef struct D3D12_TILED_RESOURCE_COORDINATE +{ + UINT X; + UINT Y; + UINT Z; + UINT Subresource; +} D3D12_TILED_RESOURCE_COORDINATE; + +} + +extern "C" +{ + +typedef struct D3D12_TILE_REGION_SIZE +{ + UINT NumTiles; + BOOL UseBox; + UINT Width; + UINT16 Height; + UINT16 Depth; +} D3D12_TILE_REGION_SIZE; + +} + +extern "C" +{ + +typedef enum D3D12XBOX_PAGE_MAPPING_RANGE_TYPE +{ + D3D12XBOX_PAGE_MAPPING_RANGE_TYPE_INCREMENTING_PAGE_INDICES = 0, + D3D12XBOX_PAGE_MAPPING_RANGE_TYPE_CONSTANT_PAGE_INDEX = 1, + D3D12XBOX_PAGE_MAPPING_RANGE_TYPE_NULL_PAGES = 2, + D3D12XBOX_PAGE_MAPPING_RANGE_TYPE_SKIP_RANGE = 3 +} D3D12XBOX_PAGE_MAPPING_RANGE_TYPE; + +typedef struct D3D12XBOX_PAGE_MAPPING_RANGE +{ + D3D12XBOX_PAGE_MAPPING_RANGE_TYPE RangeType; + UINT StartPageIndexInPool; + UINT PageCount; +} D3D12XBOX_PAGE_MAPPING_RANGE; + +typedef struct D3D12XBOX_PAGE_MAPPING_BATCH +{ + D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress; + UINT RangeCount; + const D3D12XBOX_PAGE_MAPPING_RANGE* pRanges; +} D3D12XBOX_PAGE_MAPPING_BATCH; + +typedef enum D3D12XBOX_PAGE_MAPPING_FLAGS +{ + D3D12XBOX_PAGE_MAPPING_FLAG_NONE = 0, + D3D12XBOX_PAGE_MAPPING_FLAG_NO_HAZARD = 1, + D3D12XBOX_PAGE_MAPPING_FLAG_2MB_PAGES = 2, +} D3D12XBOX_PAGE_MAPPING_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_PAGE_MAPPING_FLAGS); + +typedef enum D3D12XBOX_RESERVED1 +{ +} D3D12XBOX_RESERVED1; + +} + +extern "C" +{ + +typedef enum D3D12_TILE_RANGE_FLAGS +{ + D3D12_TILE_RANGE_FLAG_NONE = 0, + D3D12_TILE_RANGE_FLAG_NULL = 1, + D3D12_TILE_RANGE_FLAG_SKIP = 2, + D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE = 4 +} D3D12_TILE_RANGE_FLAGS; + +typedef struct D3D12_SUBRESOURCE_TILING +{ + UINT WidthInTiles; + UINT16 HeightInTiles; + UINT16 DepthInTiles; + UINT StartTileIndexInOverallResource; +} D3D12_SUBRESOURCE_TILING; + +} + +extern "C" +{ + +typedef struct D3D12_TILE_SHAPE +{ + UINT WidthInTexels; + UINT HeightInTexels; + UINT DepthInTexels; +} D3D12_TILE_SHAPE; + +} + +extern "C" +{ + +typedef struct D3D12_PACKED_MIP_INFO +{ + UINT8 NumStandardMips; + UINT8 NumPackedMips; + UINT NumTilesForPackedMips; + UINT StartTileIndexInOverallResource; +} D3D12_PACKED_MIP_INFO; + +} + +extern "C" +{ + +typedef enum D3D12_TILE_MAPPING_FLAGS +{ + D3D12_TILE_MAPPING_FLAG_NONE = 0, + D3D12_TILE_MAPPING_FLAG_NO_HAZARD = 0x1 +} D3D12_TILE_MAPPING_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_TILE_MAPPING_FLAGS ); + +typedef enum D3D12_TILE_COPY_FLAGS +{ + D3D12_TILE_COPY_FLAG_NONE = 0, + D3D12_TILE_COPY_FLAG_NO_HAZARD = 0x1, + D3D12_TILE_COPY_FLAG_LINEAR_BUFFER_TO_SWIZZLED_TILED_RESOURCE = 0x2, + D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER = 0x4 +} D3D12_TILE_COPY_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_TILE_COPY_FLAGS ); + +typedef enum D3D12XBOX_FLUSH : UINT +{ + D3D12XBOX_FLUSH_NONE = 0x00000000, + + D3D12XBOX_FLUSH_TOP_BASE_COHERENCY = 0x00000001, + D3D12XBOX_FLUSH_TOP_COLOR_BLOCK_COHERENCY = 0x00000040, + D3D12XBOX_FLUSH_TOP_DEPTH_BLOCK_COHERENCY = 0x00004000, + D3D12XBOX_FLUSH_TOP_COLOR_BLOCK_INVALIDATE = 0x02000000, + D3D12XBOX_FLUSH_TOP_DEPTH_BLOCK_INVALIDATE = 0x04000000, + D3D12XBOX_FLUSH_TOP_TEXTURE_L1_INVALIDATE = 0x00400000, + D3D12XBOX_FLUSH_TOP_TEXTURE_L2_INVALIDATE = 0x00800000, + D3D12XBOX_FLUSH_TOP_TEXTURE_L2_WRITEBACK = 0x00040000, + D3D12XBOX_FLUSH_TOP_KCACHE_INVALIDATE = 0x08000000, + D3D12XBOX_FLUSH_TOP_ICACHE_INVALIDATE = 0x20000000, + D3D12XBOX_FLUSH_TOP_SELECT_ENGINE_PFP = 0x80000000, + D3D12XBOX_FLUSH_TOP_SELECT_ENGINE_CE = 0x00080000, // Apply TOP flush operations at the CE (currently only + // respected by D3D12XBOX_FLUSH_IDLE) + D3D12XBOX_FLUSH_TOP_PFP_SYNC_ME = 0x40000000, // Synchronize command processor PFP with ME + + D3D12XBOX_FLUSH_BOP_COLOR_BLOCK_DATA = 0x00000004, // Flush Color Block pixel data + D3D12XBOX_FLUSH_BOP_DEPTH_BLOCK_DATA = 0x00000008, // Flush Depth Block data + D3D12XBOX_FLUSH_BOP_COLOR_BLOCK_META = 0x00000010, // Flush Color Block metadata + D3D12XBOX_FLUSH_BOP_DEPTH_BLOCK_META = 0x00000020, // Flush Depth Block metadata + D3D12XBOX_FLUSH_BOP_TEXTURE_L1_INVALIDATE = 0x00001000, + D3D12XBOX_FLUSH_BOP_TEXTURE_L2_INVALIDATE = 0x00002000, + D3D12XBOX_FLUSH_BOP_TEXTURE_L2_WRITEBACK = 0x00000800, + D3D12XBOX_FLUSH_BOP_CS_PARTIAL = 0x00020000, // Ensure all CS finished running before dispatching new CS + D3D12XBOX_FLUSH_BOP_VS_PARTIAL = 0x00100000, // Ensure all VS finished running before dispatching new VS + D3D12XBOX_FLUSH_BOP_PS_PARTIAL = 0x01000000, // Ensure all PS finished running before dispatching new PS + D3D12XBOX_FLUSH_BOP_STREAMOUT = 0x00000400, // Flush stream out caches + + D3D12XBOX_FLUSH_IDLE = 0x00200000, + + D3D12XBOX_FLUSH_TOP_MASK = + D3D12XBOX_FLUSH_TOP_BASE_COHERENCY | + D3D12XBOX_FLUSH_TOP_COLOR_BLOCK_COHERENCY | + D3D12XBOX_FLUSH_TOP_DEPTH_BLOCK_COHERENCY | + D3D12XBOX_FLUSH_TOP_COLOR_BLOCK_INVALIDATE | + D3D12XBOX_FLUSH_TOP_DEPTH_BLOCK_INVALIDATE | + D3D12XBOX_FLUSH_TOP_TEXTURE_L1_INVALIDATE | + D3D12XBOX_FLUSH_TOP_TEXTURE_L2_INVALIDATE | + D3D12XBOX_FLUSH_TOP_TEXTURE_L2_WRITEBACK | + D3D12XBOX_FLUSH_TOP_KCACHE_INVALIDATE | + D3D12XBOX_FLUSH_TOP_ICACHE_INVALIDATE | + D3D12XBOX_FLUSH_TOP_SELECT_ENGINE_PFP | + D3D12XBOX_FLUSH_TOP_SELECT_ENGINE_CE | + D3D12XBOX_FLUSH_TOP_PFP_SYNC_ME, + + D3D12XBOX_FLUSH_BOP_MASK = + D3D12XBOX_FLUSH_BOP_COLOR_BLOCK_DATA | + D3D12XBOX_FLUSH_BOP_DEPTH_BLOCK_DATA | + D3D12XBOX_FLUSH_BOP_COLOR_BLOCK_META | + D3D12XBOX_FLUSH_BOP_DEPTH_BLOCK_META | + D3D12XBOX_FLUSH_BOP_TEXTURE_L1_INVALIDATE | + D3D12XBOX_FLUSH_BOP_TEXTURE_L2_INVALIDATE | + D3D12XBOX_FLUSH_BOP_TEXTURE_L2_WRITEBACK | + D3D12XBOX_FLUSH_BOP_CS_PARTIAL | + D3D12XBOX_FLUSH_BOP_VS_PARTIAL | + D3D12XBOX_FLUSH_BOP_PS_PARTIAL | + D3D12XBOX_FLUSH_BOP_STREAMOUT, + + D3D12XBOX_FLUSH_TOP_COMPUTE_MASK = + D3D12XBOX_FLUSH_TOP_TEXTURE_L1_INVALIDATE | + D3D12XBOX_FLUSH_TOP_TEXTURE_L2_INVALIDATE | + D3D12XBOX_FLUSH_TOP_TEXTURE_L2_WRITEBACK | + D3D12XBOX_FLUSH_TOP_KCACHE_INVALIDATE | + D3D12XBOX_FLUSH_TOP_ICACHE_INVALIDATE, + + D3D12XBOX_FLUSH_BOP_COMPUTE_MASK = + D3D12XBOX_FLUSH_BOP_TEXTURE_L1_INVALIDATE | + D3D12XBOX_FLUSH_BOP_TEXTURE_L2_INVALIDATE | + D3D12XBOX_FLUSH_BOP_TEXTURE_L2_WRITEBACK | + D3D12XBOX_FLUSH_BOP_CS_PARTIAL, + +} D3D12XBOX_FLUSH; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_FLUSH ); + + +typedef enum D3D12XBOX_SYNC_FLAGS : UINT +{ + D3D12XBOX_SYNC_FLAG_NONE = 0x00000000, + + D3D12XBOX_SYNC_FLAG_ICACHE_INVALIDATE = 0x00000001, + D3D12XBOX_SYNC_FLAG_ICACHE_RANGE = 0x00000002, + D3D12XBOX_SYNC_FLAG_ICACHE_MARGIN = 0x00000003, + + D3D12XBOX_SYNC_FLAG_KCACHE_INVALIDATE = 0x00000080, + D3D12XBOX_SYNC_FLAG_VCACHE_INVALIDATE = 0x00000100, + D3D12XBOX_SYNC_FLAG_MCACHE_INVALIDATE = 0x00000020, + D3D12XBOX_SYNC_FLAG_MCACHE_WRITEBACK = 0x00000010, + + D3D12XBOX_SYNC_FLAG_GL0_INVALIDATE = D3D12XBOX_SYNC_FLAG_VCACHE_INVALIDATE, + + D3D12XBOX_SYNC_FLAG_GL1_INVALIDATE = 0x00000200, + D3D12XBOX_SYNC_FLAG_GL1_RANGE = 0x00000008, + D3D12XBOX_SYNC_FLAG_GL1_MARGIN = 0x0000000C, + + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE = 0x00004000, + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE_UNSHARED = 0x00000400, + D3D12XBOX_SYNC_FLAG_GL2_WRITEBACK = 0x00008000, + D3D12XBOX_SYNC_FLAG_GL2_VOLATILE = 0x00000800, + D3D12XBOX_SYNC_FLAG_GL2_RANGE = 0x00001000, + D3D12XBOX_SYNC_FLAG_GL2_MARGIN = 0x00001800, + + D3D12XBOX_SYNC_FLAG_BASE_COHERENCY = 0x01000000, + D3D12XBOX_SYNC_FLAG_COLOR_BLOCK_COHERENCY = 0x40000000, + D3D12XBOX_SYNC_FLAG_DEPTH_BLOCK_COHERENCY = 0x20000000, + D3D12XBOX_SYNC_FLAG_COLOR_BLOCK_INVALIDATE = 0x02000000, + D3D12XBOX_SYNC_FLAG_DEPTH_BLOCK_INVALIDATE = 0x04000000, + + D3D12XBOX_SYNC_FLAG_COLOR_BLOCK_DATA_FLUSH = 0x00040000, + D3D12XBOX_SYNC_FLAG_DEPTH_BLOCK_DATA_FLUSH = 0x00080000, + D3D12XBOX_SYNC_FLAG_COLOR_BLOCK_META_FLUSH = 0x08000000, + D3D12XBOX_SYNC_FLAG_DEPTH_BLOCK_META_FLUSH = 0x10000000, + D3D12XBOX_SYNC_FLAG_CS_PARTIAL_FLUSH = 0x00100000, + D3D12XBOX_SYNC_FLAG_VS_PARTIAL_FLUSH = 0x00200000, + D3D12XBOX_SYNC_FLAG_PS_PARTIAL_FLUSH = 0x00400000, + D3D12XBOX_SYNC_FLAG_STREAMOUT_FLUSH = 0x00800000, + + D3D12XBOX_SYNC_FLAG_PFP_SYNC_ME = 0x00000040, + + D3D12XBOX_SYNC_FLAG_SYNC_CPDMA = 0x00020000, + + D3D12XBOX_SYNC_FLAG_IDLE = 0x80000000, + + D3D12XBOX_SYNC_FLAG_TOP_MASK = + D3D12XBOX_SYNC_FLAG_ICACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_ICACHE_RANGE | + D3D12XBOX_SYNC_FLAG_ICACHE_MARGIN | + D3D12XBOX_SYNC_FLAG_KCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_VCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_MCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_MCACHE_WRITEBACK | + D3D12XBOX_SYNC_FLAG_GL1_INVALIDATE | + D3D12XBOX_SYNC_FLAG_GL1_RANGE | + D3D12XBOX_SYNC_FLAG_GL1_MARGIN | + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE | + D3D12XBOX_SYNC_FLAG_GL2_WRITEBACK | + D3D12XBOX_SYNC_FLAG_GL2_VOLATILE | + D3D12XBOX_SYNC_FLAG_GL2_MARGIN | + D3D12XBOX_SYNC_FLAG_GL2_RANGE | + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE_UNSHARED | + D3D12XBOX_SYNC_FLAG_BASE_COHERENCY | + D3D12XBOX_SYNC_FLAG_COLOR_BLOCK_COHERENCY | + D3D12XBOX_SYNC_FLAG_DEPTH_BLOCK_COHERENCY | + D3D12XBOX_SYNC_FLAG_COLOR_BLOCK_INVALIDATE | + D3D12XBOX_SYNC_FLAG_DEPTH_BLOCK_INVALIDATE | + D3D12XBOX_SYNC_FLAG_PFP_SYNC_ME | + D3D12XBOX_SYNC_FLAG_SYNC_CPDMA | + D3D12XBOX_SYNC_FLAG_IDLE, + + D3D12XBOX_SYNC_FLAG_BOP_MASK = + D3D12XBOX_SYNC_FLAG_VCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_MCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_MCACHE_WRITEBACK | + D3D12XBOX_SYNC_FLAG_GL1_INVALIDATE | + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE | + D3D12XBOX_SYNC_FLAG_GL2_WRITEBACK | + D3D12XBOX_SYNC_FLAG_GL2_VOLATILE | + D3D12XBOX_SYNC_FLAG_GL2_RANGE | + D3D12XBOX_SYNC_FLAG_GL2_MARGIN | + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE_UNSHARED | + D3D12XBOX_SYNC_FLAG_COLOR_BLOCK_DATA_FLUSH | + D3D12XBOX_SYNC_FLAG_DEPTH_BLOCK_DATA_FLUSH | + D3D12XBOX_SYNC_FLAG_COLOR_BLOCK_META_FLUSH | + D3D12XBOX_SYNC_FLAG_DEPTH_BLOCK_META_FLUSH | + D3D12XBOX_SYNC_FLAG_CS_PARTIAL_FLUSH | + D3D12XBOX_SYNC_FLAG_VS_PARTIAL_FLUSH | + D3D12XBOX_SYNC_FLAG_PS_PARTIAL_FLUSH | + D3D12XBOX_SYNC_FLAG_STREAMOUT_FLUSH | + D3D12XBOX_SYNC_FLAG_PFP_SYNC_ME | + D3D12XBOX_SYNC_FLAG_SYNC_CPDMA | + D3D12XBOX_SYNC_FLAG_IDLE, + + D3D12XBOX_SYNC_FLAG_TOP_COMPUTE_MASK = + D3D12XBOX_SYNC_FLAG_ICACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_ICACHE_RANGE | + D3D12XBOX_SYNC_FLAG_ICACHE_MARGIN | + D3D12XBOX_SYNC_FLAG_KCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_VCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_MCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_MCACHE_WRITEBACK | + D3D12XBOX_SYNC_FLAG_GL1_INVALIDATE | + D3D12XBOX_SYNC_FLAG_GL1_RANGE | + D3D12XBOX_SYNC_FLAG_GL1_MARGIN | + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE | + D3D12XBOX_SYNC_FLAG_GL2_WRITEBACK | + D3D12XBOX_SYNC_FLAG_GL2_VOLATILE | + D3D12XBOX_SYNC_FLAG_GL2_RANGE | + D3D12XBOX_SYNC_FLAG_GL2_MARGIN | + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE_UNSHARED | + D3D12XBOX_SYNC_FLAG_SYNC_CPDMA, + + D3D12XBOX_SYNC_FLAG_BOP_COMPUTE_MASK = + D3D12XBOX_SYNC_FLAG_VCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_MCACHE_INVALIDATE | + D3D12XBOX_SYNC_FLAG_MCACHE_WRITEBACK | + D3D12XBOX_SYNC_FLAG_GL1_INVALIDATE | + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE | + D3D12XBOX_SYNC_FLAG_GL2_WRITEBACK | + D3D12XBOX_SYNC_FLAG_GL2_VOLATILE | + D3D12XBOX_SYNC_FLAG_GL2_RANGE | + D3D12XBOX_SYNC_FLAG_GL2_MARGIN | + D3D12XBOX_SYNC_FLAG_GL2_INVALIDATE_UNSHARED | + D3D12XBOX_SYNC_FLAG_CS_PARTIAL_FLUSH, + + +} D3D12XBOX_SYNC_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_SYNC_FLAGS ); + +typedef enum D3D12XBOX_SYNC_CONTROL_FLAGS : UINT +{ + D3D12XBOX_SYNC_CONTROL_FLAG_NONE = 0x00000000, + + D3D12XBOX_SYNC_CONTROL_FLAG_TOP_SELECT_ENGINE_PFP = 0x80000000, + D3D12XBOX_SYNC_CONTROL_FLAG_TOP_SELECT_ENGINE_CE = 0x40000000, + + D3D12XBOX_SYNC_CONTROL_FLAG_IDLE_SELECT_ENGINE_PFP = 0x20000000, + D3D12XBOX_SYNC_CONTROL_FLAG_IDLE_SELECT_ENGINE_CE = + D3D12XBOX_SYNC_CONTROL_FLAG_TOP_SELECT_ENGINE_CE, + + D3D12XBOX_SYNC_CONTROL_FLAG_CPDMA_SELECT_ENGINE_PFP = 0x01000000, + + D3D12XBOX_SYNC_CONTROL_FLAG_GCR_SEQUENCE_FORWARD = 0x00010000, + D3D12XBOX_SYNC_CONTROL_FLAG_GCR_SEQUENCE_REVERSE = 0x00020000, + + +} D3D12XBOX_SYNC_CONTROL_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_SYNC_CONTROL_FLAGS ); + +typedef struct D3D12XBOX_SYNC_PARAMS +{ + D3D12XBOX_SYNC_FLAGS SyncFlags; + D3D12XBOX_SYNC_CONTROL_FLAGS ControlFlags; + D3D12_GPU_VIRTUAL_ADDRESS BaseAddress; + SIZE_T SizeInBytes; +} D3D12XBOX_SYNC_PARAMS; + +// If full memory range needs to be specified, then specify this size with a nullptr for pBaseAddress into FlushPipelineX, +// SyncTopOfPipeX, or SyncBottomOfPipeX. Try to specify the realistic resource size if the pBaseAddress is not a nullptr. + +#define D3D12XBOX_FLUSH_RANGE_ALL 0xFFFFFFFFFF00ull + + +typedef enum D3D12_RESOURCE_STATES +{ + D3D12_RESOURCE_STATE_COMMON = 0, + + D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER = 0x0001, + D3D12_RESOURCE_STATE_INDEX_BUFFER = 0x0002, + D3D12_RESOURCE_STATE_RENDER_TARGET = 0x0004, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS = 0x0008, + D3D12_RESOURCE_STATE_DEPTH_WRITE = 0x0010, + D3D12_RESOURCE_STATE_DEPTH_READ = 0x0020, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE = 0x0040, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE = 0x0080, + D3D12_RESOURCE_STATE_STREAM_OUT = 0x0100, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT = 0x0200, + D3D12_RESOURCE_STATE_COPY_DEST = 0x0400, + D3D12_RESOURCE_STATE_COPY_SOURCE = 0x0800, + D3D12_RESOURCE_STATE_RESOLVE_DEST = 0x1000, + D3D12_RESOURCE_STATE_RESOLVE_SOURCE = 0x2000, + D3D12_RESOURCE_STATE_PRESENT = 0x100000, + D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE = 0x400000, + D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE = 0x1000000, + + D3D12_RESOURCE_STATE_VIDEO_DECODE_READ = 0x10000, + D3D12_RESOURCE_STATE_VIDEO_DECODE_WRITE = 0x20000, + D3D12_RESOURCE_STATE_VIDEO_PROCESS_READ = 0x40000, + D3D12_RESOURCE_STATE_VIDEO_PROCESS_WRITE = 0x80000, + D3D12_RESOURCE_STATE_VIDEO_ENCODE_READ = 0x200000, + D3D12_RESOURCE_STATE_VIDEO_ENCODE_WRITE = 0x800000, + + D3D12_RESOURCE_STATE_GENERIC_READ = + D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER | + D3D12_RESOURCE_STATE_INDEX_BUFFER | + D3D12_RESOURCE_STATE_COPY_SOURCE | + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + + D3D12_RESOURCE_STATE_PREDICATION = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + + D3D12XBOX_RESOURCE_STATE_PRESERVE_COMPRESSED_COLOR = 0x10000000, + D3D12XBOX_RESOURCE_STATE_PRESERVE_COMPRESSED_DEPTH = 0x10000000, + D3D12XBOX_RESOURCE_STATE_PRESERVE_COMPRESSED_STENCIL = 0x20000000, + D3D12XBOX_RESOURCE_STATE_PRESERVE_COMPRESSED_DEPTH_STENCIL = + D3D12XBOX_RESOURCE_STATE_PRESERVE_COMPRESSED_DEPTH | + D3D12XBOX_RESOURCE_STATE_PRESERVE_COMPRESSED_STENCIL, + D3D12XBOX_RESOURCE_STATE_PRESERVE_INDIRECT_COLOR_CLEAR = 0x40000000, + D3D12XBOX_RESOURCE_STATE_PRESERVE_SCATTERED_COLOR_FMASK = 0x02000000, + D3D12XBOX_RESOURCE_STATE_PRESERVE_DCC = 0x20000000, + + D3D12XBOX_RESOURCE_STATE_PRESERVE_EXPANDED_COLOR = 0x04000000, + D3D12XBOX_RESOURCE_STATE_PRESERVE_EXPANDED_DEPTH = 0x04000000, + D3D12XBOX_RESOURCE_STATE_PRESERVE_EXPANDED_STENCIL = 0x08000000, + D3D12XBOX_RESOURCE_STATE_PRESERVE_EXPANDED_DEPTH_STENCIL = + D3D12XBOX_RESOURCE_STATE_PRESERVE_EXPANDED_DEPTH | + D3D12XBOX_RESOURCE_STATE_PRESERVE_EXPANDED_STENCIL, + +} D3D12_RESOURCE_STATES; +DEFINE_ENUM_FLAG_OPERATORS( D3D12_RESOURCE_STATES ); + +typedef enum D3D12_RESOURCE_BARRIER_TYPE +{ + D3D12_RESOURCE_BARRIER_TYPE_TRANSITION = 0, + D3D12_RESOURCE_BARRIER_TYPE_ALIASING = 1, + D3D12_RESOURCE_BARRIER_TYPE_UAV = 2 +} D3D12_RESOURCE_BARRIER_TYPE; + +typedef struct D3D12_RESOURCE_TRANSITION_BARRIER +{ + ID3D12Resource* pResource; + UINT Subresource; + D3D12_RESOURCE_STATES StateBefore; + D3D12_RESOURCE_STATES StateAfter; +} D3D12_RESOURCE_TRANSITION_BARRIER; + +typedef struct D3D12_RESOURCE_ALIASING_BARRIER +{ + ID3D12Resource* pResourceBefore; + ID3D12Resource* pResourceAfter; +} D3D12_RESOURCE_ALIASING_BARRIER; + +typedef struct D3D12_RESOURCE_UAV_BARRIER +{ + ID3D12Resource* pResource; +} D3D12_RESOURCE_UAV_BARRIER; + +typedef enum D3D12_RESOURCE_BARRIER_FLAGS +{ + D3D12_RESOURCE_BARRIER_FLAG_NONE = 0x0, + D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY = 0x1, + D3D12_RESOURCE_BARRIER_FLAG_END_ONLY = 0x2, + D3D12XBOX_RESOURCE_BARRIER_FLAG_PREVENT_PIPELINE_FLUSH = 0x00010000, +} D3D12_RESOURCE_BARRIER_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS( D3D12_RESOURCE_BARRIER_FLAGS ); + +typedef struct D3D12_RESOURCE_BARRIER +{ + D3D12_RESOURCE_BARRIER_TYPE Type; + D3D12_RESOURCE_BARRIER_FLAGS Flags; + union + { + D3D12_RESOURCE_TRANSITION_BARRIER Transition; + D3D12_RESOURCE_ALIASING_BARRIER Aliasing; + D3D12_RESOURCE_UAV_BARRIER UAV; + }; +} D3D12_RESOURCE_BARRIER; + +typedef enum D3D12XBOX_RESOURCE_BARRIER_ACTIONS : UINT64 +{ + D3D12XBOX_RESOURCE_BARRIER_ACTION_NONE = 0, + + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_BASE_COHERENCY = D3D12XBOX_FLUSH_TOP_BASE_COHERENCY, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_COLOR_BLOCK_COHERENCY = D3D12XBOX_FLUSH_TOP_COLOR_BLOCK_COHERENCY, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_DEPTH_BLOCK_COHERENCY = D3D12XBOX_FLUSH_TOP_DEPTH_BLOCK_COHERENCY, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_COLOR_BLOCK_INVALIDATE = D3D12XBOX_FLUSH_TOP_COLOR_BLOCK_INVALIDATE, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_DEPTH_BLOCK_INVALIDATE = D3D12XBOX_FLUSH_TOP_DEPTH_BLOCK_INVALIDATE, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_TEXTURE_L1_INVALIDATE = D3D12XBOX_FLUSH_TOP_TEXTURE_L1_INVALIDATE, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_TEXTURE_L2_INVALIDATE = D3D12XBOX_FLUSH_TOP_TEXTURE_L2_INVALIDATE, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_TEXTURE_L2_WRITEBACK = D3D12XBOX_FLUSH_TOP_TEXTURE_L2_WRITEBACK, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_KCACHE_INVALIDATE = D3D12XBOX_FLUSH_TOP_KCACHE_INVALIDATE, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_ICACHE_INVALIDATE = D3D12XBOX_FLUSH_TOP_ICACHE_INVALIDATE, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_SELECT_ENGINE_PFP = D3D12XBOX_FLUSH_TOP_SELECT_ENGINE_PFP, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_SELECT_ENGINE_CE = D3D12XBOX_FLUSH_TOP_SELECT_ENGINE_CE, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_PFP_SYNC_ME = D3D12XBOX_FLUSH_TOP_PFP_SYNC_ME, + + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_COLOR_BLOCK_DATA = D3D12XBOX_FLUSH_BOP_COLOR_BLOCK_DATA, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_DEPTH_BLOCK_DATA = D3D12XBOX_FLUSH_BOP_DEPTH_BLOCK_DATA, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_COLOR_BLOCK_META = D3D12XBOX_FLUSH_BOP_COLOR_BLOCK_META, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_DEPTH_BLOCK_META = D3D12XBOX_FLUSH_BOP_DEPTH_BLOCK_META, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_TEXTURE_L1_INVALIDATE = D3D12XBOX_FLUSH_BOP_TEXTURE_L1_INVALIDATE, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_TEXTURE_L2_INVALIDATE = D3D12XBOX_FLUSH_BOP_TEXTURE_L2_INVALIDATE, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_TEXTURE_L2_WRITEBACK = D3D12XBOX_FLUSH_BOP_TEXTURE_L2_WRITEBACK, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_CS_PARTIAL = D3D12XBOX_FLUSH_BOP_CS_PARTIAL, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_VS_PARTIAL = D3D12XBOX_FLUSH_BOP_VS_PARTIAL, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_PS_PARTIAL = D3D12XBOX_FLUSH_BOP_PS_PARTIAL, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_STREAMOUT = D3D12XBOX_FLUSH_BOP_STREAMOUT, + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_IDLE = D3D12XBOX_FLUSH_IDLE, + + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_EXPAND_COLOR = 0x000100000000, + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_EXPAND_DEPTH = 0x000200000000, + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_EXPAND_STENCIL = 0x000400000000, + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_EXPAND_DEPTH_STENCIL = 0x000600000000, + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_PROPAGATE_COLOR_CLEAR = 0x000800000000, + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_GATHER_COLOR_FMASK = 0x001000000000, + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_ELIMINATE_DCC = 0x002000000000, + + D3D12XBOX_RESOURCE_BARRIER_ACTION_WAIT_FOR_DISPLAY = 0x100000000000, + D3D12XBOX_RESOURCE_BARRIER_ACTION_WAIT_FOR_RESOURCE = 0x200000000000, + + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_MASK = + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_BASE_COHERENCY | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_COLOR_BLOCK_COHERENCY | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_DEPTH_BLOCK_COHERENCY | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_COLOR_BLOCK_INVALIDATE | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_DEPTH_BLOCK_INVALIDATE | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_TEXTURE_L1_INVALIDATE | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_TEXTURE_L2_INVALIDATE | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_TEXTURE_L2_WRITEBACK | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_KCACHE_INVALIDATE | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_ICACHE_INVALIDATE | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_SELECT_ENGINE_PFP | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_TOP_PFP_SYNC_ME, + + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_MASK = + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_COLOR_BLOCK_DATA | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_DEPTH_BLOCK_DATA | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_COLOR_BLOCK_META | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_DEPTH_BLOCK_META | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_TEXTURE_L1_INVALIDATE | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_TEXTURE_L2_INVALIDATE | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_TEXTURE_L2_WRITEBACK | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_CS_PARTIAL | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_VS_PARTIAL | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_PS_PARTIAL | + D3D12XBOX_RESOURCE_BARRIER_ACTION_FLUSH_BOP_STREAMOUT, + + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_MASK = + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_EXPAND_COLOR | + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_EXPAND_DEPTH | + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_EXPAND_STENCIL | + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_PROPAGATE_COLOR_CLEAR | + D3D12XBOX_RESOURCE_BARRIER_ACTION_DECOMPRESS_GATHER_COLOR_FMASK, + + D3D12XBOX_RESOURCE_BARRIER_ACTION_WAIT_MASK = + D3D12XBOX_RESOURCE_BARRIER_ACTION_WAIT_FOR_DISPLAY | + D3D12XBOX_RESOURCE_BARRIER_ACTION_WAIT_FOR_RESOURCE, +} D3D12XBOX_RESOURCE_BARRIER_ACTIONS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_RESOURCE_BARRIER_ACTIONS ); + +// Mask off compression-related activity from a set of resource barrier actions and convert to a set +// of flushes that may be given to FlushPipelineX + +inline D3D12XBOX_FLUSH D3D12GetFlushFromResourceBarrierActionsX( + D3D12XBOX_RESOURCE_BARRIER_ACTIONS Actions) +{ + return (D3D12XBOX_FLUSH)Actions; +} + +typedef enum D3D12XBOX_RESOURCE_BARRIER_SHARED_FLAGS +{ + D3D12XBOX_RESOURCE_BARRIER_SHARED_FLAG_NONE = 0x0, + D3D12XBOX_RESOURCE_BARRIER_SHARED_FLAG_PREVENT_PIPELINE_SYNC = 0x00010000, +} D3D12XBOX_RESOURCE_BARRIER_SHARED_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_RESOURCE_BARRIER_SHARED_FLAGS ); + +typedef enum D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTIONS : UINT32 +{ + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_NONE = 0, + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_DECOMPRESS_EXPAND_COLOR = 0x0001, + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_DECOMPRESS_EXPAND_DEPTH = 0x0002, + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_DECOMPRESS_EXPAND_STENCIL = 0x0004, + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_DECOMPRESS_EXPAND_DEPTH_STENCIL = 0x0006, + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_DECOMPRESS_PROPAGATE_COLOR_CLEAR = 0x0008, + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_DECOMPRESS_GATHER_COLOR_FMASK = 0x0010, + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_DECOMPRESS_ELIMINATE_DCC = 0x0020, + + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_WAIT_FOR_DISPLAY = 0x1000, + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTION_WAIT_FOR_RESOURCE = 0x2000, +} D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTIONS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTIONS ); + +typedef struct D3D12XBOX_RESOURCE_BARRIER_SUMMARY_ACTIONS +{ + D3D12XBOX_SYNC_PARAMS SyncBottomOfPipe; + D3D12XBOX_SYNC_PARAMS SyncTopOfPipe; + D3D12XBOX_RESOURCE_BARRIER_SUPPLEMENTAL_ACTIONS Supplemental; +} D3D12XBOX_RESOURCE_BARRIER_SUMMARY_ACTIONS; + +typedef struct D3D12_SUBRESOURCE_FOOTPRINT +{ + DXGI_FORMAT Format; + UINT Width; + UINT Height; + UINT Depth; + UINT RowPitch; // Must be a multiple of D3D12XBOX_TEXTURE_DATA_PITCH_ALIGNMENT +} D3D12_SUBRESOURCE_FOOTPRINT; + +typedef enum D3D12XBOX_SET_SHADER_SCRATCH_SPACE_FLAGS +{ + D3D12XBOX_SET_SHADER_SCRATCH_SPACE_FLAGS_GRAPHICS = 0x1, + D3D12XBOX_SET_SHADER_SCRATCH_SPACE_FLAGS_COMPUTE = 0x2, + D3D12XBOX_SET_SHADER_SCRATCH_SPACE_FLAGS_W32 = 0x4 // Driver default is W64 at new command list, should always restore, changes stride in the scratch descriptor +} D3D12XBOX_SET_SHADER_SCRATCH_SPACE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_SET_SHADER_SCRATCH_SPACE_FLAGS); + +} + +extern "C" +{ + +typedef struct D3D12_PLACED_SUBRESOURCE_FOOTPRINT +{ + UINT64 Offset; + D3D12_SUBRESOURCE_FOOTPRINT Footprint; +} D3D12_PLACED_SUBRESOURCE_FOOTPRINT; + +typedef enum D3D12_TEXTURE_COPY_TYPE +{ + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX = 0, + D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT = 1 +} D3D12_TEXTURE_COPY_TYPE; + +typedef struct D3D12_TEXTURE_COPY_LOCATION +{ + ID3D12Resource* pResource; + D3D12_TEXTURE_COPY_TYPE Type; + union + { + D3D12_PLACED_SUBRESOURCE_FOOTPRINT PlacedFootprint; + UINT SubresourceIndex; + }; +} D3D12_TEXTURE_COPY_LOCATION; + +typedef enum D3D12_RESOLVE_MODE +{ + D3D12_RESOLVE_MODE_DECOMPRESS = 0, + D3D12_RESOLVE_MODE_MIN = 1, + D3D12_RESOLVE_MODE_MAX = 2, + D3D12_RESOLVE_MODE_AVERAGE = 3, + D3D12_RESOLVE_MODE_ENCODE_SAMPLER_FEEDBACK = 4, + D3D12_RESOLVE_MODE_DECODE_SAMPLER_FEEDBACK = 5 +} D3D12_RESOLVE_MODE; + +typedef struct D3D12_SAMPLE_POSITION +{ + INT8 X; + INT8 Y; +} D3D12_SAMPLE_POSITION; + +typedef struct D3D12_VIEW_INSTANCE_LOCATION +{ + UINT ViewportArrayIndex; + UINT RenderTargetArrayIndex; +} D3D12_VIEW_INSTANCE_LOCATION; + +typedef enum D3D12_VIEW_INSTANCING_FLAGS +{ + D3D12_VIEW_INSTANCING_FLAG_NONE = 0, + D3D12_VIEW_INSTANCING_FLAG_ENABLE_VIEW_INSTANCE_MASKING = 0x1 +} D3D12_VIEW_INSTANCING_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_VIEW_INSTANCING_FLAGS ); + +typedef struct D3D12_VIEW_INSTANCING_DESC +{ + UINT ViewInstanceCount; + _Field_size_full_(ViewInstanceCount) const D3D12_VIEW_INSTANCE_LOCATION* pViewInstanceLocations; + D3D12_VIEW_INSTANCING_FLAGS Flags; +} D3D12_VIEW_INSTANCING_DESC; + +} + +extern "C" +{ + +typedef enum D3D12_SHADER_COMPONENT_MAPPING +{ + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_0 = 0, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_1 = 1, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_2 = 2, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_3 = 3, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 = 4, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1 = 5, +} D3D12_SHADER_COMPONENT_MAPPING; + +#define D3D12_SHADER_COMPONENT_MAPPING_MASK 0x7 +#define D3D12_SHADER_COMPONENT_MAPPING_SHIFT 3 +#define D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES (1<<(D3D12_SHADER_COMPONENT_MAPPING_SHIFT*4)) +#define D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(Src0,Src1,Src2,Src3) \ + ((((Src0)&D3D12_SHADER_COMPONENT_MAPPING_MASK)| \ + (((Src1)&D3D12_SHADER_COMPONENT_MAPPING_MASK)<> (D3D12_SHADER_COMPONENT_MAPPING_SHIFT*ComponentToExtract) & D3D12_SHADER_COMPONENT_MAPPING_MASK)) +#define D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0,1,2,3) + +typedef enum D3D12_BUFFER_SRV_FLAGS +{ + D3D12_BUFFER_SRV_FLAG_NONE = 0x0, + D3D12_BUFFER_SRV_FLAG_RAW = 0x1, + D3D12XBOX_BUFFER_SRV_FLAG_STRIDED_TYPED = 0x2 // NumElements becomes offset in bytes, StructureByteStride is allowed with a known format +} D3D12_BUFFER_SRV_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_BUFFER_SRV_FLAGS ); + +typedef struct D3D12_BUFFER_SRV +{ + UINT64 FirstElement; + UINT NumElements; + UINT StructureByteStride; + D3D12_BUFFER_SRV_FLAGS Flags; +} D3D12_BUFFER_SRV; + +typedef struct D3D12_TEX1D_SRV +{ + UINT MostDetailedMip; + UINT MipLevels; + FLOAT ResourceMinLODClamp; +} D3D12_TEX1D_SRV; + +typedef struct D3D12_TEX1D_ARRAY_SRV +{ + UINT MostDetailedMip; + UINT MipLevels; + UINT FirstArraySlice; + UINT ArraySize; + FLOAT ResourceMinLODClamp; +} D3D12_TEX1D_ARRAY_SRV; + +typedef struct D3D12_TEX2D_SRV +{ + UINT MostDetailedMip; + UINT MipLevels; + UINT PlaneSlice; + FLOAT ResourceMinLODClamp; +} D3D12_TEX2D_SRV; + +typedef struct D3D12_TEX2D_ARRAY_SRV +{ + UINT MostDetailedMip; + UINT MipLevels; + UINT FirstArraySlice; + UINT ArraySize; + UINT PlaneSlice; + FLOAT ResourceMinLODClamp; +} D3D12_TEX2D_ARRAY_SRV; + +typedef struct D3D12_TEX3D_SRV +{ + UINT MostDetailedMip; + UINT MipLevels; + FLOAT ResourceMinLODClamp; +} D3D12_TEX3D_SRV; + +typedef struct D3D12_TEXCUBE_SRV +{ + UINT MostDetailedMip; + UINT MipLevels; + FLOAT ResourceMinLODClamp; +} D3D12_TEXCUBE_SRV; + +typedef struct D3D12_TEXCUBE_ARRAY_SRV +{ + UINT MostDetailedMip; + UINT MipLevels; + UINT First2DArrayFace; + UINT NumCubes; + FLOAT ResourceMinLODClamp; +} D3D12_TEXCUBE_ARRAY_SRV; + +typedef struct D3D12_TEX2DMS_SRV +{ + UINT UnusedField_NothingToDefine; +} D3D12_TEX2DMS_SRV; + +typedef struct D3D12_TEX2DMS_ARRAY_SRV +{ + UINT FirstArraySlice; + UINT ArraySize; +} D3D12_TEX2DMS_ARRAY_SRV; + +typedef struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_SRV +{ + D3D12_GPU_VIRTUAL_ADDRESS Location; +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_SRV; + +typedef enum D3D12_SRV_DIMENSION +{ + D3D12_SRV_DIMENSION_UNKNOWN = 0, + D3D12_SRV_DIMENSION_BUFFER = 1, + D3D12_SRV_DIMENSION_TEXTURE1D = 2, + D3D12_SRV_DIMENSION_TEXTURE1DARRAY = 3, + D3D12_SRV_DIMENSION_TEXTURE2D = 4, + D3D12_SRV_DIMENSION_TEXTURE2DARRAY = 5, + D3D12_SRV_DIMENSION_TEXTURE2DMS = 6, + D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D12_SRV_DIMENSION_TEXTURE3D = 8, + D3D12_SRV_DIMENSION_TEXTURECUBE = 9, + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY = 10, + D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE = 11 +} D3D12_SRV_DIMENSION; + +typedef struct D3D12_SHADER_RESOURCE_VIEW_DESC +{ + DXGI_FORMAT Format; + D3D12_SRV_DIMENSION ViewDimension; + UINT Shader4ComponentMapping; + union + { + D3D12_BUFFER_SRV Buffer; + D3D12_TEX1D_SRV Texture1D; + D3D12_TEX1D_ARRAY_SRV Texture1DArray; + D3D12_TEX2D_SRV Texture2D; + D3D12_TEX2D_ARRAY_SRV Texture2DArray; + D3D12_TEX2DMS_SRV Texture2DMS; + D3D12_TEX2DMS_ARRAY_SRV Texture2DMSArray; + D3D12_TEX3D_SRV Texture3D; + D3D12_TEXCUBE_SRV TextureCube; + D3D12_TEXCUBE_ARRAY_SRV TextureCubeArray; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_SRV RaytracingAccelerationStructure; + }; +} D3D12_SHADER_RESOURCE_VIEW_DESC; + +typedef struct D3D12XBOX_SHADER_RESOURCE_VIEW_DESC +{ + DXGI_FORMAT Format; + D3D12_SRV_DIMENSION ViewDimension; + UINT Shader4ComponentMapping; + union + { + D3D12_BUFFER_SRV Buffer; + D3D12_TEX1D_SRV Texture1D; + D3D12_TEX1D_ARRAY_SRV Texture1DArray; + D3D12_TEX2D_SRV Texture2D; + D3D12_TEX2D_ARRAY_SRV Texture2DArray; + D3D12_TEX2DMS_SRV Texture2DMS; + D3D12_TEX2DMS_ARRAY_SRV Texture2DMSArray; + D3D12_TEX3D_SRV Texture3D; + D3D12_TEXCUBE_SRV TextureCube; + D3D12_TEXCUBE_ARRAY_SRV TextureCubeArray; + }; + D3D12_GPU_VIRTUAL_ADDRESS ResourceLocation; + D3D12XBOX_IMAGE_FORMAT ImageFormat; + UINT MemoryType; + FLOAT TextureWarnLevelOfDetail; + INT TexturePerfModulation; +} D3D12XBOX_SHADER_RESOURCE_VIEW_DESC; + +typedef struct D3D12_CONSTANT_BUFFER_VIEW_DESC +{ + D3D12_GPU_VIRTUAL_ADDRESS BufferLocation; + UINT SizeInBytes; +} D3D12_CONSTANT_BUFFER_VIEW_DESC; + +typedef enum D3D12_FILTER +{ + D3D12_FILTER_MIN_MAG_MIP_POINT = 0, + D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1, + D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4, + D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5, + D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10, + D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11, + D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14, + D3D12_FILTER_MIN_MAG_MIP_LINEAR = 0x15, + D3D12_FILTER_ANISOTROPIC = 0x55, + D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80, + D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81, + D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84, + D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85, + D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90, + D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91, + D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94, + D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95, + D3D12_FILTER_COMPARISON_ANISOTROPIC = 0xd5, + D3D12_FILTER_MINIMUM_MIN_MAG_MIP_POINT = 0x100, + D3D12_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101, + D3D12_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104, + D3D12_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105, + D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110, + D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111, + D3D12_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114, + D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR = 0x115, + D3D12_FILTER_MINIMUM_ANISOTROPIC = 0x155, + D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_POINT = 0x180, + D3D12_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181, + D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184, + D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185, + D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190, + D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191, + D3D12_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194, + D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195, + D3D12_FILTER_MAXIMUM_ANISOTROPIC = 0x1d5 +} D3D12_FILTER; + +typedef enum D3D12_FILTER_TYPE +{ + D3D12_FILTER_TYPE_POINT = 0, + D3D12_FILTER_TYPE_LINEAR = 1 +} D3D12_FILTER_TYPE; + +typedef enum D3D12_FILTER_REDUCTION_TYPE +{ + D3D12_FILTER_REDUCTION_TYPE_STANDARD = 0, + D3D12_FILTER_REDUCTION_TYPE_COMPARISON = 1, + D3D12_FILTER_REDUCTION_TYPE_MINIMUM = 2, + D3D12_FILTER_REDUCTION_TYPE_MAXIMUM = 3 +} D3D12_FILTER_REDUCTION_TYPE; + +#define D3D12_FILTER_REDUCTION_TYPE_MASK ( 0x3 ) + +#define D3D12_FILTER_REDUCTION_TYPE_SHIFT ( 7 ) + +#define D3D12_FILTER_TYPE_MASK ( 0x3 ) + +#define D3D12_MIN_FILTER_SHIFT ( 4 ) + +#define D3D12_MAG_FILTER_SHIFT ( 2 ) + +#define D3D12_MIP_FILTER_SHIFT ( 0 ) + +#define D3D12_ANISOTROPIC_FILTERING_BIT ( 0x40 ) + +#define D3D12_ENCODE_BASIC_FILTER( min, mag, mip, reduction ) \ + ( ( D3D12_FILTER ) ( \ + ( ( ( min ) & D3D12_FILTER_TYPE_MASK ) << D3D12_MIN_FILTER_SHIFT ) | \ + ( ( ( mag ) & D3D12_FILTER_TYPE_MASK ) << D3D12_MAG_FILTER_SHIFT ) | \ + ( ( ( mip ) & D3D12_FILTER_TYPE_MASK ) << D3D12_MIP_FILTER_SHIFT ) | \ + ( ( ( reduction ) & D3D12_FILTER_REDUCTION_TYPE_MASK ) << D3D12_FILTER_REDUCTION_TYPE_SHIFT ) ) ) +#define D3D12_ENCODE_ANISOTROPIC_FILTER( reduction ) \ + ( ( D3D12_FILTER ) ( \ + D3D12_ANISOTROPIC_FILTERING_BIT | \ + D3D12_ENCODE_BASIC_FILTER( D3D12_FILTER_TYPE_LINEAR, \ + D3D12_FILTER_TYPE_LINEAR, \ + D3D12_FILTER_TYPE_LINEAR, \ + reduction ) ) ) +#define D3D12_DECODE_MIN_FILTER( D3D12Filter ) \ + ( ( D3D12_FILTER_TYPE ) \ + ( ( ( D3D12Filter ) >> D3D12_MIN_FILTER_SHIFT ) & D3D12_FILTER_TYPE_MASK ) ) +#define D3D12_DECODE_MAG_FILTER( D3D12Filter ) \ + ( ( D3D12_FILTER_TYPE ) \ + ( ( ( D3D12Filter ) >> D3D12_MAG_FILTER_SHIFT ) & D3D12_FILTER_TYPE_MASK ) ) +#define D3D12_DECODE_MIP_FILTER( D3D12Filter ) \ + ( ( D3D12_FILTER_TYPE ) \ + ( ( ( D3D12Filter ) >> D3D12_MIP_FILTER_SHIFT ) & D3D12_FILTER_TYPE_MASK ) ) +#define D3D12_DECODE_FILTER_REDUCTION( D3D12Filter ) \ + ( ( D3D12_FILTER_REDUCTION_TYPE ) \ + ( ( ( D3D12Filter ) >> D3D12_FILTER_REDUCTION_TYPE_SHIFT ) & D3D12_FILTER_REDUCTION_TYPE_MASK ) ) +#define D3D12_DECODE_IS_COMPARISON_FILTER( D3D12Filter ) \ + ( D3D12_DECODE_FILTER_REDUCTION( D3D12Filter ) == D3D12_FILTER_REDUCTION_TYPE_COMPARISON ) +#define D3D12_DECODE_IS_ANISOTROPIC_FILTER( D3D12Filter ) \ + ( ( ( D3D12Filter ) & D3D12_ANISOTROPIC_FILTERING_BIT ) && \ + ( D3D12_FILTER_TYPE_LINEAR == D3D12_DECODE_MIN_FILTER( D3D12Filter ) ) && \ + ( D3D12_FILTER_TYPE_LINEAR == D3D12_DECODE_MAG_FILTER( D3D12Filter ) ) && \ + ( D3D12_FILTER_TYPE_LINEAR == D3D12_DECODE_MIP_FILTER( D3D12Filter ) ) ) + +typedef enum D3D12_TEXTURE_ADDRESS_MODE +{ + D3D12_TEXTURE_ADDRESS_MODE_WRAP = 1, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR = 2, + D3D12_TEXTURE_ADDRESS_MODE_CLAMP = 3, + D3D12_TEXTURE_ADDRESS_MODE_BORDER = 4, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE = 5, + D3D12XBOX_TEXTURE_ADDRESS_MODE_HALF_BORDER = 6, + D3D12XBOX_TEXTURE_ADDRESS_HALF_BORDER = D3D12XBOX_TEXTURE_ADDRESS_MODE_HALF_BORDER, + D3D12XBOX_TEXTURE_ADDRESS_MODE_MIRROR_ONCE_BORDER = 7, + D3D12XBOX_TEXTURE_ADDRESS_MIRROR_ONCE_BORDER = D3D12XBOX_TEXTURE_ADDRESS_MODE_MIRROR_ONCE_BORDER, + D3D12XBOX_TEXTURE_ADDRESS_MODE_MIRROR_ONCE_HALF_BORDER = 8, + D3D12XBOX_TEXTURE_ADDRESS_MIRROR_ONCE_HALF_BORDER = D3D12XBOX_TEXTURE_ADDRESS_MODE_MIRROR_ONCE_HALF_BORDER +} D3D12_TEXTURE_ADDRESS_MODE; + +typedef enum D3D12XBOX_TEXTURE_FILTER_MODE : UINT +{ + D3D12XBOX_TEXTURE_FILTER_MODE_LERP = 0, + D3D12XBOX_TEXTURE_FILTER_MODE_MIN = 1, + D3D12XBOX_TEXTURE_FILTER_MODE_MAX = 2, +} D3D12XBOX_TEXTURE_FILTER_MODE; + +typedef enum D3D12XBOX_TEXTURE_XY_FILTER : UINT +{ + D3D12XBOX_TEXTURE_XY_FILTER_POINT = 0, + D3D12XBOX_TEXTURE_XY_FILTER_BILINEAR = 1, + D3D12XBOX_TEXTURE_XY_FILTER_ANISO_POINT = 2, + D3D12XBOX_TEXTURE_XY_FILTER_ANISO_BILINEAR = 3, +} D3D12XBOX_TEXTURE_XY_FILTER; + +typedef enum D3D12XBOX_TEXTURE_Z_FILTER : UINT +{ + D3D12XBOX_TEXTURE_Z_FILTER_NONE = 0, + D3D12XBOX_TEXTURE_Z_FILTER_POINT = 1, + D3D12XBOX_TEXTURE_Z_FILTER_LINEAR = 2, +} D3D12XBOX_TEXTURE_Z_FILTER; + +typedef enum D3D12XBOX_TEXTURE_MIP_FILTER : UINT +{ + D3D12XBOX_TEXTURE_MIP_FILTER_NONE = 0, + D3D12XBOX_TEXTURE_MIP_FILTER_POINT = 1, + D3D12XBOX_TEXTURE_MIP_FILTER_LINEAR = 2, +} D3D12XBOX_TEXTURE_MIP_FILTER; + + +typedef struct D3D12_SAMPLER_DESC +{ + D3D12_FILTER Filter; + D3D12_TEXTURE_ADDRESS_MODE AddressU; + D3D12_TEXTURE_ADDRESS_MODE AddressV; + D3D12_TEXTURE_ADDRESS_MODE AddressW; + FLOAT MipLODBias; + UINT MaxAnisotropy; + D3D12_COMPARISON_FUNC ComparisonFunc; + FLOAT BorderColor[4]; + FLOAT MinLOD; + FLOAT MaxLOD; +} D3D12_SAMPLER_DESC; + +typedef enum D3D12XBOX_SAMPLER_FLAGS : UINT +{ + D3D12XBOX_SAMPLER_FLAG_NONE = 0x0000, + D3D12XBOX_SAMPLER_FLAG_ENABLE_UNNORMALIZED_COORDINATES = 0x0001, + D3D12XBOX_SAMPLER_FLAG_TRUNCATE_COORDINATES = 0x0002, + D3D12XBOX_SAMPLER_FLAG_TRUNCATE_COORDINATES_MC = 0x0004, + D3D12XBOX_SAMPLER_FLAG_ENABLE_DEGAMMA_OVERRIDE = 0x0008, + D3D12XBOX_SAMPLER_FLAG_DISABLE_PRECLAMP_BIAS = 0x0010, + D3D12XBOX_SAMPLER_FLAG_DISABLE_CUBEMAP_WRAP = 0x0020, + D3D12XBOX_SAMPLER_FLAG_ENABLE_MINMIP_FILTER = 0x0100, + D3D12XBOX_SAMPLER_FLAG_ENABLE_ANISO_OVERRIDE = 0x0200, + D3D12XBOX_SAMPLER_FLAG_ENABLE_POST_FILTER_LSB_CEILING = 0x0000, // Deprecated + D3D12XBOX_SAMPLER_FLAG_DISABLE_POST_FILTER_NORMALIZATION_ROUNDING = 0x0000 // Deprecated +} D3D12XBOX_SAMPLER_FLAGS; + +typedef struct D3D12_SAMPLER_DESC2 +{ + D3D12_FILTER Filter; + D3D12_TEXTURE_ADDRESS_MODE AddressU; + D3D12_TEXTURE_ADDRESS_MODE AddressV; + D3D12_TEXTURE_ADDRESS_MODE AddressW; + FLOAT MipLODBias; + UINT MaxAnisotropy; + D3D12_COMPARISON_FUNC ComparisonFunc; + union + { + FLOAT FloatBorderColor[4]; + UINT UintBorderColor[4]; + }; + FLOAT MinLOD; + FLOAT MaxLOD; + D3D12XBOX_SAMPLER_FLAGS Flags; +} D3D12_SAMPLER_DESC2; + +typedef enum D3D12XBOX_MINMIP_FILTER_SLOPE : UINT +{ + D3D12XBOX_MINMIP_FILTER_SLOPE_2_5 = 0, + D3D12XBOX_MINMIP_FILTER_SLOPE_3 = 1, + D3D12XBOX_MINMIP_FILTER_SLOPE_4 = 2, + D3D12XBOX_MINMIP_FILTER_SLOPE_5 = 3, + D3D12XBOX_MINMIP_FILTER_SLOPE_8 = 4, + D3D12XBOX_MINMIP_FILTER_SLOPE_16 = 5, + D3D12XBOX_MINMIP_FILTER_SLOPE_32 = 6, + D3D12XBOX_MINMIP_FILTER_SLOPE_64 = 7 +} D3D12XBOX_MINMIP_FILTER_SLOPE; + +typedef enum D3D12XBOX_MINMIP_FILTER_OFFSET : UINT +{ + D3D12XBOX_MINMIP_FILTER_OFFSET_1_4 = 0, + D3D12XBOX_MINMIP_FILTER_OFFSET_1_8 = 1, + D3D12XBOX_MINMIP_FILTER_OFFSET_1_16 = 2, + D3D12XBOX_MINMIP_FILTER_OFFSET_1_32 = 3, + D3D12XBOX_MINMIP_FILTER_OFFSET_1_64 = 4, + D3D12XBOX_MINMIP_FILTER_OFFSET_1_128 = 5 +} D3D12XBOX_MINMIP_FILTER_OFFSET; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_SAMPLER_FLAGS ); + +typedef struct D3D12XBOX_SAMPLER_DESC +{ + D3D12XBOX_SAMPLER_FLAGS Flags; + D3D12XBOX_TEXTURE_XY_FILTER FilterMag; + D3D12XBOX_TEXTURE_XY_FILTER FilterMin; + D3D12XBOX_TEXTURE_MIP_FILTER FilterMip; + D3D12XBOX_TEXTURE_Z_FILTER FilterZ; + D3D12XBOX_TEXTURE_FILTER_MODE FilterMode; + D3D12_TEXTURE_ADDRESS_MODE AddressU; + D3D12_TEXTURE_ADDRESS_MODE AddressV; + D3D12_TEXTURE_ADDRESS_MODE AddressW; + FLOAT MinLOD; + FLOAT MaxLOD; + FLOAT MipLODBias; + FLOAT MipLODBiasSecondary; + UINT MaxAnisotropy; + FLOAT AnisotropyBias; + UINT AnisotropyThreshold; + D3D12_COMPARISON_FUNC ComparisonFunc; + FLOAT BorderColor[4]; + UINT PerformanceMip; + UINT PerformanceZ; + D3D12XBOX_MINMIP_FILTER_SLOPE MinMipSlopeU; + D3D12XBOX_MINMIP_FILTER_OFFSET MinMipOffsetU; + D3D12XBOX_MINMIP_FILTER_SLOPE MinMipSlopeVOrW; + D3D12XBOX_MINMIP_FILTER_OFFSET MinMipOffsetVOrW; +} D3D12XBOX_SAMPLER_DESC; + +typedef enum D3D12_BUFFER_UAV_FLAGS +{ + D3D12_BUFFER_UAV_FLAG_NONE = 0x0, + D3D12_BUFFER_UAV_FLAG_RAW = 0x1, + D3D12XBOX_BUFFER_UAV_FLAG_STRIDED_TYPED = 0x2 // NumElements becomes offset in bytes, StructureByteStride is allowed with a known format +} D3D12_BUFFER_UAV_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_BUFFER_UAV_FLAGS ); + +typedef struct D3D12_BUFFER_UAV +{ + UINT64 FirstElement; + UINT NumElements; + UINT StructureByteStride; + UINT64 CounterOffsetInBytes; + D3D12_BUFFER_UAV_FLAGS Flags; +} D3D12_BUFFER_UAV; + +typedef struct D3D12_TEX1D_UAV +{ + UINT MipSlice; +} D3D12_TEX1D_UAV; + +typedef struct D3D12_TEX1D_ARRAY_UAV +{ + UINT MipSlice; + UINT FirstArraySlice; + UINT ArraySize; +} D3D12_TEX1D_ARRAY_UAV; + +typedef struct D3D12_TEX2D_UAV +{ + UINT MipSlice; + UINT PlaneSlice; +} D3D12_TEX2D_UAV; + +typedef struct D3D12_TEX2D_ARRAY_UAV +{ + UINT MipSlice; + UINT FirstArraySlice; + UINT ArraySize; + UINT PlaneSlice; +} D3D12_TEX2D_ARRAY_UAV; + +typedef struct D3D12_TEX3D_UAV +{ + UINT MipSlice; + UINT FirstWSlice; + UINT WSize; +} D3D12_TEX3D_UAV; + +typedef enum D3D12_UAV_DIMENSION +{ + D3D12_UAV_DIMENSION_UNKNOWN = 0, + D3D12_UAV_DIMENSION_BUFFER = 1, + D3D12_UAV_DIMENSION_TEXTURE1D = 2, + D3D12_UAV_DIMENSION_TEXTURE1DARRAY = 3, + D3D12_UAV_DIMENSION_TEXTURE2D = 4, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY = 5, + D3D12_UAV_DIMENSION_TEXTURE3D = 8 +} D3D12_UAV_DIMENSION; + +typedef struct D3D12_UNORDERED_ACCESS_VIEW_DESC +{ + DXGI_FORMAT Format; + D3D12_UAV_DIMENSION ViewDimension; + union + { + D3D12_BUFFER_UAV Buffer; + D3D12_TEX1D_UAV Texture1D; + D3D12_TEX1D_ARRAY_UAV Texture1DArray; + D3D12_TEX2D_UAV Texture2D; + D3D12_TEX2D_ARRAY_UAV Texture2DArray; + D3D12_TEX3D_UAV Texture3D; + }; +} D3D12_UNORDERED_ACCESS_VIEW_DESC; + +typedef struct D3D12XBOX_UNORDERED_ACCESS_VIEW_DESC +{ + DXGI_FORMAT Format; + D3D12_UAV_DIMENSION ViewDimension; + union + { + D3D12_BUFFER_UAV Buffer; + D3D12_TEX1D_UAV Texture1D; + D3D12_TEX1D_ARRAY_UAV Texture1DArray; + D3D12_TEX2D_UAV Texture2D; + D3D12_TEX2D_ARRAY_UAV Texture2DArray; + D3D12_TEX3D_UAV Texture3D; + }; + D3D12_GPU_VIRTUAL_ADDRESS ResourceLocation; + D3D12_GPU_VIRTUAL_ADDRESS CounterResourceLocation; + UINT MemoryType; +} D3D12XBOX_UNORDERED_ACCESS_VIEW_DESC; + +typedef struct D3D12_BUFFER_RTV +{ + UINT64 FirstElement; + UINT NumElements; +} D3D12_BUFFER_RTV; + +typedef struct D3D12_TEX1D_RTV +{ + UINT MipSlice; +} D3D12_TEX1D_RTV; + +typedef struct D3D12_TEX1D_ARRAY_RTV +{ + UINT MipSlice; + UINT FirstArraySlice; + UINT ArraySize; +} D3D12_TEX1D_ARRAY_RTV; + +typedef struct D3D12_TEX2D_RTV +{ + UINT MipSlice; + UINT PlaneSlice; +} D3D12_TEX2D_RTV; + +typedef struct D3D12_TEX2DMS_RTV +{ + UINT UnusedField_NothingToDefine; +} D3D12_TEX2DMS_RTV; + +typedef struct D3D12_TEX2D_ARRAY_RTV +{ + UINT MipSlice; + UINT FirstArraySlice; + UINT ArraySize; + UINT PlaneSlice; +} D3D12_TEX2D_ARRAY_RTV; + +typedef struct D3D12_TEX2DMS_ARRAY_RTV +{ + UINT FirstArraySlice; + UINT ArraySize; +} D3D12_TEX2DMS_ARRAY_RTV; + +typedef struct D3D12_TEX3D_RTV +{ + UINT MipSlice; + UINT FirstWSlice; + UINT WSize; +} D3D12_TEX3D_RTV; + +typedef enum D3D12_RTV_DIMENSION +{ + D3D12_RTV_DIMENSION_UNKNOWN = 0, + D3D12_RTV_DIMENSION_BUFFER = 1, + D3D12_RTV_DIMENSION_TEXTURE1D = 2, + D3D12_RTV_DIMENSION_TEXTURE1DARRAY = 3, + D3D12_RTV_DIMENSION_TEXTURE2D = 4, + D3D12_RTV_DIMENSION_TEXTURE2DARRAY = 5, + D3D12_RTV_DIMENSION_TEXTURE2DMS = 6, + D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D12_RTV_DIMENSION_TEXTURE3D = 8 +} D3D12_RTV_DIMENSION; + +typedef struct D3D12_RENDER_TARGET_VIEW_DESC +{ + DXGI_FORMAT Format; + D3D12_RTV_DIMENSION ViewDimension; + union + { + D3D12_BUFFER_RTV Buffer; + D3D12_TEX1D_RTV Texture1D; + D3D12_TEX1D_ARRAY_RTV Texture1DArray; + D3D12_TEX2D_RTV Texture2D; + D3D12_TEX2D_ARRAY_RTV Texture2DArray; + D3D12_TEX2DMS_RTV Texture2DMS; + D3D12_TEX2DMS_ARRAY_RTV Texture2DMSArray; + D3D12_TEX3D_RTV Texture3D; + }; +} D3D12_RENDER_TARGET_VIEW_DESC; + +typedef struct D3D12_TEX1D_DSV +{ + UINT MipSlice; +} D3D12_TEX1D_DSV; + +typedef struct D3D12_TEX1D_ARRAY_DSV +{ + UINT MipSlice; + UINT FirstArraySlice; + UINT ArraySize; +} D3D12_TEX1D_ARRAY_DSV; + +typedef struct D3D12_TEX2D_DSV +{ + UINT MipSlice; +} D3D12_TEX2D_DSV; + +typedef struct D3D12_TEX2D_ARRAY_DSV +{ + UINT MipSlice; + UINT FirstArraySlice; + UINT ArraySize; +} D3D12_TEX2D_ARRAY_DSV; + +typedef struct D3D12_TEX2DMS_DSV +{ + UINT UnusedField_NothingToDefine; +} D3D12_TEX2DMS_DSV; + +typedef struct D3D12_TEX2DMS_ARRAY_DSV +{ + UINT FirstArraySlice; + UINT ArraySize; +} D3D12_TEX2DMS_ARRAY_DSV; + +typedef enum D3D12_DSV_FLAGS +{ + D3D12_DSV_FLAG_NONE = 0x0L, + D3D12_DSV_FLAG_READ_ONLY_DEPTH = 0x1L, + D3D12_DSV_FLAG_READ_ONLY_STENCIL = 0x2L, +} D3D12_DSV_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_DSV_FLAGS ); + +typedef enum D3D12_DSV_DIMENSION +{ + D3D12_DSV_DIMENSION_UNKNOWN = 0, + D3D12_DSV_DIMENSION_TEXTURE1D = 1, + D3D12_DSV_DIMENSION_TEXTURE1DARRAY = 2, + D3D12_DSV_DIMENSION_TEXTURE2D = 3, + D3D12_DSV_DIMENSION_TEXTURE2DARRAY = 4, + D3D12_DSV_DIMENSION_TEXTURE2DMS = 5, + D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY = 6 +} D3D12_DSV_DIMENSION; + +typedef struct D3D12_DEPTH_STENCIL_VIEW_DESC +{ + DXGI_FORMAT Format; + D3D12_DSV_DIMENSION ViewDimension; + D3D12_DSV_FLAGS Flags; + union + { + D3D12_TEX1D_DSV Texture1D; + D3D12_TEX1D_ARRAY_DSV Texture1DArray; + D3D12_TEX2D_DSV Texture2D; + D3D12_TEX2D_ARRAY_DSV Texture2DArray; + D3D12_TEX2DMS_DSV Texture2DMS; + D3D12_TEX2DMS_ARRAY_DSV Texture2DMSArray; + }; +} D3D12_DEPTH_STENCIL_VIEW_DESC; + +typedef enum D3D12_CLEAR_FLAGS +{ + D3D12_CLEAR_FLAG_DEPTH = 0x1L, + D3D12_CLEAR_FLAG_STENCIL = 0x2L, +} D3D12_CLEAR_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_CLEAR_FLAGS ); + +typedef enum D3D12_FENCE_FLAGS +{ + D3D12_FENCE_FLAG_NONE = 0, + D3D12_FENCE_FLAG_SHARED = 0x1, + D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER = 0x2, + D3D12_FENCE_FLAG_NON_MONITORED = 0x4, + D3D12XBOX_FENCE_FLAG_DSTORAGE_DEBUG_USE_AFTER_FREE = 0x80, +} D3D12_FENCE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_FENCE_FLAGS ); + +typedef enum D3D12_DESCRIPTOR_HEAP_TYPE +{ + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + D3D12XBOX_DESCRIPTOR_HEAP_TYPE_SAMPLER_UNBOUNDED, // Unbounded in size sampler heap that only supports limited set of border colors + D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES +} D3D12_DESCRIPTOR_HEAP_TYPE; + +typedef enum D3D12_DESCRIPTOR_HEAP_FLAGS +{ + D3D12_DESCRIPTOR_HEAP_FLAG_NONE = 0x0, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE = 0x1 +} D3D12_DESCRIPTOR_HEAP_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_DESCRIPTOR_HEAP_FLAGS ); + +typedef struct D3D12_DESCRIPTOR_HEAP_DESC +{ + D3D12_DESCRIPTOR_HEAP_TYPE Type; + UINT NumDescriptors; + D3D12_DESCRIPTOR_HEAP_FLAGS Flags; + UINT NodeMask; +} D3D12_DESCRIPTOR_HEAP_DESC; + +typedef enum D3D12_DESCRIPTOR_RANGE_TYPE +{ + D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + D3D12_DESCRIPTOR_RANGE_TYPE_CBV, + D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, +} D3D12_DESCRIPTOR_RANGE_TYPE; + +typedef struct D3D12_DESCRIPTOR_RANGE +{ + D3D12_DESCRIPTOR_RANGE_TYPE RangeType; + UINT NumDescriptors; + UINT BaseShaderRegister; + UINT RegisterSpace; + UINT OffsetInDescriptorsFromTableStart; +} D3D12_DESCRIPTOR_RANGE; + +typedef struct D3D12_ROOT_DESCRIPTOR_TABLE +{ + UINT NumDescriptorRanges; + const D3D12_DESCRIPTOR_RANGE* pDescriptorRanges; +} D3D12_ROOT_DESCRIPTOR_TABLE; + +typedef struct D3D12_ROOT_CONSTANTS +{ + UINT ShaderRegister; + UINT RegisterSpace; + UINT Num32BitValues; +} D3D12_ROOT_CONSTANTS; + +typedef struct D3D12_ROOT_DESCRIPTOR +{ + UINT ShaderRegister; + UINT RegisterSpace; +} D3D12_ROOT_DESCRIPTOR; + +typedef enum D3D12_SHADER_VISIBILITY +{ + D3D12_SHADER_VISIBILITY_ALL = 0, + D3D12_SHADER_VISIBILITY_VERTEX = 1, + D3D12_SHADER_VISIBILITY_HULL = 2, + D3D12_SHADER_VISIBILITY_DOMAIN = 3, + D3D12_SHADER_VISIBILITY_GEOMETRY = 4, + D3D12_SHADER_VISIBILITY_PIXEL = 5, + D3D12_SHADER_VISIBILITY_AMPLIFICATION = 6, + D3D12_SHADER_VISIBILITY_MESH = 7, +} D3D12_SHADER_VISIBILITY; + +typedef enum D3D12_ROOT_PARAMETER_TYPE +{ + D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + D3D12_ROOT_PARAMETER_TYPE_CBV, + D3D12_ROOT_PARAMETER_TYPE_SRV, + D3D12_ROOT_PARAMETER_TYPE_UAV +} D3D12_ROOT_PARAMETER_TYPE; + +typedef struct D3D12_ROOT_PARAMETER +{ + D3D12_ROOT_PARAMETER_TYPE ParameterType; + union + { + D3D12_ROOT_DESCRIPTOR_TABLE DescriptorTable; + D3D12_ROOT_CONSTANTS Constants; + D3D12_ROOT_DESCRIPTOR Descriptor; + }; + D3D12_SHADER_VISIBILITY ShaderVisibility; +} D3D12_ROOT_PARAMETER; + +typedef enum D3D12_ROOT_SIGNATURE_FLAGS +{ + D3D12_ROOT_SIGNATURE_FLAG_NONE = 0x0, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT = 0x1, + D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS = 0x2, + D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS = 0x4, + D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS = 0x8, + D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS = 0x10, + D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS = 0x20, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT = 0x40, + D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE = 0x80, + D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS = 0x100, + D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS = 0x200, + D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED = 0x400, + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED = 0x800, + + // Compile XDXR shader ABI, start at higher bits + D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI = 0x01000000, + D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_COMPUTE_2_SPILL_AREA = 0x02000000, + + D3D12XBOX_ROOT_SIGNATURE_FLAG_RAYTRACING = D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI, + D3D12XBOX_ROOT_SIGNATURE_FLAG_INTERNAL_XDXR = D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI | + D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_COMPUTE_2_SPILL_AREA + +} D3D12_ROOT_SIGNATURE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_ROOT_SIGNATURE_FLAGS ); + +typedef +enum D3D12_STATIC_BORDER_COLOR +{ + D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK = 0, + D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK = ( D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK + 1 ), + D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE = ( D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK + 1 ), + D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT = (D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE + 1), + D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT = (D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT + 1) +} D3D12_STATIC_BORDER_COLOR; + +typedef struct D3D12_STATIC_SAMPLER_DESC +{ + D3D12_FILTER Filter; + D3D12_TEXTURE_ADDRESS_MODE AddressU; + D3D12_TEXTURE_ADDRESS_MODE AddressV; + D3D12_TEXTURE_ADDRESS_MODE AddressW; + FLOAT MipLODBias; + UINT MaxAnisotropy; + D3D12_COMPARISON_FUNC ComparisonFunc; + D3D12_STATIC_BORDER_COLOR BorderColor; + FLOAT MinLOD; + FLOAT MaxLOD; + UINT ShaderRegister; + UINT RegisterSpace; + D3D12_SHADER_VISIBILITY ShaderVisibility; +} D3D12_STATIC_SAMPLER_DESC; + +typedef struct D3D12_ROOT_SIGNATURE_DESC +{ + UINT NumParameters; + const D3D12_ROOT_PARAMETER* pParameters; + UINT NumStaticSamplers; + const D3D12_STATIC_SAMPLER_DESC* pStaticSamplers; + D3D12_ROOT_SIGNATURE_FLAGS Flags; +} D3D12_ROOT_SIGNATURE_DESC; + +typedef enum D3D12_DESCRIPTOR_RANGE_FLAGS +{ + D3D12_DESCRIPTOR_RANGE_FLAG_NONE = 0, + D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE = 0x1, + D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE = 0x2, + D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE = 0x4, + D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC = 0x8, + D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_STATIC_KEEPING_BUFFER_BOUNDS_CHECKS = 0x10000, +} D3D12_DESCRIPTOR_RANGE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_DESCRIPTOR_RANGE_FLAGS ); + +typedef struct D3D12_DESCRIPTOR_RANGE1 +{ + D3D12_DESCRIPTOR_RANGE_TYPE RangeType; + UINT NumDescriptors; + UINT BaseShaderRegister; + UINT RegisterSpace; + D3D12_DESCRIPTOR_RANGE_FLAGS Flags; + UINT OffsetInDescriptorsFromTableStart; +} D3D12_DESCRIPTOR_RANGE1; + +typedef struct D3D12_ROOT_DESCRIPTOR_TABLE1 +{ + UINT NumDescriptorRanges; + _Field_size_full_(NumDescriptorRanges) const D3D12_DESCRIPTOR_RANGE1* pDescriptorRanges; +} D3D12_ROOT_DESCRIPTOR_TABLE1; + +typedef enum D3D12_ROOT_DESCRIPTOR_FLAGS +{ + D3D12_ROOT_DESCRIPTOR_FLAG_NONE = 0, + D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE = 0x2, + D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE = 0x4, + D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC = 0x8 +} D3D12_ROOT_DESCRIPTOR_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_ROOT_DESCRIPTOR_FLAGS ); + +typedef struct D3D12_ROOT_DESCRIPTOR1 +{ + UINT ShaderRegister; + UINT RegisterSpace; + D3D12_ROOT_DESCRIPTOR_FLAGS Flags; +} D3D12_ROOT_DESCRIPTOR1; + +typedef struct D3D12_ROOT_PARAMETER1 +{ + D3D12_ROOT_PARAMETER_TYPE ParameterType; + union + { + D3D12_ROOT_DESCRIPTOR_TABLE1 DescriptorTable; + D3D12_ROOT_CONSTANTS Constants; + D3D12_ROOT_DESCRIPTOR1 Descriptor; + }; + D3D12_SHADER_VISIBILITY ShaderVisibility; +} D3D12_ROOT_PARAMETER1; + +typedef struct D3D12_ROOT_SIGNATURE_DESC1 +{ + UINT NumParameters; + _Field_size_full_(NumParameters) const D3D12_ROOT_PARAMETER1* pParameters; + UINT NumStaticSamplers; + _Field_size_full_(NumStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* pStaticSamplers; + D3D12_ROOT_SIGNATURE_FLAGS Flags; +} D3D12_ROOT_SIGNATURE_DESC1; + +typedef struct D3D12_VERSIONED_ROOT_SIGNATURE_DESC +{ + D3D_ROOT_SIGNATURE_VERSION Version; + union + { + D3D12_ROOT_SIGNATURE_DESC Desc_1_0; + D3D12_ROOT_SIGNATURE_DESC1 Desc_1_1; + }; +} D3D12_VERSIONED_ROOT_SIGNATURE_DESC; + + +} + + +extern "C" +{ + +// +// ID3D12RootSignatureDeserializer +// + +struct D3D12RootSignatureDeserializer_Function_Table +{ + GraphicsUnknown_Function_Table ObjectFunction; + + const D3D12_ROOT_SIGNATURE_DESC* (D3DAPI* GetRootSignature)( + ID3D12RootSignatureDeserializer* pDeserializer); +}; + + +} + +D3DINTERFACE(ID3D12RootSignatureDeserializer, 34AB647B,3CC8,46AC,84,1B,C0,96,56,45,C0,46) : public IGraphicsUnknown +{ +public: + + D3DINLINE D3D12RootSignatureDeserializer_Function_Table* DeserializerFunction() + { + return (D3D12RootSignatureDeserializer_Function_Table*)m_pFunction; + } + + D3DINLINE const D3D12_ROOT_SIGNATURE_DESC* GetRootSignatureDesc() + { + return DeserializerFunction()->GetRootSignature(this); + } +}; + + + + +extern "C" +{ + +// +// ID3D12VersionedRootSignatureDeserializer +// + +struct D3D12VersionedRootSignatureDeserializer_Function_Table +{ + GraphicsUnknown_Function_Table ObjectFunction; + + HRESULT (D3DAPI* GetRootSignatureDescAtVersion)( + ID3D12VersionedRootSignatureDeserializer* pDeserializer, + D3D_ROOT_SIGNATURE_VERSION ConvertToVersion, + _Out_ const D3D12_VERSIONED_ROOT_SIGNATURE_DESC** ppDesc); + + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* (D3DAPI* GetUnconvertedRootSignatureDesc)( + ID3D12VersionedRootSignatureDeserializer* pDeserializer); +}; + + +} + +D3DINTERFACE(ID3D12VersionedRootSignatureDeserializer, 7F91CE67,090C,4BB7,B7,8E,ED,8F,F2,E3,1D,A0) : public IGraphicsUnknown +{ +public: + + D3DINLINE D3D12VersionedRootSignatureDeserializer_Function_Table* DeserializerFunction() + { + return (D3D12VersionedRootSignatureDeserializer_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetRootSignatureDescAtVersion( + D3D_ROOT_SIGNATURE_VERSION ConvertToVersion, + _Out_ const D3D12_VERSIONED_ROOT_SIGNATURE_DESC** ppDesc) + { + return DeserializerFunction()->GetRootSignatureDescAtVersion(this, ConvertToVersion, ppDesc); + } + + D3DINLINE const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* D3DAPI GetUnconvertedRootSignatureDesc() + { + return DeserializerFunction()->GetUnconvertedRootSignatureDesc(this); + } +}; + + +extern "C" +{ + +typedef HRESULT (D3DAPI* PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)( + _In_ const D3D12_ROOT_SIGNATURE_DESC* pRootSignature, + _In_ D3D_ROOT_SIGNATURE_VERSION Version, + _Out_ ID3DBlob** ppBlob, + _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorBlob); + +typedef HRESULT (D3DAPI* PFN_D3D12_CREATE_ROOT_SIGNATURE_DESERIALIZER)( + _In_reads_bytes_(SrcDataSizeInBytes) LPCVOID pSrcData, + _In_ SIZE_T SrcDataSizeInBytes, + _In_ REFIID pRootSignatureDeserializerInterface, + _Out_ void** ppRootSignatureDeserializer); + +typedef HRESULT (D3DAPI* PFN_D3D12_SERIALIZE_VERSIONED_ROOT_SIGNATURE)( + _In_ const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* pRootSignature, + _Out_ ID3DBlob** ppBlob, + _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorBlob); + +typedef HRESULT (D3DAPI* PFN_D3D12_CREATE_VERSIONED_ROOT_SIGNATURE_DESERIALIZER)( + _In_reads_bytes_(SrcDataSizeInBytes) LPCVOID pSrcData, + _In_ SIZE_T SrcDataSizeInBytes, + _In_ REFIID pRootSignatureDeserializerInterface, + _Out_ void** ppRootSignatureDeserializer); + +HRESULT D3DAPI D3D12SerializeRootSignature( + _In_ const D3D12_ROOT_SIGNATURE_DESC* pRootSignature, + _In_ D3D_ROOT_SIGNATURE_VERSION Version, + _Out_ ID3DBlob** ppBlob, + _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorBlob); + +HRESULT D3DAPI D3D12CreateRootSignatureDeserializer( + _In_reads_bytes_(SrcDataSizeInBytes) LPCVOID pSrcData, + _In_ SIZE_T SrcDataSizeInBytes, + _In_ REFIID pRootSignatureDeserializerInterface, + _Out_ void** ppRootSignatureDeserializer); + +HRESULT D3DAPI D3D12SerializeVersionedRootSignature( + _In_ const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* pRootSignature, + _Out_ ID3DBlob** ppBlob, + _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorBlob); + +HRESULT D3DAPI D3D12CreateVersionedRootSignatureDeserializer( + _In_reads_bytes_(SrcDataSizeInBytes) LPCVOID pSrcData, + _In_ SIZE_T SrcDataSizeInBytes, + _In_ REFIID pRootSignatureDeserializerInterface, + _Out_ void** ppRootSignatureDeserializer); + +} + +typedef struct D3D12_CPU_DESCRIPTOR_HANDLE +{ + SIZE_T ptr; +} D3D12_CPU_DESCRIPTOR_HANDLE; + +D3DINLINE void* D3D12XboxGetWritePointer(const D3D12_CPU_DESCRIPTOR_HANDLE& Handle) +{ + + return (void*)Handle.ptr; + +} + +D3DINLINE const void* D3D12XboxGetCachedReadPointer(const D3D12_CPU_DESCRIPTOR_HANDLE& Handle) +{ + + return (const void*)Handle.ptr; + +} + +typedef struct D3D12_GPU_DESCRIPTOR_HANDLE +{ + UINT64 ptr; +} D3D12_GPU_DESCRIPTOR_HANDLE; + +extern "C" +{ + +// If rects are supplied in D3D12_DISCARD_REGION, below, the resource +// must have 2D subresources with all specified subresources the same dimension. +typedef struct D3D12_DISCARD_REGION +{ + UINT NumRects; + _In_reads_(NumRects) const D3D12_RECT* pRects; + UINT FirstSubresource; + UINT NumSubresources; +} D3D12_DISCARD_REGION; + +typedef enum D3D12_QUERY_HEAP_TYPE +{ + D3D12_QUERY_HEAP_TYPE_OCCLUSION = 0, + D3D12_QUERY_HEAP_TYPE_TIMESTAMP = 1, + D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS = 2, + D3D12_QUERY_HEAP_TYPE_SO_STATISTICS = 3, + D3D12_QUERY_HEAP_TYPE_COPY_QUEUE_TIMESTAMP = 5, + D3D12XBOX_QUERY_HEAP_TYPE_DMA_TIMESTAMP = 7, + D3D12XBOX_QUERY_HEAP_TYPE_OCCLUSION_NO_SYNC = 9, + D3D12XBOX_QUERY_HEAP_TYPE_TIMESTAMP_NO_SYNC = 10, + D3D12XBOX_QUERY_HEAP_TYPE_DMA_TIMESTAMP_NO_SYNC = 11, + D3D12_QUERY_HEAP_TYPE_MAX_VALID = 13 +} D3D12_QUERY_HEAP_TYPE; + +typedef struct D3D12_QUERY_HEAP_DESC +{ + D3D12_QUERY_HEAP_TYPE Type; + UINT Count; + UINT NodeMask; +} D3D12_QUERY_HEAP_DESC; + +typedef enum D3D12_QUERY_TYPE +{ + D3D12_QUERY_TYPE_OCCLUSION = 0, + D3D12_QUERY_TYPE_BINARY_OCCLUSION = 1, + D3D12_QUERY_TYPE_TIMESTAMP = 2, + D3D12_QUERY_TYPE_PIPELINE_STATISTICS = 3, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0 = 4, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1 = 5, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2 = 6, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3 = 7, + D3D12XBOX_QUERY_TYPE_PREDICATION_STATUS = 12 +} D3D12_QUERY_TYPE; + +typedef enum D3D12_PREDICATION_OP +{ + D3D12_PREDICATION_OP_EQUAL_ZERO = 0, + D3D12_PREDICATION_OP_NOT_EQUAL_ZERO = 1, +} D3D12_PREDICATION_OP; + +typedef struct D3D12_QUERY_DATA_PIPELINE_STATISTICS +{ + UINT64 IAVertices; + UINT64 IAPrimitives; + UINT64 VSInvocations; + UINT64 GSInvocations; + UINT64 GSPrimitives; + UINT64 CInvocations; + UINT64 CPrimitives; + UINT64 PSInvocations; + UINT64 HSInvocations; + UINT64 DSInvocations; + UINT64 CSInvocations; +} D3D12_QUERY_DATA_PIPELINE_STATISTICS; + +typedef struct D3D12_QUERY_DATA_SO_STATISTICS +{ + UINT64 NumPrimitivesWritten; + UINT64 PrimitivesStorageNeeded; +} D3D12_QUERY_DATA_SO_STATISTICS; + +typedef enum D3D12XBOX_OCCLUSION_QUERY_CONTROL_COUNT_FLAG : UINT +{ + D3D12XBOX_OCCLUSION_QUERY_CONTROL_COUNT_DEPTH_PASS = 0x1, // Count samples which pass the depth test + D3D12XBOX_OCCLUSION_QUERY_CONTROL_COUNT_DEPTH_FAIL = 0x2, // Count samples which fail the depth test + D3D12XBOX_OCCLUSION_QUERY_CONTROL_COUNT_STENCIL_FAIL = 0x4, // Count samples which fail the stencil test + D3D12XBOX_OCCLUSION_QUERY_CONTROL_COUNT_DEPTH_BOUNDS_FAIL = 0x8, // Count samples which fail the depth bounds test +} D3D12XBOX_OCCLUSION_QUERY_CONTROL_COUNT_FLAG; + +#define D3D12XBOX_OCCLUSION_QUERY_CONTROL_SAMPLE_COUNT_INHERIT_FROM_RENDERTARGET (0x7) + +typedef struct D3D12XBOX_OCCLUSION_QUERY_CONTROL +{ + UINT : 1; + BOOL EnablePerfectOcclusionQueries : 3; + UINT SampleCountLog2 : 4; + UINT EnableZPass : 4; + UINT EnableZFail : 4; + UINT EnableSFail : 4; + UINT EnableDepthBoundsFail : 4; + UINT EnableEvenSlices : 4; + UINT EnableOddSlices : 4; + +#ifdef __D3D11X_QUERY_CONFIG_OCCLUSION__DEFINED__ + + void InitializeFromQueryConfigOcclusion(const D3D11X_QUERY_CONFIG_OCCLUSION& qco) + { + EnablePerfectOcclusionQueries = qco.DisableOptimizationsForCountAccuracy; + DWORD sc = 0; + if (qco.Samples > 0) + { + _BitScanReverse(&sc, qco.Samples); + } + else + { + sc = D3D12XBOX_OCCLUSION_QUERY_CONTROL_SAMPLE_COUNT_INHERIT_FROM_RENDERTARGET; + } + SampleCountLog2 = sc; + for (UINT i = 0; i < 2; i++) + { + EnableZPass |= ((qco.Counter[i].Flags & D3D11X_QUERY_CONFIG_OCCLUSION_COUNT_DEPTH_PASS) << i); + EnableZFail |= (((qco.Counter[i].Flags & D3D11X_QUERY_CONFIG_OCCLUSION_COUNT_DEPTH_FAIL) >> 1) << i); + EnableSFail |= (((qco.Counter[i].Flags & D3D11X_QUERY_CONFIG_OCCLUSION_COUNT_STENCIL_FAIL) >> 2) << i); + EnableDepthBoundsFail |= ((qco.Counter[i].Flags & D3D11X_QUERY_CONFIG_OCCLUSION_COUNT_DEPTH_BOUNDS_FAIL) >> (3 - i)); + + if (qco.Counter[i].EnableEvenTargets) + { + EnableEvenSlices |= (1 << i); + } + if (qco.Counter[i].EnableOddTargets) + { + EnableOddSlices |= (1 << i); + } + } + } + +#endif // __D3D11X_QUERY_CONFIG_OCCLUSION__DEFINED__ + +} D3D12XBOX_OCCLUSION_QUERY_CONTROL; + +typedef enum D3D12XBOX_HISTENCIL_COMPARE_FUNCTION +{ + D3D12XBOX_HISTENCIL_COMPARE_FUNCTION_NEVER = 0x0, // never pass + D3D12XBOX_HISTENCIL_COMPARE_FUNCTION_LESS = 0x1, // pass if left < right + D3D12XBOX_HISTENCIL_COMPARE_FUNCTION_EQUAL = 0x2, // pass if left = right + D3D12XBOX_HISTENCIL_COMPARE_FUNCTION_LEQUAL = 0x3, // pass if left <= right + D3D12XBOX_HISTENCIL_COMPARE_FUNCTION_GREATER = 0x4, // pass if left > right + D3D12XBOX_HISTENCIL_COMPARE_FUNCTION_NOTEQUAL = 0x5, // pass if left != right + D3D12XBOX_HISTENCIL_COMPARE_FUNCTION_GEQUAL = 0x6, // pass if left >= right + D3D12XBOX_HISTENCIL_COMPARE_FUNCTION_ALWAYS = 0x7, // always pass +} D3D12XBOX_HISTENCIL_COMPARE_FUNCTION; + +typedef struct D3D12XBOX_HISTENCIL_COMPARE_STATE +{ + D3D12XBOX_HISTENCIL_COMPARE_FUNCTION CompareFunction : 4; + UINT CompareValue : 8; + UINT CompareMask : 12; + BOOL Enabled : 8; +} D3D12XBOX_HISTENCIL_COMPARE_STATE; + +typedef struct D3D12XBOX_HISTENCIL_CONTROL +{ + D3D12XBOX_HISTENCIL_COMPARE_STATE State0; + D3D12XBOX_HISTENCIL_COMPARE_STATE State1; +} D3D12XBOX_HISTENCIL_CONTROL; + +typedef struct D3D12_STREAM_OUTPUT_BUFFER_VIEW +{ + D3D12_GPU_VIRTUAL_ADDRESS BufferLocation; + UINT64 SizeInBytes; + D3D12_GPU_VIRTUAL_ADDRESS BufferFilledSizeLocation; +} D3D12_STREAM_OUTPUT_BUFFER_VIEW; + +typedef struct D3D12_DRAW_ARGUMENTS +{ + UINT VertexCountPerInstance; + UINT InstanceCount; + UINT StartVertexLocation; + UINT StartInstanceLocation; +} D3D12_DRAW_ARGUMENTS; + +typedef struct D3D12_DRAW_INDEXED_ARGUMENTS +{ + UINT IndexCountPerInstance; + UINT InstanceCount; + UINT StartIndexLocation; + INT BaseVertexLocation; + UINT StartInstanceLocation; +} D3D12_DRAW_INDEXED_ARGUMENTS; + +typedef struct D3D12_DISPATCH_ARGUMENTS +{ + UINT ThreadGroupCountX; + UINT ThreadGroupCountY; + UINT ThreadGroupCountZ; +} D3D12_DISPATCH_ARGUMENTS; + +typedef struct D3D12_VERTEX_BUFFER_VIEW +{ + D3D12_GPU_VIRTUAL_ADDRESS BufferLocation; + UINT SizeInBytes; + UINT StrideInBytes; +} D3D12_VERTEX_BUFFER_VIEW; + +typedef struct D3D12_INDEX_BUFFER_VIEW +{ + D3D12_GPU_VIRTUAL_ADDRESS BufferLocation; + UINT SizeInBytes; + DXGI_FORMAT Format; +} D3D12_INDEX_BUFFER_VIEW; + +typedef struct D3D12XBOX_DISPATCHX_ARGUMENTS +{ + UINT ThreadGroupCountX; + UINT ThreadGroupCountY; + UINT ThreadGroupCountZ; + D3D12XBOX_DISPATCH_FLAGS Flags; +} D3D12XBOX_DISPATCH_ARGUMENTS; + +typedef struct D3D12XBOX_DPBB_BREAK_BATCH_ARGUMENTS +{ + UINT DoBreakBatch; +} D3D12XBOX_DPBB_BREAK_BATCH_ARGUMENTS; + +typedef struct D3D12XBOX_DISPATCH_MESH_X_ARGUMENTS +{ + UINT ThreadGroupCountX; // How many threadgroups to launch + UINT Reserved0; // Future use, will be packed divisors for decompressing thread ids + UINT Reserved1_And_PayloadAddr_39_36; // Parent group id (overloads Base Vertex) + UINT PayloadAddr_35_4; // Loaded into GetPayload in the mesh shader (overloads Base Instance) +} D3D12XBOX_DISPATCH_MESH_X_ARGUMENTS; + +typedef struct D3D12XBOX_FLUSHPIPELINEX_ARGUMENTS +{ + UINT FlushFlags; +} D3D12XBOX_FLUSHPIPELINEX_ARGUMENTS; + + +typedef enum D3D12_INDIRECT_ARGUMENT_TYPE +{ + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_RAYS, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH, + + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_PADDING = 100, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_DESCRIPTOR_TABLE, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_PIPELINE_STATE, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_DISPATCHX, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_DISPATCH_L2, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_DISPATCH_SINGLE = D3D12XBOX_INDIRECT_ARGUMENT_TYPE_DISPATCH_L2, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_DPBB_BREAK_BATCH, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH_X, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_FLUSH_PIPELINEX, + D3D12XBOX_INDIRECT_ARGUMENT_TYPE_COMPUTE_SHADER_LAUNCH_PARAMETERSX, +} D3D12_INDIRECT_ARGUMENT_TYPE; + +typedef struct D3D12_INDIRECT_ARGUMENT_DESC +{ + D3D12_INDIRECT_ARGUMENT_TYPE Type; + + union + { + struct + { + UINT Slot; + } VertexBuffer; + + struct + { + UINT RootParameterIndex; + UINT DestOffsetIn32BitValues; + UINT Num32BitValuesToSet; + } Constant; + + struct + { + UINT RootParameterIndex; + } ConstantBufferView; + + struct + { + UINT RootParameterIndex; + } ShaderResourceView; + + struct + { + UINT RootParameterIndex; + } UnorderedAccessView; + + struct + { + UINT RootParameterIndex; + } DescriptorTable; + + struct + { + UINT SizeInBytes; + } Padding; + + struct + { + D3D12XBOX_DISPATCH_FLAGS Flags; + } DispatchSingle; + + struct + { + D3D12XBOX_DISPATCH_FLAGS Flags; + } DispatchL2; + }; +} D3D12_INDIRECT_ARGUMENT_DESC; + +typedef struct D3D12_COMMAND_SIGNATURE_DESC +{ + UINT ByteStride; + UINT NumArgumentDescs; + const D3D12_INDIRECT_ARGUMENT_DESC* pArgumentDescs; + UINT NodeMask; +} D3D12_COMMAND_SIGNATURE_DESC; + + +#define D3D12XBOX_EXECUTE_INDIRECT_MAX_COMMAND_COUNT 65535 + + +typedef enum D3D12XBOX_PIX_CAPTURE_FLAGS +{ + D3D12XBOX_PIX_CAPTURE_ALL_ENGINES = 0x2, + D3D12XBOX_PIX_CAPTURE_ASYNC_COMPUTE_AS_CPU = 0x4, + D3D12XBOX_PIX_CAPTURE_DMA_AS_CPU = 0x8, + D3D12XBOX_PIX_CAPTURE_ALL_MEMORY = 0x10, + D3D12XBOX_PIX_CAPTURE_ENTIRE_ACCESSED_TEXTURES = 0x20, // only valid when !D3D12XBOX_PIX_CAPTURE_ALL_MEMORY + D3D12XBOX_PIX_CAPTURE_ENTIRE_ACCESSED_BUFFERS = 0x40, // only valid when !D3D12XBOX_PIX_CAPTURE_ALL_MEMORY + D3D12XBOX_PIX_CAPTURE_SET_DYNAMIC_POWER = 0x80, // title uses dynamic power + D3D12XBOX_PIX_CAPTURE_API = 0x10000, + D3D12XBOX_PIX_CAPTURE_GOLD_IMAGE = 0x200000, +} D3D12XBOX_PIX_CAPTURE_FLAGS; + + +typedef enum D3D12XBOX_COPY_FLAGS : UINT +{ + D3D12XBOX_COPY_FLAG_NONE = 0x0, + D3D12XBOX_COPY_FLAG_RESUMMARIZE_HTILE = 0x10, + D3D12XBOX_COPY_FLAG_FORCE_DECOMPRESS_EXPAND_COLOR = 0x20, + D3D12XBOX_COPY_FLAG_FORCE_DECOMPRESS_EXPAND_DEPTH = 0x20, + D3D12XBOX_COPY_FLAG_FORCE_DECOMPRESS_EXPAND_STENCIL = 0x40, + D3D12XBOX_COPY_FLAG_FORCE_DECOMPRESS = 0x60, + D3D12XBOX_COPY_FLAG_FORCE_PROPAGATE_COLOR_CLEAR = 0x400, + D3D12XBOX_COPY_FLAG_FORCE_GATHER_COLOR_FMASK = 0x800, + D3D12XBOX_COPY_FLAG_FORCE_ELIMINATE_DCC = 0x1000, + D3D12XBOX_COPY_FLAG_COPY_DEPTH_SAMPLE_TO_RED = 0x80, + D3D12XBOX_COPY_FLAG_COPY_STENCIL_SAMPLE_TO_RED = 0x100, + D3D12XBOX_COPY_FLAG_COPY_STENCIL_SAMPLE_TO_GREEN = 0x180, + D3D12XBOX_COPY_FLAG_COPY_DEPTH_STENCIL_SAMPLES_TO_RED_GREEN = 0x200, + D3D12XBOX_COPY_FLAG_INVALIDATE_HTILE = 0x400, + D3D12XBOX_COPY_FLAG_USE_CP_DMA = 0x800, +} D3D12XBOX_COPY_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_COPY_FLAGS ); + +typedef enum D3D12XBOX_COMPRESSION_STATE_FLAGS : UINT +{ + D3D12XBOX_COMPRESSION_STATE_FLAG_NONE = 0x0, + D3D12XBOX_COMPRESSION_STATE_FLAG_ENABLE_COLOR = 0x1, // Also enable indirect color clear and scattered color FMask + D3D12XBOX_COMPRESSION_STATE_FLAG_ENABLE_DEPTH = 0x1, + D3D12XBOX_COMPRESSION_STATE_FLAG_ENABLE_STENCIL = 0x2, + D3D12XBOX_COMPRESSION_STATE_FLAG_ENABLE_DEPTH_STENCIL = (D3D12XBOX_COMPRESSION_STATE_FLAG_ENABLE_DEPTH | D3D12XBOX_COMPRESSION_STATE_FLAG_ENABLE_STENCIL), +} D3D12XBOX_COMPRESSION_STATE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_COMPRESSION_STATE_FLAGS ); + +typedef enum D3D12XBOX_WRITE_VALUE_TOP_FLAGS : UINT +{ + D3D12XBOX_WRITE_VALUE_TOP_FLAG_NONE = 0x0, + D3D12XBOX_WRITE_VALUE_TOP_FLAG_WAIT_FOR_WRITE_CONFIRM = 0x1, + D3D12XBOX_WRITE_VALUE_TOP_FLAG_SELECT_ENGINE_PFP = 0x2, + D3D12XBOX_WRITE_VALUE_TOP_FLAG_GPU_TIMESTAMP = 0x4, // Only valid with Write64BitValueTopOfPipeX + D3D12XBOX_WRITE_VALUE_TOP_FLAG_SYSTEM_TIMESTAMP = 0x8, // Only valid with Write64BitValueTopOfPipeX +} D3D12XBOX_WRITE_VALUE_TOP_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_WRITE_VALUE_TOP_FLAGS ); + +typedef enum D3D12XBOX_WRITE_VALUE_BOP_FLAGS : UINT +{ + D3D12XBOX_WRITE_VALUE_BOP_FLAG_NONE = 0x0, + D3D12XBOX_WRITE_VALUE_BOP_FLAG_GPU_TIMESTAMP = 0x1, // Only valid with Write64BitValueBottomOfPipe(2)X + D3D12XBOX_WRITE_VALUE_BOP_FLAG_SYSTEM_TIMESTAMP = 0x2, // Only valid with Write64BitValueBottomOfPipe(2)X +} D3D12XBOX_WRITE_VALUE_BOP_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_WRITE_VALUE_BOP_FLAGS ); + +typedef enum D3D12XBOX_WAIT_FLAGS : UINT +{ + D3D12XBOX_WAIT_FLAG_NONE = 0x0, + D3D12XBOX_WAIT_FLAG_SELECT_ENGINE_PFP = 0x1, + D3D12XBOX_WAIT_FLAG_SELECT_ENGINE_CE = 0x2, +} D3D12XBOX_WAIT_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_WAIT_FLAGS ); + +typedef enum D3D12XBOX_SHADER_STAGE : UINT +{ + D3D12XBOX_SHADER_STAGE_VERTEX = 0, + D3D12XBOX_SHADER_STAGE_HULL = 1, + D3D12XBOX_SHADER_STAGE_DOMAIN = 2, + D3D12XBOX_SHADER_STAGE_GEOMETRY = 3, + D3D12XBOX_SHADER_STAGE_PIXEL = 4, + D3D12XBOX_SHADER_STAGE_COMPUTE = 5, +} D3D12XBOX_SHADER_STAGE; + +typedef enum D3D12XBOX_DEBUG_FLAGS : UINT +{ + D3D12XBOX_DEBUG_FLAG_NONE = 0x00000000, + D3D12XBOX_DEBUG_FLAG_API_ERROR_DISABLE_BREAKS = 0x00000001, + D3D12XBOX_DEBUG_FLAG_DISABLE_BARRIER_VALIDATION = 0x00000200, + D3D12XBOX_DEBUG_FLAG_ENABLE_TRANSITION_BARRIER_LOGGING = 0x00000400, + D3D12XBOX_DEBUG_FLAG_ENABLE_INVALID_ROOT_PARAMETER_VALIDATION = 0x00000800, + D3D12XBOX_DEBUG_FLAG_ENABLE_NULL_DESCRIPTOR_VALIDATION = 0x00001000, + D3D12XBOX_DEBUG_FLAG_ENABLE_NULL_VERTEX_BUFFER_VIEW_VALIDATION = 0x00002000, + D3D12XBOX_DEBUG_FLAG_ENABLE_OUT_OF_ORDER_CMD_LIST_VALIDATION = 0x00004000, + D3D12XBOX_DEBUG_FLAG_ENABLE_ENHANCED_BARRIER_LOGGING = 0x00008000, + + // Deprecated flags: + D3D12XBOX_DEBUG_FLAG_DISABLE_COMMON_STATE_PROMOTION_AND_DECAY = 0x00000000, + +} D3D12XBOX_DEBUG_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_DEBUG_FLAGS ); + +typedef enum D3D12XBOX_DEBUG_FILTER_FLAGS : UINT +{ + D3D12XBOX_DEBUG_FILTER_FLAG_NONE = 0x00000000, + D3D12XBOX_DEBUG_FILTER_FLAG_DISABLE_BREAKS = 0x00000001, + D3D12XBOX_DEBUG_FILTER_FLAG_DISABLE_OUTPUT = 0x00000002, + D3D12XBOX_DEBUG_FILTER_FLAG_DISABLE_CALLBACK = 0x00000004, + D3D12XBOX_DEBUG_FILTER_FLAG_DISABLE_FAILURE = 0x00000008, +} D3D12XBOX_DEBUG_FILTER_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_DEBUG_FILTER_FLAGS ); + +// Return true to suppress the break +typedef bool (*D3D12XBOX_DEBUG_CALLBACK)( + void* pUserContext, + void* pCommandList, + DWORD messageId, + const CHAR* strMessage); + +typedef enum D3D12XBOX_SHADER_STAGE_FLAGS : UINT +{ + D3D12XBOX_SHADER_STAGE_FLAG_NONE = 0x0, + D3D12XBOX_SHADER_STAGE_FLAG_VERTEX = 0x1, + D3D12XBOX_SHADER_STAGE_FLAG_HULL = 0x2, + D3D12XBOX_SHADER_STAGE_FLAG_DOMAIN = 0x4, + D3D12XBOX_SHADER_STAGE_FLAG_GEOMETRY = 0x8, + D3D12XBOX_SHADER_STAGE_FLAG_PIXEL = 0x10, + D3D12XBOX_SHADER_STAGE_FLAG_COMPUTE = 0x20, + D3D12XBOX_SHADER_STAGE_FLAG_AMPLIFICATION = 0x40, + D3D12XBOX_SHADER_STAGE_FLAG_MESH = 0x80, +} D3D12XBOX_SHADER_STAGE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_SHADER_STAGE_FLAGS); + +typedef void (*D3D12XBOX_SHADER_RECOMPILE_CALLBACK)( + D3D12XBOX_SHADER_STAGE_FLAGS ShaderStageFlags); + +// Frame scheduling and presentation: + +#define D3D12XBOX_FRAME_INTERVAL_120_HZ 8333 +#define D3D12XBOX_FRAME_INTERVAL_60_HZ 16667 +#define D3D12XBOX_FRAME_INTERVAL_40_HZ 25000 +#define D3D12XBOX_FRAME_INTERVAL_30_HZ 33333 +#define D3D12XBOX_FRAME_INTERVAL_24_HZ 41667 + +typedef enum D3D12XBOX_FRAME_INTERVAL_FLAGS +{ + D3D12XBOX_FRAME_INTERVAL_FLAG_NONE = 0x0, + D3D12XBOX_FRAME_INTERVAL_FLAG_60FPS_PLUS = 0x1, +} D3D12XBOX_FRAME_INTERVAL_FLAGS; + + +typedef UINT64 D3D12XBOX_FRAME_PIPELINE_TOKEN; + +#define D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL 0ull + + +typedef enum D3D12XBOX_FRAME_EVENT_TYPE +{ + D3D12XBOX_FRAME_EVENT_ORIGIN = 0, + D3D12XBOX_FRAME_EVENT_DISPLAY_VBLANK = 1, + D3D12XBOX_FRAME_EVENT_DISPLAY_FLIP = 2, +} D3D12XBOX_FRAME_EVENT_TYPE; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_FRAME_EVENT_TYPE ); + +typedef enum D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAGS +{ + D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAG_NONE = 0x0, + D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAG_DISABLE_SIGNAL = 0x1, +} D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAGS ); + + +typedef struct D3D12XBOX_SCHEDULE_FRAME_OBJECT_LIST +{ + UINT Count; + HANDLE* pObjects; +} D3D12XBOX_SCHEDULE_FRAME_OBJECT_LIST; + +typedef enum D3D12XBOX_WAIT_FRAME_EVENT_FLAGS +{ + D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE = 0x0, + D3D12XBOX_WAIT_FRAME_EVENT_FLAG_WAIT_ALL = 0x1, + D3D12XBOX_WAIT_FRAME_EVENT_FLAG_PROCESS_TOKEN_ON_TIMEOUT = 0x2, +} D3D12XBOX_WAIT_FRAME_EVENT_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_WAIT_FRAME_EVENT_FLAGS ); + +typedef struct D3D12XBOX_WAIT_FRAME_OBJECT_LIST +{ + UINT Count; + HANDLE* pObjects; + UINT* pSignaledObjectIndex; // _Out_opt_ +} D3D12XBOX_WAIT_FRAME_OBJECT_LIST; + +#define D3D12XBOX_SIGNALED_OBJECT_INDEX_NONE 0xFFFFFFFF +#define D3D12XBOX_SIGNALED_OBJECT_INDEX_PRIMARY 0xFFFFFFFE + +#define D3D12XBOX_WAIT_FRAME_EVENT_INFINITE 0xFFFFFFFF + + +#define D3D12XBOX_PRESENT_PLANES_MAX 2 +#define D3D12XBOX_PRESENT_VIEWS_MAX 8 + +typedef enum D3D12XBOX_PRESENT_FLAGS +{ + D3D12XBOX_PRESENT_FLAG_NONE = 0x0, + D3D12XBOX_PRESENT_FLAG_IMMEDIATE = 0x1, + D3D12XBOX_PRESENT_FLAG_DO_NOT_WAIT = 0x2, + D3D12XBOX_PRESENT_FLAG_PERSIST = 0x4, + D3D12XBOX_PRESENT_FLAG_DISABLE_VARIABLE_REFRESH_RATE = 0x8, +} D3D12XBOX_PRESENT_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_PRESENT_FLAGS ); + +typedef enum D3D12XBOX_PRESENT_PLANE_SCALE_FILTER +{ + D3D12XBOX_PRESENT_PLANE_SCALE_FILTER_DEFAULT = 0x0, + D3D12XBOX_PRESENT_PLANE_UPSCALE_FILTER_BILINEAR = 0x1, + D3D12XBOX_PRESENT_PLANE_UPSCALE_FILTER_SINC4 = 0x2, + D3D12XBOX_PRESENT_PLANE_UPSCALE_FILTER_LANCZOS4 = 0x3, + D3D12XBOX_PRESENT_PLANE_UPSCALE_FILTER_LANCZOS6 = 0x4, + D3D12XBOX_PRESENT_PLANE_UPSCALE_FILTER_LANCZOS6_SOFT = 0x5, + D3D12XBOX_PRESENT_PLANE_UPSCALE_FILTER_LANCZOS8 = 0x6, + D3D12XBOX_PRESENT_PLANE_UPSCALE_FILTER_LANCZOS10 = 0x7, +} D3D12XBOX_PRESENT_PLANE_SCALE_FILTER; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_PRESENT_PLANE_SCALE_FILTER ); + +typedef enum D3D12XBOX_PRESENT_PLANE_FLAGS +{ + D3D12XBOX_PRESENT_PLANE_FLAG_NONE = 0x0, +} D3D12XBOX_PRESENT_PLANE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_PRESENT_PLANE_FLAGS ); + +typedef struct D3D12XBOX_VIEW_RECT +{ + FLOAT left; + FLOAT top; + FLOAT right; + FLOAT bottom; +} D3D12XBOX_VIEW_RECT; + + +typedef enum D3D12XBOX_PRESENT_DESC_TYPE +{ + D3D12XBOX_PRESENT_DESC_TYPE_NONE = 0x0, + D3D12XBOX_PRESENT_DESC_TYPE_TITLE_PERFORMANCE_OVERLAY = 0x1, +} D3D12XBOX_PRESENT_DESC_TYPE; + +typedef enum D3D12XBOX_PRESENT_DESC_TITLE_PERFORMANCE_OVERLAY_FLAGS +{ + D3D12XBOX_PRESENT_DESC_TITLE_PERFORMANCE_OVERLAY_FLAGS_NONE = 0x0, + +} D3D12XBOX_PRESENT_DESC_TITLE_PERFORMANCE_OVERLAY_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_PRESENT_DESC_TITLE_PERFORMANCE_OVERLAY_FLAGS ); + +typedef struct D3D12XBOX_PRESENT_DESC_TITLE_PERFORMANCE_OVERLAY +{ + D3D12XBOX_PRESENT_DESC_TITLE_PERFORMANCE_OVERLAY_FLAGS Flags; + USHORT RenderResolutionWidth; + USHORT RenderResolutionHeight; + USHORT MaxResolutionWidth; + USHORT MaxResolutionHeight; +} D3D12XBOX_PRESENT_TITLE_PERFORMANCE_OVERLAY; + +typedef struct D3D12XBOX_PRESENT_DESC +{ + D3D12XBOX_PRESENT_DESC_TYPE Type; + + union + { + D3D12XBOX_PRESENT_DESC_TITLE_PERFORMANCE_OVERLAY TitlePerfOverlay; + }; +} D3D12XBOX_PRESENT_DESC; + +typedef enum D3D12XBOX_PRESENT_PLANE_DESC_TYPE +{ +} D3D12XBOX_PRESENT_PLANE_DESC_TYPE; + +typedef struct D3D12XBOX_PRESENT_PLANE_DESC +{ + D3D12XBOX_PRESENT_PLANE_DESC_TYPE Type; + +} D3D12XBOX_PRESENT_PLANE_DESC; + +typedef struct D3D12XBOX_PRESENT_PLANE_PARAMETERS +{ + D3D12XBOX_FRAME_PIPELINE_TOKEN Token; + UINT ResourceCount; + ID3D12Resource** ppResources; + D3D12_RECT* pSrcViewRects; + D3D12XBOX_VIEW_RECT* pDestPlacementBase; + DXGI_COLOR_SPACE_TYPE ColorSpace; + D3D12XBOX_PRESENT_PLANE_SCALE_FILTER ScaleFilter; + UINT ExtendedDescCount; + D3D12XBOX_PRESENT_PLANE_DESC* pExtendedDescs; + D3D12XBOX_PRESENT_PLANE_FLAGS Flags; +} D3D12XBOX_PRESENT_PLANE_PARAMETERS; + +typedef struct D3D12XBOX_PRESENT_PARAMETERS +{ + FLOAT ImmediateThresholdPercent; + UINT ViewCount; + UINT ExtendedDescCount; + D3D12XBOX_PRESENT_DESC* pExtendedDescs; + D3D12XBOX_PRESENT_FLAGS Flags; +} D3D12XBOX_PRESENT_PARAMETERS; + +typedef enum D3D12XBOX_FRAME_STATISTICS_TYPE +{ + D3D12XBOX_FRAME_STATISTICS_TYPE_NONE = 0x0, + D3D12XBOX_FRAME_STATISTICS_TYPE_FRAME_INTERVAL = 0x1, + D3D12XBOX_FRAME_STATISTICS_TYPE_FRAME_EVENT = 0x2, + D3D12XBOX_FRAME_STATISTICS_TYPE_POWERSCALING = 0x4, + D3D12XBOX_FRAME_STATISTICS_TYPE_RENDER = 0x100, + D3D12XBOX_FRAME_STATISTICS_TYPE_PRESENT = 0x1000, + D3D12XBOX_FRAME_STATISTICS_TYPE_DISPLAY = 0x10000, + D3D12XBOX_FRAME_STATISTICS_TYPE_INPUT = 0x100000, + +} D3D12XBOX_FRAME_STATISTICS_TYPE; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_FRAME_STATISTICS_TYPE ); + +typedef struct D3D12XBOX_INPUT_STATISTICS +{ + UINT64 Context; + UINT64 OriginTime; + UINT64 AvailableTime; + UINT64 QueryTime; +} D3D12XBOX_INPUT_STATISTICS; + +typedef struct D3D12XBOX_FRAME_INTERVAL_STATISTICS +{ + UINT32 LengthInMicroseconds; + UINT32 PeriodInIntervals; + D3D12XBOX_FRAME_INTERVAL_FLAGS Flags; +} D3D12XBOX_FRAME_INTERVAL_STATISTICS; + +typedef enum D3D12XBOX_FRAME_EVENT_STATISTICS_FLAGS +{ + D3D12XBOX_FRAME_EVENT_STATISTICS_FLAG_NONE = 0x0, + D3D12XBOX_FRAME_EVENT_STATISTICS_FLAG_SIGNAL_PENDING = 0x1, + D3D12XBOX_FRAME_EVENT_STATISTICS_FLAG_INTERVAL_OFFSET_PENDING = 0x2, +} D3D12XBOX_FRAME_EVENT_STATISTICS_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_FRAME_EVENT_STATISTICS_FLAGS ); + +typedef struct D3D12XBOX_FRAME_EVENT_STATISTICS +{ + D3D12XBOX_FRAME_EVENT_TYPE EventType; + UINT64 WaitCallTime; + UINT64 SignalTime; + UINT64 WaitReturnTime; + UINT32 IntervalOffsetInMicroseconds; + D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAGS SignalFlags; + D3D12XBOX_FRAME_EVENT_STATISTICS_FLAGS StatisticsFlags; +} D3D12XBOX_FRAME_EVENT_STATISTICS; + +typedef enum D3D12XBOX_FRAME_PRESENT_STATISTICS_FLAGS +{ + D3D12XBOX_FRAME_PRESENT_STATISTICS_FLAG_NONE = 0x0, + D3D12XBOX_FRAME_PRESENT_STATISTICS_FLAG_FRAME_DROP = 0x1, +} D3D12XBOX_FRAME_PRESENT_STATISTICS_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_FRAME_PRESENT_STATISTICS_FLAGS ); + +typedef struct D3D12XBOX_PRESENT_STATISTICS +{ + UINT8 PlaneIndex; + UINT8 PlaneCount; + UINT8 ViewCount; + UINT64 PresentCallTime; + UINT64 PresentQueueTime; + UINT64 PresentReturnTime; + UINT64 GPUProcessTime; + UINT8 QueuedFrameCount; + UINT16 PlaneSwapMask; + D3D12XBOX_FRAME_PRESENT_STATISTICS_FLAGS Flags; +} D3D12XBOX_PRESENT_STATISTICS; + +typedef struct D3D12XBOX_RENDER_STATISTICS +{ + UINT8 PlaneIndex; + UINT64 GPUWriteCompleteTime; + UINT64 GPUBusyDuration; +} D3D12XBOX_RENDER_STATISTICS; + +typedef struct D3D12XBOX_DISPLAY_STATISTICS +{ + UINT8 PlaneIndex; + UINT64 VSyncTime; + UINT64 FlipTime; + FLOAT PercentScanned; +} D3D12XBOX_DISPLAY_STATISTICS; + +typedef struct D3D12XBOX_POWERSCALING_STATISTICS +{ + UINT8 PlaneIndex; + UINT64 GPUBusyDurationScaled; + double ScaleFactor; +} D3D12XBOX_POWERSCALING_STATISTICS; + +typedef struct D3D12XBOX_FRAME_STATISTICS +{ + D3D12XBOX_FRAME_STATISTICS_TYPE Type; + + union + { + D3D12XBOX_FRAME_INTERVAL_STATISTICS Interval; + D3D12XBOX_FRAME_EVENT_STATISTICS Event; + D3D12XBOX_INPUT_STATISTICS Input; + D3D12XBOX_RENDER_STATISTICS Render; + D3D12XBOX_PRESENT_STATISTICS Present; + D3D12XBOX_DISPLAY_STATISTICS Display; + D3D12XBOX_POWERSCALING_STATISTICS PowerScaling; + }; +} D3D12XBOX_FRAME_STATISTICS; + + +#define D3D12_SDK_VERSION_MAJOR 2 +#define D3D12_SDK_VERSION_MINOR 4 + +#define D3D12_SDK_VERSION ((D3D12_SDK_VERSION_MAJOR << 16 ) | D3D12_SDK_VERSION_MINOR) + +} + + +typedef enum D3D12XBOX_HARDWARE_VERSION +{ + D3D12XBOX_HARDWARE_VERSION_XBOX_ONE = 0, + D3D12XBOX_HARDWARE_VERSION_XBOX_ONE_S = 1, + D3D12XBOX_HARDWARE_VERSION_XBOX_ONE_X = 2, + D3D12XBOX_HARDWARE_VERSION_XBOX_ONE_X_DEVKIT = 3, + D3D12XBOX_HARDWARE_VERSION_XBOX_SCARLETT_LOCKHART = 4, + D3D12XBOX_HARDWARE_VERSION_XBOX_SCARLETT_ANACONDA = 5, + D3D12XBOX_HARDWARE_VERSION_XBOX_SCARLETT_DEVKIT = 6, +} D3D12XBOX_HARDWARE_VERSION; + +// Definitions to maintain backwards compat with previous XDKs. +#define D3D12XBOX_HARDWARE_VERSION_SCORPIO D3D12XBOX_HARDWARE_VERSION_XBOX_ONE_X +#define D3D12XBOX_HARDWARE_VERSION_SCORPIO_DEVKIT D3D12XBOX_HARDWARE_VERSION_XBOX_ONE_X_DEVKIT + +typedef struct D3D12XBOX_GPU_HARDWARE_CONFIGURATION +{ + UINT64 GpuFrequency; + D3D12XBOX_HARDWARE_VERSION HardwareVersion; +} D3D12XBOX_GPU_HARDWARE_CONFIGURATION; + +typedef enum D3D12XBOX_PREFETCH_MEMORY_FLAGS +{ + D3D12XBOX_PREFETCH_MEMORY_FLAG_NONE = 0, + D3D12XBOX_PREFETCH_MEMORY_FLAG_USE_PFP = 0x1 +} D3D12XBOX_PREFETCH_MEMORY_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_PREFETCH_MEMORY_FLAGS); + +typedef enum D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAGS +{ + D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAG_CS = 0x01, + D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAG_PS = 0x02, + D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAG_VS = 0x04, + D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAG_GS = 0x08, + D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAG_ES = 0x10, + D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAG_HS = 0x20, + D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAG_LS = 0x40, + D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAG_GRAPHICS = 0x7E, +} D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAGS); + + +typedef enum D3D12XBOX_BINNING_FLAGS +{ + D3D12XBOX_BINNING_FLAG_NONE = 0, +} D3D12XBOX_BINNING_FLAGS; + +typedef enum D3D12XBOX_BINNING_MODE +{ + D3D12XBOX_BINNING_MODE_BINNING_ALLOWED = 0, + D3D12XBOX_BINNING_MODE_FORCE_BINNING_ON = 1, + D3D12XBOX_BINNING_MODE_DISABLE_BINNING_USE_NEW_SC = 2, + D3D12XBOX_BINNING_MODE_DISABLE_BINNING_USE_LEGACY_SC = 3, +} D3D12XBOX_BINNING_MODE; + +typedef enum D3D12XBOX_BIN_SIZE +{ + D3D12XBOX_BIN_SIZE_32_PIXELS = 0, + D3D12XBOX_BIN_SIZE_64_PIXELS = 1, + D3D12XBOX_BIN_SIZE_128_PIXELS = 2, + D3D12XBOX_BIN_SIZE_256_PIXELS = 3, + D3D12XBOX_BIN_SIZE_512_PIXELS = 4, +} D3D12XBOX_BIN_SIZE; + +typedef enum D3D12XBOX_BIN_MAPPING_MODE +{ + D3D12XBOX_BIN_MAPPING_MODE_NONE = 0, + D3D12XBOX_BIN_MAPPING_MODE_RENDER_TARGET_ARRAY_INDEX = 1, + D3D12XBOX_BIN_MAPPING_MODE_POPS = 2, +} D3D12XBOX_BIN_MAPPING_MODE; + +#define D3D12XBOX_BINNING_PARAMETER_DEFAULT ((UINT)-1) + +typedef struct D3D12XBOX_DPBB_STATE +{ + D3D12XBOX_BINNING_FLAGS Flags; + D3D12XBOX_BINNING_MODE BinningMode; + D3D12XBOX_BIN_SIZE BinSizeX; + D3D12XBOX_BIN_SIZE BinSizeY; + UINT ContextStatesPerBin; + UINT PersistentStatesPerBin; + BOOL DisableStartOfPrimitive; + UINT FPOVTokensPerBatch; + BOOL OptimalBinSelection; + BOOL FlushOnBinningTransition; + D3D12XBOX_BIN_MAPPING_MODE MappingMode; + BOOL FSRExpansionEnable; + UINT MaxParameterAllocPerBatch; + UINT MaxPrimitivesPerBatch; +} D3D12XBOX_DPBB_STATE; + + + +D3DINLINE void D3D12XboxInitializeDefaultDpbbState( + D3D12XBOX_DPBB_STATE* pDesc) +{ + ZeroMemory(pDesc, sizeof(*pDesc)); + pDesc->BinningMode = D3D12XBOX_BINNING_MODE_DISABLE_BINNING_USE_LEGACY_SC; + pDesc->BinSizeX = D3D12XBOX_BIN_SIZE_128_PIXELS; + pDesc->BinSizeY = D3D12XBOX_BIN_SIZE_128_PIXELS; + pDesc->FlushOnBinningTransition = TRUE; + pDesc->ContextStatesPerBin = D3D12XBOX_BINNING_PARAMETER_DEFAULT; + pDesc->PersistentStatesPerBin = D3D12XBOX_BINNING_PARAMETER_DEFAULT; + pDesc->FPOVTokensPerBatch = D3D12XBOX_BINNING_PARAMETER_DEFAULT; + pDesc->MaxParameterAllocPerBatch = D3D12XBOX_BINNING_PARAMETER_DEFAULT; + pDesc->MaxPrimitivesPerBatch = D3D12XBOX_BINNING_PARAMETER_DEFAULT; +} + +extern "C" +{ + +// +// ID3D12Pageable +// + +struct D3D12Pageable_Function_Table +{ + D3D12DeviceChild_Function_Table DeviceChildFunction; +}; + + +} + +D3DINTERFACE(ID3D12Pageable, 63ee58fb,1268,4835,86,da,f0,08,ce,62,f0,d6) : public ID3D12DeviceChild +{ +public: + + D3DINLINE D3D12Pageable_Function_Table* PageableFunction() + { + return (D3D12Pageable_Function_Table*)m_pFunction; + } +}; + + +extern "C" +{ + +// +// ID3D12Heap +// + +struct D3D12Heap_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; + + void (D3DAPI* GetDesc)( + _Inout_ ID3D12Heap* pHeap, + _Out_ D3D12_HEAP_DESC* pDesc); +}; + + +} + +D3DINTERFACE(ID3D12Heap, 6b3b2502,6e51,45b3,90,ee,98,84,26,5e,8d,f3) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12Heap_Function_Table* HeapFunction() + { + return (D3D12Heap_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_HEAP_DESC D3DAPI GetDesc() + { + D3D12_HEAP_DESC desc; + HeapFunction()->GetDesc(this, &desc); + return desc; + } +}; + + +extern "C" +{ + +// +// ID3D12Resource +// + +typedef enum D3D12XBOX_RESOURCE_VALIDATION_FLAGS +{ + D3D12XBOX_RESOURCE_VALIDATION_FLAG_NONE = 0, + D3D12XBOX_RESOURCE_VALIDATION_FLAG_DISABLE_BARRIER_VALIDATION = 1, +} D3D12XBOX_RESOURCE_VALIDATION_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS(D3D12XBOX_RESOURCE_VALIDATION_FLAGS); + +struct D3D12Resource_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; + + HRESULT (D3DAPI* Map)( + _Inout_ ID3D12Resource* pResource, + UINT Subresource, + _In_opt_ const D3D12_RANGE* pReadRange, + _Outptr_ void **ppData); + + void (D3DAPI* Unmap)( + _Inout_ ID3D12Resource* pResource, + UINT Subresource, + _In_opt_ const D3D12_RANGE* pWrittenRange); + + void (D3DAPI* GetDesc)( + _Inout_ ID3D12Resource* pResource, + _Out_ D3D12_RESOURCE_DESC* pDesc); + + D3D12_GPU_VIRTUAL_ADDRESS (D3DAPI* GetGPUVirtualAddress)( + _Inout_ ID3D12Resource* pResource); + + HRESULT (D3DAPI* WriteToSubresource)( + _Inout_ ID3D12Resource* pResource, + UINT DstSubresource, + _In_opt_ const D3D12_BOX* pDstBox, + _In_ const void* pSrcData, + UINT SrcRowPitch, + UINT SrcDepthPitch); + + HRESULT (D3DAPI* ReadFromSubresource)( + _Inout_ ID3D12Resource* pResource, + _Out_ void* pDstData, + UINT DstRowPitch, + UINT DstDepthPitch, + UINT SrcSubresource, + _In_opt_ const D3D12_BOX* pSrcBox); + + HRESULT (D3DAPI* GetHeapProperties)( + _Inout_ ID3D12Resource* pResource, + _Out_opt_ D3D12_HEAP_PROPERTIES* pHeapProperties, + _Out_opt_ D3D12_HEAP_FLAGS* pHeapFlags); + + D3D12_RESOURCE_DESC (D3DAPI* GetPlacementDescX)( + _Inout_ ID3D12Resource* pResource); + + D3D12XBOX_RESOURCE_VALIDATION_FLAGS (D3DAPI* GetValidationFlagsX)( + _Inout_ ID3D12Resource* pResource); + + void (D3DAPI* SetValidationFlagsX)( + _Inout_ ID3D12Resource* pResource, + _In_ D3D12XBOX_RESOURCE_VALIDATION_FLAGS Flags); +}; + + +} + +D3DINTERFACE(ID3D12Resource, 696442be,a72e,4059,bc,79,5b,5c,98,04,0f,ad) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12Resource_Function_Table* ResourceFunction() + { + return (D3D12Resource_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI Map( + UINT Subresource, + _In_opt_ const D3D12_RANGE* pReadRange, + _Outptr_ void **ppData) + { + return ResourceFunction()->Map(this, Subresource, pReadRange, ppData); + } + + D3DINLINE void D3DAPI Unmap( + UINT Subresource, + _In_opt_ const D3D12_RANGE* pWrittenRange) + { + ResourceFunction()->Unmap(this, Subresource, pWrittenRange); + } + + D3DINLINE D3D12_RESOURCE_DESC D3DAPI GetDesc() + { + D3D12_RESOURCE_DESC desc; + ResourceFunction()->GetDesc(this, &desc); + return desc; + } + + D3DINLINE D3D12_GPU_VIRTUAL_ADDRESS D3DAPI GetGPUVirtualAddress() + { + return ResourceFunction()->GetGPUVirtualAddress(this); + } + + D3DINLINE HRESULT D3DAPI WriteToSubresource( + UINT DstSubresource, + _In_opt_ const D3D12_BOX* pDstBox, + _In_ const void* pSrcData, + UINT SrcRowPitch, + UINT SrcDepthPitch) + { + return ResourceFunction()->WriteToSubresource(this, + DstSubresource, + pDstBox, + pSrcData, + SrcRowPitch, + SrcDepthPitch); + } + + D3DINLINE HRESULT D3DAPI ReadFromSubresource( + _Out_ void* pDstData, + UINT DstRowPitch, + UINT DstDepthPitch, + UINT SrcSubresource, + _In_opt_ const D3D12_BOX* pSrcBox) + { + return ResourceFunction()->ReadFromSubresource(this, + pDstData, + DstRowPitch, + DstDepthPitch, + SrcSubresource, + pSrcBox); + } + + D3DINLINE HRESULT D3DAPI GetHeapProperties( + _Out_opt_ D3D12_HEAP_PROPERTIES* pHeapProperties, + _Out_opt_ D3D12_HEAP_FLAGS* pHeapFlags) + { + return ResourceFunction()->GetHeapProperties(this, + pHeapProperties, + pHeapFlags); + } + + D3DINLINE D3D12_RESOURCE_DESC GetPlacementDescX() + { + return ResourceFunction()->GetPlacementDescX(this); + } + + D3DINLINE D3D12XBOX_RESOURCE_VALIDATION_FLAGS GetValidationFlagsX() + { + return ResourceFunction()->GetValidationFlagsX(this); + } + + D3DINLINE void SetValidationFlagsX( + _In_ D3D12XBOX_RESOURCE_VALIDATION_FLAGS Flags) + { + ResourceFunction()->SetValidationFlagsX(this, Flags); + } +}; + + +extern "C" +{ + +enum D3D12XBOX_COMMAND_ALLOCATOR_CALLBACK_FLAGS +{ + D3D12XBOX_COMMAND_ALLOCATOR_CALLBACK_FLAG_32BIT_ALLOCATION_REQUIRED = 1, +}; + +typedef void* (*D3D12XBOX_COMMAND_ALLOCATOR_CALLBACK)( + ID3D12CommandAllocator* pCommandAllocator, + ID3D12CommandList* pCommandList, + UINT XMemAllocType, + SIZE_T SizeInBytes, + UINT AlignmentInBytes, + UINT Flags, + UINT64 Context); + +// +// ID3D12CommandAllocator +// + +struct D3D12CommandAllocator_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; + + HRESULT (D3DAPI* Reset)( + _Inout_ ID3D12CommandAllocator* pAllocator); + + void (D3DAPI* SetAllocatorCallbackX)( + _Inout_ ID3D12CommandAllocator* pAllocator, + _In_ D3D12XBOX_COMMAND_ALLOCATOR_CALLBACK pCallback, + _In_ UINT64 Context); +}; + + +} + +D3DINTERFACE(ID3D12CommandAllocator, 6102dee4,af59,4b09,b9,99,b4,4d,73,f0,9b,24) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12CommandAllocator_Function_Table* AllocatorFunction() + { + return (D3D12CommandAllocator_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI Reset() + { + return AllocatorFunction()->Reset(this); + } + + D3DINLINE void D3DAPI SetAllocatorCallbackX( + _In_ D3D12XBOX_COMMAND_ALLOCATOR_CALLBACK pCallback, + _In_ UINT64 Context) + { + AllocatorFunction()->SetAllocatorCallbackX(this, pCallback, Context); + } +}; + + +extern "C" +{ + +// +// ID3D12Fence +// + +struct D3D12Fence_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; + + UINT64 (D3DAPI* GetCompletedValue)( + _Inout_ ID3D12Fence* pFence); + + HRESULT (D3DAPI* SetEventOnCompletion)( + _Inout_ ID3D12Fence* pFence, + _In_ UINT64 Value, + _In_ HANDLE hEvent); + + HRESULT (D3DAPI* Signal)( + _Inout_ ID3D12Fence* pFence, + _In_ UINT64 Value); +}; + + +} + +D3DINTERFACE(ID3D12Fence, 0a753dcf,c4d8,4b91,ad,f6,be,5a,60,d9,5a,76) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12Fence_Function_Table* FenceFunction() + { + return (D3D12Fence_Function_Table*)m_pFunction; + } + + D3DINLINE UINT64 D3DAPI GetCompletedValue() + { + return FenceFunction()->GetCompletedValue(this); + } + + D3DINLINE HRESULT D3DAPI SetEventOnCompletion( + _In_ UINT64 Value, + _In_ HANDLE hEvent) + { + return FenceFunction()->SetEventOnCompletion(this, Value, hEvent); + } + + D3DINLINE HRESULT D3DAPI Signal( + _In_ UINT64 Value) + { + return FenceFunction()->Signal(this, Value); + } +}; + + +extern "C" +{ + +// +// ID3D12Fence1 +// + +struct D3D12Fence1_Function_Table +{ + D3D12Fence_Function_Table FenceFunction; + + D3D12_FENCE_FLAGS (D3DAPI* GetCreationFlags)( + _Inout_ ID3D12Fence1* pFence); + + D3D12_GPU_VIRTUAL_ADDRESS(D3DAPI* GetGpuAddressX)( + _Inout_ ID3D12Fence1* pFence); +}; + + +} + +D3DINTERFACE(ID3D12Fence1, 433685fe,e22b,4ca0,a8,db,b5,b4,f4,dd,0e,4a) : public ID3D12Fence +{ +public: + + D3DINLINE D3D12Fence1_Function_Table* Fence1Function() + { + return (D3D12Fence1_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_FENCE_FLAGS D3DAPI GetCreationFlags() + { + return Fence1Function()->GetCreationFlags(this); + } + + D3DINLINE D3D12_GPU_VIRTUAL_ADDRESS D3DAPI GetGpuAddressX() + { + return Fence1Function()->GetGpuAddressX(this); + } +}; + + +extern "C" +{ + + +// +// Shader symbol information +// Returned in response to D3D12XBOX_PIPELINE_STATE_INFORMATION_TYPE_SYMBOL_TABLE +// The name pointers are valid while the pipeline state is alive +// The function pointers are valid while the pipeline state is alive +// + +struct D3D12XBOX_SHADER_SYMBOL +{ + const char* pFunctionName; + UINT FunctionOffset; + + UINT ScratchPerWaveInUnitsOf256DW : 16; + UINT ScratchPerLaneInDW : 16; + UINT LDSDwordsPerThreadgroup : 16; + UINT Reserved : 16; + UINT NumVGPRs : 9; + UINT HasIndirectCalls : 1; + UINT EntryPoint : 1; + UINT NumSGPRs : 8; +}; + +struct D3D12XBOX_SHADER_SYMBOL_LIST +{ + const D3D12XBOX_SHADER_SYMBOL* pSymbols; + D3D12_GPU_VIRTUAL_ADDRESS ShaderAllocationBase; + UINT NumSymbols; + UINT TotalShaderSize; +}; + + +// +// Can be used to retrieve internal information about the Pipeline State Object +// +enum D3D12XBOX_PIPELINE_STATE_INFORMATION_TYPE +{ + D3D12XBOX_PIPELINE_STATE_INFORMATION_TYPE_SCRATCH_SIZE_PER_WAVE_IN_UNITS_OF_256DW, // Return one UINT -- scratch size per wave in units of 1024B. If scratch size is 0 then it is disabled. + D3D12XBOX_PIPELINE_STATE_INFORMATION_TYPE_SYMBOL_TABLE, // Returns shader's symbol table. Only compute is supported. +}; + +// +// Can be used to retrieve internal information about the Pipeline State Object. Raytracing doesn't know these until the callgraph is known +// so can't make these settings during the PSO create. +// +enum D3D12XBOX_PIPELINE_STATE_OPTION_TYPE +{ + D3D12XBOX_PIPELINE_STATE_OPTION_TYPE_ENABLE_USE_OF_PRIVATE_SCRATCH, // Turns off SCRATCH_EN and expects the shader to call SetPrivateScratch function. Shader must not be in use during this call. Only compute is supported. + D3D12XBOX_PIPELINE_STATE_OPTION_TYPE_SET_NUM_VGPRS, // Set the number of VGPRs for the entry point + D3D12XBOX_PIPELINE_STATE_OPTION_TYPE_SET_LDS_SIZE_IN_DWORDS_PER_THREADGROUP, // Set the LDS size for the entry point + D3D12XBOX_PIPELINE_STATE_OPTION_TYPE_SET_EXCP_EN, // Set TRAP_EN and other options +}; + +// +// ID3D12PipelineState +// + +struct D3D12PipelineState_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; + + HRESULT (D3DAPI* GetCachedBlob)( + _Inout_ ID3D12PipelineState* pPipelineState, + _Out_ ID3DBlob **ppBlob); + + HRESULT (D3DAPI *GetGraphicsDesc)( + _Inout_ ID3D12PipelineState *pPipelineState, + _Out_ D3D12_GRAPHICS_PIPELINE_STATE_DESC *pDesc, + _Inout_ D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_DESC *pExtDescs, + _In_ UINT extDescsCount, + _Out_ D3D12_SO_DECLARATION_ENTRY (&soEntries)[D3D12_SO_BUFFER_SLOT_COUNT], + _Out_ D3D12_INPUT_ELEMENT_DESC (&inputLayoutElements)[D3D12_STANDARD_VERTEX_ELEMENT_COUNT]); + + HRESULT (D3DAPI* GetComputeDesc)( + _Inout_ ID3D12PipelineState* pPipelineState, + _Out_ D3D12_COMPUTE_PIPELINE_STATE_DESC *pDesc, + _Inout_ D3D12XBOX_EXTENDED_COMPUTE_PIPELINE_STATE_DESC *pExtDescs, + _In_ UINT extDescsCount); + + // Return extended information about this pipeline state object + HRESULT (D3DAPI* GetInformationX)( + _Inout_ ID3D12PipelineState* pPipelineState, + _In_ D3D12XBOX_PIPELINE_STATE_INFORMATION_TYPE info, + _In_ UINT64 extraOptions, + _Out_ ID3DBlob **ppBlob); + + // Set extended option + HRESULT (D3DAPI* SetOptionX)( + _Inout_ ID3D12PipelineState* pPipelineState, + _In_ D3D12XBOX_PIPELINE_STATE_OPTION_TYPE type, + _In_ UINT64 extraFlags, + _In_ UINT optionSize, + _In_ const void* pOptionData); + + // Patch shaders + HRESULT (D3DAPI* PatchShadersX)( + _Inout_ ID3D12PipelineState* pPipelineState, + _In_opt_ const void* pVS, + _In_opt_ const void* pPS, + _In_opt_ const void* pES, + _In_opt_ const void* pGS, + _In_opt_ const void* pLS, + _In_opt_ const void* pHS, + _In_opt_ const void* pFS, + _In_opt_ const void* pCS); +}; + + +} + +D3DINTERFACE(ID3D12PipelineState, 765a30f3,f624,4c6f,a8,28,ac,e9,48,62,24,45) : public ID3D12Pageable +{ +public: + + // This is the Command buffer packet representing this Pipeline State object. Although + // the packet itself is 6 dwords, here we SSE align and pad to 8 dwords for convenience. + // The two padding dwords contain a NOP instruction: + union + { + D3D12XBOX_DESCRIPTOR_PIPELINE_STATE Descriptor; + __m128i Oword[2]; + UINT64 Qword[4]; + UINT32 Dword[8]; + } m_Packet; + + #define D3D12XBOX_GRAPHICS_PSO_TESSELLATION_FLAG 0x1 + #define D3D12XBOX_GRAPHICS_PSO_GEOMETRY_FLAG 0x2 + #define D3D12XBOX_COMPUTE_PSO_WAVE32_FLAG 0x100000 + + // Only Valid for Compute PSOs + bool IsWave32() const + { + return (m_Packet.Dword[4] & D3D12XBOX_COMPUTE_PSO_WAVE32_FLAG); + } + + static bool UsesHardwareGSorHS(const D3D12XBOX_DESCRIPTOR_PIPELINE_STATE* pDescriptor) + { + return !!(pDescriptor->ContextHash & (D3D12XBOX_GRAPHICS_PSO_TESSELLATION_FLAG | D3D12XBOX_GRAPHICS_PSO_GEOMETRY_FLAG)); + } + + bool UsesHardwareGSorHS() const + { + return UsesHardwareGSorHS(&m_Packet.Descriptor); + } + + +public: + + D3DINLINE D3D12PipelineState_Function_Table* PipelineStateFunction() + { + return (D3D12PipelineState_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetCachedBlob( + _Out_ ID3DBlob **ppBlob) + { + return PipelineStateFunction()->GetCachedBlob(this, ppBlob); + } + + + D3DINLINE void D3DAPI GetDescriptorX( + _Out_ D3D12XBOX_DESCRIPTOR_PIPELINE_STATE* pDescriptor) + { + *pDescriptor = m_Packet.Descriptor; + } + + D3DINLINE HRESULT D3DAPI GetInformationX( + _In_ D3D12XBOX_PIPELINE_STATE_INFORMATION_TYPE info, + _In_ UINT64 extraOptions, + _Out_ ID3DBlob **ppBlob) + { + return PipelineStateFunction()->GetInformationX(this, + info, + extraOptions, + ppBlob); + } + + D3DINLINE HRESULT D3DAPI SetOptionX( + _In_ D3D12XBOX_PIPELINE_STATE_OPTION_TYPE type, + _In_ UINT64 extraFlags, + _In_ UINT optionSize, + _In_ const void* pOptionData) + { + return PipelineStateFunction()->SetOptionX( + this, + type, + extraFlags, + optionSize, + pOptionData); + } + + D3DINLINE HRESULT D3DAPI PatchShadersX( + _In_opt_ const void* pVS, + _In_opt_ const void* pPS, + _In_opt_ const void* pES, + _In_opt_ const void* pGS, + _In_opt_ const void* pLS, + _In_opt_ const void* pHS, + _In_opt_ const void* pFS, + _In_opt_ const void* pCS) + { + return PipelineStateFunction()->PatchShadersX( + this, + pVS, + pPS, + pES, + pGS, + pLS, + pHS, + pFS, + pCS); + } +}; + + +extern "C" +{ + +// +// ID3D12DescriptorHeap +// + +typedef UINT D3D12XBOX_SAMPLER_DESCRIPTOR_HEAP_BCT_HANDLE; + +struct D3D12DescriptorHeap_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; + + void (D3DAPI* GetDesc)( + _Inout_ ID3D12DescriptorHeap* pHeap, + _Out_ D3D12_DESCRIPTOR_HEAP_DESC* pDesc); + + D3D12_CPU_DESCRIPTOR_HANDLE (D3DAPI* GetCPUDescriptorHandleForHeapStart)( + _Inout_ ID3D12DescriptorHeap* pHeap); + + D3D12_GPU_DESCRIPTOR_HANDLE (D3DAPI* GetGPUDescriptorHandleForHeapStart)( + _Inout_ ID3D12DescriptorHeap* pHeap); + + D3D12XBOX_SAMPLER_DESCRIPTOR_HEAP_BCT_HANDLE (D3DAPI* GetSamplerBorderColorTableX)( + _Inout_ ID3D12DescriptorHeap* pHeap); +}; + + +} + +D3DINTERFACE(ID3D12DescriptorHeap, 8efb471d,616c,4f49,90,f7,12,7b,b7,63,fa,51) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12DescriptorHeap_Function_Table* DescriptorHeapFunction() + { + return (D3D12DescriptorHeap_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_DESCRIPTOR_HEAP_DESC GetDesc() + { + D3D12_DESCRIPTOR_HEAP_DESC Desc; + DescriptorHeapFunction()->GetDesc(this, &Desc); + return Desc; + } + + D3DINLINE D3D12_CPU_DESCRIPTOR_HANDLE D3DAPI GetCPUDescriptorHandleForHeapStart() + { + return DescriptorHeapFunction()->GetCPUDescriptorHandleForHeapStart(this); + } + + D3DINLINE D3D12_GPU_DESCRIPTOR_HANDLE D3DAPI GetGPUDescriptorHandleForHeapStart() + { + return DescriptorHeapFunction()->GetGPUDescriptorHandleForHeapStart(this); + } + + D3DINLINE D3D12XBOX_SAMPLER_DESCRIPTOR_HEAP_BCT_HANDLE D3DAPI GetSamplerBorderColorTableX() + { + return DescriptorHeapFunction()->GetSamplerBorderColorTableX(this); + } +}; + +extern "C" +{ + +// +// ID3D12QueryHeap +// + +struct D3D12QueryHeap_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; +}; + + +} + +D3DINTERFACE(ID3D12QueryHeap, 0d9658ae,ed45,469e,a6,1d,97,0e,c5,83,ca,b4) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12QueryHeap_Function_Table* QueryHeapFunction() + { + return (D3D12QueryHeap_Function_Table*)m_pFunction; + } +}; + +extern "C" +{ + +// +// ID3D12CommandSignature +// + +struct D3D12CommandSignature_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; +}; + + +} + +D3DINTERFACE(ID3D12CommandSignature, c36a797c,ec80,4f0a,89,85,a7,b2,47,50,82,d1) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12CommandSignature_Function_Table* CommandSignatureFunction() + { + return (D3D12CommandSignature_Function_Table*)m_pFunction; + } +}; + +extern "C" +{ + +// +// ID3D12CommandList +// + +struct D3D12CommandList_Function_Table +{ + D3D12DeviceChild_Function_Table DeviceChildFunction; + + D3D12_COMMAND_LIST_TYPE (D3DAPI* GetType)( + _Inout_ ID3D12CommandList* pCommandList); +}; + + +} + +D3DINTERFACE(ID3D12CommandList, 7116d91c,e7e4,47ce,b8,c6,ec,81,68,f4,37,e5) : public ID3D12DeviceChild +{ +public: + + D3D12_COMMAND_LIST_TYPE m_Type; + +public: + + D3DINLINE D3D12CommandList_Function_Table* CommandListFunction() + { + return (D3D12CommandList_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_COMMAND_LIST_TYPE D3DAPI GetType() + { + return CommandListFunction()->GetType(this); + } +}; + + +extern "C" +{ + +// +// ID3D12GraphicsCommandList +// + +struct D3D12GraphicsCommandList_Function_Table +{ + D3D12CommandList_Function_Table CommandListFunction; + + HRESULT (D3DAPI* Close)( + _Inout_ ID3D12GraphicsCommandList* pCommandList); + + HRESULT (D3DAPI* Reset)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12CommandAllocator* pAllocator, + _In_opt_ ID3D12PipelineState* pInitialState); + + void (D3DAPI* ClearState)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_opt_ ID3D12PipelineState* pPipelineState); + + void (D3DAPI* DrawInstanced)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT VertexCountPerInstance, + _In_ UINT InstanceCount, + _In_ UINT StartVertexLocation, + _In_ UINT StartInstanceLocation); + + void (D3DAPI* DrawIndexedInstanced)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT IndexCountPerInstance, + _In_ UINT InstanceCount, + _In_ UINT StartIndexLocation, + _In_ INT BaseVertexLocation, + _In_ UINT StartInstanceLocation); + + void (D3DAPI* Dispatch)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT ThreadGroupCountX, + _In_ UINT ThreadGroupCountY, + _In_ UINT ThreadGroupCountZ); + + void (D3DAPI* CopyBufferRegion)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pDstBuffer, + UINT64 DstOffset, + _In_ ID3D12Resource* pSrcBuffer, + UINT64 SrcOffset, + UINT64 NumBytes); + + void (D3DAPI* CopyTextureRegion)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, + UINT DstX, + UINT DstY, + UINT DstZ, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pSrc, + _In_opt_ const D3D12_BOX* pSrcBox); + + void (D3DAPI* CopyResource)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pDstResource, + _In_ ID3D12Resource* pSrcResource); + + void (D3DAPI* CopyTiles)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pTiledResource, + _In_ const D3D12_TILED_RESOURCE_COORDINATE* pTileRegionStartCoordinate, + _In_ const D3D12_TILE_REGION_SIZE* pTileRegionSize, + _In_ ID3D12Resource* pBuffer, + UINT64 BufferStartOffsetInBytes, + D3D12_TILE_COPY_FLAGS Flags); + + void (D3DAPI* ResolveSubresource)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pDstResource, + _In_ UINT DstSubresource, + _In_ ID3D12Resource* pSrcResource, + _In_ UINT SrcSubresource, + _In_ DXGI_FORMAT Format); + + void (D3DAPI* IASetPrimitiveTopology)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_PRIMITIVE_TOPOLOGY PrimitiveTopology); + + void (D3DAPI* RSSetViewports)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT Count, + _In_reads_( Count) const D3D12_VIEWPORT* pViewports); + + void (D3DAPI* RSSetScissorRects)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT Count, + _In_reads_( Count) const D3D12_RECT* pRects); + + void (D3DAPI* OMSetBlendFactor)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_reads_opt_(4) const FLOAT BlendFactor[4]); + + void (D3DAPI* OMSetStencilRef)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT StencilRef); + + void (D3DAPI* SetPipelineState)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12PipelineState* pPipelineState); + + D3D12XBOX_RESOURCE_BARRIER_ACTIONS (D3DAPI* ResourceBarrier)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER* pBarriers); + + void (D3DAPI* ExecuteBundle)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12GraphicsCommandList *pBundle); + + void (D3DAPI* BeginQuery)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void (D3DAPI* EndQuery)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void (D3DAPI* ResolveQueryData)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartIndex, + _In_ UINT NumQueries, + _In_ ID3D12Resource* pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset); + + void (D3DAPI* SetPredication)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_opt_ ID3D12Resource* pBuffer, + _In_ UINT64 AlignedBufferOffset, + _In_ D3D12_PREDICATION_OP Operation); + + void (D3DAPI* SetDescriptorHeaps)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT NumDescriptorHeaps, + _In_reads_(NumDescriptorHeaps) ID3D12DescriptorHeap*const* pDescriptorHeaps); + + void (D3DAPI* SetComputeRootSignature)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12RootSignature* pRootSignature); + + void (D3DAPI* SetGraphicsRootSignature)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12RootSignature* pRootSignature); + + void (D3DAPI* SetComputeRootDescriptorTable)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor); + + void (D3DAPI* SetGraphicsRootDescriptorTable)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor); + + void (D3DAPI* SetComputeRoot32BitConstant)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ UINT SrcData, + _In_ UINT DestOffsetIn32BitValues); + + void (D3DAPI* SetGraphicsRoot32BitConstant)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ UINT SrcData, + _In_ UINT DestOffsetIn32BitValues); + + void (D3DAPI* SetComputeRoot32BitConstants)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ UINT Num32BitValuesToSet, + _In_reads_(Num32BitValuesToSet*sizeof(UINT)) const void* pSrcData, + _In_ UINT DestOffsetIn32BitValues); + + void (D3DAPI* SetGraphicsRoot32BitConstants)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ UINT Num32BitValuesToSet, + _In_reads_(Num32BitValuesToSet*sizeof(UINT)) const void* pSrcData, + _In_ UINT DestOffsetIn32BitValues); + + void (D3DAPI* SetComputeRootConstantBufferView)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation); + + void (D3DAPI* SetGraphicsRootConstantBufferView)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation); + + void (D3DAPI* SetComputeRootShaderResourceView)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation); + + void (D3DAPI* SetGraphicsRootShaderResourceView)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation); + + void (D3DAPI* SetComputeRootUnorderedAccessView)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation); + + void (D3DAPI* SetGraphicsRootUnorderedAccessView)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation); + + void (D3DAPI* IASetIndexBuffer)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_opt_ const D3D12_INDEX_BUFFER_VIEW* pView); + + void (D3DAPI* IASetVertexBuffers)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT StartSlot, + _In_ UINT NumViews, + _In_reads_opt_(NumViews) const D3D12_VERTEX_BUFFER_VIEW* pViews); + + void (D3DAPI* SOSetTargets)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT StartSlot, + _In_ UINT NumViews, + _In_reads_opt_(NumViews) const D3D12_STREAM_OUTPUT_BUFFER_VIEW* pViews); + + void (D3DAPI* OMSetRenderTargets)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT NumRenderTargetDescriptors, + _In_opt_ const D3D12_CPU_DESCRIPTOR_HANDLE* pRenderTargetDescriptors, + _In_ BOOL RTsSingleHandleToDescriptorRange, + _In_opt_ const D3D12_CPU_DESCRIPTOR_HANDLE* pDepthStencilDescriptor); + + void (D3DAPI* ClearDepthStencilView)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DepthStencilView, + _In_ D3D12_CLEAR_FLAGS ClearFlags, + _In_ FLOAT Depth, + _In_ UINT8 Stencil, + _In_ UINT NumRects, + _In_reads_(NumRects) const D3D12_RECT* pRect); + + void (D3DAPI* ClearRenderTargetView)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetView, + _In_ const FLOAT ColorRGBA[4], + _In_ UINT NumRects, + _In_reads_(NumRects) const D3D12_RECT* pRects); + + void (D3DAPI* ClearUnorderedAccessViewUint)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, + _In_ ID3D12Resource* pResource, + _In_ const UINT Values[4], + _In_ UINT NumRects, + _In_reads_(NumRects) const D3D12_RECT* pRects); + + void (D3DAPI* ClearUnorderedAccessViewFloat)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, + _In_ ID3D12Resource* pResource, + _In_ const FLOAT Values[4], + _In_ UINT NumRects, + _In_reads_(NumRects) const D3D12_RECT* pRects); + + void (D3DAPI* DiscardResource)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pResource, + _In_opt_ const D3D12_DISCARD_REGION* pDesc); + + void (D3DAPI* SetMarker)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size); + + void (D3DAPI* BeginEvent)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size); + + void (D3DAPI* EndEvent)( + _Inout_ ID3D12GraphicsCommandList* pCommandList); + + void (D3DAPI* InsertGpuMarker)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + UINT8 opcode, + _In_reads_bytes_(Size) const void* pData, + UINT Size); + + void (D3DAPI* InsertTimingMarker)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + UINT8 opcode); + + void (D3DAPI* ExecuteIndirect)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12CommandSignature* pCommandSignature, + _In_ UINT MaxCommandCount, + _In_ ID3D12Resource* pArgumentBuffer, + _In_ UINT64 ArgumentBufferOffset, + _In_opt_ ID3D12Resource* pCountBuffer, + _In_ UINT64 CountBufferOffset); + + void (D3DAPI* CopyMemoryToMemoryX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS Destination, + D3D12_GPU_VIRTUAL_ADDRESS Source, + UINT64 SizeBytes, + D3D12XBOX_COPY_FLAGS Flags); + + void (D3DAPI* FillMemoryWith32BitValueX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS Destination, + UINT64 SizeBytes, + UINT Value, + D3D12XBOX_COPY_FLAGS Flags); + + void (D3DAPI* FillMemoryWith64BitValueX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS Destination, + UINT64 SizeBytes, + UINT64 Value, + D3D12XBOX_COPY_FLAGS Flags); + + void (D3DAPI* FillMemoryWith128BitValueX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS Destination, + UINT64 SizeBytes, + UINT Value[4], + D3D12XBOX_COPY_FLAGS Flags); + + void (D3DAPI* SetOcclusionQueryControlX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_opt_ const D3D12XBOX_OCCLUSION_QUERY_CONTROL* pControl); + + void (D3DAPI* SetPerfectOcclusionQueriesX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + BOOL PerfectOcclusionQueries); + + void (D3DAPI* SetHiStencilControlX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_opt_ const D3D12XBOX_HISTENCIL_CONTROL* pControl); + + void (D3DAPI* FlushPipelineX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12XBOX_FLUSH Flags, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BaseAddress, + _In_ SIZE_T SizeInBytes); + + void (D3DAPI* OMSetDepthBoundsX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ FLOAT Min, + _In_ FLOAT Max); + + void (D3DAPI* Write32BitValueBottomOfPipeX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT Value, + _In_ D3D12XBOX_FLUSH Flush, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS Flags); + + void (D3DAPI* Write64BitValueBottomOfPipeX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 Value, + _In_ D3D12XBOX_FLUSH Flush, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS Flags); + + void (D3DAPI* Wait32BitValueX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Address, + _In_ D3D12_COMPARISON_FUNC ComparisonFunction, + _In_ UINT ReferenceValue, + _In_ UINT MaskValue, + _In_ D3D12XBOX_WAIT_FLAGS Flags); + + void (D3DAPI* Wait64BitValueX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Address, + _In_ D3D12_COMPARISON_FUNC ComparisonFunction, + _In_ UINT64 ReferenceValue, + _In_ D3D12XBOX_WAIT_FLAGS Flags); + + void (D3DAPI* SetPixelShaderDepthForceZOrderX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ BOOL ForceOrder); + + void (D3DAPI* ExecuteIndirectBundleX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pBundle, + _In_ UINT BundleOffset, + _In_ UINT MaxSize, + _In_opt_ ID3D12Resource* pSizeBuffer, + _In_ UINT SizeBufferOffset, + _In_ UINT PredicationBufferOffset); + + void (D3DAPI* SetupOrderedAppendCounterX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT CounterIndex, + _In_ UINT RingBufferAvailableSpace, + _In_ UINT GdsAddressOfTheCounterDwords, + _In_ D3D12XBOX_ORDERED_APPEND_SHADER_STAGE ShaderStage, + _In_ UINT Enable, + _In_ UINT ReservedSetTo0); + + void (D3DAPI* WriteGDSX)( + _Inout_ ID3D12GraphicsCommandList* pDeviceContext, + _In_ UINT OffsetDwords, + _In_ UINT NumDwords, + _In_ const UINT* pValues, + _In_ D3D12XBOX_GDS_OPERATION Flags ); + + void (D3DAPI* ReadGDSX)( + _Inout_ ID3D12GraphicsCommandList* pDeviceContext, + _In_ UINT OffsetDwords, + _In_ UINT NumDwords, + _Inout_ D3D12_GPU_VIRTUAL_ADDRESS pValues, + _In_ D3D12XBOX_GDS_OPERATION Flags ); + + void (D3DAPI* DispatchX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT ThreadGroupCountX, + _In_ UINT ThreadGroupCountY, + _In_ UINT ThreadGroupCountZ, + _In_ D3D12XBOX_DISPATCH_FLAGS Flags); + + void (D3DAPI* SetHiStencilStateX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pResource, + _In_opt_ const D3D12XBOX_HISTENCIL_CONTROL* pControl); + + void (D3DAPI* RSSetMSAAParametersX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_opt_ const D3D12XBOX_MSAA_SAMPLE_LOCATIONS* pSampleLocations, + _In_opt_ const D3D12XBOX_MSAA_CENTROID_PRIORITIES* pCentroidPriorities, + _In_opt_ const D3D12XBOX_MSAA_PARAMETERS* pMSAAParameters); + + void (D3DAPI* DrawIndexedX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS IndexBufferLocation, + _In_ DXGI_FORMAT IndexFormat, + _In_ UINT IndexCount, + _In_ UINT IndexOffset); + + void (D3DAPI* NopX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT SizeBytes); + + void (D3DAPI* CopyTextureRegionX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, + UINT DstX, + UINT DstY, + UINT DstZ, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pSrc, + _In_opt_ const D3D12_BOX* pSrcBox, + D3D12XBOX_COPY_FLAGS Flags); + + void (D3DAPI* CopyResourceX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pDstResource, + _In_ ID3D12Resource* pSrcResource, + D3D12XBOX_COPY_FLAGS Flags); + + void (D3DAPI* Deprecated_SetPredicationBufferX)(); + + void (D3DAPI* Deprecated_AdvancePredicationX)(); + + void (D3DAPI* ExecuteCommandListsX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT Count, + _In_reads_(Count) ID3D12CommandList* const* ppCommandLists, + _In_reads_(Count) UINT* const* ppPredicationBufferOffsets); + + void (D3DAPI* Write32BitValueTopOfPipeX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT Value, + _In_ D3D12XBOX_WRITE_VALUE_TOP_FLAGS Flags); + + void (D3DAPI* Write64BitValueTopOfPipeX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 Value, + _In_ D3D12XBOX_WRITE_VALUE_TOP_FLAGS Flags); + + void (D3DAPI* Write32BitValueBottomOfShaderX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT Value, + _In_ D3D12XBOX_SHADER_STAGE ShaderStage); + + UINT (D3DAPI* GetExecutionCommandSizeX)( + _Inout_ ID3D12GraphicsCommandList* pList); + + UINT (D3DAPI* CloseBundleX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _Inout_ void** ppBundleBufferAddress, + UINT BundleBufferMaxSize); + + void (D3DAPI* KickoffX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList); + + void (D3DAPI* RSSetDepthBiasX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ INT DepthBias, + _In_ FLOAT DepthBiasClamp, + _In_ FLOAT SlopeScaledDepthBias, + _In_ BOOL DepthClipEnable); + + void (D3DAPI* SetGraphicsShaderLimitsX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ BOOL PixelShaderEnabled, + _In_ BOOL TessellationEnabled, + _In_ BOOL GeometryShaderEnabled, + _In_ BOOL GeometryShaderOnChip, + _In_ BOOL PrimitiveShaderEnabled, + _In_opt_ const D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC* pShaderLimits); + + void (D3DAPI* SetComputeShaderLimitsX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_opt_ const D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC* pShaderLimits); + + void (D3DAPI* SetResourceCompressionStateX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _Inout_ ID3D12Resource* pResource, + _In_ D3D12XBOX_COMPRESSION_STATE_FLAGS CompressionStateFlags, + _In_ D3D12_RESOURCE_STATES PreserveFlags); + + void (D3DAPI* DispatchMeshX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT ThreadGroupCountX, + _In_ UINT64 Flags, + _In_ UINT64 IndirectArgsPointer, + _In_ UINT64 PayloadPointer); + + UINT64 (D3DAPI* DriverHintX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ UINT64 feature, + _In_ UINT64 value); + + void (D3DAPI* StartCountersX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12XboxCounterSet* pCounterSet); + + void (D3DAPI* SampleCountersX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset); + + void (D3DAPI* StopCountersX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList); + + void (D3DAPI* SetDeferredPrimitiveBatchBinningX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ const D3D12XBOX_DPBB_STATE* pBinningState); + + void (D3DAPI* DeferredPrimitiveBreakBatchX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList); +}; + +} + +typedef UINT32* __restrict D3D12XBOX_PPUT; + +// +// struct D3D12XboxPutBuffer +// +// This is a private D3D structure for managing the writing of GPU commands to the current +// command buffer segment. +// + +struct D3D12XboxPutBuffer +{ +public: + // Number of dwords by which m_pPutLimit is biased downward from the true limit: + static const UINT32 BiasDwordCount = 66; + + // Minimum number of dwords that is available after calling MakeSpace(): + static const UINT32 MakeSpaceDwordCount = 1024; + + // Points to the location in the segment currently being constructed where the next GPU + // command will be added: + D3D12XBOX_PPUT m_pCurrent; + + // Points to the end of the current segment biased down by BiasDwordCount dwords. + // If m_pCurrent < m_pLimit then it's guaranteed that there are at least 66 dwords + // of room left in the ring buffer. If m_pCurrent >= m_pLimit then MakeSpace() must be + // called before any more data can be added. + D3D12XBOX_PPUT m_pLimit; + + // Same as m_pLimit but usually null on INSTRUMENTED builds. This allows D3D to add + // out-of-line timing instrumentation to Draw calls while keeping all other API calls + // inlined. + D3D12XBOX_PPUT m_pLimit_Draw; + + // Same as m_pLimit but always null on DEBUG builds. This is used by inline API + // implementations to allow D3D to pull the calls out-of-line and thereby do full + // parameter checking (since doing parameter checking inline would be impractical). + D3D12XBOX_PPUT m_pLimit_Api; + + // Same as m_pLimit_Api but not biased down by BiasDwordCount. This is used by API + // calls when the size of the packet may exceed BiasDwordCount dwords. + D3D12XBOX_PPUT m_pUnbiasedLimit_Api; + + + // Reserved space: + UINT32 m_Reserved2[64]; + +public: + // Methods for writing values into a command buffer. These automatically advance the 'put' + // pointer. The 'put' pointer is explicitly passed as an argument rather than accessed directly + // through the class member field so as to ensure that the pointer is en-registered by the + // compiler and aliasing issues are avoided. + void PutD(D3D12XBOX_PPUT& pPut, UINT32 DwordValue) + { + *((volatile UINT32* __restrict) pPut) = DwordValue; + pPut += 1; + } + void PutQ(D3D12XBOX_PPUT& pPut, UINT64 QwordValue) + { + *((volatile UINT64* __restrict) pPut) = QwordValue; + pPut += 2; + } + void PutO(D3D12XBOX_PPUT& pPut, __m128i OwordValue) + { + _mm_storeu_si128((__m128i* __restrict) pPut, OwordValue); + pPut += 4; + } +}; + +D3DINTERFACE(ID3D12GraphicsCommandList, 5b160d0f,ac1b,4185,8b,a8,b3,ae,42,a5,a4,55) : public ID3D12CommandList +{ +public: + + //--------------------------------------------------------------------------------------------- + // Note: All fields here are private and subject to change! Please refrain from accessing + // these directly as your code will likely be broken with a future XDK release. + //--------------------------------------------------------------------------------------------- + // Class for accessing the put buffer pointers directly: + D3D12XboxPutBuffer m_Putter; + + // Cpu State used to accelerate GPU timeline (its much faster for these to not be bitfields) + struct CpuState + { + // Certain APIs (Vertex Buffer Sets, Root Data spill) require the use of Shader Memory 'shmem' + // this puts an added burden on the CP to manage so we track if shmem is dirty or not here and + // choose a faster packet when it's clean. + UINT8 shmem_dirty; + UINT8 pso_wave32; + // Primitive Reset (part of the PSO) can cause problems for large non-indexed draws as the hardware + // has an internal index buffer that can trigger the reset. The complex draw packet handles this so + // on transitions from Draw to Draw Indexed (and vice versa) we issue the complex packet to handle state. + UINT8 last_draw_indexed; + // When predication is used on a command list we want to use the complex packet exclusively + UINT8 predication_used; + }; + CpuState m_cpuState; + + // Lookup tables for determining the appropriate Command Processor packet header for the + // particular root index operation. These are updated whenever a new Root Signature is set: + UINT32 m_GraphicsRootPacketHeader[D3D12XBOX_ROOT_PARAMETER_MAX_INDEX + 1]; + UINT32 m_ComputeRootPacketHeader[D3D12XBOX_ROOT_PARAMETER_MAX_INDEX + 1]; + + // CPU PSO shadow for amplification shaders speicfically + UINT32 m_GraphicsPSOShadow[8]; + +public: + + // Packets for RootData (SetComputeRootDescriptorTable, SetGraphicsRoot32BitConstant etc) come in two flavors: + // - User Data: These resolve to 32-bit register sets that get sent directly to the shader and are available via scalar + // registers. Xbox Series S/X consoles have 32 registers availble for each graphics shader stage and 16 + // for compute. The shader compiler reserves 8 registers on graphics and 4 on compute leaving 24 and 12 + // registers availble for the title's root signature respectively. The driver will pack as many root + // signature entries as it can into the user registers with the remainder being handled by the Constant + // Engine (CE) of the Command Processor (CP) via CERAM and shader memory (shmem)(see below). It's slightly faster + // for a shader to read its data from user registers than it is from shmem because that requires a level of + // indirection. Additionally, it's desireable to work exclusively with user data because it enables optimizations + // on the CP front end with these packets being typically 25-50% faster to process. + // + // - CERAM: Root Data which does not fit into the user data rgisters and additional bindings such as Vertex Buffers reach the + // shader via shader memory or 'shmem'. This is a small piece of memory that is versioned every time one of the bindings + // is changed. The versioning of this memory is handled by the Constant Engine (CE) of the Command Processor (CP) with + // changes being cached in its internal CERAM before being dumped to the new location in the shmem ring before the draw. + + // +-----------------------------------------------------+ + // | Command Buffer (Stream of PM4 Commands) | + // +-----+ | + // | +-----------------------------------------------------+ + // | + // | +-----------------------------------------------------------+ + // | | | + // | | +---------------------+ Command Processor | +---------------------+ + // | | | Constant Engine | (CP) | | | + // | | | | | | Shader Memory +-+ +------------------------+ + // | | | | | | | | | Shader Engine | + // | | | | | | (shmem) | +-+ | | + // | | | | | | | | | | +--------------------+ | + // | | | | | | -Vertex Buffers | | | | |Shader Registers | | + // +-----+-> CE +-----------------------------------+--> -Root Data Spill +-+-+----+ | | | | + // | | | | | | -Other Driver Stuff | | | +----+-> | | + // | | | | | | | | | | | | | | + // | | | | | | | | | | | | | | + // | | | | | | | | | | | | | | + // | | | | | | | | | | | | | | + // | | +---------------------+ | ++--------------------+ | | | | +--------------------+ | + // | | | | | | | | | + // | | +---------------------+ +---------------------+ | +-+--------------------+ | | +------------------------+ + // | | | Prefetch Processor | | Micro Engine | | | | | + // | | | | | | | +----------------------+ | + // | | | | | | | | + // | | | | | | | | + // | | | | | | | | + // | | | | | | | | + // +-----+-> PFP +-------> ME +-----+---------------------------------+ + // | | | | | | + // | | | | | | + // | | | | | | + // | | | | | | + // | | | | | | + // | +---------------------+ +---------------------+ | + // | | + // +-----------------------------------------------------------+ + + // User Data register Command Processor Op Codes + #define D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_1_DWORD 0xDD // Fast common case versions that only set VS+PS + #define D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_2_DWORD 0xDE // + #define D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_4_DWORD 0xDF // + #define D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA 0xE0 // + #define D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_1_DWORD_GSHS 0xE1 // 'Broadcast' versions that set VS+GS+HS+DS+PS + #define D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_2_DWORD_GSHS 0xE2 // + #define D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_4_DWORD_GSHS 0xE3 // + #define D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_GSHS 0xE4 // + #define D3D12XBOX_CP_PACKET_TYPE_MASK 0xc0000000 + #define D3D12XBOX_CP_OP_CODE_SHIFT 8 + #define D3D12XBOX_CP_OP_CODE_MASK 0xff + + static UINT GetPacketOpCode(UINT Header) + { + return (Header >> D3D12XBOX_CP_OP_CODE_SHIFT) & D3D12XBOX_CP_OP_CODE_MASK; + } + + // Type 0 Packets are handled by the Constant Engine (CE) + static bool IsType0Packet(UINT Header) + { + return (Header & D3D12XBOX_CP_PACKET_TYPE_MASK) == 0; + } + + bool CurrentPsoUsesHardwareGSorHS() + { + return ID3D12PipelineState::UsesHardwareGSorHS((D3D12XBOX_DESCRIPTOR_PIPELINE_STATE*)m_GraphicsPSOShadow); + } + + UINT AdjustRootDataHeader(bool Gfx, UINT Header, UINT NumDwords, UINT OffsetDwords) + { + if(IsType0Packet(Header) == false) // is this a user register packet? + { + if(Gfx) // For Graphics adjust the opcode to pick the most efficient version + { + switch(NumDwords) + { + case 1: break; // nothing to do + case 2: Header += 0x100; break; // Convert _GRAPHICS_ROOT_DATA_1 to _GRAPHICS_ROOT_DATA_2 + case 4: Header += 0x200; break; // etc. + default: Header += 0x300; break; + } + + // Root User Data packets are defined with the assumption that regular hardware Vs+PS will be used (common case); however, sometimes + // API Vertex Shaders are converted to the Hardware Geometry Shader stage (NGG is an example) so we must account for that. The same + // applies for other uncommon pipeline configurations such as Tessellation. + if(CurrentPsoUsesHardwareGSorHS() && (GetPacketOpCode(Header) < D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_1_DWORD_GSHS)) + { + Header += 0x400; // Covert to broadcast packet e.g. D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_1_DWORD -> D3D12XBOX_IT1_SET_GRAPHICS_ROOT_DATA_1_DWORD_GSHS + } + } + + Header += (OffsetDwords << 2); // Low 2 bits unused + } + else // CERAM / shmem write + { + Header += (OffsetDwords * sizeof(UINT)); // CERAM works in bytes + m_cpuState.shmem_dirty = 1; + } + + return Header; + } + + D3DINLINE D3D12GraphicsCommandList_Function_Table* CommandListFunction() + { + return (D3D12GraphicsCommandList_Function_Table*)m_pFunction; + } + + void D3DAPI DrawInstanced( + _In_ UINT VertexCountPerInstance, + _In_ UINT InstanceCount, + _In_ UINT StartVertexLocation, + _In_ UINT StartInstanceLocation) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Draw) + { + const bool useComplexPacket = (m_cpuState.shmem_dirty | m_cpuState.last_draw_indexed | m_cpuState.predication_used); + + const UINT header = useComplexPacket ? D3D12XBOX_PACKET_DRAW_INSTANCED : D3D12XBOX_PACKET_DRAW_INSTANCED_NO_SHMEM; + + m_Putter.PutD(pPut, header); + m_Putter.PutD(pPut, InstanceCount); + m_Putter.PutD(pPut, VertexCountPerInstance); + m_Putter.PutD(pPut, StartVertexLocation); + m_Putter.PutD(pPut, StartInstanceLocation); + m_Putter.m_pCurrent = pPut; + + m_cpuState.shmem_dirty = 0; + m_cpuState.last_draw_indexed = 0; + } + else + { + CommandListFunction()->DrawInstanced(this, + VertexCountPerInstance, + InstanceCount, + StartVertexLocation, + StartInstanceLocation); + } + } + + void D3DAPI DrawIndexedInstanced( + _In_ UINT IndexCountPerInstance, + _In_ UINT InstanceCount, + _In_ UINT StartIndexLocation, + _In_ INT BaseVertexLocation, + _In_ UINT StartInstanceLocation) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Draw) + { + const bool useComplexPacket = (m_cpuState.shmem_dirty | (!m_cpuState.last_draw_indexed) | m_cpuState.predication_used); + + const UINT header = useComplexPacket ? D3D12XBOX_PACKET_DRAW_INDEXED_INSTANCED : D3D12XBOX_PACKET_DRAW_INDEXED_INSTANCED_NO_SHMEM; + + m_Putter.PutD(pPut, header); + m_Putter.PutD(pPut, InstanceCount); + m_Putter.PutD(pPut, StartIndexLocation); + m_Putter.PutD(pPut, IndexCountPerInstance); + m_Putter.PutD(pPut, BaseVertexLocation); + m_Putter.PutD(pPut, StartInstanceLocation); + m_Putter.m_pCurrent = pPut; + + m_cpuState.shmem_dirty = 0; + m_cpuState.last_draw_indexed = 1; + } + else + { + CommandListFunction()->DrawIndexedInstanced(this, + IndexCountPerInstance, + InstanceCount, + StartIndexLocation, + BaseVertexLocation, + StartInstanceLocation); + } + } + + void D3DAPI Dispatch( + _In_ UINT ThreadGroupCountX, + _In_ UINT ThreadGroupCountY, + _In_ UINT ThreadGroupCountZ) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Draw) + { + if (m_cpuState.shmem_dirty || m_cpuState.predication_used) + { + m_Putter.PutD(pPut, D3D12XBOX_PACKET_DISPATCH); + } + else + { + // Include the Wave32 bit so the CP doesn't have to fetch it + m_Putter.PutD(pPut, D3D12XBOX_PACKET_DISPATCH_NO_SHMEM | ((m_cpuState.pso_wave32 & 0x1) << 2)); + } + + m_Putter.PutD(pPut, ThreadGroupCountX); + m_Putter.PutD(pPut, ThreadGroupCountY); + m_Putter.PutD(pPut, ThreadGroupCountZ); + m_Putter.m_pCurrent = pPut; + + m_cpuState.shmem_dirty = 0; + } + else + { + CommandListFunction()->Dispatch(this, + ThreadGroupCountX, + ThreadGroupCountY, + ThreadGroupCountZ); + } + } + + void D3DAPI IASetPrimitiveTopology( + _In_ D3D12_PRIMITIVE_TOPOLOGY PrimitiveTopology) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, D3D12XBOX_PACKET_SET_PRIMITIVE_TOPOLOGY); + m_Putter.PutD(pPut, D3D12XBOX_SET_PRIMITIVE_TOPOLOGY_LOOKUP[PrimitiveTopology]); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->IASetPrimitiveTopology(this, PrimitiveTopology); + } + } + + void D3DAPI OMSetBlendFactor( + _In_reads_opt_(4) const FLOAT BlendFactor[4]) + { + CommandListFunction()->OMSetBlendFactor(this, BlendFactor); + } + + void D3DAPI OMSetStencilRef( + _In_ UINT StencilRef) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, D3D12XBOX_PACKET_SET_STENCIL_REF); + m_Putter.PutD(pPut, StencilRef); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->OMSetStencilRef(this, StencilRef); + } + } + + void D3DAPI IASetIndexBuffer( + _In_opt_ const D3D12_INDEX_BUFFER_VIEW* pView) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + if (pView != nullptr) + { + m_Putter.PutD(pPut, D3D12XBOX_PACKET_SET_INDEX_BUFFER + pView->Format); + m_Putter.PutQ(pPut, pView->BufferLocation); + m_Putter.m_pCurrent = pPut; + } + } + else + { + CommandListFunction()->IASetIndexBuffer(this, pView); + } + } + + void D3DAPI IASetVertexBuffers( + _In_ UINT StartSlot, + _In_ UINT NumViews, + _In_reads_opt_(NumViews) const D3D12_VERTEX_BUFFER_VIEW* pViews) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + + // Note that if this m_pLimit_Api comparison succeeds, there is at least 66 dwords of + // room in the buffer which is enough for our worst case of NumViews equal to + // D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT: + if (pPut < m_Putter.m_pLimit_Api && NumViews) + { + if (pViews == nullptr) + { + m_Putter.PutD(pPut, D3D12XBOX_PACKET_CLEAR_VERTEX_BUFFERS + StartSlot); + m_Putter.PutD(pPut, NumViews); + } + else + { + UINT packetHeader = D3D12XBOX_PACKET_SET_VERTEX_BUFFERS + + StartSlot + + (NumViews << (D3D12XBOX_PACKET_COUNT_SHIFT + 1)); + + m_Putter.PutD(pPut, packetHeader); + + do { + UINT64 descriptor = UINT64(pViews->BufferLocation) + + (UINT64(pViews->StrideInBytes) << D3D12XBOX_SET_VERTEX_BUFFERS_STRIDE_SHIFT64); + + m_Putter.PutQ(pPut, descriptor); + pViews++; + } while (--NumViews != 0); + } + m_Putter.m_pCurrent = pPut; + + m_cpuState.shmem_dirty = 1; + } + else + { + CommandListFunction()->IASetVertexBuffers(this, + StartSlot, + NumViews, + pViews); + } + } + + void D3DAPI SetPipelineState( + _In_ ID3D12PipelineState* pPipelineState) + { + _mm_storeu_si128((__m128i* __restrict)&m_GraphicsPSOShadow[0], pPipelineState->m_Packet.Oword[0]); + _mm_storeu_si128((__m128i* __restrict)&m_GraphicsPSOShadow[4], pPipelineState->m_Packet.Oword[1]); + + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + // 7 dwords + m_Putter.PutO(pPut, pPipelineState->m_Packet.Oword[0]); + m_Putter.PutQ(pPut, pPipelineState->m_Packet.Qword[2]); + m_Putter.PutD(pPut, pPipelineState->m_Packet.Dword[6]); + m_Putter.m_pCurrent = pPut; + + m_cpuState.shmem_dirty = 1; + m_cpuState.pso_wave32 = pPipelineState->IsWave32(); + } + else + { + CommandListFunction()->SetPipelineState(this, pPipelineState); + } + } + + void D3DAPI SetComputeRootDescriptorTable( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, AdjustRootDataHeader(false, m_ComputeRootPacketHeader[RootParameterIndex], 1, 0)); + m_Putter.PutD(pPut, (UINT32) BaseDescriptor.ptr); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetComputeRootDescriptorTable(this, RootParameterIndex, BaseDescriptor); + } + } + + void D3DAPI SetGraphicsRootDescriptorTable( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, AdjustRootDataHeader(true, m_GraphicsRootPacketHeader[RootParameterIndex], 1, 0)); + m_Putter.PutD(pPut, (UINT32) BaseDescriptor.ptr); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetGraphicsRootDescriptorTable(this, RootParameterIndex, BaseDescriptor); + } + } + + void D3DAPI SetComputeRoot32BitConstant( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ UINT SrcData, + _In_ UINT DestOffsetIn32BitValues) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + UINT32 packetHeader = AdjustRootDataHeader(false, m_ComputeRootPacketHeader[RootParameterIndex], 1, DestOffsetIn32BitValues); + m_Putter.PutD(pPut, packetHeader); + m_Putter.PutD(pPut, SrcData); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetComputeRoot32BitConstant(this, + RootParameterIndex, + SrcData, + DestOffsetIn32BitValues); + } + } + + void D3DAPI SetGraphicsRoot32BitConstant( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ UINT SrcData, + _In_ UINT DestOffsetIn32BitValues) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + UINT32 packetHeader = AdjustRootDataHeader(true, m_GraphicsRootPacketHeader[RootParameterIndex], 1, DestOffsetIn32BitValues); + m_Putter.PutD(pPut, packetHeader); + m_Putter.PutD(pPut, SrcData); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetGraphicsRoot32BitConstant(this, + RootParameterIndex, + SrcData, + DestOffsetIn32BitValues); + } + } + + void D3DAPI SetComputeRoot32BitConstants( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ UINT Num32BitValuesToSet, + _In_reads_(Num32BitValuesToSet*sizeof(UINT)) const void* pSrcData, + _In_ UINT DestOffsetIn32BitValues) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + UINT32 packetHeader = AdjustRootDataHeader(false, m_ComputeRootPacketHeader[RootParameterIndex], Num32BitValuesToSet, DestOffsetIn32BitValues); + packetHeader += (Num32BitValuesToSet - 1) << D3D12XBOX_PACKET_COUNT_SHIFT; + m_Putter.PutD(pPut, packetHeader); + + const UINT32* pSrc = (UINT32*) pSrcData; + do { + m_Putter.PutD(pPut, *pSrc++); + } while (--Num32BitValuesToSet != 0); + + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetComputeRoot32BitConstants(this, + RootParameterIndex, + Num32BitValuesToSet, + pSrcData, + DestOffsetIn32BitValues); + } + } + + void D3DAPI SetGraphicsRoot32BitConstants( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ UINT Num32BitValuesToSet, + _In_reads_(Num32BitValuesToSet*sizeof(UINT)) const void* pSrcData, + _In_ UINT DestOffsetIn32BitValues) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + UINT32 packetHeader = AdjustRootDataHeader(true, m_GraphicsRootPacketHeader[RootParameterIndex], Num32BitValuesToSet, DestOffsetIn32BitValues); + packetHeader += (Num32BitValuesToSet - 1) << D3D12XBOX_PACKET_COUNT_SHIFT; + + m_Putter.PutD(pPut, packetHeader); + + const UINT32* pSrc = (UINT32*) pSrcData; + do { + m_Putter.PutD(pPut, *pSrc++); + } while (--Num32BitValuesToSet != 0); + + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetGraphicsRoot32BitConstants(this, + RootParameterIndex, + Num32BitValuesToSet, + pSrcData, + DestOffsetIn32BitValues); + } + } + + void D3DAPI SetComputeRootConstantBufferView( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, AdjustRootDataHeader(false, m_ComputeRootPacketHeader[RootParameterIndex], 2, 0)); + m_Putter.PutQ(pPut, BufferLocation); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetComputeRootConstantBufferView(this, RootParameterIndex, BufferLocation); + } + } + + void D3DAPI SetGraphicsRootConstantBufferView( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, AdjustRootDataHeader(true, m_GraphicsRootPacketHeader[RootParameterIndex], 2, 0)); + m_Putter.PutQ(pPut, BufferLocation); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetGraphicsRootConstantBufferView(this, RootParameterIndex, BufferLocation); + } + } + + void D3DAPI SetComputeRootShaderResourceView( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, AdjustRootDataHeader(false, m_ComputeRootPacketHeader[RootParameterIndex], 2, 0)); + m_Putter.PutQ(pPut, BufferLocation); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetComputeRootShaderResourceView(this, RootParameterIndex, BufferLocation); + } + } + + void D3DAPI SetGraphicsRootShaderResourceView( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, AdjustRootDataHeader(true, m_GraphicsRootPacketHeader[RootParameterIndex], 2, 0)); + m_Putter.PutQ(pPut, BufferLocation); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetGraphicsRootShaderResourceView(this, RootParameterIndex, BufferLocation); + } + } + + void D3DAPI SetComputeRootUnorderedAccessView( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, AdjustRootDataHeader(false, m_ComputeRootPacketHeader[RootParameterIndex], 2, 0)); + m_Putter.PutQ(pPut, BufferLocation); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetComputeRootUnorderedAccessView(this, RootParameterIndex, BufferLocation); + } + } + + void D3DAPI SetGraphicsRootUnorderedAccessView( + _In_range_(0, D3D12XBOX_ROOT_PARAMETER_MAX_INDEX) UINT RootParameterIndex, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + m_Putter.PutD(pPut, AdjustRootDataHeader(true, m_GraphicsRootPacketHeader[RootParameterIndex], 2, 0)); + m_Putter.PutQ(pPut, BufferLocation); + m_Putter.m_pCurrent = pPut; + } + else + { + CommandListFunction()->SetGraphicsRootUnorderedAccessView(this, RootParameterIndex, BufferLocation); + } + } + + //--------------------------------------------------------------------------------------------- + + D3DINLINE HRESULT D3DAPI Close() + { + return CommandListFunction()->Close(this); + } + + D3DINLINE HRESULT D3DAPI Reset( + _In_ ID3D12CommandAllocator* pAllocator, + _In_opt_ ID3D12PipelineState* pInitialState) + { + return CommandListFunction()->Reset(this, pAllocator, pInitialState); + } + + D3DINLINE void D3DAPI ClearState( + _In_opt_ ID3D12PipelineState* pPipelineState) + { + CommandListFunction()->ClearState(this, pPipelineState); + } + + D3DINLINE void D3DAPI CopyBufferRegion( + _In_ ID3D12Resource* pDstBuffer, + UINT64 DstOffset, + _In_ ID3D12Resource* pSrcBuffer, + UINT64 SrcOffset, + UINT64 NumBytes) + { + CommandListFunction()->CopyBufferRegion(this, + pDstBuffer, + DstOffset, + pSrcBuffer, + SrcOffset, + NumBytes); + } + + D3DINLINE void D3DAPI CopyTextureRegion( + _In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, + UINT DstX, + UINT DstY, + UINT DstZ, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pSrc, + _In_opt_ const D3D12_BOX* pSrcBox) + { + CommandListFunction()->CopyTextureRegionX(this, + pDst, + DstX, + DstY, + DstZ, + pSrc, + pSrcBox, + D3D12XBOX_COPY_FLAG_NONE); + } + + D3DINLINE void D3DAPI CopyTextureRegionX( + _In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, + UINT DstX, + UINT DstY, + UINT DstZ, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pSrc, + _In_opt_ const D3D12_BOX* pSrcBox, + D3D12XBOX_COPY_FLAGS Flags) + { + CommandListFunction()->CopyTextureRegionX(this, + pDst, + DstX, + DstY, + DstZ, + pSrc, + pSrcBox, + Flags); + } + + D3DINLINE void D3DAPI CopyResource( + _In_ ID3D12Resource* pDstResource, + _In_ ID3D12Resource* pSrcResource) + { + CommandListFunction()->CopyResourceX(this, pDstResource, pSrcResource, D3D12XBOX_COPY_FLAG_NONE); + } + + D3DINLINE void D3DAPI CopyResourceX( + _In_ ID3D12Resource* pDstResource, + _In_ ID3D12Resource* pSrcResource, + D3D12XBOX_COPY_FLAGS Flags) + { + CommandListFunction()->CopyResourceX(this, pDstResource, pSrcResource, Flags); + } + + D3DINLINE void D3DAPI CopyTiles( + _In_ ID3D12Resource* pTiledResource, + _In_ const D3D12_TILED_RESOURCE_COORDINATE* pTileRegionStartCoordinate, + _In_ const D3D12_TILE_REGION_SIZE* pTileRegionSize, + _In_ ID3D12Resource* pBuffer, + UINT64 BufferStartOffsetInBytes, + D3D12_TILE_COPY_FLAGS Flags) + { + CommandListFunction()->CopyTiles(this, + pTiledResource, + pTileRegionStartCoordinate, + pTileRegionSize, + pBuffer, + BufferStartOffsetInBytes, + Flags); + } + + D3DINLINE void D3DAPI ResolveSubresource( + _In_ ID3D12Resource* pDstResource, + _In_ UINT DstSubresource, + _In_ ID3D12Resource* pSrcResource, + _In_ UINT SrcSubresource, + _In_ DXGI_FORMAT Format) + { + CommandListFunction()->ResolveSubresource(this, + pDstResource, + DstSubresource, + pSrcResource, + SrcSubresource, + Format); + } + + D3DINLINE void D3DAPI RSSetViewports( + _In_range_(0, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumViewports, + _In_reads_(NumViewports) const D3D12_VIEWPORT* pViewports) + { + CommandListFunction()->RSSetViewports(this, NumViewports, pViewports); + } + + D3DINLINE void D3DAPI RSSetScissorRects( + _In_range_(0, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumRects, + _In_reads_(NumRects) const D3D12_RECT* pRects) + { + CommandListFunction()->RSSetScissorRects(this, NumRects, pRects); + } + + D3DINLINE void D3DAPI ResourceBarrier( + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER* pBarriers) + { + CommandListFunction()->ResourceBarrier(this, NumBarriers, pBarriers); + } + + D3DINLINE void D3DAPI ExecuteBundle( + _In_ ID3D12GraphicsCommandList* pCommandList) + { + CommandListFunction()->ExecuteBundle(this, pCommandList); + } + + D3DINLINE void D3DAPI BeginQuery( + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index) + { + CommandListFunction()->BeginQuery(this, pQueryHeap, Type, Index); + } + + D3DINLINE void D3DAPI EndQuery( + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index) + { + CommandListFunction()->EndQuery(this, pQueryHeap, Type, Index); + } + + D3DINLINE void D3DAPI ResolveQueryData( + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartIndex, + _In_ UINT NumQueries, + _In_ ID3D12Resource* pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset) + { + CommandListFunction()->ResolveQueryData(this, + pQueryHeap, + Type, + StartIndex, + NumQueries, + pDestinationBuffer, + AlignedDestinationBufferOffset); + } + + D3DINLINE void D3DAPI SetPredication( + _In_opt_ ID3D12Resource* pBuffer, + _In_ UINT64 AlignedBufferOffset, + _In_ D3D12_PREDICATION_OP Operation) + { + m_cpuState.predication_used = 1; + CommandListFunction()->SetPredication(this, pBuffer, AlignedBufferOffset, Operation); + } + + D3DINLINE void D3DAPI SetDescriptorHeaps( + _In_ UINT NumDescriptorHeaps, + _In_reads_(NumDescriptorHeaps) ID3D12DescriptorHeap*const* pDescriptorHeaps) + { + CommandListFunction()->SetDescriptorHeaps(this, NumDescriptorHeaps, pDescriptorHeaps); + } + + D3DINLINE void D3DAPI SetComputeRootSignature( + _In_ ID3D12RootSignature* pRootSignature) + { + CommandListFunction()->SetComputeRootSignature(this, pRootSignature); + } + + D3DINLINE void D3DAPI SetGraphicsRootSignature( + _In_ ID3D12RootSignature* pRootSignature) + { + CommandListFunction()->SetGraphicsRootSignature(this, pRootSignature); + } + + D3DINLINE void D3DAPI SOSetTargets( + _In_ UINT StartSlot, + _In_ UINT NumViews, + _In_reads_opt_(NumViews) const D3D12_STREAM_OUTPUT_BUFFER_VIEW* pViews) + { + CommandListFunction()->SOSetTargets(this, + StartSlot, + NumViews, + pViews); + } + + D3DINLINE void D3DAPI OMSetRenderTargets( + _In_ UINT NumRenderTargetDescriptors, + _In_opt_ const D3D12_CPU_DESCRIPTOR_HANDLE* pRenderTargetDescriptors, + _In_ BOOL RTsSingleHandleToDescriptorRange, + _In_opt_ const D3D12_CPU_DESCRIPTOR_HANDLE* pDepthStencilDescriptor) + { + CommandListFunction()->OMSetRenderTargets(this, + NumRenderTargetDescriptors, + pRenderTargetDescriptors, + RTsSingleHandleToDescriptorRange, + pDepthStencilDescriptor); + } + + D3DINLINE void D3DAPI ClearDepthStencilView( + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DepthStencilView, + _In_ D3D12_CLEAR_FLAGS ClearFlags, + _In_ FLOAT Depth, + _In_ UINT8 Stencil, + _In_ UINT NumRects, + _In_reads_(NumRects) const D3D12_RECT* pRect) + { + CommandListFunction()->ClearDepthStencilView(this, + DepthStencilView, + ClearFlags, + Depth, + Stencil, + NumRects, + pRect); + } + + D3DINLINE void D3DAPI ClearRenderTargetView( + _In_ D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetView, + _In_ const FLOAT ColorRGBA[4], + _In_ UINT NumRects, + _In_reads_(NumRects) const D3D12_RECT* pRects) + { + CommandListFunction()->ClearRenderTargetView(this, + RenderTargetView, + ColorRGBA, + NumRects, + pRects); + } + + D3DINLINE void D3DAPI ClearUnorderedAccessViewUint( + _In_ D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, + _In_ ID3D12Resource* pResource, + _In_ const UINT Values[4], + _In_ UINT NumRects, + _In_reads_(NumRects) const D3D12_RECT* pRects) + { + CommandListFunction()->ClearUnorderedAccessViewUint(this, + ViewGPUHandleInCurrentHeap, + ViewCPUHandle, + pResource, + Values, + NumRects, + pRects); + } + + D3DINLINE void D3DAPI ClearUnorderedAccessViewFloat( + _In_ D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, + _In_ ID3D12Resource* pResource, + _In_ const FLOAT Values[4], + _In_ UINT NumRects, + _In_reads_(NumRects) const D3D12_RECT* pRects) + { + CommandListFunction()->ClearUnorderedAccessViewFloat(this, + ViewGPUHandleInCurrentHeap, + ViewCPUHandle, + pResource, + Values, + NumRects, + pRects); + } + + D3DINLINE void D3DAPI DiscardResource( + _In_ ID3D12Resource* pResource, + _In_opt_ const D3D12_DISCARD_REGION* pDesc) + { + CommandListFunction()->DiscardResource(this, + pResource, + pDesc); + } + + D3DINLINE void D3DAPI SetMarker( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size) + { + CommandListFunction()->SetMarker(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI BeginEvent( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size) + { + CommandListFunction()->BeginEvent(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI EndEvent() + { + CommandListFunction()->EndEvent(this); + } + + D3DINLINE void D3DAPI InsertGpuMarker( + UINT8 opcode, + _In_reads_bytes_(Size) const void* pData, + UINT Size) + { + CommandListFunction()->InsertGpuMarker(this, opcode, pData, Size); + } + + D3DINLINE void D3DAPI InsertTimingMarker( + UINT8 opcode) + { + CommandListFunction()->InsertTimingMarker(this, opcode); + } + + D3DINLINE void D3DAPI ExecuteIndirect( + _In_ ID3D12CommandSignature* pCommandSignature, + _In_ UINT MaxCommandCount, + _In_ ID3D12Resource* pArgumentBuffer, + _In_ UINT64 ArgumentBufferOffset, + _In_opt_ ID3D12Resource* pCountBuffer, + _In_ UINT64 CountBufferOffset) + { + CommandListFunction()->ExecuteIndirect(this, + pCommandSignature, + MaxCommandCount, + pArgumentBuffer, + ArgumentBufferOffset, + pCountBuffer, + CountBufferOffset); + } + + D3DINLINE void D3DAPI CopyMemoryToMemoryX( + D3D12_GPU_VIRTUAL_ADDRESS Destination, + D3D12_GPU_VIRTUAL_ADDRESS Source, + UINT64 SizeBytes, + D3D12XBOX_COPY_FLAGS Flags) + { + CommandListFunction()->CopyMemoryToMemoryX(this, + Destination, + Source, + SizeBytes, + Flags); + } + + D3DINLINE void D3DAPI FillMemoryWith32BitValueX( + D3D12_GPU_VIRTUAL_ADDRESS Destination, + UINT64 SizeBytes, + UINT Value, + D3D12XBOX_COPY_FLAGS Flags) + { + CommandListFunction()->FillMemoryWith32BitValueX(this, + Destination, + SizeBytes, + Value, + Flags); + } + + D3DINLINE void D3DAPI FillMemoryWith64BitValueX( + D3D12_GPU_VIRTUAL_ADDRESS Destination, + UINT64 SizeBytes, + UINT64 Value, + D3D12XBOX_COPY_FLAGS Flags) + { + CommandListFunction()->FillMemoryWith64BitValueX(this, + Destination, + SizeBytes, + Value, + Flags); + } + + D3DINLINE void D3DAPI FillMemoryWith128BitValueX( + D3D12_GPU_VIRTUAL_ADDRESS Destination, + UINT64 SizeBytes, + UINT Value[4], + D3D12XBOX_COPY_FLAGS Flags) + { + CommandListFunction()->FillMemoryWith128BitValueX(this, + Destination, + SizeBytes, + Value, + Flags); + } + + D3DINLINE void D3DAPI Write32BitValueTopOfPipeX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT Value, + _In_ D3D12XBOX_WRITE_VALUE_TOP_FLAGS Flags) + { + CommandListFunction()->Write32BitValueTopOfPipeX(this, + Destination, + Value, + Flags); + } + + D3DINLINE void D3DAPI Write64BitValueTopOfPipeX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 Value, + _In_ D3D12XBOX_WRITE_VALUE_TOP_FLAGS Flags) + { + CommandListFunction()->Write64BitValueTopOfPipeX(this, + Destination, + Value, + Flags); + } + + D3DINLINE void D3DAPI Write32BitValueBottomOfPipeX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT Value, + _In_ D3D12XBOX_FLUSH Flush, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS Flags) + { + CommandListFunction()->Write32BitValueBottomOfPipeX(this, + Destination, + Value, + Flush, + Flags); + } + + D3DINLINE void D3DAPI Write64BitValueBottomOfPipeX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 Value, + _In_ D3D12XBOX_FLUSH Flush, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS Flags) + { + CommandListFunction()->Write64BitValueBottomOfPipeX(this, + Destination, + Value, + Flush, + Flags); + } + + D3DINLINE void D3DAPI Write32BitValueBottomOfShaderX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT Value, + _In_ D3D12XBOX_SHADER_STAGE ShaderStage) + { + CommandListFunction()->Write32BitValueBottomOfShaderX(this, + Destination, + Value, + ShaderStage); + } + + D3DINLINE void D3DAPI Wait32BitValueX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Address, + _In_ D3D12_COMPARISON_FUNC ComparisonFunction, + _In_ UINT ReferenceValue, + _In_ UINT MaskValue, + _In_ D3D12XBOX_WAIT_FLAGS Flags) + { + CommandListFunction()->Wait32BitValueX(this, + Address, + ComparisonFunction, + ReferenceValue, + MaskValue, + Flags); + } + + D3DINLINE void D3DAPI Wait64BitValueX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Address, + _In_ D3D12_COMPARISON_FUNC ComparisonFunction, + _In_ UINT64 ReferenceValue, + _In_ D3D12XBOX_WAIT_FLAGS Flags) + { + CommandListFunction()->Wait64BitValueX(this, + Address, + ComparisonFunction, + ReferenceValue, + Flags); + } + + D3DINLINE void D3DAPI SetOcclusionQueryControlX( + _In_opt_ const D3D12XBOX_OCCLUSION_QUERY_CONTROL* pControl) + { + CommandListFunction()->SetOcclusionQueryControlX(this, pControl); + } + + D3DINLINE void D3DAPI SetPerfectOcclusionQueriesX( + BOOL PerfectOcclusionQueries) + { + CommandListFunction()->SetPerfectOcclusionQueriesX(this, PerfectOcclusionQueries); + } + + D3DINLINE void D3DAPI SetHiStencilControlX( + _In_opt_ const D3D12XBOX_HISTENCIL_CONTROL* pControl) + { + CommandListFunction()->SetHiStencilStateX(this, nullptr, pControl); + } + + D3DINLINE void D3DAPI SetHiStencilStateX( + _In_ ID3D12Resource* pResource, + _In_opt_ const D3D12XBOX_HISTENCIL_CONTROL* pControl) + { + CommandListFunction()->SetHiStencilStateX(this, pResource, pControl); + } + + D3DINLINE void D3DAPI FlushPipelineX( + _In_ D3D12XBOX_FLUSH Flags, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BaseAddress, + _In_ SIZE_T SizeInBytes) + { + CommandListFunction()->FlushPipelineX(this, + Flags, + BaseAddress, + SizeInBytes); + } + + D3DINLINE void D3DAPI OMSetDepthBoundsX( + _In_ FLOAT Min, + _In_ FLOAT Max) + { + CommandListFunction()->OMSetDepthBoundsX(this, + Min, + Max); + } + + D3DINLINE void D3DAPI SetPixelShaderDepthForceZOrderX( + _In_ BOOL ForceOrder) + { + CommandListFunction()->SetPixelShaderDepthForceZOrderX(this, + ForceOrder); + } + + D3DINLINE void D3DAPI ExecuteIndirectBundleX( + _In_ ID3D12Resource* pBundleBuffer, + _In_ UINT BundleBufferOffset, + _In_ UINT MaxSize, + _In_opt_ ID3D12Resource* pSizeBuffer, + _In_ UINT SizeBufferOffset, + _In_ UINT PredicationBufferOffset) + { + CommandListFunction()->ExecuteIndirectBundleX(this, + pBundleBuffer, + BundleBufferOffset, + MaxSize, + pSizeBuffer, + SizeBufferOffset, + PredicationBufferOffset); + } + + D3DINLINE void D3DAPI SetupOrderedAppendCounterX( + _In_ UINT CounterIndex, + _In_ UINT RingBufferAvailableSpace, + _In_ UINT GdsAddressOfTheCounterDwords, + _In_ D3D12XBOX_ORDERED_APPEND_SHADER_STAGE ShaderStage, + _In_ UINT Enable, + _In_ UINT ReservedSetTo0) + { + CommandListFunction()->SetupOrderedAppendCounterX(this, + CounterIndex, + RingBufferAvailableSpace, + GdsAddressOfTheCounterDwords, + ShaderStage, + Enable, + ReservedSetTo0); + } + + D3DINLINE void D3DAPI WriteGDSX( + _In_ UINT OffsetDwords, + _In_ UINT NumDwords, + _In_ const UINT* pValues, + _In_ D3D12XBOX_GDS_OPERATION Flags) + { + CommandListFunction()->WriteGDSX(this, + OffsetDwords, + NumDwords, + pValues, + Flags); + } + + D3DINLINE void D3DAPI ReadGDSX( + _In_ UINT OffsetDwords, + _In_ UINT NumDwords, + _Inout_ D3D12_GPU_VIRTUAL_ADDRESS pValues, + _In_ D3D12XBOX_GDS_OPERATION Flags) + { + CommandListFunction()->ReadGDSX(this, + OffsetDwords, + NumDwords, + pValues, + Flags); + } + + D3DINLINE void D3DAPI DispatchX( + _In_ UINT ThreadGroupCountX, + _In_ UINT ThreadGroupCountY, + _In_ UINT ThreadGroupCountZ, + _In_ D3D12XBOX_DISPATCH_FLAGS Flags) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Draw) + { + m_Putter.PutD(pPut, D3D12XBOX_PACKET_DISPATCH_X); + m_Putter.PutD(pPut, ThreadGroupCountX); + m_Putter.PutD(pPut, ThreadGroupCountY); + m_Putter.PutD(pPut, ThreadGroupCountZ); + m_Putter.PutD(pPut, Flags); + m_Putter.m_pCurrent = pPut; + + m_cpuState.shmem_dirty = 0; + } + else + { + CommandListFunction()->DispatchX(this, + ThreadGroupCountX, + ThreadGroupCountY, + ThreadGroupCountZ, + Flags); + } + } + + D3DINLINE void D3DAPI RSSetMSAAParametersX( + _In_opt_ const D3D12XBOX_MSAA_SAMPLE_LOCATIONS* pSampleLocations, + _In_opt_ const D3D12XBOX_MSAA_CENTROID_PRIORITIES* pCentroidPriorities, + _In_opt_ const D3D12XBOX_MSAA_PARAMETERS* pMSAAParameters) + { + CommandListFunction()->RSSetMSAAParametersX(this, + pSampleLocations, + pCentroidPriorities, + pMSAAParameters); + } + + D3DINLINE void D3DAPI DrawIndexedX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS IndexBufferLocation, + _In_ DXGI_FORMAT IndexFormat, + _In_ UINT IndexCount, + _In_ UINT IndexOffset) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Draw) + { + m_Putter.PutD(pPut, D3D12XBOX_PACKET_DRAW_INDEXED_X); + m_Putter.PutQ(pPut, IndexBufferLocation); + m_Putter.PutD(pPut, IndexFormat); + m_Putter.PutD(pPut, IndexCount); + m_Putter.PutD(pPut, IndexOffset); + m_Putter.m_pCurrent = pPut; + + m_cpuState.shmem_dirty = 0; + } + else + { + CommandListFunction()->DrawIndexedX(this, + IndexBufferLocation, + IndexFormat, + IndexCount, + IndexOffset); + } + }; + + D3DINLINE void D3DAPI NopX( + _In_ UINT SizeBytes) + { + D3D12XBOX_PPUT pPut = m_Putter.m_pCurrent; + if (pPut < m_Putter.m_pLimit_Api) + { + D3D12XBOX_PPUT pEnd = (D3D12XBOX_PPUT)((UINT_PTR) pPut + SizeBytes); + if (SizeBytes == 4) + { + m_Putter.PutD(pPut, D3D12XBOX_PACKET_NOP); + } + else + { + m_Putter.PutD(pPut, D3D12XBOX_PACKET_NOP_WITH_COUNT + (SizeBytes << (D3D12XBOX_PACKET_COUNT_SHIFT - 2))); + } + m_Putter.m_pCurrent = pEnd; + } + else + { + CommandListFunction()->NopX(this, + SizeBytes); + } + }; + + D3DINLINE void D3DAPI ExecuteCommandListsX( + _In_ UINT Count, + _In_reads_(Count) ID3D12CommandList* const* ppCommandLists, + _In_reads_(Count) UINT* const* ppPredicationBufferOffsets) + { + CommandListFunction()->ExecuteCommandListsX(this, + Count, + ppCommandLists, + ppPredicationBufferOffsets); + } + + D3DINLINE UINT D3DAPI GetExecutionCommandSizeX() + { + return CommandListFunction()->GetExecutionCommandSizeX(this); + } + + D3DINLINE UINT D3DAPI CloseBundleX( + _Inout_ void** ppBundleBufferAddress, + UINT BundleBufferMaxSize) + { + return CommandListFunction()->CloseBundleX(this, + ppBundleBufferAddress, + BundleBufferMaxSize); + } + + D3DINLINE void D3DAPI KickoffX() + { + CommandListFunction()->KickoffX(this); + } + + D3DINLINE void D3DAPI RSSetDepthBiasX( + _In_ INT DepthBias, + _In_ FLOAT DepthBiasClamp, + _In_ FLOAT SlopeScaledDepthBias, + _In_ BOOL DepthClipEnable) + + { + CommandListFunction()->RSSetDepthBiasX(this, + DepthBias, + DepthBiasClamp, + SlopeScaledDepthBias, + DepthClipEnable); + } + + D3DINLINE void D3DAPI SetGraphicsShaderLimitsX( + _In_ BOOL PixelShaderEnabled, + _In_ BOOL TessellationEnabled, + _In_ BOOL GeometryShaderEnabled, + _In_ BOOL GeometryShaderOnChip, + _In_ BOOL PrimitiveShaderEnabled, + _In_opt_ const D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC* pShaderLimits) + { + CommandListFunction()->SetGraphicsShaderLimitsX(this, + PixelShaderEnabled, + TessellationEnabled, + GeometryShaderEnabled, + GeometryShaderOnChip, + PrimitiveShaderEnabled, + pShaderLimits); + } + + D3DINLINE void D3DAPI SetComputeShaderLimitsX( + _In_opt_ const D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC* pShaderLimits) + { + CommandListFunction()->SetComputeShaderLimitsX(this, + pShaderLimits); + } + + D3DINLINE void D3DAPI SetResourceCompressionStateX( + _Inout_ ID3D12Resource* pResource, + _In_ D3D12XBOX_COMPRESSION_STATE_FLAGS CompressionStateFlags, + _In_ D3D12_RESOURCE_STATES PreserveFlags) + { + CommandListFunction()->SetResourceCompressionStateX(this, + pResource, + CompressionStateFlags, + PreserveFlags); + } + + D3DINLINE void D3DAPI DispatchMeshX( + _In_ UINT ThreadGroupCountX, + _In_ UINT64 Flags, + _In_ UINT64 IndirectArgsPointer, + _In_ UINT64 PayloadPointer) + { + CommandListFunction()->DispatchMeshX(this, + ThreadGroupCountX, + Flags, + IndirectArgsPointer, + PayloadPointer); + } + + D3DINLINE UINT64 D3DAPI DriverHintX( + _In_ UINT64 feature, + _In_ UINT64 value) + { + return CommandListFunction()->DriverHintX(this, + feature, + value); + } + + D3DINLINE void D3DAPI StartCountersX( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12XboxCounterSet* pCounterSet) + { + return CommandListFunction()->StartCountersX(this, + pCounterSet); + } + + D3DINLINE void D3DAPI SampleCountersX( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12Resource* pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset) + { + return CommandListFunction()->SampleCountersX(this, + pDestinationBuffer, + AlignedDestinationBufferOffset); + } + + D3DINLINE void D3DAPI StopCountersX( + _Inout_ ID3D12GraphicsCommandList* pCommandList) + { + return CommandListFunction()->StopCountersX(this); + } + + D3DINLINE void D3DAPI SetDeferredPrimitiveBatchBinningX( + _In_opt_ const D3D12XBOX_DPBB_STATE* pBinningState) + { + CommandListFunction()->SetDeferredPrimitiveBatchBinningX(this, pBinningState); + } + + D3DINLINE void D3DAPI DeferredPrimitiveBreakBatchX() + { + CommandListFunction()->DeferredPrimitiveBreakBatchX(this); + } +}; + +extern "C" +{ + + // + // ID3D12XboxDmaCommandList + // + + struct D3D12DmaCommandList_Function_Table + { + D3D12CommandList_Function_Table CommandListFunction; + + HRESULT (D3DAPI* Close)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList); + + HRESULT (D3DAPI* Reset)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12CommandAllocator* pAllocator, + _In_opt_ ID3D12PipelineState* pInitialState); + + void (D3DAPI* CopyBufferRegion)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12Resource* pDstBuffer, + UINT64 DstOffset, + _In_ ID3D12Resource* pSrcBuffer, + UINT64 SrcOffset, + UINT64 NumBytes); + + void (D3DAPI* CopyTextureRegion)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, + UINT DstX, + UINT DstY, + UINT DstZ, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pSrc, + _In_opt_ const D3D12_BOX* pSrcBox); + + void (D3DAPI* CopyResource)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12Resource* pDstResource, + _In_ ID3D12Resource* pSrcResource); + + void (D3DAPI* CopyTiles)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12Resource* pTiledResource, + _In_ const D3D12_TILED_RESOURCE_COORDINATE* pTileRegionStartCoordinate, + _In_ const D3D12_TILE_REGION_SIZE* pTileRegionSize, + _In_ ID3D12Resource* pBuffer, + UINT64 BufferStartOffsetInBytes, + D3D12_TILE_COPY_FLAGS Flags); + + D3D12XBOX_RESOURCE_BARRIER_ACTIONS (D3DAPI* ResourceBarrier)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER* pBarriers); + + void (D3DAPI* BeginQuery)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void (D3DAPI* EndQuery)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void (D3DAPI* ResolveQueryData)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartElement, + _In_ UINT ElementCount, + _In_ ID3D12Resource* pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset); + + void (D3DAPI* SetMarker)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size); + + void (D3DAPI* BeginEvent)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size); + + void (D3DAPI* EndEvent)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList); + + void (D3DAPI* InsertGpuMarker)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + UINT8 opcode, + _In_reads_bytes_(Size) const void* pData, + UINT Size); + + void (D3DAPI* InsertTimingMarker)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + UINT8 opcode); + + void (D3DAPI* CopyMemoryToMemoryX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS Destination, + D3D12_GPU_VIRTUAL_ADDRESS Source, + UINT64 SizeBytes, + D3D12XBOX_COPY_FLAGS Flags); + + void (D3DAPI* FillMemoryWith32BitValueX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS Destination, + UINT64 SizeBytes, + UINT Value, + D3D12XBOX_COPY_FLAGS Flags); + + void (D3DAPI* Write64BitValueBottomOfPipeX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 Value, + _In_ D3D12XBOX_FLUSH Flush, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS Flags); + + void (D3DAPI* Wait64BitValueX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Address, + _In_ D3D12_COMPARISON_FUNC ComparisonFunction, + _In_ UINT64 ReferenceValue, + _In_ D3D12XBOX_WAIT_FLAGS Flags); + + void (D3DAPI* CopyLastErrorCodeToMemoryX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination ); + + HRESULT (D3DAPI* LZDecompressMemoryX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS DecompressedDestination, + D3D12_GPU_VIRTUAL_ADDRESS CompressedSource, + UINT64 SourceSizeBytes); + + HRESULT (D3DAPI* LZCompressMemoryX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS CompressedDestination, + D3D12_GPU_VIRTUAL_ADDRESS DecompressedSource, + UINT64 SourceSizeBytes); + + HRESULT (D3DAPI* JPEGDecodeMemoryX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, + UINT DstX, + UINT DstY, + UINT DstZ, + D3D12_GPU_VIRTUAL_ADDRESS Source, + UINT64 SourceSizeBytes); + + void (D3DAPI* EnqueueDwordsX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_reads_bytes_(DwordCount * 4) const UINT32* pPacketDwords, + UINT32 DwordCount); + + void (D3DAPI* KickoffX)( + _Inout_ ID3D12XboxDmaCommandList* pCommandList); + }; + + +#if DECLARE_UMD_EXPORTS_D3D12X + + D3D12_COMMAND_LIST_TYPE D3d12DmaCommandList_GetType( + _Inout_ ID3D12CommandList* pCommandList); + + ULONG D3DAPI D3d12DmaCommandList_Release( + _Inout_ IGraphicsUnknown* pCommandList); + + HRESULT D3DAPI D3d12DmaCommandList_Close( + _Inout_ ID3D12XboxDmaCommandList* pCommandList); + + HRESULT D3DAPI D3d12DmaCommandList_Reset( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12CommandAllocator* pAllocator, + _In_opt_ ID3D12PipelineState* pInitialState); + + void D3DAPI D3d12DmaCommandList_CopyBufferRegion( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12Resource* pDstBuffer, + UINT64 DstOffset, + _In_ ID3D12Resource* pSrcBuffer, + UINT64 SrcOffset, + UINT64 NumBytes); + + void D3DAPI D3d12DmaCommandList_CopyTextureRegion( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, + UINT DstX, + UINT DstY, + UINT DstZ, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pSrc, + _In_opt_ const D3D12_BOX* pSrcBox); + + void D3DAPI D3d12DmaCommandList_CopyResource( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12Resource* pDstResource, + _In_ ID3D12Resource* pSrcResource); + + void D3DAPI D3d12DmaCommandList_CopyTiles( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12Resource* pTiledResource, + _In_ const D3D12_TILED_RESOURCE_COORDINATE* pTileRegionStartCoordinate, + _In_ const D3D12_TILE_REGION_SIZE* pTileRegionSize, + _In_ ID3D12Resource* pBuffer, + UINT64 BufferStartOffsetInBytes, + D3D12_TILE_COPY_FLAGS Flags); + + D3D12XBOX_RESOURCE_BARRIER_ACTIONS D3DAPI D3d12DmaCommandList_ResourceBarrier( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER* pBarriers); + + void D3DAPI D3d12DmaCommandList_BeginQuery( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void D3DAPI D3d12DmaCommandList_EndQuery( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void D3DAPI D3d12DmaCommandList_ResolveQueryData( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartElement, + _In_ UINT ElementCount, + _In_ ID3D12Resource* pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset); + + void D3DAPI D3d12DmaCommandList_SetMarker( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size); + + void D3DAPI D3d12DmaCommandList_BeginEvent( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size); + + void D3DAPI D3d12DmaCommandList_EndEvent( + _Inout_ ID3D12XboxDmaCommandList* pCommandList); + + void D3DAPI D3d12DmaCommandList_InsertGpuMarker( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + UINT8 opcode, + _In_reads_bytes_(Size) const void* pData, + UINT Size); + + void D3DAPI D3d12DmaCommandList_InsertTimingMarker( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + UINT8 opcode); + + void D3DAPI D3d12DmaCommandList_CopyMemoryToMemoryX( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS Destination, + D3D12_GPU_VIRTUAL_ADDRESS Source, + UINT64 SizeBytes, + D3D12XBOX_COPY_FLAGS Flags); + + void D3DAPI D3d12DmaCommandList_FillMemoryWith32BitValueX( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + D3D12_GPU_VIRTUAL_ADDRESS Destination, + UINT64 SizeBytes, + UINT Value, + D3D12XBOX_COPY_FLAGS Flags); + + void D3DAPI D3d12DmaCommandList_Write64BitValueBottomOfPipeX( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 Value, + _In_ D3D12XBOX_FLUSH Flush, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS Flags); + + void D3DAPI D3d12DmaCommandList_Wait64BitValueX( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Address, + _In_ D3D12_COMPARISON_FUNC ComparisonFunction, + _In_ UINT64 ReferenceValue, + _In_ D3D12XBOX_WAIT_FLAGS Flags); + + void D3DAPI D3d12DmaCommandList_EnqueueDwordsX( + _Inout_ ID3D12XboxDmaCommandList* pCommandList, + _In_reads_bytes_(DwordCount * 4) const UINT32* pPacketDwords, + UINT32 DwordCount); + + void D3DAPI D3d12DmaCommandList_KickoffX( + _Inout_ ID3D12XboxDmaCommandList* pCommandList); + + D3DCONST D3D12DmaCommandList_Function_Table D3D__D3d12DmaCommandList_Function_Table = + { + { + { + { + { + D3d12Object_QueryInterface, + D3d12DeviceChild_AddRef, + D3d12DmaCommandList_Release, + }, + + D3d12Object_GetPrivateData, + D3d12Object_SetPrivateData, + D3d12Object_SetPrivateDataInterface, + D3d12Object_SetName, + }, + + D3d12DeviceChild_GetDevice, + }, + + D3d12DmaCommandList_GetType, + }, + + D3d12DmaCommandList_Close, + D3d12DmaCommandList_Reset, + D3d12DmaCommandList_CopyBufferRegion, + D3d12DmaCommandList_CopyTextureRegion, + D3d12DmaCommandList_CopyResource, + D3d12DmaCommandList_CopyTiles, + D3d12DmaCommandList_ResourceBarrier, + D3d12DmaCommandList_BeginQuery, + D3d12DmaCommandList_EndQuery, + D3d12DmaCommandList_ResolveQueryData, + D3d12DmaCommandList_SetMarker, + D3d12DmaCommandList_BeginEvent, + D3d12DmaCommandList_EndEvent, + D3d12DmaCommandList_InsertGpuMarker, + D3d12DmaCommandList_InsertTimingMarker, + D3d12DmaCommandList_CopyMemoryToMemoryX, + D3d12DmaCommandList_FillMemoryWith32BitValueX, + D3d12DmaCommandList_Write64BitValueBottomOfPipeX, + D3d12DmaCommandList_Wait64BitValueX, + + nullptr, + nullptr, + nullptr, + nullptr, + D3d12DmaCommandList_EnqueueDwordsX, + D3d12DmaCommandList_KickoffX, + }; + +#endif + +} + + +extern "C" +{ + +// +// ID3D12GraphicsCommandList1 +// + +struct D3D12GraphicsCommandList1_Function_Table +{ + D3D12GraphicsCommandList_Function_Table CommandListFunction; + + void (D3DAPI* AtomicCopyBufferUINT)( + _Inout_ ID3D12GraphicsCommandList1* pCommandList, + _In_ ID3D12Resource* pDstBuffer, + UINT64 DstOffset, + _In_ ID3D12Resource* pSrcBuffer, + UINT64 SrcOffset, + UINT Dependencies, + _In_reads_(Dependencies) ID3D12Resource* const* ppDependentResources, + _In_reads_(Dependencies) const D3D12_SUBRESOURCE_RANGE_UINT64* pDependentSubresourceRanges); + + void (D3DAPI* AtomicCopyBufferUINT64)( + _Inout_ ID3D12GraphicsCommandList1* pCommandList, + _In_ ID3D12Resource* pDstBuffer, + UINT64 DstOffset, + _In_ ID3D12Resource* pSrcBuffer, + UINT64 SrcOffset, + UINT Dependencies, + _In_reads_(Dependencies) ID3D12Resource* const* ppDependentResources, + _In_reads_(Dependencies) const D3D12_SUBRESOURCE_RANGE_UINT64* pDependentSubresourceRanges); + + void (D3DAPI* OMSetDepthBounds)( + _Inout_ ID3D12GraphicsCommandList1* pCommandList, + _In_ FLOAT Min, + _In_ FLOAT Max); + + void (D3DAPI* SetSamplePositions)( + _Inout_ ID3D12GraphicsCommandList1* pCommandList, + _In_ UINT NumSamplesPerPixel, + _In_ UINT NumPixels, + _In_reads_(NumSamplesPerPixel * NumPixels) D3D12_SAMPLE_POSITION* pSamplePositions); + + void (D3DAPI* ResolveSubresourceRegion)( + _Inout_ ID3D12GraphicsCommandList1* pCommandList, + _In_ ID3D12Resource* pDstResource, + _In_ UINT DstSubresource, + _In_ UINT DstX, + _In_ UINT DstY, + _In_ ID3D12Resource* pSrcResource, + _In_ UINT SrcSubresource, + _In_opt_ D3D12_RECT* pSrcRect, + _In_ DXGI_FORMAT Format, + _In_ D3D12_RESOLVE_MODE ResolveMode); + + void (D3DAPI* SetViewInstanceMask)( + _Inout_ ID3D12GraphicsCommandList1* pCommandList, + _In_ UINT Mask); +}; + +} + + +D3DINTERFACE(ID3D12GraphicsCommandList1, 553103fb,1fe7,4557,bb,38,94,6d,7d,0e,7c,a7) : public ID3D12GraphicsCommandList +{ +public: + + D3DINLINE D3D12GraphicsCommandList1_Function_Table* CommandList1Function() + { + return (D3D12GraphicsCommandList1_Function_Table*)m_pFunction; + } + + D3DINLINE void D3DAPI AtomicCopyBufferUINT( + _In_ ID3D12Resource* pDstBuffer, + UINT64 DstOffset, + _In_ ID3D12Resource* pSrcBuffer, + UINT64 SrcOffset, + UINT Dependencies, + _In_reads_(Dependencies) ID3D12Resource* const* ppDependentResources, + _In_reads_(Dependencies) const D3D12_SUBRESOURCE_RANGE_UINT64* pDependentSubresourceRanges) + { + CommandList1Function()->AtomicCopyBufferUINT( + this, + pDstBuffer, + DstOffset, + pSrcBuffer, + SrcOffset, + Dependencies, + ppDependentResources, + pDependentSubresourceRanges); + } + + D3DINLINE void D3DAPI AtomicCopyBufferUINT64( + _In_ ID3D12Resource* pDstBuffer, + UINT64 DstOffset, + _In_ ID3D12Resource* pSrcBuffer, + UINT64 SrcOffset, + UINT Dependencies, + _In_reads_(Dependencies) ID3D12Resource* const* ppDependentResources, + _In_reads_(Dependencies) const D3D12_SUBRESOURCE_RANGE_UINT64* pDependentSubresourceRanges) + { + CommandList1Function()->AtomicCopyBufferUINT64( + this, + pDstBuffer, + DstOffset, + pSrcBuffer, + SrcOffset, + Dependencies, + ppDependentResources, + pDependentSubresourceRanges); + } + + D3DINLINE void D3DAPI OMSetDepthBounds( + _In_ FLOAT Min, + _In_ FLOAT Max) + { + CommandList1Function()->OMSetDepthBounds( + this, + Min, + Max); + } + + D3DINLINE void D3DAPI SetSamplePositions( + _In_ UINT NumSamplesPerPixel, + _In_ UINT NumPixels, + _In_reads_(NumSamplesPerPixel * NumPixels) D3D12_SAMPLE_POSITION* pSamplePositions) + { + CommandList1Function()->SetSamplePositions( + this, + NumSamplesPerPixel, + NumPixels, + pSamplePositions); + } + + D3DINLINE void D3DAPI ResolveSubresourceRegion( + _In_ ID3D12Resource* pDstResource, + _In_ UINT DstSubresource, + _In_ UINT DstX, + _In_ UINT DstY, + _In_ ID3D12Resource* pSrcResource, + _In_ UINT SrcSubresource, + _In_opt_ D3D12_RECT* pSrcRect, + _In_ DXGI_FORMAT Format, + _In_ D3D12_RESOLVE_MODE ResolveMode) + { + CommandList1Function()->ResolveSubresourceRegion( + this, + pDstResource, + DstSubresource, + DstX, + DstY, + pSrcResource, + SrcSubresource, + pSrcRect, + Format, + ResolveMode); + } + + D3DINLINE void D3DAPI SetViewInstanceMask( + _In_ UINT Mask) + { + CommandList1Function()->SetViewInstanceMask( + this, + Mask); + } +}; + + +extern "C" +{ + +typedef struct D3D12_WRITEBUFFERIMMEDIATE_PARAMETER +{ + D3D12_GPU_VIRTUAL_ADDRESS Dest; + UINT32 Value; +} D3D12_WRITEBUFFERIMMEDIATE_PARAMETER; + +typedef enum D3D12_WRITEBUFFERIMMEDIATE_MODE +{ + D3D12_WRITEBUFFERIMMEDIATE_MODE_DEFAULT = 0, + D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN = 0x1, + D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT = 0x2 +} D3D12_WRITEBUFFERIMMEDIATE_MODE; + +// +// ID3D12GraphicsCommandList2 +// + +struct D3D12GraphicsCommandList2_Function_Table +{ + D3D12GraphicsCommandList1_Function_Table CommandListFunction; + + void (D3DAPI* WriteBufferImmediate)( + _Inout_ ID3D12GraphicsCommandList2* pCommandList, + UINT Count, + _In_reads_(Count) const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER* pParams, + _In_reads_opt_(Count) const D3D12_WRITEBUFFERIMMEDIATE_MODE* pModes); +}; + +} + +D3DINTERFACE(ID3D12GraphicsCommandList2, 38C3E585,FF17,412C,91,50,4F,C6,F9,D7,2A,28) : public ID3D12GraphicsCommandList1 +{ +public: + + D3DINLINE D3D12GraphicsCommandList2_Function_Table* CommandList2Function() + { + return (D3D12GraphicsCommandList2_Function_Table*)m_pFunction; + } + + D3DINLINE void D3DAPI WriteBufferImmediate( + UINT Count, + _In_reads_(Count) const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER* pParams, + _In_reads_opt_(Count) const D3D12_WRITEBUFFERIMMEDIATE_MODE* pModes) + { + CommandList2Function()->WriteBufferImmediate( + this, + Count, + pParams, + pModes); + } +}; + + +D3DINTERFACE(ID3D12XboxDmaCommandList, 30bc77b9,8379,4b25,95,de,b8,58,8c,42,27,5d) : public ID3D12CommandList +{ +public: + + D3DINLINE D3D12DmaCommandList_Function_Table* CommandListFunction() + { + return (D3D12DmaCommandList_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI Close() + { + return CommandListFunction()->Close(this); + } + + D3DINLINE HRESULT D3DAPI Reset( + _In_ ID3D12CommandAllocator* pAllocator, + _In_opt_ ID3D12PipelineState* pInitialState) + { + return CommandListFunction()->Reset(this, pAllocator, pInitialState); + } + + D3DINLINE void D3DAPI CopyBufferRegion( + _In_ ID3D12Resource* pDstBuffer, + UINT64 DstOffset, + _In_ ID3D12Resource* pSrcBuffer, + UINT64 SrcOffset, + UINT64 NumBytes) + { + CommandListFunction()->CopyBufferRegion(this, + pDstBuffer, + DstOffset, + pSrcBuffer, + SrcOffset, + NumBytes); + } + + D3DINLINE void D3DAPI CopyTextureRegion( + _In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, + UINT DstX, + UINT DstY, + UINT DstZ, + _In_ const D3D12_TEXTURE_COPY_LOCATION *pSrc, + _In_opt_ const D3D12_BOX* pSrcBox) + { + CommandListFunction()->CopyTextureRegion(this, + pDst, + DstX, + DstY, + DstZ, + pSrc, + pSrcBox); + } + + D3DINLINE void D3DAPI CopyResource( + _In_ ID3D12Resource* pDstResource, + _In_ ID3D12Resource* pSrcResource) + { + CommandListFunction()->CopyResource(this, pDstResource, pSrcResource); + } + + D3DINLINE void D3DAPI CopyTiles( + _In_ ID3D12Resource* pTiledResource, + _In_ const D3D12_TILED_RESOURCE_COORDINATE* pTileRegionStartCoordinate, + _In_ const D3D12_TILE_REGION_SIZE* pTileRegionSize, + _In_ ID3D12Resource* pBuffer, + UINT64 BufferStartOffsetInBytes, + D3D12_TILE_COPY_FLAGS Flags) + { + CommandListFunction()->CopyTiles(this, + pTiledResource, + pTileRegionStartCoordinate, + pTileRegionSize, + pBuffer, + BufferStartOffsetInBytes, + Flags); + } + + D3DINLINE void D3DAPI ResourceBarrier( + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER* pBarriers) + { + CommandListFunction()->ResourceBarrier(this, NumBarriers, pBarriers); + } + + D3DINLINE void D3DAPI BeginQuery( + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index) + { + CommandListFunction()->BeginQuery(this, pQueryHeap, Type, Index); + } + + D3DINLINE void D3DAPI EndQuery( + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index) + { + CommandListFunction()->EndQuery(this, pQueryHeap, Type, Index); + } + + D3DINLINE void D3DAPI ResolveQueryData( + _In_ ID3D12QueryHeap* pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartElement, + _In_ UINT ElementCount, + _In_ ID3D12Resource* pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset) + { + CommandListFunction()->ResolveQueryData(this, + pQueryHeap, + Type, + StartElement, + ElementCount, + pDestinationBuffer, + AlignedDestinationBufferOffset); + } + + D3DINLINE void D3DAPI SetMarker( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size) + { + CommandListFunction()->SetMarker(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI BeginEvent( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size) + { + CommandListFunction()->BeginEvent(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI EndEvent() + { + CommandListFunction()->EndEvent(this); + } + + D3DINLINE void D3DAPI InsertGpuMarker( + UINT8 opcode, + _In_reads_bytes_(Size) const void* pData, + UINT Size) + { + CommandListFunction()->InsertGpuMarker(this, opcode, pData, Size); + } + + D3DINLINE void D3DAPI InsertTimingMarker( + UINT8 opcode) + { + CommandListFunction()->InsertTimingMarker(this, opcode); + } + + D3DINLINE void D3DAPI CopyMemoryToMemoryX( + D3D12_GPU_VIRTUAL_ADDRESS Destination, + D3D12_GPU_VIRTUAL_ADDRESS Source, + UINT64 SizeBytes, + D3D12XBOX_COPY_FLAGS Flags) + { + CommandListFunction()->CopyMemoryToMemoryX(this, + Destination, + Source, + SizeBytes, + Flags); + } + + D3DINLINE void D3DAPI FillMemoryWith32BitValueX( + D3D12_GPU_VIRTUAL_ADDRESS Destination, + UINT64 SizeBytes, + UINT Value, + D3D12XBOX_COPY_FLAGS Flags) + { + CommandListFunction()->FillMemoryWith32BitValueX(this, + Destination, + SizeBytes, + Value, + Flags); + } + + D3DINLINE void D3DAPI Write64BitValueBottomOfPipeX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 Value, + _In_ D3D12XBOX_FLUSH Flush, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS Flags) + { + CommandListFunction()->Write64BitValueBottomOfPipeX(this, + Destination, + Value, + Flush, + Flags); + } + + D3DINLINE void D3DAPI Wait64BitValueX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Address, + _In_ D3D12_COMPARISON_FUNC ComparisonFunction, + _In_ UINT64 ReferenceValue, + _In_ D3D12XBOX_WAIT_FLAGS Flags) + { + CommandListFunction()->Wait64BitValueX(this, + Address, + ComparisonFunction, + ReferenceValue, + Flags); + } + + D3DINLINE void D3DAPI EnqueueDwordsX( + _In_reads_bytes_(DwordCount * 4) const UINT32* pPacketDwords, + UINT32 DwordCount) + { + CommandListFunction()->EnqueueDwordsX(this, pPacketDwords, DwordCount); + } + + D3DINLINE void D3DAPI KickoffX() + { + CommandListFunction()->KickoffX(this); + } +}; + +extern "C" +{ + +// +// ID3D12CommandQueue +// + +typedef enum D3D12XBOX_EXECUTE_COMMAND_LIST_FLAGS : UINT +{ + D3D12XBOX_EXECUTE_COMMAND_LIST_FLAGS_NONE = 0, + D3D12XBOX_EXECUTE_COMMAND_LIST_FLAGS_NO_SWITCH_BUFFER = 1, + D3D12XBOX_EXECUTE_COMMAND_LIST_FLAGS_CHAIN_SEGMENTS = 2, +} D3D12XBOX_EXECUTE_COMMAND_LIST_FLAGS; + +struct D3D12CommandQueue_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; + + void (D3DAPI* UpdateTileMappings)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ ID3D12Resource* pResource, + UINT NumResourceRegions, + _In_reads_opt_(NumResourceRegions) const D3D12_TILED_RESOURCE_COORDINATE* pResourceRegionStartCoordinates, + _In_reads_opt_(NumResourceRegions) const D3D12_TILE_REGION_SIZE* pResourceRegionSizes, + _In_opt_ ID3D12Heap* pHeap, + UINT NumRanges, + _In_reads_opt_(NumRanges) const D3D12_TILE_RANGE_FLAGS* pRangeFlags, + _In_reads_opt_(NumRanges) const UINT* pHeapRangeStartOffsets, + _In_reads_opt_(NumRanges) const UINT* pRangeTileCounts, + D3D12_TILE_MAPPING_FLAGS Flags); + + void (D3DAPI* CopyTileMappings)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ ID3D12Resource* pDstResource, + _In_ const D3D12_TILED_RESOURCE_COORDINATE* pDstRegionStartCoordinate, + _In_ ID3D12Resource* pSrcResource, + _In_ const D3D12_TILED_RESOURCE_COORDINATE* pSrcRegionStartCoordinate, + _In_ const D3D12_TILE_REGION_SIZE* pRegionSize, + D3D12_TILE_MAPPING_FLAGS Flags); + + void (D3DAPI* ExecuteCommandLists)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ UINT Count, + _In_reads_(Count) ID3D12CommandList* const* ppCommandLists); + + void (D3DAPI* SetMarker)( + _Inout_ ID3D12CommandQueue* pQueue, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size); + + void (D3DAPI* BeginEvent)( + _Inout_ ID3D12CommandQueue* pQueue, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size); + + void (D3DAPI* EndEvent)( + _Inout_ ID3D12CommandQueue* pQueue); + + void (D3DAPI* InsertGpuMarker)( + _Inout_ ID3D12CommandQueue* pQueue, + UINT8 opcode, + _In_reads_bytes_(Size) const void* pData, + UINT Size); + + void (D3DAPI* InsertTimingMarker)( + _Inout_ ID3D12CommandQueue* pQueue, + UINT8 opcode); + + HRESULT (D3DAPI* Signal)( + _Inout_ ID3D12CommandQueue* pQueue, + ID3D12Fence* pFence, + UINT64 Value); + + HRESULT (D3DAPI* Wait)( + _Inout_ ID3D12CommandQueue* pQueue, + ID3D12Fence* pFence, + UINT64 Value); + + HRESULT (D3DAPI* GetTimestampFrequency)( + _Inout_ ID3D12CommandQueue* pQueue, + _Out_ UINT64* pFrequency); + + HRESULT (D3DAPI* GetClockCalibration)( + _Inout_ ID3D12CommandQueue* pQueue, + _Out_ UINT64* pGpuTimestamp, + _Out_ UINT64* pCpuTimestamp); + + HRESULT (D3DAPI* PIXGpuCaptureNextFrame)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ UINT Flags, + _In_z_ LPCWSTR lpOutputFileName); + + HRESULT (D3DAPI* PIXGpuBeginCapture)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ UINT Flags, + _In_z_ LPCWSTR lpOutputFileName); + + HRESULT (D3DAPI* PIXGpuEndCapture)( + _Inout_ ID3D12CommandQueue* pQueue); + + HRESULT (D3DAPI* SuspendX)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ UINT Flags); + + HRESULT (D3DAPI* ResumeX)( + _Inout_ ID3D12CommandQueue* pQueue); + + HRESULT (D3DAPI* SignalX)( + _Inout_ ID3D12CommandQueue* pQueue, + ID3D12Fence* pFence, + UINT64 Value, + D3D12XBOX_FLUSH FlushFlags); + + void (D3DAPI* InvalidateGraphicsTLBX)( + _Inout_ ID3D12CommandQueue* pQueue); + + void (D3DAPI* KickoffX)( + _Inout_ ID3D12CommandQueue* pQueue); + + void (D3DAPI* GetDesc)( + _Inout_ ID3D12CommandQueue* pQueue, + _Out_ D3D12_COMMAND_QUEUE_DESC* pDesc); + + HRESULT (D3DAPI* CopyPageMappingsX)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress, + _In_ UINT RangeCount, + _In_reads_(RangeCount) const D3D12XBOX_PAGE_MAPPING_RANGE* pRanges, + _In_ D3D12_GPU_VIRTUAL_ADDRESS SourcePagePoolAddress, + _In_ UINT SourcePagePoolPageCount, + _In_ D3D12XBOX_PAGE_MAPPING_FLAGS Flags); + + HRESULT (D3DAPI* ClearPageMappingsX)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress, + _In_ UINT PageCount, + _In_ D3D12XBOX_PAGE_MAPPING_FLAGS Flags); + + HRESULT (D3DAPI* CopyPageMappingsBatchX)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ UINT BatchCount, + _In_reads_(BatchCount) const D3D12XBOX_PAGE_MAPPING_BATCH* pBatches, + _In_ D3D12_GPU_VIRTUAL_ADDRESS SourcePagePoolAddress, + _In_ UINT SourcePagePoolPageCount, + _In_ D3D12XBOX_PAGE_MAPPING_FLAGS Flags); + + HRESULT (D3DAPI* PresentX)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_range_(0, D3D12XBOX_PRESENT_PLANES_MAX) UINT PlaneCount, + _In_reads_opt_(PlaneCount) const D3D12XBOX_PRESENT_PLANE_PARAMETERS* pPlaneParameters, + _In_opt_ const D3D12XBOX_PRESENT_PARAMETERS* pPresentParameters); + + HRESULT (D3DAPI* SetHDRToneMapperX)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_opt_ ID3D12Resource* pHDRToneMapper); + + HRESULT (D3DAPI* Signal2X)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ ID3D12Fence* pFence, + _In_ UINT64 Value, + _In_opt_ D3D12XBOX_SYNC_PARAMS* pSyncBottomOfPipeParams, + _In_opt_ D3D12XBOX_SYNC_PARAMS* pSyncTopOfPipeParams); + + void (D3DAPI* ExecuteCommandLists2X)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ UINT Count, + _In_reads_(Count) ID3D12CommandList* const* ppCommandLists, + _In_ D3D12XBOX_FRAME_PIPELINE_TOKEN Token, + _In_ D3D12XBOX_EXECUTE_COMMAND_LIST_FLAGS Flags); + + HRESULT (D3DAPI* EnableLiveDebuggingX)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_opt_ D3D12XBOX_LIVE_DEBUGGING_PARAMETERS* pDebugParams); + + HRESULT (D3DAPI* WaitX)( + _Inout_ ID3D12CommandQueue* pQueue, + _In_ ID3D12Fence* pFence, + _In_ UINT64 Value, + _In_opt_ D3D12XBOX_SYNC_PARAMS* pSyncTopOfPipeParams); +}; + + +} + +D3DINTERFACE(ID3D12CommandQueue, 0ec870a6,5d7e,4c22,8c,fc,5b,aa,e0,76,16,ed) : public ID3D12Pageable +{ +public: + + D3D12_COMMAND_LIST_TYPE m_Type; + +public: + + D3DINLINE D3D12CommandQueue_Function_Table* QueueFunction() + { + return (D3D12CommandQueue_Function_Table*)m_pFunction; + } + + D3DINLINE void D3DAPI UpdateTileMappings( + _In_ ID3D12Resource* pResource, + UINT NumResourceRegions, + _In_reads_opt_(NumResourceRegions) const D3D12_TILED_RESOURCE_COORDINATE* pResourceRegionStartCoordinates, + _In_reads_opt_(NumResourceRegions) const D3D12_TILE_REGION_SIZE* pResourceRegionSizes, + _In_opt_ ID3D12Heap* pHeap, + UINT NumRanges, + _In_reads_opt_(NumRanges) const D3D12_TILE_RANGE_FLAGS* pRangeFlags, + _In_reads_opt_(NumRanges) const UINT* pHeapRangeStartOffsets, + _In_reads_opt_(NumRanges) const UINT* pRangeTileCounts, + D3D12_TILE_MAPPING_FLAGS Flags) + { + QueueFunction()->UpdateTileMappings(this, + pResource, + NumResourceRegions, + pResourceRegionStartCoordinates, + pResourceRegionSizes, + pHeap, + NumRanges, + pRangeFlags, + pHeapRangeStartOffsets, + pRangeTileCounts, + Flags); + } + + D3DINLINE void D3DAPI CopyTileMappings( + _In_ ID3D12Resource* pDstResource, + _In_ const D3D12_TILED_RESOURCE_COORDINATE* pDstRegionStartCoordinate, + _In_ ID3D12Resource* pSrcResource, + _In_ const D3D12_TILED_RESOURCE_COORDINATE* pSrcRegionStartCoordinate, + _In_ const D3D12_TILE_REGION_SIZE* pRegionSize, + D3D12_TILE_MAPPING_FLAGS Flags) + { + QueueFunction()->CopyTileMappings(this, + pDstResource, + pDstRegionStartCoordinate, + pSrcResource, + pSrcRegionStartCoordinate, + pRegionSize, + Flags); + } + + D3DINLINE void D3DAPI ExecuteCommandLists( + _In_ UINT Count, + _In_reads_(Count) ID3D12CommandList* const* ppCommandLists) + { + QueueFunction()->ExecuteCommandLists(this, Count, ppCommandLists); + } + + D3DINLINE void D3DAPI SetMarker( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size) + { + QueueFunction()->SetMarker(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI BeginEvent( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void* pData, + UINT Size) + { + QueueFunction()->BeginEvent(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI EndEvent() + { + QueueFunction()->EndEvent(this); + } + + D3DINLINE void D3DAPI InsertGpuMarker( + UINT8 opcode, + _In_reads_bytes_(Size) const void* pData, + UINT Size) + { + QueueFunction()->InsertGpuMarker(this, opcode, pData, Size); + } + + D3DINLINE void D3DAPI InsertTimingMarker( + UINT8 opcode) + { + QueueFunction()->InsertTimingMarker(this, opcode); + } + + D3DINLINE HRESULT D3DAPI Signal( + ID3D12Fence* pFence, + UINT64 Value) + { + return QueueFunction()->Signal(this, pFence, Value); + } + + D3DINLINE HRESULT D3DAPI SignalX( + ID3D12Fence* pFence, + UINT64 Value, + D3D12XBOX_FLUSH FlushFlags) + { + return QueueFunction()->SignalX(this, pFence, Value, FlushFlags); + } + + D3DINLINE HRESULT D3DAPI Wait( + ID3D12Fence* pFence, + UINT64 Value) + { + return QueueFunction()->Wait(this, pFence, Value); + } + + D3DINLINE HRESULT D3DAPI GetTimestampFrequency( + _Out_ UINT64* pFrequency) + { + return QueueFunction()->GetTimestampFrequency(this, pFrequency); + } + + D3DINLINE HRESULT D3DAPI GetClockCalibration( + _Out_ UINT64* pGpuTimestamp, + _Out_ UINT64* pCpuTimestamp) + { + return QueueFunction()->GetClockCalibration(this, pGpuTimestamp, pCpuTimestamp); + } + + D3DINLINE D3D12_COMMAND_QUEUE_DESC GetDesc() + { + D3D12_COMMAND_QUEUE_DESC desc; + QueueFunction()->GetDesc(this, &desc); + return desc; + } + + D3DINLINE HRESULT D3DAPI PIXGpuCaptureNextFrame( + _In_ UINT Flags, + _In_z_ LPCWSTR lpOutputFileName) + { + return QueueFunction()->PIXGpuCaptureNextFrame(this, Flags, lpOutputFileName); + } + + D3DINLINE HRESULT D3DAPI PIXGpuBeginCapture( + _In_ UINT Flags, + _In_z_ LPCWSTR lpOutputFileName) + { + return QueueFunction()->PIXGpuBeginCapture(this, Flags, lpOutputFileName); + } + + D3DINLINE HRESULT D3DAPI PIXGpuEndCapture() + { + return QueueFunction()->PIXGpuEndCapture(this); + } + + D3DINLINE HRESULT D3DAPI SuspendX( + _In_ UINT Flags) + { + return QueueFunction()->SuspendX(this, Flags); + } + + D3DINLINE HRESULT D3DAPI ResumeX() + { + return QueueFunction()->ResumeX(this); + } + + D3DINLINE void D3DAPI InvalidateGraphicsTLBX() + { + return QueueFunction()->InvalidateGraphicsTLBX(this); + } + + D3DINLINE void D3DAPI KickoffX() + { + QueueFunction()->KickoffX(this); + } + + D3DINLINE HRESULT D3DAPI CopyPageMappingsX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress, + _In_ UINT RangeCount, + _In_reads_(RangeCount) const D3D12XBOX_PAGE_MAPPING_RANGE* pRanges, + _In_ D3D12_GPU_VIRTUAL_ADDRESS SourcePagePoolAddress, + _In_ UINT SourcePagePoolPageCount, + _In_ D3D12XBOX_PAGE_MAPPING_FLAGS Flags) + { + return QueueFunction()->CopyPageMappingsX( + this, + DestinationAddress, + RangeCount, + pRanges, + SourcePagePoolAddress, + SourcePagePoolPageCount, + Flags); + } + + D3DINLINE HRESULT D3DAPI ClearPageMappingsX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress, + _In_ UINT PageCount, + _In_ D3D12XBOX_PAGE_MAPPING_FLAGS Flags) + { + return QueueFunction()->ClearPageMappingsX( + this, + DestinationAddress, + PageCount, + Flags); + } + + D3DINLINE HRESULT D3DAPI CopyPageMappingsBatchX( + _In_ UINT BatchCount, + _In_reads_(BatchCount) const D3D12XBOX_PAGE_MAPPING_BATCH* pBatches, + _In_ D3D12_GPU_VIRTUAL_ADDRESS SourcePagePoolAddress, + _In_ UINT SourcePagePoolPageCount, + _In_ D3D12XBOX_PAGE_MAPPING_FLAGS Flags) + { + return QueueFunction()->CopyPageMappingsBatchX( + this, + BatchCount, + pBatches, + SourcePagePoolAddress, + SourcePagePoolPageCount, + Flags); + } + + D3DINLINE HRESULT D3DAPI PresentX( + _In_range_(0, D3D12XBOX_PRESENT_PLANES_MAX) UINT PlaneCount, + _In_reads_opt_(PlaneCount) const D3D12XBOX_PRESENT_PLANE_PARAMETERS* pPlaneParameters, + _In_opt_ const D3D12XBOX_PRESENT_PARAMETERS* pPresentParameters) + { + return QueueFunction()->PresentX( + this, + PlaneCount, + pPlaneParameters, + pPresentParameters); + } + + D3DINLINE HRESULT D3DAPI SetHDRToneMapperX( + _In_opt_ ID3D12Resource* pHDRToneMapper) + { + return QueueFunction()->SetHDRToneMapperX( + this, + pHDRToneMapper); + } + + D3DINLINE HRESULT D3DAPI Signal2X( + _In_ ID3D12Fence* pFence, + _In_ UINT64 Value, + _In_opt_ D3D12XBOX_SYNC_PARAMS* pSyncBottomOfPipeParams, + _In_opt_ D3D12XBOX_SYNC_PARAMS* pSyncTopOfPipeParams) + { + return QueueFunction()->Signal2X(this, pFence, Value, pSyncBottomOfPipeParams, pSyncTopOfPipeParams); + } + + D3DINLINE void D3DAPI ExecuteCommandLists2X( + _In_ UINT Count, + _In_reads_(Count) ID3D12CommandList* const* ppCommandLists, + _In_ D3D12XBOX_FRAME_PIPELINE_TOKEN Token, + _In_ D3D12XBOX_EXECUTE_COMMAND_LIST_FLAGS Flags) + { + QueueFunction()->ExecuteCommandLists2X(this, Count, ppCommandLists, Token, Flags); + } + + D3DINLINE HRESULT D3DAPI EnableLiveDebuggingX( + _In_opt_ D3D12XBOX_LIVE_DEBUGGING_PARAMETERS* pDebugParams) + { + return QueueFunction()->EnableLiveDebuggingX(this, pDebugParams); + } + + D3DINLINE HRESULT D3DAPI WaitX( + _In_ ID3D12Fence* pFence, + _In_ UINT64 Value, + _In_opt_ D3D12XBOX_SYNC_PARAMS* pSyncTopOfPipeParams) + { + return QueueFunction()->WaitX(this, pFence, Value, pSyncTopOfPipeParams); + } +}; + + +extern "C" +{ + +typedef enum D3D12_MULTIPLE_FENCE_WAIT_FLAGS +{ + D3D12_MULTIPLE_FENCE_WAIT_FLAG_NONE = 0, + D3D12_MULTIPLE_FENCE_WAIT_FLAG_ANY = 0x1, + D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL = 0 +} D3D12_MULTIPLE_FENCE_WAIT_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_MULTIPLE_FENCE_WAIT_FLAGS ); + +typedef enum D3D12_RESIDENCY_PRIORITY +{ + D3D12_RESIDENCY_PRIORITY_MINIMUM = 0x28000000, + D3D12_RESIDENCY_PRIORITY_LOW = 0x50000000, + D3D12_RESIDENCY_PRIORITY_NORMAL = 0x78000000, + D3D12_RESIDENCY_PRIORITY_HIGH = 0xa0010000, + D3D12_RESIDENCY_PRIORITY_MAXIMUM = 0xc8000000 +} D3D12_RESIDENCY_PRIORITY; + +typedef enum D3D12_RESIDENCY_FLAGS +{ + D3D12_RESIDENCY_FLAG_NONE = 0, + D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET = 0x1, +} D3D12_RESIDENCY_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_RESIDENCY_FLAGS ); + +typedef enum D3D12_COMMAND_LIST_FLAGS +{ + D3D12_COMMAND_LIST_FLAG_NONE = 0 +} D3D12_COMMAND_LIST_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_COMMAND_LIST_FLAGS ); + + +typedef enum D3D12_COMMAND_POOL_FLAGS +{ + D3D12_COMMAND_POOL_FLAG_NONE = 0, +} D3D12_COMMAND_POOL_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_COMMAND_POOL_FLAGS ); + +typedef enum D3D12_COMMAND_RECORDER_FLAGS +{ + D3D12_COMMAND_RECORDER_FLAG_NONE = 0, +} D3D12_COMMAND_RECORDER_FLAGS; + +DEFINE_ENUM_FLAG_OPERATORS( D3D12_COMMAND_RECORDER_FLAGS ); + +typedef enum D3D12_PROTECTED_SESSION_STATUS +{ + D3D12_PROTECTED_SESSION_STATUS_OK = 0, + D3D12_PROTECTED_SESSION_STATUS_INVALID = 1, +} D3D12_PROTECTED_SESSION_STATUS; + +} + +extern "C" +{ + + +// +// ID3D12Device +// + +struct D3D12Device_Function_Table +{ + D3D12Object_Function_Table ObjectFunction; + + UINT (D3DAPI* GetNodeCount)( + _Inout_ ID3D12Device* pDevice); + + HRESULT (D3DAPI* CreateCommandQueue)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_COMMAND_QUEUE_DESC* pDesc, + REFIID riid, + _Outptr_ void** ppCommandQueue); + + HRESULT (D3DAPI* CreateCommandAllocator)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12_COMMAND_LIST_TYPE type, + REFIID riid, + _Outptr_ void** ppCommandAllocator); + + HRESULT (D3DAPI* CreateGraphicsPipelineState)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_GRAPHICS_PIPELINE_STATE_DESC* pDesc, + REFIID riid, + _Outptr_ void** ppPipelineState); + + HRESULT (D3DAPI* CreateComputePipelineState)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_COMPUTE_PIPELINE_STATE_DESC* pDesc, + REFIID riid, + _Outptr_ void** ppPipelineState); + + HRESULT (D3DAPI* CreateCommandList)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT nodeMask, + _In_ D3D12_COMMAND_LIST_TYPE type, + _In_ ID3D12CommandAllocator* pCommandAllocator, + _In_opt_ ID3D12PipelineState* pInitialState, + REFIID riid, + _Outptr_ void** ppCommandList); + + HRESULT (D3DAPI* CheckFeatureSupport)( + _Inout_ ID3D12Device* pDevice, + D3D12_FEATURE Feature, + _Inout_updates_bytes_(FeatureSupportDataSize) void* pFeatureSupportData, + UINT FeatureSupportDataSize); + + HRESULT (D3DAPI* CreateDescriptorHeap)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_DESCRIPTOR_HEAP_DESC* pDescriptorHeapDesc, + REFIID riid, + _Outptr_ void** ppvHeap); + + UINT (D3DAPI* GetDescriptorHandleIncrementSize)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapType); + + HRESULT (D3DAPI* CreateRootSignature)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT nodeMask, + _In_reads_(BlobLengthInBytes) const void* pBlobWithRootSignature, + _In_ SIZE_T BlobLengthInBytes, + REFIID riid, + _Outptr_ void** ppvRootSignature); + + void (D3DAPI* CreateConstantBufferView)( + _Inout_ ID3D12Device* pDevice, + _In_opt_ const D3D12_CONSTANT_BUFFER_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + void (D3DAPI* CreateShaderResourceView)( + _Inout_ ID3D12Device* pDevice, + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12_SHADER_RESOURCE_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + void (D3DAPI* CreateUnorderedAccessView)( + _Inout_ ID3D12Device* pDevice, + _In_opt_ ID3D12Resource* pResource, + _In_opt_ ID3D12Resource* pCounterResource, + _In_opt_ const D3D12_UNORDERED_ACCESS_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + void (D3DAPI* CreateRenderTargetView)( + _Inout_ ID3D12Device* pDevice, + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12_RENDER_TARGET_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + void (D3DAPI* CreateDepthStencilView)( + _Inout_ ID3D12Device* pDevice, + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12_DEPTH_STENCIL_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + void (D3DAPI* CreateSampler)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_SAMPLER_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + void (D3DAPI* CopyDescriptors)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT NumDestDescriptorRanges, + _In_reads_(NumDestDescriptorRanges) const D3D12_CPU_DESCRIPTOR_HANDLE* pDestDescriptorRangeStarts, + _In_reads_opt_(NumDestDescriptorRanges) const UINT* pDestDescriptorRangeSizes, + _In_ UINT NumSrcDescriptorRanges, + _In_reads_(NumSrcDescriptorRanges) const D3D12_CPU_DESCRIPTOR_HANDLE* pSrcDescriptorRangeStarts, + _In_reads_opt_(NumSrcDescriptorRanges) const UINT* pSrcDescriptorRangeSizes, + _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapsType); + + void (D3DAPI* CopyDescriptorsSimple)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT NumDescriptors, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptorRangeStart, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE SrcDescriptorRangeStart, + _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapsType); + + D3D12_RESOURCE_ALLOCATION_INFO (D3DAPI* GetResourceAllocationInfo)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT VisibleMask, + _In_ UINT NumResourceDescs, + _In_reads_(NumResourceDescs) const D3D12_RESOURCE_DESC* pRDescs); + + D3D12_HEAP_PROPERTIES (D3DAPI* GetCustomHeapProperties)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT nodeMask, + D3D12_HEAP_TYPE HeapType); + + HRESULT (D3DAPI* CreateCommittedResource)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12_RESOURCE_DESC* pResourceDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riidResource, + _Outptr_opt_ void** ppvResource); + + HRESULT (D3DAPI* CreateHeap)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_HEAP_DESC* pDesc, + REFIID riid, + _Outptr_opt_ void** ppvHeap); + + HRESULT (D3DAPI* CreatePlacedResource)( + _Inout_ ID3D12Device* pDevice, + _In_ ID3D12Heap* pHeap, + UINT64 HeapOffset, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + HRESULT (D3DAPI* CreateReservedResource)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + HRESULT (D3DAPI* CreateSharedHandle)( + _Inout_ ID3D12Device* pDevice, + _In_ ID3D12DeviceChild* pObject, + _In_opt_ const SECURITY_ATTRIBUTES* pAttributes, + DWORD Access, + _In_opt_ LPCWSTR Name, + _Out_ HANDLE* pHandle); + + HRESULT (D3DAPI* OpenSharedHandle)( + _Inout_ ID3D12Device* pDevice, + _In_ HANDLE NTHandle, + REFIID riid, + _Out_opt_ void** ppvObj); + + HRESULT (D3DAPI* OpenSharedHandleByName)( + _Inout_ ID3D12Device* pDevice, + _In_ LPCWSTR Name, + DWORD Access, + _Out_ HANDLE* pNTHandle); + + HRESULT (D3DAPI* MakeResident)( + _Inout_ ID3D12Device* pDevice, + UINT NumObjects, + _In_reads_(NumObjects) ID3D12Pageable* const* ppObjects); + + HRESULT (D3DAPI* Evict)( + _Inout_ ID3D12Device* pDevice, + UINT NumObjects, + _In_reads_(NumObjects) ID3D12Pageable* const* ppObjects); + + HRESULT (D3DAPI* CreateFence)( + _Inout_ ID3D12Device* pDevice, + UINT64 InitialValue, + D3D12_FENCE_FLAGS Flags, + REFIID riid, + _Outptr_ void** ppFence); + + HRESULT (D3DAPI* GetDeviceRemovedReason)( + _Inout_ ID3D12Device* pDevice); + + void (D3DAPI* GetCopyableFootprints)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_RESOURCE_DESC* pResourceDesc, + _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0,D3D12_REQ_SUBRESOURCES - FirstSubresource) UINT NumSubresources, + UINT64 BaseOffset, + _Out_writes_opt_(NumSubresources) D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts, + _Out_writes_opt_(NumSubresources) UINT* pNumRows, + _Out_writes_opt_(NumSubresources) UINT64* pRowSizeInBytes, + _Out_opt_ UINT64* pTotalBytes); + + HRESULT (D3DAPI* CreateQueryHeap)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_QUERY_HEAP_DESC* pDesc, + REFIID riid, // Expected: ID3D12QueryHeap + _Outptr_opt_ void** ppvHeap + ); + + HRESULT (D3DAPI* SetStablePowerState)( + _Inout_ ID3D12Device* pDevice, + BOOL Enable); + + HRESULT (D3DAPI* CreateCommandSignature)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_COMMAND_SIGNATURE_DESC* pDesc, + _In_opt_ ID3D12RootSignature* pRootSignature, + REFIID riid, + _Outptr_opt_ void** ppvCommandSignature); + + void (D3DAPI* GetResourceTiling)( + _Inout_ ID3D12Device* pDevice, + _In_ ID3D12Resource* pTiledResource, + _Out_opt_ UINT* pNumTilesForEntireResource, + _Out_opt_ D3D12_PACKED_MIP_INFO* pPackedMipDesc, + _Out_opt_ D3D12_TILE_SHAPE* pStandardTileShapeForNonPackedMips, + _Inout_opt_ UINT* pNumSubresourceTilings, + _In_ UINT FirstSubresourceTilingToGet, + _Out_writes_(*pNumSubresourceTilings) D3D12_SUBRESOURCE_TILING* pSubresourceTilingsForNonPackedMips); + + LUID (D3DAPI* GetAdapterLuid)( + _Inout_ ID3D12Device* pDevice); + + HRESULT (D3DAPI* CreatePlacedResourceX)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12_GPU_VIRTUAL_ADDRESS ResourceLocation, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + HRESULT (D3DAPI* CreateComponentPlacedResourceX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12XBOX_COMPONENT_PLACED_ADDRESSES* pComponentLocations, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + void (D3DAPI* CreatePlacedShaderResourceViewX)( + _Inout_ ID3D12Device* pDevice, + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12XBOX_SHADER_RESOURCE_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + void (D3DAPI* CreatePlacedUnorderedAccessViewX)( + _Inout_ ID3D12Device* pDevice, + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12XBOX_UNORDERED_ACCESS_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + HRESULT (D3DAPI* CreateCommandQueueX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12XBOX_COMMAND_QUEUE_DESC* pDesc, + REFIID riid, + _Outptr_ void** ppCommandQueue); + + UINT64 (D3DAPI* SetDriverHintX)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT64 Feature, + _In_ UINT64 Value); + + void (D3DAPI* SetHangCallbacksX)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12XBOX_HANGBEGINCALLBACK pBeginCallback, + _In_ D3D12XBOX_HANGPRINTCALLBACK pPrintCallback, + _In_ D3D12XBOX_HANGDUMPCALLBACK pDumpCallback); + + void (D3DAPI* ReportGpuHangX)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12XBOX_REPORT_GPU_HANG_FLAGS Flags); + + void (D3DAPI* SetDebugFlagsX)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12XBOX_DEBUG_FLAGS Flags); + + D3D12XBOX_DEBUG_FLAGS (D3DAPI* GetDebugFlagsX)( + _Inout_ ID3D12Device* pDevice); + + void (D3DAPI* SetDebugCallbackX)( + _Inout_ ID3D12Device* pDevice, + _In_opt_ D3D12XBOX_DEBUG_CALLBACK pCallback, + _In_opt_ void* pUserContext); + + HRESULT (D3DAPI* CreateDerivedGraphicsPipelineStateX)( + _Inout_ ID3D12Device* pDevice, + _In_ ID3D12PipelineState* pSrcPipelineState, + _In_ UINT NumDescs, + _In_ const D3D12XBOX_DERIVED_GRAPHICS_STATE_DESC* pDescs, + _In_ REFIID riid, + _Outptr_ void** ppDerivedPipelineState); + + HRESULT (D3DAPI* SerializeGraphicsPipelineStateX)( + _Inout_ ID3D12Device* pDevice, + _In_ ID3D12PipelineState* pPipelineState, + _In_ UINT Flags, + _Out_ D3D12XBOX_SERIALIZE_GRAPHICS_PIPELINE_STATE* pSerializeState); + + HRESULT (D3DAPI* DeserializeGraphicsPipelineStateX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12XBOX_DESERIALIZE_GRAPHICS_PIPELINE_STATE* pDeserializeState, + _In_ REFIID riid, + _Outptr_ void** ppPipelineState); + + void (D3DAPI* EnableManualGraphicsTLBInvalidationX)( + _Inout_ ID3D12Device* pDevice, + _In_ BOOL Enabled); + + HRESULT (D3DAPI* GetDefaultMSAAParametersX)( + _Inout_ ID3D12Device* pDevice, + _In_ const DXGI_SAMPLE_DESC* pSampleDesc, + _Inout_opt_ D3D12XBOX_MSAA_SAMPLE_LOCATIONS* pSampleLocations, + _Inout_opt_ D3D12XBOX_MSAA_CENTROID_PRIORITIES* pCentroidPriorities, + _Inout_opt_ D3D12XBOX_MSAA_PARAMETERS* pMSAAParameters); + + HRESULT (D3DAPI* CreateGraphicsPipelineStateX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_GRAPHICS_PIPELINE_STATE_DESC* pBaseDesc, + _In_ UINT NumExtendedDescs, + _In_ const D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_DESC* pExtendedDescs, + _In_ REFIID riid, + _Outptr_ void** ppPipelineState); + + void (D3DAPI* CreateSamplerX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12XBOX_SAMPLER_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + HRESULT (D3DAPI* CreateComputePipelineStateX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_COMPUTE_PIPELINE_STATE_DESC* pBaseDesc, + _In_ UINT NumExtendedDescs, + _In_ const D3D12XBOX_EXTENDED_COMPUTE_PIPELINE_STATE_DESC* pExtendedDescs, + REFIID riid, + _Outptr_ void** ppPipelineState); + + HRESULT (D3DAPI* CreateDerivedComputePipelineStateX)( + _Inout_ ID3D12Device* pDevice, + _In_ ID3D12PipelineState* pSrcPipelineState, + _In_ UINT NumDescs, + _In_ const D3D12XBOX_DERIVED_COMPUTE_STATE_DESC* pDescs, + _In_ REFIID riid, + _Outptr_ void** ppDerivedPipelineState); + + UINT32 (D3DAPI* RegisterCustomFenceLocationX)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12_GPU_VIRTUAL_ADDRESS FenceGpuAddress, + _In_z_ LPCWSTR pName); + + void (D3DAPI* UnregisterCustomFenceLocationX)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT32 Handle); + + HRESULT (D3DAPI* SerializeComputePipelineStateX)( + _Inout_ ID3D12Device* pDevice, + _In_ ID3D12PipelineState* pPipelineState, + _In_ UINT Flags, + _Out_ D3D12XBOX_SERIALIZE_COMPUTE_PIPELINE_STATE* pSerializeState); + + HRESULT (D3DAPI* DeserializeComputePipelineStateX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12XBOX_DESERIALIZE_COMPUTE_PIPELINE_STATE* pDeserializeState, + _In_ REFIID riid, + _Outptr_ void** ppPipelineState); + + void (D3DAPI* GetGpuHardwareConfigurationX)( + _Inout_ ID3D12Device* pDevice, + _Out_ D3D12XBOX_GPU_HARDWARE_CONFIGURATION* pGpuHardwareConfiguration); + + HRESULT (D3DAPI* SetDebugErrorFilterX)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT ErrorIdentifier, + _In_ D3D12XBOX_DEBUG_FILTER_FLAGS FilterFlags); + + void (D3DAPI* CreatePlacedRawShaderResourceViewX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_RESOURCE_DESC* pResourceDesc, + _In_ const D3D12XBOX_SHADER_RESOURCE_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + void (D3DAPI* CreatePlacedRawUnorderedAccessViewX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_RESOURCE_DESC* pResourceDesc, + _In_ const D3D12XBOX_UNORDERED_ACCESS_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + HRESULT (D3DAPI* SetGpuMemoryPriorityX)( + _Inout_ ID3D12Device* pDevice, + _In_ UINT Priority); + + HRESULT (D3DAPI* CreateCommandListX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12XBOX_COMMAND_LIST_DESC* pDesc, + _In_ ID3D12CommandAllocator* pCommandAllocator, + _In_opt_ ID3D12PipelineState* pInitialState, + REFIID riid, + _Outptr_ void** ppCommandList); + + HRESULT (D3DAPI* RegisterPagePoolX)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12_GPU_VIRTUAL_ADDRESS PagePoolAddress, + _In_ UINT PagePoolPageCount, + _Out_ HANDLE* pPagePoolHandle); + + HRESULT (D3DAPI* UnregisterPagePoolX)( + _Inout_ ID3D12Device* pDevice, + _In_ HANDLE PagePoolHandle); + + HRESULT (D3DAPI* CreateCommittedResourceX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12XBOX_RESOURCE_DESC* pResourceDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riidResource, + _Outptr_opt_ void** ppvResource); + + HRESULT (D3DAPI* CreateComponentPlacedResourceX1)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12XBOX_COMPONENT_PLACED_ADDRESSES* pComponentLocations, + _In_ const D3D12XBOX_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + HRESULT (D3DAPI* SetFrameIntervalX)( + _Inout_ ID3D12Device* pDevice, + _In_opt_ IDXGIOutput* pOutputSyncTarget, + _In_ UINT LengthInMicroseconds, + _In_ UINT PeriodInIntervals, + _In_ D3D12XBOX_FRAME_INTERVAL_FLAGS Flags); + + HRESULT (D3DAPI* ScheduleFrameEventX)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12XBOX_FRAME_EVENT_TYPE Type, + _In_ UINT IntervalOffsetInMicroseconds, + _In_opt_ D3D12XBOX_SCHEDULE_FRAME_OBJECT_LIST* pAncillarySignalList, + _In_ D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAGS Flags); + + HRESULT (D3DAPI* WaitFrameEventX)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12XBOX_FRAME_EVENT_TYPE Type, + _In_ UINT TimeOutInMs, + _In_opt_ D3D12XBOX_WAIT_FRAME_OBJECT_LIST* pAncillaryWaitList, + _In_ D3D12XBOX_WAIT_FRAME_EVENT_FLAGS Flags, + _Inout_ D3D12XBOX_FRAME_PIPELINE_TOKEN* pToken); + + HRESULT (D3DAPI* GetFrameStatisticsX)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12XBOX_FRAME_PIPELINE_TOKEN Token, + _In_ D3D12XBOX_FRAME_STATISTICS_TYPE TypeSet, + _Inout_ UINT* pCount, + _Out_ D3D12XBOX_FRAME_STATISTICS* pStatistics); + + HRESULT (D3DAPI* CreateCounterSetX)( + _Inout_ ID3D12Device* pDevice, + _In_ const D3D12XBOX_COUNTER_SET_DESC* pCounterSetDesc, + REFIID riid, + _Outptr_opt_ void** ppCounterSet); +}; + + + +} + +D3DINTERFACE(ID3D12Device, 189819f1,1db6,4b57,be,54,18,21,33,9b,85,f7) : public ID3D12Object +{ +public: + + // ID3D12Device APIs that are ordinarily inlined should call out of line: + static const UINT8 OutOfLineFlags_Common = 0x1; + +public: + + UINT64 m_NullConstantBufferAddress; + + union + { + struct + { + // These flags dictate when D3D needs to call into the run-time instead of using + // the inline API implementation. This is done to support run-time switching between + // retail/instrumented and validated versions of D3D. For ultimate performance + // compile with the #define D3DCOMPILE_NO_DEBUG set to 1 before including this header + // file - but beware that this will disable some validation and parameter checking + // code. + UINT8 m_OutOfLineFlags; + }; + + // Space for future growth so that not all callers have to be recompiled if a new + // field is added. + UINT32 m_Reserved[16]; + }; + + +public: + + D3DINLINE D3D12Device_Function_Table* DeviceFunction() + { + return (D3D12Device_Function_Table*)m_pFunction; + } + + // Decide at compile-time if possible, or run-time if necessary, whether the inline + // code should be used, or whether it's necessary to call out-of-line into the D3D run-time: + D3DINLINE bool DoInline() + { + #if D3DCOMPILE_NO_DEBUG + // We know at compile time to always take the inline path: + return true; + #else + // We only know at run-time whether we can use the inline path: + return !m_OutOfLineFlags; + #endif + } + + // Get the storage size in Owords of a descriptor from the given heap type. The + // DescriptorHeapType should ideally be passed as a literal to completely eliminate + // the overhead of the retrieval: + D3DINLINE UINT GetDescriptorSizeInOwordsFromHeapType(D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapType) + { + UINT descriptorSizeInOwords; + + if (DescriptorHeapType == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + { + descriptorSizeInOwords = D3D12XBOX_DESCRIPTOR_SHADER_RESOURCE_VIEW_SIZE_IN_OWORDS; + } + else if (DescriptorHeapType == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER || + DescriptorHeapType == D3D12XBOX_DESCRIPTOR_HEAP_TYPE_SAMPLER_UNBOUNDED) + { + descriptorSizeInOwords = D3D12XBOX_DESCRIPTOR_SAMPLER_STATE_SIZE_IN_OWORDS; + } + else if (DescriptorHeapType == D3D12_DESCRIPTOR_HEAP_TYPE_RTV) + { + descriptorSizeInOwords = D3D12XBOX_DESCRIPTOR_RENDER_TARGET_VIEW_SIZE_IN_OWORDS; + } + else // D3D12_DESCRIPTOR_HEAP_TYPE_DSV + { + descriptorSizeInOwords = D3D12XBOX_DESCRIPTOR_DEPTH_STENCIL_VIEW_SIZE_IN_OWORDS; + } + + return descriptorSizeInOwords; + } + + D3DINLINE UINT D3DAPI GetNodeCount() + { + return DeviceFunction()->GetNodeCount(this); + } + + D3DINLINE HRESULT D3DAPI CreateCommandQueue( + _In_ const D3D12_COMMAND_QUEUE_DESC* pDesc, + _In_ REFIID riid, + _Outptr_ void** ppCommandQueue) + { + return DeviceFunction()->CreateCommandQueue(this, pDesc, riid, ppCommandQueue); + } + + D3DINLINE HRESULT D3DAPI CreateCommandAllocator( + _In_ D3D12_COMMAND_LIST_TYPE type, + _In_ REFIID riid, + _Outptr_ void** ppCommandAllocator) + { + return DeviceFunction()->CreateCommandAllocator(this, type, riid, ppCommandAllocator); + } + + D3DINLINE HRESULT D3DAPI CreateGraphicsPipelineState( + _In_ const D3D12_GRAPHICS_PIPELINE_STATE_DESC* pDesc, + _In_ REFIID riid, + _Outptr_ void** ppPipelineState) + { + return DeviceFunction()->CreateGraphicsPipelineState(this, pDesc, riid, ppPipelineState); + } + + D3DINLINE HRESULT D3DAPI CreateComputePipelineState( + _In_ const D3D12_COMPUTE_PIPELINE_STATE_DESC* pDesc, + _In_ REFIID riid, + _Outptr_ void** ppPipelineState) + { + return DeviceFunction()->CreateComputePipelineStateX(this, pDesc, 0, nullptr, riid, ppPipelineState); + } + + D3DINLINE HRESULT D3DAPI CreateCommandList( + _In_ UINT nodeMask, + _In_ D3D12_COMMAND_LIST_TYPE type, + _In_ ID3D12CommandAllocator* pCommandAllocator, + _In_opt_ ID3D12PipelineState* pInitialState, + REFIID riid, + _Outptr_ void** ppCommandList) + { + D3D12XBOX_COMMAND_LIST_DESC desc; + desc.Type = type; + desc.NodeMask = nodeMask; + desc.ResourceBarrierBatchSize = 0; + desc.Flags = D3D12XBOX_COMMAND_LIST_FLAG_NONE; + return DeviceFunction()->CreateCommandListX(this, &desc, pCommandAllocator, pInitialState, riid, ppCommandList); + } + + D3DINLINE HRESULT D3DAPI CreateCommandListX( + _In_ const D3D12XBOX_COMMAND_LIST_DESC* pDesc, + _In_ ID3D12CommandAllocator* pCommandAllocator, + _In_opt_ ID3D12PipelineState* pInitialState, + REFIID riid, + _Outptr_ void** ppCommandList) + { + return DeviceFunction()->CreateCommandListX(this, pDesc, pCommandAllocator, pInitialState, riid, ppCommandList); + } + + D3DINLINE HRESULT D3DAPI CheckFeatureSupport( + D3D12_FEATURE Feature, + _Inout_updates_bytes_(FeatureSupportDataSize) void* pFeatureSupportData, + UINT FeatureSupportDataSize) + { + return DeviceFunction()->CheckFeatureSupport(this, Feature, pFeatureSupportData, FeatureSupportDataSize); + } + + D3DINLINE HRESULT D3DAPI CreateDescriptorHeap( + _In_ const D3D12_DESCRIPTOR_HEAP_DESC* pDescriptorHeapDesc, + REFIID riid, + _Outptr_ void** ppvHeap) + { + return DeviceFunction()->CreateDescriptorHeap(this, pDescriptorHeapDesc, riid, ppvHeap); + } + + D3DINLINE UINT D3DAPI GetDescriptorHandleIncrementSize( + _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapType) + { + return DeviceFunction()->GetDescriptorHandleIncrementSize(this, DescriptorHeapType); + } + + D3DINLINE HRESULT D3DAPI CreateRootSignature( + _In_ UINT nodeMask, + _In_reads_(BlobLengthInBytes) const void* pBlobWithRootSignature, + _In_ SIZE_T BlobLengthInBytes, + REFIID riid, + _Outptr_ void** ppvRootSignature) + { + return DeviceFunction()->CreateRootSignature(this, + nodeMask, + pBlobWithRootSignature, + BlobLengthInBytes, + riid, + ppvRootSignature); + } + + D3DINLINE void D3DAPI CreateConstantBufferView( + _In_opt_ const D3D12_CONSTANT_BUFFER_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + if (DoInline()) + { + UINT64* pDescriptor = (UINT64*)D3D12XboxGetWritePointer(DestDescriptor); + + if (pDesc != nullptr) + { + pDescriptor[0] = pDesc->BufferLocation + D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_NATIVE_STRIDE; + pDescriptor[1] = (UINT64)((pDesc->SizeInBytes + 15ull) >> 4) + D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_NATIVE_FORMAT; + } + else + { + pDescriptor[0] = m_NullConstantBufferAddress + D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_NATIVE_STRIDE; + pDescriptor[1] = 1ull + D3D12XBOX_DESCRIPTOR_CONSTANT_BUFFER_VIEW_NATIVE_FORMAT; + } + } + else + { + DeviceFunction()->CreateConstantBufferView(this, pDesc, DestDescriptor); + } + } + + D3DINLINE void D3DAPI CreateShaderResourceView( + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12_SHADER_RESOURCE_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreateShaderResourceView(this, pResource, pDesc, DestDescriptor); + } + + D3DINLINE void D3DAPI CreateUnorderedAccessView( + _In_opt_ ID3D12Resource* pResource, + _In_opt_ ID3D12Resource* pCounterResource, + _In_opt_ const D3D12_UNORDERED_ACCESS_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreateUnorderedAccessView(this, + pResource, + pCounterResource, + pDesc, + DestDescriptor); + } + + D3DINLINE void D3DAPI CreateRenderTargetView( + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12_RENDER_TARGET_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreateRenderTargetView(this, pResource, pDesc, DestDescriptor); + } + + D3DINLINE void D3DAPI CreateDepthStencilView( + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12_DEPTH_STENCIL_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreateDepthStencilView(this, pResource, pDesc, DestDescriptor); + } + + D3DINLINE void D3DAPI CreateSampler( + _In_ const D3D12_SAMPLER_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreateSampler(this, pDesc, DestDescriptor); + } + + D3DINLINE void D3DAPI CreateSamplerX( + _In_ const D3D12XBOX_SAMPLER_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreateSamplerX(this, pDesc, DestDescriptor); + } + + D3DINLINE void D3DAPI CopyDescriptors( + _In_ UINT NumDestDescriptorRanges, + _In_reads_(NumDestDescriptorRanges) const D3D12_CPU_DESCRIPTOR_HANDLE* pDestDescriptorRangeStarts, + _In_reads_opt_(NumDestDescriptorRanges) const UINT* pDestDescriptorRangeSizes, + _In_ UINT NumSrcDescriptorRanges, + _In_reads_(NumSrcDescriptorRanges) const D3D12_CPU_DESCRIPTOR_HANDLE* pSrcDescriptorRangeStarts, + _In_reads_opt_(NumSrcDescriptorRanges) const UINT* pSrcDescriptorRangeSizes, + _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapsType) + { + DeviceFunction()->CopyDescriptors(this, + NumDestDescriptorRanges, + pDestDescriptorRangeStarts, + pDestDescriptorRangeSizes, + NumSrcDescriptorRanges, + pSrcDescriptorRangeStarts, + pSrcDescriptorRangeSizes, + DescriptorHeapsType); + } + + D3DINLINE void D3DAPI CopyDescriptorsSimple( + _In_ UINT NumDescriptors, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptorRangeStart, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE SrcDescriptorRangeStart, + _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapsType) + { + if (DoInline() && + DescriptorHeapsType != D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) + { + UINT descriptorSizeInOwords = GetDescriptorSizeInOwordsFromHeapType(DescriptorHeapsType); + + const __m128i* pSrc = (const __m128i*)D3D12XboxGetCachedReadPointer(SrcDescriptorRangeStart); + __m128i* pDst = (__m128i*)D3D12XboxGetWritePointer(DestDescriptorRangeStart); + UINT numOwords = NumDescriptors * descriptorSizeInOwords; + + do { + _mm_storeu_si128(pDst, _mm_loadu_si128(pSrc)); + ++pDst; + ++pSrc; + --numOwords; + } while (numOwords); + } + else + { + DeviceFunction()->CopyDescriptorsSimple(this, + NumDescriptors, + DestDescriptorRangeStart, + SrcDescriptorRangeStart, + DescriptorHeapsType); + } + } + + D3DINLINE D3D12_RESOURCE_ALLOCATION_INFO D3DAPI GetResourceAllocationInfo( + _In_ UINT visibleMask, + UINT NumResourceDescs, + _In_reads_(NumResourceDescs) const D3D12_RESOURCE_DESC* pRDescs) + { + return DeviceFunction()->GetResourceAllocationInfo(this, visibleMask, NumResourceDescs, pRDescs); + } + + D3DINLINE D3D12_HEAP_PROPERTIES D3DAPI GetCustomHeapProperties( + _In_ UINT nodeMask, + D3D12_HEAP_TYPE HeapType) + { + return DeviceFunction()->GetCustomHeapProperties(this, nodeMask, HeapType); + } + + D3DINLINE HRESULT D3DAPI CreateCommittedResource( + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12_RESOURCE_DESC* pResourceDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riidResource, + _Outptr_opt_ void** ppvResource) + { + return DeviceFunction()->CreateCommittedResource(this, + pHeapProperties, + HeapFlags, + pResourceDesc, + InitialState, + pOptimizedClearValue, + riidResource, + ppvResource); + } + + D3DINLINE HRESULT D3DAPI CreateHeap( + _In_ const D3D12_HEAP_DESC* pDesc, + REFIID riid, + _Outptr_opt_ void** ppvHeap) + { + return DeviceFunction()->CreateHeap(this, pDesc, riid, ppvHeap); + } + + D3DINLINE HRESULT D3DAPI CreatePlacedResource( + _In_ ID3D12Heap* pHeap, + UINT64 HeapOffset, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource) + { + return DeviceFunction()->CreatePlacedResource(this, + pHeap, + HeapOffset, + pDesc, + InitialState, + pOptimizedClearValue, + riid, + ppvResource); + } + + D3DINLINE HRESULT D3DAPI CreateReservedResource( + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource) + { + return DeviceFunction()->CreateReservedResource(this, + pDesc, + InitialState, + pOptimizedClearValue, + riid, + ppvResource); + } + + D3DINLINE HRESULT D3DAPI CreateSharedHandle( + _In_ ID3D12DeviceChild* pObject, + _In_opt_ const SECURITY_ATTRIBUTES* pAttributes, + DWORD Access, + _In_opt_ LPCWSTR Name, + _Out_ HANDLE* pHandle) + { + return DeviceFunction()->CreateSharedHandle(this, + pObject, + pAttributes, + Access, + Name, + pHandle); + } + + D3DINLINE HRESULT D3DAPI OpenSharedHandle( + _In_ HANDLE NTHandle, + REFIID riid, + _Out_opt_ void** ppvObj) + { + return DeviceFunction()->OpenSharedHandle(this, + NTHandle, + riid, + ppvObj); + } + + D3DINLINE HRESULT D3DAPI OpenSharedHandleByName( + _In_ LPCWSTR Name, + DWORD Access, + _Out_ HANDLE* pNTHandle) + { + return DeviceFunction()->OpenSharedHandleByName(this, + Name, + Access, + pNTHandle); + } + + D3DINLINE HRESULT D3DAPI MakeResident( + UINT NumObjects, + _In_reads_(NumObjects) ID3D12Pageable* const* ppObjects) + { + return DeviceFunction()->MakeResident(this, NumObjects, ppObjects); + } + + D3DINLINE HRESULT D3DAPI Evict( + UINT NumObjects, + _In_reads_(NumObjects) ID3D12Pageable* const* ppObjects) + { + return DeviceFunction()->Evict(this, NumObjects, ppObjects); + } + + D3DINLINE HRESULT D3DAPI CreateFence( + UINT64 InitialValue, + D3D12_FENCE_FLAGS Flags, + _In_ REFIID riid, + _Outptr_ void** ppFence) + { + return DeviceFunction()->CreateFence(this, + InitialValue, + Flags, + riid, + ppFence); + } + + D3DINLINE HRESULT D3DAPI GetDeviceRemovedReason() + { + return DeviceFunction()->GetDeviceRemovedReason(this); + } + + D3DINLINE void D3DAPI GetCopyableFootprints( + _In_ const D3D12_RESOURCE_DESC* pResourceDesc, + _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0,D3D12_REQ_SUBRESOURCES - FirstSubresource) UINT NumSubresources, + UINT64 BaseOffset, + _Out_writes_opt_(NumSubresources) D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts, + _Out_writes_opt_(NumSubresources) UINT* pNumRows, + _Out_writes_opt_(NumSubresources) UINT64* pRowSizeInBytes, + _Out_opt_ UINT64* pTotalBytes) + { + DeviceFunction()->GetCopyableFootprints(this, + pResourceDesc, + FirstSubresource, + NumSubresources, + BaseOffset, + pLayouts, + pNumRows, + pRowSizeInBytes, + pTotalBytes); + } + + D3DINLINE HRESULT D3DAPI CreateQueryHeap( + _In_ const D3D12_QUERY_HEAP_DESC* pDesc, + REFIID riid, // Expected: ID3D12QueryHeap + _Outptr_opt_ void** ppvHeap + ) + { + return DeviceFunction()->CreateQueryHeap(this, pDesc, riid, ppvHeap); + } + + D3DINLINE HRESULT D3DAPI SetStablePowerState( + BOOL Enable) + { + return DeviceFunction()->SetStablePowerState(this, + Enable); + } + + D3DINLINE HRESULT D3DAPI CreateCommandSignature( + _In_ const D3D12_COMMAND_SIGNATURE_DESC* pDesc, + _In_opt_ ID3D12RootSignature* pRootSignature, + REFIID riid, + _Outptr_opt_ void** ppvCommandSignature) + { + return DeviceFunction()->CreateCommandSignature(this, + pDesc, + pRootSignature, + riid, + ppvCommandSignature); + } + + D3DINLINE void D3DAPI GetResourceTiling( + _In_ ID3D12Resource* pTiledResource, + _Out_opt_ UINT* pNumTilesForEntireResource, + _Out_opt_ D3D12_PACKED_MIP_INFO* pPackedMipDesc, + _Out_opt_ D3D12_TILE_SHAPE* pStandardTileShapeForNonPackedMips, + _Inout_opt_ UINT* pNumSubresourceTilings, + _In_ UINT FirstSubresourceTilingToGet, + _Out_writes_(*pNumSubresourceTilings) D3D12_SUBRESOURCE_TILING* pSubresourceTilingsForNonPackedMips) + { + DeviceFunction()->GetResourceTiling(this, + pTiledResource, + pNumTilesForEntireResource, + pPackedMipDesc, + pStandardTileShapeForNonPackedMips, + pNumSubresourceTilings, + FirstSubresourceTilingToGet, + pSubresourceTilingsForNonPackedMips); + } + + D3DINLINE LUID D3DAPI GetAdapterLuid() + { + return DeviceFunction()->GetAdapterLuid(this); + } + + D3DINLINE HRESULT D3DAPI CreatePlacedResourceX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS ResourceLocation, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource) + { + return DeviceFunction()->CreatePlacedResourceX(this, + ResourceLocation, + pDesc, + InitialState, + pOptimizedClearValue, + riid, + ppvResource); + } + + D3DINLINE HRESULT D3DAPI CreateComponentPlacedResourceX( + _In_ const D3D12XBOX_COMPONENT_PLACED_ADDRESSES* pComponentLocations, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource) + { + return DeviceFunction()->CreateComponentPlacedResourceX(this, + pComponentLocations, + pDesc, + InitialState, + pOptimizedClearValue, + riid, + ppvResource); + } + + D3DINLINE void D3DAPI CreatePlacedShaderResourceViewX( + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12XBOX_SHADER_RESOURCE_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreatePlacedShaderResourceViewX(this, + pResource, + pDesc, + DestDescriptor); + } + + D3DINLINE void D3DAPI CreatePlacedUnorderedAccessViewX( + _In_opt_ ID3D12Resource* pResource, + _In_opt_ const D3D12XBOX_UNORDERED_ACCESS_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreatePlacedUnorderedAccessViewX(this, + pResource, + pDesc, + DestDescriptor); + } + + D3DINLINE HRESULT D3DAPI CreateCommandQueueX( + _In_ const D3D12XBOX_COMMAND_QUEUE_DESC* pDesc, + REFIID riid, + _Outptr_ void** ppCommandQueue) + { + return DeviceFunction()->CreateCommandQueueX(this, + pDesc, + riid, + ppCommandQueue); + } + + D3DINLINE UINT64 D3DAPI SetDriverHintX( + _In_ UINT64 Feature, + _In_ UINT64 Value) + { + return DeviceFunction()->SetDriverHintX(this, Feature, Value); + } + + D3DINLINE void D3DAPI SetHangCallbacksX( + _In_ D3D12XBOX_HANGBEGINCALLBACK pBeginCallback, + _In_ D3D12XBOX_HANGPRINTCALLBACK pPrintCallback, + _In_ D3D12XBOX_HANGDUMPCALLBACK pDumpCallback) + { + DeviceFunction()->SetHangCallbacksX(this, + pBeginCallback, + pPrintCallback, + pDumpCallback); + } + + D3DINLINE void D3DAPI ReportGpuHangX( + _In_ D3D12XBOX_REPORT_GPU_HANG_FLAGS Flags) + { + DeviceFunction()->ReportGpuHangX(this, + Flags); + } + + D3DINLINE void D3DAPI SetDebugFlagsX( + _In_ D3D12XBOX_DEBUG_FLAGS Flags) + { + DeviceFunction()->SetDebugFlagsX(this, + Flags); + } + + D3DINLINE D3D12XBOX_DEBUG_FLAGS D3DAPI GetDebugFlagsX() + { + return DeviceFunction()->GetDebugFlagsX(this); + } + + D3DINLINE void D3DAPI SetDebugCallbackX( + _In_opt_ D3D12XBOX_DEBUG_CALLBACK pCallback, + _In_opt_ void* pUserContext) + { + return DeviceFunction()->SetDebugCallbackX(this, + pCallback, + pUserContext); + } + + D3DINLINE HRESULT D3DAPI CreateDerivedGraphicsPipelineStateX( + _In_ ID3D12PipelineState* pSrcPipelineState, + _In_ UINT NumDescs, + _In_ const D3D12XBOX_DERIVED_GRAPHICS_STATE_DESC* pDescs, + _In_ REFIID riid, + _Outptr_ void** ppDerivedPipelineState) + { + return DeviceFunction()->CreateDerivedGraphicsPipelineStateX(this, + pSrcPipelineState, + NumDescs, + pDescs, + riid, + ppDerivedPipelineState); + } + + D3DINLINE HRESULT D3DAPI SerializeGraphicsPipelineStateX( + _In_ ID3D12PipelineState* pPipelineState, + _In_ UINT Flags, + _Out_ D3D12XBOX_SERIALIZE_GRAPHICS_PIPELINE_STATE* pSerializeState) + { + return DeviceFunction()->SerializeGraphicsPipelineStateX(this, + pPipelineState, + Flags, + pSerializeState); + } + + D3DINLINE HRESULT D3DAPI DeserializeGraphicsPipelineStateX( + _In_ const D3D12XBOX_DESERIALIZE_GRAPHICS_PIPELINE_STATE* pDeserializeState, + _In_ REFIID riid, + _Outptr_ void** ppPipelineState) + { + return DeviceFunction()->DeserializeGraphicsPipelineStateX(this, + pDeserializeState, + riid, + ppPipelineState); + } + + D3DINLINE void D3DAPI EnableManualGraphicsTLBInvalidationX( + _In_ BOOL Enabled) + { + return DeviceFunction()->EnableManualGraphicsTLBInvalidationX(this, Enabled); + } + + D3DINLINE HRESULT D3DAPI GetDefaultMSAAParametersX( + _In_ const DXGI_SAMPLE_DESC* pDesc, + _Inout_opt_ D3D12XBOX_MSAA_SAMPLE_LOCATIONS* pSampleLocations, + _Inout_opt_ D3D12XBOX_MSAA_CENTROID_PRIORITIES* pCentroidPriorities, + _Inout_opt_ D3D12XBOX_MSAA_PARAMETERS* pMSAAParameters) + { + return DeviceFunction()->GetDefaultMSAAParametersX(this, + pDesc, + pSampleLocations, + pCentroidPriorities, + pMSAAParameters); + } + + D3DINLINE HRESULT D3DAPI CreateGraphicsPipelineStateX( + _In_ const D3D12_GRAPHICS_PIPELINE_STATE_DESC* pBaseDesc, + _In_ UINT NumExtendedDescs, + _In_ const D3D12XBOX_EXTENDED_GRAPHICS_PIPELINE_STATE_DESC* pExtendedDescs, + _In_ REFIID riid, + _Outptr_ void** ppPipelineState) + { + return DeviceFunction()->CreateGraphicsPipelineStateX(this, + pBaseDesc, + NumExtendedDescs, + pExtendedDescs, + riid, + ppPipelineState); + } + + D3DINLINE HRESULT D3DAPI CreateComputePipelineStateX( + _In_ const D3D12_COMPUTE_PIPELINE_STATE_DESC* pBaseDesc, + _In_ UINT NumExtendedDescs, + _In_ const D3D12XBOX_EXTENDED_COMPUTE_PIPELINE_STATE_DESC* pExtendedDescs, + REFIID riid, + _Outptr_ void** ppPipelineState) + { + return DeviceFunction()->CreateComputePipelineStateX(this, + pBaseDesc, + NumExtendedDescs, + pExtendedDescs, + riid, + ppPipelineState); + } + + D3DINLINE HRESULT D3DAPI CreateDerivedComputePipelineStateX( + _In_ ID3D12PipelineState* pSrcPipelineState, + _In_ UINT NumDescs, + _In_ const D3D12XBOX_DERIVED_COMPUTE_STATE_DESC* pDescs, + _In_ REFIID riid, + _Outptr_ void** ppDerivedPipelineState) + { + return DeviceFunction()->CreateDerivedComputePipelineStateX(this, + pSrcPipelineState, + NumDescs, + pDescs, + riid, + ppDerivedPipelineState); + } + + D3DINLINE HRESULT D3DAPI SerializeComputePipelineStateX( + _In_ ID3D12PipelineState* pPipelineState, + _In_ UINT Flags, + _Out_ D3D12XBOX_SERIALIZE_COMPUTE_PIPELINE_STATE* pSerializeState) + { + return DeviceFunction()->SerializeComputePipelineStateX(this, + pPipelineState, + Flags, + pSerializeState); + } + + D3DINLINE HRESULT D3DAPI DeserializeComputePipelineStateX( + _In_ const D3D12XBOX_DESERIALIZE_COMPUTE_PIPELINE_STATE* pDeserializeState, + _In_ REFIID riid, + _Outptr_ void** ppPipelineState) + { + return DeviceFunction()->DeserializeComputePipelineStateX(this, + pDeserializeState, + riid, + ppPipelineState); + } + + D3DINLINE UINT32 D3DAPI RegisterCustomFenceLocationX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS FenceGpuAddress, + _In_z_ LPCWSTR pName) + { + return DeviceFunction()->RegisterCustomFenceLocationX(this, FenceGpuAddress, pName); + } + + D3DINLINE void D3DAPI UnregisterCustomFenceLocationX( + _In_ UINT32 Handle) + { + DeviceFunction()->UnregisterCustomFenceLocationX(this, Handle); + } + + D3DINLINE void D3DAPI GetGpuHardwareConfigurationX( + _Out_ D3D12XBOX_GPU_HARDWARE_CONFIGURATION* pGpuHardwareConfiguration) + { + DeviceFunction()->GetGpuHardwareConfigurationX(this, pGpuHardwareConfiguration); + } + + D3DINLINE HRESULT D3DAPI SetDebugErrorFilterX( + _In_ UINT ErrorIdentifier, + _In_ D3D12XBOX_DEBUG_FILTER_FLAGS FilterFlags) + { + return DeviceFunction()->SetDebugErrorFilterX(this, + ErrorIdentifier, + FilterFlags); + } + + D3DINLINE void D3DAPI CreatePlacedRawShaderResourceViewX( + _In_ const D3D12_RESOURCE_DESC* pResourceDesc, + _In_ const D3D12XBOX_SHADER_RESOURCE_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreatePlacedRawShaderResourceViewX(this, + pResourceDesc, + pDesc, + DestDescriptor); + } + + D3DINLINE void D3DAPI CreatePlacedRawUnorderedAccessViewX( + _In_ const D3D12_RESOURCE_DESC* pResourceDesc, + _In_ const D3D12XBOX_UNORDERED_ACCESS_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + DeviceFunction()->CreatePlacedRawUnorderedAccessViewX(this, + pResourceDesc, + pDesc, + DestDescriptor); + } + + D3DINLINE HRESULT D3DAPI SetGpuMemoryPriorityX( + _In_ UINT Priority) + { + return DeviceFunction()->SetGpuMemoryPriorityX(this, + Priority); + } + + D3DINLINE HRESULT D3DAPI RegisterPagePoolX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS PagePoolAddress, + _In_ UINT PagePoolPageCount, + _Out_ HANDLE* pPagePoolHandle) + { + return DeviceFunction()->RegisterPagePoolX(this, PagePoolAddress, PagePoolPageCount, pPagePoolHandle); + } + + D3DINLINE HRESULT D3DAPI UnregisterPagePoolX( + _In_ HANDLE PagePoolHandle) + { + return DeviceFunction()->UnregisterPagePoolX(this, PagePoolHandle); + } + + D3DINLINE HRESULT D3DAPI CreateCommittedResourceX( + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12XBOX_RESOURCE_DESC* pResourceDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riidResource, + _Outptr_opt_ void** ppvResource) + { + return DeviceFunction()->CreateCommittedResourceX( + this, + pHeapProperties, + HeapFlags, + pResourceDesc, + InitialState, + pOptimizedClearValue, + riidResource, + ppvResource); + } + + D3DINLINE HRESULT D3DAPI CreateComponentPlacedResourceX1( + _In_ const D3D12XBOX_COMPONENT_PLACED_ADDRESSES* pComponentLocations, + _In_ const D3D12XBOX_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource) + { + return DeviceFunction()->CreateComponentPlacedResourceX1( + this, + pComponentLocations, + pDesc, + InitialState, + pOptimizedClearValue, + riid, + ppvResource); + } + + D3DINLINE HRESULT D3DAPI SetFrameIntervalX( + _In_opt_ IDXGIOutput* pOutputSyncTarget, + _In_ UINT LengthInMicroseconds, + _In_ UINT PeriodInIntervals, + _In_ D3D12XBOX_FRAME_INTERVAL_FLAGS Flags) + { + return DeviceFunction()->SetFrameIntervalX( + this, + pOutputSyncTarget, + LengthInMicroseconds, + PeriodInIntervals, + Flags); + } + + D3DINLINE HRESULT D3DAPI ScheduleFrameEventX( + _In_ D3D12XBOX_FRAME_EVENT_TYPE Type, + _In_ UINT IntervalOffsetInMicroseconds, + _In_opt_ D3D12XBOX_SCHEDULE_FRAME_OBJECT_LIST* pAncillarySignalList, + _In_ D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAGS Flags) + { + return DeviceFunction()->ScheduleFrameEventX( + this, + Type, + IntervalOffsetInMicroseconds, + pAncillarySignalList, + Flags); + } + + D3DINLINE HRESULT D3DAPI WaitFrameEventX( + _In_ D3D12XBOX_FRAME_EVENT_TYPE Type, + _In_ UINT TimeOutInMs, + _In_opt_ D3D12XBOX_WAIT_FRAME_OBJECT_LIST* pAncillaryWaitList, + _In_ D3D12XBOX_WAIT_FRAME_EVENT_FLAGS Flags, + _Inout_ D3D12XBOX_FRAME_PIPELINE_TOKEN* pToken) + { + return DeviceFunction()->WaitFrameEventX( + this, + Type, + TimeOutInMs, + pAncillaryWaitList, + Flags, + pToken); + } + + D3DINLINE HRESULT D3DAPI GetFrameStatisticsX( + _In_ D3D12XBOX_FRAME_PIPELINE_TOKEN Token, + _In_ D3D12XBOX_FRAME_STATISTICS_TYPE TypeSet, + _Inout_ UINT* pCount, + _Out_ D3D12XBOX_FRAME_STATISTICS* pStatistics) + { + return DeviceFunction()->GetFrameStatisticsX( + this, + Token, + TypeSet, + pCount, + pStatistics); + } + + D3DINLINE HRESULT D3DAPI CreateCounterSetX( + _In_ const D3D12XBOX_COUNTER_SET_DESC* pCounterSetDesc, + REFIID riid, + _Outptr_opt_ void** ppCounterSet) + { + return DeviceFunction()->CreateCounterSetX( + this, + pCounterSetDesc, + riid, + ppCounterSet); + } +}; + + +extern "C" +{ + +// +// ID3D12Device1 +// + +struct D3D12Device1_Function_Table +{ + D3D12Device_Function_Table DeviceFunction; + + HRESULT (D3DAPI* CreatePipelineLibrary)( + _Inout_ ID3D12Device1* pDevice1, + _In_reads_(BlobLength) const void* pLibraryBlob, + SIZE_T BlobLength, + REFIID riid, + _Outptr_ void** ppPipelineLibrary); + + HRESULT (D3DAPI* SetEventOnMultipleFenceCompletion)( + _Inout_ ID3D12Device1* pDevice1, + _In_reads_(NumFences) ID3D12Fence* const* ppFences, + _In_reads_(NumFences) const UINT64* pFenceValues, + UINT NumFences, + D3D12_MULTIPLE_FENCE_WAIT_FLAGS Flags, + HANDLE hEvent); + + HRESULT (D3DAPI* SetResidencyPriority)( + _Inout_ ID3D12Device1* pDevice1, + UINT NumObjects, + _In_reads_(NumObjects) ID3D12Pageable* const* ppObjects, + _In_reads_(NumObjects) const D3D12_RESIDENCY_PRIORITY* pPriorities); +}; + + +} + +D3DINTERFACE(ID3D12Device1, 77acce80,638e,4e65,88,95,c1,f2,33,86,86,3e) : public ID3D12Device +{ +public: + + D3DINLINE D3D12Device1_Function_Table* Device1Function() + { + return (D3D12Device1_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI CreatePipelineLibrary( + _In_reads_(BlobLength) const void* pLibraryBlob, + SIZE_T BlobLength, + REFIID riid, + _Outptr_ void** ppPipelineLibrary) + { + return Device1Function()->CreatePipelineLibrary( + this, + pLibraryBlob, + BlobLength, + riid, + ppPipelineLibrary); + } + + D3DINLINE HRESULT D3DAPI SetEventOnMultipleFenceCompletion( + _In_reads_(NumFences) ID3D12Fence* const* ppFences, + _In_reads_(NumFences) const UINT64* pFenceValues, + UINT NumFences, + D3D12_MULTIPLE_FENCE_WAIT_FLAGS Flags, + HANDLE hEvent) + { + return Device1Function()->SetEventOnMultipleFenceCompletion( + this, + ppFences, + pFenceValues, + NumFences, + Flags, + hEvent); + } + + D3DINLINE HRESULT D3DAPI SetResidencyPriority( + UINT NumObjects, + _In_reads_(NumObjects) ID3D12Pageable* const* ppObjects, + _In_reads_(NumObjects) const D3D12_RESIDENCY_PRIORITY* pPriorities) + { + return Device1Function()->SetResidencyPriority( + this, + NumObjects, + ppObjects, + pPriorities); + } +}; + + +extern "C" +{ + + +// +// ID3D12Device2 +// + +struct D3D12Device2_Function_Table +{ + D3D12Device1_Function_Table DeviceFunction; + + HRESULT (D3DAPI* CreatePipelineState)( + _Inout_ ID3D12Device2* pDevice2, + const D3D12_PIPELINE_STATE_STREAM_DESC* pDesc, + REFIID riid, + _Outptr_ void** ppPipelineState); +}; + + +} + +D3DINTERFACE(ID3D12Device2, 30baa41e,b15b,475c,a0,bb,1a,f5,c5,b6,43,28) : public ID3D12Device1 +{ +public: + + D3DINLINE D3D12Device2_Function_Table* Device2Function() + { + return (D3D12Device2_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI CreatePipelineState( + const D3D12_PIPELINE_STATE_STREAM_DESC* pDesc, + REFIID riid, + _Outptr_ void** ppPipelineState) + { + return Device2Function()->CreatePipelineState( + this, + pDesc, + riid, + ppPipelineState); + } + +}; + + +extern "C" +{ + +// +// ID3D12Device3 +// + +struct D3D12Device3_Function_Table +{ + D3D12Device2_Function_Table DeviceFunction; + + HRESULT (D3DAPI* OpenExistingHeapFromAddress)( + _Inout_ ID3D12Device3* pDevice3, + _In_ const void* pAddress, + REFIID riid, + _Outptr_ void** ppvHeap); + + HRESULT (D3DAPI* OpenExistingHeapFromFileMapping)( + _Inout_ ID3D12Device3* pDevice3, + _In_ HANDLE hFileMapping, + REFIID riid, + _Outptr_ void** ppvHeap); + + HRESULT (D3DAPI* EnqueueMakeResident)( + _Inout_ ID3D12Device3* pDevice3, + D3D12_RESIDENCY_FLAGS Flags, + UINT NumObjects, + _In_reads_(NumObjects) ID3D12Pageable*const* ppObjects, + _In_ ID3D12Fence* pFenceToSignal, + UINT64 FenceValueToSignal); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12Device3, 81dadc15,2bad,4392,93,c5,10,13,45,c4,aa,98) : public ID3D12Device2 +{ +public: + + D3DINLINE D3D12Device3_Function_Table* Device3Function() + { + return (D3D12Device3_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI OpenExistingHeapFromAddress( + _In_ const void* pAddress, + REFIID riid, + _Outptr_ void** ppvHeap) + { + return Device3Function()->OpenExistingHeapFromAddress( + this, + pAddress, + riid, + ppvHeap); + } + + D3DINLINE HRESULT D3DAPI OpenExistingHeapFromFileMapping( + _In_ HANDLE hFileMapping, + REFIID riid, + _Outptr_ void** ppvHeap) + { + return Device3Function()->OpenExistingHeapFromFileMapping( + this, + hFileMapping, + riid, + ppvHeap); + } + + D3DINLINE HRESULT D3DAPI EnqueueMakeResident( + D3D12_RESIDENCY_FLAGS Flags, + UINT NumObjects, + _In_reads_(NumObjects) ID3D12Pageable*const* ppObjects, + _In_ ID3D12Fence* pFenceToSignal, + UINT64 FenceValueToSignal) + { + return Device3Function()->EnqueueMakeResident( + this, + Flags, + NumObjects, + ppObjects, + pFenceToSignal, + FenceValueToSignal); + } + +}; + +extern "C" +{ + +typedef enum D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAGS +{ + D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAG_NONE = 0x0, + D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAG_SUPPORTED = 0x1, + +} D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAGS; + +typedef struct D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT +{ + UINT NodeIndex; // input + D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAGS Support; // output +} D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT; + +typedef enum D3D12_PROTECTED_RESOURCE_SESSION_FLAGS +{ + D3D12_PROTECTED_RESOURCE_SESSION_FLAG_NONE = 0x0, + +} D3D12_PROTECTED_RESOURCE_SESSION_FLAGS; + +typedef struct D3D12_PROTECTED_RESOURCE_SESSION_DESC +{ + UINT NodeMask; + D3D12_PROTECTED_RESOURCE_SESSION_FLAGS Flags; +} D3D12_PROTECTED_RESOURCE_SESSION_DESC; + +} + +extern "C" +{ + +// +// ID3D12ProtectedSession +// + +struct D3D12ProtectedSession_Function_Table +{ + D3D12DeviceChild_Function_Table DeviceChildFunction; + + HRESULT (D3DAPI* GetStatusFence)( + _Inout_ ID3D12ProtectedSession* pProtectedSession, + REFIID riid, + _Outptr_opt_ void** ppFence); + + D3D12_PROTECTED_SESSION_STATUS (D3DAPI* GetSessionStatus)( + _Inout_ ID3D12ProtectedSession* pProtectedSession); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12ProtectedSession, A1533D18,0AC1,4084,85,B9,89,A9,61,16,80,6B) : public ID3D12DeviceChild +{ +public: + + D3DINLINE D3D12ProtectedSession_Function_Table* ProtectedSessionFunction() + { + return (D3D12ProtectedSession_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetStatusFence( + REFIID riid, + _Outptr_opt_ void** ppFence) + { + return ProtectedSessionFunction()->GetStatusFence( + this, + riid, + ppFence); + } + + D3DINLINE D3D12_PROTECTED_SESSION_STATUS D3DAPI GetSessionStatus() + { + return ProtectedSessionFunction()->GetSessionStatus(this); + } + +}; +extern "C" +{ + +// +// ID3D12ProtectedResourceSession +// + +struct D3D12ProtectedResourceSession_Function_Table +{ + D3D12ProtectedSession_Function_Table ProtectedSessionFunction; + + D3D12_PROTECTED_RESOURCE_SESSION_DESC (D3DAPI* GetDesc)( + _Inout_ ID3D12ProtectedResourceSession* pProtectedResourceSession); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12ProtectedResourceSession, 6CD696F4,F289,40CC,80,91,5A,6C,0A,09,9C,3D) : public ID3D12ProtectedSession +{ +public: + + D3DINLINE D3D12ProtectedResourceSession_Function_Table* ProtectedResourceSessionFunction() + { + return (D3D12ProtectedResourceSession_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_PROTECTED_RESOURCE_SESSION_DESC D3DAPI GetDesc() + { + return ProtectedResourceSessionFunction()->GetDesc(this); + } + +}; + +// +// ID3D12ProtectedResourceSession1 +// + +extern "C" +{ + +typedef struct D3D12_PROTECTED_RESOURCE_SESSION_DESC1 +{ + UINT NodeMask; + D3D12_PROTECTED_RESOURCE_SESSION_FLAGS Flags; + GUID ProtectionType; +} D3D12_PROTECTED_RESOURCE_SESSION_DESC1; + +struct D3D12ProtectedResourceSession1_Function_Table +{ + D3D12ProtectedResourceSession_Function_Table ParentFunction; + + D3D12_PROTECTED_RESOURCE_SESSION_DESC1 (D3DAPI *GetDesc1)( + _Inout_ ID3D12ProtectedResourceSession1* pProtectedResourceSession + ); +}; + +#if DECLARE_UMD_EXPORTS_D3D12X + +D3D12_PROTECTED_RESOURCE_SESSION_DESC1 D3d12ProtectedResourceSession1_GetDesc1( + _Inout_ ID3D12ProtectedResourceSession1* pProtectedResourceSession +); + +D3DCONST D3D12ProtectedResourceSession1_Function_Table D3D__D3d12ProtectedResourceSession1_Function_Table = +{ + D3D__D3d12ProtectedResourceSession_Function_Table, + + D3d12ProtectedResourceSession1_GetDesc1, +}; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12ProtectedResourceSession1, D6F12DD6,76FB,406E,89,61,42,96,EE,FC,04,09) : public ID3D12ProtectedResourceSession +{ +public: + D3DINLINE D3D12ProtectedResourceSession1_Function_Table* ProtectedResourceSession1Function() + { + return (D3D12ProtectedResourceSession1_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_PROTECTED_RESOURCE_SESSION_DESC1 GetDesc1( + ) + { + return ProtectedResourceSession1Function()->GetDesc1(this); + } +}; + +extern "C" +{ + +// +// ID3D12Device4 +// + +struct D3D12Device4_Function_Table +{ + D3D12Device3_Function_Table DeviceFunction; + + HRESULT (D3DAPI* CreateCommandList1)( + _Inout_ ID3D12Device4* pDevice4, + _In_ UINT nodeMask, + _In_ D3D12_COMMAND_LIST_TYPE type, + _In_ D3D12_COMMAND_LIST_FLAGS flags, + REFIID riid, + _Outptr_ void** ppCommandList); + + HRESULT (D3DAPI* CreateProtectedResourceSession)( + _Inout_ ID3D12Device4* pDevice4, + _In_ const D3D12_PROTECTED_RESOURCE_SESSION_DESC* pDesc, + _In_ REFIID riid, + _Outptr_ void** ppSession); + + HRESULT (D3DAPI* CreateCommittedResource1)( + _Inout_ ID3D12Device4* pDevice4, + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialResourceState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + REFIID riidResource, + _Outptr_opt_ void** ppvResource); + + HRESULT (D3DAPI* CreateHeap1)( + _Inout_ ID3D12Device4* pDevice4, + _In_ const D3D12_HEAP_DESC* pDesc, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + REFIID riid, + _Outptr_opt_ void** ppvHeap); + + HRESULT (D3DAPI* CreateReservedResource1)( + _Inout_ ID3D12Device4* pDevice4, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + D3D12_RESOURCE_ALLOCATION_INFO (D3DAPI* GetResourceAllocationInfo1)( + _Inout_ ID3D12Device4* pDevice4, + UINT visibleMask, + UINT numResourceDescs, + _In_reads_(numResourceDescs) const D3D12_RESOURCE_DESC* pResourceDescs, + _Out_writes_opt_(numResourceDescs) D3D12_RESOURCE_ALLOCATION_INFO1* pResourceAllocationInfo1); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12Device4, e865df17,a9ee,46f9,a4,63,30,98,31,5a,a2,e5) : public ID3D12Device3 +{ +public: + + D3DINLINE D3D12Device4_Function_Table* Device4Function() + { + return (D3D12Device4_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI CreateCommandList1( + _In_ UINT nodeMask, + _In_ D3D12_COMMAND_LIST_TYPE type, + _In_ D3D12_COMMAND_LIST_FLAGS flags, + REFIID riid, + _Outptr_ void** ppCommandList) + { + return Device4Function()->CreateCommandList1( + this, + nodeMask, + type, + flags, + riid, + ppCommandList); + } + + D3DINLINE HRESULT D3DAPI CreateProtectedResourceSession( + _In_ const D3D12_PROTECTED_RESOURCE_SESSION_DESC* pDesc, + _In_ REFIID riid, + _Outptr_ void** ppSession) + { + return Device4Function()->CreateProtectedResourceSession( + this, + pDesc, + riid, + ppSession); + } + + D3DINLINE HRESULT D3DAPI CreateCommittedResource1( + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialResourceState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + REFIID riidResource, + _Outptr_opt_ void** ppvResource) + { + return Device4Function()->CreateCommittedResource1( + this, + pHeapProperties, + HeapFlags, + pDesc, + InitialResourceState, + pOptimizedClearValue, + pProtectedSession, + riidResource, + ppvResource); + } + + D3DINLINE HRESULT D3DAPI CreateHeap1( + _In_ const D3D12_HEAP_DESC* pDesc, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + REFIID riid, + _Outptr_opt_ void** ppvHeap) + { + return Device4Function()->CreateHeap1( + this, + pDesc, + pProtectedSession, + riid, + ppvHeap); + } + + D3DINLINE HRESULT D3DAPI CreateReservedResource1( + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + REFIID riid, + _Outptr_opt_ void** ppvResource) + { + return Device4Function()->CreateReservedResource1( + this, + pDesc, + InitialState, + pOptimizedClearValue, + pProtectedSession, + riid, + ppvResource); + } + + D3DINLINE D3D12_RESOURCE_ALLOCATION_INFO D3DAPI GetResourceAllocationInfo1( + UINT visibleMask, + UINT numResourceDescs, + _In_reads_(numResourceDescs) const D3D12_RESOURCE_DESC* pResourceDescs, + _Out_writes_opt_(numResourceDescs) D3D12_RESOURCE_ALLOCATION_INFO1* pResourceAllocationInfo1) + { + return Device4Function()->GetResourceAllocationInfo1( + this, + visibleMask, + numResourceDescs, + pResourceDescs, + pResourceAllocationInfo1); + } + +}; + +extern "C" +{ + +typedef enum D3D12_LIFETIME_STATE +{ + D3D12_LIFETIME_STATE_IN_USE, + D3D12_LIFETIME_STATE_NOT_IN_USE, +} D3D12_LIFETIME_STATE; + +// +// ID3D12LifetimeOwner +// + +struct D3D12LifetimeOwner_Function_Table +{ + GraphicsUnknown_Function_Table UnknownFunction; + + void (D3DAPI* LifetimeStateUpdated)( + _Inout_ ID3D12LifetimeOwner* pLifetimeOwner, + D3D12_LIFETIME_STATE NewState); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12LifetimeOwner, e667af9f,cd56,4f46,83,ce,03,2e,59,5d,70,a8) : public IGraphicsUnknown +{ +public: + + D3DINLINE D3D12LifetimeOwner_Function_Table* LifetimeOwnerFunction() + { + return (D3D12LifetimeOwner_Function_Table*)m_pFunction; + } + + D3DINLINE void D3DAPI LifetimeStateUpdated( + D3D12_LIFETIME_STATE NewState) + { + return LifetimeOwnerFunction()->LifetimeStateUpdated( + this, + NewState); + } + +}; + +extern "C" +{ + +// +// ID3D12SwapChainAssistant +// + +struct D3D12SwapChainAssistant_Function_Table +{ + GraphicsUnknown_Function_Table UnknownFunction; + + LUID (D3DAPI* GetLUID)( + _Inout_ ID3D12SwapChainAssistant* pSwapChainAssistant); + + HRESULT (D3DAPI* GetSwapChainObject)( + _Inout_ ID3D12SwapChainAssistant* pSwapChainAssistant, + REFIID riid, + _Outptr_ void** ppv); + + HRESULT (D3DAPI* GetCurrentResourceAndCommandQueue)( + _Inout_ ID3D12SwapChainAssistant* pSwapChainAssistant, + REFIID riidResource, + _Outptr_ void** ppvResource, + REFIID riidQueue, + _Outptr_ void** ppvQueue); + + HRESULT (D3DAPI* InsertImplicitSync)( + _Inout_ ID3D12SwapChainAssistant* pSwapChainAssistant); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12SwapChainAssistant, f1df64b6,57fd,49cd,88,07,c0,eb,88,b4,5c,8f) : public IGraphicsUnknown +{ +public: + + D3DINLINE D3D12SwapChainAssistant_Function_Table* SwapChainAssistantFunction() + { + return (D3D12SwapChainAssistant_Function_Table*)m_pFunction; + } + + D3DINLINE LUID D3DAPI GetLUID() + { + return SwapChainAssistantFunction()->GetLUID(this); + } + + D3DINLINE HRESULT D3DAPI GetSwapChainObject( + REFIID riid, + _Outptr_ void** ppv) + { + return SwapChainAssistantFunction()->GetSwapChainObject( + this, + riid, + ppv); + } + + D3DINLINE HRESULT D3DAPI GetCurrentResourceAndCommandQueue( + REFIID riidResource, + _Outptr_ void** ppvResource, + REFIID riidQueue, + _Outptr_ void** ppvQueue) + { + return SwapChainAssistantFunction()->GetCurrentResourceAndCommandQueue( + this, + riidResource, + ppvResource, + riidQueue, + ppvQueue); + } + + D3DINLINE HRESULT D3DAPI InsertImplicitSync() + { + return SwapChainAssistantFunction()->InsertImplicitSync(this); + } + +}; + +extern "C" +{ + +// +// ID3D12LifetimeTracker +// + +struct D3D12LifetimeTracker_Function_Table +{ + D3D12DeviceChild_Function_Table DeviceChildFunction; + + HRESULT (D3DAPI* DestroyOwnedObject)( + _Inout_ ID3D12LifetimeTracker* pLifetimeTracker, + _In_ ID3D12DeviceChild* pObject); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12LifetimeTracker, 3fd03d36,4eb1,424a,a5,82,49,4e,cb,8b,a8,13) : public ID3D12DeviceChild +{ +public: + + D3DINLINE D3D12LifetimeTracker_Function_Table* LifetimeTrackerFunction() + { + return (D3D12LifetimeTracker_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI DestroyOwnedObject( + _In_ ID3D12DeviceChild* pObject) + { + return LifetimeTrackerFunction()->DestroyOwnedObject( + this, + pObject); + } + +}; + +extern "C" +{ + +typedef enum D3D12_META_COMMAND_PARAMETER_TYPE +{ + D3D12_META_COMMAND_PARAMETER_TYPE_FLOAT = 0, + D3D12_META_COMMAND_PARAMETER_TYPE_UINT64 = 1, + D3D12_META_COMMAND_PARAMETER_TYPE_GPU_VIRTUAL_ADDRESS = 2, + D3D12_META_COMMAND_PARAMETER_TYPE_CPU_DESCRIPTOR_HANDLE_HEAP_TYPE_CBV_SRV_UAV = 3, + D3D12_META_COMMAND_PARAMETER_TYPE_GPU_DESCRIPTOR_HANDLE_HEAP_TYPE_CBV_SRV_UAV = 4, +} D3D12_META_COMMAND_PARAMETER_TYPE; + +typedef enum D3D12_META_COMMAND_PARAMETER_FLAGS +{ + D3D12_META_COMMAND_PARAMETER_FLAG_INPUT = 0x00000001, + D3D12_META_COMMAND_PARAMETER_FLAG_OUTPUT = 0x00000002 +} D3D12_META_COMMAND_PARAMETER_FLAGS; + +typedef enum D3D12_META_COMMAND_PARAMETER_STAGE +{ + D3D12_META_COMMAND_PARAMETER_STAGE_CREATION = 0, + D3D12_META_COMMAND_PARAMETER_STAGE_INITIALIZATION = 1, + D3D12_META_COMMAND_PARAMETER_STAGE_EXECUTION = 2, +} D3D12_META_COMMAND_PARAMETER_STAGE; + +typedef struct D3D12_META_COMMAND_PARAMETER_DESC +{ + LPCWSTR Name; + D3D12_META_COMMAND_PARAMETER_TYPE Type; + D3D12_META_COMMAND_PARAMETER_FLAGS Flags; + D3D12_RESOURCE_STATES RequiredResourceState; + UINT StructureOffset; +} D3D12_META_COMMAND_PARAMETER_DESC; + +typedef enum D3D12_GRAPHICS_STATES +{ + D3D12_GRAPHICS_STATE_NONE = 0, + D3D12_GRAPHICS_STATE_IA_VERTEX_BUFFERS = (1 << 0), + D3D12_GRAPHICS_STATE_IA_INDEX_BUFFER = (1 << 1), + D3D12_GRAPHICS_STATE_IA_PRIMITIVE_TOPOLOGY = (1 << 2), + D3D12_GRAPHICS_STATE_DESCRIPTOR_HEAP = (1 << 3), + D3D12_GRAPHICS_STATE_GRAPHICS_ROOT_SIGNATURE = (1 << 4), + D3D12_GRAPHICS_STATE_COMPUTE_ROOT_SIGNATURE = (1 << 5), + D3D12_GRAPHICS_STATE_RS_VIEWPORTS = (1 << 6), + D3D12_GRAPHICS_STATE_RS_SCISSOR_RECTS = (1 << 7), + D3D12_GRAPHICS_STATE_PREDICATION = (1 << 8), + D3D12_GRAPHICS_STATE_OM_RENDER_TARGETS = (1 << 9), + D3D12_GRAPHICS_STATE_OM_STENCIL_REF = (1 << 10), + D3D12_GRAPHICS_STATE_OM_BLEND_FACTOR = (1 << 11), + D3D12_GRAPHICS_STATE_PIPELINE_STATE = (1 << 12), + D3D12_GRAPHICS_STATE_SO_TARGETS = (1 << 13), + D3D12_GRAPHICS_STATE_OM_DEPTH_BOUNDS = (1 << 14), + D3D12_GRAPHICS_STATE_SAMPLE_POSITIONS = (1 << 15), + D3D12_GRAPHICS_STATE_VIEW_INSTANCE_MASK = (1 << 16), + +} D3D12_GRAPHICS_STATES; + +typedef struct D3D12_META_COMMAND_DESC +{ + GUID Id; + LPCWSTR Name; + D3D12_GRAPHICS_STATES InitializationDirtyState; + D3D12_GRAPHICS_STATES ExecutionDirtyState; +} D3D12_META_COMMAND_DESC; + + +struct D3D12XBOX_RAYTRACING_INFORMATION_EXPORT +{ + const wchar_t* pExportName; + UINT ShaderId[8]; + UINT SftStackSizeBytesPerLane; + UINT ScratchSizeDwordsPerLane; + UINT Reserved[2]; + UINT16 NumVGPRs; + UINT16 NumSGPRs; +}; + +struct D3D12XBOX_RAYTRACING_INFORMATION_EXPORT_TABLE +{ + const D3D12XBOX_RAYTRACING_INFORMATION_EXPORT* pExports; + UINT NumExports; +}; + +// +union D3D12XBOX_RAYTRACING_INFORMATION +{ + // D3D12XBOX_RAYTRACING_INFORMATION_FLAG_GET_BASE_INFO + struct + { + UINT SftStackSize; // Per-lane stack memory needed for the state function transform + UINT ScratchSize; // Per-lane scratch memory needed for spill + + // Below fields are only valid in INSTRUMENTED builds + UINT LastRaysPerDispatch; + UINT LastNumDispatches; + } BaseInfo; + + // D3D12XBOX_RAYTRACING_INFORMATION_FLAG_GET_SCRATCH_INFO + struct + { + UINT PerLaneSftStackSize; // Per-lane stack memory needed for the state function transform + UINT PerLaneScratchSize; // Per-lane scratch memory needed for spill + UINT WaveOccupancyLimit; // Computed wave32 occupancy limit for the RTPSO (1 - 20) + + // The following value takes into account the wave occupancy limit and the number of SIMDs available. + // It can be used to size a title-supplied scratch buffer for DispatchRaysX(). + UINT SuggestedScratchSize; // Total scratch memory needed to unthrottle DispatchRaysX + } ScratchInfo; + + // D3D12XBOX_RAYTRACING_INFORMATION_FLAG_GET_EXPORT_TABLE -> D3D12XBOX_RAYTRACING_INFORMATION_EXPORTS + ID3DBlob* GenericData; +}; + +enum D3D12XBOX_RAYTRACING_INFORMATION_FLAGS +{ + D3D12XBOX_RAYTRACING_INFORMATION_FLAG_GET_BASE_INFO, // D3D12XBOX_RAYTRACING_INFORMATION::BaseInfo + D3D12XBOX_RAYTRACING_INFORMATION_FLAG_GET_EXPORT_TABLE, // D3D12XBOX_RAYTRACING_INFORMATION::GenericData + D3D12XBOX_RAYTRACING_INFORMATION_FLAG_GET_SCRATCH_INFO // D3D12XBOX_RAYTRACING_INFORMATION::ScratchInfo +}; + +// +// ID3D12StateObject +// + +struct D3D12StateObject_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; + + void (D3DAPI* GetPipelineStateX)( + _Inout_ ID3D12StateObject* pStateObject, + _Out_ ID3D12PipelineState** ppPipelineState); +}; + + +} // extern C + +D3DINTERFACE(ID3D12StateObject, 47016943,fca8,4594,93,ea,af,25,8b,55,34,6d) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12StateObject_Function_Table* StateObjectFunction() + { + return (D3D12StateObject_Function_Table*)m_pFunction; + } + + D3DINLINE void D3DAPI GetPipelineStateX( + _Out_ ID3D12PipelineState** ppPipelineState) + { + return StateObjectFunction()->GetPipelineStateX( + this, + ppPipelineState); + } +}; + +// The default behaviour for a missing anyhit is "accept". Use null identifier to specify that. +// Use this to specify that anyhit does not need to be called but the result should be ignore. +#define D3D12XBOX_XDXR_BUILTIN_SHADER_IMPORT_NULL_ANYHIT_IGNORE L"__xdxr_builtin_NullAnyhitIgnore" + +extern "C" +{ + +// +// ID3D12StateObjectProperties +// + +struct D3D12StateObjectProperties_Function_Table +{ + GraphicsUnknown_Function_Table UnknownFunction; + + const void* (D3DAPI* GetShaderIdentifier)( + _Inout_ ID3D12StateObjectProperties* pStateObjectProperties, + _In_ LPCWSTR pExportName); + + UINT64 (D3DAPI* GetShaderStackSize)( + _Inout_ ID3D12StateObjectProperties* pStateObjectProperties, + _In_ LPCWSTR pExportName); + + UINT64 (D3DAPI* GetPipelineStackSize)( + _Inout_ ID3D12StateObjectProperties* pStateObjectProperties); + + void (D3DAPI* SetPipelineStackSize)( + _Inout_ ID3D12StateObjectProperties* pStateObjectProperties, + UINT64 PipelineStackSizeInBytes); + + void (D3DAPI* GetInformationX)( + _Inout_ ID3D12StateObjectProperties* pStateObjectProperties, + UINT64 Flags, // D3D12XBOX_RAYTRACING_INFORMATION_FLAGS + D3D12XBOX_RAYTRACING_INFORMATION* pOutputinfo); +}; + + +} // extern C + +D3DINTERFACE(ID3D12StateObjectProperties, de5fa827,9bf9,4f26,89,ff,d7,f5,6f,de,38,60) : public IGraphicsUnknown +{ +public: + + D3DINLINE D3D12StateObjectProperties_Function_Table* StateObjectPropertiesFunction() + { + return (D3D12StateObjectProperties_Function_Table*)m_pFunction; + } + + D3DINLINE const void* D3DAPI GetShaderIdentifier( + _In_ LPCWSTR pExportName) + { + return StateObjectPropertiesFunction()->GetShaderIdentifier( + this, + pExportName); + } + + D3DINLINE UINT64 D3DAPI GetShaderStackSize( + _In_ LPCWSTR pExportName) + { + return StateObjectPropertiesFunction()->GetShaderStackSize( + this, + pExportName); + } + + D3DINLINE UINT64 D3DAPI GetPipelineStackSize() + { + return StateObjectPropertiesFunction()->GetPipelineStackSize(this); + } + + D3DINLINE void D3DAPI SetPipelineStackSize( + UINT64 PipelineStackSizeInBytes) + { + return StateObjectPropertiesFunction()->SetPipelineStackSize( + this, + PipelineStackSizeInBytes); + } + + D3DINLINE void D3DAPI GetInformationX( + UINT64 Flags, + _Out_ D3D12XBOX_RAYTRACING_INFORMATION* pOutputinfo) + { + return StateObjectPropertiesFunction()->GetInformationX( + this, + Flags, + pOutputinfo); + } +}; + + + +extern "C" +{ +typedef enum D3D12_STATE_SUBOBJECT_TYPE +{ + D3D12_STATE_SUBOBJECT_TYPE_STATE_OBJECT_CONFIG = 0, // D3D12_STATE_OBJECT_CONFIG + D3D12_STATE_SUBOBJECT_TYPE_GLOBAL_ROOT_SIGNATURE = 1, // D3D12_GLOBAL_ROOT_SIGNATURE + D3D12_STATE_SUBOBJECT_TYPE_LOCAL_ROOT_SIGNATURE = 2, // D3D12_LOCAL_ROOT_SIGNATURE + D3D12_STATE_SUBOBJECT_TYPE_NODE_MASK = 3, // D3D12_NODE_MASK + D3D12XBOX_STATE_SUBOBJECT_TYPE_RAYTRACING_OPTIONS = 4, // 4 unused D3D12XBOX_STATE_SUBOBJECT_TYPE_OPTIONS + D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY = 5, // D3D12_DXIL_LIBRARY_DESC + D3D12_STATE_SUBOBJECT_TYPE_EXISTING_COLLECTION = 6, // D3D12_EXISTING_COLLECTION_DESC + D3D12_STATE_SUBOBJECT_TYPE_SUBOBJECT_TO_EXPORTS_ASSOCIATION = 7, // D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION + D3D12_STATE_SUBOBJECT_TYPE_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION = 8, // D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION + D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_SHADER_CONFIG = 9, // D3D12_RAYTRACING_SHADER_CONFIG + D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_PIPELINE_CONFIG = 10, // D3D12_RAYTRACING_PIPELINE_CONFIG + D3D12_STATE_SUBOBJECT_TYPE_HIT_GROUP = 11, // D3D12_HIT_GROUP_DESC + D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_PIPELINE_CONFIG1 = 12, // D3D12_RAYTRACING_PIPELINE_CONFIG1 + D3D12_STATE_SUBOBJECT_TYPE_MAX_VALID, +} D3D12_STATE_SUBOBJECT_TYPE; + +typedef struct D3D12_STATE_SUBOBJECT +{ + D3D12_STATE_SUBOBJECT_TYPE Type; + const void* pDesc; +} D3D12_STATE_SUBOBJECT; + +typedef enum D3D12_STATE_OBJECT_FLAGS +{ + D3D12_STATE_OBJECT_FLAG_NONE = 0x0, + D3D12_STATE_OBJECT_FLAG_ALLOW_LOCAL_DEPENDENCIES_ON_EXTERNAL_DEFINITIONS = 0x1, + D3D12_STATE_OBJECT_FLAG_ALLOW_EXTERNAL_DEPENDENCIES_ON_LOCAL_DEFINITIONS = 0x2, + D3D12_STATE_OBJECT_FLAG_ALLOW_STATE_OBJECT_ADDITIONS = 0x4, +} D3D12_STATE_OBJECT_FLAGS; + +typedef struct D3D12_STATE_OBJECT_CONFIG +{ + D3D12_STATE_OBJECT_FLAGS Flags; +} D3D12_STATE_OBJECT_CONFIG; + +typedef struct D3D12_GLOBAL_ROOT_SIGNATURE +{ + ID3D12RootSignature* pGlobalRootSignature; +} D3D12_GLOBAL_ROOT_SIGNATURE; + +typedef struct D3D12_LOCAL_ROOT_SIGNATURE +{ + ID3D12RootSignature* pLocalRootSignature; +} D3D12_LOCAL_ROOT_SIGNATURE; + +typedef struct D3D12_NODE_MASK +{ + UINT NodeMask; +} D3D12_NODE_MASK; + +typedef enum D3D12_EXPORT_FLAGS +{ + D3D12_EXPORT_FLAG_NONE = 0x0, +} D3D12_EXPORT_FLAGS; + +typedef struct D3D12_EXPORT_DESC +{ + LPCWSTR Name; + _In_opt_ LPCWSTR ExportToRename; + D3D12_EXPORT_FLAGS Flags; +} D3D12_EXPORT_DESC; + +typedef struct D3D12_DXIL_LIBRARY_DESC +{ + D3D12_SHADER_BYTECODE DXILLibrary; + UINT NumExports; // Optional, if 0 all exports in the library/collection will be surfaced + _In_reads_(NumExports) D3D12_EXPORT_DESC* pExports; +} D3D12_DXIL_LIBRARY_DESC; + +typedef struct D3D12_EXISTING_COLLECTION_DESC +{ + ID3D12StateObject* pExistingCollection; + UINT NumExports; // Optional, if 0 all exports in the library/collection will be surfaced + _In_reads_(NumExports) D3D12_EXPORT_DESC* pExports; +} D3D12_EXISTING_COLLECTION_DESC; + +typedef struct D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION +{ + const D3D12_STATE_SUBOBJECT* pSubobjectToAssociate; + UINT NumExports; + _In_reads_(NumExports) LPCWSTR* pExports; +} D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION; + +typedef struct D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION +{ + LPCWSTR SubobjectToAssociate; + UINT NumExports; + _In_reads_(NumExports) LPCWSTR* pExports; +} D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION; + +typedef enum D3D12_HIT_GROUP_TYPE +{ + D3D12_HIT_GROUP_TYPE_TRIANGLES = 0x0, + D3D12_HIT_GROUP_TYPE_PROCEDURAL_PRIMITIVE = 0x1, +} D3D12_HIT_GROUP_TYPE; + +typedef struct D3D12_HIT_GROUP_DESC +{ + LPCWSTR HitGroupExport; + D3D12_HIT_GROUP_TYPE Type; + _In_opt_ LPCWSTR AnyHitShaderImport; + _In_opt_ LPCWSTR ClosestHitShaderImport; + _In_opt_ LPCWSTR IntersectionShaderImport; +} D3D12_HIT_GROUP_DESC; + +typedef struct D3D12_RAYTRACING_SHADER_CONFIG +{ + UINT MaxPayloadSizeInBytes; + UINT MaxAttributeSizeInBytes; +} D3D12_RAYTRACING_SHADER_CONFIG; + +typedef struct D3D12_RAYTRACING_PIPELINE_CONFIG +{ + UINT MaxTraceRecursionDepth; +} D3D12_RAYTRACING_PIPELINE_CONFIG; + +typedef enum D3D12_RAYTRACING_PIPELINE_FLAGS +{ + D3D12_RAYTRACING_PIPELINE_FLAG_NONE = 0x0, + D3D12_RAYTRACING_PIPELINE_FLAG_SKIP_TRIANGLES = 0x100, + D3D12_RAYTRACING_PIPELINE_FLAG_SKIP_PROCEDURAL_PRIMITIVES = 0x200, +} D3D12_RAYTRACING_PIPELINE_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS( D3D12_RAYTRACING_PIPELINE_FLAGS ); + +typedef struct D3D12_RAYTRACING_PIPELINE_CONFIG1 +{ + UINT MaxTraceRecursionDepth; + D3D12_RAYTRACING_PIPELINE_FLAGS Flags; +} D3D12_RAYTRACING_PIPELINE_CONFIG1; + +typedef enum D3D12_STATE_OBJECT_TYPE +{ + D3D12_STATE_OBJECT_TYPE_COLLECTION = 0, + // D3D12_STATE_OBJECT_TYPE_COMPUTE_PIPELINE = 1, + // D3D12_STATE_OBJECT_TYPE_GRAPHICS_PIPELINE = 2, + D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE = 3, +} D3D12_STATE_OBJECT_TYPE; + +typedef struct D3D12_STATE_OBJECT_DESC +{ + D3D12_STATE_OBJECT_TYPE Type; + UINT NumSubobjects; + _In_reads_(NumSubobjects) const D3D12_STATE_SUBOBJECT* pSubobjects; +} D3D12_STATE_OBJECT_DESC; + +typedef enum D3D12_RAYTRACING_GEOMETRY_FLAGS +{ + D3D12_RAYTRACING_GEOMETRY_FLAG_NONE = 0x0, + D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE = 0x1, + D3D12_RAYTRACING_GEOMETRY_FLAG_NO_DUPLICATE_ANYHIT_INVOCATION = 0x2 +} D3D12_RAYTRACING_GEOMETRY_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS( D3D12_RAYTRACING_GEOMETRY_FLAGS ); + +typedef enum D3D12_RAYTRACING_GEOMETRY_TYPE +{ + D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES, + D3D12_RAYTRACING_GEOMETRY_TYPE_PROCEDURAL_PRIMITIVE_AABBS, +} D3D12_RAYTRACING_GEOMETRY_TYPE; + +#define D3D12XBOX_RAYTRACING_INSTANCE_FLAG_TAPU4_DEFINED +#define D3D12XBOX_RAYTRACING_INSTANCE_FLAG_TAPU4_MASK (3 << 6) + +typedef enum D3D12_RAYTRACING_INSTANCE_FLAGS +{ + D3D12_RAYTRACING_INSTANCE_FLAG_NONE = 0x0, + D3D12_RAYTRACING_INSTANCE_FLAG_TRIANGLE_CULL_DISABLE = 0x1, + D3D12_RAYTRACING_INSTANCE_FLAG_TRIANGLE_FRONT_COUNTERCLOCKWISE = 0x2, + D3D12_RAYTRACING_INSTANCE_FLAG_FORCE_OPAQUE = 0x4, + D3D12_RAYTRACING_INSTANCE_FLAG_FORCE_NON_OPAQUE = 0x8 + , + // Xbox extended flags + // Possibly a temporary hint to the builder to forcibly rebraid (pull up blas into tlas) this instance + D3D12XBOX_RAYTRACING_INSTANCE_FLAG_TAPU4 = 0x40, + D3D12XBOX_RAYTRACING_INSTANCE_FLAG_TAPU16 = 0xC0, + D3D12XBOX_RAYTRACING_INSTANCE_FLAG_TAPU_RESERVED = 0x80 +} D3D12_RAYTRACING_INSTANCE_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS( D3D12_RAYTRACING_INSTANCE_FLAGS ); + +typedef struct D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE +{ + D3D12_GPU_VIRTUAL_ADDRESS StartAddress; + UINT64 StrideInBytes; +} D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE; + +typedef struct D3D12_GPU_VIRTUAL_ADDRESS_RANGE +{ + D3D12_GPU_VIRTUAL_ADDRESS StartAddress; + UINT64 SizeInBytes; +} D3D12_GPU_VIRTUAL_ADDRESS_RANGE; + +typedef struct D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE +{ + D3D12_GPU_VIRTUAL_ADDRESS StartAddress; + UINT64 SizeInBytes; + UINT64 StrideInBytes; +} D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE; + +typedef struct D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC +{ + D3D12_GPU_VIRTUAL_ADDRESS Transform3x4; + DXGI_FORMAT IndexFormat; + DXGI_FORMAT VertexFormat; + UINT IndexCount; + UINT VertexCount; + D3D12_GPU_VIRTUAL_ADDRESS IndexBuffer; + D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE VertexBuffer; +} D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC; + +typedef struct D3D12_RAYTRACING_AABB +{ + FLOAT MinX; + FLOAT MinY; + FLOAT MinZ; + FLOAT MaxX; + FLOAT MaxY; + FLOAT MaxZ; +} D3D12_RAYTRACING_AABB; + +typedef struct D3D12_RAYTRACING_GEOMETRY_AABBS_DESC +{ + UINT64 AABBCount; + D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE AABBs; +} D3D12_RAYTRACING_GEOMETRY_AABBS_DESC; + +typedef enum D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS +{ + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_NONE = 0x00, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE = 0x01, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION = 0x02, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE = 0x04, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD = 0x08, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY = 0x10, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE = 0x20, + D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_DEHYDRATE = 0x40000000, + +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS( D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS ); + +typedef enum D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE +{ + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE = 0x0, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT = 0x1, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_VISUALIZATION_DECODE_FOR_TOOLS = 0x2, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE = 0x3, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_DESERIALIZE = 0x4, + + // The following are deprecated and to be removed in June 2024 + D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE_AND_COMPRESS = 0x80000005, + D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE_AND_COMPRESS_FOR_GPU = 0x80000006, +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE; + +typedef enum D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE +{ + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL = 0x0, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL = 0x1 +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE; + +typedef enum D3D12_ELEMENTS_LAYOUT +{ + D3D12_ELEMENTS_LAYOUT_ARRAY = 0x0, + D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS = 0x1 +} D3D12_ELEMENTS_LAYOUT; + +typedef enum D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE +{ + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE = 0x0, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION = 0x1, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION = 0x2, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE = 0x3, + + D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_OFFLINE_STATISTICS = 0x10 +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE; + +typedef struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC +{ + D3D12_GPU_VIRTUAL_ADDRESS DestBuffer; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE InfoType; +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC; + +typedef struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE_DESC +{ + UINT64 CompactedSizeInBytes; +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE_DESC; + +typedef struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION_DESC +{ + UINT64 DecodedSizeInBytes; +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION_DESC; + +typedef struct D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_TOOLS_VISUALIZATION_HEADER +{ + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE Type; + UINT NumDescs; +} D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_TOOLS_VISUALIZATION_HEADER; + +typedef struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION_DESC +{ + UINT64 SerializedSizeInBytes; + UINT64 NumBottomLevelAccelerationStructurePointers; +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION_DESC; + +typedef struct D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_OFFLINE_STATISTICS_DESC +{ + UINT NumTriangles; + UINT NumGeometries; + UINT NumLeaves; + UINT NumLeafBounds; + UINT NumFP16Nodes; + UINT NumFP32Nodes; + + FLOAT TreeSAH; +} D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_OFFLINE_STATISTICS_DESC; + +typedef struct D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER +{ + GUID DriverOpaqueGUID; + BYTE DriverOpaqueVersioningData[16]; +} D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER; + +typedef enum D3D12_SERIALIZED_DATA_TYPE +{ + D3D12_SERIALIZED_DATA_RAYTRACING_ACCELERATION_STRUCTURE = 0x0, +} D3D12_SERIALIZED_DATA_TYPE; + +typedef enum D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS +{ + D3D12_DRIVER_MATCHING_IDENTIFIER_COMPATIBLE_WITH_DEVICE = 0x0, + D3D12_DRIVER_MATCHING_IDENTIFIER_UNSUPPORTED_TYPE = 0x1, + D3D12_DRIVER_MATCHING_IDENTIFIER_UNRECOGNIZED = 0x2, + D3D12_DRIVER_MATCHING_IDENTIFIER_INCOMPATIBLE_VERSION = 0x3, + D3D12_DRIVER_MATCHING_IDENTIFIER_INCOMPATIBLE_TYPE = 0x4, +} D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS; + +typedef struct D3D12_SERIALIZED_RAYTRACING_ACCELERATION_STRUCTURE_HEADER +{ + D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER DriverMatchingIdentifier; + UINT64 SerializedSizeInBytesIncludingHeader; + UINT64 DeserializedSizeInBytes; + UINT64 NumBottomLevelAccelerationStructurePointersAfterHeader; +} D3D12_SERIALIZED_RAYTRACING_ACCELERATION_STRUCTURE_HEADER; + +typedef struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE_DESC +{ + UINT64 CurrentSizeInBytes; +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE_DESC; + +typedef struct D3D12_RAYTRACING_INSTANCE_DESC +{ + FLOAT Transform[3][4]; + UINT InstanceID : 24; + UINT InstanceMask : 8; + UINT InstanceContributionToHitGroupIndex : 24; + UINT Flags : 8; + D3D12_GPU_VIRTUAL_ADDRESS AccelerationStructure; +} D3D12_RAYTRACING_INSTANCE_DESC; + +typedef struct D3D12_RAYTRACING_GEOMETRY_DESC +{ + D3D12_RAYTRACING_GEOMETRY_TYPE Type; + D3D12_RAYTRACING_GEOMETRY_FLAGS Flags; + union + { + D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC Triangles; + D3D12_RAYTRACING_GEOMETRY_AABBS_DESC AABBs; + }; +} D3D12_RAYTRACING_GEOMETRY_DESC; + +typedef struct D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS +{ + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE Type; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS Flags; + UINT NumDescs; + D3D12_ELEMENTS_LAYOUT DescsLayout; + union + { + D3D12_GPU_VIRTUAL_ADDRESS InstanceDescs; + const D3D12_RAYTRACING_GEOMETRY_DESC* pGeometryDescs; + const D3D12_RAYTRACING_GEOMETRY_DESC*const* ppGeometryDescs; + }; +} D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS; + +typedef struct D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC +{ + D3D12_GPU_VIRTUAL_ADDRESS DestAccelerationStructureData; + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS Inputs; + _In_opt_ D3D12_GPU_VIRTUAL_ADDRESS SourceAccelerationStructureData; + D3D12_GPU_VIRTUAL_ADDRESS ScratchAccelerationStructureData; +} D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC; + +typedef struct D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO +{ + UINT64 ResultDataMaxSizeInBytes; + UINT64 ScratchDataSizeInBytes; + UINT64 UpdateScratchDataSizeInBytes; +} D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO; + +typedef enum D3D12_RAY_FLAGS +{ + D3D12_RAY_FLAG_NONE = 0x00, + D3D12_RAY_FLAG_FORCE_OPAQUE = 0x01, + D3D12_RAY_FLAG_FORCE_NON_OPAQUE = 0x02, + D3D12_RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH = 0x04, + D3D12_RAY_FLAG_SKIP_CLOSEST_HIT_SHADER = 0x08, + D3D12_RAY_FLAG_CULL_BACK_FACING_TRIANGLES = 0x10, + D3D12_RAY_FLAG_CULL_FRONT_FACING_TRIANGLES = 0x20, + D3D12_RAY_FLAG_CULL_OPAQUE = 0x40, + D3D12_RAY_FLAG_CULL_NON_OPAQUE = 0x80, + D3D12_RAY_FLAG_SKIP_TRIANGLES = 0x100, + D3D12_RAY_FLAG_SKIP_PROCEDURAL_PRIMITIVES = 0x200, + + D3D12XBOX_RAY_FLAG_COHERENT_RAYS_HINT = 0x1000, +} D3D12_RAY_FLAGS; + +typedef enum D3D12XBOX_RAYTRACING_OPTIONS_TRAVERSE_TYPE +{ + D3D12XBOX_RAYTRACING_OPTIONS_TRAVERSE_TYPE_TRAVERSE_DEFAULT = 0, + D3D12XBOX_RAYTRACING_OPTIONS_TRAVERSE_TYPE_TRAVERSE_ALWAYS_HIT = 1, + D3D12XBOX_RAYTRACING_OPTIONS_TRAVERSE_TYPE_TRAVERSE_FORCE_ANYHIT = 2 +} D3D12XBOX_RAYTRACING_OPTIONS_TRAVERSE_TYPE; + +typedef struct D3D12XBOX_RAYTRACING_OPTIONS +{ + D3D12XBOX_RAYTRACING_OPTIONS_TRAVERSE_TYPE traverseType : 4; + BOOL shortStack : 1; +} D3D12XBOX_RAYTRACING_OPTIONS; + +typedef struct D3D12XBOX_RAYTRACING_FP16_AABB +{ + USHORT MinX; + USHORT MinY; + USHORT MinZ; + USHORT MaxX; + USHORT MaxY; + USHORT MaxZ; +} D3D12XBOX_RAYTRACING_FP16_AABB; + +typedef enum D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE_TYPE +{ + D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE_TYPE_TRIANGLE = 0, + D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE_TYPE_FP16_AABB = 1, + D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE_TYPE_FP32_AABB = 3, + D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE_TYPE_QUAD = 4 +} D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE_TYPE; + +typedef struct D3D12XBOX_RAYTRACING_CANONICAL_TRIANGLE_NODE_DATA +{ + float VertexPositions[5][3]; + UINT PrimitiveIndices[4]; + unsigned char RemapIndices[4][2]; + UINT GeometryIndex; +} D3D12XBOX_RAYTRACING_CANONICAL_TRIANGLE_NODE_DATA; + +struct D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE; + +typedef struct D3D12XBOX_RAYTRACING_CANONICAL_FP16_AABB_DATA +{ + D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE* ChildNodes[4]; + unsigned char TriangleIndices[4]; + D3D12XBOX_RAYTRACING_FP16_AABB AABBs[4]; +} D3D12XBOX_RAYTRACING_CANONICAL_FP16_AABB_DATA; + +typedef struct D3D12XBOX_RAYTRACING_CANONICAL_FP32_AABB_DATA +{ + D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE* ChildNodes[4]; + unsigned char TriangleIndices[4]; + D3D12_RAYTRACING_AABB AABBs[4]; + UINT UnreservedSpace[4]; +} D3D12XBOX_RAYTRACING_CANONICAL_FP32_AABB_DATA; + +typedef struct D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE +{ + D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE_TYPE Type; + + union + { + D3D12XBOX_RAYTRACING_CANONICAL_TRIANGLE_NODE_DATA TriangleNodeData; + D3D12XBOX_RAYTRACING_CANONICAL_FP16_AABB_DATA FP16AABBData; + D3D12XBOX_RAYTRACING_CANONICAL_FP32_AABB_DATA FP32AABBData; + }; +} D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE; + +typedef enum D3D12_HIT_KIND +{ + D3D12_HIT_KIND_TRIANGLE_FRONT_FACE = 0xfe, + D3D12_HIT_KIND_TRIANGLE_BACK_FACE = 0xff, +} D3D12_HIT_KIND; + + +} + +extern "C" +{ + +// +// ID3D12Device5 +// + +struct D3D12Device5_Function_Table +{ + D3D12Device4_Function_Table DeviceFunction; + + HRESULT (D3DAPI* CreateLifetimeTracker)( + _Inout_ ID3D12Device5* pDevice5, + _In_ ID3D12LifetimeOwner* pOwner, + REFIID riid, + _Outptr_ void** ppvTracker); + + void (D3DAPI* RemoveDevice)( + _Inout_ ID3D12Device5* pDevice5); + + HRESULT (D3DAPI* EnumerateMetaCommands)( + _Inout_ ID3D12Device5* pDevice5, + _Inout_ UINT* pNumMetaCommands, + _Out_writes_opt_(*pNumMetaCommands) D3D12_META_COMMAND_DESC* pDescs); + + HRESULT (D3DAPI* EnumerateMetaCommandParameters)( + _Inout_ ID3D12Device5* pDevice5, + _In_ REFGUID CommandId, + _In_ D3D12_META_COMMAND_PARAMETER_STAGE Stage, + _Out_opt_ UINT* pTotalStructureSizeInBytes, + _Inout_ UINT* pParameterCount, + _Out_writes_opt_(*pParameterCount) D3D12_META_COMMAND_PARAMETER_DESC* pParameterDescs); + + HRESULT (D3DAPI* CreateMetaCommand)( + _Inout_ ID3D12Device5* pDevice5, + _In_ REFGUID CommandId, + _In_ UINT NodeMask, + _In_reads_bytes_opt_(CreationParametersDataSizeInBytes) const void * pCreationParametersData, + _In_ SIZE_T CreationParametersDataSizeInBytes, + REFIID riid, + _Outptr_ void** ppMetaCommand); + + HRESULT (D3DAPI* CreateStateObject)( + _Inout_ ID3D12Device5* pDevice5, + const D3D12_STATE_OBJECT_DESC* pDesc, + REFIID riid, + _Outptr_ void** ppStateObject); + + void (D3DAPI* GetRaytracingAccelerationStructurePrebuildInfo)( + _Inout_ ID3D12Device5* pDevice5, + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* pDesc, + _Out_ D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* pInfo); + + D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS (D3DAPI* CheckDriverMatchingIdentifier)( + _Inout_ ID3D12Device5* pDevice5, + _In_ D3D12_SERIALIZED_DATA_TYPE SerializedDataType, + _In_ const D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER* pIdentifierToCheck); + + // Deprecated, leaving the slot alone and unused + HRESULT (D3DAPI* StoreDXRStateObjectDescX_DeprecatedUnused)( + _Inout_ ID3D12Device5*, + _In_ const void*, + _Inout_ void*); +}; + + +} // extern C + +D3DINTERFACE(ID3D12Device5, 8b4f173b,2fea,4b80,8f,58,43,07,19,1a,b9,5d) : public ID3D12Device4 +{ +public: + + D3DINLINE D3D12Device5_Function_Table* Device5Function() + { + return (D3D12Device5_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI CreateLifetimeTracker( + _In_ ID3D12LifetimeOwner* pOwner, + REFIID riid, + _Outptr_ void** ppvTracker) + { + return Device5Function()->CreateLifetimeTracker( + this, + pOwner, + riid, + ppvTracker); + } + + D3DINLINE void D3DAPI RemoveDevice() + { + return Device5Function()->RemoveDevice(this); + } + + D3DINLINE HRESULT D3DAPI EnumerateMetaCommands( + _Inout_ UINT* pNumMetaCommands, + _Out_writes_opt_(*pNumMetaCommands) D3D12_META_COMMAND_DESC* pDescs) + { + return Device5Function()->EnumerateMetaCommands( + this, + pNumMetaCommands, + pDescs); + } + + D3DINLINE HRESULT D3DAPI EnumerateMetaCommandParameters( + _In_ REFGUID CommandId, + _In_ D3D12_META_COMMAND_PARAMETER_STAGE Stage, + _Out_opt_ UINT* pTotalStructureSizeInBytes, + _Inout_ UINT* pParameterCount, + _Out_writes_opt_(*pParameterCount) D3D12_META_COMMAND_PARAMETER_DESC* pParameterDescs) + { + return Device5Function()->EnumerateMetaCommandParameters( + this, + CommandId, + Stage, + pTotalStructureSizeInBytes, + pParameterCount, + pParameterDescs); + } + + D3DINLINE HRESULT D3DAPI CreateMetaCommand( + _In_ REFGUID CommandId, + _In_ UINT NodeMask, + _In_reads_bytes_opt_(CreationParametersDataSizeInBytes) const void * pCreationParametersData, + _In_ SIZE_T CreationParametersDataSizeInBytes, + REFIID riid, + _Outptr_ void** ppMetaCommand) + { + return Device5Function()->CreateMetaCommand( + this, + CommandId, + NodeMask, + pCreationParametersData, + CreationParametersDataSizeInBytes, + riid, + ppMetaCommand); + } + + D3DINLINE HRESULT D3DAPI CreateStateObject( + const D3D12_STATE_OBJECT_DESC* pDesc, + REFIID riid, + _Outptr_ void** ppStateObject) + { + return Device5Function()->CreateStateObject( + this, + pDesc, + riid, + ppStateObject); + } + + D3DINLINE void D3DAPI GetRaytracingAccelerationStructurePrebuildInfo( + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* pDesc, + _Out_ D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* pInfo) + { + return Device5Function()->GetRaytracingAccelerationStructurePrebuildInfo( + this, + pDesc, + pInfo); + } + + D3DINLINE D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS D3DAPI CheckDriverMatchingIdentifier( + _In_ D3D12_SERIALIZED_DATA_TYPE SerializedDataType, + _In_ const D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER* pIdentifierToCheck) + { + return Device5Function()->CheckDriverMatchingIdentifier( + this, + SerializedDataType, + pIdentifierToCheck); + } +}; + +extern "C" +{ + +typedef enum D3D12_BACKGROUND_PROCESSING_MODE +{ + D3D12_BACKGROUND_PROCESSING_MODE_ALLOWED, + D3D12_BACKGROUND_PROCESSING_MODE_ALLOW_INTRUSIVE_MEASUREMENTS, + D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK, + D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_PROFILING_BY_SYSTEM, +} D3D12_BACKGROUND_PROCESSING_MODE; + +typedef enum D3D12_MEASUREMENTS_ACTION +{ + D3D12_MEASUREMENTS_ACTION_KEEP_ALL, + D3D12_MEASUREMENTS_ACTION_COMMIT_RESULTS, + D3D12_MEASUREMENTS_ACTION_COMMIT_RESULTS_HIGH_PRIORITY, + D3D12_MEASUREMENTS_ACTION_DISCARD_PREVIOUS, +} D3D12_MEASUREMENTS_ACTION; + +// +// ID3D12Device6 +// + +struct D3D12Device6_Function_Table +{ + D3D12Device5_Function_Table DeviceFunction; + + HRESULT (D3DAPI* SetBackgroundProcessingMode)( + ID3D12Device6* pDevice, + D3D12_BACKGROUND_PROCESSING_MODE Mode, + D3D12_MEASUREMENTS_ACTION MeasurementsAction, + _In_opt_ HANDLE hEventToSignalUponCompletion, + _Out_opt_ BOOL* pbFurtherMeasurementsDesired); +}; + + +} // extern C + +D3DINTERFACE(ID3D12Device6, c70b221b,40e4,4a17,89,af,02,5a,07,27,a6,dc) : public ID3D12Device5 +{ +public: + + D3DINLINE D3D12Device6_Function_Table* Device6Function() + { + return (D3D12Device6_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT SetBackgroundProcessingMode( + D3D12_BACKGROUND_PROCESSING_MODE Mode, + D3D12_MEASUREMENTS_ACTION MeasurementsAction, + _In_opt_ HANDLE hEventToSignalUponCompletion, + _Out_opt_ BOOL* pbFurtherMeasurementsDesired) + { + return Device6Function()->SetBackgroundProcessingMode(this, Mode, MeasurementsAction, hEventToSignalUponCompletion, pbFurtherMeasurementsDesired); + } +}; + +extern "C" +{ + +// +// ID3D12Device7 +// + +struct D3D12Device7_Function_Table +{ + D3D12Device6_Function_Table DeviceFunction; + + HRESULT (D3DAPI *AddToStateObject)( + ID3D12Device7* pDevice, + _In_ const D3D12_STATE_OBJECT_DESC* pAddition, + _In_ ID3D12StateObject* pStateObjectToGrowFrom, + _In_ REFIID riid, // ID3D12StateObject + _Outptr_ void** ppNewStateObject + ); + + HRESULT (D3DAPI *CreateProtectedResourceSession1)( + ID3D12Device7* pDevice, + _In_ const D3D12_PROTECTED_RESOURCE_SESSION_DESC1* pDesc, + _In_ REFIID riid, // Expected: ID3D12ProtectedResourceSession1, + _Outptr_ void** ppSession + ); +}; + + +} // extern C + +D3DINTERFACE(ID3D12Device7, 5c014b53,68a1,4b9b,8b,d1,dd,60,46,b9,35,8b) : public ID3D12Device6 +{ +public: + + D3DINLINE D3D12Device7_Function_Table* Device7Function() + { + return (D3D12Device7_Function_Table*)m_pFunction; + } + + HRESULT AddToStateObject( + _In_ const D3D12_STATE_OBJECT_DESC* pAddition, + _In_ ID3D12StateObject* pStateObjectToGrowFrom, + _In_ REFIID riid, // ID3D12StateObject + _Outptr_ void** ppNewStateObject + ) + { + return Device7Function()->AddToStateObject(this, pAddition, pStateObjectToGrowFrom, riid, ppNewStateObject); + } + + HRESULT CreateProtectedResourceSession1( + _In_ const D3D12_PROTECTED_RESOURCE_SESSION_DESC1* pDesc, + _In_ REFIID riid, // Expected: ID3D12ProtectedResourceSession1, + _Outptr_ void** ppSession + ) + { + return Device7Function()->CreateProtectedResourceSession1(this, pDesc, riid, ppSession); + } +}; + + + + +// +// Regular blob like PC ID3D10Blob and IDxcBlob that uses virtual functions and not a function pointers table +// XDXR's backend can be built against PC headers so overloading ID3DBlob becomes basically different code +// So use this interface which is compatible with DXC and PC D3D blobs. It shouldn't make a difference to the +// caller but it helps keep implementation stable. +// +struct IXDXRBlob : public IUnknown +{ + virtual LPVOID STDMETHODCALLTYPE GetBufferPointer() = 0; + virtual SIZE_T STDMETHODCALLTYPE GetBufferSize() = 0; +}; + + +typedef struct D3D12XBOX_XDXR_STREAM_DESC +{ + _In_ SIZE_T SizeInBytes; + _In_reads_(_Inexpressible_("Dependent on size of subobjects")) const void* pXdxrStreamDesc; +} D3D12XBOX_XDXR_STREAM_DESC; + + +typedef struct D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2 +{ + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC Desc; + UINT NumPostbuildInfoDescs; + const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* pPostbuildInfoDescs; + D3D12XBOX_XDXR_STREAM_DESC ExtraOptions; +} D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2; + +typedef enum D3D12XBOX_REGISTER_PAGE_POOL_FLAGS +{ + D3D12XBOX_REGISTER_PAGE_POOL_FLAG_NONE = 0, + D3D12XBOX_REGISTER_PAGE_POOL_FLAG_2MB_PAGES = 1, +} D3D12XBOX_REGISTER_PAGE_POOL_FLAGS; + +extern "C" +{ + +// +// ID3D12Device8 +// + +struct D3D12Device8_Function_Table +{ + D3D12Device7_Function_Table DeviceFunction; + + D3D12_RESOURCE_ALLOCATION_INFO (D3DAPI* GetResourceAllocationInfo2)( + ID3D12Device8* pDevice, + UINT visibleMask, + UINT numResourceDescs, + _In_reads_(numResourceDescs) const D3D12_RESOURCE_DESC1* pResourceDescs, + _Out_writes_opt_(numResourceDescs) D3D12_RESOURCE_ALLOCATION_INFO1* pResourceAllocationInfo1); + + HRESULT (D3DAPI* CreateCommittedResource2)( + ID3D12Device8* pDevice, + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_RESOURCE_STATES InitialResourceState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + _In_ REFIID riidResource, // Expected: ID3D12Resource1* + _Outptr_ void** ppvResource); + + HRESULT (D3DAPI* CreatePlacedResource1)( + ID3D12Device8* pDevice, + _In_ ID3D12Heap* pHeap, + UINT64 HeapOffset, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_ REFIID riid, // Expected: ID3D12Resource* + _Outptr_ void** ppvResource); + + void (D3DAPI* CreateSamplerFeedbackUnorderedAccessViewX)( + ID3D12Device8* pDevice, + _In_opt_ ID3D12Resource* pTargetedResource, + _In_opt_ ID3D12Resource* pFeedbackResource, + _In_opt_ const D3D12_UNORDERED_ACCESS_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + void (D3DAPI* GetCopyableFootprints1)( + ID3D12Device8* pDevice, + _In_ const D3D12_RESOURCE_DESC1* pResourceDesc, + _In_range_(0, D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0, D3D12_REQ_SUBRESOURCES - FirstSubresource) UINT NumSubresources, + UINT64 BaseOffset, + _Out_writes_opt_(NumSubresources) D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts, + _Out_writes_opt_(NumSubresources) UINT* pNumRows, + _Out_writes_opt_(NumSubresources) UINT64* pRowSizeInBytes, + _Out_opt_ UINT64* pTotalBytes); + + void (D3DAPI* CreateMinMipShaderResourceViewX)( + ID3D12Device8* pDevice, + _In_opt_ ID3D12Resource* pTargetedResource, + _In_opt_ const D3D12_RESOURCE_DESC* pTargetedResourceDesc, + _In_opt_ ID3D12Resource* pMinMipResource, + _In_opt_ const D3D12_SHADER_RESOURCE_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor); + + HRESULT (D3DAPI *SerializeStateObjectX)( + ID3D12Device8* pDevice, + _In_ ID3D12StateObject* pStateObjectToSerialize, + _In_ UINT Flags, + _Out_ IXDXRBlob** ppOutput); + + HRESULT (D3DAPI *DeserializeStateObjectX)( + ID3D12Device8* pDevice, + _In_ const void* pSourceData, + _In_ UINT sourceDataSize, + ID3D12RootSignature* pRootSignature, + _In_ UINT Flags, + _In_ REFIID riid, + _In_ void** ppStateObjectFromSerialized); + + void (D3DAPI* GetRaytracingAccelerationStructurePrebuildInfoX)( + _Inout_ ID3D12Device8* pDevice8, + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* pInputs, + _In_ const D3D12XBOX_XDXR_STREAM_DESC* pExtraOptions, + _Out_ D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* pInfo); + + UINT (D3DAPI* GetShaderResourceViewPRTLODIndexX)( + _Inout_ ID3D12Device8* pDevice8, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE Descriptor); + + void (D3DAPI* SetShaderResourceViewPRTLODIndexX)( + _Inout_ ID3D12Device8* pDevice8, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor, + _In_ UINT Index); + + HRESULT(D3DAPI* AddBlobToGpuHangDumpX)( + _Inout_ ID3D12Device8* pDevice8, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Address, + _In_ UINT SizeBytes, + _In_ UINT64 Metadata); + + HRESULT(D3DAPI* RegisterPagePool2X)( + _Inout_ ID3D12Device* pDevice, + _In_ D3D12_GPU_VIRTUAL_ADDRESS PagePoolAddress, + _In_ UINT PagePoolPageCount, + _In_ D3D12XBOX_REGISTER_PAGE_POOL_FLAGS Flags, + _Out_ HANDLE* pPagePoolHandle); + + void (D3DAPI* SetShaderRecompileCallbackX)( + _Inout_ ID3D12Device8* pDevice, + _In_ D3D12XBOX_SHADER_RECOMPILE_CALLBACK pRecompileCallback); + + void (D3DAPI* SetCompileTimeShaderPdbPathX)( + _Inout_ ID3D12Device8* pDevice, + _In_ const wchar_t* pShaderPdbPath); + + HRESULT (D3DAPI* XboxReserved1)( + _Inout_ ID3D12Device8* pDevice, + _In_ D3D12XBOX_RESERVED1 Argument1); +}; + + +} // extern C + +D3DINTERFACE(ID3D12Device8, 728f1fa2,ea11,4a9f,9b,52,9b,42,a4,84,d5,c9) : public ID3D12Device7 +{ +public: + + D3DINLINE D3D12Device8_Function_Table* Device8Function() + { + return (D3D12Device8_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_RESOURCE_ALLOCATION_INFO GetResourceAllocationInfo2( + UINT visibleMask, + UINT numResourceDescs, + _In_reads_(numResourceDescs) const D3D12_RESOURCE_DESC1* pResourceDescs, + _Out_writes_opt_(numResourceDescs) D3D12_RESOURCE_ALLOCATION_INFO1* pResourceAllocationInfo1) + { + return Device8Function()->GetResourceAllocationInfo2(this, visibleMask, numResourceDescs, pResourceDescs, pResourceAllocationInfo1); + } + + D3DINLINE HRESULT CreateCommittedResource2( + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_RESOURCE_STATES InitialResourceState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + _In_ REFIID riidResource, // Expected: ID3D12Resource1* + _Outptr_ void** ppvResource) + { + return Device8Function()->CreateCommittedResource2(this, pHeapProperties, HeapFlags, pDesc, InitialResourceState, pOptimizedClearValue, pProtectedSession, riidResource, ppvResource); + } + + D3DINLINE HRESULT CreatePlacedResource1( + _In_ ID3D12Heap* pHeap, + UINT64 HeapOffset, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_RESOURCE_STATES InitialState, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_ REFIID riid, // Expected: ID3D12Resource* + _Outptr_ void** ppvResource) + { + return Device8Function()->CreatePlacedResource1(this, pHeap, HeapOffset, pDesc, InitialState, pOptimizedClearValue, riid, ppvResource); + } + + D3DINLINE void CreateSamplerFeedbackUnorderedAccessView( + _In_opt_ ID3D12Resource* pTargetedResource, + _In_opt_ ID3D12Resource* pFeedbackResource, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + Device8Function()->CreateSamplerFeedbackUnorderedAccessViewX(this, pTargetedResource, pFeedbackResource, nullptr, DestDescriptor); + } + + D3DINLINE void CreateSamplerFeedbackUnorderedAccessViewX( + _In_opt_ ID3D12Resource* pTargetedResource, + _In_opt_ ID3D12Resource* pFeedbackResource, + _In_opt_ const D3D12_UNORDERED_ACCESS_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + Device8Function()->CreateSamplerFeedbackUnorderedAccessViewX(this, pTargetedResource, pFeedbackResource, pDesc, DestDescriptor); + } + + D3DINLINE void GetCopyableFootprints1( + _In_ const D3D12_RESOURCE_DESC1* pResourceDesc, + _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, + UINT64 BaseOffset, + _Out_writes_opt_(NumSubresources) D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts, + _Out_writes_opt_(NumSubresources) UINT* pNumRows, + _Out_writes_opt_(NumSubresources) UINT64* pRowSizeInBytes, + _Out_opt_ UINT64* pTotalBytes) + { + Device8Function()->GetCopyableFootprints1(this, pResourceDesc, FirstSubresource, NumSubresources, BaseOffset, pLayouts, pNumRows, pRowSizeInBytes, pTotalBytes); + } + + D3DINLINE void CreateMinMipShaderResourceViewX( + _In_opt_ ID3D12Resource* pTargetedResource, + _In_opt_ const D3D12_RESOURCE_DESC* pTargetedResourceDesc, + _In_opt_ ID3D12Resource* pMinMipResource, + _In_opt_ const D3D12_SHADER_RESOURCE_VIEW_DESC* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) + { + Device8Function()->CreateMinMipShaderResourceViewX(this, pTargetedResource, pTargetedResourceDesc, pMinMipResource, pDesc, DestDescriptor); + } + + + D3DINLINE HRESULT SerializeStateObjectX( + _In_ ID3D12StateObject* pStateObjectToSerialize, + _In_ UINT Flags, + _Out_ IXDXRBlob** ppOutput) + { + return Device8Function()->SerializeStateObjectX(this, + pStateObjectToSerialize, + Flags, + ppOutput); + } + + D3DINLINE HRESULT DeserializeStateObjectX( + _In_ const void* pSourceData, + _In_ UINT sourceDataSize, + ID3D12RootSignature* pRootSignature, + _In_ UINT Flags, + _In_ REFIID riid, + _In_ void** ppStateObjectFromSerialized) + { + return Device8Function()->DeserializeStateObjectX(this, + pSourceData, + sourceDataSize, + pRootSignature, + Flags, + riid, + ppStateObjectFromSerialized); + } + + D3DINLINE void GetRaytracingAccelerationStructurePrebuildInfoX( + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* pInputs, + _In_ const D3D12XBOX_XDXR_STREAM_DESC* pExtraOptions, + _Out_ D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* pInfo) + { + Device8Function()->GetRaytracingAccelerationStructurePrebuildInfoX(this, + pInputs, + pExtraOptions, + pInfo); + } + + D3DINLINE UINT GetShaderResourceViewPRTLODIndexX( + _In_ D3D12_CPU_DESCRIPTOR_HANDLE Descriptor) + { + return Device8Function()->GetShaderResourceViewPRTLODIndexX(this, Descriptor); + } + + D3DINLINE void SetShaderResourceViewPRTLODIndexX( + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor, + _In_ UINT Index) + { + Device8Function()->SetShaderResourceViewPRTLODIndexX(this, DestDescriptor, Index); + } + + D3DINLINE HRESULT AddBlobToGpuHangDumpX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Address, + _In_ UINT SizeBytes, + _In_ UINT64 Metadata) + { + return Device8Function()->AddBlobToGpuHangDumpX(this, Address, SizeBytes, Metadata); + } + + D3DINLINE HRESULT RegisterPagePool2X( + _In_ D3D12_GPU_VIRTUAL_ADDRESS PagePoolAddress, + _In_ UINT PagePoolPageCount, + _In_ D3D12XBOX_REGISTER_PAGE_POOL_FLAGS Flags, + _Out_ HANDLE* pPagePoolHandle) + { + return Device8Function()->RegisterPagePool2X(this, PagePoolAddress, PagePoolPageCount, Flags, pPagePoolHandle); + } + + D3DINLINE void SetShaderRecompileCallbackX( + _In_ D3D12XBOX_SHADER_RECOMPILE_CALLBACK pRecompileCallback) + { + Device8Function()->SetShaderRecompileCallbackX(this, pRecompileCallback); + } + + D3DINLINE void SetCompileTimeShaderPdbPathX( + _In_ const wchar_t* pShaderPdbPath) + { + Device8Function()->SetCompileTimeShaderPdbPathX(this, pShaderPdbPath); + } + + D3DINLINE HRESULT D3DAPI XboxReserved1( + _In_ D3D12XBOX_RESERVED1 Argument1) + { + HRESULT hr = E_NOTIMPL; + return hr; + } +}; + +extern "C" +{ + + struct D3D12Device9_Function_Table + { + D3D12Device8_Function_Table ParentFunction; + + HRESULT(D3DAPI* CreateCommandQueue1)( + _Inout_ ID3D12Device9* pDevice, + _In_ const D3D12_COMMAND_QUEUE_DESC* pDesc, + const IID& CreatorID, + const IID& riid, + _Outptr_ void** ppCommandQueue + ); + + HRESULT(D3DAPI* CreateShaderCacheSession)( + _Inout_ ID3D12Device9* pDevice, + _In_ const D3D12_SHADER_CACHE_SESSION_DESC* pDesc, + const IID& riid, + _Outptr_opt_ void** ppvSession + ); + + HRESULT(D3DAPI* ShaderCacheControl)( + _Inout_ ID3D12Device9* pDevice, + D3D12_SHADER_CACHE_KIND_FLAGS Kinds, + D3D12_SHADER_CACHE_CONTROL_FLAGS Control + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + HRESULT D3d12Device9_CreateCommandQueue1( + _Inout_ ID3D12Device9* pDevice, + _In_ const D3D12_COMMAND_QUEUE_DESC* pDesc, + const IID& CreatorID, + const IID& riid, + _Outptr_ void** ppCommandQueue + ); + + HRESULT D3d12Device9_CreateShaderCacheSession( + _Inout_ ID3D12Device9* pDevice, + _In_ const D3D12_SHADER_CACHE_SESSION_DESC* pDesc, + const IID& riid, + _Outptr_opt_ void** ppvSession + ); + + HRESULT D3d12Device9_ShaderCacheControl( + _Inout_ ID3D12Device9* pDevice, + D3D12_SHADER_CACHE_KIND_FLAGS Kinds, + D3D12_SHADER_CACHE_CONTROL_FLAGS Control + ); + + D3DCONST D3D12Device9_Function_Table D3D__D3d12Device9_Function_Table = + { + D3D__D3d12Device8_Function_Table, + + D3d12Device9_CreateCommandQueue1, + D3d12Device9_CreateShaderCacheSession, + D3d12Device9_ShaderCacheControl, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Device9, 4c80e962, f032, 4f60, bc, 9e, eb, c2, cf, a1, d8, 3c) : public ID3D12Device8 +{ +public: + D3DINLINE D3D12Device9_Function_Table* Device9Function() + { + return (D3D12Device9_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT CreateCommandQueue1( + _In_ const D3D12_COMMAND_QUEUE_DESC * pDesc, + const IID & CreatorID, + const IID & riid, + _Outptr_ void** ppCommandQueue + ) + { + return Device9Function()->CreateCommandQueue1(this, pDesc, CreatorID, riid, ppCommandQueue); + } + + D3DINLINE HRESULT CreateShaderCacheSession( + _In_ const D3D12_SHADER_CACHE_SESSION_DESC * pDesc, + const IID & riid, + _Outptr_opt_ void** ppvSession + ) + { + return Device9Function()->CreateShaderCacheSession(this, pDesc, riid, ppvSession); + } + + D3DINLINE HRESULT ShaderCacheControl( + D3D12_SHADER_CACHE_KIND_FLAGS Kinds, + D3D12_SHADER_CACHE_CONTROL_FLAGS Control + ) + { + return Device9Function()->ShaderCacheControl(this, Kinds, Control); + } +}; + +// +// ID3D12Device10 +// + +extern "C" +{ + typedef enum D3D12_BARRIER_LAYOUT + { + D3D12_BARRIER_LAYOUT_UNDEFINED = 0xffffffff, + D3D12_BARRIER_LAYOUT_COMMON = 0, + D3D12_BARRIER_LAYOUT_GENERIC_READ, + D3D12_BARRIER_LAYOUT_RENDER_TARGET, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + D3D12_BARRIER_LAYOUT_SHADER_RESOURCE, + D3D12_BARRIER_LAYOUT_COPY_SOURCE, + D3D12_BARRIER_LAYOUT_COPY_DEST, + D3D12_BARRIER_LAYOUT_RESOLVE_SOURCE, + D3D12_BARRIER_LAYOUT_RESOLVE_DEST, + D3D12_BARRIER_LAYOUT_SHADING_RATE_SOURCE, + D3D12_BARRIER_LAYOUT_VIDEO_DECODE_READ, + D3D12_BARRIER_LAYOUT_VIDEO_DECODE_WRITE, + D3D12_BARRIER_LAYOUT_VIDEO_PROCESS_READ, + D3D12_BARRIER_LAYOUT_VIDEO_PROCESS_WRITE, + D3D12_BARRIER_LAYOUT_VIDEO_ENCODE_READ, + D3D12_BARRIER_LAYOUT_VIDEO_ENCODE_WRITE, + D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COMMON, + D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ, + D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE, + D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_SOURCE, + D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_DEST, + D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COMMON, + D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_GENERIC_READ, + D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE, + D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_SOURCE, + D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_DEST, + D3D12_BARRIER_LAYOUT_VIDEO_QUEUE_COMMON, + D3D12_BARRIER_LAYOUT_PRESENT, + D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ_COMPUTE_QUEUE_ACCESSIBLE, + + } D3D12_BARRIER_LAYOUT; + + typedef enum D3D12_BARRIER_SYNC + { + D3D12_BARRIER_SYNC_NONE = 0x0, + D3D12_BARRIER_SYNC_ALL = 0x1, + D3D12_BARRIER_SYNC_DRAW = 0x2, + D3D12_BARRIER_SYNC_INDEX_INPUT = 0x4, + D3D12_BARRIER_SYNC_VERTEX_SHADING = 0x8, + D3D12_BARRIER_SYNC_PIXEL_SHADING = 0x10, + D3D12_BARRIER_SYNC_DEPTH_STENCIL = 0x20, + D3D12_BARRIER_SYNC_RENDER_TARGET = 0x40, + D3D12_BARRIER_SYNC_COMPUTE_SHADING = 0x80, + D3D12_BARRIER_SYNC_RAYTRACING = 0x100, + D3D12_BARRIER_SYNC_COPY = 0x200, + D3D12_BARRIER_SYNC_RESOLVE = 0x400, + D3D12_BARRIER_SYNC_EXECUTE_INDIRECT = 0x800, + D3D12_BARRIER_SYNC_PREDICATION = 0x800, // Aliased with SYNC_EXECUTE_INDIRECT + D3D12_BARRIER_SYNC_ALL_SHADING = 0x1000, + D3D12_BARRIER_SYNC_NON_PIXEL_SHADING = 0x2000, + D3D12_BARRIER_SYNC_EMIT_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO = 0x4000, + D3D12_BARRIER_SYNC_CLEAR_UNORDERED_ACCESS_VIEW = 0x8000, + D3D12_BARRIER_SYNC_VIDEO_DECODE = 0x100000, + D3D12_BARRIER_SYNC_VIDEO_PROCESS = 0x200000, + D3D12_BARRIER_SYNC_VIDEO_ENCODE = 0x400000, + D3D12_BARRIER_SYNC_BUILD_RAYTRACING_ACCELERATION_STRUCTURE = 0x800000, + D3D12_BARRIER_SYNC_COPY_RAYTRACING_ACCELERATION_STRUCTURE = 0x1000000, + D3D12_BARRIER_SYNC_SPLIT = 0x80000000, + } D3D12_BARRIER_SYNC; + DEFINE_ENUM_FLAG_OPERATORS( D3D12_BARRIER_SYNC ); + + typedef enum D3D12_BARRIER_ACCESS + { + D3D12_BARRIER_ACCESS_COMMON = 0, + D3D12_BARRIER_ACCESS_VERTEX_BUFFER = 0x1, + D3D12_BARRIER_ACCESS_CONSTANT_BUFFER = 0x2, + D3D12_BARRIER_ACCESS_INDEX_BUFFER = 0x4, + D3D12_BARRIER_ACCESS_RENDER_TARGET = 0x8, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS = 0x10, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE = 0x20, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ = 0x40, + D3D12_BARRIER_ACCESS_SHADER_RESOURCE = 0x80, + D3D12_BARRIER_ACCESS_STREAM_OUTPUT = 0x100, + D3D12_BARRIER_ACCESS_INDIRECT_ARGUMENT = 0x200, + D3D12_BARRIER_ACCESS_PREDICATION = 0x200, // Aliased with ACCESS_INDIRECT_ARGUMENT + D3D12_BARRIER_ACCESS_COPY_DEST = 0x400, + D3D12_BARRIER_ACCESS_COPY_SOURCE = 0x800, + D3D12_BARRIER_ACCESS_RESOLVE_DEST = 0x1000, + D3D12_BARRIER_ACCESS_RESOLVE_SOURCE = 0x2000, + D3D12_BARRIER_ACCESS_RAYTRACING_ACCELERATION_STRUCTURE_READ = 0x4000, + D3D12_BARRIER_ACCESS_RAYTRACING_ACCELERATION_STRUCTURE_WRITE = 0x8000, + D3D12_BARRIER_ACCESS_SHADING_RATE_SOURCE = 0x10000, + D3D12_BARRIER_ACCESS_VIDEO_DECODE_READ = 0x20000, + D3D12_BARRIER_ACCESS_VIDEO_DECODE_WRITE = 0x40000, + D3D12_BARRIER_ACCESS_VIDEO_PROCESS_READ = 0x80000, + D3D12_BARRIER_ACCESS_VIDEO_PROCESS_WRITE = 0x100000, + D3D12_BARRIER_ACCESS_VIDEO_ENCODE_READ = 0x200000, + D3D12_BARRIER_ACCESS_VIDEO_ENCODE_WRITE = 0x400000, + D3D12_BARRIER_ACCESS_NO_ACCESS = 0x80000000, + } D3D12_BARRIER_ACCESS; + DEFINE_ENUM_FLAG_OPERATORS( D3D12_BARRIER_ACCESS ); + + typedef enum D3D12_BARRIER_TYPE + { + D3D12_BARRIER_TYPE_GLOBAL, + D3D12_BARRIER_TYPE_TEXTURE, + D3D12_BARRIER_TYPE_BUFFER, + } D3D12_BARRIER_TYPE; + + typedef enum D3D12_TEXTURE_BARRIER_FLAGS + { + D3D12_TEXTURE_BARRIER_FLAG_NONE = 0x0, + D3D12_TEXTURE_BARRIER_FLAG_DISCARD = 0x1, + } D3D12_TEXTURE_BARRIER_FLAGS; + DEFINE_ENUM_FLAG_OPERATORS( D3D12_TEXTURE_BARRIER_FLAGS ); + + typedef struct D3D12_BARRIER_SUBRESOURCE_RANGE + { + UINT IndexOrFirstMipLevel; + UINT NumMipLevels; + UINT FirstArraySlice; + UINT NumArraySlices; + UINT FirstPlane; + UINT NumPlanes; + } D3D12_BARRIER_SUBRESOURCE_RANGE; + + typedef struct D3D12_GLOBAL_BARRIER + { + D3D12_BARRIER_SYNC SyncBefore; + D3D12_BARRIER_SYNC SyncAfter; + D3D12_BARRIER_ACCESS AccessBefore; + D3D12_BARRIER_ACCESS AccessAfter; + } D3D12_GLOBAL_BARRIER; + + typedef struct D3D12_TEXTURE_BARRIER + { + D3D12_BARRIER_SYNC SyncBefore; + D3D12_BARRIER_SYNC SyncAfter; + D3D12_BARRIER_ACCESS AccessBefore; + D3D12_BARRIER_ACCESS AccessAfter; + D3D12_BARRIER_LAYOUT LayoutBefore; + D3D12_BARRIER_LAYOUT LayoutAfter; + ID3D12Resource *pResource; + D3D12_BARRIER_SUBRESOURCE_RANGE Subresources; + D3D12_TEXTURE_BARRIER_FLAGS Flags; + } D3D12_TEXTURE_BARRIER; + + typedef struct D3D12_BUFFER_BARRIER + { + D3D12_BARRIER_SYNC SyncBefore; + D3D12_BARRIER_SYNC SyncAfter; + D3D12_BARRIER_ACCESS AccessBefore; + D3D12_BARRIER_ACCESS AccessAfter; + ID3D12Resource *pResource; + UINT64 Offset; + UINT64 Size; + } D3D12_BUFFER_BARRIER; + + typedef struct D3D12_BARRIER_GROUP + { + D3D12_BARRIER_TYPE Type; + UINT32 NumBarriers; + union + { + const D3D12_GLOBAL_BARRIER *pGlobalBarriers; + const D3D12_TEXTURE_BARRIER *pTextureBarriers; + const D3D12_BUFFER_BARRIER *pBufferBarriers; + }; + } D3D12_BARRIER_GROUP; + + struct D3D12Device10_Function_Table + { + D3D12Device9_Function_Table Device9; + + HRESULT(D3DAPI* CreateCommittedResource3)( + _Inout_ ID3D12Device10* pDevice, + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + UINT32 NumCastableFormats, + _In_opt_count_(NumCastableFormats) DXGI_FORMAT* pCastableFormats, + const IID& riidResource, + _Outptr_opt_ void** ppvResource + ); + + HRESULT(D3DAPI* CreatePlacedResource2)( + _Inout_ ID3D12Device10* pDevice, + _In_ ID3D12Heap* pHeap, + UINT64 HeapOffset, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + UINT32 NumCastableFormats, + _In_opt_count_(NumCastableFormats) DXGI_FORMAT* pCastableFormats, + const IID& riid, + _Outptr_opt_ void** ppvResource + ); + + HRESULT(D3DAPI* CreateReservedResource2)( + _Inout_ ID3D12Device10* pDevice, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + UINT32 NumCastableFormats, + _In_opt_count_(NumCastableFormats) DXGI_FORMAT* pCastableFormats, + const IID& riid, + _Outptr_opt_ void** ppvResource + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + HRESULT D3d12Device10_CreateCommittedResource3( + _Inout_ ID3D12Device10* pDevice, + _In_ const D3D12_HEAP_PROPERTIES* pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + UINT32 NumCastableFormats, + _In_opt_count_(NumCastableFormats) DXGI_FORMAT* pCastableFormats, + const IID& riidResource, + _Outptr_opt_ void** ppvResource + ); + + HRESULT D3d12Device10_CreatePlacedResource2( + _Inout_ ID3D12Device10* pDevice, + _In_ ID3D12Heap* pHeap, + UINT64 HeapOffset, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + UINT32 NumCastableFormats, + _In_opt_count_(NumCastableFormats) DXGI_FORMAT* pCastableFormats, + const IID& riid, + _Outptr_opt_ void** ppvResource + ); + + HRESULT D3d12Device10_CreateReservedResource2( + _Inout_ ID3D12Device10* pDevice, + _In_ const D3D12_RESOURCE_DESC* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedSession, + UINT32 NumCastableFormats, + _In_opt_count_(NumCastableFormats) DXGI_FORMAT* pCastableFormats, + const IID& riid, + _Outptr_opt_ void** ppvResource + ); + + D3DCONST D3D12Device10_Function_Table D3D__D3d12Device10_Function_Table = + { + D3D__D3d12Device9_Function_Table, + D3d12Device10_CreateCommittedResource3, + D3d12Device10_CreatePlacedResource2, + D3d12Device10_CreateReservedResource2, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Device10, 517f8718, aa66, 49f9, b0, 2b, a7, ab, 89, c0, 60, 31) : public ID3D12Device9 +{ +public: + D3DINLINE D3D12Device10_Function_Table* Device10Function() + { + return (D3D12Device10_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT CreateCommittedResource3( + _In_ const D3D12_HEAP_PROPERTIES * pHeapProperties, + D3D12_HEAP_FLAGS HeapFlags, + _In_ const D3D12_RESOURCE_DESC1 * pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE * pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession * pProtectedSession, + UINT32 NumCastableFormats, + _In_opt_count_(NumCastableFormats) DXGI_FORMAT * pCastableFormats, + const IID & riidResource, + _Outptr_opt_ void** ppvResource + ) + { + return Device10Function()->CreateCommittedResource3(this, pHeapProperties, HeapFlags, pDesc, InitialLayout, pOptimizedClearValue, pProtectedSession, NumCastableFormats, pCastableFormats, riidResource, ppvResource); + } + + D3DINLINE HRESULT CreatePlacedResource2( + _In_ ID3D12Heap * pHeap, + UINT64 HeapOffset, + _In_ const D3D12_RESOURCE_DESC1 * pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE * pOptimizedClearValue, + UINT32 NumCastableFormats, + _In_opt_count_(NumCastableFormats) DXGI_FORMAT * pCastableFormats, + const IID & riid, + _Outptr_opt_ void** ppvResource + ) + { + return Device10Function()->CreatePlacedResource2(this, pHeap, HeapOffset, pDesc, InitialLayout, pOptimizedClearValue, NumCastableFormats, pCastableFormats, riid, ppvResource); + } + + D3DINLINE HRESULT CreateReservedResource2( + _In_ const D3D12_RESOURCE_DESC * pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE * pOptimizedClearValue, + _In_opt_ ID3D12ProtectedResourceSession * pProtectedSession, + UINT32 NumCastableFormats, + _In_opt_count_(NumCastableFormats) DXGI_FORMAT * pCastableFormats, + const IID & riid, + _Outptr_opt_ void** ppvResource + ) + { + return Device10Function()->CreateReservedResource2(this, pDesc, InitialLayout, pOptimizedClearValue, pProtectedSession, NumCastableFormats, pCastableFormats, riid, ppvResource); + } +}; +// +// ID3D12Device11 +// + +extern "C" +{ + + struct D3D12Device11_Function_Table + { + D3D12Device10_Function_Table Device10; + + void (D3DAPI* CreateSampler2)( + _Inout_ ID3D12Device11* pDevice, + _In_ const D3D12_SAMPLER_DESC2* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor + ); + + HRESULT(D3DAPI* EnableLiveDebuggingX)( + _Inout_ ID3D12Device11* pDevice, + _In_ D3D12XBOX_LIVE_DEBUGGING_GLOBAL_PARAMETERS* pDebugParams); + + void (D3DAPI* ReportGpuHaltX)( + _Inout_ ID3D12Device11* pDevice, + _In_ D3D12XBOX_REPORT_GPU_HALT_FLAGS Flags); + + HRESULT (D3DAPI* CreatePlacedResourceX1)( + _Inout_ ID3D12Device11* pDevice, + _In_ D3D12_GPU_VIRTUAL_ADDRESS ResourceLocation, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + HRESULT (D3DAPI* CreateComponentPlacedResourceX2)( + _Inout_ ID3D12Device11* pDevice, + _In_ const D3D12XBOX_COMPONENT_PLACED_ADDRESSES* pComponentLocations, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + BOOL (D3DAPI* IsLiveDebugServerActiveX)( + _Inout_ ID3D12Device11* pDevice); + + HRESULT (D3DAPI* RehydrateRaytracingAccelerationStructureX)( + _Inout_ ID3D12Device11* pDevice, + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc); + + HRESULT (D3DAPI* ValidateAccelerationStructureBuildDescCrc32X)( + _Inout_ ID3D12Device11* pDevice, + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc); + + HRESULT (D3DAPI* QueryBVHStatsCPUX)( + _Inout_ ID3D12Device11* pDevice, + _In_ const void* pBlasHeaderAddressCPU, + _Out_ D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_OFFLINE_STATISTICS_DESC* pResultStatisticsDesc); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12Device11_CreateSampler2( + _Inout_ ID3D12Device11* pDevice, + _In_ const D3D12_SAMPLER_DESC2* pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor + ); + + HRESULT D3d12Device11_EnableLiveDebuggingX( + _Inout_ ID3D12Device11* pDevice, + _In_ D3D12XBOX_LIVE_DEBUGGING_GLOBAL_PARAMETERS* pDebugParams); + + void D3DAPI D3d12Device11_ReportGpuHaltX( + _Inout_ ID3D12Device11* pDevice, + _In_ D3D12XBOX_REPORT_GPU_HALT_FLAGS Flags); + + HRESULT D3d12Device11_CreatePlacedResourceX1( + _Inout_ ID3D12Device11* pDevice, + _In_ D3D12_GPU_VIRTUAL_ADDRESS ResourceLocation, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + HRESULT D3d12Device11_CreateComponentPlacedResourceX2( + _Inout_ ID3D12Device11* pDevice, + _In_ const D3D12XBOX_COMPONENT_PLACED_ADDRESSES* pComponentLocations, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource); + + BOOL D3d12Device11_IsLiveDebugServerActiveX( + _Inout_ ID3D12Device11* pDevice); + + HRESULT D3d12Device11_RehydrateRaytracingAccelerationStructureX( + _Inout_ ID3D12Device11* pDevice, + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc); + + HRESULT D3d12Device11_ValidateAccelerationStructureBuildDescCrc32X( + _Inout_ ID3D12Device11* pDevice, + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc); + + HRESULT D3d12Device11_QueryBVHStatsCPUX( + _Inout_ ID3D12Device11* pDevice, + _In_ const void* pBlasHeaderAddressCPU, + _Out_ D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_OFFLINE_STATISTICS_DESC* pResultStatisticsDesc); + + D3DCONST D3D12Device11_Function_Table D3D__D3d12Device11_Function_Table = + { + D3D__D3d12Device10_Function_Table, + D3d12Device11_CreateSampler2, + D3d12Device11_EnableLiveDebuggingX, + D3d12Device11_ReportGpuHaltX, + D3d12Device11_CreatePlacedResourceX1, + D3d12Device11_CreateComponentPlacedResourceX2, + D3d12Device11_IsLiveDebugServerActiveX, + D3d12Device11_RehydrateRaytracingAccelerationStructureX, + D3d12Device11_ValidateAccelerationStructureBuildDescCrc32X, + D3d12Device11_QueryBVHStatsCPUX, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Device11, 5405c344, d457, 444e, b4, dd, 23, 66, e4, 5a, ee, 39) : public ID3D12Device10 +{ +public: + D3DINLINE D3D12Device11_Function_Table* Device11Function() + { + return (D3D12Device11_Function_Table*)m_pFunction; + } + + D3DINLINE void CreateSampler2( + _In_ const D3D12_SAMPLER_DESC2 * pDesc, + _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor + ) + { + Device11Function()->CreateSampler2(this, pDesc, DestDescriptor); + } + + D3DINLINE HRESULT EnableLiveDebuggingX( + _In_ D3D12XBOX_LIVE_DEBUGGING_GLOBAL_PARAMETERS* pDebugParams) + { + return Device11Function()->EnableLiveDebuggingX(this, pDebugParams); + } + + D3DINLINE void ReportGpuHaltX( + _In_ D3D12XBOX_REPORT_GPU_HALT_FLAGS Flags) + { + Device11Function()->ReportGpuHaltX(this, Flags); + } + + D3DINLINE HRESULT CreatePlacedResourceX1( + _In_ D3D12_GPU_VIRTUAL_ADDRESS ResourceLocation, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource) + { + return Device11Function()->CreatePlacedResourceX1( + this, + ResourceLocation, + pDesc, + InitialLayout, + pOptimizedClearValue, + riid, + ppvResource); + } + + D3DINLINE HRESULT CreateComponentPlacedResourceX2( + _In_ const D3D12XBOX_COMPONENT_PLACED_ADDRESSES* pComponentLocations, + _In_ const D3D12_RESOURCE_DESC1* pDesc, + D3D12_BARRIER_LAYOUT InitialLayout, + _In_opt_ const D3D12_CLEAR_VALUE* pOptimizedClearValue, + REFIID riid, + _Outptr_opt_ void** ppvResource) + { + return Device11Function()->CreateComponentPlacedResourceX2( + this, + pComponentLocations, + pDesc, + InitialLayout, + pOptimizedClearValue, + riid, + ppvResource); + } + + D3DINLINE BOOL IsLiveDebugServerActiveX() + { + return Device11Function()->IsLiveDebugServerActiveX(this); + } + + D3DINLINE HRESULT RehydrateRaytracingAccelerationStructureX( + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc) + { + return Device11Function()->RehydrateRaytracingAccelerationStructureX( + this, + pDesc); + } + + HRESULT ValidateAccelerationStructureBuildDescCrc32X( + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc) + { + return Device11Function()->ValidateAccelerationStructureBuildDescCrc32X(this, pDesc); + } + + D3DINLINE HRESULT QueryBVHStatsCPUX( + _In_ const void* pBlasHeaderAddressCPU, + _Out_ D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_OFFLINE_STATISTICS_DESC* pResultStatisticsDesc) + { + return Device11Function()->QueryBVHStatsCPUX( + this, + pBlasHeaderAddressCPU, + pResultStatisticsDesc); + } +}; + +extern "C" +{ + +typedef enum D3D12_AUTO_BREADCRUMB_OP +{ + D3D12_AUTO_BREADCRUMB_OP_SETMARKER = 0, + D3D12_AUTO_BREADCRUMB_OP_BEGINEVENT = 1, + D3D12_AUTO_BREADCRUMB_OP_ENDEVENT = 2, + D3D12_AUTO_BREADCRUMB_OP_DRAWINSTANCED = 3, + D3D12_AUTO_BREADCRUMB_OP_DRAWINDEXEDINSTANCED = 4, + D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT = 5, + D3D12_AUTO_BREADCRUMB_OP_DISPATCH = 6, + D3D12_AUTO_BREADCRUMB_OP_COPYBUFFERREGION = 7, + D3D12_AUTO_BREADCRUMB_OP_COPYTEXTUREREGION = 8, + D3D12_AUTO_BREADCRUMB_OP_COPYRESOURCE = 9, + D3D12_AUTO_BREADCRUMB_OP_COPYTILES = 10, + D3D12_AUTO_BREADCRUMB_OP_RESOLVESUBRESOURCE = 11, + D3D12_AUTO_BREADCRUMB_OP_CLEARRENDERTARGETVIEW = 12, + D3D12_AUTO_BREADCRUMB_OP_CLEARUNORDEREDACCESSVIEW = 13, + D3D12_AUTO_BREADCRUMB_OP_CLEARDEPTHSTENCILVIEW = 14, + D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER = 15, + D3D12_AUTO_BREADCRUMB_OP_EXECUTEBUNDLE = 16, + D3D12_AUTO_BREADCRUMB_OP_PRESENT = 17, + D3D12_AUTO_BREADCRUMB_OP_RESOLVEQUERYDATA = 18, + D3D12_AUTO_BREADCRUMB_OP_BEGINSUBMISSION = 19, + D3D12_AUTO_BREADCRUMB_OP_ENDSUBMISSION = 20, + D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME = 21, + D3D12_AUTO_BREADCRUMB_OP_PROCESSFRAMES = 22, + D3D12_AUTO_BREADCRUMB_OP_ATOMICCOPYBUFFERUINT = 23, + D3D12_AUTO_BREADCRUMB_OP_ATOMICCOPYBUFFERUINT64 = 24, + D3D12_AUTO_BREADCRUMB_OP_RESOLVESUBRESOURCEREGION = 25, + D3D12_AUTO_BREADCRUMB_OP_WRITEBUFFERIMMEDIATE = 26, + D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME1 = 27, + D3D12_AUTO_BREADCRUMB_OP_SETPROTECTEDRESOURCESESSION = 28, + D3D12_AUTO_BREADCRUMB_OP_DECODEFRAME2 = 29, + D3D12_AUTO_BREADCRUMB_OP_PROCESSFRAMES1 = 30, + D3D12_AUTO_BREADCRUMB_OP_BUILDRAYTRACINGACCELERATIONSTRUCTURE = 31, + D3D12_AUTO_BREADCRUMB_OP_EMITRAYTRACINGACCELERATIONSTRUCTUREPOSTBUILDINFO = 32, + D3D12_AUTO_BREADCRUMB_OP_COPYRAYTRACINGACCELERATIONSTRUCTURE = 33, + D3D12_AUTO_BREADCRUMB_OP_DISPATCHRAYS = 34, + D3D12_AUTO_BREADCRUMB_OP_INITIALIZEMETACOMMAND = 35, + D3D12_AUTO_BREADCRUMB_OP_EXECUTEMETACOMMAND = 36, + D3D12_AUTO_BREADCRUMB_OP_ESTIMATEMOTION = 37, + D3D12_AUTO_BREADCRUMB_OP_RESOLVEMOTIONVECTORHEAP = 38, + D3D12_AUTO_BREADCRUMB_OP_SETPIPELINESTATE1 = 39, + D3D12_AUTO_BREADCRUMB_OP_INITIALIZEEXTENSIONCOMMAND = 40, + D3D12_AUTO_BREADCRUMB_OP_EXECUTEEXTENSIONCOMMAND = 41, + D3D12_AUTO_BREADCRUMB_OP_DISPATCHMESH = 42, + D3D12_AUTO_BREADCRUMB_OP_ENCODEFRAME = 43, + D3D12_AUTO_BREADCRUMB_OP_RESOLVEENCODEROUTPUTMETADATA = 44, +} D3D12_AUTO_BREADCRUMB_OP; + +typedef struct D3D12_AUTO_BREADCRUMB_NODE +{ + const char *pCommandListDebugNameA; + const wchar_t *pCommandListDebugNameW; + const char *pCommandQueueDebugNameA; + const wchar_t *pCommandQueueDebugNameW; + ID3D12GraphicsCommandList *pCommandList; + ID3D12CommandQueue *pCommandQueue; + UINT32 BreadcrumbCount; + UINT32 *pLastBreadcrumbValue; + D3D12_AUTO_BREADCRUMB_OP *pCommandHistory; + struct D3D12_AUTO_BREADCRUMB_NODE *pNext; // pointer to next node +} D3D12_AUTO_BREADCRUMB_NODE; + +typedef struct D3D12_DRED_BREADCRUMB_CONTEXT +{ + UINT BreadcrumbIndex; + const wchar_t* pContextString; +} D3D12_DRED_BREADCRUMB_CONTEXT; + +typedef struct D3D12_AUTO_BREADCRUMB_NODE1 +{ + const char* pCommandListDebugNameA; + const wchar_t* pCommandListDebugNameW; + const char* pCommandQueueDebugNameA; + const wchar_t* pCommandQueueDebugNameW; + ID3D12GraphicsCommandList* pCommandList; + ID3D12CommandQueue* pCommandQueue; + UINT BreadcrumbCount; + const UINT* pLastBreadcrumbValue; + const D3D12_AUTO_BREADCRUMB_OP* pCommandHistory; + const struct D3D12_AUTO_BREADCRUMB_NODE1* pNext; + UINT BreadcrumbContextsCount; + D3D12_DRED_BREADCRUMB_CONTEXT* pBreadcrumbContexts; +} D3D12_AUTO_BREADCRUMB_NODE1; + +typedef struct D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT +{ + const D3D12_AUTO_BREADCRUMB_NODE* pHeadAutoBreadcrumbNode; +} D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT; + +typedef struct D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1 +{ + const D3D12_AUTO_BREADCRUMB_NODE1* pHeadAutoBreadcrumbNode; +} D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1; + +// D3D12_DRED_VERSION +typedef enum D3D12_DRED_VERSION +{ + D3D12_DRED_VERSION_1_0 = 0x1, +} D3D12_DRED_VERSION; + +typedef enum D3D12_DRED_FLAGS +{ + D3D12_DRED_FLAG_NONE = 0, + D3D12_DRED_FLAG_FORCE_ENABLE = 1, + D3D12_DRED_FLAG_DISABLE_AUTOBREADCRUMBS = 2, +} D3D12_DRED_FLAGS; + +typedef enum D3D12_DRED_ALLOCATION_TYPE +{ + D3D12_DRED_ALLOCATION_TYPE_COMMAND_QUEUE = 19, + D3D12_DRED_ALLOCATION_TYPE_COMMAND_ALLOCATOR = 20, + D3D12_DRED_ALLOCATION_TYPE_PIPELINE_STATE = 21, + D3D12_DRED_ALLOCATION_TYPE_COMMAND_LIST = 22, + D3D12_DRED_ALLOCATION_TYPE_FENCE = 23, + D3D12_DRED_ALLOCATION_TYPE_DESCRIPTOR_HEAP = 24, + D3D12_DRED_ALLOCATION_TYPE_HEAP = 25, + D3D12_DRED_ALLOCATION_TYPE_QUERY_HEAP = 27, + D3D12_DRED_ALLOCATION_TYPE_COMMAND_SIGNATURE = 28, + D3D12_DRED_ALLOCATION_TYPE_PIPELINE_LIBRARY = 29, + D3D12_DRED_ALLOCATION_TYPE_VIDEO_DECODER = 30, + D3D12_DRED_ALLOCATION_TYPE_VIDEO_PROCESSOR = 32, + D3D12_DRED_ALLOCATION_TYPE_RESOURCE = 34, + D3D12_DRED_ALLOCATION_TYPE_PASS = 35, + D3D12_DRED_ALLOCATION_TYPE_CRYPTOSESSION = 36, + D3D12_DRED_ALLOCATION_TYPE_CRYPTOSESSIONPOLICY = 37, + D3D12_DRED_ALLOCATION_TYPE_PROTECTEDRESOURCESESSION = 38, + D3D12_DRED_ALLOCATION_TYPE_VIDEO_DECODER_HEAP = 39, + D3D12_DRED_ALLOCATION_TYPE_COMMAND_POOL = 40, + D3D12_DRED_ALLOCATION_TYPE_COMMAND_RECORDER = 41, + D3D12_DRED_ALLOCATION_TYPE_STATE_OBJECT = 42, + D3D12_DRED_ALLOCATION_TYPE_METACOMMAND = 43, + D3D12_DRED_ALLOCATION_TYPE_SCHEDULINGGROUP = 44, + D3D12_DRED_ALLOCATION_TYPE_VIDEO_MOTION_ESTIMATOR = 45, + D3D12_DRED_ALLOCATION_TYPE_VIDEO_MOTION_VECTOR_HEAP = 46, + D3D12_DRED_ALLOCATION_TYPE_VIDEO_EXTENSION_COMMAND = 47, + D3D12_DRED_ALLOCATION_TYPE_VIDEO_ENCODER = 48, + D3D12_DRED_ALLOCATION_TYPE_VIDEO_ENCODER_HEAP = 49, + D3D12_DRED_ALLOCATION_TYPE_INVALID = 4294967295, +} D3D12_DRED_ALLOCATION_TYPE; + +typedef enum D3D12_DRED_DEVICE_STATE +{ + D3D12_DRED_DEVICE_STATE_UNKNOWN = 0, + D3D12_DRED_DEVICE_STATE_HUNG = 3, + D3D12_DRED_DEVICE_STATE_FAULT = 6, + D3D12_DRED_DEVICE_STATE_PAGEFAULT = 7, +} D3D12_DRED_DEVICE_STATE; + +typedef enum D3D12_DRED_ENABLEMENT +{ + D3D12_DRED_ENABLEMENT_SYSTEM_CONTROLLED = 0, + D3D12_DRED_ENABLEMENT_FORCED_OFF = 1, + D3D12_DRED_ENABLEMENT_FORCED_ON = 2, +} D3D12_DRED_ENABLEMENT; + +typedef enum D3D12_DRED_PAGE_FAULT_FLAGS +{ + D3D12_DRED_PAGE_FAULT_FLAGS_NONE = 0, +} D3D12_DRED_PAGE_FAULT_FLAGS; + +typedef struct D3D12_DRED_ALLOCATION_NODE +{ + const char* ObjectNameA; + const wchar_t* ObjectNameW; + D3D12_DRED_ALLOCATION_TYPE AllocationType; + const struct D3D12_DRED_ALLOCATION_NODE* pNext; +} D3D12_DRED_ALLOCATION_NODE; + +typedef struct D3D12_DRED_ALLOCATION_NODE1 +{ + const char* ObjectNameA; + const wchar_t* ObjectNameW; + D3D12_DRED_ALLOCATION_TYPE AllocationType; + const struct D3D12_DRED_ALLOCATION_NODE1* pNext; + const IUnknown* pObject; +} D3D12_DRED_ALLOCATION_NODE1; + +typedef struct D3D12_DRED_PAGE_FAULT_OUTPUT +{ + D3D12_GPU_VIRTUAL_ADDRESS PageFaultVA; + const D3D12_DRED_ALLOCATION_NODE* pHeadExistingAllocationNode; + const D3D12_DRED_ALLOCATION_NODE* pHeadRecentFreedAllocationNode; +} D3D12_DRED_PAGE_FAULT_OUTPUT; + +typedef struct D3D12_DRED_PAGE_FAULT_OUTPUT1 +{ + D3D12_GPU_VIRTUAL_ADDRESS PageFaultVA; + const D3D12_DRED_ALLOCATION_NODE1* pHeadExistingAllocationNode; + const D3D12_DRED_ALLOCATION_NODE1* pHeadRecentFreedAllocationNode; +} D3D12_DRED_PAGE_FAULT_OUTPUT1; + +typedef struct D3D12_DRED_PAGE_FAULT_OUTPUT2 +{ + D3D12_GPU_VIRTUAL_ADDRESS PageFaultVA; + const D3D12_DRED_ALLOCATION_NODE1* pHeadExistingAllocationNode; + const D3D12_DRED_ALLOCATION_NODE1* pHeadRecentFreedAllocationNode; + D3D12_DRED_PAGE_FAULT_FLAGS PageFaultFlags; +} D3D12_DRED_PAGE_FAULT_OUTPUT2; + +typedef struct D3D12_DEVICE_REMOVED_EXTENDED_DATA +{ + _In_ D3D12_DRED_FLAGS Flags; // Dred flags + _Out_ D3D12_AUTO_BREADCRUMB_NODE *pHeadAutoBreadcrumbNode; // Pointer to head of a linked list of auto-breadcrumb data +} D3D12_DEVICE_REMOVED_EXTENDED_DATA; + + +typedef struct D3D12_VERSIONED_DEVICE_REMOVED_EXTENDED_DATA +{ + D3D12_DRED_VERSION Version; // Version of the DRED data + union + { + D3D12_DEVICE_REMOVED_EXTENDED_DATA Dred_1_0; + }; +} D3D12_VERSIONED_DEVICE_REMOVED_EXTENDED_DATA; + +} + +// +// ID3D12DeviceRemovedExtendedData +// + +extern "C" +{ + + struct D3D12DeviceRemovedExtendedData_Function_Table + { + + HRESULT(D3DAPI* GetAutoBreadcrumbsOutput)( + _Inout_ ID3D12DeviceRemovedExtendedData* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT* pOutput + ); + + HRESULT(D3DAPI* GetPageFaultAllocationOutput)( + _Inout_ ID3D12DeviceRemovedExtendedData* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_PAGE_FAULT_OUTPUT* pOutput + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + HRESULT D3d12DeviceRemovedExtendedData_GetAutoBreadcrumbsOutput( + _Inout_ ID3D12DeviceRemovedExtendedData* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT* pOutput + ); + + HRESULT D3d12DeviceRemovedExtendedData_GetPageFaultAllocationOutput( + _Inout_ ID3D12DeviceRemovedExtendedData* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_PAGE_FAULT_OUTPUT* pOutput + ); + + D3DCONST D3D12DeviceRemovedExtendedData_Function_Table D3D__D3d12DeviceRemovedExtendedData_Function_Table = + { + D3d12DeviceRemovedExtendedData_GetAutoBreadcrumbsOutput, + D3d12DeviceRemovedExtendedData_GetPageFaultAllocationOutput, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DeviceRemovedExtendedData, 98931D33, 5AE8, 4791, AA, 3C, 1A, 73, A2, 93, 4E, 71) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12DeviceRemovedExtendedData_Function_Table* DeviceRemovedExtendedDataFunction() + { + return (D3D12DeviceRemovedExtendedData_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT GetAutoBreadcrumbsOutput( + _Out_ D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT * pOutput + ) + { + return DeviceRemovedExtendedDataFunction()->GetAutoBreadcrumbsOutput(this, pOutput); + } + + D3DINLINE HRESULT GetPageFaultAllocationOutput( + _Out_ D3D12_DRED_PAGE_FAULT_OUTPUT * pOutput + ) + { + return DeviceRemovedExtendedDataFunction()->GetPageFaultAllocationOutput(this, pOutput); + } +}; + +// +// ID3D12DeviceRemovedExtendedData1 +// + +extern "C" +{ + + struct D3D12DeviceRemovedExtendedData1_Function_Table + { + D3D12DeviceRemovedExtendedData_Function_Table ParentFunction; + + HRESULT(D3DAPI* GetAutoBreadcrumbsOutput1)( + _Inout_ ID3D12DeviceRemovedExtendedData1* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1* pOutput + ); + + HRESULT(D3DAPI* GetPageFaultAllocationOutput1)( + _Inout_ ID3D12DeviceRemovedExtendedData1* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_PAGE_FAULT_OUTPUT1* pOutput + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + HRESULT D3d12DeviceRemovedExtendedData1_GetAutoBreadcrumbsOutput1( + _Inout_ ID3D12DeviceRemovedExtendedData1* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1* pOutput + ); + + HRESULT D3d12DeviceRemovedExtendedData1_GetPageFaultAllocationOutput1( + _Inout_ ID3D12DeviceRemovedExtendedData1* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_PAGE_FAULT_OUTPUT1* pOutput + ); + + D3DCONST D3D12DeviceRemovedExtendedData1_Function_Table D3D__D3d12DeviceRemovedExtendedData1_Function_Table = + { + D3D__D3d12DeviceRemovedExtendedData_Function_Table, + D3d12DeviceRemovedExtendedData1_GetAutoBreadcrumbsOutput1, + D3d12DeviceRemovedExtendedData1_GetPageFaultAllocationOutput1, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DeviceRemovedExtendedData1, 9727A022, CF1D, 4DDA, 9E, BA, EF, FA, 65, 3F, C5, 06) : public ID3D12DeviceRemovedExtendedData +{ +public: + D3DINLINE D3D12DeviceRemovedExtendedData1_Function_Table* DeviceRemovedExtendedData1Function() + { + return (D3D12DeviceRemovedExtendedData1_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT GetAutoBreadcrumbsOutput1( + _Out_ D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT1 * pOutput + ) + { + return DeviceRemovedExtendedData1Function()->GetAutoBreadcrumbsOutput1(this, pOutput); + } + + D3DINLINE HRESULT GetPageFaultAllocationOutput1( + _Out_ D3D12_DRED_PAGE_FAULT_OUTPUT1 * pOutput + ) + { + return DeviceRemovedExtendedData1Function()->GetPageFaultAllocationOutput1(this, pOutput); + } +}; +// +// ID3D12DeviceRemovedExtendedData2 +// + +extern "C" +{ + + struct D3D12DeviceRemovedExtendedData2_Function_Table + { + D3D12DeviceRemovedExtendedData1_Function_Table ParentFunction; + + D3D12_DRED_DEVICE_STATE(D3DAPI* GetDeviceState)( + _Inout_ ID3D12DeviceRemovedExtendedData2* pDeviceRemovedExtendedData + ); + + HRESULT(D3DAPI* GetPageFaultAllocationOutput2)( + _Inout_ ID3D12DeviceRemovedExtendedData2* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_PAGE_FAULT_OUTPUT2* pOutput + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + D3D12_DRED_DEVICE_STATE D3d12DeviceRemovedExtendedData2_GetDeviceState( + _Inout_ ID3D12DeviceRemovedExtendedData2* pDeviceRemovedExtendedData + ); + + HRESULT D3d12DeviceRemovedExtendedData2_GetPageFaultAllocationOutput2( + _Inout_ ID3D12DeviceRemovedExtendedData2* pDeviceRemovedExtendedData, + _Out_ D3D12_DRED_PAGE_FAULT_OUTPUT2* pOutput + ); + + D3DCONST D3D12DeviceRemovedExtendedData2_Function_Table D3D__D3d12DeviceRemovedExtendedData2_Function_Table = + { + D3D__D3d12DeviceRemovedExtendedData1_Function_Table, + D3d12DeviceRemovedExtendedData2_GetDeviceState, + D3d12DeviceRemovedExtendedData2_GetPageFaultAllocationOutput2, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DeviceRemovedExtendedData2, 67FC5816, E4CA, 4915, BF, 18, 42, 54, 12, 72, DA, 54) : public ID3D12DeviceRemovedExtendedData1 +{ +public: + D3DINLINE D3D12DeviceRemovedExtendedData2_Function_Table* DeviceRemovedExtendedData2Function() + { + return (D3D12DeviceRemovedExtendedData2_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_DRED_DEVICE_STATE GetDeviceState( + ) + { + return DeviceRemovedExtendedData2Function()->GetDeviceState(this); + } + + D3DINLINE HRESULT GetPageFaultAllocationOutput2( + _Out_ D3D12_DRED_PAGE_FAULT_OUTPUT2 * pOutput + ) + { + return DeviceRemovedExtendedData2Function()->GetPageFaultAllocationOutput2(this, pOutput); + } +}; + +// +// ID3D12DeviceRemovedExtendedDataSettings +// + +extern "C" +{ + + struct D3D12DeviceRemovedExtendedDataSettings_Function_Table + { + + void (D3DAPI* SetAutoBreadcrumbsEnablement)( + _Inout_ ID3D12DeviceRemovedExtendedDataSettings* pDeviceRemovedExtendedDataSettings, + D3D12_DRED_ENABLEMENT Enablement + ); + + void (D3DAPI* SetPageFaultEnablement)( + _Inout_ ID3D12DeviceRemovedExtendedDataSettings* pDeviceRemovedExtendedDataSettings, + D3D12_DRED_ENABLEMENT Enablement + ); + + void (D3DAPI* SetWatsonDumpEnablement)( + _Inout_ ID3D12DeviceRemovedExtendedDataSettings* pDeviceRemovedExtendedDataSettings, + D3D12_DRED_ENABLEMENT Enablement + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12DeviceRemovedExtendedDataSettings_SetAutoBreadcrumbsEnablement( + _Inout_ ID3D12DeviceRemovedExtendedDataSettings* pDeviceRemovedExtendedDataSettings, + D3D12_DRED_ENABLEMENT Enablement + ); + + void D3d12DeviceRemovedExtendedDataSettings_SetPageFaultEnablement( + _Inout_ ID3D12DeviceRemovedExtendedDataSettings* pDeviceRemovedExtendedDataSettings, + D3D12_DRED_ENABLEMENT Enablement + ); + + void D3d12DeviceRemovedExtendedDataSettings_SetWatsonDumpEnablement( + _Inout_ ID3D12DeviceRemovedExtendedDataSettings* pDeviceRemovedExtendedDataSettings, + D3D12_DRED_ENABLEMENT Enablement + ); + + D3DCONST D3D12DeviceRemovedExtendedDataSettings_Function_Table D3D__D3d12DeviceRemovedExtendedDataSettings_Function_Table = + { + D3d12DeviceRemovedExtendedDataSettings_SetAutoBreadcrumbsEnablement, + D3d12DeviceRemovedExtendedDataSettings_SetPageFaultEnablement, + D3d12DeviceRemovedExtendedDataSettings_SetWatsonDumpEnablement, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DeviceRemovedExtendedDataSettings, 82BC481C, 6B9B, 4030, AE, DB, 7E, E3, D1, DF, 1E, 63) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12DeviceRemovedExtendedDataSettings_Function_Table* DeviceRemovedExtendedDataSettingsFunction() + { + return (D3D12DeviceRemovedExtendedDataSettings_Function_Table*)m_pFunction; + } + + D3DINLINE void SetAutoBreadcrumbsEnablement( + D3D12_DRED_ENABLEMENT Enablement + ) + { + DeviceRemovedExtendedDataSettingsFunction()->SetAutoBreadcrumbsEnablement(this, Enablement); + } + + D3DINLINE void SetPageFaultEnablement( + D3D12_DRED_ENABLEMENT Enablement + ) + { + DeviceRemovedExtendedDataSettingsFunction()->SetPageFaultEnablement(this, Enablement); + } + + D3DINLINE void SetWatsonDumpEnablement( + D3D12_DRED_ENABLEMENT Enablement + ) + { + DeviceRemovedExtendedDataSettingsFunction()->SetWatsonDumpEnablement(this, Enablement); + } +}; +// +// ID3D12DeviceRemovedExtendedDataSettings1 +// + +extern "C" +{ + + struct D3D12DeviceRemovedExtendedDataSettings1_Function_Table + { + D3D12DeviceRemovedExtendedDataSettings_Function_Table ParentFunction; + + void (D3DAPI* SetBreadcrumbContextEnablement)( + _Inout_ ID3D12DeviceRemovedExtendedDataSettings1* pDeviceRemovedExtendedDataSettings, + D3D12_DRED_ENABLEMENT Enablement + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12DeviceRemovedExtendedDataSettings1_SetBreadcrumbContextEnablement( + _Inout_ ID3D12DeviceRemovedExtendedDataSettings1* pDeviceRemovedExtendedDataSettings, + D3D12_DRED_ENABLEMENT Enablement + ); + + D3DCONST D3D12DeviceRemovedExtendedDataSettings1_Function_Table D3D__D3d12DeviceRemovedExtendedDataSettings1_Function_Table = + { + D3D__D3d12DeviceRemovedExtendedDataSettings_Function_Table, + D3d12DeviceRemovedExtendedDataSettings1_SetBreadcrumbContextEnablement, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DeviceRemovedExtendedDataSettings1, DBD5AE51, 3317, 4F0A, AD, F9, 1D, 7C, ED, CA, AE, 0B) : public ID3D12DeviceRemovedExtendedDataSettings +{ +public: + D3DINLINE D3D12DeviceRemovedExtendedDataSettings1_Function_Table* DeviceRemovedExtendedDataSettings1Function() + { + return (D3D12DeviceRemovedExtendedDataSettings1_Function_Table*)m_pFunction; + } + + D3DINLINE void SetBreadcrumbContextEnablement( + D3D12_DRED_ENABLEMENT Enablement + ) + { + DeviceRemovedExtendedDataSettings1Function()->SetBreadcrumbContextEnablement(this, Enablement); + } +}; +extern "C" +{ + +// +// ID3D12Resource1 +// + +struct D3D12Resource1_Function_Table +{ + D3D12Resource_Function_Table ResourceTable; + + HRESULT (D3DAPI* GetProtectedResourceSession)( + _Inout_ ID3D12Resource1* pResource1, + REFIID riid, + _Outptr_opt_ void** ppProtectedSession); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12Resource1, 9D5E227A,4430,4161,88,B3,3E,CA,6B,B1,6E,19) : public ID3D12Resource +{ +public: + + D3DINLINE D3D12Resource1_Function_Table* Resource1Function() + { + return (D3D12Resource1_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetProtectedResourceSession( + REFIID riid, + _Outptr_opt_ void** ppProtectedSession) + { + return Resource1Function()->GetProtectedResourceSession( + this, + riid, + ppProtectedSession); + } + +}; + +// +// ID3D12Resource2 +// + +extern "C" +{ + +struct D3D12Resource2_Function_Table +{ + D3D12Resource1_Function_Table ParentFunction; + + D3D12_RESOURCE_DESC1 (D3DAPI *GetDesc1)( + _Inout_ ID3D12Resource2* pResource + ); +}; + +#if DECLARE_UMD_EXPORTS_D3D12X + +D3D12_RESOURCE_DESC1 D3d12Resource2_GetDesc1( + _Inout_ ID3D12Resource2* pResource +); + +D3DCONST D3D12Resource2_Function_Table D3D__D3d12Resource2_Function_Table = +{ + D3D__D3d12Resource1_Function_Table, + + D3d12Resource2_GetDesc1, +}; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Resource2, BE36EC3B,EA85,4AEB,A4,5A,E9,D7,64,04,A4,95) : public ID3D12Resource1 +{ +public: + D3DINLINE D3D12Resource2_Function_Table* Resource2Function() + { + return (D3D12Resource2_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_RESOURCE_DESC1 GetDesc1( + ) + { + return Resource2Function()->GetDesc1(this); + } +}; +extern "C" +{ +} + +extern "C" +{ + +// +// ID3D12Heap1 +// + +struct D3D12Heap1_Function_Table +{ + D3D12Heap_Function_Table HeapTable; + + HRESULT (D3DAPI* GetProtectedResourceSession)( + _Inout_ ID3D12Heap1* pHeap1, + REFIID riid, + _Outptr_opt_ void** ppProtectedSession); + + D3D12_GPU_VIRTUAL_ADDRESS(D3DAPI* GetGpuAddressX)( + _Inout_ ID3D12Heap1* pHeap1); +}; + + +} // extern C + +D3DINTERFACE(ID3D12Heap1, 572F7389,2168,49E3,96,93,D6,DF,58,71,BF,6D) : public ID3D12Heap +{ +public: + + D3DINLINE D3D12Heap1_Function_Table* Heap1Function() + { + return (D3D12Heap1_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI GetProtectedResourceSession( + REFIID riid, + _Outptr_opt_ void** ppProtectedSession) + { + return Heap1Function()->GetProtectedResourceSession( + this, + riid, + ppProtectedSession); + } + + D3DINLINE D3D12_GPU_VIRTUAL_ADDRESS D3DAPI GetGpuAddressX() + { + return Heap1Function()->GetGpuAddressX(this); + } +}; + +extern "C" +{ +} + +extern "C" +{ + +// +// ID3D12GraphicsCommandList3 +// + +struct D3D12GraphicsCommandList3_Function_Table +{ + D3D12GraphicsCommandList2_Function_Table CommandListFunction; + + void (D3DAPI* SetProtectedResourceSession)( + _Inout_ ID3D12GraphicsCommandList3* pGraphicsCommandList3, + _In_opt_ ID3D12ProtectedResourceSession* pProtectedResourceSession); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12GraphicsCommandList3, 6FDA83A7,B84C,4E38,9A,C8,C7,BD,22,01,6B,3D) : public ID3D12GraphicsCommandList2 +{ +public: + + D3DINLINE D3D12GraphicsCommandList3_Function_Table* GraphicsCommandList3Function() + { + return (D3D12GraphicsCommandList3_Function_Table*)m_pFunction; + } + + D3DINLINE void D3DAPI SetProtectedResourceSession( + _In_opt_ ID3D12ProtectedResourceSession* pProtectedResourceSession) + { + return GraphicsCommandList3Function()->SetProtectedResourceSession( + this, + pProtectedResourceSession); + } + +}; + +extern "C" +{ +// Beginning Access +typedef enum D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE +{ + D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_DISCARD, + D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE, + D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR, + D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_NO_ACCESS +} D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE; + +typedef struct D3D12_RENDER_PASS_BEGINNING_ACCESS_CLEAR_PARAMETERS +{ + D3D12_CLEAR_VALUE ClearValue; +} D3D12_RENDER_PASS_BEGINNING_ACCESS_CLEAR_PARAMETERS; + +typedef struct D3D12_RENDER_PASS_BEGINNING_ACCESS +{ + D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE Type; + + union + { + D3D12_RENDER_PASS_BEGINNING_ACCESS_CLEAR_PARAMETERS Clear; + }; +} D3D12_RENDER_PASS_BEGINNING_ACCESS; + +// Ending Access +typedef enum D3D12_RENDER_PASS_ENDING_ACCESS_TYPE +{ + D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_DISCARD, + D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE, + D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE, + D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_NO_ACCESS +} D3D12_RENDER_PASS_ENDING_ACCESS_TYPE; + +typedef struct D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS +{ + UINT SrcSubresource; + UINT DstSubresource; + + UINT DstX; + UINT DstY; + D3D12_RECT SrcRect; // (0, 0, 0, 0) == resolve entire resource. + +} D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS; + +typedef struct D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS +{ + ID3D12Resource* pSrcResource; + ID3D12Resource* pDstResource; + + // Can be a subset of RT's array slices, but can't target subresources that were't part of RTV/DSV. + UINT SubresourceCount; + _Field_size_full_(SubresourceCount) const D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_SUBRESOURCE_PARAMETERS *pSubresourceParameters; + + DXGI_FORMAT Format; + D3D12_RESOLVE_MODE ResolveMode; + + BOOL PreserveResolveSource; + +} D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS; + +typedef struct D3D12_RENDER_PASS_ENDING_ACCESS +{ + D3D12_RENDER_PASS_ENDING_ACCESS_TYPE Type; + + union + { + D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS Resolve; + }; +} D3D12_RENDER_PASS_ENDING_ACCESS; + +// Render Target Desc +typedef struct D3D12_RENDER_PASS_RENDER_TARGET_DESC +{ + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptor; + + D3D12_RENDER_PASS_BEGINNING_ACCESS BeginningAccess; + D3D12_RENDER_PASS_ENDING_ACCESS EndingAccess; + +} D3D12_RENDER_PASS_RENDER_TARGET_DESC; + +// Depth-Stencil Desc +typedef struct D3D12_RENDER_PASS_DEPTH_STENCIL_DESC +{ + D3D12_CPU_DESCRIPTOR_HANDLE cpuDescriptor; + + D3D12_RENDER_PASS_BEGINNING_ACCESS DepthBeginningAccess; + D3D12_RENDER_PASS_BEGINNING_ACCESS StencilBeginningAccess; + + D3D12_RENDER_PASS_ENDING_ACCESS DepthEndingAccess; + D3D12_RENDER_PASS_ENDING_ACCESS StencilEndingAccess; + +} D3D12_RENDER_PASS_DEPTH_STENCIL_DESC; + +// UAV Access Mode +typedef enum D3D12_RENDER_PASS_FLAGS +{ + D3D12_RENDER_PASS_FLAG_NONE = 0x0, + D3D12_RENDER_PASS_FLAG_ALLOW_UAV_WRITES = 0x1, + D3D12_RENDER_PASS_FLAG_SUSPENDING_PASS = 0x2, + D3D12_RENDER_PASS_FLAG_RESUMING_PASS = 0x4 +} D3D12_RENDER_PASS_FLAGS; + +} + +extern "C" +{ + +// +// ID3D12MetaCommand +// + +struct D3D12MetaCommand_Function_Table +{ + D3D12Pageable_Function_Table PageableFunction; + + UINT64 (D3DAPI* GetRequiredParameterResourceSize)( + _Inout_ ID3D12MetaCommand* pMetaCommand, + _In_ D3D12_META_COMMAND_PARAMETER_STAGE Stage, + _In_ UINT ParameterIndex); + +}; + + +} // extern C + +D3DINTERFACE(ID3D12MetaCommand, DBB84C27,36CE,4FC9,B8,01,F0,48,C4,6A,C5,70) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12MetaCommand_Function_Table* MetaCommandFunction() + { + return (D3D12MetaCommand_Function_Table*)m_pFunction; + } + + D3DINLINE UINT64 D3DAPI GetRequiredParameterResourceSize( + _In_ D3D12_META_COMMAND_PARAMETER_STAGE Stage, + _In_ UINT ParameterIndex) + { + return MetaCommandFunction()->GetRequiredParameterResourceSize( + this, + Stage, + ParameterIndex); + } + +}; + +extern "C" +{ +typedef struct D3D12_DISPATCH_RAYS_DESC +{ + D3D12_GPU_VIRTUAL_ADDRESS_RANGE RayGenerationShaderRecord; + D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE MissShaderTable; + D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE HitGroupTable; + D3D12_GPU_VIRTUAL_ADDRESS_RANGE_AND_STRIDE CallableShaderTable; + UINT Width; + UINT Height; + UINT Depth; +} D3D12_DISPATCH_RAYS_DESC; +} + +extern "C" +{ + +// +// ID3D12GraphicsCommandList4 +// + +struct D3D12GraphicsCommandList4_Function_Table +{ + D3D12GraphicsCommandList3_Function_Table CommandListFunction; + + void (D3DAPI* BeginRenderPass)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4, + _In_ UINT NumRenderTargets, + _In_reads_opt_(NumRenderTargets) const D3D12_RENDER_PASS_RENDER_TARGET_DESC* pRenderTargets, + _In_opt_ const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC* pDepthStencil, + D3D12_RENDER_PASS_FLAGS Flags); + + void (D3DAPI* EndRenderPass)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4); + + void (D3DAPI* InitializeMetaCommand)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4, + _In_ ID3D12MetaCommand * pMetaCommand, + _In_reads_bytes_opt_(InitializationParametersDataSizeInBytes) const void * pInitializationParametersData, + _In_ SIZE_T InitializationParametersDataSizeInBytes); + + void (D3DAPI* ExecuteMetaCommand)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4, + _In_ ID3D12MetaCommand * pMetaCommand, + _In_reads_bytes_opt_(ExecutionParametersDataSizeInBytes) const void * pExecutionParametersData, + _In_ SIZE_T ExecutionParametersDataSizeInBytes); + + void (D3DAPI* BuildRaytracingAccelerationStructure)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4, + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc, + _In_ UINT NumPostbuildInfoDescs, + _In_reads_opt_(NumPostbuildInfoDescs) const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* pPostbuildInfoDescs); + + void (D3DAPI* EmitRaytracingAccelerationStructurePostbuildInfo)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4, + _In_ const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* pDesc, + _In_ UINT NumSourceAccelerationStructures, + _In_reads_( NumSourceAccelerationStructures ) const D3D12_GPU_VIRTUAL_ADDRESS* pSourceAccelerationStructureData); + + void (D3DAPI* CopyRaytracingAccelerationStructure)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4, + _In_ D3D12_GPU_VIRTUAL_ADDRESS DestAccelerationStructureData, + _In_ D3D12_GPU_VIRTUAL_ADDRESS SourceAccelerationStructureData, + _In_ D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE Mode); + + void (D3DAPI* SetPipelineState1)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4, + _In_ ID3D12StateObject* pStateObject); + + void (D3DAPI* DispatchRays)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4, + _In_ const D3D12_DISPATCH_RAYS_DESC* pDesc); + + // + // Xbox extensions + // + + // An XDR bring up helper -- validate the structure that has been built. This has to be called + // after the GPU is done building it. + void (D3DAPI* CpuValidateResultX)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList4, + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc); + + void (D3DAPI* BuildRaytracingAccelerationStructureFromCanonicalBVH)( + _Inout_ ID3D12GraphicsCommandList4* pGraphicsCommandList6, + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc, + _In_ const D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE* pRootNode, + _In_opt_ const D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE* pHierarchyNodes, + _In_ UINT NumHierarchyNodes, + _In_opt_ const D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE* pLeafNodes, + _In_ UINT NumLeafNodes, + _In_ UINT NumPostbuildInfoDescs, + _In_reads_opt_(NumPostbuildInfoDescs) const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* pPostbuildInfoDescs); +}; + + +} // extern C + +D3DINTERFACE(ID3D12GraphicsCommandList4, 8754318e,d3a9,4541,98,cf,64,5b,50,dc,48,74) : public ID3D12GraphicsCommandList3 +{ +public: + + D3DINLINE D3D12GraphicsCommandList4_Function_Table* GraphicsCommandList4Function() + { + return (D3D12GraphicsCommandList4_Function_Table*)m_pFunction; + } + + D3DINLINE void D3DAPI BeginRenderPass( + _In_ UINT NumRenderTargets, + _In_reads_opt_(NumRenderTargets) const D3D12_RENDER_PASS_RENDER_TARGET_DESC* pRenderTargets, + _In_opt_ const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC* pDepthStencil, + D3D12_RENDER_PASS_FLAGS Flags) + { + return GraphicsCommandList4Function()->BeginRenderPass( + this, + NumRenderTargets, + pRenderTargets, + pDepthStencil, + Flags); + } + + D3DINLINE void D3DAPI EndRenderPass() + { + return GraphicsCommandList4Function()->EndRenderPass(this); + } + + D3DINLINE void D3DAPI InitializeMetaCommand( + _In_ ID3D12MetaCommand * pMetaCommand, + _In_reads_bytes_opt_(InitializationParametersDataSizeInBytes) const void * pInitializationParametersData, + _In_ SIZE_T InitializationParametersDataSizeInBytes) + { + return GraphicsCommandList4Function()->InitializeMetaCommand( + this, + pMetaCommand, + pInitializationParametersData, + InitializationParametersDataSizeInBytes); + } + + D3DINLINE void D3DAPI ExecuteMetaCommand( + _In_ ID3D12MetaCommand * pMetaCommand, + _In_reads_bytes_opt_(ExecutionParametersDataSizeInBytes) const void * pExecutionParametersData, + _In_ SIZE_T ExecutionParametersDataSizeInBytes) + { + return GraphicsCommandList4Function()->ExecuteMetaCommand( + this, + pMetaCommand, + pExecutionParametersData, + ExecutionParametersDataSizeInBytes); + } + + D3DINLINE void D3DAPI BuildRaytracingAccelerationStructure( + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc, + _In_ UINT NumPostbuildInfoDescs, + _In_reads_opt_(NumPostbuildInfoDescs) const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* pPostbuildInfoDescs) + { + return GraphicsCommandList4Function()->BuildRaytracingAccelerationStructure( + this, + pDesc, + NumPostbuildInfoDescs, + pPostbuildInfoDescs); + } + + D3DINLINE void D3DAPI EmitRaytracingAccelerationStructurePostbuildInfo( + _In_ const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* pDesc, + _In_ UINT NumSourceAccelerationStructures, + _In_reads_( NumSourceAccelerationStructures ) const D3D12_GPU_VIRTUAL_ADDRESS* pSourceAccelerationStructureData) + { + return GraphicsCommandList4Function()->EmitRaytracingAccelerationStructurePostbuildInfo( + this, + pDesc, + NumSourceAccelerationStructures, + pSourceAccelerationStructureData); + } + + D3DINLINE void D3DAPI CopyRaytracingAccelerationStructure( + _In_ D3D12_GPU_VIRTUAL_ADDRESS DestAccelerationStructureData, + _In_ D3D12_GPU_VIRTUAL_ADDRESS SourceAccelerationStructureData, + _In_ D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE Mode) + { + return GraphicsCommandList4Function()->CopyRaytracingAccelerationStructure( + this, + DestAccelerationStructureData, + SourceAccelerationStructureData, + Mode); + } + + D3DINLINE void D3DAPI SetPipelineState1( + _In_ ID3D12StateObject* pStateObject) + { + return GraphicsCommandList4Function()->SetPipelineState1( + this, + pStateObject); + } + + D3DINLINE void D3DAPI DispatchRays( + _In_ const D3D12_DISPATCH_RAYS_DESC* pDesc) + { + return GraphicsCommandList4Function()->DispatchRays( + this, + pDesc); + } + + D3DINLINE void D3DAPI CpuValidateResultX( + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc) + { + return GraphicsCommandList4Function()->CpuValidateResultX( + this, + pDesc); + } + + D3DINLINE void BuildRaytracingAccelerationStructureFromCanonicalBVH( + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* pDesc, + _In_ const D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE* pRootNode, + _In_opt_ const D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE* pHierarchyNodes, + _In_ UINT NumHierarchyNodes, + _In_opt_ const D3D12XBOX_RAYTRACING_CANONICAL_ACCELERATION_STRUCTURE_NODE* pLeafNodes, + _In_ UINT NumLeafNodes, + _In_ UINT NumPostbuildInfoDescs, + _In_reads_opt_(NumPostbuildInfoDescs) const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* pPostbuildInfoDescs) + { + GraphicsCommandList4Function()->BuildRaytracingAccelerationStructureFromCanonicalBVH(this, + pDesc, + pRootNode, + pHierarchyNodes, + NumHierarchyNodes, + pLeafNodes, + NumLeafNodes, + NumPostbuildInfoDescs, + pPostbuildInfoDescs); + } +}; + + +// +// ID3D12GraphicsCommandList5 +// + + +extern "C" +{ +typedef enum D3D12_AXIS_SHADING_RATE +{ + D3D12_AXIS_SHADING_RATE_1X = 0x0, + D3D12_AXIS_SHADING_RATE_2X = 0x1, + D3D12_AXIS_SHADING_RATE_4X = 0x2 +} D3D12_AXIS_SHADING_RATE; + + +#define D3D12_RS_SET_SHADING_RATE_COMBINER_COUNT 2 + +#define D3D12_SHADING_RATE_X_AXIS_SHIFT 2 +#define D3D12_SHADING_RATE_VALID_MASK 3 + +#define D3D12_MAKE_COARSE_SHADING_RATE(x,y) ((x) << D3D12_SHADING_RATE_X_AXIS_SHIFT | (y)) + +#define D3D12_GET_COARSE_SHADING_RATE_X_AXIS(x) (((x) >> D3D12_SHADING_RATE_X_AXIS_SHIFT) & D3D12_SHADING_RATE_VALID_MASK) +#define D3D12_GET_COARSE_SHADING_RATE_Y_AXIS(y) ((y) & D3D12_SHADING_RATE_VALID_MASK) + +typedef enum D3D12_SHADING_RATE +{ + D3D12_SHADING_RATE_1X1 = 0x0, + D3D12_SHADING_RATE_1X2 = 0x1, + D3D12_SHADING_RATE_2X1 = 0x4, + D3D12_SHADING_RATE_2X2 = 0x5, + D3D12_SHADING_RATE_2X4 = 0x6, + D3D12_SHADING_RATE_4X2 = 0x9, + D3D12_SHADING_RATE_4X4 = 0xA +} D3D12_SHADING_RATE; + +typedef enum D3D12_SHADING_RATE_COMBINER +{ + D3D12_SHADING_RATE_COMBINER_PASSTHROUGH = 0, + D3D12_SHADING_RATE_COMBINER_OVERRIDE = 1, + D3D12_SHADING_RATE_COMBINER_MIN = 2, + D3D12_SHADING_RATE_COMBINER_MAX = 3, + D3D12_SHADING_RATE_COMBINER_SUM = 4, +} D3D12_SHADING_RATE_COMBINER; + + + +// +// Multiple settings can be set via this API +// + +enum D3D12XBOX_SHADING_RATE_SETTINGS_TYPE +{ + D3D12XBOX_SHADING_RATE_SETTINGS_TYPE_COMBINERS = 0, // The driver will back off the combiners and setting of the shading rate images + D3D12XBOX_SHADING_RATE_SETTINGS_TYPE_PIXEL_CENTER_OFFSETS = 1, // Write pixel center offset registers for VRS + D3D12XBOX_SHADING_RATE_SETTINGS_TYPE_HTILE_MODE_TYPE = 2, // + D3D12XBOX_SHADING_RATE_SETTINGS_TYPE_CMASK_VRS_HINT = 3 // + +}; + + +// +// Direct programming of the VRS combiners and rates. +// +struct D3D12XBOX_SHADING_RATE_SETTINGS_COMBINERS +{ + BOOL Deprecated0 : 1; + + // PA_CL_VRS_CNTL + + // Controls how the vertex VRS rate will be calculated from the state based VRS rate and the exported vertex rate. + D3D12_SHADING_RATE_COMBINER VertexRateCombinerMode : 3; // Shader enables via PA_CL_VS_OUT_CNTL.USE_VTX_VRS_RATE when SV_ShadingRate is output + + // Controls how the primitive VRS rate will be calculated from the exported primitive VRS rate and the vertex rate. + D3D12_SHADING_RATE_COMBINER PrimitiveRateCombinerMode : 3; // Shader enables via VGT_DRAW_PAYLOAD_CNTL.EN_VRS_RATE in MeshShaders when SV_ShadingRate is output per-primitive + + // Controls how each 8x8 tile's VRS rate will be calculated from the primitive's VRS rate and the VRS rate encoded in the HTile + D3D12_SHADING_RATE_COMBINER HTileRateCombinerMode : 3; // DB_TILE_SURFACE.VRS_HTILE_ENCODING controls this, but we need to know the DSV to program it right + + // Controls how the tile's VRS rate will be combined with the value provided in the PS_ITER_SAMPLES state to form the rate used for rendering + D3D12_SHADING_RATE_COMBINER SampleIterCombinerMode : 3; // Shader or MSAA extension state enables PS_ITER_SAMPLES for supersampling + + // Controls how the shader input mask of a coarse pixel is generated + BOOL ExposeVrsPixelsMask : 1; // Keep 1, no difference is the pixel shaders don't read SV_ShadingRate + + // Zero out the VRS rate for tiles rendered to the CMASK hint buffer + BOOL CMaskRateHintForceZero : 1; // For when blending is turned on for example -- write zero into the CBs VRS_HINT bits + + // GE_VRS_RATE + + UINT StateVRSRateX : 2; // [-2; 1] is 2s complement. 0 -- 1x, 1 - 2x, 2 - supersample -1, 3 supersample -2 + UINT StateVRSRateY : 2; // [-2; 1] is 2s complement. 0 -- 1x, 1 - 2x, 2 - supersample -1, 3 supersample -2 +}; + + +// +// Direct programming of the pixel center offsets. The driver doesn't uses those at the moment but will reset for each new command list. +// +struct D3D12XBOX_SHADING_RATE_SETTINGS_PIXEL_CENTER_OFFSETS +{ + // DB_SPI_VRS_CENTER_LOCATION + // 4b signed offset from pixel center range -8/16 to 7/16 + UINT CenterXOffset1x1 : 4; + UINT CenterYOffset1x1 : 4; + UINT CenterXOffset2x1 : 4; + UINT CenterYOffset2x1 : 4; + UINT CenterXOffset1x2 : 4; + UINT CenterYOffset1x2 : 4; + UINT CenterXOffset2x2 : 4; + UINT CenterYOffset2x2 : 4; +}; + + +// +// Htile VRS settings +// +enum D3D12XBOX_SHADING_RATE_SETTINGS_HTILE_MODE_TYPE +{ + D3D12XBOX_SHADING_RATE_SETTINGS_HTILE_MODE_TYPE_DISABLE = 0, + D3D12XBOX_SHADING_RATE_SETTINGS_HTILE_MODE_TYPE_2BIT_ENCODING = 1, + D3D12XBOX_SHADING_RATE_SETTINGS_HTILE_MODE_TYPE_4BIT_ENCODING = 2 // Default mode +}; + +// +// Htile format reprogramming -- will be reset at each SetRenderTargets! +// Stop the GPU before touching this. +// +struct D3D12XBOX_SHADING_RATE_SETTINGS_HTILE_MODE +{ + // DB_HTILE_SURFACE.VRS_HTILE_ENCODING for the last set up DSV! + D3D12XBOX_SHADING_RATE_SETTINGS_HTILE_MODE_TYPE HtileEncodingType; +}; + +// +// CMask VRS HINT reprogramming -- will be reset at each SetRenderTargets! +// Stop the GPU before touching this. +// +struct D3D12XBOX_SHADING_RATE_SETTINGS_CMASK_VRS_HINT_MODE +{ + // CB_COLOR#_ATTRIB3.VRS_RATE_HINT_ENABLE for the last set up RTVs + UINT NumRTVs; + BYTE VrsRateHintEnable[8]; +}; + +// +// +// +struct D3D12XBOX_SHADING_RATE_SETTINGS +{ + D3D12XBOX_SHADING_RATE_SETTINGS_TYPE Type; + + union + { + D3D12XBOX_SHADING_RATE_SETTINGS_COMBINERS Combiners; + D3D12XBOX_SHADING_RATE_SETTINGS_PIXEL_CENTER_OFFSETS PixelCenterOffsets; + D3D12XBOX_SHADING_RATE_SETTINGS_HTILE_MODE HTileMode; + D3D12XBOX_SHADING_RATE_SETTINGS_CMASK_VRS_HINT_MODE CMaskVrsHintMode; + }; +}; + +// +// ID3D12GraphicsCommandList5 +// + +struct D3D12GraphicsCommandList5_Function_Table +{ + D3D12GraphicsCommandList4_Function_Table CommandListFunction; + + void (D3DAPI* RSSetShadingRate)( + _Inout_ ID3D12GraphicsCommandList5* pGraphicsCommandList5, + _In_ D3D12_SHADING_RATE baseShadingRate, + _In_reads_opt_(D3D12_RS_SET_SHADING_RATE_COMBINER_COUNT) const D3D12_SHADING_RATE_COMBINER* combiners); + + void (D3DAPI* RSSetShadingRateImage)( + _Inout_ ID3D12GraphicsCommandList5* pGraphicsCommandList5, + _In_opt_ ID3D12Resource* shadingRateImage); + + // Xbox + + void (D3DAPI* RSSetShadingRateX)( + _Inout_ ID3D12GraphicsCommandList5* pGraphicsCommandList5, + _In_ const D3D12XBOX_SHADING_RATE_SETTINGS* shadingRateSettings); +}; + + +} // extern C + +D3DINTERFACE(ID3D12GraphicsCommandList5, 55050859,4024,474c,98,cf,64,5b,51,dc,48,74) : public ID3D12GraphicsCommandList4 +{ +public: + D3DINLINE D3D12GraphicsCommandList5_Function_Table* GraphicsCommandList5Function() + { + return (D3D12GraphicsCommandList5_Function_Table*)m_pFunction; + } + + D3DINLINE void RSSetShadingRate( + _In_ D3D12_SHADING_RATE baseShadingRate, + _In_reads_opt_(D3D12_RS_SET_SHADING_RATE_COMBINER_COUNT) const D3D12_SHADING_RATE_COMBINER* combiners) + { + GraphicsCommandList5Function()->RSSetShadingRate(this, baseShadingRate, combiners); + } + + D3DINLINE void RSSetShadingRateImage( + _In_opt_ ID3D12Resource* shadingRateImage) + { + GraphicsCommandList5Function()->RSSetShadingRateImage(this, shadingRateImage); + } + + D3DINLINE void RSSetShadingRateX( + _In_opt_ const D3D12XBOX_SHADING_RATE_SETTINGS* shadingRateSettings) + { + GraphicsCommandList5Function()->RSSetShadingRateX(this, shadingRateSettings); + } +}; + + + + + +extern "C" +{ + +typedef struct D3D12_DISPATCH_MESH_ARGUMENTS +{ + UINT ThreadGroupCountX; + UINT ThreadGroupCountY; + UINT ThreadGroupCountZ; +} D3D12_DISPATCH_MESH_ARGUMENTS; + + +// Deprecated +typedef struct D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC +{ + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC Desc; + UINT NumPostbuildInfoDescs; + const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* pPostbuildInfoDescs; +} D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC; + +typedef enum D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE +{ + D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE_PARAMS1, + D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE_PARAMS2, + D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE_PARAMS3, +} D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE; + +typedef struct D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS1 +{ + D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE Type; // D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE_PARAMS1 + float QuadJoinThreshold; // Acceptable box growth size in %% to accept two adjacent triangles as a quad. Large values will merge any triangles into a quad possible causing perf regressions. + float FP16BoxInflationThreshold; // Acceptable compress->decompress error for F16 box use. Larger errors mean perf regression because more rays are caught in the box pointlessly. + BYTE TreeletFirstLevel; // First level of the tree where TR7 begins + BYTE TreeletNumLevels; // Number of levels for TR7 to walk + BYTE TreeletStepSizeBetweenRounds; // Step multiplier for tree level skipping + BYTE TreeletRoundsLimiter; // Overall rounds limiter +} D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS1; + +inline +void D3D12XboxMakeDefault_D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS1( + D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS1* pParams) +{ + pParams->Type = D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE_PARAMS1; + pParams->QuadJoinThreshold = -1; // Use internal setting + pParams->FP16BoxInflationThreshold = -1; // Use internal setting + pParams->TreeletFirstLevel = 0; // Use internal setting based on build flags + pParams->TreeletNumLevels = 0; // Use internal setting based on build flags + pParams->TreeletStepSizeBetweenRounds = 0; // Use internal setting based on build flags + pParams->TreeletRoundsLimiter = 0; // Use internal setting based on build flags +} + +typedef struct D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS2 +{ + D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE Type; // D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE_PARAMS2 + float TriangleSplitFactor; // Maximum overall allowed tree increase due to triangle splitting. At the moment only affects offline builder, no effect on the runtime builder. + UINT NumberOfElementsAllocated; // If set, the pre-build info should correctly represent the number of instances to pull up otherwise instances will get dropped. To be used with TAPU. Ignored for offline builds. + BYTE OfflineBuilderOptionsNumThreads; // Control the number of threads in the offline builder for this instance of the build. Doesn't affect anything for the runtime builders. + BYTE KDOPTesselationFactorN; // Control the size of the k-DOP and apex point map. Each cube face has N * N * 2 apex points. + BYTE DisableTLASOptimization1; // Disables an experimental optimization for the TLAS + BYTE EnableAutomaticBLASRotation; // Enables an experimental optimization to rotate the BLAS space for faster ray traversal +} D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS2; + +inline +void D3D12XboxMakeDefault_D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS2( + D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS2* pParams) +{ + pParams->Type = D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE_PARAMS2; + pParams->TriangleSplitFactor = -1; // Use internal defaults + pParams->NumberOfElementsAllocated = 0; // Use the "instance count" from the desc + pParams->OfflineBuilderOptionsNumThreads = 0; // Use the default number of threads (1) + pParams->KDOPTesselationFactorN = 0; // Disable k-DOP by default + pParams->DisableTLASOptimization1 = 0; // Enable the optimization by default + pParams->EnableAutomaticBLASRotation = 0; // Disable rotation by default +} + +typedef struct D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS3 +{ + D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE Type; // D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE_PARAMS3 + UINT NumExtraElementsForInstanceSplitting; + float InstanceSplit16Fraction; + float IsolateSARatio; +} D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS3; + +inline +void D3D12XboxMakeDefault_D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS3( + D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_PARAMS3* pParams) +{ + pParams->Type = D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_SUBOBJECT_TYPE_PARAMS3; + pParams->NumExtraElementsForInstanceSplitting = 0xFFFFFFFF; // Use default amount of extra space (depends on build flag) + pParams->InstanceSplit16Fraction = -1; // Use internal defaults + pParams->IsolateSARatio = 0; // Use internal defaults +} + +typedef struct D3D12XBOX_DISPATCH_RAYS_DESC +{ + D3D12_DISPATCH_RAYS_DESC DispatchArgs; + D3D12_GPU_VIRTUAL_ADDRESS_RANGE Scratch; + D3D12XBOX_XDXR_STREAM_DESC ExtraOptions; +} D3D12XBOX_DISPATCH_RAYS_DESC; + +typedef enum D3D12XBOX_COMMAND_LIST_RESET_FLAGS : UINT +{ + D3D12XBOX_COMMAND_LIST_RESET_FLAGS_NONE = 0, + D3D12XBOX_COMMAND_LIST_RESET_FLAGS_MINIMAL_STATE = 1, + D3D12XBOX_COMMAND_LIST_RESET_FLAGS_DONT_SYNC_ON_CLEAR = 2, + D3D12XBOX_COMMAND_LIST_RESET_FLAGS_DONT_SYNC_ON_COPY = 4, + D3D12XBOX_COMMAND_LIST_RESET_FLAGS_DONT_SYNC_ON_CLEAR_OR_COPY = + D3D12XBOX_COMMAND_LIST_RESET_FLAGS_DONT_SYNC_ON_CLEAR | + D3D12XBOX_COMMAND_LIST_RESET_FLAGS_DONT_SYNC_ON_COPY, + D3D12XBOX_COMMAND_LIST_RESET_FLAGS_FORCE_HIGH_PRECISION_GUARDBAND = 8, +} D3D12XBOX_COMMAND_LIST_RESET_FLAGS; + +// +// ID3D12GraphicsCommandList6 +// + +struct D3D12GraphicsCommandList6_Function_Table +{ + D3D12GraphicsCommandList5_Function_Table CommandListFunction; + + void (D3DAPI* DispatchMesh)( + _Inout_ ID3D12GraphicsCommandList6* pGraphicsCommandList6, + _In_ UINT ThreadGroupCountX, + _In_ UINT ThreadGroupCountY, + _In_ UINT ThreadGroupCountZ); + + // Deprecated + void (D3DAPI* BuildRaytracingAccelerationStructureBatchedX)( + _Inout_ ID3D12GraphicsCommandList6* pGraphicsCommandList6, + _In_ UINT NumBuildDescs, + _In_ const D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC* pDescs); + + void (D3DAPI* SyncTopOfPipeX)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ D3D12XBOX_SYNC_FLAGS SyncFlags, + _In_ D3D12XBOX_SYNC_CONTROL_FLAGS ControlFlags, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BaseAddress, + _In_ SIZE_T SizeInBytes); + + void (D3DAPI* SyncBottomOfPipeX)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ D3D12XBOX_SYNC_FLAGS SyncFlags, + _In_ D3D12XBOX_SYNC_CONTROL_FLAGS ControlFlags, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BaseAddress, + _In_ SIZE_T SizeInBytes); + + void (D3DAPI* BuildRaytracingAccelerationStructureBatched2X)( + _Inout_ ID3D12GraphicsCommandList6* pGraphicsCommandList6, + _In_ UINT NumBuildDescs, + _In_ const D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2* pDescs); + + void (D3DAPI* DispatchRaysX)( + _Inout_ ID3D12GraphicsCommandList6* pGraphicsCommandList4, + _In_ const D3D12XBOX_DISPATCH_RAYS_DESC* pDesc); + + void (D3DAPI* PrefetchMemoryX)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BaseAddress, + _In_ UINT64 SizeBytes, + _In_ D3D12XBOX_PREFETCH_MEMORY_FLAGS Flags); + + void (D3DAPI* PrefetchPipelineStateX)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ ID3D12PipelineState* pPipelineState, + _In_ UINT64 ShaderPrefetchSizeBytes, + _In_ D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAGS PipelineStateFlags, + _In_ D3D12XBOX_PREFETCH_MEMORY_FLAGS Flags); + + void (D3DAPI* Write32BitValueBottomOfPipe2X)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT Value, + _In_ D3D12XBOX_SYNC_FLAGS SyncFlags, + _In_ D3D12XBOX_SYNC_CONTROL_FLAGS ControlFlags, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS WriteFlags); + + void (D3DAPI* Write64BitValueBottomOfPipe2X)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 Value, + _In_ D3D12XBOX_SYNC_FLAGS SyncFlags, + _In_ D3D12XBOX_SYNC_CONTROL_FLAGS ControlFlags, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS WriteFlags); + + HRESULT (D3DAPI* ResetX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ ID3D12CommandAllocator* pAllocator, + _In_opt_ ID3D12PipelineState* pInitialState, + _In_ D3D12XBOX_COMMAND_LIST_RESET_FLAGS Flags); + + void (D3DAPI* ResourceBarrierX)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER* pBarriers, + _In_ D3D12XBOX_RESOURCE_BARRIER_SHARED_FLAGS Flags, + _Out_opt_ D3D12XBOX_RESOURCE_BARRIER_SUMMARY_ACTIONS* pActions); + + void (D3DAPI* SetShaderScratchSpaceX)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ D3D12XBOX_SET_SHADER_SCRATCH_SPACE_FLAGS Flags, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 SizeBytes, + _In_ UINT SizePerWaveInBytes); + + void (D3DAPI* OMSetSampleMaskX)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ UINT64 QuadSampleMask); + + void (D3DAPI* WritePRTLODStatisticsX)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_ const D3D12XBOX_PRT_LOD_REPORT_DESC* pReport); + + HRESULT(D3DAPI* EnableLiveDebuggingX)( + _Inout_ ID3D12GraphicsCommandList6* pCommandList, + _In_opt_ D3D12XBOX_LIVE_DEBUGGING_PARAMETERS* pDebugParams); + + void (D3DAPI *SetComputeShaderLaunchParametersX)( + _Inout_ ID3D12GraphicsCommandList* pCommandList, + _In_ const D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETERS* pLaunchParameters); +}; + + +} // extern C + +D3DINTERFACE(ID3D12GraphicsCommandList6, c3827890,4024,474c,98,cf,64,5b,51,dc,48,74) : public ID3D12GraphicsCommandList5 +{ +public: + D3DINLINE D3D12GraphicsCommandList6_Function_Table* GraphicsCommandList6Function() + { + return (D3D12GraphicsCommandList6_Function_Table*)m_pFunction; + } + + D3DINLINE void DispatchMesh( + _In_ UINT ThreadGroupCountX, + _In_ UINT ThreadGroupCountY, + _In_ UINT ThreadGroupCountZ) + { + GraphicsCommandList6Function()->DispatchMesh(this, + ThreadGroupCountX, + ThreadGroupCountY, + ThreadGroupCountZ); + } + + // Deprecated + //D3DINLINE void BuildRaytracingAccelerationStructureBatchedX( + // _In_ UINT NumBuildDescs, + // _In_ const D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC* pDescs) + //{ + // GraphicsCommandList6Function()->BuildRaytracingAccelerationStructureBatchedX(this, + // NumBuildDescs, + // pDescs); + //} + + D3DINLINE void D3DAPI SyncTopOfPipeX( + _In_ D3D12XBOX_SYNC_FLAGS SyncFlags, + _In_ D3D12XBOX_SYNC_CONTROL_FLAGS ControlFlags, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BaseAddress, + _In_ SIZE_T SizeInBytes) + { + GraphicsCommandList6Function()->SyncTopOfPipeX(this, + SyncFlags, + ControlFlags, + BaseAddress, + SizeInBytes); + } + + D3DINLINE void D3DAPI SyncBottomOfPipeX( + _In_ D3D12XBOX_SYNC_FLAGS SyncFlags, + _In_ D3D12XBOX_SYNC_CONTROL_FLAGS ControlFlags, + _In_ D3D12_GPU_VIRTUAL_ADDRESS BaseAddress, + _In_ SIZE_T SizeInBytes) + { + GraphicsCommandList6Function()->SyncBottomOfPipeX(this, + SyncFlags, + ControlFlags, + BaseAddress, + SizeInBytes); + } + + D3DINLINE void BuildRaytracingAccelerationStructureBatched2X( + _In_ UINT NumBuildDescs, + _In_ const D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2* pDescs) + { + GraphicsCommandList6Function()->BuildRaytracingAccelerationStructureBatched2X(this, + NumBuildDescs, + pDescs); + } + + D3DINLINE void D3DAPI DispatchRaysX( + _In_ const D3D12XBOX_DISPATCH_RAYS_DESC* pDesc) + { + return GraphicsCommandList6Function()->DispatchRaysX( + this, + pDesc); + } + + D3DINLINE void D3DAPI PrefetchMemoryX( + _In_ D3D12_GPU_VIRTUAL_ADDRESS BaseAddress, + _In_ UINT64 SizeBytes, + _In_ D3D12XBOX_PREFETCH_MEMORY_FLAGS Flags) + { + GraphicsCommandList6Function()->PrefetchMemoryX(this, + BaseAddress, + SizeBytes, + Flags); + } + + D3DINLINE void D3DAPI PrefetchPipelineStateX( + _In_ ID3D12PipelineState* pPipelineState, + _In_ UINT64 ShaderPrefetchSizeBytes, + _In_ D3D12XBOX_PREFETCH_PIPELINE_STATE_FLAGS PipelineStateFlags, + _In_ D3D12XBOX_PREFETCH_MEMORY_FLAGS Flags) + { + GraphicsCommandList6Function()->PrefetchPipelineStateX(this, + pPipelineState, + ShaderPrefetchSizeBytes, + PipelineStateFlags, + Flags); + } + + D3DINLINE void D3DAPI Write32BitValueBottomOfPipe2X( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT Value, + _In_ D3D12XBOX_SYNC_FLAGS SyncFlags, + _In_ D3D12XBOX_SYNC_CONTROL_FLAGS ControlFlags, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS WriteFlags) + { + GraphicsCommandList6Function()->Write32BitValueBottomOfPipe2X(this, + Destination, + Value, + SyncFlags, + ControlFlags, + WriteFlags); + } + + D3DINLINE void D3DAPI Write64BitValueBottomOfPipe2X( + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 Value, + _In_ D3D12XBOX_SYNC_FLAGS SyncFlags, + _In_ D3D12XBOX_SYNC_CONTROL_FLAGS ControlFlags, + _In_ D3D12XBOX_WRITE_VALUE_BOP_FLAGS WriteFlags) + { + GraphicsCommandList6Function()->Write64BitValueBottomOfPipe2X(this, + Destination, + Value, + SyncFlags, + ControlFlags, + WriteFlags); + } + + D3DINLINE HRESULT D3DAPI ResetX( + _In_ ID3D12CommandAllocator* pAllocator, + _In_opt_ ID3D12PipelineState* pInitialState, + _In_ D3D12XBOX_COMMAND_LIST_RESET_FLAGS Flags) + { + return GraphicsCommandList6Function()->ResetX(this, + pAllocator, + pInitialState, + Flags); + } + + D3DINLINE void D3DAPI ResourceBarrierX( + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER* pBarriers, + _In_ D3D12XBOX_RESOURCE_BARRIER_SHARED_FLAGS Flags, + _Out_opt_ D3D12XBOX_RESOURCE_BARRIER_SUMMARY_ACTIONS* pActions) + { + GraphicsCommandList6Function()->ResourceBarrierX(this, + NumBarriers, + pBarriers, + Flags, + pActions); + } + + D3DINLINE void D3DAPI SetShaderScratchSpaceX( + _In_ D3D12XBOX_SET_SHADER_SCRATCH_SPACE_FLAGS Flags, + _In_ D3D12_GPU_VIRTUAL_ADDRESS Destination, + _In_ UINT64 SizeBytes, + _In_ UINT SizePerWaveInBytes) + { + GraphicsCommandList6Function()->SetShaderScratchSpaceX(this, + Flags, + Destination, + SizeBytes, + SizePerWaveInBytes); + } + + D3DINLINE void D3DAPI OMSetSampleMaskX( + _In_ UINT64 QuadSampleMask) + { + GraphicsCommandList6Function()->OMSetSampleMaskX(this, QuadSampleMask); + } + + D3DINLINE void D3DAPI WritePRTLODStatisticsX( + _In_ const D3D12XBOX_PRT_LOD_REPORT_DESC* pReport) + { + GraphicsCommandList6Function()->WritePRTLODStatisticsX(this, pReport); + } + + D3DINLINE HRESULT D3DAPI EnableLiveDebuggingX( + _In_opt_ D3D12XBOX_LIVE_DEBUGGING_PARAMETERS* pDebugParams) + { + return GraphicsCommandList6Function()->EnableLiveDebuggingX(this, pDebugParams); + } + + D3DINLINE void D3DAPI SetComputeShaderLaunchParametersX( + _In_ const D3D12XBOX_COMPUTE_SHADER_LAUNCH_PARAMETERS* pLaunchParameters) + { + GraphicsCommandList6Function()->SetComputeShaderLaunchParametersX(this, pLaunchParameters); + } +}; + +// +// ID3D12GraphicsCommandList7 +// + +extern "C" +{ + struct D3D12GraphicsCommandList7_Function_Table + { + D3D12GraphicsCommandList6_Function_Table ParentFunction; + + void (D3DAPI* Barrier)( + _Inout_ ID3D12GraphicsCommandList7* pGraphicsCommandList, + UINT32 NumBarrierGroups, + _In_reads_(NumBarrierGroups) const D3D12_BARRIER_GROUP* pBarrierGroups + ); + }; + + +} // extern C + +D3DINTERFACE(ID3D12GraphicsCommandList7, dd171223, 8b61, 4769, 90, e3, 16, 0c, cd, e4, e2, c1) : public ID3D12GraphicsCommandList6 +{ +public: + D3DINLINE D3D12GraphicsCommandList7_Function_Table * GraphicsCommandList7Function() + { + return (D3D12GraphicsCommandList7_Function_Table*)m_pFunction; + } + + D3DINLINE void Barrier( + UINT32 NumBarrierGroups, + _In_reads_(NumBarrierGroups) const D3D12_BARRIER_GROUP * pBarrierGroups + ) + { + GraphicsCommandList7Function()->Barrier(this, NumBarrierGroups, pBarrierGroups); + } +}; +// +// ID3D12GraphicsCommandList8 +// + +extern "C" +{ + + struct D3D12GraphicsCommandList8_Function_Table + { + D3D12GraphicsCommandList7_Function_Table CmdList7; + + void (D3DAPI* OMSetFrontAndBackStencilRef)( + _Inout_ ID3D12GraphicsCommandList8* pGraphicsCommandList, + _In_ UINT FrontStencilRef, + _In_ UINT BackStencilRef + ); + + void* (D3DAPI* AllocateFromCommandAllocatorX)( + _Inout_ ID3D12GraphicsCommandList8* pGraphicsCommandList, + _In_ UINT sizeBytes, + _In_ UINT alignmentBytes + ); + + HRESULT (D3DAPI* RehydrateRaytracingAccelerationStructureBatchedX)( + _Inout_ ID3D12GraphicsCommandList8* pGraphicsCommandList, + _In_ UINT NumInputs, + _In_reads_(NumInputs) const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* Inputs + ); + }; + +} // extern C + +D3DINTERFACE(ID3D12GraphicsCommandList8, ee936ef9, 599d, 4d28, 93, 8e, 23, c4, ad, 05, ce, 51) : public ID3D12GraphicsCommandList7 +{ +public: + D3DINLINE D3D12GraphicsCommandList8_Function_Table * GraphicsCommandList8Function() + { + return (D3D12GraphicsCommandList8_Function_Table*)m_pFunction; + } + + D3DINLINE void OMSetFrontAndBackStencilRef( + _In_ UINT FrontStencilRef, + _In_ UINT BackStencilRef + ) + { + GraphicsCommandList8Function()->OMSetFrontAndBackStencilRef(this, FrontStencilRef, BackStencilRef); + } + + D3DINLINE void* AllocateFromCommandAllocatorX( + _In_ UINT sizeBytes, + _In_ UINT alignmentBytes + ) + { + return GraphicsCommandList8Function()->AllocateFromCommandAllocatorX(this, sizeBytes, alignmentBytes); + } + + D3DINLINE HRESULT RehydrateRaytracingAccelerationStructureBatchedX( + _In_ UINT NumInputs, + _In_reads_(NumInputs) const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* Inputs + ) + { + return GraphicsCommandList8Function()->RehydrateRaytracingAccelerationStructureBatchedX(this, NumInputs, Inputs); + } + +}; + +extern "C" +{ + +// +// ID3D12XboxCounterSet +// + +struct D3D12CounterSet_Function_Table +{ + D3D12DeviceChild_Function_Table DeviceChildFunction; + + SIZE_T (D3DAPI* GetCounterDataSizeX)( + _Inout_ ID3D12XboxCounterSet* pCounterSet); + + HRESULT (D3DAPI* RetrieveCounterDataX)( + _Inout_ ID3D12XboxCounterSet* pCounterSet, + _In_ ID3D12Resource* pSourceBuffer, + _In_ UINT64 AlignedSourceBufferOffset, + _Out_ D3D12XBOX_COUNTER_DATA* pCounterData); +}; + +} + +D3DINTERFACE(ID3D12XboxCounterSet, 9598d782,875d,4fa0,a0,8e,dc,25,ec,17,d0,2c) : public ID3D12DeviceChild +{ +public: + + D3DINLINE D3D12CounterSet_Function_Table* CounterSetFunction() + { + return (D3D12CounterSet_Function_Table*)m_pFunction; + } + + D3DINLINE SIZE_T D3DAPI GetCounterDataSizeX() + { + return CounterSetFunction()->GetCounterDataSizeX(this); + } + + D3DINLINE HRESULT D3DAPI RetrieveCounterDataX( + _In_ ID3D12Resource* pSourceBuffer, + _In_ UINT64 AlignedSourceBufferOffset, + _Out_ D3D12XBOX_COUNTER_DATA* pCounterData) + { + return CounterSetFunction()->RetrieveCounterDataX(this, + pSourceBuffer, + AlignedSourceBufferOffset, + pCounterData); + } +}; + +extern "C" +{ + +// +// ID3D12Tools +// + +struct D3D12Tools_Function_Table +{ + GraphicsUnknown_Function_Table UnknownFunction; + + void (D3DAPI* EnableShaderInstrumentation)( + _Inout_ ID3D12Tools* pTools, + BOOL bEnable); + + BOOL (D3DAPI* ShaderInstrumentationEnabled)( + _Inout_ ID3D12Tools* pTools); +}; + + +} + +D3DINTERFACE(ID3D12Tools, 7071e1f0,e84b,4b33,97,4f,12,fa,49,de,65,c5) : public IGraphicsUnknown +{ +public: + + D3DINLINE D3D12Tools_Function_Table* ToolsFunction() + { + return (D3D12Tools_Function_Table*)m_pFunction; + } + + D3DINLINE void D3DAPI EnableShaderInstrumentation( + BOOL bEnable) + { + ToolsFunction()->EnableShaderInstrumentation(this, bEnable); + } + + D3DINLINE BOOL D3DAPI ShaderInstrumentationEnabled() + { + return ToolsFunction()->ShaderInstrumentationEnabled(this); + } +}; + + +//================================================================================================================================== +// +// Info Queue +// +//================================================================================================================================== +typedef enum D3D12_MESSAGE_CATEGORY { + D3D12_MESSAGE_CATEGORY_APPLICATION_DEFINED, + D3D12_MESSAGE_CATEGORY_MISCELLANEOUS, + D3D12_MESSAGE_CATEGORY_INITIALIZATION, + D3D12_MESSAGE_CATEGORY_CLEANUP, + D3D12_MESSAGE_CATEGORY_COMPILATION, + D3D12_MESSAGE_CATEGORY_STATE_CREATION, + D3D12_MESSAGE_CATEGORY_STATE_SETTING, + D3D12_MESSAGE_CATEGORY_STATE_GETTING, + D3D12_MESSAGE_CATEGORY_RESOURCE_MANIPULATION, + D3D12_MESSAGE_CATEGORY_EXECUTION, + D3D12_MESSAGE_CATEGORY_SHADER, +} D3D12_MESSAGE_CATEGORY; + +typedef enum D3D12_MESSAGE_SEVERITY { + D3D12_MESSAGE_SEVERITY_CORRUPTION, + D3D12_MESSAGE_SEVERITY_ERROR, + D3D12_MESSAGE_SEVERITY_WARNING, + D3D12_MESSAGE_SEVERITY_INFO, + D3D12_MESSAGE_SEVERITY_MESSAGE +} D3D12_MESSAGE_SEVERITY; + +// Unique ID for every error +typedef enum D3D12_MESSAGE_ID { + D3D12_MESSAGE_ID_UNKNOWN = 0, + + //-------------------------------------------------------------------------- + // Messages Used by Core + // Message IDs generated from core are at the beginning + // since the core changes less frequently than the debug layer. + + // End of Messages used by Core + // ------------------------------------------------------------------------ + D3D12_MESSAGE_ID_STRING_FROM_APPLICATION, + D3D12_MESSAGE_ID_CORRUPTED_THIS, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER1, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER2, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER3, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER4, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER5, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER6, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER7, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER8, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER9, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER10, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER11, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER12, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER13, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER14, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER15, + D3D12_MESSAGE_ID_CORRUPTED_MULTITHREADING, + D3D12_MESSAGE_ID_MESSAGE_REPORTING_OUTOFMEMORY, + + D3D12_MESSAGE_ID_GETPRIVATEDATA_MOREDATA, + D3D12_MESSAGE_ID_SETPRIVATEDATA_INVALIDFREEDATA, + D3D12_MESSAGE_ID_SETPRIVATEDATA_INVALIDIUNKNOWN, + D3D12_MESSAGE_ID_SETPRIVATEDATA_INVALIDFLAGS, + D3D12_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS, + D3D12_MESSAGE_ID_SETPRIVATEDATA_OUTOFMEMORY, + + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_UNRECOGNIZEDFORMAT, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDESC, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFORMAT, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDVIDEOPLANESLICE, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDPLANESLICE, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDIMENSIONS, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDRESOURCE, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_OUTOFMEMORY_RETURN, + + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_UNRECOGNIZEDFORMAT, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_UNSUPPORTEDFORMAT, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDESC, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDFORMAT, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDVIDEOPLANESLICE, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDPLANESLICE, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDIMENSIONS, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDRESOURCE, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_OUTOFMEMORY_RETURN, + + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_UNRECOGNIZEDFORMAT, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDESC, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFORMAT, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDIMENSIONS, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDRESOURCE, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_OUTOFMEMORY_RETURN, + + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TOOMANYELEMENTS, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDFORMAT, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INCOMPATIBLEFORMAT, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOT, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDINPUTSLOTCLASS, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_STEPRATESLOTCLASSMISMATCH, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOTCLASSCHANGE, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSTEPRATECHANGE, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDALIGNMENT, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_DUPLICATESEMANTIC, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_NULLSEMANTIC, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_MISSINGELEMENT, + + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERTYPE, + + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERBYTECODE, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERTYPE, + + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERBYTECODE, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERTYPE, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMENTRIES, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSTREAMSTRIDEUNUSED, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDDECL, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_EXPECTEDDECL, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSLOT0EXPECTED, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSLOT, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_ONLYONEELEMENTPERSLOT, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCOMPONENTCOUNT, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTARTCOMPONENTANDCOMPONENTCOUNT, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDGAPDEFINITION, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_REPEATEDOUTPUT, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSTREAMSTRIDE, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGSEMANTIC, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MASKMISMATCH, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_CANTHAVEONLYGAPS, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DECLTOOCOMPLEX, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGOUTPUTSIGNATURE, + + D3D12_MESSAGE_ID_CREATEPIXELSHADER_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERTYPE, + + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFILLMODE, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDCULLMODE, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDDEPTHBIASCLAMP, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDSLOPESCALEDDEPTHBIAS, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_NULLDESC, + + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHWRITEMASK, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHFUNC, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFAILOP, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILZFAILOP, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILPASSOP, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFUNC, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFAILOP, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILZFAILOP, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILPASSOP, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFUNC, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_NULLDESC, + + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLEND, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLEND, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOP, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLENDALPHA, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLENDALPHA, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOPALPHA, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDRENDERTARGETWRITEMASK, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_NULLDESC, + + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDFILTER, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSU, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSV, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSW, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMIPLODBIAS, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXANISOTROPY, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDCOMPARISONFUNC, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMINLOD, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXLOD, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_NULLDESC, + + D3D12_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNRECOGNIZED, + D3D12_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNDEFINED, + + D3D12_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_INVALIDVIEWPORT, + + D3D12_MESSAGE_ID_DEVICE_RSSETSCISSORRECTS_INVALIDSCISSOR, + + D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_DENORMFLUSH, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DENORMFLUSH, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALID, + + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCE, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDDESTINATIONSTATE, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCESTATE, + + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSUBRESOURCE, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONBOX, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSTATE, + + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_INVALID, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_SUBRESOURCE_INVALID, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_INVALID, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_SUBRESOURCE_INVALID, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_FORMAT_INVALID, + + D3D12_MESSAGE_ID_BUFFER_MAP_INVALIDMAPTYPE, + D3D12_MESSAGE_ID_BUFFER_MAP_INVALIDFLAGS, + D3D12_MESSAGE_ID_BUFFER_MAP_ALREADYMAPPED, + D3D12_MESSAGE_ID_BUFFER_MAP_DEVICEREMOVED_RETURN, + D3D12_MESSAGE_ID_BUFFER_UNMAP_NOTMAPPED, + + D3D12_MESSAGE_ID_TEXTURE1D_MAP_INVALIDMAPTYPE, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_INVALIDFLAGS, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_ALREADYMAPPED, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_DEVICEREMOVED_RETURN, + D3D12_MESSAGE_ID_TEXTURE1D_UNMAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_TEXTURE1D_UNMAP_NOTMAPPED, + + D3D12_MESSAGE_ID_TEXTURE2D_MAP_INVALIDMAPTYPE, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_INVALIDFLAGS, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_ALREADYMAPPED, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_DEVICEREMOVED_RETURN, + D3D12_MESSAGE_ID_TEXTURE2D_UNMAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_TEXTURE2D_UNMAP_NOTMAPPED, + + D3D12_MESSAGE_ID_TEXTURE3D_MAP_INVALIDMAPTYPE, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_INVALIDFLAGS, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_ALREADYMAPPED, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_DEVICEREMOVED_RETURN, + D3D12_MESSAGE_ID_TEXTURE3D_UNMAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_TEXTURE3D_UNMAP_NOTMAPPED, + + D3D12_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_DEPRECATED, + D3D12_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_FORMAT_DEPRECATED, + + D3D12_MESSAGE_ID_SETEXCEPTIONMODE_UNRECOGNIZEDFLAGS, + D3D12_MESSAGE_ID_SETEXCEPTIONMODE_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_SETEXCEPTIONMODE_DEVICEREMOVED_RETURN, + + D3D12_MESSAGE_ID_REF_SIMULATING_INFINITELY_FAST_HARDWARE, + D3D12_MESSAGE_ID_REF_THREADING_MODE, + D3D12_MESSAGE_ID_REF_UMDRIVER_EXCEPTION, + D3D12_MESSAGE_ID_REF_KMDRIVER_EXCEPTION, + D3D12_MESSAGE_ID_REF_HARDWARE_EXCEPTION, + D3D12_MESSAGE_ID_REF_ACCESSING_INDEXABLE_TEMP_OUT_OF_RANGE, + D3D12_MESSAGE_ID_REF_PROBLEM_PARSING_SHADER, + D3D12_MESSAGE_ID_REF_OUT_OF_MEMORY, + D3D12_MESSAGE_ID_REF_INFO, + + //drawtime validation + D3D12_MESSAGE_ID_DEVICE_DRAW_VERTEXPOS_OVERFLOW, + D3D12_MESSAGE_ID_DEVICE_DRAWINDEXED_INDEXPOS_OVERFLOW, + D3D12_MESSAGE_ID_DEVICE_DRAWINSTANCED_VERTEXPOS_OVERFLOW, + D3D12_MESSAGE_ID_DEVICE_DRAWINSTANCED_INSTANCEPOS_OVERFLOW, + + D3D12_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INSTANCEPOS_OVERFLOW, + D3D12_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INDEXPOS_OVERFLOW, + + D3D12_MESSAGE_ID_DEVICE_DRAW_VERTEX_SHADER_NOT_SET, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERINDEX, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_COMPONENTTYPE, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERMASK, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SYSTEMVALUE, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS, + + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_ROOT_SIGNATURE_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_BUFFER_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INPUTLAYOUT_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_CONSTANT_BUFFER_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_CONSTANT_BUFFER_TOO_SMALL, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SAMPLER_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SHADERRESOURCEVIEW_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VIEW_DIMENSION_MISMATCH, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_BUFFER_TOO_SMALL, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_BUFFER_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_BUFFER_FORMAT_INVALID, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_BUFFER_TOO_SMALL, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_GS_INPUT_PRIMITIVE_MISMATCH, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_RETURN_TYPE_MISMATCH, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_POSITION_NOT_PRESENT, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OUTPUT_STREAM_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_BOUND_RESOURCE_MAPPED, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INVALID_PRIMITIVETOPOLOGY, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_OFFSET_UNALIGNED, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_STRIDE_UNALIGNED, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_OFFSET_UNALIGNED, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OUTPUT_STREAM_OFFSET_UNALIGNED, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_FORMAT_LD_UNSUPPORTED, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_FORMAT_SAMPLE_UNSUPPORTED, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_FORMAT_SAMPLE_C_UNSUPPORTED, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_MULTISAMPLE_UNSUPPORTED, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SO_TARGETS_BOUND_WITHOUT_SOURCE, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SO_STRIDE_LARGER_THAN_BUFFER, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0, + D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_AT_FAULT, + D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_POSSIBLY_AT_FAULT, + D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_NOT_AT_FAULT, + + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BADINTERFACE_RETURN, + + D3D12_MESSAGE_ID_DEVICE_DRAW_VIEWPORT_NOT_SET, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TRAILING_DIGIT_IN_SEMANTIC, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_TRAILING_DIGIT_IN_SEMANTIC, + D3D12_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_DENORMFLUSH, + D3D12_MESSAGE_ID_OMSETRENDERTARGETS_INVALIDVIEW, + D3D12_MESSAGE_ID_DEVICE_SETTEXTFILTERSIZE_INVALIDDIMENSIONS, + D3D12_MESSAGE_ID_DEVICE_DRAW_SAMPLER_MISMATCH, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TYPE_MISMATCH, + + D3D12_MESSAGE_ID_BLENDSTATE_GETDESC_LEGACY, + D3D12_MESSAGE_ID_SHADERRESOURCEVIEW_GETDESC_LEGACY, + + D3D12_MESSAGE_ID_DEVICE_DRAW_PS_OUTPUT_TYPE_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_GATHER_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_DRAW_INVALID_USE_OF_CENTER_MULTISAMPLE_PATTERN, + D3D12_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_STRIDE_TOO_LARGE, + D3D12_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_INVALIDRANGE, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_EMPTY_LAYOUT, + D3D12_MESSAGE_ID_DEVICE_DRAW_RESOURCE_SAMPLE_COUNT_MISMATCH, + + D3D12_MESSAGE_ID_LIVE_OBJECT_SUMMARY, + D3D12_MESSAGE_ID_LIVE_BUFFER, + D3D12_MESSAGE_ID_LIVE_TEXTURE1D, + D3D12_MESSAGE_ID_LIVE_TEXTURE2D, + D3D12_MESSAGE_ID_LIVE_TEXTURE3D, + D3D12_MESSAGE_ID_LIVE_SHADERRESOURCEVIEW, + D3D12_MESSAGE_ID_LIVE_RENDERTARGETVIEW, + D3D12_MESSAGE_ID_LIVE_DEPTHSTENCILVIEW, + D3D12_MESSAGE_ID_LIVE_VERTEXSHADER, + D3D12_MESSAGE_ID_LIVE_GEOMETRYSHADER, + D3D12_MESSAGE_ID_LIVE_PIXELSHADER, + D3D12_MESSAGE_ID_LIVE_INPUTLAYOUT, + D3D12_MESSAGE_ID_LIVE_SAMPLER, + D3D12_MESSAGE_ID_LIVE_BLENDSTATE, + D3D12_MESSAGE_ID_LIVE_DEPTHSTENCILSTATE, + D3D12_MESSAGE_ID_LIVE_RASTERIZERSTATE, + D3D12_MESSAGE_ID_LIVE_QUERY, + D3D12_MESSAGE_ID_LIVE_PREDICATE, + D3D12_MESSAGE_ID_LIVE_COUNTER, + D3D12_MESSAGE_ID_LIVE_DEVICE, + D3D12_MESSAGE_ID_LIVE_SWAPCHAIN, + + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFLAGS, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDCLASSLINKAGE, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDCLASSLINKAGE, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMSTREAMS, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTREAMTORASTERIZER, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDSTREAMS, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCLASSLINKAGE, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDCLASSLINKAGE, + + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTREAM, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDENTRIES, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDSTRIDES, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMSTRIDES, + + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDCALL, + D3D12_MESSAGE_ID_CREATEHULLSHADER_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDSHADERBYTECODE, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDSHADERTYPE, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDCLASSLINKAGE, + + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDCALL, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDSHADERBYTECODE, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDSHADERTYPE, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDCLASSLINKAGE, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_XOR_DS_MISMATCH, + + D3D12_MESSAGE_ID_DEVICE_DRAWINDIRECT_INVALID_ARG_BUFFER, + D3D12_MESSAGE_ID_DEVICE_DRAWINDIRECT_OFFSET_UNALIGNED, + D3D12_MESSAGE_ID_DEVICE_DRAWINDIRECT_OFFSET_OVERFLOW, + + D3D12_MESSAGE_ID_RESOURCE_MAP_INVALIDMAPTYPE, + D3D12_MESSAGE_ID_RESOURCE_MAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_RESOURCE_MAP_INVALIDFLAGS, + D3D12_MESSAGE_ID_RESOURCE_MAP_ALREADYMAPPED, + D3D12_MESSAGE_ID_RESOURCE_MAP_DEVICEREMOVED_RETURN, + D3D12_MESSAGE_ID_RESOURCE_MAP_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_RESOURCE_MAP_WITHOUT_INITIAL_DISCARD, + D3D12_MESSAGE_ID_RESOURCE_UNMAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_RESOURCE_UNMAP_NOTMAPPED, + + D3D12_MESSAGE_ID_DEVICE_DRAW_RASTERIZING_CONTROL_POINTS, + D3D12_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_DS_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_DRAW_HULL_SHADER_INPUT_TOPOLOGY_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_DS_CONTROL_POINT_COUNT_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_DS_TESSELLATOR_DOMAIN_MISMATCH, + + D3D12_MESSAGE_ID_DEVICE_CHECKFEATURESUPPORT_UNRECOGNIZED_FEATURE, + D3D12_MESSAGE_ID_DEVICE_CHECKFEATURESUPPORT_MISMATCHED_DATA_SIZE, + D3D12_MESSAGE_ID_DEVICE_CHECKFEATURESUPPORT_INVALIDARG_RETURN, + + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_INVALIDCALL, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_INVALIDSHADERBYTECODE, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_INVALIDCLASSLINKAGE, + D3D12_MESSAGE_ID_DEVICE_CSSETSHADERRESOURCES_VIEWS_EMPTY, + D3D12_MESSAGE_ID_CSSETCONSTANTBUFFERS_INVALIDBUFFER, + D3D12_MESSAGE_ID_DEVICE_CSSETCONSTANTBUFFERS_BUFFERS_EMPTY, + D3D12_MESSAGE_ID_DEVICE_CSSETSAMPLERS_SAMPLERS_EMPTY, + D3D12_MESSAGE_ID_DEVICE_CSGETSHADERRESOURCES_VIEWS_EMPTY, + D3D12_MESSAGE_ID_DEVICE_CSGETCONSTANTBUFFERS_BUFFERS_EMPTY, + D3D12_MESSAGE_ID_DEVICE_CSGETSAMPLERS_SAMPLERS_EMPTY, + + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_DOUBLEFLOATOPSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_DOUBLEFLOATOPSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_DOUBLEFLOATOPSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_DOUBLEFLOATOPSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DOUBLEFLOATOPSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_DOUBLEFLOATOPSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_DOUBLEFLOATOPSNOTSUPPORTED, + + D3D12_MESSAGE_ID_CREATEBUFFER_INVALIDSTRUCTURESTRIDE, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFLAGS, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDRESOURCE, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDDESC, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDFORMAT, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDVIDEOPLANESLICE, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDPLANESLICE, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDDIMENSIONS, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_UNRECOGNIZEDFORMAT, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_OVERLAPPING_OLD_SLOTS, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_NO_OP, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_CLEARUNORDEREDACCESSVIEW_DENORMFLUSH, + D3D12_MESSAGE_ID_DEVICE_CSSETUNORDEREDACCESSS_VIEWS_EMPTY, + D3D12_MESSAGE_ID_DEVICE_CSGETUNORDEREDACCESSS_VIEWS_EMPTY, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDFLAGS, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_INVALID_ARG_BUFFER, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_OFFSET_UNALIGNED, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_OFFSET_OVERFLOW, + + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DEPTH_READONLY, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_STENCIL_READONLY, + D3D12_MESSAGE_ID_CHECKFEATURESUPPORT_FORMAT_DEPRECATED, + + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_RETURN_TYPE_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_NOT_SET, + D3D12_MESSAGE_ID_DEVICE_DRAW_UNORDEREDACCESSVIEW_RENDERTARGETVIEW_OVERLAP, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_DIMENSION_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_APPEND_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMICS_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_STRUCTURE_STRIDE_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_BUFFER_TYPE_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_RAW_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_FORMAT_LD_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_FORMAT_STORE_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_ADD_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_BITWISE_OPS_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_CMPSTORE_CMPEXCHANGE_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_EXCHANGE_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_SIGNED_MINMAX_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_UNSIGNED_MINMAX_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_BOUND_RESOURCE_MAPPED, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_THREADGROUPCOUNT_OVERFLOW, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_THREADGROUPCOUNT_ZERO, + D3D12_MESSAGE_ID_DEVICE_SHADERRESOURCEVIEW_STRUCTURE_STRIDE_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_SHADERRESOURCEVIEW_BUFFER_TYPE_MISMATCH, + D3D12_MESSAGE_ID_DEVICE_SHADERRESOURCEVIEW_RAW_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_UNSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_UNSUPPORTED, + + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_INVALIDOFFSET, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_LARGEOFFSET, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_INVALIDDESTINATIONSTATE, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_INVALIDSOURCESTATE, + + D3D12_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_NOT_SUPPORTED, + D3D12_MESSAGE_ID_CLEARUNORDEREDACCESSVIEWFLOAT_INVALIDFORMAT, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_COUNTER_UNSUPPORTED, + + D3D12_MESSAGE_ID_DEVICE_DRAW_PIXEL_SHADER_WITHOUT_RTV_OR_DSV, + + D3D12_MESSAGE_ID_SHADER_ABORT, + D3D12_MESSAGE_ID_SHADER_MESSAGE, + D3D12_MESSAGE_ID_SHADER_ERROR, + + D3D12_MESSAGE_ID_OFFERRESOURCES_INVALIDRESOURCE, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_ACCESSDENIED_RETURN, + + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFORCEDSAMPLECOUNT, + + D3D12_MESSAGE_ID_DEVICE_DRAW_INVALID_USE_OF_FORCED_SAMPLE_COUNT, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDLOGICOPS, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDARRAYWITHDECODER, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDDARRAYWITHDECODER, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDARRAYWITHDECODER, + D3D12_MESSAGE_ID_DEVICE_LOCKEDOUT_INTERFACE, + + D3D12_MESSAGE_ID_OFFERRESOURCES_INVALIDPRIORITY, + + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_INVALIDVIEW, + + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_DOUBLEEXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_SHADEREXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_DOUBLEEXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_SHADEREXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_DOUBLEEXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_SHADEREXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_DOUBLEEXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_SHADEREXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DOUBLEEXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_SHADEREXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_DOUBLEEXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_SHADEREXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_DOUBLEEXTENSIONSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_SHADEREXTENSIONSNOTSUPPORTED, + + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_MINPRECISION, + + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_UAVSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_UAVSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_UAVSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_UAVSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UAVSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_UAVSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_UAVSNOTSUPPORTED, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_INVALIDOFFSET, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_TOOMANYVIEWS, + + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_NOTSUPPORTED, + + D3D12_MESSAGE_ID_SWAPDEVICECONTEXTSTATE_NOTSUPPORTED, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_PREFERUPDATESUBRESOURCE1, + + D3D12_MESSAGE_ID_GETDC_INACCESSIBLE, + + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_INVALIDRECT, + + D3D12_MESSAGE_ID_DEVICE_DRAW_SAMPLE_MASK_IGNORED_ON_FL9, + + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE1_NOT_SUPPORTED, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BY_NAME_NOT_SUPPORTED, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_NOT_SUPPORTED, + D3D12_MESSAGE_ID_OFFERRELEASE_NOT_SUPPORTED, + + D3D12_MESSAGE_ID_OFFERRESOURCES_INACCESSIBLE, + D3D12_MESSAGE_ID_CREATEVIDEOPROCESSORINPUTVIEW_INVALIDMSAA, + D3D12_MESSAGE_ID_CREATEVIDEOPROCESSOROUTPUTVIEW_INVALIDMSAA, + + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_INVALIDSOURCERECT, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_EMPTYRECT, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_EMPTYDESTBOX, + D3D12_MESSAGE_ID_COPYSUBRESOURCEREGION_EMPTYSOURCEBOX, + D3D12_MESSAGE_ID_DEVICE_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_LOGIC_OPS, + D3D12_MESSAGE_ID_DEVICE_DRAW_DEPTHSTENCILVIEW_NOT_SET, + D3D12_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET, + D3D12_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET_DUE_TO_FLIP_PRESENT, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_NOT_SET_DUE_TO_FLIP_PRESENT, + + D3D12_MESSAGE_ID_GETDATAFORNEWHARDWAREKEY_NULLPARAM, + D3D12_MESSAGE_ID_CHECKCRYPTOSESSIONSTATUS_NULLPARAM, + D3D12_MESSAGE_ID_SETEVENTONHARDWARECONTENTPROTECTIONTILT_NULLPARAM, + D3D12_MESSAGE_ID_GETVIDEODECODERCAPS_NULLPARAM, + D3D12_MESSAGE_ID_GETVIDEODECODERCAPS_ZEROWIDTHHEIGHT, + D3D12_MESSAGE_ID_CHECKVIDEODECODERDOWNSAMPLING_NULLPARAM, + D3D12_MESSAGE_ID_CHECKVIDEODECODERDOWNSAMPLING_INVALIDCOLORSPACE, + D3D12_MESSAGE_ID_CHECKVIDEODECODERDOWNSAMPLING_ZEROWIDTHHEIGHT, + D3D12_MESSAGE_ID_VIDEODECODERENABLEDOWNSAMPLING_NULLPARAM, + D3D12_MESSAGE_ID_VIDEODECODERENABLEDOWNSAMPLING_UNSUPPORTED, + D3D12_MESSAGE_ID_VIDEODECODERUPDATEDOWNSAMPLING_NULLPARAM, + D3D12_MESSAGE_ID_VIDEODECODERUPDATEDOWNSAMPLING_UNSUPPORTED, + D3D12_MESSAGE_ID_CHECKVIDEOPROCESSORFORMATCONVERSION_NULLPARAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETOUTPUTCOLORSPACE1_NULLPARAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETOUTPUTCOLORSPACE1_NULLPARAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMCOLORSPACE1_NULLPARAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMCOLORSPACE1_INVALIDSTREAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMMIRROR_NULLPARAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMMIRROR_INVALIDSTREAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMMIRROR_UNSUPPORTED, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETSTREAMCOLORSPACE1_NULLPARAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETSTREAMMIRROR_NULLPARAM, + D3D12_MESSAGE_ID_RECOMMENDVIDEODECODERDOWNSAMPLING_NULLPARAM, + D3D12_MESSAGE_ID_RECOMMENDVIDEODECODERDOWNSAMPLING_INVALIDCOLORSPACE, + D3D12_MESSAGE_ID_RECOMMENDVIDEODECODERDOWNSAMPLING_ZEROWIDTHHEIGHT, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETOUTPUTSHADERUSAGE_NULLPARAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETOUTPUTSHADERUSAGE_NULLPARAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_NULLPARAM, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_INVALIDSTREAMCOUNT, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_TARGETRECT, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_INVALIDSOURCERECT, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_INVALIDDESTRECT, + + D3D12_MESSAGE_ID_CREATEBUFFER_INVALIDUSAGE, + D3D12_MESSAGE_ID_CREATETEXTURE1D_INVALIDUSAGE, + D3D12_MESSAGE_ID_CREATETEXTURE2D_INVALIDUSAGE, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_LEVEL9_STEPRATE_NOT_1, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_LEVEL9_INSTANCING_NOT_SUPPORTED, + D3D12_MESSAGE_ID_UPDATETILEMAPPINGS_INVALID_PARAMETER, + D3D12_MESSAGE_ID_COPYTILEMAPPINGS_INVALID_PARAMETER, + D3D12_MESSAGE_ID_COPYTILES_INVALID_PARAMETER, + D3D12_MESSAGE_ID_NULL_TILE_MAPPING_ACCESS_WARNING, + D3D12_MESSAGE_ID_NULL_TILE_MAPPING_ACCESS_ERROR, + D3D12_MESSAGE_ID_DIRTY_TILE_MAPPING_ACCESS, + D3D12_MESSAGE_ID_DUPLICATE_TILE_MAPPINGS_IN_COVERED_AREA, + D3D12_MESSAGE_ID_TILE_MAPPINGS_IN_COVERED_AREA_DUPLICATED_OUTSIDE, + D3D12_MESSAGE_ID_TILE_MAPPINGS_SHARED_BETWEEN_INCOMPATIBLE_RESOURCES, + D3D12_MESSAGE_ID_TILE_MAPPINGS_SHARED_BETWEEN_INPUT_AND_OUTPUT, + D3D12_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_INVALIDFLAGS, + D3D12_MESSAGE_ID_GETRESOURCETILING_NONTILED_RESOURCE, + D3D12_MESSAGE_ID_NEED_TO_CALL_TILEDRESOURCEBARRIER, + + D3D12_MESSAGE_ID_CREATEDEVICE_INVALIDARGS, + D3D12_MESSAGE_ID_CREATEDEVICE_WARNING, + + D3D12_MESSAGE_ID_TILED_RESOURCE_TIER_1_BUFFER_TEXTURE_MISMATCH, + + D3D12_MESSAGE_ID_CREATE_CRYPTOSESSION, + D3D12_MESSAGE_ID_CREATE_AUTHENTICATEDCHANNEL, + D3D12_MESSAGE_ID_LIVE_CRYPTOSESSION, + D3D12_MESSAGE_ID_LIVE_AUTHENTICATEDCHANNEL, + D3D12_MESSAGE_ID_DESTROY_CRYPTOSESSION, + D3D12_MESSAGE_ID_DESTROY_AUTHENTICATEDCHANNEL, + + D3D12_MESSAGE_ID_MAP_INVALID_SUBRESOURCE, + D3D12_MESSAGE_ID_MAP_INVALID_TYPE, + D3D12_MESSAGE_ID_MAP_UNSUPPORTED_TYPE, + D3D12_MESSAGE_ID_UNMAP_INVALID_SUBRESOURCE, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_TYPE, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_NULL_POINTER, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_SUBRESOURCE, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_RESERVED_BITS, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISSING_BIND_FLAGS, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISMATCHING_MISC_FLAGS, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MATCHING_STATES, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_COMBINATION, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_BEFORE_AFTER_MISMATCH, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_RESOURCE, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_SAMPLE_COUNT, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_FLAGS, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_COMBINED_FLAGS, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_FLAGS_FOR_FORMAT, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_SPLIT_BARRIER, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_UNMATCHED_END, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_UNMATCHED_BEGIN, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_FLAG, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_COMMAND_LIST_TYPE, + D3D12_MESSAGE_ID_INVALID_SUBRESOURCE_STATE, + D3D12_MESSAGE_ID_INEFFICIENT_PRESENT, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_CONTENTION, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_RESET, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_RESET_BUNDLE, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_CANNOT_RESET, + D3D12_MESSAGE_ID_COMMAND_LIST_OPEN, + D3D12_MESSAGE_ID_QUERY_STATE_MISMATCH, + D3D12_MESSAGE_ID_INVALID_BUNDLE_API, + D3D12_MESSAGE_ID_COMMAND_LIST_CLOSED, + D3D12_MESSAGE_ID_COMMAND_LIST_CLOSED_WITH_INVALID_RESOURCE, + D3D12_MESSAGE_ID_WRONG_COMMAND_ALLOCATOR_TYPE, + D3D12_MESSAGE_ID_INVALID_INDIRECT_ARGUMENT_BUFFER, + D3D12_MESSAGE_ID_COMPUTE_AND_GRAPHICS_PIPELINE, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_SYNC, + D3D12_MESSAGE_ID_COMMAND_LIST_SYNC, + D3D12_MESSAGE_ID_SET_DESCRIPTOR_HEAP_INVALID, + D3D12_MESSAGE_ID_CREATE_QUEUE_IMAGE_NOT_SUPPORTED, + D3D12_MESSAGE_ID_CREATE_COMMAND_ALLOCATOR_IMAGE_NOT_SUPPORTED, + + D3D12_MESSAGE_ID_CREATE_COMMANDQUEUE, + D3D12_MESSAGE_ID_CREATE_COMMANDALLOCATOR, + D3D12_MESSAGE_ID_CREATE_PIPELINESTATE, + D3D12_MESSAGE_ID_CREATE_COMMANDLIST12, + D3D12_MESSAGE_ID_CREATE_IMAGECOMMANDLIST, + D3D12_MESSAGE_ID_CREATE_RESOURCE, + D3D12_MESSAGE_ID_CREATE_DESCRIPTORHEAP, + D3D12_MESSAGE_ID_CREATE_ROOTSIGNATURE, + D3D12_MESSAGE_ID_CREATE_LIBRARY, + D3D12_MESSAGE_ID_CREATE_HEAP, + D3D12_MESSAGE_ID_CREATE_MONITOREDFENCE, + D3D12_MESSAGE_ID_CREATE_QUERYHEAP, + D3D12_MESSAGE_ID_CREATE_COMMANDSIGNATURE, + + D3D12_MESSAGE_ID_LIVE_COMMANDQUEUE, + D3D12_MESSAGE_ID_LIVE_COMMANDALLOCATOR, + D3D12_MESSAGE_ID_LIVE_PIPELINESTATE, + D3D12_MESSAGE_ID_LIVE_COMMANDLIST12, + D3D12_MESSAGE_ID_LIVE_IMAGECOMMANDLIST, + D3D12_MESSAGE_ID_LIVE_RESOURCE, + D3D12_MESSAGE_ID_LIVE_DESCRIPTORHEAP, + D3D12_MESSAGE_ID_LIVE_ROOTSIGNATURE, + D3D12_MESSAGE_ID_LIVE_LIBRARY, + D3D12_MESSAGE_ID_LIVE_HEAP, + D3D12_MESSAGE_ID_LIVE_MONITOREDFENCE, + D3D12_MESSAGE_ID_LIVE_QUERYHEAP, + D3D12_MESSAGE_ID_LIVE_COMMANDSIGNATURE, + + D3D12_MESSAGE_ID_DESTROY_COMMANDQUEUE, + D3D12_MESSAGE_ID_DESTROY_COMMANDALLOCATOR, + D3D12_MESSAGE_ID_DESTROY_PIPELINESTATE, + D3D12_MESSAGE_ID_DESTROY_COMMANDLIST12, + D3D12_MESSAGE_ID_DESTROY_IMAGECOMMANDLIST, + D3D12_MESSAGE_ID_DESTROY_RESOURCE, + D3D12_MESSAGE_ID_DESTROY_DESCRIPTORHEAP, + D3D12_MESSAGE_ID_DESTROY_ROOTSIGNATURE, + D3D12_MESSAGE_ID_DESTROY_LIBRARY, + D3D12_MESSAGE_ID_DESTROY_HEAP, + D3D12_MESSAGE_ID_DESTROY_MONITOREDFENCE, + D3D12_MESSAGE_ID_DESTROY_QUERYHEAP, + D3D12_MESSAGE_ID_DESTROY_COMMANDSIGNATURE, + + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDHEAPTYPE, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDDIMENSIONS, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDMISCFLAGS, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDMISCFLAGS, + D3D12_MESSAGE_ID_CREATERESOURCE_LARGEALLOCATION, + D3D12_MESSAGE_ID_CREATERESOURCE_SMALLALLOCATION, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_CREATERESOURCE_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDDESC, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDINITIALSTATE, + D3D12_MESSAGE_ID_RESOURCE_HAS_PENDING_INITIAL_DATA, + D3D12_MESSAGE_ID_POSSIBLY_INVALID_SUBRESOURCE_STATE, + D3D12_MESSAGE_ID_INVALID_USE_OF_NON_RESIDENT_RESOURCE, + D3D12_MESSAGE_ID_POSSIBLE_INVALID_USE_OF_NON_RESIDENT_RESOURCE, + D3D12_MESSAGE_ID_BUNDLE_PIPELINE_STATE_MISMATCH, + D3D12_MESSAGE_ID_PRIMITIVE_TOPOLOGY_MISMATCH_PIPELINE_STATE, + D3D12_MESSAGE_ID_RENDER_TARGET_NUMBER_MISMATCH_PIPELINE_STATE, + D3D12_MESSAGE_ID_RENDER_TARGET_FORMAT_MISMATCH_PIPELINE_STATE, + D3D12_MESSAGE_ID_RENDER_TARGET_SAMPLE_DESC_MISMATCH_PIPELINE_STATE, + D3D12_MESSAGE_ID_DEPTH_STENCIL_FORMAT_MISMATCH_PIPELINE_STATE, + D3D12_MESSAGE_ID_DEPTH_STENCIL_SAMPLE_DESC_MISMATCH_PIPELINE_STATE, + D3D12_MESSAGE_ID_RENDER_TARGET_NUMBER_MISMATCH_BUNDLE_PIPELINE_STATE, + D3D12_MESSAGE_ID_RENDER_TARGET_FORMAT_MISMATCH_BUNDLE_PIPELINE_STATE, + D3D12_MESSAGE_ID_RENDER_TARGET_SAMPLE_DESC_MISMATCH_BUNDLE_PIPELINE_STATE, + D3D12_MESSAGE_ID_DEPTH_STENCIL_FORMAT_MISMATCH_BUNDLE_PIPELINE_STATE, + D3D12_MESSAGE_ID_DEPTH_STENCIL_SAMPLE_DESC_MISMATCH_BUNDLE_PIPELINE_STATE, + D3D12_MESSAGE_ID_CREATESHADER_INVALIDBYTECODE, + D3D12_MESSAGE_ID_CREATEHEAP_NULLDESC, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDSIZE, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDHEAPTYPE, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDCPUPAGEPROPERTIES, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDMEMORYPOOL, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDPROPERTIES, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDALIGNMENT, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDMISCFLAGS, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDMISCFLAGS, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_CREATEHEAP_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_NULLHEAPPROPERTIES, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDHEAPTYPE, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDCPUPAGEPROPERTIES, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDMEMORYPOOL, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDHEAPPROPERTIES, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDHEAPMISCFLAGS, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDHEAPMISCFLAGS, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_GETCUSTOMHEAPPROPERTIES_UNRECOGNIZEDHEAPTYPE, + D3D12_MESSAGE_ID_GETCUSTOMHEAPPROPERTIES_INVALIDHEAPTYPE, + D3D12_MESSAGE_ID_CREATE_DESCRIPTOR_HEAP_INVALID_DESC, + D3D12_MESSAGE_ID_INVALID_DESCRIPTOR_HANDLE, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALID_CONSERVATIVERASTERMODE, + D3D12_MESSAGE_ID_DEVICE_DRAW_INVALID_SYSTEMVALUE, + D3D12_MESSAGE_ID_CREATE_CONSTANT_BUFFER_VIEW_INVALID_RESOURCE, + D3D12_MESSAGE_ID_CREATE_CONSTANT_BUFFER_VIEW_INVALID_DESC, + D3D12_MESSAGE_ID_CREATE_CONSTANT_BUFFER_VIEW_LARGE_OFFSET, + D3D12_MESSAGE_ID_CREATE_UNORDEREDACCESS_VIEW_INVALID_COUNTER_USAGE, + D3D12_MESSAGE_ID_COPY_DESCRIPTORS_INVALID_RANGES, + D3D12_MESSAGE_ID_COPY_DESCRIPTORS_WRITE_ONLY_DESCRIPTOR, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_RTV_FORMAT_NOT_UNKNOWN, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_RENDER_TARGET_COUNT, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_VERTEX_SHADER_NOT_SET, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INPUTLAYOUT_NOT_SET, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_HS_DS_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_REGISTERINDEX, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_COMPONENTTYPE, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_REGISTERMASK, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_SYSTEMVALUE, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_MINPRECISION, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_XOR_DS_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HULL_SHADER_INPUT_TOPOLOGY_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_PATCH_TOPOLOGY_SHADER_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_DS_CONTROL_POINT_COUNT_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_DS_TESSELLATOR_DOMAIN_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_USE_OF_CENTER_MULTISAMPLE_PATTERN, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_USE_OF_FORCED_SAMPLE_COUNT, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_PRIMITIVETOPOLOGY, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_SYSTEMVALUE, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_PS_OUTPUT_TYPE_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_OM_RENDER_TARGET_DOES_NOT_SUPPORT_LOGIC_OPS, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_RENDERTARGETVIEW_NOT_SET, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_DEPTHSTENCILVIEW_NOT_SET, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_GS_INPUT_PRIMITIVE_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_POSITION_NOT_PRESENT, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_MISSING_ROOT_SIGNATURE_FLAGS, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_INDEX_BUFFER_PROPERTIES, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_SAMPLE_DESC, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_DS_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_VS_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_GS_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_PS_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_MISSING_ROOT_SIGNATURE, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_OPEN_BUNDLE, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_DESCRIPTOR_HEAP_MISMATCH, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_TYPE, + D3D12_MESSAGE_ID_DRAW_EMPTY_SCISSOR_RECTANGLE, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_BLOB_NOT_FOUND, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_DESERIALIZE_FAILED, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_INVALID_CONFIGURATION, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_NOT_SUPPORTED_ON_DEVICE, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_NULLRESOURCEPROPERTIES, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_NULLHEAP, + D3D12_MESSAGE_ID_GETRESOURCEALLOCATIONINFO_INVALIDRDESCS, + D3D12_MESSAGE_ID_MAKERESIDENT_NULLOBJECTARRAY, + D3D12_MESSAGE_ID_MAKERESIDENT_INVALIDOBJECT, + D3D12_MESSAGE_ID_EVICT_NULLOBJECTARRAY, + D3D12_MESSAGE_ID_EVICT_INVALIDOBJECT, + D3D12_MESSAGE_ID_HEAPS_UNSUPPORTED, + D3D12_MESSAGE_ID_SET_DESCRIPTOR_TABLE_INVALID, + D3D12_MESSAGE_ID_SET_ROOT_CONSTANT_INVALID, + D3D12_MESSAGE_ID_SET_ROOT_CONSTANT_BUFFER_VIEW_INVALID, + D3D12_MESSAGE_ID_SET_ROOT_SHADER_RESOURCE_VIEW_INVALID, + D3D12_MESSAGE_ID_SET_ROOT_UNORDERED_ACCESS_VIEW_INVALID, + D3D12_MESSAGE_ID_SET_VERTEX_BUFFERS_INVALID_DESC, + D3D12_MESSAGE_ID_SET_VERTEX_BUFFERS_LARGE_OFFSET, + D3D12_MESSAGE_ID_SET_INDEX_BUFFER_INVALID_DESC, + D3D12_MESSAGE_ID_SET_INDEX_BUFFER_LARGE_OFFSET, + D3D12_MESSAGE_ID_SET_STREAM_OUTPUT_BUFFERS_INVALID_DESC, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDDIMENSIONALITY, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDLAYOUT, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDDIMENSIONALITY, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDALIGNMENT, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDMIPLEVELS, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDSAMPLEDESC, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDLAYOUT, + D3D12_MESSAGE_ID_SET_INDEX_BUFFER_INVALID, + D3D12_MESSAGE_ID_SET_VERTEX_BUFFERS_INVALID, + D3D12_MESSAGE_ID_SET_STREAM_OUTPUT_BUFFERS_INVALID, + D3D12_MESSAGE_ID_SET_RENDER_TARGETS_INVALID, + D3D12_MESSAGE_ID_CREATEQUERY_HEAP_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_CREATEQUERY_HEAP_JPEG_NOT_SUPPORTED, + D3D12_MESSAGE_ID_BEGIN_END_QUERY_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_CLOSE_COMMAND_LIST_OPEN_QUERY, + D3D12_MESSAGE_ID_RESOLVE_QUERY_DATA_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_SET_PREDICATION_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_TIMESTAMPS_NOT_SUPPORTED, + D3D12_MESSAGE_ID_UNSTABLE_POWER_STATE, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDFORMAT, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDFORMAT, + D3D12_MESSAGE_ID_GETCOPYABLEFOOTPRINTS_INVALIDSUBRESOURCERANGE, + D3D12_MESSAGE_ID_GETCOPYABLEFOOTPRINTS_INVALIDBASEOFFSET, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_HEAP, + D3D12_MESSAGE_ID_CREATE_SAMPLER_INVALID, + D3D12_MESSAGE_ID_CREATECOMMANDSIGNATURE_INVALID, + D3D12_MESSAGE_ID_EXECUTE_INDIRECT_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_GETGPUVIRTUALADDRESS_INVALID_RESOURCE_DIMENSION, + + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDCONTEXTTYPE, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_DECODENOTSUPPORTED, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_ENCODENOTSUPPORTED, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDPLANEINDEX, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDVIDEOPLANEINDEX, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_AMBIGUOUSVIDEOPLANEINDEX, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDPLANEINDEX, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDVIDEOPLANEINDEX, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_AMBIGUOUSVIDEOPLANEINDEX, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDPLANEINDEX, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDVIDEOPLANEINDEX, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_AMBIGUOUSVIDEOPLANEINDEX, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDSCANDATAOFFSET, + D3D12_MESSAGE_ID_JPEGDECODE_NOTSUPPORTED, + D3D12_MESSAGE_ID_JPEGDECODE_DIMENSIONSTOOLARGE, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDCOMPONENTS, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDCOMPONENTS, + D3D12_MESSAGE_ID_JPEGDECODE_DESTINATIONNOT2D, + D3D12_MESSAGE_ID_JPEGDECODE_TILEDRESOURCESUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGDECODE_GUARDRECTSUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGDECODE_FORMATUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDMIPLEVEL, + D3D12_MESSAGE_ID_JPEGDECODE_EMPTYDESTBOX, + D3D12_MESSAGE_ID_JPEGDECODE_DESTBOXNOT2D, + D3D12_MESSAGE_ID_JPEGDECODE_DESTBOXNOTSUB, + D3D12_MESSAGE_ID_JPEGDECODE_DESTBOXESINTERSECT, + D3D12_MESSAGE_ID_JPEGDECODE_XSUBSAMPLEMISMATCH, + D3D12_MESSAGE_ID_JPEGDECODE_YSUBSAMPLEMISMATCH, + D3D12_MESSAGE_ID_JPEGDECODE_XSUBSAMPLEODD, + D3D12_MESSAGE_ID_JPEGDECODE_YSUBSAMPLEODD, + D3D12_MESSAGE_ID_JPEGDECODE_UPSCALEUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGDECODE_TIER4DOWNSCALETOLARGE, + D3D12_MESSAGE_ID_JPEGDECODE_TIER3DOWNSCALEUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGDECODE_CHROMASIZEMISMATCH, + D3D12_MESSAGE_ID_JPEGDECODE_LUMACHROMASIZEMISMATCH, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDNUMDESTINATIONS, + D3D12_MESSAGE_ID_JPEGDECODE_SUBBOXUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGDECODE_1DESTUNSUPPORTEDFORMAT, + D3D12_MESSAGE_ID_JPEGDECODE_3DESTUNSUPPORTEDFORMAT, + D3D12_MESSAGE_ID_JPEGDECODE_SCALEUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDSOURCESIZE, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDCOPYFLAGS, + D3D12_MESSAGE_ID_JPEGDECODE_HAZARD, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDSRCBUFFERUSAGE, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDSRCBUFFERMISCFLAGS, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDDSTTEXTUREUSAGE, + D3D12_MESSAGE_ID_JPEGDECODE_BACKBUFFERNOTSUPPORTED, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPRTEDCOPYFLAGS, + D3D12_MESSAGE_ID_JPEGENCODE_NOTSUPPORTED, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDSCANDATAOFFSET, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDCOMPONENTS, + D3D12_MESSAGE_ID_JPEGENCODE_SOURCENOT2D, + D3D12_MESSAGE_ID_JPEGENCODE_TILEDRESOURCESUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGENCODE_GUARDRECTSUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGENCODE_XSUBSAMPLEMISMATCH, + D3D12_MESSAGE_ID_JPEGENCODE_YSUBSAMPLEMISMATCH, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDCOMPONENTS, + D3D12_MESSAGE_ID_JPEGENCODE_FORMATUNSUPPORTED, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDMIPLEVEL, + D3D12_MESSAGE_ID_JPEGENCODE_DIMENSIONSTOOLARGE, + D3D12_MESSAGE_ID_JPEGENCODE_HAZARD, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDDSTBUFFERUSAGE, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDDSTBUFFERMISCFLAGS, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDSRCTEXTUREUSAGE, + D3D12_MESSAGE_ID_JPEGENCODE_BACKBUFFERNOTSUPPORTED, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_UNSUPPORTEDCONTEXTTTYPEFORQUERY, + D3D12_MESSAGE_ID_FLUSH1_INVALIDCONTEXTTYPE, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDCLEARVALUE, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDCLEARVALUEFORMAT, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDCLEARVALUEFORMAT, + D3D12_MESSAGE_ID_CREATERESOURCE_CLEARVALUEDENORMFLUSH, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALIDDEPTH, + D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE, + D3D12_MESSAGE_ID_MAP_INVALIDHEAP, + D3D12_MESSAGE_ID_UNMAP_INVALIDHEAP, + D3D12_MESSAGE_ID_MAP_INVALIDRESOURCE, + D3D12_MESSAGE_ID_UNMAP_INVALIDRESOURCE, + D3D12_MESSAGE_ID_MAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_UNMAP_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_MAP_INVALIDRANGE, + D3D12_MESSAGE_ID_UNMAP_INVALIDRANGE, + D3D12_MESSAGE_ID_MAP_NULLRANGE, + D3D12_MESSAGE_ID_UNMAP_NULLRANGE, + D3D12_MESSAGE_ID_MAP_INVALIDDATAPOINTER, + D3D12_MESSAGE_ID_MAP_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_MAP_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_BUNDLENOTSUPPORTED, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_COMMANDLISTMISMATCH, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_OPENCOMMANDLIST, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_FAILEDCOMMANDLIST, + D3D12_MESSAGE_ID_COPYBUFFERREGION_NULLDST, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALIDDSTRESOURCEDIMENSION, + D3D12_MESSAGE_ID_COPYBUFFERREGION_DSTRANGEOUTOFBOUNDS, + D3D12_MESSAGE_ID_COPYBUFFERREGION_NULLSRC, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALIDSRCRESOURCEDIMENSION, + D3D12_MESSAGE_ID_COPYBUFFERREGION_SRCRANGEOUTOFBOUNDS, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALIDCOPYFLAGS, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_NULLDST, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDDSTTYPE, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTRESOURCEDIMENSION, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTRESOURCE, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTSUBRESOURCE, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTOFFSET, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDDSTFORMAT, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTFORMAT, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTDIMENSIONS, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTROWPITCH, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTPLACEMENT, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTDSPLACEDFOOTPRINTFORMAT, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_DSTREGIONOUTOFBOUNDS, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_NULLSRC, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDSRCTYPE, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCRESOURCEDIMENSION, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCRESOURCE, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCSUBRESOURCE, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCOFFSET, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDSRCFORMAT, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCFORMAT, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCDIMENSIONS, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCROWPITCH, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCPLACEMENT, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCDSPLACEDFOOTPRINTFORMAT, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_SRCREGIONOUTOFBOUNDS, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTCOORDINATES, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCBOX, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_FORMATMISMATCH, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_EMPTYBOX, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDCOPYFLAGS, + + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALID_SUBRESOURCE_INDEX, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALID_FORMAT, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_RESOURCE_MISMATCH, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALID_SAMPLE_COUNT, + + D3D12_MESSAGE_ID_CREATECOMPUTEPIPELINESTATE_INVALID_SHADER, + D3D12_MESSAGE_ID_CREATECOMPUTEPIPELINESTATE_CS_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_CREATECOMPUTEPIPELINESTATE_MISSING_ROOT_SIGNATURE, + + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_INVALIDCACHEDBLOB, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBADAPTERMISMATCH, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBDRIVERVERSIONMISMATCH, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBDESCMISMATCH, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBIGNORED, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDHEAP, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDRESOURCE, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDBOX, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_EMPTYBOX, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDHEAP, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDRESOURCE, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDBOX, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDSUBRESOURCE, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_EMPTYBOX, + + D3D12_MESSAGE_ID_TOO_MANY_NODES_SPECIFIED, + D3D12_MESSAGE_ID_INVALID_NODE_INDEX, + + D3D12_MESSAGE_ID_GETHEAPPROPERTIES_INVALIDRESOURCE, + D3D12_MESSAGE_ID_NODE_MASK_MISMATCH, + D3D12_MESSAGE_ID_COMMAND_LIST_OUTOFMEMORY, + D3D12_MESSAGE_ID_COMMAND_LIST_MULTIPLE_SWAPCHAIN_BUFFER_REFERENCES, + D3D12_MESSAGE_ID_COMMAND_LIST_TOO_MANY_SWAPCHAIN_REFERENCES, + D3D12_MESSAGE_ID_COMMAND_QUEUE_TOO_MANY_SWAPCHAIN_REFERENCES, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_WRONGSWAPCHAINBUFFERREFERENCE, + D3D12_MESSAGE_ID_COMMAND_LIST_SETRENDERTARGETS_INVALIDNUMRENDERTARGETS, + D3D12_MESSAGE_ID_CREATE_QUEUE_INVALID_TYPE, + D3D12_MESSAGE_ID_CREATE_QUEUE_INVALID_FLAGS, + + D3D12_MESSAGE_ID_CREATESHAREDRESOURCE_INVALIDFLAGS, + D3D12_MESSAGE_ID_CREATESHAREDRESOURCE_INVALIDFORMAT, + D3D12_MESSAGE_ID_CREATESHAREDHEAP_INVALIDFLAGS, + D3D12_MESSAGE_ID_REFLECTSHAREDPROPERTIES_UNRECOGNIZEDPROPERTIES, + D3D12_MESSAGE_ID_REFLECTSHAREDPROPERTIES_INVALIDSIZE, + D3D12_MESSAGE_ID_REFLECTSHAREDPROPERTIES_INVALIDOBJECT, + D3D12_MESSAGE_ID_KEYEDMUTEX_INVALIDOBJECT, + D3D12_MESSAGE_ID_KEYEDMUTEX_INVALIDKEY, + D3D12_MESSAGE_ID_KEYEDMUTEX_WRONGSTATE, + D3D12_MESSAGE_ID_CREATE_QUEUE_INVALID_PRIORITY, + + D3D12_MESSAGE_ID_OBJECT_DELETED_WHILE_STILL_IN_USE, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_INVALID_FLAGS, + + D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_HAS_NO_RESOURCE, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RENDER_TARGET_DELETED, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_ALL_RENDER_TARGETS_HAVE_UNKNOWN_FORMAT, + D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_INTERSECTS_MULTIPLE_BUFFERS, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_GPU_WRITTEN_READBACK_RESOURCE_MAPPED, + D3D12_MESSAGE_ID_UNMAP_RANGE_NOT_EMPTY, + D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE, + D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE, + D3D12_MESSAGE_ID_NO_GRAPHICS_API_SUPPORT, + D3D12_MESSAGE_ID_NO_COMPUTE_API_SUPPORT, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_RESOURCE_FLAGS_NOT_SUPPORTED, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_ROOT_ARGUMENT_UNINITIALIZED, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_DESCRIPTOR_HEAP_INDEX_OUT_OF_BOUNDS, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_DESCRIPTOR_TABLE_REGISTER_INDEX_OUT_OF_BOUNDS, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_DESCRIPTOR_UNINITIALIZED, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_DESCRIPTOR_TYPE_MISMATCH, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_SRV_RESOURCE_DIMENSION_MISMATCH, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_UAV_RESOURCE_DIMENSION_MISMATCH, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_INCOMPATIBLE_RESOURCE_STATE, + D3D12_MESSAGE_ID_COPYRESOURCE_NULLDST, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDDSTRESOURCE, + D3D12_MESSAGE_ID_COPYRESOURCE_NULLSRC, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDSRCRESOURCE, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_NULLDST, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALIDDSTRESOURCE, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_NULLSRC, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALIDSRCRESOURCE, + D3D12_MESSAGE_ID_PIPELINE_STATE_TYPE_MISMATCH, + D3D12_MESSAGE_ID_COMMAND_LIST_DISPATCH_ROOT_SIGNATURE_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_DISPATCH_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_ZERO_BARRIERS, + D3D12_MESSAGE_ID_BEGIN_END_EVENT_MISMATCH, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_POSSIBLE_BEFORE_AFTER_MISMATCH, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISMATCHING_BEGIN_END, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_INVALID_RESOURCE, + D3D12_MESSAGE_ID_USE_OF_ZERO_REFCOUNT_OBJECT, + D3D12_MESSAGE_ID_OBJECT_EVICTED_WHILE_STILL_IN_USE, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_ROOT_DESCRIPTOR_ACCESS_OUT_OF_BOUNDS, + D3D12_MESSAGE_ID_CREATEPIPELINELIBRARY_INVALIDLIBRARYBLOB, + D3D12_MESSAGE_ID_CREATEPIPELINELIBRARY_DRIVERVERSIONMISMATCH, + D3D12_MESSAGE_ID_CREATEPIPELINELIBRARY_ADAPTERVERSIONMISMATCH, + D3D12_MESSAGE_ID_CREATEPIPELINELIBRARY_UNSUPPORTED, + D3D12_MESSAGE_ID_CREATE_PIPELINELIBRARY, + D3D12_MESSAGE_ID_LIVE_PIPELINELIBRARY, + D3D12_MESSAGE_ID_DESTROY_PIPELINELIBRARY, + D3D12_MESSAGE_ID_STOREPIPELINE_NONAME, + D3D12_MESSAGE_ID_STOREPIPELINE_DUPLICATENAME, + D3D12_MESSAGE_ID_LOADPIPELINE_NAMENOTFOUND, + D3D12_MESSAGE_ID_LOADPIPELINE_INVALIDDESC, + D3D12_MESSAGE_ID_PIPELINELIBRARY_SERIALIZE_NOTENOUGHMEMORY, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_PS_OUTPUT_RT_OUTPUT_MISMATCH, + D3D12_MESSAGE_ID_SETEVENTONMULTIPLEFENCECOMPLETION_INVALIDFLAGS, + D3D12_MESSAGE_ID_CREATE_QUEUE_VIDEO_NOT_SUPPORTED, + D3D12_MESSAGE_ID_CREATE_COMMAND_ALLOCATOR_VIDEO_NOT_SUPPORTED, + D3D12_MESSAGE_ID_CREATEQUERY_HEAP_VIDEO_DECODE_STATISTICS_NOT_SUPPORTED, + D3D12_MESSAGE_ID_CREATE_VIDEODECODECOMMANDLIST, + D3D12_MESSAGE_ID_CREATE_VIDEODECODER, + D3D12_MESSAGE_ID_CREATE_VIDEODECODESTREAM, + D3D12_MESSAGE_ID_LIVE_VIDEODECODECOMMANDLIST, + D3D12_MESSAGE_ID_LIVE_VIDEODECODER, + D3D12_MESSAGE_ID_LIVE_VIDEODECODESTREAM, + D3D12_MESSAGE_ID_DESTROY_VIDEODECODECOMMANDLIST, + D3D12_MESSAGE_ID_DESTROY_VIDEODECODER, + D3D12_MESSAGE_ID_DESTROY_VIDEODECODESTREAM, + D3D12_MESSAGE_ID_DECODE_FRAME_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_DEPRECATED_API, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISMATCHING_COMMAND_LIST_TYPE, + D3D12_MESSAGE_ID_COMMAND_LIST_DESCRIPTOR_TABLE_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_ROOT_CONSTANT_BUFFER_VIEW_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_ROOT_SHADER_RESOURCE_VIEW_NOT_SET, + D3D12_MESSAGE_ID_COMMAND_LIST_ROOT_UNORDERED_ACCESS_VIEW_NOT_SET, + D3D12_MESSAGE_ID_DISCARD_INVALID_SUBRESOURCE_RANGE, + D3D12_MESSAGE_ID_DISCARD_ONE_SUBRESOURCE_FOR_MIPS_WITH_RECTS, + D3D12_MESSAGE_ID_DISCARD_NO_RECTS_FOR_NON_TEXTURE2D, + D3D12_MESSAGE_ID_COPY_ON_SAME_SUBRESOURCE, + D3D12_MESSAGE_ID_SETRESIDENCYPRIORITY_INVALID_PAGEABLE, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_UNSUPPORTED, + D3D12_MESSAGE_ID_STATIC_DESCRIPTOR_INVALID_DESCRIPTOR_CHANGE, + D3D12_MESSAGE_ID_DATA_STATIC_DESCRIPTOR_INVALID_DATA_CHANGE, + D3D12_MESSAGE_ID_DATA_STATIC_WHILE_SET_AT_EXECUTE_DESCRIPTOR_INVALID_DATA_CHANGE, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_STATIC_DESCRIPTOR_DATA_STATIC_NOT_SET, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_RESOURCE_ACCESS_OUT_OF_BOUNDS, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_SAMPLER_MODE_MISMATCH, + D3D12_MESSAGE_ID_CREATE_FENCE_INVALID_FLAGS, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_DUPLICATE_SUBRESOURCE_TRANSITIONS, + D3D12_MESSAGE_ID_SETRESIDENCYPRIORITY_INVALID_PRIORITY, + D3D12_MESSAGE_ID_CREATE_DESCRIPTOR_HEAP_LARGE_NUM_DESCRIPTORS, + D3D12_MESSAGE_ID_BEGIN_EVENT, + D3D12_MESSAGE_ID_END_EVENT, + D3D12_MESSAGE_ID_CREATEDEVICE_DEBUG_LAYER_STARTUP_OPTIONS, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_DEPTHBOUNDSTEST_UNSUPPORTED, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_DUPLICATE_SUBOBJECT, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_UNKNOWN_SUBOBJECT, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_ZERO_SIZE_STREAM, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_INVALID_STREAM, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CANNOT_DEDUCE_TYPE, + D3D12_MESSAGE_ID_COMMAND_LIST_STATIC_DESCRIPTOR_RESOURCE_DIMENSION_MISMATCH, + D3D12_MESSAGE_ID_CREATE_COMMAND_QUEUE_INSUFFICIENT_PRIVILEGE_FOR_GLOBAL_REALTIME, + D3D12_MESSAGE_ID_CREATE_COMMAND_QUEUE_INSUFFICIENT_HARDWARE_SUPPORT_FOR_GLOBAL_REALTIME, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_INVALID_ARCHITECTURE, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_NULL_DST, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_INVALID_DST_RESOURCE_DIMENSION, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_DST_RANGE_OUT_OF_BOUNDS, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_NULL_SRC, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_INVALID_SRC_RESOURCE_DIMENSION, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_SRC_RANGE_OUT_OF_BOUNDS, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_INVALID_OFFSET_ALIGNMENT, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_NULL_DEPENDENT_RESOURCES, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_NULL_DEPENDENT_SUBRESOURCE_RANGES, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_INVALID_DEPENDENT_RESOURCE, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_INVALID_DEPENDENT_SUBRESOURCE_RANGE, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_DEPENDENT_SUBRESOURCE_OUT_OF_BOUNDS, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_DEPENDENT_RANGE_OUT_OF_BOUNDS, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_ZERO_DEPENDENCIES, + D3D12_MESSAGE_ID_DEVICE_CREATE_SHARED_HANDLE_INVALIDARG, + D3D12_MESSAGE_ID_DESCRIPTOR_HANDLE_WITH_INVALID_RESOURCE, + D3D12_MESSAGE_ID_SETDEPTHBOUNDS_INVALIDARGS, + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_RESOURCE_STATE_IMPRECISE, + D3D12_MESSAGE_ID_COMMAND_LIST_PIPELINE_STATE_NOT_SET, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_MODEL_MISMATCH, + D3D12_MESSAGE_ID_OBJECT_ACCESSED_WHILE_STILL_IN_USE, + D3D12_MESSAGE_ID_PROGRAMMABLE_MSAA_UNSUPPORTED, + D3D12_MESSAGE_ID_SETSAMPLEPOSITIONS_INVALIDARGS, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCEREGION_INVALID_RECT, + D3D12_MESSAGE_ID_CREATE_VIDEODECODECOMMANDQUEUE, + D3D12_MESSAGE_ID_CREATE_VIDEOPROCESSCOMMANDLIST, + D3D12_MESSAGE_ID_CREATE_VIDEOPROCESSCOMMANDQUEUE, + D3D12_MESSAGE_ID_LIVE_VIDEODECODECOMMANDQUEUE, + D3D12_MESSAGE_ID_LIVE_VIDEOPROCESSCOMMANDLIST, + D3D12_MESSAGE_ID_LIVE_VIDEOPROCESSCOMMANDQUEUE, + D3D12_MESSAGE_ID_DESTROY_VIDEODECODECOMMANDQUEUE, + D3D12_MESSAGE_ID_DESTROY_VIDEOPROCESSCOMMANDLIST, + D3D12_MESSAGE_ID_DESTROY_VIDEOPROCESSCOMMANDQUEUE, + D3D12_MESSAGE_ID_CREATE_VIDEOPROCESSOR, + D3D12_MESSAGE_ID_CREATE_VIDEOPROCESSSTREAM, + D3D12_MESSAGE_ID_LIVE_VIDEOPROCESSOR, + D3D12_MESSAGE_ID_LIVE_VIDEOPROCESSSTREAM, + D3D12_MESSAGE_ID_DESTROY_VIDEOPROCESSOR, + D3D12_MESSAGE_ID_DESTROY_VIDEOPROCESSSTREAM, + D3D12_MESSAGE_ID_PROCESS_FRAME_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_COPY_INVALIDLAYOUT, + D3D12_MESSAGE_ID_CREATE_CRYPTO_SESSION, + D3D12_MESSAGE_ID_CREATE_CRYPTO_SESSION_POLICY, + D3D12_MESSAGE_ID_CREATE_PROTECTED_RESOURCE_SESSION, + D3D12_MESSAGE_ID_LIVE_CRYPTO_SESSION, + D3D12_MESSAGE_ID_LIVE_CRYPTO_SESSION_POLICY, + D3D12_MESSAGE_ID_LIVE_PROTECTED_RESOURCE_SESSION, + D3D12_MESSAGE_ID_DESTROY_CRYPTO_SESSION, + D3D12_MESSAGE_ID_DESTROY_CRYPTO_SESSION_POLICY, + D3D12_MESSAGE_ID_DESTROY_PROTECTED_RESOURCE_SESSION, + D3D12_MESSAGE_ID_PROTECTED_RESOURCE_SESSION_UNSUPPORTED, + D3D12_MESSAGE_ID_FENCE_INVALIDOPERATION, + D3D12_MESSAGE_ID_CREATEQUERY_HEAP_COPY_QUEUE_TIMESTAMPS_NOT_SUPPORTED, + D3D12_MESSAGE_ID_SAMPLEPOSITIONS_MISMATCH_DEFERRED, + D3D12_MESSAGE_ID_SAMPLEPOSITIONS_MISMATCH_RECORDTIME_ASSUMEDFROMFIRSTUSE, + D3D12_MESSAGE_ID_SAMPLEPOSITIONS_MISMATCH_RECORDTIME_ASSUMEDFROMCLEAR, + D3D12_MESSAGE_ID_CREATE_VIDEODECODERHEAP, + D3D12_MESSAGE_ID_LIVE_VIDEODECODERHEAP, + D3D12_MESSAGE_ID_DESTROY_VIDEODECODERHEAP, + D3D12_MESSAGE_ID_OPENEXISTINGHEAP_INVALIDARG_RETURN, + D3D12_MESSAGE_ID_OPENEXISTINGHEAP_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_OPENEXISTINGHEAP_INVALIDADDRESS, + D3D12_MESSAGE_ID_OPENEXISTINGHEAP_INVALIDHANDLE, + D3D12_MESSAGE_ID_WRITEBUFFERIMMEDIATE_INVALID_DEST, + D3D12_MESSAGE_ID_WRITEBUFFERIMMEDIATE_INVALID_MODE, + D3D12_MESSAGE_ID_WRITEBUFFERIMMEDIATE_INVALID_ALIGNMENT, + D3D12_MESSAGE_ID_WRITEBUFFERIMMEDIATE_NOT_SUPPORTED, + D3D12_MESSAGE_ID_SETVIEWINSTANCEMASK_INVALIDARGS, + D3D12_MESSAGE_ID_VIEW_INSTANCING_UNSUPPORTED, + D3D12_MESSAGE_ID_VIEW_INSTANCING_INVALIDARGS, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_MISMATCH_DECODE_REFERENCE_ONLY_FLAG, + D3D12_MESSAGE_ID_COPYRESOURCE_MISMATCH_DECODE_REFERENCE_ONLY_FLAG, + D3D12_MESSAGE_ID_CREATE_VIDEO_DECODE_HEAP_CAPS_FAILURE, + D3D12_MESSAGE_ID_CREATE_VIDEO_DECODE_HEAP_CAPS_UNSUPPORTED, + D3D12_MESSAGE_ID_VIDEO_DECODE_SUPPORT_INVALID_INPUT, + D3D12_MESSAGE_ID_CREATE_VIDEO_DECODER_UNSUPPORTED, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_METADATA_ERROR, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_VIEW_INSTANCING_VERTEX_SIZE_EXCEEDED, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_RUNTIME_INTERNAL_ERROR, + D3D12_MESSAGE_ID_NO_VIDEO_API_SUPPORT, + D3D12_MESSAGE_ID_VIDEO_PROCESS_SUPPORT_INVALID_INPUT, + D3D12_MESSAGE_ID_CREATE_VIDEO_PROCESSOR_CAPS_FAILURE, + D3D12_MESSAGE_ID_VIDEO_PROCESS_SUPPORT_UNSUPPORTED_FORMAT, + D3D12_MESSAGE_ID_VIDEO_DECODE_FRAME_INVALID_ARGUMENT, + D3D12_MESSAGE_ID_ENQUEUE_MAKE_RESIDENT_INVALID_FLAGS, + D3D12_MESSAGE_ID_OPENEXISTINGHEAP_UNSUPPORTED, + D3D12_MESSAGE_ID_VIDEO_PROCESS_FRAMES_INVALID_ARGUMENT, + D3D12_MESSAGE_ID_VIDEO_DECODE_SUPPORT_UNSUPPORTED, + D3D12_MESSAGE_ID_CREATE_COMMANDRECORDER, + D3D12_MESSAGE_ID_LIVE_COMMANDRECORDER, + D3D12_MESSAGE_ID_DESTROY_COMMANDRECORDER, + D3D12_MESSAGE_ID_CREATE_COMMAND_RECORDER_VIDEO_NOT_SUPPORTED, + D3D12_MESSAGE_ID_CREATE_COMMAND_RECORDER_INVALID_SUPPORT_FLAGS, + D3D12_MESSAGE_ID_CREATE_COMMAND_RECORDER_INVALID_FLAGS, + D3D12_MESSAGE_ID_CREATE_COMMAND_RECORDER_MORE_RECORDERS_THAN_LOGICAL_PROCESSORS, + D3D12_MESSAGE_ID_CREATE_COMMANDPOOL, + D3D12_MESSAGE_ID_LIVE_COMMANDPOOL, + D3D12_MESSAGE_ID_DESTROY_COMMANDPOOL, + D3D12_MESSAGE_ID_CREATE_COMMAND_POOL_INVALID_FLAGS, + D3D12_MESSAGE_ID_CREATE_COMMAND_LIST_VIDEO_NOT_SUPPORTED, + D3D12_MESSAGE_ID_COMMAND_RECORDER_SUPPORT_FLAGS_MISMATCH, + D3D12_MESSAGE_ID_COMMAND_RECORDER_CONTENTION, + D3D12_MESSAGE_ID_COMMAND_RECORDER_USAGE_WITH_CREATECOMMANDLIST_COMMAND_LIST, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_USAGE_WITH_CREATECOMMANDLIST1_COMMAND_LIST, + D3D12_MESSAGE_ID_CANNOT_EXECUTE_EMPTY_COMMAND_LIST, + D3D12_MESSAGE_ID_CANNOT_RESET_COMMAND_POOL_WITH_OPEN_COMMAND_LISTS, + D3D12_MESSAGE_ID_CANNOT_USE_COMMAND_RECORDER_WITHOUT_CURRENT_TARGET, + D3D12_MESSAGE_ID_CANNOT_CHANGE_COMMAND_RECORDER_TARGET_WHILE_RECORDING, + D3D12_MESSAGE_ID_COMMAND_POOL_SYNC, + D3D12_MESSAGE_ID_EVICT_UNDERFLOW, + D3D12_MESSAGE_ID_CREATE_META_COMMAND, + D3D12_MESSAGE_ID_LIVE_META_COMMAND, + D3D12_MESSAGE_ID_DESTROY_META_COMMAND, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALID_DST_RESOURCE, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALID_SRC_RESOURCE, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_INVALID_DST_RESOURCE, + D3D12_MESSAGE_ID_ATOMICCOPYBUFFER_INVALID_SRC_RESOURCE, + D3D12_MESSAGE_ID_CREATEPLACEDRESOURCEONBUFFER_NULL_BUFFER, + D3D12_MESSAGE_ID_CREATEPLACEDRESOURCEONBUFFER_NULL_RESOURCE_DESC, + D3D12_MESSAGE_ID_CREATEPLACEDRESOURCEONBUFFER_UNSUPPORTED, + D3D12_MESSAGE_ID_CREATEPLACEDRESOURCEONBUFFER_INVALID_BUFFER_DIMENSION, + D3D12_MESSAGE_ID_CREATEPLACEDRESOURCEONBUFFER_INVALID_BUFFER_FLAGS, + D3D12_MESSAGE_ID_CREATEPLACEDRESOURCEONBUFFER_INVALID_BUFFER_OFFSET, + D3D12_MESSAGE_ID_CREATEPLACEDRESOURCEONBUFFER_INVALID_RESOURCE_DIMENSION, + D3D12_MESSAGE_ID_CREATEPLACEDRESOURCEONBUFFER_INVALID_RESOURCE_FLAGS, + D3D12_MESSAGE_ID_CREATEPLACEDRESOURCEONBUFFER_OUTOFMEMORY_RETURN, + D3D12_MESSAGE_ID_CANNOT_CREATE_GRAPHICS_AND_VIDEO_COMMAND_RECORDER, + D3D12_MESSAGE_ID_UPDATETILEMAPPINGS_POSSIBLY_MISMATCHING_PROPERTIES, + D3D12_MESSAGE_ID_CREATE_COMMAND_LIST_INVALID_COMMAND_LIST_TYPE, + D3D12_MESSAGE_ID_CLEARUNORDEREDACCESSVIEW_INCOMPATIBLE_WITH_STRUCTURED_BUFFERS, + D3D12_MESSAGE_ID_COMPUTE_ONLY_DEVICE_OPERATION_UNSUPPORTED, + D3D12_MESSAGE_ID_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INVALID, + D3D12_MESSAGE_ID_EMIT_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_INVALID, + D3D12_MESSAGE_ID_COPY_RAYTRACING_ACCELERATION_STRUCTURE_INVALID, + D3D12_MESSAGE_ID_DISPATCH_RAYS_INVALID, + D3D12_MESSAGE_ID_GET_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO_INVALID, + D3D12_MESSAGE_ID_CREATE_LIFETIMETRACKER, + D3D12_MESSAGE_ID_LIVE_LIFETIMETRACKER, + D3D12_MESSAGE_ID_DESTROY_LIFETIMETRACKER, + D3D12_MESSAGE_ID_DESTROYOWNEDOBJECT_OBJECTNOTOWNED, + D3D12_MESSAGE_ID_CREATE_TRACKEDWORKLOAD, + D3D12_MESSAGE_ID_LIVE_TRACKEDWORKLOAD, + D3D12_MESSAGE_ID_DESTROY_TRACKEDWORKLOAD, + D3D12_MESSAGE_ID_RENDER_PASS_ERROR, + D3D12_MESSAGE_ID_META_COMMAND_ID_INVALID, + D3D12_MESSAGE_ID_META_COMMAND_UNSUPPORTED_PARAMS, + D3D12_MESSAGE_ID_META_COMMAND_FAILED_ENUMERATION, + D3D12_MESSAGE_ID_META_COMMAND_PARAMETER_SIZE_MISMATCH, + D3D12_MESSAGE_ID_UNINITIALIZED_META_COMMAND, + D3D12_MESSAGE_ID_META_COMMAND_INVALID_GPU_VIRTUAL_ADDRESS, + D3D12_MESSAGE_ID_CREATE_VIDEOENCODECOMMANDLIST, + D3D12_MESSAGE_ID_LIVE_VIDEOENCODECOMMANDLIST, + D3D12_MESSAGE_ID_DESTROY_VIDEOENCODECOMMANDLIST, + D3D12_MESSAGE_ID_CREATE_VIDEOENCODECOMMANDQUEUE, + D3D12_MESSAGE_ID_LIVE_VIDEOENCODECOMMANDQUEUE, + D3D12_MESSAGE_ID_DESTROY_VIDEOENCODECOMMANDQUEUE, + D3D12_MESSAGE_ID_CREATE_VIDEOMOTIONESTIMATOR, + D3D12_MESSAGE_ID_LIVE_VIDEOMOTIONESTIMATOR, + D3D12_MESSAGE_ID_DESTROY_VIDEOMOTIONESTIMATOR, + D3D12_MESSAGE_ID_CREATE_VIDEOMOTIONVECTORHEAP, + D3D12_MESSAGE_ID_LIVE_VIDEOMOTIONVECTORHEAP, + D3D12_MESSAGE_ID_DESTROY_VIDEOMOTIONVECTORHEAP, + D3D12_MESSAGE_ID_MULTIPLE_TRACKED_WORKLOADS, + D3D12_MESSAGE_ID_MULTIPLE_TRACKED_WORKLOAD_PAIRS, + D3D12_MESSAGE_ID_OUT_OF_ORDER_TRACKED_WORKLOAD_PAIR, + D3D12_MESSAGE_ID_CANNOT_ADD_TRACKED_WORKLOAD, + D3D12_MESSAGE_ID_INCOMPLETE_TRACKED_WORKLOAD_PAIR, + D3D12_MESSAGE_ID_CREATE_STATE_OBJECT_ERROR, + D3D12_MESSAGE_ID_GET_SHADER_IDENTIFIER_ERROR, + D3D12_MESSAGE_ID_GET_SHADER_STACK_SIZE_ERROR, + D3D12_MESSAGE_ID_GET_PIPELINE_STACK_SIZE_ERROR, + D3D12_MESSAGE_ID_SET_PIPELINE_STACK_SIZE_ERROR, + D3D12_MESSAGE_ID_GET_SHADER_IDENTIFIER_SIZE_INVALID, + D3D12_MESSAGE_ID_CHECK_DRIVER_MATCHING_IDENTIFIER_INVALID, + D3D12_MESSAGE_ID_CHECK_DRIVER_MATCHING_IDENTIFIER_DRIVER_REPORTED_ISSUE, + D3D12_MESSAGE_ID_RENDER_PASS_INVALID_RESOURCE_BARRIER, + D3D12_MESSAGE_ID_RENDER_PASS_DISALLOWED_API_CALLED, + D3D12_MESSAGE_ID_RENDER_PASS_CANNOT_NEST_RENDER_PASSES, + D3D12_MESSAGE_ID_RENDER_PASS_CANNOT_END_WITHOUT_BEGIN, + D3D12_MESSAGE_ID_RENDER_PASS_CANNOT_CLOSE_COMMAND_LIST, + D3D12_MESSAGE_ID_RENDER_PASS_GPU_WORK_WHILE_SUSPENDED, + D3D12_MESSAGE_ID_RENDER_PASS_MISMATCHING_SUSPEND_RESUME, + D3D12_MESSAGE_ID_RENDER_PASS_NO_PRIOR_SUSPEND_WITHIN_EXECUTECOMMANDLISTS, + D3D12_MESSAGE_ID_RENDER_PASS_NO_SUBSEQUENT_RESUME_WITHIN_EXECUTECOMMANDLISTS, + D3D12_MESSAGE_ID_TRACKED_WORKLOAD_COMMAND_QUEUE_MISMATCH, + D3D12_MESSAGE_ID_TRACKED_WORKLOAD_NOT_SUPPORTED, + D3D12_MESSAGE_ID_RENDER_PASS_MISMATCHING_NO_ACCESS, + D3D12_MESSAGE_ID_RENDER_PASS_UNSUPPORTED_RESOLVE, + D3D12_MESSAGE_ID_CLEARUNORDEREDACCESSVIEW_INVALID_RESOURCE_PTR, + D3D12_MESSAGE_ID_WINDOWS7_FENCE_OUTOFORDER_SIGNAL, + D3D12_MESSAGE_ID_WINDOWS7_FENCE_OUTOFORDER_WAIT, + D3D12_MESSAGE_ID_VIDEO_CREATE_MOTION_ESTIMATOR_INVALID_ARGUMENT, + D3D12_MESSAGE_ID_VIDEO_CREATE_MOTION_VECTOR_HEAP_INVALID_ARGUMENT, + D3D12_MESSAGE_ID_ESTIMATE_MOTION_INVALID_ARGUMENT, + D3D12_MESSAGE_ID_RESOLVE_MOTION_VECTOR_HEAP_INVALID_ARGUMENT, + D3D12_MESSAGE_ID_GETGPUVIRTUALADDRESS_INVALID_HEAP_TYPE, + D3D12_MESSAGE_ID_SET_BACKGROUND_PROCESSING_MODE_INVALID_ARGUMENT, + D3D12_MESSAGE_ID_CREATE_COMMAND_LIST_INVALID_COMMAND_LIST_TYPE_FOR_FEATURE_LEVEL, + D3D12_MESSAGE_ID_CREATE_VIDEOEXTENSIONCOMMAND, + D3D12_MESSAGE_ID_LIVE_VIDEOEXTENSIONCOMMAND, + D3D12_MESSAGE_ID_DESTROY_VIDEOEXTENSIONCOMMAND, + D3D12_MESSAGE_ID_INVALID_VIDEO_EXTENSION_COMMAND_ID, + D3D12_MESSAGE_ID_VIDEO_EXTENSION_COMMAND_INVALID_ARGUMENT, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_NOT_UNIQUE_IN_DXIL_LIBRARY, + + D3D12_MESSAGE_ID_VARIABLE_SHADING_RATE_NOT_ALLOWED_WITH_TIR, + D3D12_MESSAGE_ID_GEOMETRY_SHADER_OUTPUTTING_BOTH_VIEWPORT_ARRAY_INDEX_AND_SHADING_RATE_NOT_SUPPORTED_ON_DEVICE, + D3D12_MESSAGE_ID_RSSETSHADING_RATE_INVALID_SHADING_RATE, + D3D12_MESSAGE_ID_RSSETSHADING_RATE_SHADING_RATE_NOT_PERMITTED_BY_CAP, + D3D12_MESSAGE_ID_RSSETSHADING_RATE_INVALID_COMBINER, + D3D12_MESSAGE_ID_RSSETSHADINGRATEIMAGE_REQUIRES_TIER_2, + D3D12_MESSAGE_ID_RSSETSHADINGRATE_REQUIRES_TIER_1, + D3D12_MESSAGE_ID_SHADING_RATE_IMAGE_INCORRECT_FORMAT, + D3D12_MESSAGE_ID_SHADING_RATE_IMAGE_INCORRECT_ARRAY_SIZE, + D3D12_MESSAGE_ID_SHADING_RATE_IMAGE_INCORRECT_MIP_LEVEL, + D3D12_MESSAGE_ID_SHADING_RATE_IMAGE_INCORRECT_SAMPLE_COUNT, + D3D12_MESSAGE_ID_SHADING_RATE_IMAGE_INCORRECT_SAMPLE_QUALITY, + + D3D12_MESSAGE_ID_NON_RETAIL_SHADER_MODEL_WONT_VALIDATE, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_AS_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_MS_ROOT_SIGNATURE_MISMATCH, + D3D12_MESSAGE_ID_ADD_TO_STATE_OBJECT_ERROR, + D3D12_MESSAGE_ID_CREATE_PROTECTED_RESOURCE_SESSION_INVALID_ARGUMENT, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_MS_PSO_DESC_MISMATCH, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_MS_INCOMPLETE_TYPE, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_AS_NOT_MS_MISMATCH, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_MS_NOT_PS_MISMATCH, + D3D12_MESSAGE_ID_NONZERO_SAMPLER_FEEDBACK_MIP_REGION_WITH_INCOMPATIBLE_FORMAT, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INPUTLAYOUT_SHADER_MISMATCH, + D3D12_MESSAGE_ID_EMPTY_DISPATCH, + D3D12_MESSAGE_ID_RESOURCE_FORMAT_REQUIRES_SAMPLER_FEEDBACK_CAPABILITY, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_MAP_INVALID_MIP_REGION, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_MAP_INVALID_DIMENSION, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_MAP_INVALID_SAMPLE_COUNT, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_MAP_INVALID_SAMPLE_QUALITY, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_MAP_INVALID_LAYOUT, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_MAP_REQUIRES_UNORDERED_ACCESS_FLAG, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_CREATE_UAV_NULL_ARGUMENTS, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_UAV_REQUIRES_SAMPLER_FEEDBACK_CAPABILITY, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_CREATE_UAV_REQUIRES_FEEDBACK_MAP_FORMAT, + D3D12_MESSAGE_ID_CREATEMESHSHADER_INVALIDSHADERBYTECODE, + D3D12_MESSAGE_ID_CREATEMESHSHADER_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATEMESHSHADERWITHSTREAMOUTPUT_INVALIDSHADERTYPE, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_SAMPLER_FEEDBACK_TRANSCODE_INVALID_FORMAT, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_SAMPLER_FEEDBACK_INVALID_MIP_LEVEL_COUNT, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_SAMPLER_FEEDBACK_TRANSCODE_ARRAY_SIZE_MISMATCH, + D3D12_MESSAGE_ID_SAMPLER_FEEDBACK_CREATE_UAV_MISMATCHING_TARGETED_RESOURCE, + D3D12_MESSAGE_ID_CREATEMESHSHADER_OUTPUTEXCEEDSMAXSIZE, + D3D12_MESSAGE_ID_CREATEMESHSHADER_GROUPSHAREDEXCEEDSMAXSIZE, + D3D12_MESSAGE_ID_VERTEX_SHADER_OUTPUTTING_BOTH_VIEWPORT_ARRAY_INDEX_AND_SHADING_RATE_NOT_SUPPORTED_ON_DEVICE, + D3D12_MESSAGE_ID_MESH_SHADER_OUTPUTTING_BOTH_VIEWPORT_ARRAY_INDEX_AND_SHADING_RATE_NOT_SUPPORTED_ON_DEVICE, + D3D12_MESSAGE_ID_CREATEMESHSHADER_MISMATCHEDASMSPAYLOADSIZE, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_UNBOUNDED_STATIC_DESCRIPTORS, + D3D12_MESSAGE_ID_CREATEAMPLIFICATIONSHADER_INVALIDSHADERBYTECODE, + D3D12_MESSAGE_ID_CREATEAMPLIFICATIONSHADER_OUTOFMEMORY, + D3D12_MESSAGE_ID_CREATE_SHADERCACHESESSION, + D3D12_MESSAGE_ID_LIVE_SHADERCACHESESSION, + D3D12_MESSAGE_ID_DESTROY_SHADERCACHESESSION, + D3D12_MESSAGE_ID_CREATESHADERCACHESESSION_INVALIDARGS, + D3D12_MESSAGE_ID_CREATESHADERCACHESESSION_DISABLED, + D3D12_MESSAGE_ID_CREATESHADERCACHESESSION_ALREADYOPEN, + D3D12_MESSAGE_ID_SHADERCACHECONTROL_DEVELOPERMODE, + D3D12_MESSAGE_ID_SHADERCACHECONTROL_INVALIDFLAGS, + D3D12_MESSAGE_ID_SHADERCACHECONTROL_STATEALREADYSET, + D3D12_MESSAGE_ID_SHADERCACHECONTROL_IGNOREDFLAG, + D3D12_MESSAGE_ID_SHADERCACHESESSION_STOREVALUE_ALREADYPRESENT, + D3D12_MESSAGE_ID_SHADERCACHESESSION_STOREVALUE_HASHCOLLISION, + D3D12_MESSAGE_ID_SHADERCACHESESSION_STOREVALUE_CACHEFULL, + D3D12_MESSAGE_ID_SHADERCACHESESSION_FINDVALUE_NOTFOUND, + D3D12_MESSAGE_ID_SHADERCACHESESSION_CORRUPT, + D3D12_MESSAGE_ID_SHADERCACHESESSION_DISABLED, + D3D12_MESSAGE_ID_OVERSIZED_DISPATCH, + D3D12_MESSAGE_ID_CREATE_VIDEOENCODER, + D3D12_MESSAGE_ID_LIVE_VIDEOENCODER, + D3D12_MESSAGE_ID_DESTROY_VIDEOENCODER, + D3D12_MESSAGE_ID_CREATE_VIDEOENCODERHEAP, + D3D12_MESSAGE_ID_LIVE_VIDEOENCODERHEAP, + D3D12_MESSAGE_ID_DESTROY_VIDEOENCODERHEAP, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_MISMATCH_ENCODE_REFERENCE_ONLY_FLAG, + D3D12_MESSAGE_ID_COPYRESOURCE_MISMATCH_ENCODE_REFERENCE_ONLY_FLAG, + D3D12_MESSAGE_ID_ENCODE_FRAME_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_ENCODE_FRAME_UNSUPPORTED_PARAMETERS, + D3D12_MESSAGE_ID_RESOLVE_ENCODER_OUTPUT_METADATA_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_RESOLVE_ENCODER_OUTPUT_METADATA_UNSUPPORTED_PARAMETERS, + D3D12_MESSAGE_ID_CREATE_VIDEO_ENCODER_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_CREATE_VIDEO_ENCODER_UNSUPPORTED_PARAMETERS, + D3D12_MESSAGE_ID_CREATE_VIDEO_ENCODER_HEAP_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_CREATE_VIDEO_ENCODER_HEAP_UNSUPPORTED_PARAMETERS, + D3D12_MESSAGE_ID_CREATECOMMANDLIST_NULL_COMMANDALLOCATOR, + D3D12_MESSAGE_ID_CLEAR_UNORDERED_ACCESS_VIEW_INVALID_DESCRIPTOR_HANDLE, + D3D12_MESSAGE_ID_DESCRIPTOR_HEAP_NOT_SHADER_VISIBLE, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_BLENDOP_WARNING, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_BLENDOPALPHA_WARNING, + D3D12_MESSAGE_ID_WRITE_COMBINE_PERFORMANCE_WARNING, + D3D12_MESSAGE_ID_RESOLVE_QUERY_INVALID_QUERY_STATE, + D3D12_MESSAGE_ID_SETPRIVATEDATA_NO_ACCESS, + D3D12_MESSAGE_ID_COMMAND_LIST_STATIC_DESCRIPTOR_SAMPLER_MODE_MISMATCH, + D3D12_MESSAGE_ID_GETCOPYABLEFOOTPRINTS_UNSUPPORTED_BUFFER_WIDTH, + D3D12_MESSAGE_ID_CREATEMESHSHADER_TOPOLOGY_MISMATCH, + D3D12_MESSAGE_ID_VRS_SUM_COMBINER_REQUIRES_CAPABILITY, + D3D12_MESSAGE_ID_SETTING_SHADING_RATE_FROM_MS_REQUIRES_CAPABILITY, + D3D12_MESSAGE_ID_SHADERCACHESESSION_SHADERCACHEDELETE_NOTSUPPORTED, + D3D12_MESSAGE_ID_SHADERCACHECONTROL_SHADERCACHECLEAR_NOTSUPPORTED, + D3D12_MESSAGE_ID_CREATERESOURCE_STATE_IGNORED, + D3D12_MESSAGE_ID_UNUSED_CROSS_EXECUTE_SPLIT_BARRIER, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_HANDLE_ACCESS_DENIED, + D3D12_MESSAGE_ID_INCOMPATIBLE_BARRIER_VALUES, + D3D12_MESSAGE_ID_INCOMPATIBLE_BARRIER_ACCESS, + D3D12_MESSAGE_ID_INCOMPATIBLE_BARRIER_SYNC, + D3D12_MESSAGE_ID_INCOMPATIBLE_BARRIER_LAYOUT, + D3D12_MESSAGE_ID_INCOMPATIBLE_BARRIER_TYPE, + D3D12_MESSAGE_ID_OUT_OF_BOUNDS_BARRIER_SUBRESOURCE_RANGE, + D3D12_MESSAGE_ID_INCOMPATIBLE_BARRIER_RESOURCE_DIMENSION, + D3D12_MESSAGE_ID_SET_SCISSOR_RECTS_INVALID_RECT, + D3D12_MESSAGE_ID_SHADING_RATE_SOURCE_REQUIRES_DIMENSION_TEXTURE2D, + D3D12_MESSAGE_ID_BUFFER_BARRIER_SUBREGION_OUT_OF_BOUNDS, + D3D12_MESSAGE_ID_UNSUPPORTED_BARRIER_LAYOUT, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALID_PARAMETERS, + D3D12_MESSAGE_ID_ENHANCED_BARRIERS_NOT_SUPPORTED, + + D3D12_MESSAGE_ID_CAST_TARGET_TEXEL_SIZE_MISMATCH, + D3D12_MESSAGE_ID_CAST_TO_PLANAR_NOT_SUPORTED, + + D3D12_MESSAGE_ID_LEGACY_BARRIER_VALIDATION_FORCED_ON, + + D3D12_MESSAGE_ID_EMPTY_ROOT_DESCRIPTOR_TABLE, + + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_ELEMENT_OFFSET_UNALIGNED, + + D3D12_MESSAGE_ID_ALPHA_BLEND_FACTOR_NOT_SUPPORTED, + + D3D12_MESSAGE_ID_BARRIER_INTEROP_INVALID_LAYOUT, + D3D12_MESSAGE_ID_BARRIER_INTEROP_INVALID_STATE, + + D3D12_MESSAGE_ID_GRAPHICS_PIPELINE_STATE_DESC_ZERO_SAMPLE_MASK, + + D3D12_MESSAGE_ID_INDEPENDENT_STENCIL_REF_NOT_SUPPORTED, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INDEPENDENT_MASKS_UNSUPPORTED, + + D3D12_MESSAGE_ID_TEXTURE_BARRIER_SUBRESOURCES_OUT_OF_BOUNDS, + + D3D12_MESSAGE_ID_NON_OPTIMAL_BARRIER_ONLY_EXECUTE_COMMAND_LISTS, + + D3D12_MESSAGE_ID_EXECUTE_INDIRECT_ZERO_COMMAND_COUNT, + + D3D12_MESSAGE_ID_GPU_BASED_VALIDATION_INCOMPATIBLE_TEXTURE_LAYOUT, + + D3D12_MESSAGE_ID_DYNAMIC_INDEX_BUFFER_STRIP_CUT_NOT_SUPPORTED, + D3D12_MESSAGE_ID_PRIMITIVE_TOPOLOGY_TRIANGLE_FANS_NOT_SUPPORTED, + + D3D12_MESSAGE_ID_CREATE_SAMPLER_COMPARISON_FUNC_IGNORED, + + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDHEAPTYPE, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDHEAPTYPE, + D3D12_MESSAGE_ID_DYNAMIC_DEPTH_BIAS_NOT_SUPPORTED, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_NON_WHOLE_DYNAMIC_DEPTH_BIAS, + + D3D12_MESSAGE_ID_DYNAMIC_DEPTH_BIAS_FLAG_MISSING, + D3D12_MESSAGE_ID_DYNAMIC_DEPTH_BIAS_NO_PIPELINE, + D3D12_MESSAGE_ID_DYNAMIC_INDEX_BUFFER_STRIP_CUT_FLAG_MISSING, + D3D12_MESSAGE_ID_DYNAMIC_INDEX_BUFFER_STRIP_CUT_NO_PIPELINE, + + D3D12_MESSAGE_ID_D3D12_MESSAGES_END, + + // Aliases + D3D12_MESSAGE_ID_GETCOPYABLELAYOUT_INVALIDSUBRESOURCERANGE = D3D12_MESSAGE_ID_GETCOPYABLEFOOTPRINTS_INVALIDSUBRESOURCERANGE, + D3D12_MESSAGE_ID_GETCOPYABLELAYOUT_INVALIDBASEOFFSET = D3D12_MESSAGE_ID_GETCOPYABLEFOOTPRINTS_INVALIDBASEOFFSET, +} D3D12_MESSAGE_ID; + + +typedef struct D3D12_MESSAGE +{ + D3D12_MESSAGE_CATEGORY Category; + D3D12_MESSAGE_SEVERITY Severity; + D3D12_MESSAGE_ID ID; + _Field_size_(DescriptionByteLength) const char* pDescription; + SIZE_T DescriptionByteLength; +} D3D12_MESSAGE; + +typedef struct D3D12_INFO_QUEUE_FILTER_DESC +{ + UINT NumCategories; + _Field_size_(NumCategories) D3D12_MESSAGE_CATEGORY* pCategoryList; + UINT NumSeverities; + _Field_size_(NumSeverities) D3D12_MESSAGE_SEVERITY* pSeverityList; + UINT NumIDs; + _Field_size_(NumIDs) D3D12_MESSAGE_ID* pIDList; +} D3D12_INFO_QUEUE_FILTER_DESC; + +// To use, memset to 0, then fill in what you need. +typedef struct D3D12_INFO_QUEUE_FILTER +{ + D3D12_INFO_QUEUE_FILTER_DESC AllowList; + D3D12_INFO_QUEUE_FILTER_DESC DenyList; +} D3D12_INFO_QUEUE_FILTER; + + +extern "C" +{ + +typedef struct D3D12_SUBRESOURCE_DATA +{ + const void *pData; + LONG_PTR RowPitch; + LONG_PTR SlicePitch; +} D3D12_SUBRESOURCE_DATA; + +typedef struct D3D12_MEMCPY_DEST +{ + void *pData; + SIZE_T RowPitch; + SIZE_T SlicePitch; +} D3D12_MEMCPY_DEST; + +} + +extern "C" +{ + +/////////////////////////////////////////////////////////////////////////// +// D3D12CreateDevice +// ------------------ +// +// pAdapter +// If NULL, D3D12CreateDevice will choose the primary adapter and +// create a new instance from a temporarily created IDXGIFactory. +// If non-NULL, D3D12CreateDevice will use the provided adapter. +// MinimumFeatureLevel +// The minimum feature level required for successful device creation. +// riid +// The interface IID of the device to be returned. Expected: ID3D12Device. +// ppDevice +// Pointer to returned interface. May be NULL. +// +// Return Values +// Any of those documented for +// CreateDXGIFactory1 +// IDXGIFactory::EnumAdapters +// D3D12CreateDevice +// +/////////////////////////////////////////////////////////////////////////// + +typedef HRESULT (D3DAPI* PFN_D3D12_CREATE_DEVICE)( + _In_opt_ IGraphicsUnknown*, + D3D_FEATURE_LEVEL, + _In_ REFIID, + _Outptr_opt_ void**); + +HRESULT D3DAPI D3D12CreateDevice( + _In_opt_ IGraphicsUnknown* pAdapter, + D3D_FEATURE_LEVEL MinimumFeatureLevel, + _In_ REFIID riid, // Expected: ID3D12Device + _Outptr_opt_ void** ppDevice); + +} + +typedef enum D3D12XBOX_PROCESS_DEBUG_FLAGS +{ + D3D12XBOX_PROCESS_DEBUG_FLAG_NONE = 0x0, + D3D12XBOX_PROCESS_DEBUG_FLAG_DEBUG = 0x00000001, + D3D12_PROCESS_DEBUG_FLAG_DEBUG_LAYER_ENABLED = D3D12XBOX_PROCESS_DEBUG_FLAG_DEBUG, + D3D12XBOX_PROCESS_DEBUG_FLAG_INSTRUMENTED = 0x00100000, + D3D12XBOX_PROCESS_DEBUG_FLAG_VALIDATED = D3D12XBOX_PROCESS_DEBUG_FLAG_DEBUG, + D3D12XBOX_PROCESS_DEBUG_FLAG_NULL_GPU = 0x00400000, + D3D12XBOX_PROCESS_DEBUG_FLAG_ENABLE_COMMON_STATE_PROMOTION = 0x01000000, + D3D12XBOX_PROCESS_DEBUG_FLAG_ENHANCED_VALIDATION = 0x02000000, +} D3D12XBOX_PROCESS_DEBUG_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_PROCESS_DEBUG_FLAGS ); + +typedef enum D3D12XBOX_CREATE_DEVICE_FLAGS +{ + D3D12XBOX_CREATE_DEVICE_FLAG_NONE = 0x00000000, + D3D12XBOX_CREATE_DEVICE_FLAG_ENABLE_AUTO_HDR = 0x00000001, + D3D12XBOX_CREATE_DEVICE_FLAG_GPU_BUSY_COUNT_CP = 0x00000002, // The Command Processor can spin so not always useful in GPU Busy. + D3D12XBOX_CREATE_DEVICE_FLAG_GPU_BUSY_COUNT_SDMA = 0x00000004, // SDMA busy can't separate front-end from back end work so may appear busy for long periods. + D3D12XBOX_CREATE_DEVICE_FLAG_DISABLE_AUTO_DPBB = 0x00000008, // Disable automatic per-PSO configuration of deferred primitive batch binning (DPBB) + D3D12XBOX_CREATE_DEVICE_FLAG_SET_MAX_OFFCHIP_BUFFERING = 0x00000010, // Set the maximum OffchipTessellationAllocation for Arden/Sparkman + D3D12XBOX_CREATE_DEVICE_FLAG_NO_RUNTIME_COMPILATION = 0x00000020, // No runtime shader recompilation (useful for memory savings if DXIL is stripped) +} D3D12XBOX_CREATE_DEVICE_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS( D3D12XBOX_CREATE_DEVICE_FLAGS ); + +#define D3D12XBOX_DEFAULT_SIZE_BYTES (UINT(-1)) + +typedef struct D3D12XBOX_CREATE_DEVICE_PARAMETERS +{ + UINT Version; // Expected: D3D12_SDK_VERSION + D3D12XBOX_PROCESS_DEBUG_FLAGS ProcessDebugFlags; // Overrides any settings from D3D12XboxSetProcessDebugFlags or ID3D12Debug::SetProcessDebugFlags + UINT GraphicsCommandQueueRingSizeBytes; // D3D12XBOX_DEFAULT_SIZE_BYTES for the default of 4 MB, or any 64KB aligned size of at least 128 KB + D3D12_GPU_VIRTUAL_ADDRESS pOffchipTessellationBuffer; // 0 for driver allocated or pointer to a graphics memory buffer of size D3D12XBOX_OFFCHIP_TESSELLATION_BUFFER_SIZE + UINT GraphicsScratchMemorySizeBytes; // D3D12XBOX_DEFAULT_SIZE_BYTES for the default of 16 MB, or 0 + UINT ComputeScratchMemorySizeBytes; // D3D12XBOX_DEFAULT_SIZE_BYTES for the default of 16 MB, or any 64KB aligned size including 0 + BOOL DisableGeometryShaderAllocations; // Doesn't allocate Geometry Shader rings. Prevents Geometry Shaders from being used. + BOOL DisableTessellationShaderAllocations; // Doesn't allocate Tessellation related rings. Prevents Geometry Shaders from being used. + BOOL DisableDXR; // Disables dll loading and scratch allocation for DXR + BOOL DisableAutomaticDPBBBreakBatchEvents; // Opt out of driver managed Break Batch evens for Deferred Primitive Batch Binning. + D3D12_GPU_VIRTUAL_ADDRESS pDXRStackBuffer; // 0 for driver to allocate a DXR scratch buffer. If not 0, DXRStackBufferOverrideSizeBytes must specify size. DispatchRaysX() can override. + UINT DXRStackBufferOverrideSizeBytes; // 0 for system default, otherwise overrides the scratch size or specifies size of non-zero pDXRStackBuffer. DispatchRaysX() can override. + D3D12XBOX_CREATE_DEVICE_FLAGS CreateDeviceFlags; // Flags + UINT AutoHDRPaperWhiteLevelNits; // Sets the paper white (SDR brightness) when AutoHDR is enabled, or 0 to use the default. + BOOL DisableAutomaticCommandSegmentChaining; // Disables automatic command segment chaining + UINT AmplificationShaderIndirectArgsBufferSize; // D3D12XBOX_DEFAULT_SIZE_BYTES for the default of 64 KB. Set to 0 if you don't use amplification shaders (or exclusively use the DispatchMeshX API) + UINT AmplificationShaderPayloadBufferSize; // D3D12XBOX_DEFAULT_SIZE_BYTES for the default of 64 KB. Set to 0 if you don't use amplification shaders (or exclusively use the DispatchMeshX API) +} D3D12XBOX_CREATE_DEVICE_PARAMETERS; + +extern "C" +{ + +typedef HRESULT (D3DAPI* PFN_D3D12_XBOX_CREATE_DEVICE)( + _In_opt_ IGraphicsUnknown*, + _In_ const D3D12XBOX_CREATE_DEVICE_PARAMETERS*, + _In_ REFIID, + _Outptr_opt_ void**); + +HRESULT D3DAPI D3D12XboxCreateDevice( + _In_opt_ IGraphicsUnknown* pAdapter, + _In_ const D3D12XBOX_CREATE_DEVICE_PARAMETERS* pParameters, + _In_ REFIID riid, // Expected: ID3D12Device + _Outptr_opt_ void** ppDevice); + +void D3DAPI D3D12XboxUnloadDriverModule(); +} + +D3DINTERFACE(ID3D12Debug, 344488b7,6846,474b,b9,89,f0,27,44,82,45,e0) : public IGraphicsUnknown +{ + virtual HRESULT SetProcessDebugFlags(D3D12XBOX_PROCESS_DEBUG_FLAGS Flags) = 0; + + D3DINLINE HRESULT EnableDebugLayer() + { + return SetProcessDebugFlags(D3D12XBOX_PROCESS_DEBUG_FLAG_DEBUG); + } +}; + +// +// ID3D12SharingContract +// + +extern "C" +{ + + struct D3D12SharingContract_Function_Table + { + + void (D3DAPI* BeginCapturableWork)( + _Inout_ ID3D12SharingContract* pSharingContract, + const GUID& guid + ); + + void (D3DAPI* EndCapturableWork)( + _Inout_ ID3D12SharingContract* pSharingContract, + const GUID& guid + ); + + void (D3DAPI* Present)( + _Inout_ ID3D12SharingContract* pSharingContract, + ID3D12Resource* pResource, + UINT Subresource, + HWND window + ); + + void (D3DAPI* SharedFenceSignal)( + _Inout_ ID3D12SharingContract* pSharingContract, + ID3D12Fence* pFence, + UINT64 FenceValue + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12SharingContract_BeginCapturableWork( + _Inout_ ID3D12SharingContract* pSharingContract, + const GUID& guid + ); + + void D3d12SharingContract_EndCapturableWork( + _Inout_ ID3D12SharingContract* pSharingContract, + const GUID& guid + ); + + void D3d12SharingContract_Present( + _Inout_ ID3D12SharingContract* pSharingContract, + ID3D12Resource* pResource, + UINT Subresource, + HWND window + ); + + void D3d12SharingContract_SharedFenceSignal( + _Inout_ ID3D12SharingContract* pSharingContract, + ID3D12Fence* pFence, + UINT64 FenceValue + ); + + D3DCONST D3D12SharingContract_Function_Table D3D__D3d12SharingContract_Function_Table = + { + D3d12SharingContract_BeginCapturableWork, + D3d12SharingContract_EndCapturableWork, + D3d12SharingContract_Present, + D3d12SharingContract_SharedFenceSignal, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12SharingContract, 0adf7d52, 929c, 4e61, ad, db, ff, ed, 30, de, 66, ef) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12SharingContract_Function_Table* SharingContractFunction() + { + return (D3D12SharingContract_Function_Table*)m_pFunction; + } + + D3DINLINE void BeginCapturableWork( + const GUID & guid + ) + { + SharingContractFunction()->BeginCapturableWork(this, guid); + } + + D3DINLINE void EndCapturableWork( + const GUID & guid + ) + { + SharingContractFunction()->EndCapturableWork(this, guid); + } + + D3DINLINE void Present( + ID3D12Resource * pResource, + UINT Subresource, + HWND window + ) + { + SharingContractFunction()->Present(this, pResource, Subresource, window); + } + + D3DINLINE void SharedFenceSignal( + ID3D12Fence * pFence, + UINT64 FenceValue + ) + { + SharingContractFunction()->SharedFenceSignal(this, pFence, FenceValue); + } +}; + +// +// ID3D12VirtualizationGuestDevice +// + +extern "C" +{ + + struct D3D12VirtualizationGuestDevice_Function_Table + { + + HRESULT(D3DAPI* CreateFenceFd)( + _Inout_ ID3D12VirtualizationGuestDevice* pVirtualizationGuestDevice, + _In_ ID3D12Fence* pFence, + UINT64 FenceValue, + _Out_ int* pFenceFd + ); + + HRESULT(D3DAPI* ShareWithHost)( + _Inout_ ID3D12VirtualizationGuestDevice* pVirtualizationGuestDevice, + _In_ ID3D12DeviceChild* pObject, + _Out_ HANDLE* pHandle + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + HRESULT D3d12VirtualizationGuestDevice_CreateFenceFd( + _Inout_ ID3D12VirtualizationGuestDevice* pVirtualizationGuestDevice, + _In_ ID3D12Fence* pFence, + UINT64 FenceValue, + _Out_ int* pFenceFd + ); + + HRESULT D3d12VirtualizationGuestDevice_ShareWithHost( + _Inout_ ID3D12VirtualizationGuestDevice* pVirtualizationGuestDevice, + _In_ ID3D12DeviceChild* pObject, + _Out_ HANDLE* pHandle + ); + + D3DCONST D3D12VirtualizationGuestDevice_Function_Table D3D__D3d12VirtualizationGuestDevice_Function_Table = + { + D3d12VirtualizationGuestDevice_CreateFenceFd, + D3d12VirtualizationGuestDevice_ShareWithHost, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12VirtualizationGuestDevice, bc66d368, 7373, 4943, 87, 57, fc, 87, dc, 79, e4, 76) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12VirtualizationGuestDevice_Function_Table* VirtualizationGuestDeviceFunction() + { + return (D3D12VirtualizationGuestDevice_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT CreateFenceFd( + _In_ ID3D12Fence * pFence, + UINT64 FenceValue, + _Out_ int* pFenceFd + ) + { + return VirtualizationGuestDeviceFunction()->CreateFenceFd(this, pFence, FenceValue, pFenceFd); + } + + D3DINLINE HRESULT ShareWithHost( + _In_ ID3D12DeviceChild * pObject, + _Out_ HANDLE * pHandle + ) + { + return VirtualizationGuestDeviceFunction()->ShareWithHost(this, pObject, pHandle); + } +}; + +// +// ID3D12Debug1 +// + +extern "C" +{ + + typedef enum D3D12_GPU_BASED_VALIDATION_FLAGS + { + D3D12_GPU_BASED_VALIDATION_FLAGS_NONE = 0, + D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING = 0x1 + } D3D12_GPU_BASED_VALIDATION_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_GPU_BASED_VALIDATION_FLAGS); + + typedef enum D3D12_DEBUG_FEATURE + { + D3D12_DEBUG_FEATURE_NONE = 0, + D3D12_DEBUG_FEATURE_ALLOW_BEHAVIOR_CHANGING_DEBUG_AIDS = 0x1, + D3D12_DEBUG_FEATURE_CONSERVATIVE_RESOURCE_STATE_TRACKING = 0x2, + D3D12_DEBUG_FEATURE_DISABLE_VIRTUALIZED_BUNDLES_VALIDATION = 0x4, + D3D12_DEBUG_FEATURE_EMULATE_WINDOWS7 = 0x8 + } D3D12_DEBUG_FEATURE; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_DEBUG_FEATURE); + + typedef enum D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE + { + D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE_NONE = 0, + D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE_STATE_TRACKING_ONLY = (D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE_NONE + 1), + D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE_UNGUARDED_VALIDATION = (D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE_STATE_TRACKING_ONLY + 1), + D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE_GUARDED_VALIDATION = (D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE_UNGUARDED_VALIDATION + 1), + NUM_D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODES = (D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE_GUARDED_VALIDATION + 1) + } D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE; + + typedef enum D3D12_GPU_BASED_VALIDATION_PIPELINE_STATE_CREATE_FLAGS + { + D3D12_GPU_BASED_VALIDATION_PIPELINE_STATE_CREATE_FLAG_NONE = 0, + D3D12_GPU_BASED_VALIDATION_PIPELINE_STATE_CREATE_FLAG_FRONT_LOAD_CREATE_TRACKING_ONLY_SHADERS = 0x1, + D3D12_GPU_BASED_VALIDATION_PIPELINE_STATE_CREATE_FLAG_FRONT_LOAD_CREATE_UNGUARDED_VALIDATION_SHADERS = 0x2, + D3D12_GPU_BASED_VALIDATION_PIPELINE_STATE_CREATE_FLAG_FRONT_LOAD_CREATE_GUARDED_VALIDATION_SHADERS = 0x4, + D3D12_GPU_BASED_VALIDATION_PIPELINE_STATE_CREATE_FLAGS_VALID_MASK = 0x7 + } D3D12_GPU_BASED_VALIDATION_PIPELINE_STATE_CREATE_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_GPU_BASED_VALIDATION_PIPELINE_STATE_CREATE_FLAGS) + + typedef enum D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE + { + D3D12_DEBUG_COMMAND_LIST_PARAMETER_GPU_BASED_VALIDATION_SETTINGS = 0 + } D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE; + + typedef struct D3D12_DEBUG_COMMAND_LIST_GPU_BASED_VALIDATION_SETTINGS + { + D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE ShaderPatchMode; + } D3D12_DEBUG_COMMAND_LIST_GPU_BASED_VALIDATION_SETTINGS; + + typedef struct D3D12_DEBUG_DEVICE_GPU_BASED_VALIDATION_SETTINGS + { + UINT MaxMessagesPerCommandList; + D3D12_GPU_BASED_VALIDATION_SHADER_PATCH_MODE DefaultShaderPatchMode; + D3D12_GPU_BASED_VALIDATION_PIPELINE_STATE_CREATE_FLAGS PipelineStateCreateFlags; + } D3D12_DEBUG_DEVICE_GPU_BASED_VALIDATION_SETTINGS; + + typedef struct D3D12_DEBUG_DEVICE_GPU_SLOWDOWN_PERFORMANCE_FACTOR + { + FLOAT SlowdownFactor; + } D3D12_DEBUG_DEVICE_GPU_SLOWDOWN_PERFORMANCE_FACTOR; + + typedef struct D3D12_QUERY_DATA_PIPELINE_STATISTICS1 + { + UINT64 IAVertices; + UINT64 IAPrimitives; + UINT64 VSInvocations; + UINT64 GSInvocations; + UINT64 GSPrimitives; + UINT64 CInvocations; + UINT64 CPrimitives; + UINT64 PSInvocations; + UINT64 HSInvocations; + UINT64 DSInvocations; + UINT64 CSInvocations; + UINT64 ASInvocations; + UINT64 MSInvocations; + UINT64 MSPrimitives; + } D3D12_QUERY_DATA_PIPELINE_STATISTICS1; + + struct D3D12Debug1_Function_Table + { + void (D3DAPI* EnableDebugLayer)( + _Inout_ ID3D12Debug1* pDebug + ); + + void (D3DAPI* SetEnableGPUBasedValidation)( + _Inout_ ID3D12Debug1* pDebug, + BOOL Enable + ); + + void (D3DAPI* SetEnableSynchronizedCommandQueueValidation)( + _Inout_ ID3D12Debug1* pDebug, + BOOL Enable + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12Debug1_EnableDebugLayer( + _Inout_ ID3D12Debug1* pDebug + ); + + void D3d12Debug1_SetEnableGPUBasedValidation( + _Inout_ ID3D12Debug1* pDebug, + BOOL Enable + ); + + void D3d12Debug1_SetEnableSynchronizedCommandQueueValidation( + _Inout_ ID3D12Debug1* pDebug, + BOOL Enable + ); + + D3DCONST D3D12Debug1_Function_Table D3D__D3d12Debug1_Function_Table = + { + D3d12Debug1_EnableDebugLayer, + D3d12Debug1_SetEnableGPUBasedValidation, + D3d12Debug1_SetEnableSynchronizedCommandQueueValidation, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Debug1, affaa4ca, 63fe, 4d8e, b8, ad, 15, 90, 00, af, 43, 04) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12Debug1_Function_Table* Debug1Function() + { + return (D3D12Debug1_Function_Table*)m_pFunction; + } + + D3DINLINE void EnableDebugLayer( + ) + { + Debug1Function()->EnableDebugLayer(this); + } + + D3DINLINE void SetEnableGPUBasedValidation( + BOOL Enable + ) + { + Debug1Function()->SetEnableGPUBasedValidation(this, Enable); + } + + D3DINLINE void SetEnableSynchronizedCommandQueueValidation( + BOOL Enable + ) + { + Debug1Function()->SetEnableSynchronizedCommandQueueValidation(this, Enable); + } +}; +// +// ID3D12Debug2 +// + +extern "C" +{ + + struct D3D12Debug2_Function_Table + { + D3D12Debug1_Function_Table ParentFunction; + + void (D3DAPI* SetGPUBasedValidationFlags)( + _Inout_ ID3D12Debug2* pDebug, + D3D12_GPU_BASED_VALIDATION_FLAGS Flags + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12Debug2_SetGPUBasedValidationFlags( + _Inout_ ID3D12Debug2* pDebug, + D3D12_GPU_BASED_VALIDATION_FLAGS Flags + ); + + D3DCONST D3D12Debug2_Function_Table D3D__D3d12Debug2_Function_Table = + { + D3D__D3d12Debug1_Function_Table, + D3d12Debug2_SetGPUBasedValidationFlags, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Debug2, 93a665c4, a3b2, 4e5d, b6, 92, a2, 6a, e1, 4e, 33, 74) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12Debug2_Function_Table* Debug2Function() + { + return (D3D12Debug2_Function_Table*)m_pFunction; + } + + D3DINLINE void SetGPUBasedValidationFlags( + D3D12_GPU_BASED_VALIDATION_FLAGS Flags + ) + { + Debug2Function()->SetGPUBasedValidationFlags(this, Flags); + } +}; +// +// ID3D12Debug3 +// + +extern "C" +{ + + struct D3D12Debug3_Function_Table + { + D3D12Debug2_Function_Table ParentFunction; + + void (D3DAPI* SetEnableGPUBasedValidation)( + _Inout_ ID3D12Debug3* pDebug, + BOOL Enable + ); + + void (D3DAPI* SetEnableSynchronizedCommandQueueValidation)( + _Inout_ ID3D12Debug3* pDebug, + BOOL Enable + ); + + void (D3DAPI* SetGPUBasedValidationFlags)( + _Inout_ ID3D12Debug3* pDebug, + D3D12_GPU_BASED_VALIDATION_FLAGS Flags + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12Debug3_SetEnableGPUBasedValidation( + _Inout_ ID3D12Debug3* pDebug, + BOOL Enable + ); + + void D3d12Debug3_SetEnableSynchronizedCommandQueueValidation( + _Inout_ ID3D12Debug3* pDebug, + BOOL Enable + ); + + void D3d12Debug3_SetGPUBasedValidationFlags( + _Inout_ ID3D12Debug3* pDebug, + D3D12_GPU_BASED_VALIDATION_FLAGS Flags + ); + + D3DCONST D3D12Debug3_Function_Table D3D__D3d12Debug3_Function_Table = + { + D3D__D3d12Debug2_Function_Table, + D3d12Debug3_SetEnableGPUBasedValidation, + D3d12Debug3_SetEnableSynchronizedCommandQueueValidation, + D3d12Debug3_SetGPUBasedValidationFlags, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Debug3, 5cf4e58f, f671, 4ff1, a5, 42, 36, 86, e3, d1, 53, d1) : public ID3D12Debug +{ +public: + D3DINLINE D3D12Debug3_Function_Table* Debug3Function() + { + return (D3D12Debug3_Function_Table*)m_pFunction; + } + + D3DINLINE void SetEnableGPUBasedValidation( + BOOL Enable + ) + { + Debug3Function()->SetEnableGPUBasedValidation(this, Enable); + } + + D3DINLINE void SetEnableSynchronizedCommandQueueValidation( + BOOL Enable + ) + { + Debug3Function()->SetEnableSynchronizedCommandQueueValidation(this, Enable); + } + + D3DINLINE void SetGPUBasedValidationFlags( + D3D12_GPU_BASED_VALIDATION_FLAGS Flags + ) + { + Debug3Function()->SetGPUBasedValidationFlags(this, Flags); + } +}; +// +// ID3D12Debug4 +// + +extern "C" +{ + + struct D3D12Debug4_Function_Table + { + D3D12Debug3_Function_Table ParentFunction; + + void (D3DAPI* DisableDebugLayer)( + _Inout_ ID3D12Debug4* pDebug + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12Debug4_DisableDebugLayer( + _Inout_ ID3D12Debug4* pDebug + ); + + D3DCONST D3D12Debug4_Function_Table D3D__D3d12Debug4_Function_Table = + { + D3D__D3d12Debug3_Function_Table, + D3d12Debug4_DisableDebugLayer, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Debug4, 014b816e, 9ec5, 4a2f, a8, 45, ff, be, 44, 1c, e1, 3a) : public ID3D12Debug3 +{ +public: + D3DINLINE D3D12Debug4_Function_Table* Debug4Function() + { + return (D3D12Debug4_Function_Table*)m_pFunction; + } + + D3DINLINE void DisableDebugLayer( + ) + { + Debug4Function()->DisableDebugLayer(this); + } +}; +// +// ID3D12Debug5 +// + +extern "C" +{ + + struct D3D12Debug5_Function_Table + { + D3D12Debug4_Function_Table ParentFunction; + + void (D3DAPI* SetEnableAutoName)( + _Inout_ ID3D12Debug5* pDebug, + BOOL Enable + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12Debug5_SetEnableAutoName( + _Inout_ ID3D12Debug5* pDebug, + BOOL Enable + ); + + D3DCONST D3D12Debug5_Function_Table D3D__D3d12Debug5_Function_Table = + { + D3D__D3d12Debug4_Function_Table, + D3d12Debug5_SetEnableAutoName, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Debug5, 548d6b12, 09fa, 40e0, 90, 69, 5d, cd, 58, 9a, 52, c9) : public ID3D12Debug4 +{ +public: + D3DINLINE D3D12Debug5_Function_Table* Debug5Function() + { + return (D3D12Debug5_Function_Table*)m_pFunction; + } + + D3DINLINE void SetEnableAutoName( + BOOL Enable + ) + { + Debug5Function()->SetEnableAutoName(this, Enable); + } +}; + +// +// ID3D12Debug6 +// + +extern "C" +{ + + struct D3D12Debug6_Function_Table + { + D3D12Debug5_Function_Table ParentFunction; + + void (D3DAPI* SetForceLegacyBarrierValidation)( + _Inout_ ID3D12Debug6* pDebug, + BOOL Enable + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + void D3d12Debug6_SetForceLegacyBarrierValidation( + _Inout_ ID3D12Debug6* pDebug, + BOOL Enable + ); + + D3DCONST D3D12Debug6_Function_Table D3D__D3d12Debug6_Function_Table = + { + D3D__D3d12Debug5_Function_Table, + D3d12Debug6_SetForceLegacyBarrierValidation, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12Debug6, 82a816d6, 5d01, 4157, 97, d0, 49, 75, 46, 3f, d1, ed) : public ID3D12Debug5 +{ +public: + D3DINLINE D3D12Debug6_Function_Table* Debug6Function() + { + return (D3D12Debug6_Function_Table*)m_pFunction; + } + + D3DINLINE void SetForceLegacyBarrierValidation( + BOOL Enable + ) + { + Debug6Function()->SetForceLegacyBarrierValidation(this, Enable); + } +}; + +// +// ID3D12DebugCommandList +// + +extern "C" +{ + + struct D3D12DebugCommandList_Function_Table + { + + BOOL(D3DAPI* AssertResourceState)( + _Inout_ ID3D12DebugCommandList* pDebugCommandList, + ID3D12Resource* pResource, + UINT Subresource, + UINT State + ); + + D3D12_DEBUG_FEATURE(D3DAPI* GetFeatureMask)( + _Inout_ ID3D12DebugCommandList* pDebugCommandList + ); + + HRESULT(D3DAPI* SetFeatureMask)( + _Inout_ ID3D12DebugCommandList* pDebugCommandList, + D3D12_DEBUG_FEATURE Mask + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + BOOL D3d12DebugCommandList_AssertResourceState( + _Inout_ ID3D12DebugCommandList* pDebugCommandList, + ID3D12Resource* pResource, + UINT Subresource, + UINT State + ); + + D3D12_DEBUG_FEATURE D3d12DebugCommandList_GetFeatureMask( + _Inout_ ID3D12DebugCommandList* pDebugCommandList + ); + + HRESULT D3d12DebugCommandList_SetFeatureMask( + _Inout_ ID3D12DebugCommandList* pDebugCommandList, + D3D12_DEBUG_FEATURE Mask + ); + + D3DCONST D3D12DebugCommandList_Function_Table D3D__D3d12DebugCommandList_Function_Table = + { + D3d12DebugCommandList_AssertResourceState, + D3d12DebugCommandList_GetFeatureMask, + D3d12DebugCommandList_SetFeatureMask, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DebugCommandList, 09e0bf36, 54ac, 484f, 88, 47, 4b, ae, ea, b6, 05, 3f) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12DebugCommandList_Function_Table* DebugCommandListFunction() + { + return (D3D12DebugCommandList_Function_Table*)m_pFunction; + } + + D3DINLINE BOOL AssertResourceState( + ID3D12Resource * pResource, + UINT Subresource, + UINT State + ) + { + return DebugCommandListFunction()->AssertResourceState(this, pResource, Subresource, State); + } + + D3DINLINE D3D12_DEBUG_FEATURE GetFeatureMask( + ) + { + return DebugCommandListFunction()->GetFeatureMask(this); + } + + D3DINLINE HRESULT SetFeatureMask( + D3D12_DEBUG_FEATURE Mask + ) + { + return DebugCommandListFunction()->SetFeatureMask(this, Mask); + } +}; +// +// ID3D12DebugCommandList1 +// + +extern "C" +{ + + struct D3D12DebugCommandList1_Function_Table + { + D3D12DebugCommandList_Function_Table ParentFunction; + + BOOL(D3DAPI* AssertResourceState)( + _Inout_ ID3D12DebugCommandList1* pDebugCommandList, + ID3D12Resource* pResource, + UINT Subresource, + UINT State + ); + + HRESULT(D3DAPI* GetDebugParameter)( + _Inout_ ID3D12DebugCommandList1* pDebugCommandList, + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ); + + HRESULT(D3DAPI* SetDebugParameter)( + _Inout_ ID3D12DebugCommandList1* pDebugCommandList, + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + BOOL D3d12DebugCommandList1_AssertResourceState( + _Inout_ ID3D12DebugCommandList1* pDebugCommandList, + ID3D12Resource* pResource, + UINT Subresource, + UINT State + ); + + HRESULT D3d12DebugCommandList1_GetDebugParameter( + _Inout_ ID3D12DebugCommandList1* pDebugCommandList, + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ); + + HRESULT D3d12DebugCommandList1_SetDebugParameter( + _Inout_ ID3D12DebugCommandList1* pDebugCommandList, + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ); + + D3DCONST D3D12DebugCommandList1_Function_Table D3D__D3d12DebugCommandList1_Function_Table = + { + D3D__D3d12DebugCommandList_Function_Table, + D3d12DebugCommandList1_AssertResourceState, + D3d12DebugCommandList1_GetDebugParameter, + D3d12DebugCommandList1_SetDebugParameter, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DebugCommandList1, 102ca951, 311b, 4b01, b1, 1f, ec, b8, 3e, 06, 1b, 37) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12DebugCommandList1_Function_Table* DebugCommandList1Function() + { + return (D3D12DebugCommandList1_Function_Table*)m_pFunction; + } + + D3DINLINE BOOL AssertResourceState( + ID3D12Resource * pResource, + UINT Subresource, + UINT State + ) + { + return DebugCommandList1Function()->AssertResourceState(this, pResource, Subresource, State); + } + + D3DINLINE HRESULT GetDebugParameter( + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ) + { + return DebugCommandList1Function()->GetDebugParameter(this, Type, pData, DataSize); + } + + D3DINLINE HRESULT SetDebugParameter( + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ) + { + return DebugCommandList1Function()->SetDebugParameter(this, Type, pData, DataSize); + } +}; +// +// ID3D12DebugCommandList2 +// + +extern "C" +{ + + struct D3D12DebugCommandList2_Function_Table + { + D3D12DebugCommandList1_Function_Table ParentFunction; + + HRESULT(D3DAPI* GetDebugParameter)( + _Inout_ ID3D12DebugCommandList2* pDebugCommandList, + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ); + + HRESULT(D3DAPI* SetDebugParameter)( + _Inout_ ID3D12DebugCommandList2* pDebugCommandList, + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + HRESULT D3d12DebugCommandList2_GetDebugParameter( + _Inout_ ID3D12DebugCommandList2* pDebugCommandList, + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ); + + HRESULT D3d12DebugCommandList2_SetDebugParameter( + _Inout_ ID3D12DebugCommandList2* pDebugCommandList, + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ); + + D3DCONST D3D12DebugCommandList2_Function_Table D3D__D3d12DebugCommandList2_Function_Table = + { + D3D__D3d12DebugCommandList1_Function_Table, + D3d12DebugCommandList2_GetDebugParameter, + D3d12DebugCommandList2_SetDebugParameter, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DebugCommandList2, aeb575cf, 4e06, 48be, ba, 3b, c4, 50, fc, 96, 65, 2e) : public ID3D12DebugCommandList +{ +public: + D3DINLINE D3D12DebugCommandList2_Function_Table* DebugCommandList2Function() + { + return (D3D12DebugCommandList2_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT GetDebugParameter( + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ) + { + return DebugCommandList2Function()->GetDebugParameter(this, Type, pData, DataSize); + } + + D3DINLINE HRESULT SetDebugParameter( + D3D12_DEBUG_COMMAND_LIST_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ) + { + return DebugCommandList2Function()->SetDebugParameter(this, Type, pData, DataSize); + } +}; +// +// ID3D12DebugCommandQueue +// + +extern "C" +{ + + struct D3D12DebugCommandQueue_Function_Table + { + + BOOL(D3DAPI* AssertResourceState)( + _Inout_ ID3D12DebugCommandQueue* pDebugCommandQueue, + ID3D12Resource* pResource, + UINT Subresource, + UINT State + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + BOOL D3d12DebugCommandQueue_AssertResourceState( + _Inout_ ID3D12DebugCommandQueue* pDebugCommandQueue, + ID3D12Resource* pResource, + UINT Subresource, + UINT State + ); + + D3DCONST D3D12DebugCommandQueue_Function_Table D3D__D3d12DebugCommandQueue_Function_Table = + { + D3d12DebugCommandQueue_AssertResourceState, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DebugCommandQueue, 09e0bf36, 54ac, 484f, 88, 47, 4b, ae, ea, b6, 05, 3a) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12DebugCommandQueue_Function_Table* DebugCommandQueueFunction() + { + return (D3D12DebugCommandQueue_Function_Table*)m_pFunction; + } + + D3DINLINE BOOL AssertResourceState( + ID3D12Resource * pResource, + UINT Subresource, + UINT State + ) + { + return DebugCommandQueueFunction()->AssertResourceState(this, pResource, Subresource, State); + } +}; + +// +// ID3D12DebugDevice +// + +extern "C" +{ + typedef enum D3D12_RLDO_FLAGS + { + D3D12_RLDO_NONE = 0, + D3D12_RLDO_SUMMARY = 0x1, + D3D12_RLDO_DETAIL = 0x2, + D3D12_RLDO_IGNORE_INTERNAL = 0x4 + } D3D12_RLDO_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_RLDO_FLAGS); + + typedef enum D3D12_DEBUG_DEVICE_PARAMETER_TYPE + { + D3D12_DEBUG_DEVICE_PARAMETER_FEATURE_FLAGS = 0, + D3D12_DEBUG_DEVICE_PARAMETER_GPU_BASED_VALIDATION_SETTINGS = (D3D12_DEBUG_DEVICE_PARAMETER_FEATURE_FLAGS + 1), + D3D12_DEBUG_DEVICE_PARAMETER_GPU_SLOWDOWN_PERFORMANCE_FACTOR = (D3D12_DEBUG_DEVICE_PARAMETER_GPU_BASED_VALIDATION_SETTINGS + 1) + } D3D12_DEBUG_DEVICE_PARAMETER_TYPE; + + struct D3D12DebugDevice_Function_Table + { + + D3D12_DEBUG_FEATURE(D3DAPI* GetFeatureMask)( + _Inout_ ID3D12DebugDevice* pDebugDevice + ); + + HRESULT(D3DAPI* ReportLiveDeviceObjects)( + _Inout_ ID3D12DebugDevice* pDebugDevice, + D3D12_RLDO_FLAGS Flags + ); + + HRESULT(D3DAPI* SetFeatureMask)( + _Inout_ ID3D12DebugDevice* pDebugDevice, + D3D12_DEBUG_FEATURE Mask + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + D3D12_DEBUG_FEATURE D3d12DebugDevice_GetFeatureMask( + _Inout_ ID3D12DebugDevice* pDebugDevice + ); + + HRESULT D3d12DebugDevice_ReportLiveDeviceObjects( + _Inout_ ID3D12DebugDevice* pDebugDevice, + D3D12_RLDO_FLAGS Flags + ); + + HRESULT D3d12DebugDevice_SetFeatureMask( + _Inout_ ID3D12DebugDevice* pDebugDevice, + D3D12_DEBUG_FEATURE Mask + ); + + D3DCONST D3D12DebugDevice_Function_Table D3D__D3d12DebugDevice_Function_Table = + { + D3d12DebugDevice_GetFeatureMask, + D3d12DebugDevice_ReportLiveDeviceObjects, + D3d12DebugDevice_SetFeatureMask, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DebugDevice, 3febd6dd, 4973, 4787, 81, 94, e4, 5f, 9e, 28, 92, 3e) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12DebugDevice_Function_Table* DebugDeviceFunction() + { + return (D3D12DebugDevice_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_DEBUG_FEATURE GetFeatureMask( + ) + { + return DebugDeviceFunction()->GetFeatureMask(this); + } + + D3DINLINE HRESULT ReportLiveDeviceObjects( + D3D12_RLDO_FLAGS Flags + ) + { + return DebugDeviceFunction()->ReportLiveDeviceObjects(this, Flags); + } + + D3DINLINE HRESULT SetFeatureMask( + D3D12_DEBUG_FEATURE Mask + ) + { + return DebugDeviceFunction()->SetFeatureMask(this, Mask); + } +}; +// +// ID3D12DebugDevice1 +// + +extern "C" +{ + + struct D3D12DebugDevice1_Function_Table + { + D3D12DebugDevice_Function_Table ParentFunction; + + HRESULT(D3DAPI* GetDebugParameter)( + _Inout_ ID3D12DebugDevice1* pDebugDevice, + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ); + + HRESULT(D3DAPI* ReportLiveDeviceObjects)( + _Inout_ ID3D12DebugDevice1* pDebugDevice, + D3D12_RLDO_FLAGS Flags + ); + + HRESULT(D3DAPI* SetDebugParameter)( + _Inout_ ID3D12DebugDevice1* pDebugDevice, + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + HRESULT D3d12DebugDevice1_GetDebugParameter( + _Inout_ ID3D12DebugDevice1* pDebugDevice, + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ); + + HRESULT D3d12DebugDevice1_ReportLiveDeviceObjects( + _Inout_ ID3D12DebugDevice1* pDebugDevice, + D3D12_RLDO_FLAGS Flags + ); + + HRESULT D3d12DebugDevice1_SetDebugParameter( + _Inout_ ID3D12DebugDevice1* pDebugDevice, + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ); + + D3DCONST D3D12DebugDevice1_Function_Table D3D__D3d12DebugDevice1_Function_Table = + { + D3D__D3d12DebugDevice_Function_Table, + D3d12DebugDevice1_GetDebugParameter, + D3d12DebugDevice1_ReportLiveDeviceObjects, + D3d12DebugDevice1_SetDebugParameter, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DebugDevice1, a9b71770, d099, 4a65, a6, 98, 3d, ee, 10, 02, 0f, 88) : public IGraphicsUnknown +{ +public: + D3DINLINE D3D12DebugDevice1_Function_Table* DebugDevice1Function() + { + return (D3D12DebugDevice1_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT GetDebugParameter( + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ) + { + return DebugDevice1Function()->GetDebugParameter(this, Type, pData, DataSize); + } + + D3DINLINE HRESULT ReportLiveDeviceObjects( + D3D12_RLDO_FLAGS Flags + ) + { + return DebugDevice1Function()->ReportLiveDeviceObjects(this, Flags); + } + + D3DINLINE HRESULT SetDebugParameter( + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ) + { + return DebugDevice1Function()->SetDebugParameter(this, Type, pData, DataSize); + } +}; +// +// ID3D12DebugDevice2 +// + +extern "C" +{ + + struct D3D12DebugDevice2_Function_Table + { + D3D12DebugDevice1_Function_Table ParentFunction; + + HRESULT(D3DAPI* GetDebugParameter)( + _Inout_ ID3D12DebugDevice2* pDebugDevice, + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ); + + HRESULT(D3DAPI* SetDebugParameter)( + _Inout_ ID3D12DebugDevice2* pDebugDevice, + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + HRESULT D3d12DebugDevice2_GetDebugParameter( + _Inout_ ID3D12DebugDevice2* pDebugDevice, + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ); + + HRESULT D3d12DebugDevice2_SetDebugParameter( + _Inout_ ID3D12DebugDevice2* pDebugDevice, + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ); + + D3DCONST D3D12DebugDevice2_Function_Table D3D__D3d12DebugDevice2_Function_Table = + { + D3D__D3d12DebugDevice1_Function_Table, + D3d12DebugDevice2_GetDebugParameter, + D3d12DebugDevice2_SetDebugParameter, + }; + +#endif + +} // extern C + +D3DINTERFACE(ID3D12DebugDevice2, 60eccbc1, 378d, 4df1, 89, 4c, f8, ac, 5c, e4, d7, dd) : public ID3D12DebugDevice +{ +public: + D3DINLINE D3D12DebugDevice2_Function_Table* DebugDevice2Function() + { + return (D3D12DebugDevice2_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT GetDebugParameter( + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + void* pData, + UINT DataSize + ) + { + return DebugDevice2Function()->GetDebugParameter(this, Type, pData, DataSize); + } + + D3DINLINE HRESULT SetDebugParameter( + D3D12_DEBUG_DEVICE_PARAMETER_TYPE Type, + const void* pData, + UINT DataSize + ) + { + return DebugDevice2Function()->SetDebugParameter(this, Type, pData, DataSize); + } +}; + +extern "C" +{ +typedef HRESULT (WINAPI* PFN_D3D12_GET_DEBUG_INTERFACE)( _In_ REFIID, _COM_Outptr_opt_ void** ); +HRESULT WINAPI D3D12GetDebugInterface( _In_ REFIID riid, _COM_Outptr_opt_ void** ppvDebug ); +HRESULT WINAPI D3D12XboxSetProcessDebugFlags(D3D12XBOX_PROCESS_DEBUG_FLAGS Flags); +HRESULT WINAPI D3D12XboxEnableMemoryProfiling(UINT64* pIndex, UINT64 Count, UINT64* pBuffer); +D3D12XBOX_PROCESS_DEBUG_FLAGS WINAPI D3D12XboxGetProcessDebugFlags(); + +} + +// A special error code that can be returned from CreateGraphicsPipelineState or CreateComputePipelineState +// Same as S_OK when returned from CreatePipelineState, but indicates that a runtime compilation occured +#define S_RUNTIME_COMPILATION ((HRESULT)2L) + + +extern "C" +{ + +// -------------------------------------------------------------------------------------------------------------------------------- +// D3D12EnableExperimentalFeatures +// +// Pass in a list of feature GUIDs to be enabled together. +// +// If a particular feature requires some configuration information on enablement, it will have +// a configuration struct that can be passed alongside the GUID. +// +// Some features might use an interface IID as the GUID. For these, once the feature is enabled via +// D3D12EnableExperimentalFeatures, D3D12GetDebugInterface can then be called with the IID to retrieve the interface +// for manipulating the feature. This allows for control that might not cleanly be expressed by just +// the configuration struct that D3D12EnableExperimentalFeatures provides. +// +// If this method is called and a change to existing feature enablement is made, +// all current D3D12 devices are set to DEVICE_REMOVED state, since under the covers there is really only one +// singleton device for a process. Removing the devices when configuration changes prevents +// mismatched expectations of how a device is supposed to work after it has been created from the app's point of view. +// +// The call returns E_NOINTERFACE if an unrecognized feature is passed in or Windows Developer mode is not on. +// The call returns E_INVALIDARG if the configuration of a feature is incorrect, the set of features passed +// in are known to be incompatible with each other, or other errors. +// Returns S_OK otherwise. +// +// -------------------------------------------------------------------------------------------------------------------------------- + +HRESULT D3DAPI D3D12EnableExperimentalFeatures( + UINT NumFeatures, + __in_ecount(NumFeatures) const IID* pIIDs, + __in_ecount_opt(NumFeatures) void* pConfigurationStructs, + __in_ecount_opt(NumFeatures) UINT* pConfigurationStructSizes); + +// -------------------------------------------------------------------------------------------------------------------------------- +// Experimental Feature: D3D12ExperimentalShaderModels +// +// Use with D3D12EnableExperimentalFeatures to enable experimental shader model support, +// meaning shader models that haven't been finalized for use in retail. +// +// Enabling D3D12ExperimentalShaderModels needs no configuration struct, pass NULL in the pConfigurationStructs array. +// +// -------------------------------------------------------------------------------------------------------------------------------- + +static const UUID D3D12ExperimentalShaderModels = /* 76f5573e-f13a-40f5-b297-81ce9e18933f */ +{ + 0x76f5573e, + 0xf13a, + 0x40f5, + { 0xb2, 0x97, 0x81, 0xce, 0x9e, 0x18, 0x93, 0x3f } +}; + +} + + + +extern "C" +{ + +typedef struct D3D12_FEATURE_DATA_DISPLAYABLE +{ + _Out_ BOOL DisplayableTexture; + _Out_ D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER SharedResourceCompatibilityTier; +} D3D12_FEATURE_DATA_DISPLAYABLE; + +typedef +enum D3D12_WAVE_MMA_TIER +{ + D3D12_WAVE_MMA_TIER_NOT_SUPPORTED = 0, + D3D12_WAVE_MMA_TIER_1_0 = 10 +} D3D12_WAVE_MMA_TIER; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS8 +{ + _Out_ BOOL UnalignedBlockTexturesSupported; +} D3D12_FEATURE_DATA_D3D12_OPTIONS8; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS9 +{ + _Out_ BOOL MeshShaderPipelineStatsSupported; + _Out_ BOOL MeshShaderSupportsFullRangeRenderTargetArrayIndex; + _Out_ BOOL AtomicInt64OnTypedResourceSupported; + _Out_ BOOL AtomicInt64OnGroupSharedSupported; + _Out_ BOOL DerivativesInMeshAndAmplificationShadersSupported; + _Out_ D3D12_WAVE_MMA_TIER WaveMMATier; +} D3D12_FEATURE_DATA_D3D12_OPTIONS9; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS10 +{ + _Out_ BOOL VariableRateShadingSumCombinerSupported; + _Out_ BOOL MeshShaderPerPrimitiveShadingRateSupported; +} D3D12_FEATURE_DATA_D3D12_OPTIONS10; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS11 +{ + _Out_ BOOL AtomicInt64OnDescriptorHeapResourceSupported; +} D3D12_FEATURE_DATA_D3D12_OPTIONS11; + +typedef enum D3D12_TRI_STATE +{ + D3D12_TRI_STATE_UNKNOWN = -1, + D3D12_TRI_STATE_FALSE = 0, + D3D12_TRI_STATE_TRUE = 1 +} D3D12_TRI_STATE; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS12 +{ + D3D12_TRI_STATE MSPrimitivesPipelineStatisticIncludesCulledPrimitives; + BOOL EnhancedBarriersSupported; + BOOL RelaxedFormatCastingSupported; +} D3D12_FEATURE_DATA_D3D12_OPTIONS12; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS13 +{ + BOOL UnrestrictedBufferTextureCopyPitchSupported; + BOOL UnrestrictedVertexElementAlignmentSupported; + BOOL InvertedViewportHeightFlipsYSupported; + BOOL InvertedViewportDepthFlipsZSupported; + BOOL TextureCopyBetweenDimensionsSupported; + BOOL AlphaBlendFactorSupported; +} D3D12_FEATURE_DATA_D3D12_OPTIONS13; + +typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS14 +{ + BOOL AdvancedTextureOpsSupported; + BOOL WriteableMSAATexturesSupported; + BOOL IndependentFrontAndBackStencilRefMaskSupported; +} D3D12_FEATURE_DATA_D3D12_OPTIONS14; + +typedef struct D3D12_FEATURE_DATA_QUERY_META_COMMAND +{ + _In_ GUID CommandId; + _In_ UINT NodeMask; + _Field_size_bytes_full_opt_( QueryInputDataSizeInBytes ) const void *pQueryInputData; + _In_ SIZE_T QueryInputDataSizeInBytes; + _Field_size_bytes_full_( QueryOutputDataSizeInBytes ) void *pQueryOutputData; + _In_ SIZE_T QueryOutputDataSizeInBytes; +} D3D12_FEATURE_DATA_QUERY_META_COMMAND; + +typedef struct D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPE_COUNT +{ + UINT NodeIndex; + UINT Count; +} D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPE_COUNT; + +typedef struct D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPES +{ + UINT NodeIndex; + UINT Count; + GUID *pTypes; +} D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPES; + +}; // extern "C" + +#pragma warning( pop ) + +#endif // __d3d12_xs_h__ + diff --git a/docs/gdkx/d3d12shader_xs.h b/docs/gdkx/d3d12shader_xs.h new file mode 100644 index 0000000..b66f0e9 --- /dev/null +++ b/docs/gdkx/d3d12shader_xs.h @@ -0,0 +1,522 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// File: D3D12Shader.h +// Content: D3D12 Shader Types and APIs +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef __D3D12SHADER_H__ +#define __D3D12SHADER_H__ + + +#include "d3d12_xs.h" + +// In some cases (ex. 11on12) d3d12_x.h and d3dcommon.h will both be included, +// which causes a redefinition of the types below which are also found in d3dcommon.h +// Also, for now d3d12_x.h will not have these types defined as they are only needed for +// the d3d compiler, so they are defined here for the time being. +#ifndef __d3dcommon_h__ +typedef +enum D3D_INTERPOLATION_MODE + { + D3D_INTERPOLATION_UNDEFINED = 0, + D3D_INTERPOLATION_CONSTANT = 1, + D3D_INTERPOLATION_LINEAR = 2, + D3D_INTERPOLATION_LINEAR_CENTROID = 3, + D3D_INTERPOLATION_LINEAR_NOPERSPECTIVE = 4, + D3D_INTERPOLATION_LINEAR_NOPERSPECTIVE_CENTROID = 5, + D3D_INTERPOLATION_LINEAR_SAMPLE = 6, + D3D_INTERPOLATION_LINEAR_NOPERSPECTIVE_SAMPLE = 7 + } D3D_INTERPOLATION_MODE; + +typedef +enum _D3D_PARAMETER_FLAGS + { + D3D_PF_NONE = 0, + D3D_PF_IN = 0x1, + D3D_PF_OUT = 0x2, + D3D_PF_FORCE_DWORD = 0x7fffffff + } D3D_PARAMETER_FLAGS; +#endif + +// Define missing 16 and 64 bit reflection types +#if (!NTDDI_WIN10_FE || (WDK_NTDDI_VERSION <= NTDDI_WIN10_FE)) +// These augment D3D_SHADER_VARIABLE_TYPE defined in d3dcommon.h +#ifdef __d3dcommon_h__ +// Apply workaround once +#ifndef D3D_SVT_INT16 + +// Disable warning about value not being valid in enum +#pragma warning( disable : 4063 ) +#define D3D_SVT_INT16 ((D3D_SHADER_VARIABLE_TYPE)58) +#define D3D_SVT_UINT16 ((D3D_SHADER_VARIABLE_TYPE)59) +#define D3D_SVT_FLOAT16 ((D3D_SHADER_VARIABLE_TYPE)60) +#define D3D_SVT_INT64 ((D3D_SHADER_VARIABLE_TYPE)61) +#define D3D_SVT_UINT64 ((D3D_SHADER_VARIABLE_TYPE)62) + +#endif // D3D_SVT_INT16 +#endif // __d3dcommon_h__ +#endif // (!NTDDI_WIN10_FE || (WDK_NTDDI_VERSION <= NTDDI_WIN10_FE)) + +typedef enum D3D12_SHADER_VERSION_TYPE +{ + D3D12_SHVER_PIXEL_SHADER = 0, + D3D12_SHVER_VERTEX_SHADER = 1, + D3D12_SHVER_GEOMETRY_SHADER = 2, + + // D3D11 Shaders + D3D12_SHVER_HULL_SHADER = 3, + D3D12_SHVER_DOMAIN_SHADER = 4, + D3D12_SHVER_COMPUTE_SHADER = 5, + + D3D12_SHVER_RESERVED0 = 0xFFF0, +} D3D12_SHADER_VERSION_TYPE; + +#define D3D12_SHVER_GET_TYPE(_Version) \ + (((_Version) >> 16) & 0xffff) +#define D3D12_SHVER_GET_MAJOR(_Version) \ + (((_Version) >> 4) & 0xf) +#define D3D12_SHVER_GET_MINOR(_Version) \ + (((_Version) >> 0) & 0xf) + +// Slot ID for library function return +#define D3D_RETURN_PARAMETER_INDEX (-1) + +typedef D3D_RESOURCE_RETURN_TYPE D3D12_RESOURCE_RETURN_TYPE; + +typedef D3D_CBUFFER_TYPE D3D12_CBUFFER_TYPE; + + +typedef struct _D3D12_SIGNATURE_PARAMETER_DESC +{ + LPCSTR SemanticName; // Name of the semantic + UINT SemanticIndex; // Index of the semantic + UINT Register; // Number of member variables + D3D_NAME SystemValueType;// A predefined system value, or D3D_NAME_UNDEFINED if not applicable + D3D_REGISTER_COMPONENT_TYPE ComponentType; // Scalar type (e.g. uint, float, etc.) + BYTE Mask; // Mask to indicate which components of the register + // are used (combination of D3D10_COMPONENT_MASK values) + BYTE ReadWriteMask; // Mask to indicate whether a given component is + // never written (if this is an output signature) or + // always read (if this is an input signature). + // (combination of D3D_MASK_* values) + UINT Stream; // Stream index + D3D_MIN_PRECISION MinPrecision; // Minimum desired interpolation precision +} D3D12_SIGNATURE_PARAMETER_DESC; + +typedef struct _D3D12_SHADER_BUFFER_DESC +{ + LPCSTR Name; // Name of the constant buffer + D3D_CBUFFER_TYPE Type; // Indicates type of buffer content + UINT Variables; // Number of member variables + UINT Size; // Size of CB (in bytes) + UINT uFlags; // Buffer description flags +} D3D12_SHADER_BUFFER_DESC; + +typedef struct _D3D12_SHADER_VARIABLE_DESC +{ + LPCSTR Name; // Name of the variable + UINT StartOffset; // Offset in constant buffer's backing store + UINT Size; // Size of variable (in bytes) + UINT uFlags; // Variable flags + LPVOID DefaultValue; // Raw pointer to default value + UINT StartTexture; // First texture index (or -1 if no textures used) + UINT TextureSize; // Number of texture slots possibly used. + UINT StartSampler; // First sampler index (or -1 if no textures used) + UINT SamplerSize; // Number of sampler slots possibly used. +} D3D12_SHADER_VARIABLE_DESC; + +typedef struct _D3D12_SHADER_TYPE_DESC +{ + D3D_SHADER_VARIABLE_CLASS Class; // Variable class (e.g. object, matrix, etc.) + D3D_SHADER_VARIABLE_TYPE Type; // Variable type (e.g. float, sampler, etc.) + UINT Rows; // Number of rows (for matrices, 1 for other numeric, 0 if not applicable) + UINT Columns; // Number of columns (for vectors & matrices, 1 for other numeric, 0 if not applicable) + UINT Elements; // Number of elements (0 if not an array) + UINT Members; // Number of members (0 if not a structure) + UINT Offset; // Offset from the start of structure (0 if not a structure member) + LPCSTR Name; // Name of type, can be NULL +} D3D12_SHADER_TYPE_DESC; + +typedef D3D_TESSELLATOR_DOMAIN D3D12_TESSELLATOR_DOMAIN; + +typedef D3D_TESSELLATOR_PARTITIONING D3D12_TESSELLATOR_PARTITIONING; + +typedef D3D_TESSELLATOR_OUTPUT_PRIMITIVE D3D12_TESSELLATOR_OUTPUT_PRIMITIVE; + +typedef struct _D3D12_SHADER_DESC +{ + UINT Version; // Shader version + LPCSTR Creator; // Creator string + UINT Flags; // Shader compilation/parse flags + + UINT ConstantBuffers; // Number of constant buffers + UINT BoundResources; // Number of bound resources + UINT InputParameters; // Number of parameters in the input signature + UINT OutputParameters; // Number of parameters in the output signature + + UINT InstructionCount; // Number of emitted instructions + UINT TempRegisterCount; // Number of temporary registers used + UINT TempArrayCount; // Number of temporary arrays used + UINT DefCount; // Number of constant defines + UINT DclCount; // Number of declarations (input + output) + UINT TextureNormalInstructions; // Number of non-categorized texture instructions + UINT TextureLoadInstructions; // Number of texture load instructions + UINT TextureCompInstructions; // Number of texture comparison instructions + UINT TextureBiasInstructions; // Number of texture bias instructions + UINT TextureGradientInstructions; // Number of texture gradient instructions + UINT FloatInstructionCount; // Number of floating point arithmetic instructions used + UINT IntInstructionCount; // Number of signed integer arithmetic instructions used + UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used + UINT StaticFlowControlCount; // Number of static flow control instructions used + UINT DynamicFlowControlCount; // Number of dynamic flow control instructions used + UINT MacroInstructionCount; // Number of macro instructions used + UINT ArrayInstructionCount; // Number of array instructions used + UINT CutInstructionCount; // Number of cut instructions used + UINT EmitInstructionCount; // Number of emit instructions used + D3D_PRIMITIVE_TOPOLOGY GSOutputTopology; // Geometry shader output topology + UINT GSMaxOutputVertexCount; // Geometry shader maximum output vertex count + D3D_PRIMITIVE InputPrimitive; // GS/HS input primitive + UINT PatchConstantParameters; // Number of parameters in the patch constant signature + UINT cGSInstanceCount; // Number of Geometry shader instances + UINT cControlPoints; // Number of control points in the HS->DS stage + D3D_TESSELLATOR_OUTPUT_PRIMITIVE HSOutputPrimitive; // Primitive output by the tessellator + D3D_TESSELLATOR_PARTITIONING HSPartitioning; // Partitioning mode of the tessellator + D3D_TESSELLATOR_DOMAIN TessellatorDomain; // Domain of the tessellator (quad, tri, isoline) + // instruction counts + UINT cBarrierInstructions; // Number of barrier instructions in a compute shader + UINT cInterlockedInstructions; // Number of interlocked instructions + UINT cTextureStoreInstructions; // Number of texture writes +} D3D12_SHADER_DESC; + +typedef struct _D3D12_SHADER_INPUT_BIND_DESC +{ + LPCSTR Name; // Name of the resource + D3D_SHADER_INPUT_TYPE Type; // Type of resource (e.g. texture, cbuffer, etc.) + UINT BindPoint; // Starting bind point + UINT BindCount; // Number of contiguous bind points (for arrays) + + UINT uFlags; // Input binding flags + D3D_RESOURCE_RETURN_TYPE ReturnType; // Return type (if texture) + D3D_SRV_DIMENSION Dimension; // Dimension (if texture) + UINT NumSamples; // Number of samples (0 if not MS texture) + UINT Space; // Register space + UINT uID; // Range ID in the bytecode +} D3D12_SHADER_INPUT_BIND_DESC; + +#define D3D_SHADER_REQUIRES_DOUBLES 0x00000001 +#define D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL 0x00000002 +#define D3D_SHADER_REQUIRES_UAVS_AT_EVERY_STAGE 0x00000004 +#define D3D_SHADER_REQUIRES_64_UAVS 0x00000008 +#define D3D_SHADER_REQUIRES_MINIMUM_PRECISION 0x00000010 +#define D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS 0x00000020 +#define D3D_SHADER_REQUIRES_11_1_SHADER_EXTENSIONS 0x00000040 +#define D3D_SHADER_REQUIRES_LEVEL_9_COMPARISON_FILTERING 0x00000080 +#define D3D_SHADER_REQUIRES_TILED_RESOURCES 0x00000100 +#define D3D_SHADER_REQUIRES_STENCIL_REF 0x00000200 +#define D3D_SHADER_REQUIRES_INNER_COVERAGE 0x00000400 +#define D3D_SHADER_REQUIRES_TYPED_UAV_LOAD_ADDITIONAL_FORMATS 0x00000800 +#define D3D_SHADER_REQUIRES_ROVS 0x00001000 +#define D3D_SHADER_REQUIRES_VIEWPORT_AND_RT_ARRAY_INDEX_FROM_ANY_SHADER_FEEDING_RASTERIZER 0x00002000 +#define D3D_SHADER_REQUIRES_WAVE_OPS 0x00004000 +#define D3D_SHADER_REQUIRES_INT64_OPS 0x00008000 +#define D3D_SHADER_REQUIRES_VIEW_ID 0x00010000 +#define D3D_SHADER_REQUIRES_BARYCENTRICS 0x00020000 +#define D3D_SHADER_REQUIRES_NATIVE_16BIT_OPS 0x00040000 +#define D3D_SHADER_REQUIRES_SHADING_RATE 0x00080000 +#define D3D_SHADER_REQUIRES_RAYTRACING_TIER_1_1 0x00100000 +#define D3D_SHADER_REQUIRES_SAMPLER_FEEDBACK 0x00200000 +#define D3D_SHADER_REQUIRES_ATOMIC_INT64_ON_TYPED_RESOURCE 0x00400000 +#define D3D_SHADER_REQUIRES_ATOMIC_INT64_ON_GROUP_SHARED 0x00800000 +#define D3D_SHADER_REQUIRES_DERIVATIVES_IN_MESH_AND_AMPLIFICATION_SHADERS 0x01000000 +#define D3D_SHADER_REQUIRES_RESOURCE_DESCRIPTOR_HEAP_INDEXING 0x02000000 +#define D3D_SHADER_REQUIRES_SAMPLER_DESCRIPTOR_HEAP_INDEXING 0x04000000 +#define D3D_SHADER_REQUIRES_WAVE_MMA 0x08000000 +#define D3D_SHADER_REQUIRES_ATOMIC_INT64_ON_DESCRIPTOR_HEAP_RESOURCE 0x10000000 + + +typedef struct _D3D12_LIBRARY_DESC +{ + LPCSTR Creator; // The name of the originator of the library. + UINT Flags; // Compilation flags. + UINT FunctionCount; // Number of functions exported from the library. +} D3D12_LIBRARY_DESC; + +typedef struct _D3D12_FUNCTION_DESC +{ + UINT Version; // Shader version + LPCSTR Creator; // Creator string + UINT Flags; // Shader compilation/parse flags + + UINT ConstantBuffers; // Number of constant buffers + UINT BoundResources; // Number of bound resources + + UINT InstructionCount; // Number of emitted instructions + UINT TempRegisterCount; // Number of temporary registers used + UINT TempArrayCount; // Number of temporary arrays used + UINT DefCount; // Number of constant defines + UINT DclCount; // Number of declarations (input + output) + UINT TextureNormalInstructions; // Number of non-categorized texture instructions + UINT TextureLoadInstructions; // Number of texture load instructions + UINT TextureCompInstructions; // Number of texture comparison instructions + UINT TextureBiasInstructions; // Number of texture bias instructions + UINT TextureGradientInstructions; // Number of texture gradient instructions + UINT FloatInstructionCount; // Number of floating point arithmetic instructions used + UINT IntInstructionCount; // Number of signed integer arithmetic instructions used + UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used + UINT StaticFlowControlCount; // Number of static flow control instructions used + UINT DynamicFlowControlCount; // Number of dynamic flow control instructions used + UINT MacroInstructionCount; // Number of macro instructions used + UINT ArrayInstructionCount; // Number of array instructions used + UINT MovInstructionCount; // Number of mov instructions used + UINT MovcInstructionCount; // Number of movc instructions used + UINT ConversionInstructionCount; // Number of type conversion instructions used + UINT BitwiseInstructionCount; // Number of bitwise arithmetic instructions used + D3D_FEATURE_LEVEL MinFeatureLevel; // Min target of the function byte code + UINT64 RequiredFeatureFlags; // Required feature flags + + LPCSTR Name; // Function name + INT FunctionParameterCount; // Number of logical parameters in the function signature (not including return) + BOOL HasReturn; // TRUE, if function returns a value, false - it is a subroutine + BOOL Has10Level9VertexShader; // TRUE, if there is a 10L9 VS blob + BOOL Has10Level9PixelShader; // TRUE, if there is a 10L9 PS blob +} D3D12_FUNCTION_DESC; + +typedef struct _D3D12_PARAMETER_DESC +{ + LPCSTR Name; // Parameter name. + LPCSTR SemanticName; // Parameter semantic name (+index). + D3D_SHADER_VARIABLE_TYPE Type; // Element type. + D3D_SHADER_VARIABLE_CLASS Class; // Scalar/Vector/Matrix. + UINT Rows; // Rows are for matrix parameters. + UINT Columns; // Components or Columns in matrix. + D3D_INTERPOLATION_MODE InterpolationMode; // Interpolation mode. + D3D_PARAMETER_FLAGS Flags; // Parameter modifiers. + + UINT FirstInRegister; // The first input register for this parameter. + UINT FirstInComponent; // The first input register component for this parameter. + UINT FirstOutRegister; // The first output register for this parameter. + UINT FirstOutComponent; // The first output register component for this parameter. +} D3D12_PARAMETER_DESC; + + +////////////////////////////////////////////////////////////////////////////// +// Interfaces //////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +typedef interface ID3D12ShaderReflectionType ID3D12ShaderReflectionType; +typedef interface ID3D12ShaderReflectionType *LPD3D12SHADERREFLECTIONTYPE; + +typedef interface ID3D12ShaderReflectionVariable ID3D12ShaderReflectionVariable; +typedef interface ID3D12ShaderReflectionVariable *LPD3D12SHADERREFLECTIONVARIABLE; + +typedef interface ID3D12ShaderReflectionConstantBuffer ID3D12ShaderReflectionConstantBuffer; +typedef interface ID3D12ShaderReflectionConstantBuffer *LPD3D12SHADERREFLECTIONCONSTANTBUFFER; + +typedef interface ID3D12ShaderReflection ID3D12ShaderReflection; +typedef interface ID3D12ShaderReflection *LPD3D12SHADERREFLECTION; + +typedef interface ID3D12LibraryReflection ID3D12LibraryReflection; +typedef interface ID3D12LibraryReflection *LPD3D12LIBRARYREFLECTION; + +typedef interface ID3D12FunctionReflection ID3D12FunctionReflection; +typedef interface ID3D12FunctionReflection *LPD3D12FUNCTIONREFLECTION; + +typedef interface ID3D12FunctionParameterReflection ID3D12FunctionParameterReflection; +typedef interface ID3D12FunctionParameterReflection *LPD3D12FUNCTIONPARAMETERREFLECTION; + + +// {E913C351-783D-48CA-A1D1-4F306284AD56} +interface DECLSPEC_UUID("E913C351-783D-48CA-A1D1-4F306284AD56") ID3D12ShaderReflectionType; +DEFINE_GUID(IID_ID3D12ShaderReflectionType, +0xe913c351, 0x783d, 0x48ca, 0xa1, 0xd1, 0x4f, 0x30, 0x62, 0x84, 0xad, 0x56); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflectionType + +DECLARE_INTERFACE(ID3D12ShaderReflectionType) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_SHADER_TYPE_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByIndex)(THIS_ _In_ UINT Index) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByName)(THIS_ _In_ LPCSTR Name) PURE; + STDMETHOD_(LPCSTR, GetMemberTypeName)(THIS_ _In_ UINT Index) PURE; + + STDMETHOD(IsEqual)(THIS_ _In_ ID3D12ShaderReflectionType* pType) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetSubType)(THIS) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetBaseClass)(THIS) PURE; + STDMETHOD_(UINT, GetNumInterfaces)(THIS) PURE; + STDMETHOD_(ID3D12ShaderReflectionType*, GetInterfaceByIndex)(THIS_ _In_ UINT uIndex) PURE; + STDMETHOD(IsOfType)(THIS_ _In_ ID3D12ShaderReflectionType* pType) PURE; + STDMETHOD(ImplementsInterface)(THIS_ _In_ ID3D12ShaderReflectionType* pBase) PURE; +}; + +// {8337A8A6-A216-444A-B2F4-314733A73AEA} +interface DECLSPEC_UUID("8337A8A6-A216-444A-B2F4-314733A73AEA") ID3D12ShaderReflectionVariable; +DEFINE_GUID(IID_ID3D12ShaderReflectionVariable, +0x8337a8a6, 0xa216, 0x444a, 0xb2, 0xf4, 0x31, 0x47, 0x33, 0xa7, 0x3a, 0xea); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflectionVariable + +DECLARE_INTERFACE(ID3D12ShaderReflectionVariable) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_SHADER_VARIABLE_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionType*, GetType)(THIS) PURE; + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetBuffer)(THIS) PURE; + + STDMETHOD_(UINT, GetInterfaceSlot)(THIS_ _In_ UINT uArrayIndex) PURE; +}; + +// {C59598B4-48B3-4869-B9B1-B1618B14A8B7} +interface DECLSPEC_UUID("C59598B4-48B3-4869-B9B1-B1618B14A8B7") ID3D12ShaderReflectionConstantBuffer; +DEFINE_GUID(IID_ID3D12ShaderReflectionConstantBuffer, +0xc59598b4, 0x48b3, 0x4869, 0xb9, 0xb1, 0xb1, 0x61, 0x8b, 0x14, 0xa8, 0xb7); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflectionConstantBuffer + +DECLARE_INTERFACE(ID3D12ShaderReflectionConstantBuffer) +{ + STDMETHOD(GetDesc)(THIS_ D3D12_SHADER_BUFFER_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByIndex)(THIS_ _In_ UINT Index) PURE; + STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(THIS_ _In_ LPCSTR Name) PURE; +}; + +// The ID3D12ShaderReflection IID may change from SDK version to SDK version +// if the reflection API changes. This prevents new code with the new API +// from working with an old binary. Recompiling with the new header +// will pick up the new IID. + +// {5A58797D-A72C-478D-8BA2-EFC6B0EFE88E} +interface DECLSPEC_UUID("5A58797D-A72C-478D-8BA2-EFC6B0EFE88E") ID3D12ShaderReflection; +DEFINE_GUID(IID_ID3D12ShaderReflection, +0x5a58797d, 0xa72c, 0x478d, 0x8b, 0xa2, 0xef, 0xc6, 0xb0, 0xef, 0xe8, 0x8e); + +#undef INTERFACE +#define INTERFACE ID3D12ShaderReflection + +DECLARE_INTERFACE_(ID3D12ShaderReflection, IUnknown) +{ + STDMETHOD(QueryInterface)(THIS_ _In_ REFIID iid, + _Out_ LPVOID *ppv) PURE; + STDMETHOD_(ULONG, AddRef)(THIS) PURE; + STDMETHOD_(ULONG, Release)(THIS) PURE; + + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_SHADER_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetConstantBufferByIndex)(THIS_ _In_ UINT Index) PURE; + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex, + _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc) PURE; + + STDMETHOD(GetInputParameterDesc)(THIS_ _In_ UINT ParameterIndex, + _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetOutputParameterDesc)(THIS_ _In_ UINT ParameterIndex, + _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + STDMETHOD(GetPatchConstantParameterDesc)(THIS_ _In_ UINT ParameterIndex, + _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name, + _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc) PURE; + + STDMETHOD_(UINT, GetMovInstructionCount)(THIS) PURE; + STDMETHOD_(UINT, GetMovcInstructionCount)(THIS) PURE; + STDMETHOD_(UINT, GetConversionInstructionCount)(THIS) PURE; + STDMETHOD_(UINT, GetBitwiseInstructionCount)(THIS) PURE; + + STDMETHOD_(D3D_PRIMITIVE, GetGSInputPrimitive)(THIS) PURE; + STDMETHOD_(BOOL, IsSampleFrequencyShader)(THIS) PURE; + + STDMETHOD_(UINT, GetNumInterfaceSlots)(THIS) PURE; + STDMETHOD(GetMinFeatureLevel)(THIS_ _Out_ enum D3D_FEATURE_LEVEL* pLevel) PURE; + + STDMETHOD_(UINT, GetThreadGroupSize)(THIS_ + _Out_opt_ UINT* pSizeX, + _Out_opt_ UINT* pSizeY, + _Out_opt_ UINT* pSizeZ) PURE; + + STDMETHOD_(UINT64, GetRequiresFlags)(THIS) PURE; +}; + +// {8E349D19-54DB-4A56-9DC9-119D87BDB804} +interface DECLSPEC_UUID("8E349D19-54DB-4A56-9DC9-119D87BDB804") ID3D12LibraryReflection; +DEFINE_GUID(IID_ID3D12LibraryReflection, +0x8e349d19, 0x54db, 0x4a56, 0x9d, 0xc9, 0x11, 0x9d, 0x87, 0xbd, 0xb8, 0x4); + +#undef INTERFACE +#define INTERFACE ID3D12LibraryReflection + +DECLARE_INTERFACE_(ID3D12LibraryReflection, IUnknown) +{ + STDMETHOD(QueryInterface)(THIS_ _In_ REFIID iid, _Out_ LPVOID * ppv) PURE; + STDMETHOD_(ULONG, AddRef)(THIS) PURE; + STDMETHOD_(ULONG, Release)(THIS) PURE; + + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_LIBRARY_DESC * pDesc) PURE; + + STDMETHOD_(ID3D12FunctionReflection *, GetFunctionByIndex)(THIS_ _In_ INT FunctionIndex) PURE; +}; + +// {1108795C-2772-4BA9-B2A8-D464DC7E2799} +interface DECLSPEC_UUID("1108795C-2772-4BA9-B2A8-D464DC7E2799") ID3D12FunctionReflection; +DEFINE_GUID(IID_ID3D12FunctionReflection, +0x1108795c, 0x2772, 0x4ba9, 0xb2, 0xa8, 0xd4, 0x64, 0xdc, 0x7e, 0x27, 0x99); + +#undef INTERFACE +#define INTERFACE ID3D12FunctionReflection + +DECLARE_INTERFACE(ID3D12FunctionReflection) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_FUNCTION_DESC * pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByIndex)(THIS_ _In_ UINT BufferIndex) PURE; + STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex, + _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) PURE; + + STDMETHOD_(ID3D12ShaderReflectionVariable *, GetVariableByName)(THIS_ _In_ LPCSTR Name) PURE; + + STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name, + _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) PURE; + + // Use D3D_RETURN_PARAMETER_INDEX to get description of the return value. + STDMETHOD_(ID3D12FunctionParameterReflection *, GetFunctionParameter)(THIS_ _In_ INT ParameterIndex) PURE; +}; + +// {EC25F42D-7006-4F2B-B33E-02CC3375733F} +interface DECLSPEC_UUID("EC25F42D-7006-4F2B-B33E-02CC3375733F") ID3D12FunctionParameterReflection; +DEFINE_GUID(IID_ID3D12FunctionParameterReflection, +0xec25f42d, 0x7006, 0x4f2b, 0xb3, 0x3e, 0x2, 0xcc, 0x33, 0x75, 0x73, 0x3f); + +#undef INTERFACE +#define INTERFACE ID3D12FunctionParameterReflection + +DECLARE_INTERFACE(ID3D12FunctionParameterReflection) +{ + STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_PARAMETER_DESC * pDesc) PURE; +}; + + +////////////////////////////////////////////////////////////////////////////// +// APIs ////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + +#ifdef __cplusplus +} +#endif //__cplusplus + +#endif //__D3D12SHADER_H__ + diff --git a/docs/gdkx/d3d12video_xs.h b/docs/gdkx/d3d12video_xs.h new file mode 100644 index 0000000..63e5765 --- /dev/null +++ b/docs/gdkx/d3d12video_xs.h @@ -0,0 +1,1671 @@ +//------------------------------------------------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// Xbox Series X|S Direct3D 12.XS constants, structures, and interfaces. +// + +#define __XBOX_D3D12_VIDEO_X__ + + +#include "d3d12_xs.h" + +#ifndef __d3d12_video_x_h__ +#define __d3d12_video_x_h__ + +#pragma once + +#pragma warning( push ) + +// Disable unreferenced parameter, nameless struct/union, zero-sized array, structure padded +// due to __declspec(align()), conditional expression is constant, unreachable code, 'symbol' +// is not defined as a preprocessor macro, replacing with '0' for 'directives', implicit +// padding + +#pragma warning( disable : 4100 4201 4200 4324 4127 4702 4668 4820 ) + + +extern "C" +{ + +// +// Forward Declarations +// + +// 12.0 + +struct ID3D12VideoDevice; +struct ID3D12VideoDecodeCommandList; +struct ID3D12VideoProcessCommandList; +struct ID3D12VideoDecoder; +struct ID3D12VideoDecoderHeap; +struct ID3D12VideoProcessor; +struct ID3D12VideoProcessStream; +struct D3D12_VIDEO_PROCESS_OUTPUT_STREAM_ARGUMENTS; +struct D3D12_VIDEO_PROCESS_INPUT_STREAM_ARGUMENTS; + +} + + +extern "C" +{ + typedef + enum D3D12_VIDEO_FRAME_FORMAT + { + D3D12_VIDEO_FRAME_FORMAT_PROGRESSIVE = 0, + D3D12_VIDEO_FRAME_FORMAT_INTERLACED_TOP_FIELD_FIRST = 1, + D3D12_VIDEO_FRAME_FORMAT_INTERLACED_BOTTOM_FIELD_FIRST = 2, + } D3D12_VIDEO_FRAME_FORMAT; + + typedef + enum D3D12_VIDEO_FRAME_STEREO_FORMAT + { + D3D12_VIDEO_FRAME_STEREO_FORMAT_NONE = 0, + D3D12_VIDEO_FRAME_STEREO_FORMAT_MONO = 1, + D3D12_VIDEO_FRAME_STEREO_FORMAT_HORIZONTAL = 2, + D3D12_VIDEO_FRAME_STEREO_FORMAT_VERTICAL = 3, + D3D12_VIDEO_FRAME_STEREO_FORMAT_SEPARATE = 4, + } D3D12_VIDEO_FRAME_STEREO_FORMAT; + + typedef struct D3D12_VIDEO_FORMAT + { + DXGI_FORMAT Format; + DXGI_COLOR_SPACE_TYPE ColorSpace; + } D3D12_VIDEO_FORMAT; + + typedef struct D3D12_VIDEO_SAMPLE + { + UINT Width; + UINT Height; + D3D12_VIDEO_FORMAT Format; + } D3D12_VIDEO_SAMPLE; + + typedef + enum D3D12_VIDEO_USAGE + { + D3D12_VIDEO_USAGE_NORMAL = 0, + D3D12_VIDEO_USAGE_POWER = 1, + D3D12_VIDEO_USAGE_QUALITY = 2, + } D3D12_VIDEO_USAGE; + + typedef + enum D3D12_VIDEO_FRAME_CODED_INTERLACE_TYPE + { + D3D12_VIDEO_FRAME_CODED_INTERLACE_TYPE_NONE = 0, + D3D12_VIDEO_FRAME_CODED_INTERLACE_TYPE_FIELD_BASED = 1, + } D3D12_VIDEO_FRAME_CODED_INTERLACE_TYPE; + + typedef + enum D3D12_FEATURE_VIDEO + { + D3D12_FEATURE_VIDEO_DECODE_SUPPORT = 0, + D3D12_FEATURE_VIDEO_DECODE_PROFILES = 1, + D3D12_FEATURE_VIDEO_DECODE_FORMATS = 2, + D3D12_FEATURE_VIDEO_DECODE_CONVERSION_SUPPORT = 3, + D3D12_FEATURE_VIDEO_PROCESS_SUPPORT = 5, + D3D12_FEATURE_VIDEO_PROCESS_MAX_INPUT_STREAMS = 6, + D3D12_FEATURE_VIDEO_PROCESS_REFERENCE_INFO = 7, + D3D12_FEATURE_VIDEO_DECODER_HEAP_SIZE = 8, + D3D12_FEATURE_VIDEO_PROCESSOR_SIZE = 9, + D3D12_FEATURE_VIDEO_DECODE_PROFILE_COUNT = 10, + D3D12_FEATURE_VIDEO_DECODE_FORMAT_COUNT = 11, + D3D12_FEATURE_VIDEO_ARCHITECTURE = 17, + D3D12_FEATURE_VIDEO_DECODE_HISTOGRAM = 18, + } D3D12_FEATURE_VIDEO; + + + typedef enum D3D12_BITSTREAM_ENCRYPTION_TYPE + { + D3D12_BITSTREAM_ENCRYPTION_TYPE_NONE = 0, + } D3D12_BITSTREAM_ENCRYPTION_TYPE; + + typedef struct D3D12_VIDEO_DECODE_CONFIGURATION + { + GUID DecodeProfile; + D3D12_BITSTREAM_ENCRYPTION_TYPE BitstreamEncryption; + D3D12_VIDEO_FRAME_CODED_INTERLACE_TYPE InterlaceType; + } D3D12_VIDEO_DECODE_CONFIGURATION; + + typedef struct D3D12_VIDEO_DECODER_DESC + { + UINT NodeMask; + D3D12_VIDEO_DECODE_CONFIGURATION Configuration; + } D3D12_VIDEO_DECODER_DESC; + + typedef struct D3D12_VIDEO_DECODER_HEAP_DESC + { + UINT NodeMask; + D3D12_VIDEO_DECODE_CONFIGURATION Configuration; + UINT DecodeWidth; + UINT DecodeHeight; + DXGI_FORMAT Format; + DXGI_RATIONAL FrameRate; + UINT BitRate; + UINT MaxDecodePictureBufferCount; + } D3D12_VIDEO_DECODER_HEAP_DESC; + + + typedef struct D3D12_VIDEO_SIZE_RANGE + { + UINT MaxWidth; + UINT MaxHeight; + UINT MinWidth; + UINT MinHeight; + } D3D12_VIDEO_SIZE_RANGE; + + typedef struct D3D12_VIDEO_PROCESSOR_DESC + { + UINT NodeMask; + D3D12_VIDEO_USAGE Usage; + } D3D12_VIDEO_PROCESSOR_DESC; + + typedef + enum D3D12_VIDEO_SCALE_SUPPORT_FLAGS + { + D3D12_VIDEO_SCALE_SUPPORT_FLAG_NONE = 0, + D3D12_VIDEO_SCALE_SUPPORT_FLAG_POW2_ONLY = 0x1, + D3D12_VIDEO_SCALE_SUPPORT_FLAG_EVEN_DIMENSIONS_ONLY = 0x2, + } D3D12_VIDEO_SCALE_SUPPORT_FLAGS; + + typedef struct D3D12_VIDEO_SCALE_SUPPORT + { + D3D12_VIDEO_SIZE_RANGE OutputSizeRange; + D3D12_VIDEO_SCALE_SUPPORT_FLAGS Flags; + } D3D12_VIDEO_SCALE_SUPPORT; + +} + +extern "C" +{ + + // + // ID3D12VideoDecodeHeap + // + + struct D3D12VideoDecoderHeap_Function_Table + { + D3D12Pageable_Function_Table ObjectFunction; + + D3D12_VIDEO_DECODER_HEAP_DESC(D3DAPI *GetDesc)(ID3D12VideoDecoderHeap * pThis); + + }; + + +#if DECLARE_UMD_EXPORTS_D3D12X + + D3D12_VIDEO_DECODER_HEAP_DESC D3DAPI D3D12VideoDecoderHeap_GetDesc(ID3D12VideoDecoderHeap * pThis); + ULONG D3DAPI D3d12VideoDecoderHeap_Release(_Inout_ IGraphicsUnknown* pUnknown); + + D3DCONST D3D12VideoDecoderHeap_Function_Table D3D__D3D12VideoDecoderHeap_Function_Table = + { + { + { + { + { + D3d12Object_QueryInterface, + D3d12DeviceChild_AddRef, + D3d12VideoDecoderHeap_Release, + }, + D3d12Object_GetPrivateData, + D3d12Object_SetPrivateData, + D3d12Object_SetPrivateDataInterface, + D3d12Object_SetName, + }, + + D3d12DeviceChild_GetDevice, + }, + }, + D3D12VideoDecoderHeap_GetDesc, + }; +#endif + + // external c +}; + + +D3DINTERFACE(ID3D12VideoDecoderHeap, 0946b7c9, ebf6, 4047, bb, 73, 86, 83, e2, 7d, bb, 1f) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12VideoDecoderHeap_Function_Table* DecoderHeapFunction() + { + return (D3D12VideoDecoderHeap_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_VIDEO_DECODER_HEAP_DESC D3DAPI GetDesc() + { + return DecoderHeapFunction()->GetDesc(this); + } +}; + + + +extern "C" + +{ + typedef + enum D3D12_VIDEO_FIELD_TYPE + { + D3D12_VIDEO_FIELD_TYPE_PROGRESSIVE = 0, + D3D12_VIDEO_FIELD_TYPE_INTERLACED_TOP_FIELD_FIRST = 1, + D3D12_VIDEO_FIELD_TYPE_INTERLACED_BOTTOM_FIELD_FIRST = 2, + D3D12_VIDEO_FIELD_TYPE_MAX_VALID = 3 + } D3D12_VIDEO_FIELD_TYPE; + + + typedef + enum D3D12_VIDEO_PROCESS_FEATURE_FLAGS + { + D3D12_VIDEO_PROCESS_FEATURE_FLAG_NONE = 0, + D3D12_VIDEO_PROCESS_FEATURE_FLAG_ALPHA_FILL = 0x1, + D3D12_VIDEO_PROCESS_FEATURE_FLAG_LUMA_KEY = 0x2, + D3D12_VIDEO_PROCESS_FEATURE_FLAG_STEREO = 0x4, + D3D12_VIDEO_PROCESS_FEATURE_FLAG_ROTATION = 0x8, + D3D12_VIDEO_PROCESS_FEATURE_FLAG_FLIP = 0x10, + D3D12_VIDEO_PROCESS_FEATURE_FLAG_ALPHA_BLENDING = 0x20, + D3D12_VIDEO_PROCESS_FEATURE_FLAG_PIXEL_ASPECT_RATIO = 0x40, + D3D12_VIDEO_PROCESS_FEATURE_FLAG_MASK = 0x7f + } D3D12_VIDEO_PROCESS_FEATURE_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_VIDEO_PROCESS_FEATURE_FLAGS); + typedef + enum D3D12_VIDEO_PROCESS_FILTER + { + D3D12_VIDEO_PROCESS_FILTER_BRIGHTNESS = 0, + D3D12_VIDEO_PROCESS_FILTER_CONTRAST = 1, + D3D12_VIDEO_PROCESS_FILTER_HUE = 2, + D3D12_VIDEO_PROCESS_FILTER_SATURATION = 3, + D3D12_VIDEO_PROCESS_FILTER_NOISE_REDUCTION = 4, + D3D12_VIDEO_PROCESS_FILTER_EDGE_ENHANCEMENT = 5, + D3D12_VIDEO_PROCESS_FILTER_ANAMORPHIC_SCALING = 6, + D3D12_VIDEO_PROCESS_FILTER_STEREO_ADJUSTMENT = 7 + } D3D12_VIDEO_PROCESS_FILTER; + + typedef + enum D3D12_VIDEO_PROCESS_FILTER_FLAGS + { + D3D12_VIDEO_PROCESS_FILTER_FLAG_NONE = 0, + D3D12_VIDEO_PROCESS_FILTER_FLAG_BRIGHTNESS = (1 << D3D12_VIDEO_PROCESS_FILTER_BRIGHTNESS), + D3D12_VIDEO_PROCESS_FILTER_FLAG_CONTRAST = (1 << D3D12_VIDEO_PROCESS_FILTER_CONTRAST), + D3D12_VIDEO_PROCESS_FILTER_FLAG_HUE = (1 << D3D12_VIDEO_PROCESS_FILTER_HUE), + D3D12_VIDEO_PROCESS_FILTER_FLAG_SATURATION = (1 << D3D12_VIDEO_PROCESS_FILTER_SATURATION), + D3D12_VIDEO_PROCESS_FILTER_FLAG_NOISE_REDUCTION = (1 << D3D12_VIDEO_PROCESS_FILTER_NOISE_REDUCTION), + D3D12_VIDEO_PROCESS_FILTER_FLAG_EDGE_ENHANCEMENT = (1 << D3D12_VIDEO_PROCESS_FILTER_EDGE_ENHANCEMENT), + D3D12_VIDEO_PROCESS_FILTER_FLAG_ANAMORPHIC_SCALING = (1 << D3D12_VIDEO_PROCESS_FILTER_ANAMORPHIC_SCALING), + D3D12_VIDEO_PROCESS_FILTER_FLAG_STEREO_ADJUSTMENT = (1 << D3D12_VIDEO_PROCESS_FILTER_STEREO_ADJUSTMENT), + D3D12_VIDEO_PROCESS_FILTER_FLAG_MASK = 0xff + } D3D12_VIDEO_PROCESS_FILTER_FLAGS; + DEFINE_ENUM_FLAG_OPERATORS(D3D12_VIDEO_PROCESS_FILTER_FLAGS); + +#define D3D12_VIDEO_PROCESS_MAX_FILTERS ( 32 ) + + typedef enum D3D12_VIDEO_PROCESS_DEINTERLACE_FLAGS + { + D3D12_VIDEO_PROCESS_DEINTERLACE_FLAG_NONE = 0x0, + D3D12_VIDEO_PROCESS_DEINTERLACE_FLAG_BOB = 0x1, + D3D12_VIDEO_PROCESS_DEINTERLACE_FLAG_CUSTOM = 0x80000000, + + } D3D12_VIDEO_PROCESS_DEINTERLACE_FLAGS; + DEFINE_ENUM_FLAG_OPERATORS(D3D12_VIDEO_PROCESS_DEINTERLACE_FLAGS); + + typedef struct D3D12_VIDEO_PROCESS_ALPHA_BLENDING + { + BOOL Enable; + FLOAT Alpha; + } D3D12_VIDEO_PROCESS_ALPHA_BLENDING; + + typedef struct D3D12_VIDEO_PROCESS_LUMA_KEY + { + BOOL Enable; + FLOAT Lower; + FLOAT Upper; + } D3D12_VIDEO_PROCESS_LUMA_KEY; + + typedef struct D3D12_VIDEO_PROCESS_INPUT_STREAM_DESC + { + DXGI_FORMAT Format; + DXGI_COLOR_SPACE_TYPE ColorSpace; + DXGI_RATIONAL SourceAspectRatio; + DXGI_RATIONAL DestinationAspectRatio; + DXGI_RATIONAL FrameRate; + D3D12_VIDEO_SIZE_RANGE SourceSizeRange; + D3D12_VIDEO_SIZE_RANGE DestinationSizeRange; + BOOL EnableOrientation; + D3D12_VIDEO_PROCESS_FILTER_FLAGS FilterFlags; + D3D12_VIDEO_FRAME_STEREO_FORMAT StereoFormat; + D3D12_VIDEO_FIELD_TYPE FieldType; + D3D12_VIDEO_PROCESS_DEINTERLACE_FLAGS DeinterlaceMode; + BOOL EnableAlphaBlending; + D3D12_VIDEO_PROCESS_LUMA_KEY LumaKey; + UINT NumPastFrames; + UINT NumFutureFrames; + BOOL EnableAutoProcessing; + } D3D12_VIDEO_PROCESS_INPUT_STREAM_DESC; + + typedef enum D3D12_VIDEO_PROCESS_ALPHA_FILL_MODE + { + D3D12_VIDEO_PROCESS_ALPHA_FILL_MODE_OPAQUE = 0, + D3D12_VIDEO_PROCESS_ALPHA_FILL_MODE_BACKGROUND = 1, + D3D12_VIDEO_PROCESS_ALPHA_FILL_MODE_DESTINATION = 2, + D3D12_VIDEO_PROCESS_ALPHA_FILL_MODE_SOURCE_STREAM = 3, + } D3D12_VIDEO_PROCESS_ALPHA_FILL_MODE; + + typedef struct D3D12_VIDEO_PROCESS_OUTPUT_STREAM_DESC + { + DXGI_FORMAT Format; + DXGI_COLOR_SPACE_TYPE ColorSpace; + D3D12_VIDEO_PROCESS_ALPHA_FILL_MODE AlphaFillMode; + UINT AlphaFillModeSourceStreamIndex; + FLOAT BackgroundColor[4]; + DXGI_RATIONAL FrameRate; + BOOL EnableStereo; + } D3D12_VIDEO_PROCESS_OUTPUT_STREAM_DESC; + + typedef + enum D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAGS + { + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_NONE = 0, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_DENOISE = 0x1, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_DERINGING = 0x2, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_EDGE_ENHANCEMENT = 0x4, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_COLOR_CORRECTION = 0x8, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_FLESH_TONE_MAPPING = 0x10, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_IMAGE_STABILIZATION = 0x20, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_SUPER_RESOLUTION = 0x40, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_ANAMORPHIC_SCALING = 0x80, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_CUSTOM = 0x100, + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAG_MASK = 0x1ff + } D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAGS); + + typedef + enum D3D12_VIDEO_PROCESS_ORIENTATION + { + D3D12_VIDEO_PROCESS_ORIENTATION_DEFAULT = 0, + D3D12_VIDEO_PROCESS_ORIENTATION_FLIP_HORIZONTAL = 1, + D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_90 = 2, + D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_90_FLIP_HORIZONTAL = 3, + D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_180 = 4, + D3D12_VIDEO_PROCESS_ORIENTATION_FLIP_VERTICAL = 5, + D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_270 = 6, + D3D12_VIDEO_PROCESS_ORIENTATION_CLOCKWISE_270_FLIP_HORIZONTAL = 7, + D3D12_VIDEO_PROCESS_ORIENTATION_MAX_VALID = 8 + } D3D12_VIDEO_PROCESS_ORIENTATION; + + + typedef + enum D3D12_VIDEO_PROCESS_INPUT_STREAM_FLAGS + { + D3D12_VIDEO_PROCESS_INPUT_STREAM_FLAG_NONE = 0, + D3D12_VIDEO_PROCESS_INPUT_STREAM_FLAG_FRAME_DISCONTINUITY = 0x1, + D3D12_VIDEO_PROCESS_INPUT_STREAM_FLAG_FRAME_REPEAT = 0x2, + D3D12_VIDEO_PROCESS_INPUT_STREAM_FLAG_MAX = 0x3 + } D3D12_VIDEO_PROCESS_INPUT_STREAM_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_VIDEO_PROCESS_INPUT_STREAM_FLAGS); + + typedef struct D3D12_VIDEO_PROCESS_FILTER_RANGE + { + INT Minimum; + INT Maximum; + INT Default; + FLOAT Multiplier; + } D3D12_VIDEO_PROCESS_FILTER_RANGE; + + typedef + enum D3D12_VIDEO_PROCESS_SUPPORT_FLAGS + { + D3D12_VIDEO_PROCESS_SUPPORT_FLAG_NONE = 0, + D3D12_VIDEO_PROCESS_SUPPORT_FLAG_SUPPORTED = 0x1, + D3D12_VIDEO_PROCESS_SUPPORT_FLAG_MASK = 0x1 + } D3D12_VIDEO_PROCESS_SUPPORT_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_VIDEO_PROCESS_SUPPORT_FLAGS); + + typedef struct D3D12_FEATURE_DATA_VIDEO_PROCESS_SUPPORT + { + UINT NodeIndex; // input + D3D12_VIDEO_SAMPLE InputSample; // input + D3D12_VIDEO_FIELD_TYPE InputFieldType; // input + D3D12_VIDEO_FRAME_STEREO_FORMAT InputStereoFormat; // input + DXGI_RATIONAL InputFrameRate; // input + D3D12_VIDEO_FORMAT OutputFormat; // input + D3D12_VIDEO_FRAME_STEREO_FORMAT OutputStereoFormat; // input + DXGI_RATIONAL OutputFrameRate; // input + D3D12_VIDEO_PROCESS_SUPPORT_FLAGS SupportFlags; // output + D3D12_VIDEO_SCALE_SUPPORT ScaleSupport; // output + D3D12_VIDEO_PROCESS_FEATURE_FLAGS FeatureSupport; // output + D3D12_VIDEO_PROCESS_DEINTERLACE_FLAGS DeinterlaceSupport; // output + D3D12_VIDEO_PROCESS_AUTO_PROCESSING_FLAGS AutoProcessingSupport; // output + D3D12_VIDEO_PROCESS_FILTER_FLAGS FilterSupport; // output + D3D12_VIDEO_PROCESS_FILTER_RANGE FilterRangeSupport[D3D12_VIDEO_PROCESS_MAX_FILTERS]; // output + } D3D12_FEATURE_DATA_VIDEO_PROCESS_SUPPORT; + + typedef struct D3D12_FEATURE_DATA_VIDEO_PROCESS_MAX_INPUT_STREAMS + { + UINT NodeIndex; // input + UINT MaxInputStreams; // output + } D3D12_FEATURE_DATA_VIDEO_PROCESS_MAX_INPUT_STREAMS; + + typedef struct D3D12_FEATURE_DATA_VIDEO_PROCESS_REFERENCE_INFO + { + UINT NodeIndex; // input + D3D12_VIDEO_PROCESS_DEINTERLACE_FLAGS DeinterlaceMode; // input + D3D12_VIDEO_PROCESS_FILTER_FLAGS Filters; // input + D3D12_VIDEO_PROCESS_FEATURE_FLAGS FeatureSupport; // input + DXGI_RATIONAL InputFrameRate; // input + DXGI_RATIONAL OutputFrameRate; // input + BOOL EnableAutoProcessing; // input + UINT PastFrames; // output + UINT FutureFrames; // output + } D3D12_FEATURE_DATA_VIDEO_PROCESS_REFERENCE_INFO; + + typedef struct D3D12_VIDEO_PROCESS_REFERENCE_SET + { + UINT NumPastFrames; + ID3D12Resource **ppPastFrames; + UINT *pPastSubresources; + UINT NumFutureFrames; + ID3D12Resource **ppFutureFrames; + UINT *pFutureSubresources; + } D3D12_VIDEO_PROCESS_REFERENCE_SET; + + typedef struct D3D12_VIDEO_PROCESS_TRANSFORM + { + D3D12_RECT SourceRectangle; + D3D12_RECT DestinationRectangle; + D3D12_VIDEO_PROCESS_ORIENTATION Orientation; + } D3D12_VIDEO_PROCESS_TRANSFORM; + + typedef struct D3D12_VIDEO_PROCESS_INPUT_STREAM_RATE + { + UINT OutputIndex; + UINT InputFrameOrField; + } D3D12_VIDEO_PROCESS_INPUT_STREAM_RATE; + + typedef struct D3D12_VIDEO_PROCESS_INPUT_STREAM + { + ID3D12Resource *pTexture2D; + UINT Subresource; + D3D12_VIDEO_PROCESS_REFERENCE_SET ReferenceSet; + } D3D12_VIDEO_PROCESS_INPUT_STREAM; + + #define D3D12_VIDEO_PROCESS_STEREO_VIEWS ( 2 ) + + typedef struct D3D12_VIDEO_PROCESS_INPUT_STREAM_ARGUMENTS + { + D3D12_VIDEO_PROCESS_INPUT_STREAM InputStream[D3D12_VIDEO_PROCESS_STEREO_VIEWS]; + D3D12_VIDEO_PROCESS_TRANSFORM Transform; + D3D12_VIDEO_PROCESS_INPUT_STREAM_FLAGS Flags; + D3D12_VIDEO_PROCESS_INPUT_STREAM_RATE RateInfo; + INT FilterLevels[D3D12_VIDEO_PROCESS_MAX_FILTERS]; + D3D12_VIDEO_PROCESS_ALPHA_BLENDING AlphaBlending; + } D3D12_VIDEO_PROCESS_INPUT_STREAM_ARGUMENTS; + + typedef struct D3D12_VIDEO_PROCESS_OUTPUT_STREAM + { + ID3D12Resource* pTexture2D; + UINT Subresource; + } D3D12_VIDEO_PROCESS_OUTPUT_STREAM; + + typedef struct D3D12_VIDEO_PROCESS_OUTPUT_STREAM_ARGUMENTS + { + D3D12_VIDEO_PROCESS_OUTPUT_STREAM OutputStream[D3D12_VIDEO_PROCESS_STEREO_VIEWS]; + D3D12_RECT TargetRectangle; + } D3D12_VIDEO_PROCESS_OUTPUT_STREAM_ARGUMENTS; + +}; + +extern "C" +{ + +// +// ID3D12VideoDevice +// + +struct D3D12VideoDevice_Function_Table +{ + GraphicsUnknown_Function_Table ObjectFunction; + + HRESULT (D3DAPI *CheckFeatureSupport )( + ID3D12VideoDevice * This, + D3D12_FEATURE_VIDEO FeatureVideo, + _Inout_updates_bytes_(FeatureSupportDataSize) void *pFeatureSupportData, + UINT FeatureSupportDataSize); + + HRESULT (D3DAPI *CreateVideoDecoder )( + ID3D12VideoDevice * This, + _In_ const D3D12_VIDEO_DECODER_DESC *pDesc, + _In_ REFIID riid, + _COM_Outptr_ void **ppVideoDecoder); + + HRESULT(D3DAPI *CreateVideoDecoderHeap)( + ID3D12VideoDevice * This, + _In_ const D3D12_VIDEO_DECODER_HEAP_DESC* pVideoDecoderHeapDesc, + _In_ REFIID riid, // Expected: IID_ID3D12VideoDecoderHeap, + _COM_Outptr_ void** ppVideoDecoderHeap + ); + + HRESULT (D3DAPI *CreateVideoProcessor )( + ID3D12VideoDevice * This, + UINT NodeMask, + _In_ const D3D12_VIDEO_PROCESS_OUTPUT_STREAM_DESC *pOutputStreamDesc, + UINT NumInputStreamDescs, + _In_reads_(NumInputStreamDescs) const D3D12_VIDEO_PROCESS_INPUT_STREAM_DESC *pInputStreamDescs, + _In_ REFIID riid, + _COM_Outptr_ void **ppVideoProcessor); + +}; + + +#if DECLARE_UMD_EXPORTS_D3D12X + +HRESULT D3DAPI D3D12VideoDevice_CheckFeatureSupport( + ID3D12VideoDevice * This, + D3D12_FEATURE_VIDEO FeatureVideo, + _Inout_updates_bytes_(FeatureSupportDataSize) void *pFeatureSupportData, + UINT FeatureSupportDataSize); + +HRESULT D3DAPI D3D12VideoDevice_CreateVideoDecoder( + ID3D12VideoDevice * This, + _In_ const D3D12_VIDEO_DECODER_DESC *pDesc, + _In_ REFIID riid, + _COM_Outptr_ void **ppVideoDecoder); + +HRESULT D3DAPI D3D12VideoDevice_CreateVideoDecoderHeap( + ID3D12VideoDevice * This, + _In_ const D3D12_VIDEO_DECODER_HEAP_DESC* pVideoDecoderHeapDesc, + _In_ REFIID riid, // Expected: IID_ID3D12VideoDecoderHeap, + _COM_Outptr_ void** ppVideoDecoderHeap); + +HRESULT D3DAPI D3D12VideoDevice_CreateVideoProcessor( + ID3D12VideoDevice * This, + UINT NodeMask, + _In_ const D3D12_VIDEO_PROCESS_OUTPUT_STREAM_DESC *pOutputStreamDesc, + UINT NumInputStreamDescs, + _In_reads_(NumInputStreamDescs) const D3D12_VIDEO_PROCESS_INPUT_STREAM_DESC *pInputStreamDescs, + _In_ REFIID riid, + _COM_Outptr_ void **ppVideoProcessor); + + +ULONG D3DAPI D3D12VideoDevice_AddRef( + _Inout_ IGraphicsUnknown* pUnknown); + +ULONG D3DAPI D3D12VideoDevice_Release( + _Inout_ IGraphicsUnknown* pUnknown); + +HRESULT D3DAPI D3D12VideoDevice_QueryInterface( + _Inout_ IGraphicsUnknown* pUnknown, + _In_ REFIID riid, + _Out_ void** ppObject); + +D3DCONST D3D12VideoDevice_Function_Table D3D__D3d12VideoDevice_Function_Table = +{ + { + D3D12VideoDevice_QueryInterface, + D3D12VideoDevice_AddRef, + D3D12VideoDevice_Release, + }, + D3D12VideoDevice_CheckFeatureSupport, + D3D12VideoDevice_CreateVideoDecoder, + D3D12VideoDevice_CreateVideoDecoderHeap, + D3D12VideoDevice_CreateVideoProcessor, +}; + +#endif +}; + + +D3DINTERFACE(ID3D12VideoDevice, 1F052807,0B46,4ACC,8A,89,36,4F,79,37,18,A4) : public IGraphicsUnknown +{ +public: + + D3DINLINE D3D12VideoDevice_Function_Table* DeviceFunction() + { + return (D3D12VideoDevice_Function_Table*)m_pFunction; + } + + D3DINLINE HRESULT D3DAPI CheckFeatureSupport( + D3D12_FEATURE_VIDEO FeatureVideo, + _Inout_updates_bytes_(FeatureSupportDataSize) void *pFeatureSupportData, + UINT FeatureSupportDataSize) + { + return DeviceFunction()->CheckFeatureSupport(this, FeatureVideo, pFeatureSupportData, FeatureSupportDataSize); + } + + D3DINLINE HRESULT D3DAPI CreateVideoDecoder( + _In_ const D3D12_VIDEO_DECODER_DESC *pDesc, + _In_ REFIID riid, + _COM_Outptr_ void **ppVideoDecoder) + { + return DeviceFunction()->CreateVideoDecoder(this, pDesc, riid, ppVideoDecoder); + } + + D3DINLINE HRESULT D3DAPI CreateVideoDecoderHeap( + _In_ const D3D12_VIDEO_DECODER_HEAP_DESC* pDesc, + _In_ REFIID riid, // Expected: IID_ID3D12VideoDecoderHeap, + _COM_Outptr_ void **ppVideoDecoderHeap) + { + return DeviceFunction()->CreateVideoDecoderHeap(this, pDesc, riid, ppVideoDecoderHeap); + } + + D3DINLINE HRESULT D3DAPI CreateVideoProcessor( + UINT NodeMask, + _In_ const D3D12_VIDEO_PROCESS_OUTPUT_STREAM_DESC *pOutputStreamDesc, + UINT NumInputStreamDescs, + _In_reads_(NumInputStreamDescs) const D3D12_VIDEO_PROCESS_INPUT_STREAM_DESC *pInputStreamDescs, + _In_ REFIID riid, + _COM_Outptr_ void **ppVideoProcessor) + { + return DeviceFunction()->CreateVideoProcessor(this, NodeMask, pOutputStreamDesc, NumInputStreamDescs, pInputStreamDescs, riid, ppVideoProcessor); + } +}; + + +extern "C" +{ + +// +// ID3D12VideoDecode +// + +struct D3D12VideoDecoder_Function_Table +{ + D3D12Pageable_Function_Table ObjectFunction; + + D3D12_VIDEO_DECODER_DESC ( D3DAPI *GetDesc )( ID3D12VideoDecoder * pThis); + +}; + + +#if DECLARE_UMD_EXPORTS_D3D12X + +D3D12_VIDEO_DECODER_DESC D3DAPI D3D12VideoDecoder_GetDesc( ID3D12VideoDecoder * pThis); + +ULONG D3DAPI D3d12VideoDecoder_Release(_Inout_ IGraphicsUnknown* pUnknown); + +D3DCONST D3D12VideoDecoder_Function_Table D3D__D3d12VideoDecoder_Function_Table = +{ + { + { + { + { + D3d12Object_QueryInterface, + D3d12DeviceChild_AddRef, + D3d12VideoDecoder_Release, + }, + D3d12Object_GetPrivateData, + D3d12Object_SetPrivateData, + D3d12Object_SetPrivateDataInterface, + D3d12Object_SetName, + }, + + D3d12DeviceChild_GetDevice, + }, + }, + D3D12VideoDecoder_GetDesc, +}; +#endif + +// external c +}; + + + +D3DINTERFACE(ID3D12VideoDecoder, C59B6BDC,7720,4074,A1,36,17,A1,56,03,74,70) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12VideoDecoder_Function_Table* DecoderFunction() + { + return (D3D12VideoDecoder_Function_Table*)m_pFunction; + } + + D3DINLINE D3D12_VIDEO_DECODER_DESC D3DAPI GetDesc() + { + return DecoderFunction()->GetDesc(this); + } +}; + + + +extern "C" +{ + + typedef + enum D3D12_VIDEO_DECODE_TIER + { + D3D12_VIDEO_DECODE_TIER_NOT_SUPPORTED = 0, + D3D12_VIDEO_DECODE_TIER_1 = 1, + D3D12_VIDEO_DECODE_TIER_2 = 2, + D3D12_VIDEO_DECODE_TIER_3 = 3, + } D3D12_VIDEO_DECODE_TIER; + + typedef + enum D3D12_VIDEO_DECODE_SUPPORT_FLAGS + { + D3D12_VIDEO_DECODE_SUPPORT_FLAG_NONE = 0, + D3D12_VIDEO_DECODE_SUPPORT_FLAG_SUPPORTED = 0x1, + } D3D12_VIDEO_DECODE_SUPPORT_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_VIDEO_DECODE_SUPPORT_FLAGS ); + typedef + enum D3D12_VIDEO_DECODE_CONFIGURATION_FLAGS + { + D3D12_VIDEO_DECODE_CONFIGURATION_FLAG_NONE = 0, + D3D12_VIDEO_DECODE_CONFIGURATION_FLAG_HEIGHT_ALIGNMENT_MULTIPLE_32_REQUIRED = 0x1, + D3D12_VIDEO_DECODE_CONFIGURATION_FLAG_POST_PROCESSING_SUPPORTED = 0x2, + D3D12_VIDEO_DECODE_CONFIGURATION_FLAG_REFERENCE_ONLY_ALLOCATIONS_REQUIRED = 0x4, + D3D12_VIDEO_DECODE_CONFIGURATION_FLAG_ALLOW_RESOLUTION_CHANGE_ON_NON_KEY_FRAME = 0x8, + } D3D12_VIDEO_DECODE_CONFIGURATION_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_VIDEO_DECODE_CONFIGURATION_FLAGS ); + typedef + enum D3D12_VIDEO_DECODE_STATUS + { + D3D12_VIDEO_DECODE_STATUS_OK = 0, + D3D12_VIDEO_DECODE_STATUS_CONTINUE = 1, + D3D12_VIDEO_DECODE_STATUS_CONTINUE_SKIP_DISPLAY = 2, + D3D12_VIDEO_DECODE_STATUS_RESTART = 3, + } D3D12_VIDEO_DECODE_STATUS; + + typedef + enum D3D12_VIDEO_DECODE_ARGUMENT_TYPE + { + D3D12_VIDEO_DECODE_ARGUMENT_TYPE_PICTURE_PARAMETERS = 0, + D3D12_VIDEO_DECODE_ARGUMENT_TYPE_INVERSE_QUANTIZATION_MATRIX = 1, + D3D12_VIDEO_DECODE_ARGUMENT_TYPE_SLICE_CONTROL = 2, + D3D12_VIDEO_DECODE_ARGUMENT_TYPE_MAX_VALID = 3 + } D3D12_VIDEO_DECODE_ARGUMENT_TYPE; + + typedef struct D3D12_FEATURE_DATA_VIDEO_DECODE_SUPPORT + { + UINT NodeIndex; + D3D12_VIDEO_DECODE_CONFIGURATION Configuration; + UINT Width; + UINT Height; + DXGI_FORMAT DecodeFormat; + DXGI_RATIONAL FrameRate; + UINT BitRate; + D3D12_VIDEO_DECODE_SUPPORT_FLAGS SupportFlags; + D3D12_VIDEO_DECODE_CONFIGURATION_FLAGS ConfigurationFlags; + D3D12_VIDEO_DECODE_TIER DecodeTier; + } D3D12_FEATURE_DATA_VIDEO_DECODE_SUPPORT; + + typedef struct D3D12_FEATURE_DATA_VIDEO_DECODE_PROFILES + { + UINT NodeIndex; + UINT ProfileCount; + _Field_size_full_(ProfileCount) GUID *pProfiles; + } D3D12_FEATURE_DATA_VIDEO_DECODE_PROFILES; + + typedef struct D3D12_FEATURE_DATA_VIDEO_DECODE_PROFILE_COUNT + { + UINT NodeIndex; // input + UINT ProfileCount; // output + } D3D12_FEATURE_DATA_VIDEO_DECODE_PROFILE_COUNT; + + typedef struct D3D12_FEATURE_DATA_VIDEO_DECODE_FORMAT_COUNT + { + UINT NodeIndex; // input + D3D12_VIDEO_DECODE_CONFIGURATION Configuration; // input + UINT FormatCount; // output + } D3D12_FEATURE_DATA_VIDEO_DECODE_FORMAT_COUNT; + + typedef struct D3D12_FEATURE_DATA_VIDEO_DECODE_FORMATS + { + UINT NodeIndex; + D3D12_VIDEO_DECODE_CONFIGURATION Configuration; + UINT FormatCount; + _Field_size_full_(FormatCount) DXGI_FORMAT *pOutputFormats; + } D3D12_FEATURE_DATA_VIDEO_DECODE_FORMATS; + + typedef struct D3D12_FEATURE_DATA_VIDEO_ARCHITECTURE + { + BOOL IOCoherent; + } D3D12_FEATURE_DATA_VIDEO_ARCHITECTURE; + + typedef + enum D3D12_VIDEO_DECODE_CONVERSION_SUPPORT_FLAGS + { + D3D12_VIDEO_DECODE_CONVERSION_SUPPORT_FLAG_NONE = 0, + D3D12_VIDEO_DECODE_CONVERSION_SUPPORT_FLAG_SUPPORTED = 0x1, + } D3D12_VIDEO_DECODE_CONVERSION_SUPPORT_FLAGS; + + DEFINE_ENUM_FLAG_OPERATORS(D3D12_VIDEO_DECODE_CONVERSION_SUPPORT_FLAGS ); + + typedef struct D3D12_FEATURE_DATA_VIDEO_DECODE_CONVERSION_SUPPORT + { + UINT NodeIndex; // input + D3D12_VIDEO_DECODE_CONFIGURATION Configuration; // input + D3D12_VIDEO_SAMPLE DecodeSample; // input + D3D12_VIDEO_FORMAT OutputFormat; // input + DXGI_RATIONAL FrameRate; // input + UINT BitRate; // input + D3D12_VIDEO_DECODE_CONVERSION_SUPPORT_FLAGS SupportFlags; // output + D3D12_VIDEO_SCALE_SUPPORT ScaleSupport; // output + } D3D12_FEATURE_DATA_VIDEO_DECODE_CONVERSION_SUPPORT; + + + typedef struct D3D12_FEATURE_DATA_VIDEO_DECODER_HEAP_SIZE + { + D3D12_VIDEO_DECODER_HEAP_DESC VideoDecoderHeapDesc; // input + UINT64 MemoryPoolL0Size; // output + UINT64 MemoryPoolL1Size; // output + } D3D12_FEATURE_DATA_VIDEO_DECODER_HEAP_SIZE; + + typedef struct D3D12_QUERY_DATA_VIDEO_DECODE_STATISTICS + { + UINT64 Status; // see D3D12_VIDEO_DECODE_STATUS + UINT64 NumMacroblocksAffected; + DXGI_RATIONAL FrameRate; + UINT BitRate; + } D3D12_QUERY_DATA_VIDEO_DECODE_STATISTICS; + + typedef struct D3D12_FEATURE_DATA_VIDEO_DECODE_BITSTREAM_ENCRYPTION_SCHEMES + { + UINT NodeIndex; + GUID DecodeProfile; + UINT EncryptionSchemeCount; + _Field_size_full_(EncryptionSchemeCount) D3D12_BITSTREAM_ENCRYPTION_TYPE *pEncryptionSchemes; + } D3D12_FEATURE_DATA_VIDEO_DECODE_BITSTREAM_ENCRYPTION_SCHEMES; + + typedef struct D3D12_VIDEO_DECODE_SUB_SAMPLE_MAPPING_BLOCK + { + UINT ClearSize; + UINT EncryptedSize; + } D3D12_VIDEO_DECODE_SUB_SAMPLE_MAPPING_BLOCK; + + typedef struct D3D12_VIDEO_DECODE_FRAME_ARGUMENT + { + D3D12_VIDEO_DECODE_ARGUMENT_TYPE Type; + _Field_size_bytes_full_(ArgumentSize) void *pData; + UINT Size; + } D3D12_VIDEO_DECODE_FRAME_ARGUMENT; + + typedef struct D3D12_VIDEO_DECODE_REFERENCE_FRAMES + { + _Field_size_full_(NumTexture2Ds) ID3D12Resource **ppTexture2Ds; + _Field_size_full_(NumTexture2Ds) UINT *pSubresources; + UINT NumTexture2Ds; + } D3D12_VIDEO_DECODE_REFERENCE_FRAMES; + + typedef struct D3D12_VIDEO_DECODE_COMPRESSED_BITSTREAM + { + ID3D12Resource *pBuffer; + UINT64 Offset; + UINT64 Size; + } D3D12_VIDEO_DECODE_COMPRESSED_BITSTREAM; + + typedef struct D3D12_VIDEO_DECODE_CONVERSION_ARGUMENTS + { + BOOL Enable; + ID3D12Resource *pReferenceTexture2D; + UINT ReferenceSubresource; + DXGI_COLOR_SPACE_TYPE OutputColorSpace; + DXGI_COLOR_SPACE_TYPE DecodeColorSpace; + } D3D12_VIDEO_DECODE_CONVERSION_ARGUMENTS; + + +#define D3D12_VIDEO_DECODE_MAX_ARGUMENTS ( 10 ) + + typedef struct D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS + { + UINT NumFrameArguments; + D3D12_VIDEO_DECODE_FRAME_ARGUMENT FrameArguments[D3D12_VIDEO_DECODE_MAX_ARGUMENTS]; + D3D12_VIDEO_DECODE_REFERENCE_FRAMES ReferenceFrames; + D3D12_VIDEO_DECODE_COMPRESSED_BITSTREAM CompressedBitstream; + ID3D12VideoDecoderHeap *pHeap; + } D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS; + + typedef struct D3D12_VIDEO_DECODE_OUTPUT_STREAM_ARGUMENTS + { + ID3D12Resource* pOutputTexture2D; + UINT OutputSubresource; + D3D12_VIDEO_DECODE_CONVERSION_ARGUMENTS ConversionArguments; + } D3D12_VIDEO_DECODE_OUTPUT_STREAM_ARGUMENTS; + + + + // external_c +} + +extern "C" +{ + + // + // ID3D12VideoProcessor + // + + struct D3D12VideoProcessor_Function_Table + { + D3D12Pageable_Function_Table ObjectFunction; + + UINT(D3DAPI *GetNodeMask)(ID3D12VideoProcessor * pThis); + UINT(D3DAPI *GetNumInputStreamDescs)(ID3D12VideoProcessor * pThis); + HRESULT(D3DAPI *GetInputStreamDescs)(ID3D12VideoProcessor * pThis, UINT NumInputStreamDescs, D3D12_VIDEO_PROCESS_INPUT_STREAM_DESC *pInputStreamDescs); + D3D12_VIDEO_PROCESS_OUTPUT_STREAM_DESC (D3DAPI *GetOutputStreamDesc)(ID3D12VideoProcessor * pThis); + }; + + +#if DECLARE_UMD_EXPORTS_D3D12X + + ULONG D3DAPI D3D12VideoProcessor_Release(IGraphicsUnknown *pVideoProcessor); + D3D12_VIDEO_PROCESS_OUTPUT_STREAM_DESC D3DAPI D3D12VideoProcessor_GetOutputStreamDesc(ID3D12VideoProcessor * pThis); + UINT D3DAPI D3D12VideoProcessor_GetNodeMask(ID3D12VideoProcessor * pThis); + UINT D3DAPI D3D12VideoProcessor_GetNumInputStreamDescs(ID3D12VideoProcessor * pThis); + HRESULT D3DAPI D3D12VideoProcessor_GetInputStreamDescs( + ID3D12VideoProcessor * pThis, + UINT NumInputStreamDescs, + D3D12_VIDEO_PROCESS_INPUT_STREAM_DESC *pInputStreamDescs); + + D3DCONST D3D12VideoProcessor_Function_Table D3D__D3D12VideoProcessor_Function_Table = + { + { + { + { + { + D3d12Object_QueryInterface, + D3d12DeviceChild_AddRef, + D3D12VideoProcessor_Release, + }, + D3d12Object_GetPrivateData, + D3d12Object_SetPrivateData, + D3d12Object_SetPrivateDataInterface, + D3d12Object_SetName, + }, + + D3d12DeviceChild_GetDevice, + }, + }, + D3D12VideoProcessor_GetNodeMask, + D3D12VideoProcessor_GetNumInputStreamDescs, + D3D12VideoProcessor_GetInputStreamDescs, + D3D12VideoProcessor_GetOutputStreamDesc + }; +#endif + + // external c +}; + + +D3DINTERFACE(ID3D12VideoProcessor, 304FDB32, bede, 410a, 85, 45, 94, 3a, c6, a4, 61, 38) : public ID3D12Pageable +{ +public: + + D3DINLINE D3D12VideoProcessor_Function_Table* VideoProcessorFunction() + { + return (D3D12VideoProcessor_Function_Table*)m_pFunction; + } + + D3DINLINE UINT GetNodeMask() + { + return VideoProcessorFunction()->GetNodeMask(this); + } + + D3DINLINE UINT GetNumInputStreamDescs() + { + return VideoProcessorFunction()->GetNodeMask(this); + } + + D3DINLINE HRESULT GetInputStreamDescs(UINT NumInputStreamDescs, D3D12_VIDEO_PROCESS_INPUT_STREAM_DESC *pInputStreamDescs) + { + return VideoProcessorFunction()->GetInputStreamDescs(this, NumInputStreamDescs, pInputStreamDescs); + } + + D3DINLINE D3D12_VIDEO_PROCESS_OUTPUT_STREAM_DESC GetOutputStreamDesc() + { + return VideoProcessorFunction()->GetOutputStreamDesc(this); + } +}; + +extern "C" +{ + +// ID3D12VideoDecodeCommandList +// + +struct D3D12VideoDecodeCommandList_Function_Table +{ + D3D12CommandList_Function_Table ObjectFunction; + + HRESULT (D3DAPI *Close )( + _In_ ID3D12VideoDecodeCommandList * pThis); + + HRESULT (D3DAPI *Reset )( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12CommandAllocator *pAllocator); + + void (D3DAPI *ClearState )(_In_ ID3D12VideoDecodeCommandList * pThis); + + void (D3DAPI *ResourceBarrier )( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER *pBarriers); + + void (D3DAPI *DiscardResource )( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12Resource *pResource, + _In_opt_ const D3D12_DISCARD_REGION *pRegion); + + void (D3DAPI *BeginQuery )( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void (D3DAPI *EndQuery )( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void (D3DAPI *ResolveQueryData )( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartIndex, + _In_ UINT NumQueries, + _In_ ID3D12Resource *pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset); + + void (D3DAPI *SetPredication )( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_opt_ ID3D12Resource *pBuffer, + _In_ UINT64 AlignedBufferOffset, + _In_ D3D12_PREDICATION_OP Operation); + + void (D3DAPI *SetMarker )( + _In_ ID3D12VideoDecodeCommandList * pThis, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size); + + void (D3DAPI *BeginEvent )( + _In_ ID3D12VideoDecodeCommandList * pThis, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size); + + void (D3DAPI *EndEvent )(_In_ ID3D12VideoDecodeCommandList * pThis); + + void (D3DAPI *DecodeFrame )( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12VideoDecoder *pDecoder, + _In_ const D3D12_VIDEO_DECODE_OUTPUT_STREAM_ARGUMENTS *pOutputArguments, + _In_ const D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS *pInputArguments); + + void (D3DAPI *WriteBufferImmediate)( + _In_ ID3D12VideoDecodeCommandList * pThis, + UINT Count, + _In_reads_(Count) const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER *pParams, + _In_reads_opt_(Count) const D3D12_WRITEBUFFERIMMEDIATE_MODE *pModes); +}; + +#if DECLARE_UMD_EXPORTS_D3D12X + + +HRESULT D3DAPI D3D12VideoDecodeCommandList_Close( + _In_ ID3D12VideoDecodeCommandList * pThis); + +HRESULT D3DAPI D3D12VideoDecodeCommandList_Reset( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12CommandAllocator *pAllocator); + +void D3DAPI D3D12VideoDecodeCommandList_ClearState(_In_ ID3D12VideoDecodeCommandList * pThis); + +void D3DAPI D3D12VideoDecodeCommandList_ResourceBarrier( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER *pBarriers); + +void D3DAPI D3D12VideoDecodeCommandList_DiscardResource( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12Resource *pResource, + _In_opt_ const D3D12_DISCARD_REGION *pRegion); + +void D3DAPI D3D12VideoDecodeCommandList_BeginQuery( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + +void D3DAPI D3D12VideoDecodeCommandList_EndQuery( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + +void D3DAPI D3D12VideoDecodeCommandList_ResolveQueryData( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartIndex, + _In_ UINT NumQueries, + _In_ ID3D12Resource *pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset); + +void D3DAPI D3D12VideoDecodeCommandList_SetPredication( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_opt_ ID3D12Resource *pBuffer, + _In_ UINT64 AlignedBufferOffset, + _In_ D3D12_PREDICATION_OP Operation); + +void D3DAPI D3D12VideoDecodeCommandList_SetMarker( + _In_ ID3D12VideoDecodeCommandList * pThis, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size); + +void D3DAPI D3D12VideoDecodeCommandList_BeginEvent( + _In_ ID3D12VideoDecodeCommandList * pThis, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size); + +void D3DAPI D3D12VideoDecodeCommandList_EndEvent(_In_ ID3D12VideoDecodeCommandList * pThis); + +void D3DAPI D3D12VideoDecodeCommandList_DecodeFrame( + _In_ ID3D12VideoDecodeCommandList * pThis, + _In_ ID3D12VideoDecoder *pDecoder, + _In_ const D3D12_VIDEO_DECODE_OUTPUT_STREAM_ARGUMENTS *pOutputArguments, + _In_ const D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS *pInputArguments); + +void D3DAPI D3D12VideoDecodeCommandList_WriteBufferImmediate( + _In_ ID3D12VideoDecodeCommandList * pThis, + UINT count, + _In_reads_(count) const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER *pParams, + _In_reads_opt_(count) const D3D12_WRITEBUFFERIMMEDIATE_MODE *pModes); + + +ULONG D3DAPI D3D12VideoDecodeCommandList_Release( + _Inout_ IGraphicsUnknown* pCommandList); + +D3DCONST D3D12VideoDecodeCommandList_Function_Table D3D__D3D12VideoDecodeCommandList_Function_Table = +{ + { + { + { + { + D3d12Object_QueryInterface, + D3d12DeviceChild_AddRef, + D3D12VideoDecodeCommandList_Release, + }, + + D3d12Object_GetPrivateData, + D3d12Object_SetPrivateData, + D3d12Object_SetPrivateDataInterface, + D3d12Object_SetName, + }, + + D3d12DeviceChild_GetDevice, + }, + + D3d12CommandList_GetType, + }, + + D3D12VideoDecodeCommandList_Close, + D3D12VideoDecodeCommandList_Reset, + D3D12VideoDecodeCommandList_ClearState, + D3D12VideoDecodeCommandList_ResourceBarrier, + D3D12VideoDecodeCommandList_DiscardResource, + D3D12VideoDecodeCommandList_BeginQuery, + D3D12VideoDecodeCommandList_EndQuery, + D3D12VideoDecodeCommandList_ResolveQueryData, + D3D12VideoDecodeCommandList_SetPredication, + D3D12VideoDecodeCommandList_SetMarker, + D3D12VideoDecodeCommandList_BeginEvent, + D3D12VideoDecodeCommandList_EndEvent, + D3D12VideoDecodeCommandList_DecodeFrame, + D3D12VideoDecodeCommandList_WriteBufferImmediate, + +}; +#endif + + +// external c +}; + + +D3DINTERFACE(ID3D12VideoDecodeCommandList, 3B60536E, AD29, 4E64, A2, 69, F8, 53, 83, 7E, 5E, 53) : public ID3D12CommandList +{ +public: + + D3DINLINE D3D12VideoDecodeCommandList_Function_Table* CommandListFunction() + { + return (D3D12VideoDecodeCommandList_Function_Table*)m_pFunction; + } + + + D3DINLINE HRESULT D3DAPI Close() + { + return CommandListFunction()->Close(this); + } + + D3DINLINE HRESULT D3DAPI Reset( + _In_ ID3D12CommandAllocator *pAllocator) + { + return CommandListFunction()->Reset(this, pAllocator); + } + + D3DINLINE void D3DAPI ClearState() + { + return CommandListFunction()->ClearState(this); + } + + D3DINLINE void D3DAPI ResourceBarrier( + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER *pBarriers) + { + return CommandListFunction()->ResourceBarrier(this, NumBarriers, pBarriers); + } + + D3DINLINE void D3DAPI DiscardResource( + _In_ ID3D12Resource *pResource, + _In_opt_ const D3D12_DISCARD_REGION *pRegion) + { + return CommandListFunction()->DiscardResource(this, pResource, pRegion); + } + + D3DINLINE void D3DAPI BeginQuery( + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index) + { + return CommandListFunction()->BeginQuery(this, pQueryHeap, Type, Index); + } + + D3DINLINE void D3DAPI EndQuery( + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index) + { + return CommandListFunction()->EndQuery(this, pQueryHeap, Type, Index); + } + + D3DINLINE void D3DAPI ResolveQueryData( + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartIndex, + _In_ UINT NumQueries, + _In_ ID3D12Resource *pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset) + { + return CommandListFunction()->ResolveQueryData(this, pQueryHeap, Type, StartIndex, NumQueries, pDestinationBuffer, AlignedDestinationBufferOffset); + } + + D3DINLINE void D3DAPI SetPredication( + _In_opt_ ID3D12Resource *pBuffer, + _In_ UINT64 AlignedBufferOffset, + _In_ D3D12_PREDICATION_OP Operation) + { + return CommandListFunction()->SetPredication(this, pBuffer, AlignedBufferOffset, Operation); + } + + D3DINLINE void D3DAPI SetMarker( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size) + { + return CommandListFunction()->SetMarker(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI BeginEvent( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size) + { + return CommandListFunction()->BeginEvent(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI EndEvent() + { + return CommandListFunction()->EndEvent(this); + } + + D3DINLINE void D3DAPI DecodeFrame( + _In_ ID3D12VideoDecoder *pDecoder, + _In_ const D3D12_VIDEO_DECODE_OUTPUT_STREAM_ARGUMENTS *pOutputArguments, + _In_ const D3D12_VIDEO_DECODE_INPUT_STREAM_ARGUMENTS *pInputArguments) + { + return CommandListFunction()->DecodeFrame(this, pDecoder, pOutputArguments, pInputArguments); + } + + D3DINLINE void D3DAPI WriteBufferImmediate( + UINT Count, + _In_reads_(Count) const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER *pParams, + _In_reads_opt_(Count) const D3D12_WRITEBUFFERIMMEDIATE_MODE *pModes) + { + return CommandListFunction()->WriteBufferImmediate(this, Count, pParams, pModes); + } +}; + + +extern "C" +{ + + // ID3D12VideoProcessCommandList + // + + struct D3D12VideoProcessCommandList_Function_Table + { + D3D12CommandList_Function_Table ObjectFunction; + + HRESULT(D3DAPI *Close)( + _In_ ID3D12VideoProcessCommandList * pThis); + + HRESULT(D3DAPI *Reset)( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12CommandAllocator *pAllocator); + + void (D3DAPI *ClearState)(_In_ ID3D12VideoProcessCommandList * pThis); + + void (D3DAPI *ResourceBarrier)( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER *pBarriers); + + void (D3DAPI *DiscardResource)( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12Resource *pResource, + _In_opt_ const D3D12_DISCARD_REGION *pRegion); + + void (D3DAPI *BeginQuery)( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void (D3DAPI *EndQuery)( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void (D3DAPI *ResolveQueryData)( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartIndex, + _In_ UINT NumQueries, + _In_ ID3D12Resource *pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset); + + void (D3DAPI *SetPredication)( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_opt_ ID3D12Resource *pBuffer, + _In_ UINT64 AlignedBufferOffset, + _In_ D3D12_PREDICATION_OP Operation); + + void (D3DAPI *SetMarker)( + _In_ ID3D12VideoProcessCommandList * pThis, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size); + + void (D3DAPI *BeginEvent)( + _In_ ID3D12VideoProcessCommandList * pThis, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size); + + void (D3DAPI *EndEvent)(_In_ ID3D12VideoProcessCommandList * pThis); + + void (D3DAPI *ProcessFrames)( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12VideoProcessor *pVideoProcessor, + _In_ const D3D12_VIDEO_PROCESS_OUTPUT_STREAM_ARGUMENTS *pOutputArguments, + UINT NumInputStreams, + _In_ const D3D12_VIDEO_PROCESS_INPUT_STREAM_ARGUMENTS *pInputArguments); + + void (D3DAPI *WriteBufferImmediate)( + _In_ ID3D12VideoProcessCommandList * pThis, + UINT Count, + _In_reads_(Count) const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER *pParams, + _In_reads_opt_(Count) const D3D12_WRITEBUFFERIMMEDIATE_MODE *pModes); + }; + +#if DECLARE_UMD_EXPORTS_D3D12X + + + HRESULT D3DAPI D3D12VideoProcessCommandList_Close( + _In_ ID3D12VideoProcessCommandList * pThis); + + HRESULT D3DAPI D3D12VideoProcessCommandList_Reset( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12CommandAllocator *pAllocator); + + void D3DAPI D3D12VideoProcessCommandList_ClearState(_In_ ID3D12VideoProcessCommandList * pThis); + + void D3DAPI D3D12VideoProcessCommandList_ResourceBarrier( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER *pBarriers); + + void D3DAPI D3D12VideoProcessCommandList_DiscardResource( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12Resource *pResource, + _In_opt_ const D3D12_DISCARD_REGION *pRegion); + + void D3DAPI D3D12VideoProcessCommandList_BeginQuery( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void D3DAPI D3D12VideoProcessCommandList_EndQuery( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index); + + void D3DAPI D3D12VideoProcessCommandList_ResolveQueryData( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartIndex, + _In_ UINT NumQueries, + _In_ ID3D12Resource *pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset); + + void D3DAPI D3D12VideoProcessCommandList_SetPredication( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_opt_ ID3D12Resource *pBuffer, + _In_ UINT64 AlignedBufferOffset, + _In_ D3D12_PREDICATION_OP Operation); + + void D3DAPI D3D12VideoProcessCommandList_SetMarker( + _In_ ID3D12VideoProcessCommandList * pThis, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size); + + void D3DAPI D3D12VideoProcessCommandList_BeginEvent( + _In_ ID3D12VideoProcessCommandList * pThis, + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size); + + void D3DAPI D3D12VideoProcessCommandList_EndEvent(_In_ ID3D12VideoProcessCommandList * pThis); + + void D3DAPI D3D12VideoProcessCommandList_ProcessFrames( + _In_ ID3D12VideoProcessCommandList * pThis, + _In_ ID3D12VideoProcessor *pVideoProcessor, + _In_ const D3D12_VIDEO_PROCESS_OUTPUT_STREAM_ARGUMENTS *pOutputArguments, + UINT NumInputStreams, + _In_ const D3D12_VIDEO_PROCESS_INPUT_STREAM_ARGUMENTS *pInputArguments); + + void D3DAPI D3D12VideoProcessCommandList_WriteBufferImmediate( + _In_ ID3D12VideoProcessCommandList * pThis, + UINT count, + _In_reads_(count) const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER *pParams, + _In_reads_opt_(count) const D3D12_WRITEBUFFERIMMEDIATE_MODE *pModes); + + + ULONG D3DAPI D3D12VideoProcessCommandList_Release( + _Inout_ IGraphicsUnknown* pCommandList); + + D3DCONST D3D12VideoProcessCommandList_Function_Table D3D__D3D12VideoProcessCommandList_Function_Table = + { + { + { + { + { + D3d12Object_QueryInterface, + D3d12DeviceChild_AddRef, + D3D12VideoProcessCommandList_Release, + }, + + D3d12Object_GetPrivateData, + D3d12Object_SetPrivateData, + D3d12Object_SetPrivateDataInterface, + D3d12Object_SetName, + }, + + D3d12DeviceChild_GetDevice, + }, + + D3d12CommandList_GetType, + }, + + D3D12VideoProcessCommandList_Close, + D3D12VideoProcessCommandList_Reset, + D3D12VideoProcessCommandList_ClearState, + D3D12VideoProcessCommandList_ResourceBarrier, + D3D12VideoProcessCommandList_DiscardResource, + D3D12VideoProcessCommandList_BeginQuery, + D3D12VideoProcessCommandList_EndQuery, + D3D12VideoProcessCommandList_ResolveQueryData, + D3D12VideoProcessCommandList_SetPredication, + D3D12VideoProcessCommandList_SetMarker, + D3D12VideoProcessCommandList_BeginEvent, + D3D12VideoProcessCommandList_EndEvent, + D3D12VideoProcessCommandList_ProcessFrames, + D3D12VideoProcessCommandList_WriteBufferImmediate, + + }; +#endif + + + D3DINTERFACE(ID3D12VideoProcessCommandList, AEB2543A, 167F, 4682, AC, C8, D1, 59, ED, 4A, 62, 09) : public ID3D12CommandList + { + public: + + D3DINLINE D3D12VideoProcessCommandList_Function_Table* CommandListFunction() + { + return (D3D12VideoProcessCommandList_Function_Table*)m_pFunction; + } + + + D3DINLINE HRESULT D3DAPI Close() + { + return CommandListFunction()->Close(this); + } + + D3DINLINE HRESULT D3DAPI Reset( + _In_ ID3D12CommandAllocator *pAllocator) + { + return CommandListFunction()->Reset(this, pAllocator); + } + + D3DINLINE void D3DAPI ClearState() + { + return CommandListFunction()->ClearState(this); + } + + D3DINLINE void D3DAPI ResourceBarrier( + _In_ UINT NumBarriers, + _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER *pBarriers) + { + return CommandListFunction()->ResourceBarrier(this, NumBarriers, pBarriers); + } + + D3DINLINE void D3DAPI DiscardResource( + _In_ ID3D12Resource *pResource, + _In_opt_ const D3D12_DISCARD_REGION *pRegion) + { + return CommandListFunction()->DiscardResource(this, pResource, pRegion); + } + + D3DINLINE void D3DAPI BeginQuery( + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index) + { + return CommandListFunction()->BeginQuery(this, pQueryHeap, Type, Index); + } + + D3DINLINE void D3DAPI EndQuery( + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT Index) + { + return CommandListFunction()->EndQuery(this, pQueryHeap, Type, Index); + } + + D3DINLINE void D3DAPI ResolveQueryData( + _In_ ID3D12QueryHeap *pQueryHeap, + _In_ D3D12_QUERY_TYPE Type, + _In_ UINT StartIndex, + _In_ UINT NumQueries, + _In_ ID3D12Resource *pDestinationBuffer, + _In_ UINT64 AlignedDestinationBufferOffset) + { + return CommandListFunction()->ResolveQueryData(this, pQueryHeap, Type, StartIndex, NumQueries, pDestinationBuffer, AlignedDestinationBufferOffset); + } + + D3DINLINE void D3DAPI SetPredication( + _In_opt_ ID3D12Resource *pBuffer, + _In_ UINT64 AlignedBufferOffset, + _In_ D3D12_PREDICATION_OP Operation) + { + return CommandListFunction()->SetPredication(this, pBuffer, AlignedBufferOffset, Operation); + } + + D3DINLINE void D3DAPI SetMarker( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size) + { + return CommandListFunction()->SetMarker(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI BeginEvent( + UINT Metadata, + _In_reads_bytes_opt_(Size) const void *pData, + UINT Size) + { + return CommandListFunction()->BeginEvent(this, Metadata, pData, Size); + } + + D3DINLINE void D3DAPI EndEvent() + { + return CommandListFunction()->EndEvent(this); + } + + D3DINLINE void D3DAPI ProcessFrames( + _In_ ID3D12VideoProcessor *pVideoProcessor, + _In_ const D3D12_VIDEO_PROCESS_OUTPUT_STREAM_ARGUMENTS *pOutputArguments, + UINT NumInputStreams, + _In_ const D3D12_VIDEO_PROCESS_INPUT_STREAM_ARGUMENTS *pInputArguments) + { + return CommandListFunction()->ProcessFrames(this, pVideoProcessor, pOutputArguments, NumInputStreams, pInputArguments); + } + + D3DINLINE void D3DAPI WriteBufferImmediate( + UINT Count, + _In_reads_(Count) const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER *pParams, + _In_reads_opt_(Count) const D3D12_WRITEBUFFERIMMEDIATE_MODE *pModes) + { + return CommandListFunction()->WriteBufferImmediate(this, Count, pParams, pModes); + } + }; + + // external c +}; + + +#pragma warning( pop ) + +#endif // __d3d12_x_h__ + diff --git a/docs/gdkx/d3d12xbox_present_plane_parameters.md b/docs/gdkx/d3d12xbox_present_plane_parameters.md new file mode 100644 index 0000000..4aff703 --- /dev/null +++ b/docs/gdkx/d3d12xbox_present_plane_parameters.md @@ -0,0 +1,115 @@ +--- +author: sdgmiller +title: "D3D12XBOX_PRESENT_PLANE_PARAMETERS (Xbox One family)" +description: "Configures a presentation plane for composition with ID3D12CommandQueue::PresentX." +kindex: D3D12XBOX_PRESENT_PLANE_PARAMETERS +ms.author: mattbron +ms.topic: reference +edited: 07/04/2019 +ms.date: '08/01/2022' +permissioned-type: secret +--- + +# D3D12XBOX_PRESENT_PLANE_PARAMETERS (Xbox One family) + +Configures a presentation plane for composition with [ID3D12CommandQueue::PresentX](../interfaces/id3d12commandqueue/methods/id3d12commandqueue_presentx.md). + +## Syntax + +```cpp +typedef struct D3D12XBOX_PRESENT_PLANE_PARAMETERS +{ + D3D12XBOX_FRAME_PIPELINE_TOKEN Token; + UINT ResourceCount; + ID3D12Resource** ppResources; + D3D12_RECT* pSrcViewRects; + D3D12XBOX_VIEW_RECT* pDestPlacementBase; + DXGI_COLOR_SPACE_TYPE ColorSpace; + D3D12XBOX_PRESENT_PLANE_SCALE_FILTER ScaleFilter; + UINT ExtendedDescCount; + D3D12XBOX_PRESENT_PLANE_DESC* pExtendedDescs; + D3D12XBOX_PRESENT_PLANE_FLAGS Flags; +} D3D12XBOX_PRESENT_PLANE_PARAMETERS; +``` + +### Members + +*pTokens* +Type: [D3D12XBOX_FRAME_PIPELINE_TOKEN](../enums/d3d12xbox_frame_pipeline_token.md) + +Pipeline token that identifies the frame used in the production of *ppResources* that constitute the plane. The *Token* is generated at the frame origin and returned through a call to [ID3D12Device::WaitFrameEventX](../interfaces/id3d12device/methods/id3d12device_waitframeeventx.md) with the [D3D12XBOX_FRAME_EVENT_ORIGIN](../enums/d3d12xbox_frame_event_type.md) event. + +*ResourceCount* +Type: UINT + +Number of resources to be presented for the plane. Multiple resources may consist of dedicated color and alpha textures and/or of unique views for each player. + +*ppResources* +Type: [ID3D12Resource](https://learn.microsoft.com/windows/win32/api/d3d12/nn-d3d12-id3d12resource)* + +Pointer to the first element in an array of resources to be presented to the display for the plane. If support for unique view resources is to be added in the future, the array should be arranged by channel group (for example, RGBE or A8) and then by player. When presenting a RGBE + A8 pair, the RGBE resource must be ordered before the A8 resource. + +*pSrcViewRects* +Type: [D3D12_RECT](https://learn.microsoft.com/windows/win32/direct3d12/d3d12-rect)* + +Optional pointer to the first element of an array of rectangles, corresponding to the view region, of each player included in the presentation. The size of the array is defined by the [ViewCount](./d3d12xbox_present_parameters.md) parameter passed to [PresentX](../interfaces/id3d12commandqueue/methods/id3d12commandqueue_presentx.md). During presentation, each view region defined by its source rectangle will be scaled to a defined destination region on the display, as specified by *pDestPlacementBase*. These rectangles are permitted to overlap and/or match; they just identify the extents desired for each player view. Null can be passed for the member to define the source view rectangles that extend to fully cover the plane, as specified by the dimensions of the plane's associated resource. + +*pDestPlacementBase* +Type: [D3D12XBOX_VIEW_RECT](./d3d12xbox_view_rect.md)* + +Optional pointer to exactly one normalized view rectangle defining the destination region of the first player included in the presentation. During presentation, the source view rectangle of the first player in the plane's resource will be scaled to fill the destination region defined through *pDestPlacementBase*; the source view rectangles of all other players will be scaled to destination regions calculated indirectly, according to the relationship between the source and destination regions of the first player. More specifically, *pDestPlacementBase* is used to internally derive a placement offset and scaling factors for the first player view, and all other views employ identical scaling and complimentary offsets. PresentX](id3d12commandqueue_presentx.md) cannot be used to perform independent scaling and compositing of source views to arbitrary destination regions; instead, PresentX uniformly scales and offsets source views to the display. + +The destination placement view rectangle is expressed in normalized, floating-point coordinates. Left and top values of 0.0 correspond to the extreme upper-left of the destination display. Right and bottom values of 1.0 correspond to the extreme lower-right of the destination display. Null may be passed for the member to define full destination coverage for the first player view. + +As an example of *pDestPlacementBase* usage in the presence of multiple *pSrcViewRects*, consider a split-screen game that involves three players. To present the player views from a 3840 x 2160 swap resource in the form of a single row with three columns of identical size that covers the entire display, a caller would provide the following: + + *pSrcViewRects*: {0, 0, 1280, 2160}, {1280, 0, 2560, 2160}, {2560, 0, 3840, 2160} + *pDestPlacementBase*: {0.0f, 0.0f, 1.0f / 3.0f, 1.0f} + +*ColorSpace* +Type: [DXGI_COLOR_SPACE_TYPE](https://learn.microsoft.com/windows/win32/api/dxgicommon/ne-dxgicommon-dxgi_color_space_type)* + +Color space in which to interpret the resource data provided for the plane. The color space may also be used to determine which provided planes' resources are to be selected for display presentation (HDR) and which are to be used for GameDVR encoding (SDR). If no color space is given (that is, if the [D3D12XBOX_PRESENT_PLANE_PARAMETERS](./d3d12xbox_present_plane_parameters.md) themselves are null), then the color space is defined as **DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709**. Valid color spaces are **DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709** and **DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020**, both of which are gamma corrected. Xbox Series X|S allows gamma corrected colorspaces **DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P709** and **DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_D65P3**. Additionally, Xbox Series X|S allows linear light color spaces **DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709**, **DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_D65P3** and **DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P2020**. Linear light color spaces are only allowed with the swap resource format **DXGI_FORMAT_R9G9B9E5_SHAREDEXP**. Gamma corrected SDR color spaces are allowed with swap resources of any format, but HDR color spaces are only allowed with swap resources of format **DXGI_FORMAT_R10G10B10A2_UNORM**. + +With **DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709**, content in the swapbuffer is expected to use 709 primaries and the range of values per channel are expected to be between 0.0 and 1.0. In HDR mode, the 0.0 to 1.0 range is interpreted as between 0 and 10,000 nits. In other words, a 10,000 nit D65 white is represented as (1.0, 1.0, 1.0). Similarly, with **DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_D65P3**, the 0.0 to 1.0 range is interpreted as between 0 and 10,000 nits and a D65 10,000 nit white is (1.0, 1.0, 1.0). The swapbuffer is expected to contain content that is created with P3 color primaries and a D65 white point. This is distinct from the DCI_P3 colorspace where the white point is not D65. With **DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P2020**, the swapbuffer is expected to contain 2020 color primaries with a D65 white point and in the range 0.0 and 1.0, which is interpreted as between 0 and 10,000 nits. A D65 10,000 nit white is (1.0, 1.0, 1.0). + +The **DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P709** colorspace expects the swapbuffer content to be created with Rec. 709 color primaries with a D65 white point, but encoded with the PQ (ST.2084) curve. The **DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_D65P3** colorspace expects the swapbuffer content to be created with P3 color primaries with a D65 white point, but encoded with the PQ (ST.2084) curve and not with a power 1.0/2.6 curve or sRGB. This is distinct from DCI_P3, which uses a different encoding and white point. The **DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020** colorspace expects the swapbuffer content to be created with Rec. 2020 color primaries with a D65 white point and encoded with a PQ (ST.2084) curve. + +*ScaleFilter* +Type: [D3D12XBOX_PRESENT_PLANE_SCALE_FILTER](../enums/d3d12xbox_present_plane_scale_filter.md) + +Preferred scale filter to employ when upsampling from a plane source to a larger display destination. The filter provided is merely a request and is not guaranteed to be applied on output. Scale filter is ignored on Xbox Series X|S. + +*ExtendedDescCount* +Type: UINT + +Number of extended plane descriptions provided in the *pExtendedDescs* list. + +*pExtendedDescs* +Type: [D3D12XBOX_PRESENT_PLANE_DESC](./d3d12xbox_present_plane_desc.md)* + +Optional pointer to the first element in an array of extended plane descriptions. Use the pointer for additional customization of the plane used in presentation. + +*Flags* +Type: [D3D12XBOX_PRESENT_PLANE_FLAGS](../enums/d3d12xbox_present_plane_flags.md) + +A set of flags used to provide additional control over the plane's composition and display. + + +## Remarks + +Titles can set up two display planes which can be used for compositing UI/HUD onto its scene automatically. In this case compositing is done with the display hardware at no extra GPU, memory or latency costs. For more information on how to set this up, refer to [Hardware overlays and swap resources](../features\graphics\directx/hardware-overlays.md) + + +## Requirements + +**Header:** d3d12_x.h + +**Supported platforms:** Xbox One family + +## See also + +[PresentX](../interfaces/id3d12commandqueue/methods/id3d12commandqueue_presentx.md) + + + diff --git a/docs/gdkx/d3dx12_xs.h b/docs/gdkx/d3dx12_xs.h new file mode 100644 index 0000000..0fdf61a --- /dev/null +++ b/docs/gdkx/d3dx12_xs.h @@ -0,0 +1,4778 @@ +////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// File: d3dx12_xs.h +// Content: D3DX12 utility library for Xbox Series X|S +// +////////////////////////////////////////////////////////////////////////////// +// XBOX integrate from +// src\onecoreuap\windows\published\d3d12\d3dx12.w + +#ifndef __D3DX12_XBOX_H__ +#define __D3DX12_XBOX_H__ + +#include "d3d12_xs.h" + +#if defined( __cplusplus ) + +#pragma warning( push ) + +// Implicit structure padding, enumerator not handled by case label, 'symbol' is +// not defined as a preprocessor macro, replacing with '0' for 'directives' + +#pragma warning( disable : 4820 4061 4668 ) + +struct CD3DX12_DEFAULT {}; +extern const DECLSPEC_SELECTANY CD3DX12_DEFAULT D3D12_DEFAULT; + +//------------------------------------------------------------------------------------------------ +inline bool operator==( const D3D12_VIEWPORT& l, const D3D12_VIEWPORT& r ) noexcept +{ + return l.TopLeftX == r.TopLeftX && l.TopLeftY == r.TopLeftY && l.Width == r.Width && + l.Height == r.Height && l.MinDepth == r.MinDepth && l.MaxDepth == r.MaxDepth; +} + +//------------------------------------------------------------------------------------------------ +inline bool operator!=( const D3D12_VIEWPORT& l, const D3D12_VIEWPORT& r ) noexcept +{ return !( l == r ); } + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_RECT : public D3D12_RECT +{ + CD3DX12_RECT() = default; + explicit CD3DX12_RECT( const D3D12_RECT& o ) noexcept : + D3D12_RECT( o ) + {} + explicit CD3DX12_RECT( + LONG Left, + LONG Top, + LONG Right, + LONG Bottom ) noexcept + { + left = Left; + top = Top; + right = Right; + bottom = Bottom; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_VIEWPORT : public D3D12_VIEWPORT +{ + CD3DX12_VIEWPORT() = default; + explicit CD3DX12_VIEWPORT( const D3D12_VIEWPORT& o ) noexcept : + D3D12_VIEWPORT( o ) + {} + explicit CD3DX12_VIEWPORT( + FLOAT topLeftX, + FLOAT topLeftY, + FLOAT width, + FLOAT height, + FLOAT minDepth = D3D12_MIN_DEPTH, + FLOAT maxDepth = D3D12_MAX_DEPTH ) noexcept + { + TopLeftX = topLeftX; + TopLeftY = topLeftY; + Width = width; + Height = height; + MinDepth = minDepth; + MaxDepth = maxDepth; + } + explicit CD3DX12_VIEWPORT( + _In_ ID3D12Resource* pResource, + UINT mipSlice = 0, + FLOAT topLeftX = 0.0f, + FLOAT topLeftY = 0.0f, + FLOAT minDepth = D3D12_MIN_DEPTH, + FLOAT maxDepth = D3D12_MAX_DEPTH ) noexcept + { + const auto Desc = pResource->GetDesc(); + const UINT64 SubresourceWidth = Desc.Width >> mipSlice; + const UINT64 SubresourceHeight = Desc.Height >> mipSlice; + switch (Desc.Dimension) + { + case D3D12_RESOURCE_DIMENSION_BUFFER: + TopLeftX = topLeftX; + TopLeftY = 0.0f; + Width = float(Desc.Width) - topLeftX; + Height = 1.0f; + break; + case D3D12_RESOURCE_DIMENSION_TEXTURE1D: + TopLeftX = topLeftX; + TopLeftY = 0.0f; + Width = (SubresourceWidth ? float(SubresourceWidth) : 1.0f) - topLeftX; + Height = 1.0f; + break; + case D3D12_RESOURCE_DIMENSION_TEXTURE2D: + case D3D12_RESOURCE_DIMENSION_TEXTURE3D: + TopLeftX = topLeftX; + TopLeftY = topLeftY; + Width = (SubresourceWidth ? float(SubresourceWidth) : 1.0f) - topLeftX; + Height = (SubresourceHeight ? float(SubresourceHeight) : 1.0f) - topLeftY; + break; + default: break; + } + + MinDepth = minDepth; + MaxDepth = maxDepth; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_BOX : public D3D12_BOX +{ + CD3DX12_BOX() = default; + explicit CD3DX12_BOX( const D3D12_BOX& o ) noexcept : + D3D12_BOX( o ) + {} + explicit CD3DX12_BOX( + LONG Left, + LONG Right ) noexcept + { + left = static_cast(Left); + top = 0; + front = 0; + right = static_cast(Right); + bottom = 1; + back = 1; + } + explicit CD3DX12_BOX( + LONG Left, + LONG Top, + LONG Right, + LONG Bottom ) noexcept + { + left = static_cast(Left); + top = static_cast(Top); + front = 0; + right = static_cast(Right); + bottom = static_cast(Bottom); + back = 1; + } + explicit CD3DX12_BOX( + LONG Left, + LONG Top, + LONG Front, + LONG Right, + LONG Bottom, + LONG Back ) noexcept + { + left = static_cast(Left); + top = static_cast(Top); + front = static_cast(Front); + right = static_cast(Right); + bottom = static_cast(Bottom); + back = static_cast(Back); + } +}; +inline bool operator==( const D3D12_BOX& l, const D3D12_BOX& r ) noexcept +{ + return l.left == r.left && l.top == r.top && l.front == r.front && + l.right == r.right && l.bottom == r.bottom && l.back == r.back; +} +inline bool operator!=( const D3D12_BOX& l, const D3D12_BOX& r ) noexcept +{ return !( l == r ); } + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_DEPTH_STENCIL_DESC : public D3D12_DEPTH_STENCIL_DESC +{ + CD3DX12_DEPTH_STENCIL_DESC() = default; + explicit CD3DX12_DEPTH_STENCIL_DESC( const D3D12_DEPTH_STENCIL_DESC& o ) noexcept : + D3D12_DEPTH_STENCIL_DESC( o ) + {} + explicit CD3DX12_DEPTH_STENCIL_DESC( CD3DX12_DEFAULT ) noexcept + { + DepthEnable = TRUE; + DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + DepthFunc = D3D12_COMPARISON_FUNC_LESS; + StencilEnable = FALSE; + StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp = + { D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS }; + FrontFace = defaultStencilOp; + BackFace = defaultStencilOp; + } + explicit CD3DX12_DEPTH_STENCIL_DESC( + BOOL depthEnable, + D3D12_DEPTH_WRITE_MASK depthWriteMask, + D3D12_COMPARISON_FUNC depthFunc, + BOOL stencilEnable, + UINT8 stencilReadMask, + UINT8 stencilWriteMask, + D3D12_STENCIL_OP frontStencilFailOp, + D3D12_STENCIL_OP frontStencilDepthFailOp, + D3D12_STENCIL_OP frontStencilPassOp, + D3D12_COMPARISON_FUNC frontStencilFunc, + D3D12_STENCIL_OP backStencilFailOp, + D3D12_STENCIL_OP backStencilDepthFailOp, + D3D12_STENCIL_OP backStencilPassOp, + D3D12_COMPARISON_FUNC backStencilFunc ) noexcept + { + DepthEnable = depthEnable; + DepthWriteMask = depthWriteMask; + DepthFunc = depthFunc; + StencilEnable = stencilEnable; + StencilReadMask = stencilReadMask; + StencilWriteMask = stencilWriteMask; + FrontFace.StencilFailOp = frontStencilFailOp; + FrontFace.StencilDepthFailOp = frontStencilDepthFailOp; + FrontFace.StencilPassOp = frontStencilPassOp; + FrontFace.StencilFunc = frontStencilFunc; + BackFace.StencilFailOp = backStencilFailOp; + BackFace.StencilDepthFailOp = backStencilDepthFailOp; + BackFace.StencilPassOp = backStencilPassOp; + BackFace.StencilFunc = backStencilFunc; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_DEPTH_STENCIL_DESC1 : public D3D12_DEPTH_STENCIL_DESC1 +{ + CD3DX12_DEPTH_STENCIL_DESC1() = default; + explicit CD3DX12_DEPTH_STENCIL_DESC1( const D3D12_DEPTH_STENCIL_DESC1& o ) noexcept : + D3D12_DEPTH_STENCIL_DESC1( o ) + {} + explicit CD3DX12_DEPTH_STENCIL_DESC1( const D3D12_DEPTH_STENCIL_DESC& o ) noexcept + { + DepthEnable = o.DepthEnable; + DepthWriteMask = o.DepthWriteMask; + DepthFunc = o.DepthFunc; + StencilEnable = o.StencilEnable; + StencilReadMask = o.StencilReadMask; + StencilWriteMask = o.StencilWriteMask; + FrontFace.StencilFailOp = o.FrontFace.StencilFailOp; + FrontFace.StencilDepthFailOp = o.FrontFace.StencilDepthFailOp; + FrontFace.StencilPassOp = o.FrontFace.StencilPassOp; + FrontFace.StencilFunc = o.FrontFace.StencilFunc; + BackFace.StencilFailOp = o.BackFace.StencilFailOp; + BackFace.StencilDepthFailOp = o.BackFace.StencilDepthFailOp; + BackFace.StencilPassOp = o.BackFace.StencilPassOp; + BackFace.StencilFunc = o.BackFace.StencilFunc; + DepthBoundsTestEnable = FALSE; + } + explicit CD3DX12_DEPTH_STENCIL_DESC1( CD3DX12_DEFAULT ) noexcept + { + DepthEnable = TRUE; + DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + DepthFunc = D3D12_COMPARISON_FUNC_LESS; + StencilEnable = FALSE; + StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + const D3D12_DEPTH_STENCILOP_DESC defaultStencilOp = + { D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS }; + FrontFace = defaultStencilOp; + BackFace = defaultStencilOp; + DepthBoundsTestEnable = FALSE; + } + explicit CD3DX12_DEPTH_STENCIL_DESC1( + BOOL depthEnable, + D3D12_DEPTH_WRITE_MASK depthWriteMask, + D3D12_COMPARISON_FUNC depthFunc, + BOOL stencilEnable, + UINT8 stencilReadMask, + UINT8 stencilWriteMask, + D3D12_STENCIL_OP frontStencilFailOp, + D3D12_STENCIL_OP frontStencilDepthFailOp, + D3D12_STENCIL_OP frontStencilPassOp, + D3D12_COMPARISON_FUNC frontStencilFunc, + D3D12_STENCIL_OP backStencilFailOp, + D3D12_STENCIL_OP backStencilDepthFailOp, + D3D12_STENCIL_OP backStencilPassOp, + D3D12_COMPARISON_FUNC backStencilFunc, + BOOL depthBoundsTestEnable ) noexcept + { + DepthEnable = depthEnable; + DepthWriteMask = depthWriteMask; + DepthFunc = depthFunc; + StencilEnable = stencilEnable; + StencilReadMask = stencilReadMask; + StencilWriteMask = stencilWriteMask; + FrontFace.StencilFailOp = frontStencilFailOp; + FrontFace.StencilDepthFailOp = frontStencilDepthFailOp; + FrontFace.StencilPassOp = frontStencilPassOp; + FrontFace.StencilFunc = frontStencilFunc; + BackFace.StencilFailOp = backStencilFailOp; + BackFace.StencilDepthFailOp = backStencilDepthFailOp; + BackFace.StencilPassOp = backStencilPassOp; + BackFace.StencilFunc = backStencilFunc; + DepthBoundsTestEnable = depthBoundsTestEnable; + } + operator D3D12_DEPTH_STENCIL_DESC() const noexcept + { + D3D12_DEPTH_STENCIL_DESC D; + D.DepthEnable = DepthEnable; + D.DepthWriteMask = DepthWriteMask; + D.DepthFunc = DepthFunc; + D.StencilEnable = StencilEnable; + D.StencilReadMask = StencilReadMask; + D.StencilWriteMask = StencilWriteMask; + D.FrontFace.StencilFailOp = FrontFace.StencilFailOp; + D.FrontFace.StencilDepthFailOp = FrontFace.StencilDepthFailOp; + D.FrontFace.StencilPassOp = FrontFace.StencilPassOp; + D.FrontFace.StencilFunc = FrontFace.StencilFunc; + D.BackFace.StencilFailOp = BackFace.StencilFailOp; + D.BackFace.StencilDepthFailOp = BackFace.StencilDepthFailOp; + D.BackFace.StencilPassOp = BackFace.StencilPassOp; + D.BackFace.StencilFunc = BackFace.StencilFunc; + return D; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_BLEND_DESC : public D3D12_BLEND_DESC +{ + CD3DX12_BLEND_DESC() = default; + explicit CD3DX12_BLEND_DESC( const D3D12_BLEND_DESC& o ) noexcept : + D3D12_BLEND_DESC( o ) + {} + explicit CD3DX12_BLEND_DESC( CD3DX12_DEFAULT ) noexcept + { + AlphaToCoverageEnable = FALSE; + IndependentBlendEnable = FALSE; + const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = + { + FALSE,FALSE, + D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, + D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, + D3D12_LOGIC_OP_NOOP, + D3D12_COLOR_WRITE_ENABLE_ALL, + }; + for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) + RenderTarget[ i ] = defaultRenderTargetBlendDesc; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_RASTERIZER_DESC : public D3D12_RASTERIZER_DESC +{ + CD3DX12_RASTERIZER_DESC() = default; + explicit CD3DX12_RASTERIZER_DESC( const D3D12_RASTERIZER_DESC& o ) noexcept : + D3D12_RASTERIZER_DESC( o ) + {} + explicit CD3DX12_RASTERIZER_DESC( CD3DX12_DEFAULT ) noexcept + { + FillMode = D3D12_FILL_MODE_SOLID; + CullMode = D3D12_CULL_MODE_BACK; + FrontCounterClockwise = FALSE; + DepthBias = D3D12_DEFAULT_DEPTH_BIAS; + DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP; + SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; + DepthClipEnable = TRUE; + MultisampleEnable = FALSE; + AntialiasedLineEnable = FALSE; + ForcedSampleCount = 0; + ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + } + explicit CD3DX12_RASTERIZER_DESC( + D3D12_FILL_MODE fillMode, + D3D12_CULL_MODE cullMode, + BOOL frontCounterClockwise, + INT depthBias, + FLOAT depthBiasClamp, + FLOAT slopeScaledDepthBias, + BOOL depthClipEnable, + BOOL multisampleEnable, + BOOL antialiasedLineEnable, + UINT forcedSampleCount, + D3D12_CONSERVATIVE_RASTERIZATION_MODE conservativeRaster) noexcept + { + FillMode = fillMode; + CullMode = cullMode; + FrontCounterClockwise = frontCounterClockwise; + DepthBias = depthBias; + DepthBiasClamp = depthBiasClamp; + SlopeScaledDepthBias = slopeScaledDepthBias; + DepthClipEnable = depthClipEnable; + MultisampleEnable = multisampleEnable; + AntialiasedLineEnable = antialiasedLineEnable; + ForcedSampleCount = forcedSampleCount; + ConservativeRaster = conservativeRaster; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_RESOURCE_ALLOCATION_INFO : public D3D12_RESOURCE_ALLOCATION_INFO +{ + CD3DX12_RESOURCE_ALLOCATION_INFO() = default; + explicit CD3DX12_RESOURCE_ALLOCATION_INFO( const D3D12_RESOURCE_ALLOCATION_INFO& o ) noexcept : + D3D12_RESOURCE_ALLOCATION_INFO( o ) + {} + CD3DX12_RESOURCE_ALLOCATION_INFO( + UINT64 size, + UINT64 alignment ) noexcept + { + SizeInBytes = size; + Alignment = alignment; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_HEAP_PROPERTIES : public D3D12_HEAP_PROPERTIES +{ + CD3DX12_HEAP_PROPERTIES() = default; + explicit CD3DX12_HEAP_PROPERTIES(const D3D12_HEAP_PROPERTIES &o) noexcept : + D3D12_HEAP_PROPERTIES(o) + {} + CD3DX12_HEAP_PROPERTIES( + D3D12_CPU_PAGE_PROPERTY cpuPageProperty, + D3D12_MEMORY_POOL memoryPoolPreference, + UINT creationNodeMask = 1, + UINT nodeMask = 1 ) noexcept + { + Type = D3D12_HEAP_TYPE_CUSTOM; + CPUPageProperty = cpuPageProperty; + MemoryPoolPreference = memoryPoolPreference; + CreationNodeMask = creationNodeMask; + VisibleNodeMask = nodeMask; + } + explicit CD3DX12_HEAP_PROPERTIES( + D3D12_HEAP_TYPE type, + UINT creationNodeMask = 1, + UINT nodeMask = 1 ) noexcept + { + Type = type; + CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + CreationNodeMask = creationNodeMask; + VisibleNodeMask = nodeMask; + } + bool IsCPUAccessible() const noexcept + { + return Type == D3D12_HEAP_TYPE_UPLOAD || Type == D3D12_HEAP_TYPE_READBACK || (Type == D3D12_HEAP_TYPE_CUSTOM && + (CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE || CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); + } +}; +inline bool operator==( const D3D12_HEAP_PROPERTIES& l, const D3D12_HEAP_PROPERTIES& r ) noexcept +{ + return l.Type == r.Type && l.CPUPageProperty == r.CPUPageProperty && + l.MemoryPoolPreference == r.MemoryPoolPreference && + l.CreationNodeMask == r.CreationNodeMask && + l.VisibleNodeMask == r.VisibleNodeMask; +} +inline bool operator!=( const D3D12_HEAP_PROPERTIES& l, const D3D12_HEAP_PROPERTIES& r ) noexcept +{ return !( l == r ); } + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_HEAP_DESC : public D3D12_HEAP_DESC +{ + CD3DX12_HEAP_DESC() = default; + explicit CD3DX12_HEAP_DESC(const D3D12_HEAP_DESC &o) noexcept : + D3D12_HEAP_DESC(o) + {} + CD3DX12_HEAP_DESC( + UINT64 size, + D3D12_HEAP_PROPERTIES properties, + UINT64 alignment = 0, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) noexcept + { + SizeInBytes = size; + Properties = properties; + Alignment = alignment; + Flags = flags; + } + CD3DX12_HEAP_DESC( + UINT64 size, + D3D12_HEAP_TYPE type, + UINT64 alignment = 0, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) noexcept + { + SizeInBytes = size; + Properties = CD3DX12_HEAP_PROPERTIES( type ); + Alignment = alignment; + Flags = flags; + } + CD3DX12_HEAP_DESC( + UINT64 size, + D3D12_CPU_PAGE_PROPERTY cpuPageProperty, + D3D12_MEMORY_POOL memoryPoolPreference, + UINT64 alignment = 0, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) noexcept + { + SizeInBytes = size; + Properties = CD3DX12_HEAP_PROPERTIES( cpuPageProperty, memoryPoolPreference ); + Alignment = alignment; + Flags = flags; + } + CD3DX12_HEAP_DESC( + const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, + D3D12_HEAP_PROPERTIES properties, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) noexcept + { + SizeInBytes = resAllocInfo.SizeInBytes; + Properties = properties; + Alignment = resAllocInfo.Alignment; + Flags = flags; + } + CD3DX12_HEAP_DESC( + const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, + D3D12_HEAP_TYPE type, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) noexcept + { + SizeInBytes = resAllocInfo.SizeInBytes; + Properties = CD3DX12_HEAP_PROPERTIES( type ); + Alignment = resAllocInfo.Alignment; + Flags = flags; + } + CD3DX12_HEAP_DESC( + const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, + D3D12_CPU_PAGE_PROPERTY cpuPageProperty, + D3D12_MEMORY_POOL memoryPoolPreference, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE ) noexcept + { + SizeInBytes = resAllocInfo.SizeInBytes; + Properties = CD3DX12_HEAP_PROPERTIES( cpuPageProperty, memoryPoolPreference ); + Alignment = resAllocInfo.Alignment; + Flags = flags; + } + bool IsCPUAccessible() const noexcept + { return static_cast< const CD3DX12_HEAP_PROPERTIES* >( &Properties )->IsCPUAccessible(); } +}; +inline bool operator==( const D3D12_HEAP_DESC& l, const D3D12_HEAP_DESC& r ) noexcept +{ + return l.SizeInBytes == r.SizeInBytes && + l.Properties == r.Properties && + l.Alignment == r.Alignment && + l.Flags == r.Flags; +} +inline bool operator!=( const D3D12_HEAP_DESC& l, const D3D12_HEAP_DESC& r ) noexcept +{ return !( l == r ); } + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_CLEAR_VALUE : public D3D12_CLEAR_VALUE +{ + CD3DX12_CLEAR_VALUE() = default; + explicit CD3DX12_CLEAR_VALUE(const D3D12_CLEAR_VALUE &o) noexcept : + D3D12_CLEAR_VALUE(o) + {} + CD3DX12_CLEAR_VALUE( + DXGI_FORMAT format, + const FLOAT color[4] ) noexcept + { + Format = format; + memcpy( Color, color, sizeof( Color ) ); + } + CD3DX12_CLEAR_VALUE( + DXGI_FORMAT format, + FLOAT depth, + UINT8 stencil ) noexcept + { + Format = format; + memset( &Color, 0, sizeof( Color ) ); + /* Use memcpy to preserve NAN values */ + memcpy( &DepthStencil.Depth, &depth, sizeof( depth ) ); + DepthStencil.Stencil = stencil; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_RANGE : public D3D12_RANGE +{ + CD3DX12_RANGE() = default; + explicit CD3DX12_RANGE(const D3D12_RANGE &o) noexcept : + D3D12_RANGE(o) + {} + CD3DX12_RANGE( + SIZE_T begin, + SIZE_T end ) noexcept + { + Begin = begin; + End = end; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_RANGE_UINT64 : public D3D12_RANGE_UINT64 +{ + CD3DX12_RANGE_UINT64() = default; + explicit CD3DX12_RANGE_UINT64(const D3D12_RANGE_UINT64 &o) noexcept : + D3D12_RANGE_UINT64(o) + {} + CD3DX12_RANGE_UINT64( + UINT64 begin, + UINT64 end ) noexcept + { + Begin = begin; + End = end; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_SUBRESOURCE_RANGE_UINT64 : public D3D12_SUBRESOURCE_RANGE_UINT64 +{ + CD3DX12_SUBRESOURCE_RANGE_UINT64() = default; + explicit CD3DX12_SUBRESOURCE_RANGE_UINT64(const D3D12_SUBRESOURCE_RANGE_UINT64 &o) noexcept : + D3D12_SUBRESOURCE_RANGE_UINT64(o) + {} + CD3DX12_SUBRESOURCE_RANGE_UINT64( + UINT subresource, + const D3D12_RANGE_UINT64& range ) noexcept + { + Subresource = subresource; + Range = range; + } + CD3DX12_SUBRESOURCE_RANGE_UINT64( + UINT subresource, + UINT64 begin, + UINT64 end ) noexcept + { + Subresource = subresource; + Range.Begin = begin; + Range.End = end; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_SHADER_BYTECODE : public D3D12_SHADER_BYTECODE +{ + CD3DX12_SHADER_BYTECODE() = default; + explicit CD3DX12_SHADER_BYTECODE(const D3D12_SHADER_BYTECODE &o) noexcept : + D3D12_SHADER_BYTECODE(o) + {} + CD3DX12_SHADER_BYTECODE( + _In_ ID3DBlob* pShaderBlob ) noexcept + { + pShaderBytecode = pShaderBlob->GetBufferPointer(); + BytecodeLength = pShaderBlob->GetBufferSize(); + } + CD3DX12_SHADER_BYTECODE( + const void* _pShaderBytecode, + SIZE_T bytecodeLength ) noexcept + { + pShaderBytecode = _pShaderBytecode; + BytecodeLength = bytecodeLength; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_TILED_RESOURCE_COORDINATE : public D3D12_TILED_RESOURCE_COORDINATE +{ + CD3DX12_TILED_RESOURCE_COORDINATE() = default; + explicit CD3DX12_TILED_RESOURCE_COORDINATE(const D3D12_TILED_RESOURCE_COORDINATE &o) noexcept : + D3D12_TILED_RESOURCE_COORDINATE(o) + {} + CD3DX12_TILED_RESOURCE_COORDINATE( + UINT x, + UINT y, + UINT z, + UINT subresource ) noexcept + { + X = x; + Y = y; + Z = z; + Subresource = subresource; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_TILE_REGION_SIZE : public D3D12_TILE_REGION_SIZE +{ + CD3DX12_TILE_REGION_SIZE() = default; + explicit CD3DX12_TILE_REGION_SIZE(const D3D12_TILE_REGION_SIZE &o) noexcept : + D3D12_TILE_REGION_SIZE(o) + {} + CD3DX12_TILE_REGION_SIZE( + UINT numTiles, + BOOL useBox, + UINT width, + UINT16 height, + UINT16 depth ) noexcept + { + NumTiles = numTiles; + UseBox = useBox; + Width = width; + Height = height; + Depth = depth; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_SUBRESOURCE_TILING : public D3D12_SUBRESOURCE_TILING +{ + CD3DX12_SUBRESOURCE_TILING() = default; + explicit CD3DX12_SUBRESOURCE_TILING(const D3D12_SUBRESOURCE_TILING &o) noexcept : + D3D12_SUBRESOURCE_TILING(o) + {} + CD3DX12_SUBRESOURCE_TILING( + UINT widthInTiles, + UINT16 heightInTiles, + UINT16 depthInTiles, + UINT startTileIndexInOverallResource ) noexcept + { + WidthInTiles = widthInTiles; + HeightInTiles = heightInTiles; + DepthInTiles = depthInTiles; + StartTileIndexInOverallResource = startTileIndexInOverallResource; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_TILE_SHAPE : public D3D12_TILE_SHAPE +{ + CD3DX12_TILE_SHAPE() = default; + explicit CD3DX12_TILE_SHAPE(const D3D12_TILE_SHAPE &o) noexcept : + D3D12_TILE_SHAPE(o) + {} + CD3DX12_TILE_SHAPE( + UINT widthInTexels, + UINT heightInTexels, + UINT depthInTexels ) noexcept + { + WidthInTexels = widthInTexels; + HeightInTexels = heightInTexels; + DepthInTexels = depthInTexels; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_RESOURCE_BARRIER : public D3D12_RESOURCE_BARRIER +{ + CD3DX12_RESOURCE_BARRIER() = default; + explicit CD3DX12_RESOURCE_BARRIER(const D3D12_RESOURCE_BARRIER &o) noexcept : + D3D12_RESOURCE_BARRIER(o) + {} + static inline CD3DX12_RESOURCE_BARRIER Transition( + _In_ ID3D12Resource* pResource, + D3D12_RESOURCE_STATES stateBefore, + D3D12_RESOURCE_STATES stateAfter, + UINT subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_BARRIER_FLAGS flags = D3D12_RESOURCE_BARRIER_FLAG_NONE) noexcept + { + CD3DX12_RESOURCE_BARRIER result = {}; + D3D12_RESOURCE_BARRIER &barrier = result; + result.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + result.Flags = flags; + barrier.Transition.pResource = pResource; + barrier.Transition.StateBefore = stateBefore; + barrier.Transition.StateAfter = stateAfter; + barrier.Transition.Subresource = subresource; + return result; + } + static inline CD3DX12_RESOURCE_BARRIER Aliasing( + _In_opt_ ID3D12Resource* pResourceBefore, + _In_opt_ ID3D12Resource* pResourceAfter) noexcept + { + CD3DX12_RESOURCE_BARRIER result = {}; + D3D12_RESOURCE_BARRIER &barrier = result; + result.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + barrier.Aliasing.pResourceBefore = pResourceBefore; + barrier.Aliasing.pResourceAfter = pResourceAfter; + return result; + } + static inline CD3DX12_RESOURCE_BARRIER UAV( + _In_opt_ ID3D12Resource* pResource) noexcept + { + CD3DX12_RESOURCE_BARRIER result = {}; + D3D12_RESOURCE_BARRIER &barrier = result; + result.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.UAV.pResource = pResource; + return result; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_PACKED_MIP_INFO : public D3D12_PACKED_MIP_INFO +{ + CD3DX12_PACKED_MIP_INFO() = default; + explicit CD3DX12_PACKED_MIP_INFO(const D3D12_PACKED_MIP_INFO &o) noexcept : + D3D12_PACKED_MIP_INFO(o) + {} + CD3DX12_PACKED_MIP_INFO( + UINT8 numStandardMips, + UINT8 numPackedMips, + UINT numTilesForPackedMips, + UINT startTileIndexInOverallResource ) noexcept + { + NumStandardMips = numStandardMips; + NumPackedMips = numPackedMips; + NumTilesForPackedMips = numTilesForPackedMips; + StartTileIndexInOverallResource = startTileIndexInOverallResource; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_SUBRESOURCE_FOOTPRINT : public D3D12_SUBRESOURCE_FOOTPRINT +{ + CD3DX12_SUBRESOURCE_FOOTPRINT() = default; + explicit CD3DX12_SUBRESOURCE_FOOTPRINT(const D3D12_SUBRESOURCE_FOOTPRINT &o) noexcept : + D3D12_SUBRESOURCE_FOOTPRINT(o) + {} + CD3DX12_SUBRESOURCE_FOOTPRINT( + DXGI_FORMAT format, + UINT width, + UINT height, + UINT depth, + UINT rowPitch ) noexcept + { + Format = format; + Width = width; + Height = height; + Depth = depth; + RowPitch = rowPitch; + } + explicit CD3DX12_SUBRESOURCE_FOOTPRINT( + const D3D12_RESOURCE_DESC& resDesc, + UINT rowPitch ) noexcept + { + Format = resDesc.Format; + Width = UINT( resDesc.Width ); + Height = resDesc.Height; + Depth = (resDesc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? resDesc.DepthOrArraySize : 1u); + RowPitch = rowPitch; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_TEXTURE_COPY_LOCATION : public D3D12_TEXTURE_COPY_LOCATION +{ + CD3DX12_TEXTURE_COPY_LOCATION() = default; + explicit CD3DX12_TEXTURE_COPY_LOCATION(const D3D12_TEXTURE_COPY_LOCATION &o) noexcept : + D3D12_TEXTURE_COPY_LOCATION(o) + {} + CD3DX12_TEXTURE_COPY_LOCATION(_In_ ID3D12Resource* pRes) noexcept + { + pResource = pRes; + Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + PlacedFootprint = {}; + } + CD3DX12_TEXTURE_COPY_LOCATION(_In_ ID3D12Resource* pRes, D3D12_PLACED_SUBRESOURCE_FOOTPRINT const& Footprint) noexcept + { + pResource = pRes; + Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + PlacedFootprint = Footprint; + } + CD3DX12_TEXTURE_COPY_LOCATION(_In_ ID3D12Resource* pRes, UINT Sub) noexcept + { + pResource = pRes; + Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + PlacedFootprint = {}; + SubresourceIndex = Sub; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_DESCRIPTOR_RANGE : public D3D12_DESCRIPTOR_RANGE +{ + CD3DX12_DESCRIPTOR_RANGE() = default; + explicit CD3DX12_DESCRIPTOR_RANGE(const D3D12_DESCRIPTOR_RANGE &o) noexcept : + D3D12_DESCRIPTOR_RANGE(o) + {} + CD3DX12_DESCRIPTOR_RANGE( + D3D12_DESCRIPTOR_RANGE_TYPE rangeType, + UINT numDescriptors, + UINT baseShaderRegister, + UINT registerSpace = 0, + UINT offsetInDescriptorsFromTableStart = + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) noexcept + { + Init(rangeType, numDescriptors, baseShaderRegister, registerSpace, offsetInDescriptorsFromTableStart); + } + + inline void Init( + D3D12_DESCRIPTOR_RANGE_TYPE rangeType, + UINT numDescriptors, + UINT baseShaderRegister, + UINT registerSpace = 0, + UINT offsetInDescriptorsFromTableStart = + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) noexcept + { + Init(*this, rangeType, numDescriptors, baseShaderRegister, registerSpace, offsetInDescriptorsFromTableStart); + } + + static inline void Init( + _Out_ D3D12_DESCRIPTOR_RANGE &range, + D3D12_DESCRIPTOR_RANGE_TYPE rangeType, + UINT numDescriptors, + UINT baseShaderRegister, + UINT registerSpace = 0, + UINT offsetInDescriptorsFromTableStart = + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) noexcept + { + range.RangeType = rangeType; + range.NumDescriptors = numDescriptors; + range.BaseShaderRegister = baseShaderRegister; + range.RegisterSpace = registerSpace; + range.OffsetInDescriptorsFromTableStart = offsetInDescriptorsFromTableStart; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_ROOT_DESCRIPTOR_TABLE : public D3D12_ROOT_DESCRIPTOR_TABLE +{ + CD3DX12_ROOT_DESCRIPTOR_TABLE() = default; + explicit CD3DX12_ROOT_DESCRIPTOR_TABLE(const D3D12_ROOT_DESCRIPTOR_TABLE &o) noexcept : + D3D12_ROOT_DESCRIPTOR_TABLE(o) + {} + CD3DX12_ROOT_DESCRIPTOR_TABLE( + UINT numDescriptorRanges, + _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges) noexcept + { + Init(numDescriptorRanges, _pDescriptorRanges); + } + + inline void Init( + UINT numDescriptorRanges, + _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges) noexcept + { + Init(*this, numDescriptorRanges, _pDescriptorRanges); + } + + static inline void Init( + _Out_ D3D12_ROOT_DESCRIPTOR_TABLE &rootDescriptorTable, + UINT numDescriptorRanges, + _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges) noexcept + { + rootDescriptorTable.NumDescriptorRanges = numDescriptorRanges; + rootDescriptorTable.pDescriptorRanges = _pDescriptorRanges; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_ROOT_CONSTANTS : public D3D12_ROOT_CONSTANTS +{ + CD3DX12_ROOT_CONSTANTS() = default; + explicit CD3DX12_ROOT_CONSTANTS(const D3D12_ROOT_CONSTANTS &o) noexcept : + D3D12_ROOT_CONSTANTS(o) + {} + CD3DX12_ROOT_CONSTANTS( + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0) noexcept + { + Init(num32BitValues, shaderRegister, registerSpace); + } + + inline void Init( + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0) noexcept + { + Init(*this, num32BitValues, shaderRegister, registerSpace); + } + + static inline void Init( + _Out_ D3D12_ROOT_CONSTANTS &rootConstants, + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0) noexcept + { + rootConstants.Num32BitValues = num32BitValues; + rootConstants.ShaderRegister = shaderRegister; + rootConstants.RegisterSpace = registerSpace; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_ROOT_DESCRIPTOR : public D3D12_ROOT_DESCRIPTOR +{ + CD3DX12_ROOT_DESCRIPTOR() = default; + explicit CD3DX12_ROOT_DESCRIPTOR(const D3D12_ROOT_DESCRIPTOR &o) noexcept : + D3D12_ROOT_DESCRIPTOR(o) + {} + CD3DX12_ROOT_DESCRIPTOR( + UINT shaderRegister, + UINT registerSpace = 0) noexcept + { + Init(shaderRegister, registerSpace); + } + + inline void Init( + UINT shaderRegister, + UINT registerSpace = 0) noexcept + { + Init(*this, shaderRegister, registerSpace); + } + + static inline void Init(_Out_ D3D12_ROOT_DESCRIPTOR &table, UINT shaderRegister, UINT registerSpace = 0) noexcept + { + table.ShaderRegister = shaderRegister; + table.RegisterSpace = registerSpace; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_ROOT_PARAMETER : public D3D12_ROOT_PARAMETER +{ + CD3DX12_ROOT_PARAMETER() = default; + explicit CD3DX12_ROOT_PARAMETER(const D3D12_ROOT_PARAMETER &o) noexcept : + D3D12_ROOT_PARAMETER(o) + {} + + static inline void InitAsDescriptorTable( + _Out_ D3D12_ROOT_PARAMETER &rootParam, + UINT numDescriptorRanges, + _In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* pDescriptorRanges, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_DESCRIPTOR_TABLE::Init(rootParam.DescriptorTable, numDescriptorRanges, pDescriptorRanges); + } + + static inline void InitAsConstants( + _Out_ D3D12_ROOT_PARAMETER &rootParam, + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_CONSTANTS::Init(rootParam.Constants, num32BitValues, shaderRegister, registerSpace); + } + + static inline void InitAsConstantBufferView( + _Out_ D3D12_ROOT_PARAMETER &rootParam, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace); + } + + static inline void InitAsShaderResourceView( + _Out_ D3D12_ROOT_PARAMETER &rootParam, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace); + } + + static inline void InitAsUnorderedAccessView( + _Out_ D3D12_ROOT_PARAMETER &rootParam, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace); + } + + inline void InitAsDescriptorTable( + UINT numDescriptorRanges, + _In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* pDescriptorRanges, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsDescriptorTable(*this, numDescriptorRanges, pDescriptorRanges, visibility); + } + + inline void InitAsConstants( + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsConstants(*this, num32BitValues, shaderRegister, registerSpace, visibility); + } + + inline void InitAsConstantBufferView( + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsConstantBufferView(*this, shaderRegister, registerSpace, visibility); + } + + inline void InitAsShaderResourceView( + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsShaderResourceView(*this, shaderRegister, registerSpace, visibility); + } + + inline void InitAsUnorderedAccessView( + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsUnorderedAccessView(*this, shaderRegister, registerSpace, visibility); + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_STATIC_SAMPLER_DESC : public D3D12_STATIC_SAMPLER_DESC +{ + CD3DX12_STATIC_SAMPLER_DESC() = default; + explicit CD3DX12_STATIC_SAMPLER_DESC(const D3D12_STATIC_SAMPLER_DESC &o) noexcept : + D3D12_STATIC_SAMPLER_DESC(o) + {} + CD3DX12_STATIC_SAMPLER_DESC( + UINT shaderRegister, + D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, + D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + FLOAT mipLODBias = 0, + UINT maxAnisotropy = 16, + D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, + D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + FLOAT minLOD = 0.f, + FLOAT maxLOD = D3D12_FLOAT32_MAX, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + UINT registerSpace = 0) noexcept + { + Init( + shaderRegister, + filter, + addressU, + addressV, + addressW, + mipLODBias, + maxAnisotropy, + comparisonFunc, + borderColor, + minLOD, + maxLOD, + shaderVisibility, + registerSpace); + } + + static inline void Init( + _Out_ D3D12_STATIC_SAMPLER_DESC &samplerDesc, + UINT shaderRegister, + D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, + D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + FLOAT mipLODBias = 0, + UINT maxAnisotropy = 16, + D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, + D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + FLOAT minLOD = 0.f, + FLOAT maxLOD = D3D12_FLOAT32_MAX, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + UINT registerSpace = 0) noexcept + { + samplerDesc.ShaderRegister = shaderRegister; + samplerDesc.Filter = filter; + samplerDesc.AddressU = addressU; + samplerDesc.AddressV = addressV; + samplerDesc.AddressW = addressW; + samplerDesc.MipLODBias = mipLODBias; + samplerDesc.MaxAnisotropy = maxAnisotropy; + samplerDesc.ComparisonFunc = comparisonFunc; + samplerDesc.BorderColor = borderColor; + samplerDesc.MinLOD = minLOD; + samplerDesc.MaxLOD = maxLOD; + samplerDesc.ShaderVisibility = shaderVisibility; + samplerDesc.RegisterSpace = registerSpace; + } + inline void Init( + UINT shaderRegister, + D3D12_FILTER filter = D3D12_FILTER_ANISOTROPIC, + D3D12_TEXTURE_ADDRESS_MODE addressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + D3D12_TEXTURE_ADDRESS_MODE addressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP, + FLOAT mipLODBias = 0, + UINT maxAnisotropy = 16, + D3D12_COMPARISON_FUNC comparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, + D3D12_STATIC_BORDER_COLOR borderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + FLOAT minLOD = 0.f, + FLOAT maxLOD = D3D12_FLOAT32_MAX, + D3D12_SHADER_VISIBILITY shaderVisibility = D3D12_SHADER_VISIBILITY_ALL, + UINT registerSpace = 0) noexcept + { + Init( + *this, + shaderRegister, + filter, + addressU, + addressV, + addressW, + mipLODBias, + maxAnisotropy, + comparisonFunc, + borderColor, + minLOD, + maxLOD, + shaderVisibility, + registerSpace); + } + +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_ROOT_SIGNATURE_DESC : public D3D12_ROOT_SIGNATURE_DESC +{ + CD3DX12_ROOT_SIGNATURE_DESC() = default; + explicit CD3DX12_ROOT_SIGNATURE_DESC(const D3D12_ROOT_SIGNATURE_DESC &o) noexcept : + D3D12_ROOT_SIGNATURE_DESC(o) + {} + CD3DX12_ROOT_SIGNATURE_DESC( + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) noexcept + { + Init(numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); + } + CD3DX12_ROOT_SIGNATURE_DESC(CD3DX12_DEFAULT) noexcept + { + Init(0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE); + } + + inline void Init( + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) noexcept + { + Init(*this, numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); + } + + static inline void Init( + _Out_ D3D12_ROOT_SIGNATURE_DESC &desc, + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) noexcept + { + desc.NumParameters = numParameters; + desc.pParameters = _pParameters; + desc.NumStaticSamplers = numStaticSamplers; + desc.pStaticSamplers = _pStaticSamplers; + desc.Flags = flags; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_DESCRIPTOR_RANGE1 : public D3D12_DESCRIPTOR_RANGE1 +{ + CD3DX12_DESCRIPTOR_RANGE1() = default; + explicit CD3DX12_DESCRIPTOR_RANGE1(const D3D12_DESCRIPTOR_RANGE1 &o) noexcept : + D3D12_DESCRIPTOR_RANGE1(o) + {} + CD3DX12_DESCRIPTOR_RANGE1( + D3D12_DESCRIPTOR_RANGE_TYPE rangeType, + UINT numDescriptors, + UINT baseShaderRegister, + UINT registerSpace = 0, + D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE, + UINT offsetInDescriptorsFromTableStart = + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) noexcept + { + Init(rangeType, numDescriptors, baseShaderRegister, registerSpace, flags, offsetInDescriptorsFromTableStart); + } + + inline void Init( + D3D12_DESCRIPTOR_RANGE_TYPE rangeType, + UINT numDescriptors, + UINT baseShaderRegister, + UINT registerSpace = 0, + D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE, + UINT offsetInDescriptorsFromTableStart = + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) noexcept + { + Init(*this, rangeType, numDescriptors, baseShaderRegister, registerSpace, flags, offsetInDescriptorsFromTableStart); + } + + static inline void Init( + _Out_ D3D12_DESCRIPTOR_RANGE1 &range, + D3D12_DESCRIPTOR_RANGE_TYPE rangeType, + UINT numDescriptors, + UINT baseShaderRegister, + UINT registerSpace = 0, + D3D12_DESCRIPTOR_RANGE_FLAGS flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE, + UINT offsetInDescriptorsFromTableStart = + D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND) noexcept + { + range.RangeType = rangeType; + range.NumDescriptors = numDescriptors; + range.BaseShaderRegister = baseShaderRegister; + range.RegisterSpace = registerSpace; + range.Flags = flags; + range.OffsetInDescriptorsFromTableStart = offsetInDescriptorsFromTableStart; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_ROOT_DESCRIPTOR_TABLE1 : public D3D12_ROOT_DESCRIPTOR_TABLE1 +{ + CD3DX12_ROOT_DESCRIPTOR_TABLE1() = default; + explicit CD3DX12_ROOT_DESCRIPTOR_TABLE1(const D3D12_ROOT_DESCRIPTOR_TABLE1 &o) noexcept : + D3D12_ROOT_DESCRIPTOR_TABLE1(o) + {} + CD3DX12_ROOT_DESCRIPTOR_TABLE1( + UINT numDescriptorRanges, + _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE1* _pDescriptorRanges) noexcept + { + Init(numDescriptorRanges, _pDescriptorRanges); + } + + inline void Init( + UINT numDescriptorRanges, + _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE1* _pDescriptorRanges) noexcept + { + Init(*this, numDescriptorRanges, _pDescriptorRanges); + } + + static inline void Init( + _Out_ D3D12_ROOT_DESCRIPTOR_TABLE1 &rootDescriptorTable, + UINT numDescriptorRanges, + _In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE1* _pDescriptorRanges) noexcept + { + rootDescriptorTable.NumDescriptorRanges = numDescriptorRanges; + rootDescriptorTable.pDescriptorRanges = _pDescriptorRanges; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_ROOT_DESCRIPTOR1 : public D3D12_ROOT_DESCRIPTOR1 +{ + CD3DX12_ROOT_DESCRIPTOR1() = default; + explicit CD3DX12_ROOT_DESCRIPTOR1(const D3D12_ROOT_DESCRIPTOR1 &o) noexcept : + D3D12_ROOT_DESCRIPTOR1(o) + {} + CD3DX12_ROOT_DESCRIPTOR1( + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_ROOT_DESCRIPTOR_FLAGS flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE) noexcept + { + Init(shaderRegister, registerSpace, flags); + } + + inline void Init( + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_ROOT_DESCRIPTOR_FLAGS flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE) noexcept + { + Init(*this, shaderRegister, registerSpace, flags); + } + + static inline void Init( + _Out_ D3D12_ROOT_DESCRIPTOR1 &table, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_ROOT_DESCRIPTOR_FLAGS flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE) noexcept + { + table.ShaderRegister = shaderRegister; + table.RegisterSpace = registerSpace; + table.Flags = flags; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_ROOT_PARAMETER1 : public D3D12_ROOT_PARAMETER1 +{ + CD3DX12_ROOT_PARAMETER1() = default; + explicit CD3DX12_ROOT_PARAMETER1(const D3D12_ROOT_PARAMETER1 &o) noexcept : + D3D12_ROOT_PARAMETER1(o) + {} + + static inline void InitAsDescriptorTable( + _Out_ D3D12_ROOT_PARAMETER1 &rootParam, + UINT numDescriptorRanges, + _In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE1* pDescriptorRanges, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_DESCRIPTOR_TABLE1::Init(rootParam.DescriptorTable, numDescriptorRanges, pDescriptorRanges); + } + + static inline void InitAsConstants( + _Out_ D3D12_ROOT_PARAMETER1 &rootParam, + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_CONSTANTS::Init(rootParam.Constants, num32BitValues, shaderRegister, registerSpace); + } + + static inline void InitAsConstantBufferView( + _Out_ D3D12_ROOT_PARAMETER1 &rootParam, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_ROOT_DESCRIPTOR_FLAGS flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_DESCRIPTOR1::Init(rootParam.Descriptor, shaderRegister, registerSpace, flags); + } + + static inline void InitAsShaderResourceView( + _Out_ D3D12_ROOT_PARAMETER1 &rootParam, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_ROOT_DESCRIPTOR_FLAGS flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_DESCRIPTOR1::Init(rootParam.Descriptor, shaderRegister, registerSpace, flags); + } + + static inline void InitAsUnorderedAccessView( + _Out_ D3D12_ROOT_PARAMETER1 &rootParam, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_ROOT_DESCRIPTOR_FLAGS flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + rootParam.ShaderVisibility = visibility; + CD3DX12_ROOT_DESCRIPTOR1::Init(rootParam.Descriptor, shaderRegister, registerSpace, flags); + } + + inline void InitAsDescriptorTable( + UINT numDescriptorRanges, + _In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE1* pDescriptorRanges, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsDescriptorTable(*this, numDescriptorRanges, pDescriptorRanges, visibility); + } + + inline void InitAsConstants( + UINT num32BitValues, + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsConstants(*this, num32BitValues, shaderRegister, registerSpace, visibility); + } + + inline void InitAsConstantBufferView( + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_ROOT_DESCRIPTOR_FLAGS flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsConstantBufferView(*this, shaderRegister, registerSpace, flags, visibility); + } + + inline void InitAsShaderResourceView( + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_ROOT_DESCRIPTOR_FLAGS flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsShaderResourceView(*this, shaderRegister, registerSpace, flags, visibility); + } + + inline void InitAsUnorderedAccessView( + UINT shaderRegister, + UINT registerSpace = 0, + D3D12_ROOT_DESCRIPTOR_FLAGS flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL) noexcept + { + InitAsUnorderedAccessView(*this, shaderRegister, registerSpace, flags, visibility); + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC : public D3D12_VERSIONED_ROOT_SIGNATURE_DESC +{ + CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC() = default; + explicit CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC &o) noexcept : + D3D12_VERSIONED_ROOT_SIGNATURE_DESC(o) + {} + explicit CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC(const D3D12_ROOT_SIGNATURE_DESC &o) noexcept + { + Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + Desc_1_0 = o; + } + explicit CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC(const D3D12_ROOT_SIGNATURE_DESC1 &o) noexcept + { + Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + Desc_1_1 = o; + } + CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC( + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) noexcept + { + Init_1_0(numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); + } + CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC( + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER1* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) noexcept + { + Init_1_1(numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); + } + CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC(CD3DX12_DEFAULT) noexcept + { + Init_1_1(0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE); + } + + inline void Init_1_0( + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) noexcept + { + Init_1_0(*this, numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); + } + + static inline void Init_1_0( + _Out_ D3D12_VERSIONED_ROOT_SIGNATURE_DESC &desc, + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) noexcept + { + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + desc.Desc_1_0.NumParameters = numParameters; + desc.Desc_1_0.pParameters = _pParameters; + desc.Desc_1_0.NumStaticSamplers = numStaticSamplers; + desc.Desc_1_0.pStaticSamplers = _pStaticSamplers; + desc.Desc_1_0.Flags = flags; + } + + inline void Init_1_1( + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER1* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) noexcept + { + Init_1_1(*this, numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags); + } + + static inline void Init_1_1( + _Out_ D3D12_VERSIONED_ROOT_SIGNATURE_DESC &desc, + UINT numParameters, + _In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER1* _pParameters, + UINT numStaticSamplers = 0, + _In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = nullptr, + D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) noexcept + { + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + desc.Desc_1_1.NumParameters = numParameters; + desc.Desc_1_1.pParameters = _pParameters; + desc.Desc_1_1.NumStaticSamplers = numStaticSamplers; + desc.Desc_1_1.pStaticSamplers = _pStaticSamplers; + desc.Desc_1_1.Flags = flags; + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_CPU_DESCRIPTOR_HANDLE : public D3D12_CPU_DESCRIPTOR_HANDLE +{ + CD3DX12_CPU_DESCRIPTOR_HANDLE() = default; + explicit CD3DX12_CPU_DESCRIPTOR_HANDLE(const D3D12_CPU_DESCRIPTOR_HANDLE &o) noexcept : + D3D12_CPU_DESCRIPTOR_HANDLE(o) + {} + CD3DX12_CPU_DESCRIPTOR_HANDLE(CD3DX12_DEFAULT) noexcept { ptr = 0; } + CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &other, INT offsetScaledByIncrementSize) noexcept + { + InitOffsetted(other, offsetScaledByIncrementSize); + } + CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &other, INT offsetInDescriptors, UINT descriptorIncrementSize) noexcept + { + InitOffsetted(other, offsetInDescriptors, descriptorIncrementSize); + } + CD3DX12_CPU_DESCRIPTOR_HANDLE& Offset(INT offsetInDescriptors, UINT descriptorIncrementSize) noexcept + { + ptr = SIZE_T(INT64(ptr) + INT64(offsetInDescriptors) * INT64(descriptorIncrementSize)); + return *this; + } + CD3DX12_CPU_DESCRIPTOR_HANDLE& Offset(INT offsetScaledByIncrementSize) noexcept + { + ptr = SIZE_T(INT64(ptr) + INT64(offsetScaledByIncrementSize)); + return *this; + } + bool operator==(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& other) const noexcept + { + return (ptr == other.ptr); + } + bool operator!=(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& other) const noexcept + { + return (ptr != other.ptr); + } + CD3DX12_CPU_DESCRIPTOR_HANDLE &operator=(const D3D12_CPU_DESCRIPTOR_HANDLE &other) noexcept + { + ptr = other.ptr; + return *this; + } + + inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) noexcept + { + InitOffsetted(*this, base, offsetScaledByIncrementSize); + } + + inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) noexcept + { + InitOffsetted(*this, base, offsetInDescriptors, descriptorIncrementSize); + } + + static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) noexcept + { + handle.ptr = SIZE_T(INT64(base.ptr) + INT64(offsetScaledByIncrementSize)); + } + + static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) noexcept + { + handle.ptr = SIZE_T(INT64(base.ptr) + INT64(offsetInDescriptors) * INT64(descriptorIncrementSize)); + } + + void* GetWritePointerX() const noexcept + { + return D3D12XboxGetWritePointer(*this); + } + + const void* GetCachedReadPointerX() const noexcept + { + return D3D12XboxGetCachedReadPointer(*this); + } +}; + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_GPU_DESCRIPTOR_HANDLE : public D3D12_GPU_DESCRIPTOR_HANDLE +{ + CD3DX12_GPU_DESCRIPTOR_HANDLE() = default; + explicit CD3DX12_GPU_DESCRIPTOR_HANDLE(const D3D12_GPU_DESCRIPTOR_HANDLE &o) noexcept : + D3D12_GPU_DESCRIPTOR_HANDLE(o) + {} + CD3DX12_GPU_DESCRIPTOR_HANDLE(CD3DX12_DEFAULT) noexcept { ptr = 0; } + CD3DX12_GPU_DESCRIPTOR_HANDLE(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &other, INT offsetScaledByIncrementSize) noexcept + { + InitOffsetted(other, offsetScaledByIncrementSize); + } + CD3DX12_GPU_DESCRIPTOR_HANDLE(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &other, INT offsetInDescriptors, UINT descriptorIncrementSize) noexcept + { + InitOffsetted(other, offsetInDescriptors, descriptorIncrementSize); + } + CD3DX12_GPU_DESCRIPTOR_HANDLE& Offset(INT offsetInDescriptors, UINT descriptorIncrementSize) noexcept + { + ptr = UINT64(INT64(ptr) + INT64(offsetInDescriptors) * INT64(descriptorIncrementSize)); + return *this; + } + CD3DX12_GPU_DESCRIPTOR_HANDLE& Offset(INT offsetScaledByIncrementSize) noexcept + { + ptr = UINT64(INT64(ptr) + INT64(offsetScaledByIncrementSize)); + return *this; + } + inline bool operator==(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE& other) const noexcept + { + return (ptr == other.ptr); + } + inline bool operator!=(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE& other) const noexcept + { + return (ptr != other.ptr); + } + CD3DX12_GPU_DESCRIPTOR_HANDLE &operator=(const D3D12_GPU_DESCRIPTOR_HANDLE &other) noexcept + { + ptr = other.ptr; + return *this; + } + + inline void InitOffsetted(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) noexcept + { + InitOffsetted(*this, base, offsetScaledByIncrementSize); + } + + inline void InitOffsetted(_In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) noexcept + { + InitOffsetted(*this, base, offsetInDescriptors, descriptorIncrementSize); + } + + static inline void InitOffsetted(_Out_ D3D12_GPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize) noexcept + { + handle.ptr = UINT64(INT64(base.ptr) + INT64(offsetScaledByIncrementSize)); + } + + static inline void InitOffsetted(_Out_ D3D12_GPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_GPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize) noexcept + { + handle.ptr = UINT64(INT64(base.ptr) + INT64(offsetInDescriptors) * INT64(descriptorIncrementSize)); + } + + D3D12_GPU_VIRTUAL_ADDRESS GetGpuVirtualAddressX() const noexcept + { + + return static_cast(ptr); + + } +}; + +//------------------------------------------------------------------------------------------------ +constexpr UINT D3D12CalcSubresource( UINT MipSlice, UINT ArraySlice, UINT PlaneSlice, UINT MipLevels, UINT ArraySize ) noexcept +{ + return MipSlice + ArraySlice * MipLevels + PlaneSlice * MipLevels * ArraySize; +} + +//------------------------------------------------------------------------------------------------ +template +inline void D3D12DecomposeSubresource( UINT Subresource, UINT MipLevels, UINT ArraySize, _Out_ T& MipSlice, _Out_ U& ArraySlice, _Out_ V& PlaneSlice ) noexcept +{ + MipSlice = static_cast(Subresource % MipLevels); + ArraySlice = static_cast((Subresource / MipLevels) % ArraySize); + PlaneSlice = static_cast(Subresource / (MipLevels * ArraySize)); +} + +//------------------------------------------------------------------------------------------------ +inline UINT8 D3D12GetFormatPlaneCount( + _In_ ID3D12Device* pDevice, + DXGI_FORMAT Format + ) noexcept +{ + D3D12_FEATURE_DATA_FORMAT_INFO formatInfo = { Format, 0 }; + if (FAILED(pDevice->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &formatInfo, sizeof(formatInfo)))) + { + return 0; + } + return formatInfo.PlaneCount; +} + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_RESOURCE_DESC : public D3D12_RESOURCE_DESC +{ + CD3DX12_RESOURCE_DESC() = default; + explicit CD3DX12_RESOURCE_DESC( const D3D12_RESOURCE_DESC& o ) noexcept : + D3D12_RESOURCE_DESC( o ) + {} + CD3DX12_RESOURCE_DESC( + D3D12_RESOURCE_DIMENSION dimension, + UINT64 alignment, + UINT64 width, + UINT height, + UINT16 depthOrArraySize, + UINT16 mipLevels, + DXGI_FORMAT format, + UINT sampleCount, + UINT sampleQuality, + D3D12_TEXTURE_LAYOUT layout, + D3D12_RESOURCE_FLAGS flags ) noexcept + { + Dimension = dimension; + Alignment = alignment; + Width = width; + Height = height; + DepthOrArraySize = depthOrArraySize; + MipLevels = mipLevels; + Format = format; + SampleDesc.Count = sampleCount; + SampleDesc.Quality = sampleQuality; + Layout = layout; + Flags = flags; + } + static inline CD3DX12_RESOURCE_DESC Buffer( + const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE ) noexcept + { + return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_BUFFER, resAllocInfo.Alignment, resAllocInfo.SizeInBytes, + 1, 1, 1, DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags ); + } + static inline CD3DX12_RESOURCE_DESC Buffer( + UINT64 width, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + UINT64 alignment = 0 ) noexcept + { + return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_BUFFER, alignment, width, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags ); + } + static inline CD3DX12_RESOURCE_DESC Tex1D( + DXGI_FORMAT format, + UINT64 width, + UINT16 arraySize = 1, + UINT16 mipLevels = 0, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, + UINT64 alignment = 0 ) noexcept + { + return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE1D, alignment, width, 1, arraySize, + mipLevels, format, 1, 0, layout, flags ); + } + static inline CD3DX12_RESOURCE_DESC Tex2D( + DXGI_FORMAT format, + UINT64 width, + UINT height, + UINT16 arraySize = 1, + UINT16 mipLevels = 0, + UINT sampleCount = 1, + UINT sampleQuality = 0, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, + UINT64 alignment = 0 ) noexcept + { + return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE2D, alignment, width, height, arraySize, + mipLevels, format, sampleCount, sampleQuality, layout, flags ); + } + static inline CD3DX12_RESOURCE_DESC Tex3D( + DXGI_FORMAT format, + UINT64 width, + UINT height, + UINT16 depth, + UINT16 mipLevels = 0, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, + UINT64 alignment = 0 ) noexcept + { + return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE3D, alignment, width, height, depth, + mipLevels, format, 1, 0, layout, flags ); + } + inline UINT16 Depth() const noexcept + { return (Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1u); } + inline UINT16 ArraySize() const noexcept + { return (Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1u); } + inline UINT8 PlaneCount(_In_ ID3D12Device* pDevice) const noexcept + { return D3D12GetFormatPlaneCount(pDevice, Format); } + inline UINT Subresources(_In_ ID3D12Device* pDevice) const noexcept + { return static_cast(MipLevels) * ArraySize() * PlaneCount(pDevice); } + inline UINT CalcSubresource(UINT MipSlice, UINT ArraySlice, UINT PlaneSlice) noexcept + { return D3D12CalcSubresource(MipSlice, ArraySlice, PlaneSlice, MipLevels, ArraySize()); } +}; +inline bool operator==( const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r ) noexcept +{ + return l.Dimension == r.Dimension && + l.Alignment == r.Alignment && + l.Width == r.Width && + l.Height == r.Height && + l.DepthOrArraySize == r.DepthOrArraySize && + l.MipLevels == r.MipLevels && + l.Format == r.Format && + l.SampleDesc.Count == r.SampleDesc.Count && + l.SampleDesc.Quality == r.SampleDesc.Quality && + l.Layout == r.Layout && + l.Flags == r.Flags; +} +inline bool operator!=( const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r ) noexcept +{ return !( l == r ); } + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_RESOURCE_DESC1 : public D3D12_RESOURCE_DESC1 +{ + CD3DX12_RESOURCE_DESC1() = default; + explicit CD3DX12_RESOURCE_DESC1( const D3D12_RESOURCE_DESC1& o ) noexcept : + D3D12_RESOURCE_DESC1( o ) + {} + explicit CD3DX12_RESOURCE_DESC1( const D3D12_RESOURCE_DESC& o ) noexcept + { + Dimension = o.Dimension; + Alignment = o.Alignment; + Width = o.Width; + Height = o.Height; + DepthOrArraySize = o.DepthOrArraySize; + MipLevels = o.MipLevels; + Format = o.Format; + SampleDesc = o.SampleDesc; + Layout = o.Layout; + Flags = o.Flags; + SamplerFeedbackMipRegion = {}; + } + CD3DX12_RESOURCE_DESC1( + D3D12_RESOURCE_DIMENSION dimension, + UINT64 alignment, + UINT64 width, + UINT height, + UINT16 depthOrArraySize, + UINT16 mipLevels, + DXGI_FORMAT format, + UINT sampleCount, + UINT sampleQuality, + D3D12_TEXTURE_LAYOUT layout, + D3D12_RESOURCE_FLAGS flags, + UINT samplerFeedbackMipRegionWidth = 0, + UINT samplerFeedbackMipRegionHeight = 0, + UINT samplerFeedbackMipRegionDepth = 0) noexcept + { + Dimension = dimension; + Alignment = alignment; + Width = width; + Height = height; + DepthOrArraySize = depthOrArraySize; + MipLevels = mipLevels; + Format = format; + SampleDesc.Count = sampleCount; + SampleDesc.Quality = sampleQuality; + Layout = layout; + Flags = flags; + SamplerFeedbackMipRegion.Width = samplerFeedbackMipRegionWidth; + SamplerFeedbackMipRegion.Height = samplerFeedbackMipRegionHeight; + SamplerFeedbackMipRegion.Depth = samplerFeedbackMipRegionDepth; + } + static inline CD3DX12_RESOURCE_DESC1 Buffer( + const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE ) noexcept + { + return CD3DX12_RESOURCE_DESC1( D3D12_RESOURCE_DIMENSION_BUFFER, resAllocInfo.Alignment, resAllocInfo.SizeInBytes, + 1, 1, 1, DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags, 0, 0, 0 ); + } + static inline CD3DX12_RESOURCE_DESC1 Buffer( + UINT64 width, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + UINT64 alignment = 0 ) noexcept + { + return CD3DX12_RESOURCE_DESC1( D3D12_RESOURCE_DIMENSION_BUFFER, alignment, width, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags, 0, 0, 0 ); + } + static inline CD3DX12_RESOURCE_DESC1 Tex1D( + DXGI_FORMAT format, + UINT64 width, + UINT16 arraySize = 1, + UINT16 mipLevels = 0, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, + UINT64 alignment = 0 ) noexcept + { + return CD3DX12_RESOURCE_DESC1( D3D12_RESOURCE_DIMENSION_TEXTURE1D, alignment, width, 1, arraySize, + mipLevels, format, 1, 0, layout, flags, 0, 0, 0 ); + } + static inline CD3DX12_RESOURCE_DESC1 Tex2D( + DXGI_FORMAT format, + UINT64 width, + UINT height, + UINT16 arraySize = 1, + UINT16 mipLevels = 0, + UINT sampleCount = 1, + UINT sampleQuality = 0, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, + UINT64 alignment = 0, + UINT samplerFeedbackMipRegionWidth = 0, + UINT samplerFeedbackMipRegionHeight = 0, + UINT samplerFeedbackMipRegionDepth = 0) noexcept + { + return CD3DX12_RESOURCE_DESC1( D3D12_RESOURCE_DIMENSION_TEXTURE2D, alignment, width, height, arraySize, + mipLevels, format, sampleCount, sampleQuality, layout, flags, samplerFeedbackMipRegionWidth, + samplerFeedbackMipRegionHeight, samplerFeedbackMipRegionDepth ); + } + static inline CD3DX12_RESOURCE_DESC1 Tex3D( + DXGI_FORMAT format, + UINT64 width, + UINT height, + UINT16 depth, + UINT16 mipLevels = 0, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN, + UINT64 alignment = 0 ) noexcept + { + return CD3DX12_RESOURCE_DESC1( D3D12_RESOURCE_DIMENSION_TEXTURE3D, alignment, width, height, depth, + mipLevels, format, 1, 0, layout, flags, 0, 0, 0 ); + } + inline UINT16 Depth() const noexcept + { return (Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1u); } + inline UINT16 ArraySize() const noexcept + { return (Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1u); } + inline UINT8 PlaneCount(_In_ ID3D12Device* pDevice) const noexcept + { return D3D12GetFormatPlaneCount(pDevice, Format); } + inline UINT Subresources(_In_ ID3D12Device* pDevice) const noexcept + { return static_cast(MipLevels) * ArraySize() * PlaneCount(pDevice); } + inline UINT CalcSubresource(UINT MipSlice, UINT ArraySlice, UINT PlaneSlice) noexcept + { return D3D12CalcSubresource(MipSlice, ArraySlice, PlaneSlice, MipLevels, ArraySize()); } +}; +inline bool operator==( const D3D12_RESOURCE_DESC1& l, const D3D12_RESOURCE_DESC1& r ) noexcept +{ + return l.Dimension == r.Dimension && + l.Alignment == r.Alignment && + l.Width == r.Width && + l.Height == r.Height && + l.DepthOrArraySize == r.DepthOrArraySize && + l.MipLevels == r.MipLevels && + l.Format == r.Format && + l.SampleDesc.Count == r.SampleDesc.Count && + l.SampleDesc.Quality == r.SampleDesc.Quality && + l.Layout == r.Layout && + l.Flags == r.Flags && + l.SamplerFeedbackMipRegion.Width == r.SamplerFeedbackMipRegion.Width && + l.SamplerFeedbackMipRegion.Height == r.SamplerFeedbackMipRegion.Height && + l.SamplerFeedbackMipRegion.Depth == r.SamplerFeedbackMipRegion.Depth; +} +inline bool operator!=( const D3D12_RESOURCE_DESC1& l, const D3D12_RESOURCE_DESC1& r ) noexcept +{ return !( l == r ); } + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_VIEW_INSTANCING_DESC : public D3D12_VIEW_INSTANCING_DESC +{ + CD3DX12_VIEW_INSTANCING_DESC() = default; + explicit CD3DX12_VIEW_INSTANCING_DESC( const D3D12_VIEW_INSTANCING_DESC& o ) noexcept : + D3D12_VIEW_INSTANCING_DESC( o ) + {} + explicit CD3DX12_VIEW_INSTANCING_DESC( CD3DX12_DEFAULT ) noexcept + { + ViewInstanceCount = 0; + pViewInstanceLocations = nullptr; + Flags = D3D12_VIEW_INSTANCING_FLAG_NONE; + } + explicit CD3DX12_VIEW_INSTANCING_DESC( + UINT InViewInstanceCount, + const D3D12_VIEW_INSTANCE_LOCATION* InViewInstanceLocations, + D3D12_VIEW_INSTANCING_FLAGS InFlags) noexcept + { + ViewInstanceCount = InViewInstanceCount; + pViewInstanceLocations = InViewInstanceLocations; + Flags = InFlags; + } +}; + +//------------------------------------------------------------------------------------------------ +// Row-by-row memcpy +inline void MemcpySubresource( + _In_ const D3D12_MEMCPY_DEST* pDest, + _In_ const D3D12_SUBRESOURCE_DATA* pSrc, + SIZE_T RowSizeInBytes, + UINT NumRows, + UINT NumSlices) noexcept +{ + for (UINT z = 0; z < NumSlices; ++z) + { + auto pDestSlice = static_cast(pDest->pData) + pDest->SlicePitch * z; + auto pSrcSlice = static_cast(pSrc->pData) + pSrc->SlicePitch * LONG_PTR(z); + for (UINT y = 0; y < NumRows; ++y) + { + memcpy(pDestSlice + pDest->RowPitch * y, + pSrcSlice + pSrc->RowPitch * LONG_PTR(y), + RowSizeInBytes); + } + } +} + +//------------------------------------------------------------------------------------------------ +// Row-by-row memcpy +inline void MemcpySubresource( + _In_ const D3D12_MEMCPY_DEST* pDest, + _In_ const void* pResourceData, + _In_ const D3D12_SUBRESOURCE_INFO* pSrc, + SIZE_T RowSizeInBytes, + UINT NumRows, + UINT NumSlices) noexcept +{ + for (UINT z = 0; z < NumSlices; ++z) + { + auto pDestSlice = static_cast(pDest->pData) + pDest->SlicePitch * z; + auto pSrcSlice = (static_cast(pResourceData) + pSrc->Offset) + pSrc->DepthPitch * ULONG_PTR(z); + for (UINT y = 0; y < NumRows; ++y) + { + memcpy(pDestSlice + pDest->RowPitch * y, + pSrcSlice + pSrc->RowPitch * ULONG_PTR(y), + RowSizeInBytes); + } + } +} + +//------------------------------------------------------------------------------------------------ +// Returns required size of a buffer to be used for data upload +inline UINT64 GetRequiredIntermediateSize( + _In_ ID3D12Resource* pDestinationResource, + _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources) noexcept +{ + const auto Desc = pDestinationResource->GetDesc(); + UINT64 RequiredSize = 0; + + ID3D12Device* pDevice = nullptr; + pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast(&pDevice)); + pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, 0, nullptr, nullptr, nullptr, &RequiredSize); + pDevice->Release(); + + return RequiredSize; +} + +//------------------------------------------------------------------------------------------------ +// All arrays must be populated (e.g. by calling GetCopyableFootprints) +template< typename t_CommandListType > +inline UINT64 UpdateSubresources( + _In_ t_CommandListType* pCmdList, + _In_ ID3D12Resource* pDestinationResource, + _In_ ID3D12Resource* pIntermediate, + _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, + UINT64 RequiredSize, + _In_reads_(NumSubresources) const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts, + _In_reads_(NumSubresources) const UINT* pNumRows, + _In_reads_(NumSubresources) const UINT64* pRowSizesInBytes, + _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) noexcept +{ + // Minor validation + const auto IntermediateDesc = pIntermediate->GetDesc(); + const auto DestinationDesc = pDestinationResource->GetDesc(); + if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset || + RequiredSize > SIZE_T(-1) || + (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && + (FirstSubresource != 0 || NumSubresources != 1))) + { + return 0; + } + + BYTE* pData; + HRESULT hr = pIntermediate->Map(0, nullptr, reinterpret_cast(&pData)); + if (FAILED(hr)) + { + return 0; + } + + for (UINT i = 0; i < NumSubresources; ++i) + { + if (pRowSizesInBytes[i] > SIZE_T(-1)) return 0; + D3D12_MEMCPY_DEST DestData = { pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, SIZE_T(pLayouts[i].Footprint.RowPitch) * SIZE_T(pNumRows[i]) }; + MemcpySubresource(&DestData, &pSrcData[i], static_cast(pRowSizesInBytes[i]), pNumRows[i], pLayouts[i].Footprint.Depth); + } + pIntermediate->Unmap(0, nullptr); + + if (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) + { + pCmdList->CopyBufferRegion( + pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, pLayouts[0].Footprint.Width); + } + else + { + for (UINT i = 0; i < NumSubresources; ++i) + { + const CD3DX12_TEXTURE_COPY_LOCATION Dst(pDestinationResource, i + FirstSubresource); + const CD3DX12_TEXTURE_COPY_LOCATION Src(pIntermediate, pLayouts[i]); + pCmdList->CopyTextureRegion(&Dst, 0, 0, 0, &Src, nullptr); + } + } + return RequiredSize; +} + +//------------------------------------------------------------------------------------------------ +// All arrays must be populated (e.g. by calling GetCopyableFootprints) +template< typename t_CommandListType > +inline UINT64 UpdateSubresources( + _In_ t_CommandListType* pCmdList, + _In_ ID3D12Resource* pDestinationResource, + _In_ ID3D12Resource* pIntermediate, + _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, + UINT64 RequiredSize, + _In_reads_(NumSubresources) const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts, + _In_reads_(NumSubresources) const UINT* pNumRows, + _In_reads_(NumSubresources) const UINT64* pRowSizesInBytes, + _In_ const void* pResourceData, + _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_INFO* pSrcData) noexcept +{ + // Minor validation + const auto IntermediateDesc = pIntermediate->GetDesc(); + const auto DestinationDesc = pDestinationResource->GetDesc(); + if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset || + RequiredSize > SIZE_T(-1) || + (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && + (FirstSubresource != 0 || NumSubresources != 1))) + { + return 0; + } + + BYTE* pData; + HRESULT hr = pIntermediate->Map(0, nullptr, reinterpret_cast(&pData)); + if (FAILED(hr)) + { + return 0; + } + + for (UINT i = 0; i < NumSubresources; ++i) + { + if (pRowSizesInBytes[i] > SIZE_T(-1)) return 0; + D3D12_MEMCPY_DEST DestData = { pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, SIZE_T(pLayouts[i].Footprint.RowPitch) * SIZE_T(pNumRows[i]) }; + MemcpySubresource(&DestData, pResourceData, &pSrcData[i], static_cast(pRowSizesInBytes[i]), pNumRows[i], pLayouts[i].Footprint.Depth); + } + pIntermediate->Unmap(0, nullptr); + + if (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) + { + pCmdList->CopyBufferRegion( + pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, pLayouts[0].Footprint.Width); + } + else + { + for (UINT i = 0; i < NumSubresources; ++i) + { + const CD3DX12_TEXTURE_COPY_LOCATION Dst(pDestinationResource, i + FirstSubresource); + const CD3DX12_TEXTURE_COPY_LOCATION Src(pIntermediate, pLayouts[i]); + pCmdList->CopyTextureRegion(&Dst, 0, 0, 0, &Src, nullptr); + } + } + return RequiredSize; +} + +//------------------------------------------------------------------------------------------------ +// Heap-allocating UpdateSubresources implementation +template< typename t_CommandListType > +inline UINT64 UpdateSubresources( + _In_ t_CommandListType* pCmdList, + _In_ ID3D12Resource* pDestinationResource, + _In_ ID3D12Resource* pIntermediate, + UINT64 IntermediateOffset, + _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, + _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) noexcept +{ + UINT64 RequiredSize = 0; + const auto MemToAlloc = static_cast(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources; + if (MemToAlloc > SIZE_MAX) + { + return 0; + } + void* pMem = HeapAlloc(GetProcessHeap(), 0, static_cast(MemToAlloc)); + if (pMem == nullptr) + { + return 0; + } + auto pLayouts = static_cast(pMem); + auto pRowSizesInBytes = reinterpret_cast(pLayouts + NumSubresources); + auto pNumRows = reinterpret_cast(pRowSizesInBytes + NumSubresources); + + const auto Desc = pDestinationResource->GetDesc(); + ID3D12Device* pDevice = nullptr; + pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast(&pDevice)); + pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize); + pDevice->Release(); + + const UINT64 Result = UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, pLayouts, pNumRows, pRowSizesInBytes, pSrcData); + HeapFree(GetProcessHeap(), 0, pMem); + return Result; +} + +//------------------------------------------------------------------------------------------------ +// Heap-allocating UpdateSubresources implementation +template< typename t_CommandListType > +inline UINT64 UpdateSubresources( + _In_ t_CommandListType* pCmdList, + _In_ ID3D12Resource* pDestinationResource, + _In_ ID3D12Resource* pIntermediate, + UINT64 IntermediateOffset, + _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, + _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, + _In_ const void* pResourceData, + _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_INFO* pSrcData) noexcept +{ + UINT64 RequiredSize = 0; + const auto MemToAlloc = static_cast(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources; + if (MemToAlloc > SIZE_MAX) + { + return 0; + } + void* pMem = HeapAlloc(GetProcessHeap(), 0, static_cast(MemToAlloc)); + if (pMem == nullptr) + { + return 0; + } + auto pLayouts = static_cast(pMem); + auto pRowSizesInBytes = reinterpret_cast(pLayouts + NumSubresources); + auto pNumRows = reinterpret_cast(pRowSizesInBytes + NumSubresources); + + const auto Desc = pDestinationResource->GetDesc(); + ID3D12Device* pDevice = nullptr; + pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast(&pDevice)); + pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize); + pDevice->Release(); + + const UINT64 Result = UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, pLayouts, pNumRows, pRowSizesInBytes, pResourceData, pSrcData); + HeapFree(GetProcessHeap(), 0, pMem); + return Result; +} + +//------------------------------------------------------------------------------------------------ +// Stack-allocating UpdateSubresources implementation +template +inline UINT64 UpdateSubresources( + _In_ t_CommandListType* pCmdList, + _In_ ID3D12Resource* pDestinationResource, + _In_ ID3D12Resource* pIntermediate, + UINT64 IntermediateOffset, + _In_range_(0,MaxSubresources) UINT FirstSubresource, + _In_range_(1,MaxSubresources-FirstSubresource) UINT NumSubresources, + _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData) noexcept +{ + UINT64 RequiredSize = 0; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT Layouts[MaxSubresources]; + UINT NumRows[MaxSubresources]; + UINT64 RowSizesInBytes[MaxSubresources]; + + const auto Desc = pDestinationResource->GetDesc(); + ID3D12Device* pDevice = nullptr; + pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast(&pDevice)); + pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize); + pDevice->Release(); + + return UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, Layouts, NumRows, RowSizesInBytes, pSrcData); +} + +//------------------------------------------------------------------------------------------------ +// Stack-allocating UpdateSubresources implementation +template +inline UINT64 UpdateSubresources( + _In_ t_CommandListType* pCmdList, + _In_ ID3D12Resource* pDestinationResource, + _In_ ID3D12Resource* pIntermediate, + UINT64 IntermediateOffset, + _In_range_(0,MaxSubresources) UINT FirstSubresource, + _In_range_(1,MaxSubresources-FirstSubresource) UINT NumSubresources, + _In_ const void* pResourceData, + _In_reads_(NumSubresources) const D3D12_SUBRESOURCE_INFO* pSrcData) noexcept +{ + UINT64 RequiredSize = 0; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT Layouts[MaxSubresources]; + UINT NumRows[MaxSubresources]; + UINT64 RowSizesInBytes[MaxSubresources]; + + const auto Desc = pDestinationResource->GetDesc(); + ID3D12Device* pDevice = nullptr; + pDestinationResource->GetDevice(IID_ID3D12Device, reinterpret_cast(&pDevice)); + pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, Layouts, NumRows, RowSizesInBytes, &RequiredSize); + pDevice->Release(); + + return UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, Layouts, NumRows, RowSizesInBytes, pResourceData, pSrcData); +} + +//------------------------------------------------------------------------------------------------ +constexpr bool D3D12IsLayoutOpaque( D3D12_TEXTURE_LAYOUT Layout ) noexcept +{ return Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN || Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; } + +//------------------------------------------------------------------------------------------------ +#ifndef D3DX12_ASSERT + #ifdef assert + #define D3DX12_ASSERT(x) assert(x) + #else + #define D3DX12_ASSERT(x) + #endif +#endif + +template< typename T > +inline T D3DX12Align(T uValue, T uAlign) +{ + // Assert power of 2 alignment + D3DX12_ASSERT(0 == (uAlign & (uAlign - 1))); + T uMask = uAlign - 1; + T uResult = (uValue + uMask) & ~uMask; + D3DX12_ASSERT(uResult >= uValue); + D3DX12_ASSERT(0 == (uResult % uAlign)); + return uResult; +} + +//------------------------------------------------------------------------------------------------ +template< typename T > +inline T D3DX12AlignAtLeast(T uValue, T uAlign) +{ + T aligned = D3DX12Align(uValue, uAlign); + return aligned > uAlign ? aligned : uAlign; +} + +//------------------------------------------------------------------------------------------------ +template +inline ID3D12CommandList * const * CommandListCast(t_CommandListType * const * pp) noexcept +{ + // This cast is useful for passing strongly typed command list pointers into + // ExecuteCommandLists. + // This cast is valid as long as the const-ness is respected. D3D12 APIs do + // respect the const-ness of their arguments. + return reinterpret_cast(pp); +} + +//------------------------------------------------------------------------------------------------ +// D3D12 exports a new method for serializing root signatures in the Windows 10 Anniversary Update. +// To help enable root signature 1.1 features when they are available and not require maintaining +// two code paths for building root signatures, this helper method reconstructs a 1.0 signature when +// 1.1 is not supported. +inline HRESULT D3DX12SerializeVersionedRootSignature( + _In_ const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* pRootSignatureDesc, + D3D_ROOT_SIGNATURE_VERSION MaxVersion, + _Outptr_ ID3DBlob** ppBlob, + _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorBlob) noexcept +{ + if (ppErrorBlob != nullptr) + { + *ppErrorBlob = nullptr; + } + + switch (MaxVersion) + { + case D3D_ROOT_SIGNATURE_VERSION_1_0: + switch (pRootSignatureDesc->Version) + { + case D3D_ROOT_SIGNATURE_VERSION_1_0: + return D3D12SerializeRootSignature(&pRootSignatureDesc->Desc_1_0, D3D_ROOT_SIGNATURE_VERSION_1, ppBlob, ppErrorBlob); + + case D3D_ROOT_SIGNATURE_VERSION_1_1: + { + HRESULT hr = S_OK; + const D3D12_ROOT_SIGNATURE_DESC1& desc_1_1 = pRootSignatureDesc->Desc_1_1; + + const SIZE_T ParametersSize = sizeof(D3D12_ROOT_PARAMETER) * desc_1_1.NumParameters; + void* pParameters = (ParametersSize > 0) ? HeapAlloc(GetProcessHeap(), 0, ParametersSize) : nullptr; + if (ParametersSize > 0 && pParameters == nullptr) + { + hr = E_OUTOFMEMORY; + } + auto pParameters_1_0 = static_cast(pParameters); + + if (SUCCEEDED(hr)) + { + for (UINT n = 0; n < desc_1_1.NumParameters; n++) + { + __analysis_assume(ParametersSize == sizeof(D3D12_ROOT_PARAMETER) * desc_1_1.NumParameters); + pParameters_1_0[n].ParameterType = desc_1_1.pParameters[n].ParameterType; + pParameters_1_0[n].ShaderVisibility = desc_1_1.pParameters[n].ShaderVisibility; + + switch (desc_1_1.pParameters[n].ParameterType) + { + case D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS: + pParameters_1_0[n].Constants.Num32BitValues = desc_1_1.pParameters[n].Constants.Num32BitValues; + pParameters_1_0[n].Constants.RegisterSpace = desc_1_1.pParameters[n].Constants.RegisterSpace; + pParameters_1_0[n].Constants.ShaderRegister = desc_1_1.pParameters[n].Constants.ShaderRegister; + break; + + case D3D12_ROOT_PARAMETER_TYPE_CBV: + case D3D12_ROOT_PARAMETER_TYPE_SRV: + case D3D12_ROOT_PARAMETER_TYPE_UAV: + pParameters_1_0[n].Descriptor.RegisterSpace = desc_1_1.pParameters[n].Descriptor.RegisterSpace; + pParameters_1_0[n].Descriptor.ShaderRegister = desc_1_1.pParameters[n].Descriptor.ShaderRegister; + break; + + case D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE: + { + const D3D12_ROOT_DESCRIPTOR_TABLE1& table_1_1 = desc_1_1.pParameters[n].DescriptorTable; + + const SIZE_T DescriptorRangesSize = sizeof(D3D12_DESCRIPTOR_RANGE) * table_1_1.NumDescriptorRanges; + void* pDescriptorRanges = (DescriptorRangesSize > 0 && SUCCEEDED(hr)) ? HeapAlloc(GetProcessHeap(), 0, DescriptorRangesSize) : nullptr; + if (DescriptorRangesSize > 0 && pDescriptorRanges == nullptr) + { + hr = E_OUTOFMEMORY; + } + auto pDescriptorRanges_1_0 = static_cast(pDescriptorRanges); + + if (SUCCEEDED(hr)) + { + for (UINT x = 0; x < table_1_1.NumDescriptorRanges; x++) + { + __analysis_assume(DescriptorRangesSize == sizeof(D3D12_DESCRIPTOR_RANGE) * table_1_1.NumDescriptorRanges); + pDescriptorRanges_1_0[x].BaseShaderRegister = table_1_1.pDescriptorRanges[x].BaseShaderRegister; + pDescriptorRanges_1_0[x].NumDescriptors = table_1_1.pDescriptorRanges[x].NumDescriptors; + pDescriptorRanges_1_0[x].OffsetInDescriptorsFromTableStart = table_1_1.pDescriptorRanges[x].OffsetInDescriptorsFromTableStart; + pDescriptorRanges_1_0[x].RangeType = table_1_1.pDescriptorRanges[x].RangeType; + pDescriptorRanges_1_0[x].RegisterSpace = table_1_1.pDescriptorRanges[x].RegisterSpace; + } + } + + D3D12_ROOT_DESCRIPTOR_TABLE& table_1_0 = pParameters_1_0[n].DescriptorTable; + table_1_0.NumDescriptorRanges = table_1_1.NumDescriptorRanges; + table_1_0.pDescriptorRanges = pDescriptorRanges_1_0; + } + break; + + default: + break; + } + } + } + + if (SUCCEEDED(hr)) + { + const CD3DX12_ROOT_SIGNATURE_DESC desc_1_0(desc_1_1.NumParameters, pParameters_1_0, desc_1_1.NumStaticSamplers, desc_1_1.pStaticSamplers, desc_1_1.Flags); + hr = D3D12SerializeRootSignature(&desc_1_0, D3D_ROOT_SIGNATURE_VERSION_1, ppBlob, ppErrorBlob); + } + + if (pParameters) + { + for (UINT n = 0; n < desc_1_1.NumParameters; n++) + { + if (desc_1_1.pParameters[n].ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + { + auto pDescriptorRanges_1_0 = pParameters_1_0[n].DescriptorTable.pDescriptorRanges; + HeapFree(GetProcessHeap(), 0, reinterpret_cast(const_cast(pDescriptorRanges_1_0))); + } + } + HeapFree(GetProcessHeap(), 0, pParameters); + } + return hr; + } + + default: + break; + } + break; + + case D3D_ROOT_SIGNATURE_VERSION_1_1: + return D3D12SerializeVersionedRootSignature(pRootSignatureDesc, ppBlob, ppErrorBlob); + } + + return E_INVALIDARG; +} + +//------------------------------------------------------------------------------------------------ +struct CD3DX12_RT_FORMAT_ARRAY : public D3D12_RT_FORMAT_ARRAY +{ + CD3DX12_RT_FORMAT_ARRAY() = default; + explicit CD3DX12_RT_FORMAT_ARRAY(const D3D12_RT_FORMAT_ARRAY& o) noexcept + : D3D12_RT_FORMAT_ARRAY(o) + {} + explicit CD3DX12_RT_FORMAT_ARRAY(_In_reads_(NumFormats) const DXGI_FORMAT* pFormats, UINT NumFormats) noexcept + { + NumRenderTargets = NumFormats; + memcpy(RTFormats, pFormats, sizeof(RTFormats)); + // assumes ARRAY_SIZE(pFormats) == ARRAY_SIZE(RTFormats) + } +}; + + +//------------------------------------------------------------------------------------------------ +// + +struct CD3D12XBOX_PIXEL_SHADER_OPTIONS_DESC : public D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC +{ + CD3D12XBOX_PIXEL_SHADER_OPTIONS_DESC() noexcept + { + PerSampleIteration = D3D12XBOX_PIXEL_SHADER_OPTION_PER_SAMPLE_ITERATION_DEFAULT; + ZOrder = D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER_DEFAULT; + TexKill = D3D12XBOX_PIXEL_SHADER_OPTION_TEXKILL_DEFAULT; + ExecOnHierFail = D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_HIER_FAIL_DEFAULT; + ExecOnNoop = D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_NOOP_DEFAULT; + DepthBeforeShader = D3D12XBOX_PIXEL_SHADER_OPTION_DEPTH_BEFORE_SHADER_DEFAULT; + ConservativeZExport = D3D12XBOX_PIXEL_SHADER_OPTION_CONSERVATIVE_Z_EXPORT_DEFAULT; + OutOfOrderRasterization = D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_DISABLED; + } + + explicit CD3D12XBOX_PIXEL_SHADER_OPTIONS_DESC(const D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC& o) noexcept + : D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC(o) + {} + + bool IsDefault() const noexcept + { + return PerSampleIteration == D3D12XBOX_PIXEL_SHADER_OPTION_PER_SAMPLE_ITERATION_DEFAULT && + ZOrder == D3D12XBOX_PIXEL_SHADER_OPTION_ZORDER_DEFAULT && + TexKill == D3D12XBOX_PIXEL_SHADER_OPTION_TEXKILL_DEFAULT && + ExecOnHierFail == D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_HIER_FAIL_DEFAULT && + ExecOnNoop == D3D12XBOX_PIXEL_SHADER_OPTION_EXEC_ON_NOOP_DEFAULT && + DepthBeforeShader == D3D12XBOX_PIXEL_SHADER_OPTION_DEPTH_BEFORE_SHADER_DEFAULT && + ConservativeZExport == D3D12XBOX_PIXEL_SHADER_OPTION_CONSERVATIVE_Z_EXPORT_DEFAULT && + OutOfOrderRasterization == D3D12XBOX_PIXEL_SHADER_OPTION_OUT_OF_ORDER_RASTERIZATION_DISABLED; + } +}; + + +//------------------------------------------------------------------------------------------------ +// + +struct CD3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC : public D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC +{ + CD3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC() noexcept + { + BackFaceDisable = 0; + DepthBoundsDisable = 0; + ColorWritesOnDepthFailEnable = 0; + ColorWritesOnDepthPassDisable = 0; + StencilReadMaskBack = 0; + StencilWriteMaskBack = 0; + StencilTestRefValueFront = 0; + StencilTestRefValueBack = 0; + StencilOpRefValueFront = 1; + StencilOpRefValueBack = 1; + } + + explicit CD3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC(const D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC& o) noexcept + : D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC(o) + {} + + bool IsDefault() const noexcept + { + return BackFaceDisable == 0 && + DepthBoundsDisable == 0 && + ColorWritesOnDepthFailEnable == 0 && + ColorWritesOnDepthPassDisable == 0 && + StencilReadMaskBack == 0 && + StencilWriteMaskBack == 0 && + StencilTestRefValueFront == 0 && + StencilTestRefValueBack == 0 && + StencilOpRefValueFront == 1 && + StencilOpRefValueBack == 1; + } +}; + + +//------------------------------------------------------------------------------------------------ +// + +struct CD3D12XBOX_TESSELLATION_PARAMETERS_DESC : public D3D12XBOX_TESSELLATION_PARAMETERS_DESC +{ + CD3D12XBOX_TESSELLATION_PARAMETERS_DESC() noexcept + { + D3D12XboxInitializeDefaultTessellationParameters(this); + } + + explicit CD3D12XBOX_TESSELLATION_PARAMETERS_DESC(const D3D12XBOX_TESSELLATION_PARAMETERS_DESC& o) noexcept + : D3D12XBOX_TESSELLATION_PARAMETERS_DESC(o) + {} + + bool IsDefault() const + { + return PatchesPerThreadgroup == D3D12XBOX_TESSELLATION_PARAMETERS_PATCHES_PER_THREADGROUP_DEFAULT && + TessellationFactorThreshold == D3D12XBOX_TESSELLATION_PARAMETERS_TESSELLATION_FACTOR_THRESHOLD_DEFAULT && + DsWaveThreshold == D3D12XBOX_TESSELLATION_PARAMETERS_DS_WAVE_THRESHOLD_DEFAULT; + } +}; + +//------------------------------------------------------------------------------------------------ +// + +struct CD3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC : public D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC +{ + CD3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC() noexcept + { + D3D12XboxInitializeDefaultGraphicsShaderLimits(this); + } + + explicit CD3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC(const D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC& o) noexcept + : D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC(o) + {} + + bool IsDefault() const noexcept + { + return MaxLateAllocParameterCacheLines == D3D12XBOX_SHADER_MAX_LATE_ALLOC_PARAMETER_CACHE_LINES_DEFAULT && + VSDisableFlags == D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_NONE && + reserved0 == 0 && + GSDisableFlags == D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_NONE && + PSDisableFlags == D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_NONE && + VSMaxWaves == D3D12XBOX_SHADER_MAX_WAVES_DEFAULT && + HSMaxWaves == D3D12XBOX_SHADER_MAX_WAVES_DEFAULT && + reserved1 == 0 && + GSMaxWaves == D3D12XBOX_SHADER_MAX_WAVES_DEFAULT && + PSMaxWaves == D3D12XBOX_SHADER_MAX_WAVES_DEFAULT && + VSMaxWavesForCuLocking == D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT && + HSMaxWavesForCuLocking == D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT && + reserved2 == 0 && + GSMaxWavesForCuLocking == D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT && + PSMaxWavesForCuLocking == D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT; + } +}; + +//------------------------------------------------------------------------------------------------ +// + +struct CD3D12XBOX_COMPUTE_SHADER_LIMITS_DESC : public D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC +{ + CD3D12XBOX_COMPUTE_SHADER_LIMITS_DESC() noexcept + { + D3D12XboxInitializeDefaultComputeShaderLimits(this); + } + + explicit CD3D12XBOX_COMPUTE_SHADER_LIMITS_DESC(const D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC& o) noexcept + : D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC(o) + {} + + bool IsDefault() const noexcept + { + constexpr unsigned NUM_SAS_PER_SE = 2; + + return DisableFlagsPerSa == D3D12XBOX_SHADER_UNIT_DISABLE_FLAG_NONE && + MaxWavesPerSa == D3D12XBOX_SHADER_MAX_WAVES_DEFAULT / NUM_SAS_PER_SE && // There are two SAs per SE so divide the per SE max by 2 + MaxThreadgroupsPerCu == D3D12XBOX_COMPUTE_SHADER_MAX_THREADGROUPS_PER_CU_DEFAULT && + MaxWavesForCuLocking == D3D12XBOX_SHADER_MAX_WAVES_FOR_CU_LOCKING_DEFAULT && + NumThreadgroupsWalkedPerCu == D3D12XBOX_SHADER_NUM_THREADGROUPS_WALKED_PER_CU_DEFAULT && + SimdWalkAlgorithm == D3D12XBOX_SHADER_CS_SIMD_WALK_ALGORITHM_DEFAULT; + } +}; + + + +//------------------------------------------------------------------------------------------------ +// Pipeline State Stream Helpers +//------------------------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------------------------ +// Stream Subobjects, i.e. elements of a stream + +struct DefaultSampleMask { operator UINT() noexcept { return UINT_MAX; } }; +struct DefaultSampleDesc { operator DXGI_SAMPLE_DESC() noexcept { return DXGI_SAMPLE_DESC{1, 0}; } }; + +#pragma warning(push) +#pragma warning(disable : 4324) // structure was padded due to alignment specifier +template +class alignas(void*) CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT +{ +private: + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE pssType; + InnerStructType pssInner; +public: + CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT() noexcept : pssType(Type), pssInner(DefaultArg()) {} + CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT(InnerStructType const& i) noexcept : pssType(Type), pssInner(i) {} + CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT& operator=(InnerStructType const& i) noexcept { pssType = Type; pssInner = i; return *this; } + operator InnerStructType const&() const noexcept { return pssInner; } + operator InnerStructType&() noexcept { return pssInner; } + InnerStructType* operator&() noexcept { return &pssInner; } + InnerStructType const* operator&() const noexcept { return &pssInner; } + + // Xbox methods + const InnerStructType& GetX() const noexcept { return pssInner; } + InnerStructType& GetX() noexcept { return pssInner; } +}; +#pragma warning(pop) +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_PIPELINE_STATE_FLAGS, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS> CD3DX12_PIPELINE_STATE_STREAM_FLAGS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< UINT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK> CD3DX12_PIPELINE_STATE_STREAM_NODE_MASK; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< ID3D12RootSignature*, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE> CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_INPUT_LAYOUT_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT> CD3DX12_PIPELINE_STATE_STREAM_INPUT_LAYOUT; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE> CD3DX12_PIPELINE_STATE_STREAM_IB_STRIP_CUT_VALUE; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_PRIMITIVE_TOPOLOGY_TYPE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY> CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS> CD3DX12_PIPELINE_STATE_STREAM_VS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS> CD3DX12_PIPELINE_STATE_STREAM_GS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_STREAM_OUTPUT_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT> CD3DX12_PIPELINE_STATE_STREAM_STREAM_OUTPUT; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS> CD3DX12_PIPELINE_STATE_STREAM_HS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS> CD3DX12_PIPELINE_STATE_STREAM_DS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS> CD3DX12_PIPELINE_STATE_STREAM_PS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS> CD3DX12_PIPELINE_STATE_STREAM_AS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS> CD3DX12_PIPELINE_STATE_STREAM_MS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS> CD3DX12_PIPELINE_STATE_STREAM_CS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_BLEND_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_DEPTH_STENCIL_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_DEPTH_STENCIL_DESC1, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL1; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< DXGI_FORMAT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT> CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_RASTERIZER_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_RASTERIZER; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_RT_FORMAT_ARRAY, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS> CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< DXGI_SAMPLE_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DefaultSampleDesc> CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_DESC; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< UINT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, DefaultSampleMask> CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_MASK; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< D3D12_CACHED_PIPELINE_STATE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO> CD3DX12_PIPELINE_STATE_STREAM_CACHED_PSO; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3DX12_VIEW_INSTANCING_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, CD3DX12_DEFAULT> CD3DX12_PIPELINE_STATE_STREAM_VIEW_INSTANCING; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3D12XBOX_PIXEL_SHADER_OPTIONS_DESC, D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_PIXEL_SHADER_OPTIONS> CD3DX12_PIPELINE_STATE_STREAM_PIXEL_SHADER_OPTIONS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC, D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_OPTIONS> CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_OPTIONS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3D12XBOX_TESSELLATION_PARAMETERS_DESC, D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_TESSELLATION_PARAMETERS> CD3DX12_PIPELINE_STATE_STREAM_TESSELLATION_PARAMETERS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC, D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_GRAPHICS_SHADER_LIMITS> CD3DX12_PIPELINE_STATE_STREAM_GRAPHICS_SHADER_LIMITS; +typedef CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT< CD3D12XBOX_COMPUTE_SHADER_LIMITS_DESC, D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_COMPUTE_SHADER_LIMITS> CD3DX12_PIPELINE_STATE_STREAM_COMPUTE_SHADER_LIMITS; + +//------------------------------------------------------------------------------------------------ +// Stream Parser Helpers + +struct ID3DX12PipelineParserCallbacks +{ + // Subobject Callbacks + virtual void FlagsCb(D3D12_PIPELINE_STATE_FLAGS) {} + virtual void NodeMaskCb(UINT) {} + virtual void RootSignatureCb(ID3D12RootSignature*) {} + virtual void InputLayoutCb(const D3D12_INPUT_LAYOUT_DESC&) {} + virtual void IBStripCutValueCb(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE) {} + virtual void PrimitiveTopologyTypeCb(D3D12_PRIMITIVE_TOPOLOGY_TYPE) {} + virtual void VSCb(const D3D12_SHADER_BYTECODE&) {} + virtual void GSCb(const D3D12_SHADER_BYTECODE&) {} + virtual void StreamOutputCb(const D3D12_STREAM_OUTPUT_DESC&) {} + virtual void HSCb(const D3D12_SHADER_BYTECODE&) {} + virtual void DSCb(const D3D12_SHADER_BYTECODE&) {} + virtual void PSCb(const D3D12_SHADER_BYTECODE&) {} + virtual void CSCb(const D3D12_SHADER_BYTECODE&) {} + virtual void ASCb(const D3D12_SHADER_BYTECODE&) {} + virtual void MSCb(const D3D12_SHADER_BYTECODE&) {} + virtual void BlendStateCb(const D3D12_BLEND_DESC&) {} + virtual void DepthStencilStateCb(const D3D12_DEPTH_STENCIL_DESC&) {} + virtual void DepthStencilState1Cb(const D3D12_DEPTH_STENCIL_DESC1&) {} + virtual void DSVFormatCb(DXGI_FORMAT) {} + virtual void RasterizerStateCb(const D3D12_RASTERIZER_DESC&) {} + virtual void RTVFormatsCb(const D3D12_RT_FORMAT_ARRAY&) {} + virtual void SampleDescCb(const DXGI_SAMPLE_DESC&) {} + virtual void SampleMaskCb(UINT) {} + virtual void ViewInstancingCb(const D3D12_VIEW_INSTANCING_DESC&) {} + virtual void CachedPSOCb(const D3D12_CACHED_PIPELINE_STATE&) {} + + // Error Callbacks + virtual void ErrorBadInputParameter(UINT /*ParameterIndex*/) {} + virtual void ErrorDuplicateSubobject(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE /*DuplicateType*/) {} + virtual void ErrorUnknownSubobject(UINT /*UnknownTypeValue*/) {} + + + virtual void XboxSetPixelShaderOptions(const D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC&) {} + virtual void XboxSetDepthStencilOptions(const D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC&) {} + virtual void XboxSetGraphicsShaderLimits(const D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC&) {} + virtual void XboxSetTessellationParameters(const D3D12XBOX_TESSELLATION_PARAMETERS_DESC&) {} + virtual void XboxSetComputeShaderLimits(const D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC&) {} + + virtual ~ID3DX12PipelineParserCallbacks() = default; +}; + +struct D3DX12_MESH_SHADER_PIPELINE_STATE_DESC +{ + ID3D12RootSignature* pRootSignature; + D3D12_SHADER_BYTECODE AS; + D3D12_SHADER_BYTECODE MS; + D3D12_SHADER_BYTECODE PS; + D3D12_BLEND_DESC BlendState; + UINT SampleMask; + D3D12_RASTERIZER_DESC RasterizerState; + D3D12_DEPTH_STENCIL_DESC DepthStencilState; + D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType; + UINT NumRenderTargets; + DXGI_FORMAT RTVFormats[ D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT ]; + DXGI_FORMAT DSVFormat; + DXGI_SAMPLE_DESC SampleDesc; + UINT NodeMask; + D3D12_CACHED_PIPELINE_STATE CachedPSO; + D3D12_PIPELINE_STATE_FLAGS Flags; +}; + + +// Use CD3DX12_PIPELINE_STATE_STREAM3 for D3D12_DEPTH_STENCIL_DESC2 when CheckFeatureSupport returns true for Options14::IndependentFrontAndBackStencilSupported is true +// Use CD3DX12_PIPELINE_STATE_STREAM2 for OS Build 19041+ (where there is a new mesh shader pipeline). +// Use CD3DX12_PIPELINE_STATE_STREAM1 for OS Build 16299+ (where there is a new view instancing subobject). +// Use CD3DX12_PIPELINE_STATE_STREAM for OS Build 15063+ support. +struct CD3DX12_PIPELINE_STATE_STREAM3 +{ + CD3DX12_PIPELINE_STATE_STREAM3() = default; + // Mesh and amplification shaders must be set manually, since they do not have representation in D3D12_GRAPHICS_PIPELINE_STATE_DESC + CD3DX12_PIPELINE_STATE_STREAM3(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , InputLayout(Desc.InputLayout) + , IBStripCutValue(Desc.IBStripCutValue) + , PrimitiveTopologyType(Desc.PrimitiveTopologyType) + , VS(Desc.VS) + , GS(Desc.GS) + , StreamOutput(Desc.StreamOutput) + , HS(Desc.HS) + , DS(Desc.DS) + , PS(Desc.PS) + , BlendState(CD3DX12_BLEND_DESC(Desc.BlendState)) + , DepthStencilState(CD3DX12_DEPTH_STENCIL_DESC1(Desc.DepthStencilState)) + , DSVFormat(Desc.DSVFormat) + , RasterizerState(CD3DX12_RASTERIZER_DESC(Desc.RasterizerState)) + , RTVFormats(CD3DX12_RT_FORMAT_ARRAY(Desc.RTVFormats, Desc.NumRenderTargets)) + , SampleDesc(Desc.SampleDesc) + , SampleMask(Desc.SampleMask) + , CachedPSO(Desc.CachedPSO) + , ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT())) + {} + CD3DX12_PIPELINE_STATE_STREAM3(const D3DX12_MESH_SHADER_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , PrimitiveTopologyType(Desc.PrimitiveTopologyType) + , PS(Desc.PS) + , AS(Desc.AS) + , MS(Desc.MS) + , BlendState(CD3DX12_BLEND_DESC(Desc.BlendState)) + , DepthStencilState(CD3DX12_DEPTH_STENCIL_DESC1(Desc.DepthStencilState)) + , DSVFormat(Desc.DSVFormat) + , RasterizerState(CD3DX12_RASTERIZER_DESC(Desc.RasterizerState)) + , RTVFormats(CD3DX12_RT_FORMAT_ARRAY(Desc.RTVFormats, Desc.NumRenderTargets)) + , SampleDesc(Desc.SampleDesc) + , SampleMask(Desc.SampleMask) + , CachedPSO(Desc.CachedPSO) + , ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT())) + {} + CD3DX12_PIPELINE_STATE_STREAM3(const D3D12_COMPUTE_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , CS(CD3DX12_SHADER_BYTECODE(Desc.CS)) + , CachedPSO(Desc.CachedPSO) + { + static_cast(DepthStencilState).DepthEnable = false; + } + CD3DX12_PIPELINE_STATE_STREAM_FLAGS Flags; + CD3DX12_PIPELINE_STATE_STREAM_NODE_MASK NodeMask; + CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE pRootSignature; + CD3DX12_PIPELINE_STATE_STREAM_INPUT_LAYOUT InputLayout; + CD3DX12_PIPELINE_STATE_STREAM_IB_STRIP_CUT_VALUE IBStripCutValue; + CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY PrimitiveTopologyType; + CD3DX12_PIPELINE_STATE_STREAM_VS VS; + CD3DX12_PIPELINE_STATE_STREAM_GS GS; + CD3DX12_PIPELINE_STATE_STREAM_STREAM_OUTPUT StreamOutput; + CD3DX12_PIPELINE_STATE_STREAM_HS HS; + CD3DX12_PIPELINE_STATE_STREAM_DS DS; + CD3DX12_PIPELINE_STATE_STREAM_PS PS; + CD3DX12_PIPELINE_STATE_STREAM_AS AS; + CD3DX12_PIPELINE_STATE_STREAM_MS MS; + CD3DX12_PIPELINE_STATE_STREAM_CS CS; + CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC BlendState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL1 DepthStencilState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT DSVFormat; + CD3DX12_PIPELINE_STATE_STREAM_RASTERIZER RasterizerState; + CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS RTVFormats; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_DESC SampleDesc; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_MASK SampleMask; + CD3DX12_PIPELINE_STATE_STREAM_CACHED_PSO CachedPSO; + CD3DX12_PIPELINE_STATE_STREAM_VIEW_INSTANCING ViewInstancingDesc; + + D3D12_GRAPHICS_PIPELINE_STATE_DESC GraphicsDescV0() const noexcept + { + D3D12_GRAPHICS_PIPELINE_STATE_DESC D; + D.Flags = this->Flags; + D.NodeMask = this->NodeMask; + D.pRootSignature = this->pRootSignature; + D.InputLayout = this->InputLayout; + D.IBStripCutValue = this->IBStripCutValue; + D.PrimitiveTopologyType = this->PrimitiveTopologyType; + D.VS = this->VS; + D.GS = this->GS; + D.StreamOutput = this->StreamOutput; + D.HS = this->HS; + D.DS = this->DS; + D.PS = this->PS; + D.BlendState = this->BlendState; + D.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(D3D12_DEPTH_STENCIL_DESC1(this->DepthStencilState)); + D.DSVFormat = this->DSVFormat; + D.RasterizerState = this->RasterizerState; + D.NumRenderTargets = D3D12_RT_FORMAT_ARRAY(this->RTVFormats).NumRenderTargets; + memcpy(D.RTVFormats, D3D12_RT_FORMAT_ARRAY(this->RTVFormats).RTFormats, sizeof(D.RTVFormats)); + D.SampleDesc = this->SampleDesc; + D.SampleMask = this->SampleMask; + D.CachedPSO = this->CachedPSO; + return D; + } + D3D12_COMPUTE_PIPELINE_STATE_DESC ComputeDescV0() const noexcept + { + D3D12_COMPUTE_PIPELINE_STATE_DESC D; + D.Flags = this->Flags; + D.NodeMask = this->NodeMask; + D.pRootSignature = this->pRootSignature; + D.CS = this->CS; + D.CachedPSO = this->CachedPSO; + return D; + } +}; + + +// CD3DX12_PIPELINE_STATE_STREAM2 Works on OS Build 19041+ (where there is a new mesh shader pipeline). +// Use CD3DX12_PIPELINE_STATE_STREAM1 for OS Build 16299+ (where there is a new view instancing subobject). +// Use CD3DX12_PIPELINE_STATE_STREAM for OS Build 15063+ support. +struct CD3DX12_PIPELINE_STATE_STREAM2 +{ + CD3DX12_PIPELINE_STATE_STREAM2() = default; + // Mesh and amplification shaders must be set manually, since they do not have representation in D3D12_GRAPHICS_PIPELINE_STATE_DESC + CD3DX12_PIPELINE_STATE_STREAM2(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , InputLayout(Desc.InputLayout) + , IBStripCutValue(Desc.IBStripCutValue) + , PrimitiveTopologyType(Desc.PrimitiveTopologyType) + , VS(Desc.VS) + , GS(Desc.GS) + , StreamOutput(Desc.StreamOutput) + , HS(Desc.HS) + , DS(Desc.DS) + , PS(Desc.PS) + , BlendState(CD3DX12_BLEND_DESC(Desc.BlendState)) + , DepthStencilState(CD3DX12_DEPTH_STENCIL_DESC1(Desc.DepthStencilState)) + , DSVFormat(Desc.DSVFormat) + , RasterizerState(CD3DX12_RASTERIZER_DESC(Desc.RasterizerState)) + , RTVFormats(CD3DX12_RT_FORMAT_ARRAY(Desc.RTVFormats, Desc.NumRenderTargets)) + , SampleDesc(Desc.SampleDesc) + , SampleMask(Desc.SampleMask) + , CachedPSO(Desc.CachedPSO) + , ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT())) + {} + CD3DX12_PIPELINE_STATE_STREAM2(const D3DX12_MESH_SHADER_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , PrimitiveTopologyType(Desc.PrimitiveTopologyType) + , PS(Desc.PS) + , AS(Desc.AS) + , MS(Desc.MS) + , BlendState(CD3DX12_BLEND_DESC(Desc.BlendState)) + , DepthStencilState(CD3DX12_DEPTH_STENCIL_DESC1(Desc.DepthStencilState)) + , DSVFormat(Desc.DSVFormat) + , RasterizerState(CD3DX12_RASTERIZER_DESC(Desc.RasterizerState)) + , RTVFormats(CD3DX12_RT_FORMAT_ARRAY(Desc.RTVFormats, Desc.NumRenderTargets)) + , SampleDesc(Desc.SampleDesc) + , SampleMask(Desc.SampleMask) + , CachedPSO(Desc.CachedPSO) + , ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT())) + {} + CD3DX12_PIPELINE_STATE_STREAM2(const D3D12_COMPUTE_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , CS(CD3DX12_SHADER_BYTECODE(Desc.CS)) + , CachedPSO(Desc.CachedPSO) + { + static_cast(DepthStencilState).DepthEnable = false; + } + CD3DX12_PIPELINE_STATE_STREAM_FLAGS Flags; + CD3DX12_PIPELINE_STATE_STREAM_NODE_MASK NodeMask; + CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE pRootSignature; + CD3DX12_PIPELINE_STATE_STREAM_INPUT_LAYOUT InputLayout; + CD3DX12_PIPELINE_STATE_STREAM_IB_STRIP_CUT_VALUE IBStripCutValue; + CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY PrimitiveTopologyType; + CD3DX12_PIPELINE_STATE_STREAM_VS VS; + CD3DX12_PIPELINE_STATE_STREAM_GS GS; + CD3DX12_PIPELINE_STATE_STREAM_STREAM_OUTPUT StreamOutput; + CD3DX12_PIPELINE_STATE_STREAM_HS HS; + CD3DX12_PIPELINE_STATE_STREAM_DS DS; + CD3DX12_PIPELINE_STATE_STREAM_PS PS; + CD3DX12_PIPELINE_STATE_STREAM_AS AS; + CD3DX12_PIPELINE_STATE_STREAM_MS MS; + CD3DX12_PIPELINE_STATE_STREAM_CS CS; + CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC BlendState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL1 DepthStencilState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT DSVFormat; + CD3DX12_PIPELINE_STATE_STREAM_RASTERIZER RasterizerState; + CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS RTVFormats; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_DESC SampleDesc; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_MASK SampleMask; + CD3DX12_PIPELINE_STATE_STREAM_CACHED_PSO CachedPSO; + CD3DX12_PIPELINE_STATE_STREAM_VIEW_INSTANCING ViewInstancingDesc; + D3D12_GRAPHICS_PIPELINE_STATE_DESC GraphicsDescV0() const noexcept + { + D3D12_GRAPHICS_PIPELINE_STATE_DESC D; + D.Flags = this->Flags; + D.NodeMask = this->NodeMask; + D.pRootSignature = this->pRootSignature; + D.InputLayout = this->InputLayout; + D.IBStripCutValue = this->IBStripCutValue; + D.PrimitiveTopologyType = this->PrimitiveTopologyType; + D.VS = this->VS; + D.GS = this->GS; + D.StreamOutput = this->StreamOutput; + D.HS = this->HS; + D.DS = this->DS; + D.PS = this->PS; + D.BlendState = this->BlendState; + D.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(D3D12_DEPTH_STENCIL_DESC1(this->DepthStencilState)); + D.DSVFormat = this->DSVFormat; + D.RasterizerState = this->RasterizerState; + D.NumRenderTargets = D3D12_RT_FORMAT_ARRAY(this->RTVFormats).NumRenderTargets; + memcpy(D.RTVFormats, D3D12_RT_FORMAT_ARRAY(this->RTVFormats).RTFormats, sizeof(D.RTVFormats)); + D.SampleDesc = this->SampleDesc; + D.SampleMask = this->SampleMask; + D.CachedPSO = this->CachedPSO; + return D; + } + D3D12_COMPUTE_PIPELINE_STATE_DESC ComputeDescV0() const noexcept + { + D3D12_COMPUTE_PIPELINE_STATE_DESC D; + D.Flags = this->Flags; + D.NodeMask = this->NodeMask; + D.pRootSignature = this->pRootSignature; + D.CS = this->CS; + D.CachedPSO = this->CachedPSO; + return D; + } +}; + +// CD3DX12_PIPELINE_STATE_STREAM1 Works on OS Build 16299+ (where there is a new view instancing subobject). +// Use CD3DX12_PIPELINE_STATE_STREAM for OS Build 15063+ support. +struct CD3DX12_PIPELINE_STATE_STREAM1 +{ + CD3DX12_PIPELINE_STATE_STREAM1() = default; + // Mesh and amplification shaders must be set manually, since they do not have representation in D3D12_GRAPHICS_PIPELINE_STATE_DESC + CD3DX12_PIPELINE_STATE_STREAM1(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , InputLayout(Desc.InputLayout) + , IBStripCutValue(Desc.IBStripCutValue) + , PrimitiveTopologyType(Desc.PrimitiveTopologyType) + , VS(Desc.VS) + , GS(Desc.GS) + , StreamOutput(Desc.StreamOutput) + , HS(Desc.HS) + , DS(Desc.DS) + , PS(Desc.PS) + , BlendState(CD3DX12_BLEND_DESC(Desc.BlendState)) + , DepthStencilState(CD3DX12_DEPTH_STENCIL_DESC1(Desc.DepthStencilState)) + , DSVFormat(Desc.DSVFormat) + , RasterizerState(CD3DX12_RASTERIZER_DESC(Desc.RasterizerState)) + , RTVFormats(CD3DX12_RT_FORMAT_ARRAY(Desc.RTVFormats, Desc.NumRenderTargets)) + , SampleDesc(Desc.SampleDesc) + , SampleMask(Desc.SampleMask) + , CachedPSO(Desc.CachedPSO) + , ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT())) + {} + CD3DX12_PIPELINE_STATE_STREAM1(const D3DX12_MESH_SHADER_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , PrimitiveTopologyType(Desc.PrimitiveTopologyType) + , PS(Desc.PS) + , BlendState(CD3DX12_BLEND_DESC(Desc.BlendState)) + , DepthStencilState(CD3DX12_DEPTH_STENCIL_DESC1(Desc.DepthStencilState)) + , DSVFormat(Desc.DSVFormat) + , RasterizerState(CD3DX12_RASTERIZER_DESC(Desc.RasterizerState)) + , RTVFormats(CD3DX12_RT_FORMAT_ARRAY(Desc.RTVFormats, Desc.NumRenderTargets)) + , SampleDesc(Desc.SampleDesc) + , SampleMask(Desc.SampleMask) + , CachedPSO(Desc.CachedPSO) + , ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT())) + {} + CD3DX12_PIPELINE_STATE_STREAM1(const D3D12_COMPUTE_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , CS(CD3DX12_SHADER_BYTECODE(Desc.CS)) + , CachedPSO(Desc.CachedPSO) + { + static_cast(DepthStencilState).DepthEnable = false; + } + CD3DX12_PIPELINE_STATE_STREAM_FLAGS Flags; + CD3DX12_PIPELINE_STATE_STREAM_NODE_MASK NodeMask; + CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE pRootSignature; + CD3DX12_PIPELINE_STATE_STREAM_INPUT_LAYOUT InputLayout; + CD3DX12_PIPELINE_STATE_STREAM_IB_STRIP_CUT_VALUE IBStripCutValue; + CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY PrimitiveTopologyType; + CD3DX12_PIPELINE_STATE_STREAM_VS VS; + CD3DX12_PIPELINE_STATE_STREAM_GS GS; + CD3DX12_PIPELINE_STATE_STREAM_STREAM_OUTPUT StreamOutput; + CD3DX12_PIPELINE_STATE_STREAM_HS HS; + CD3DX12_PIPELINE_STATE_STREAM_DS DS; + CD3DX12_PIPELINE_STATE_STREAM_PS PS; + CD3DX12_PIPELINE_STATE_STREAM_CS CS; + CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC BlendState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL1 DepthStencilState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT DSVFormat; + CD3DX12_PIPELINE_STATE_STREAM_RASTERIZER RasterizerState; + CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS RTVFormats; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_DESC SampleDesc; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_MASK SampleMask; + CD3DX12_PIPELINE_STATE_STREAM_CACHED_PSO CachedPSO; + CD3DX12_PIPELINE_STATE_STREAM_VIEW_INSTANCING ViewInstancingDesc; + D3D12_GRAPHICS_PIPELINE_STATE_DESC GraphicsDescV0() const noexcept + { + D3D12_GRAPHICS_PIPELINE_STATE_DESC D; + D.Flags = this->Flags; + D.NodeMask = this->NodeMask; + D.pRootSignature = this->pRootSignature; + D.InputLayout = this->InputLayout; + D.IBStripCutValue = this->IBStripCutValue; + D.PrimitiveTopologyType = this->PrimitiveTopologyType; + D.VS = this->VS; + D.GS = this->GS; + D.StreamOutput = this->StreamOutput; + D.HS = this->HS; + D.DS = this->DS; + D.PS = this->PS; + D.BlendState = this->BlendState; + D.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(D3D12_DEPTH_STENCIL_DESC1(this->DepthStencilState)); + D.DSVFormat = this->DSVFormat; + D.RasterizerState = this->RasterizerState; + D.NumRenderTargets = D3D12_RT_FORMAT_ARRAY(this->RTVFormats).NumRenderTargets; + memcpy(D.RTVFormats, D3D12_RT_FORMAT_ARRAY(this->RTVFormats).RTFormats, sizeof(D.RTVFormats)); + D.SampleDesc = this->SampleDesc; + D.SampleMask = this->SampleMask; + D.CachedPSO = this->CachedPSO; + return D; + } + D3D12_COMPUTE_PIPELINE_STATE_DESC ComputeDescV0() const noexcept + { + D3D12_COMPUTE_PIPELINE_STATE_DESC D; + D.Flags = this->Flags; + D.NodeMask = this->NodeMask; + D.pRootSignature = this->pRootSignature; + D.CS = this->CS; + D.CachedPSO = this->CachedPSO; + return D; + } +}; + + +struct CD3DX12_PIPELINE_MESH_STATE_STREAM +{ + CD3DX12_PIPELINE_MESH_STATE_STREAM() = default; + CD3DX12_PIPELINE_MESH_STATE_STREAM(const D3DX12_MESH_SHADER_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , PrimitiveTopologyType(Desc.PrimitiveTopologyType) + , PS(Desc.PS) + , AS(Desc.AS) + , MS(Desc.MS) + , BlendState(CD3DX12_BLEND_DESC(Desc.BlendState)) + , DepthStencilState(CD3DX12_DEPTH_STENCIL_DESC1(Desc.DepthStencilState)) + , DSVFormat(Desc.DSVFormat) + , RasterizerState(CD3DX12_RASTERIZER_DESC(Desc.RasterizerState)) + , RTVFormats(CD3DX12_RT_FORMAT_ARRAY(Desc.RTVFormats, Desc.NumRenderTargets)) + , SampleDesc(Desc.SampleDesc) + , SampleMask(Desc.SampleMask) + , CachedPSO(Desc.CachedPSO) + , ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT())) + {} + CD3DX12_PIPELINE_STATE_STREAM_FLAGS Flags; + CD3DX12_PIPELINE_STATE_STREAM_NODE_MASK NodeMask; + CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE pRootSignature; + CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY PrimitiveTopologyType; + CD3DX12_PIPELINE_STATE_STREAM_PS PS; + CD3DX12_PIPELINE_STATE_STREAM_AS AS; + CD3DX12_PIPELINE_STATE_STREAM_MS MS; + CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC BlendState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL1 DepthStencilState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT DSVFormat; + CD3DX12_PIPELINE_STATE_STREAM_RASTERIZER RasterizerState; + CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS RTVFormats; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_DESC SampleDesc; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_MASK SampleMask; + CD3DX12_PIPELINE_STATE_STREAM_CACHED_PSO CachedPSO; + CD3DX12_PIPELINE_STATE_STREAM_VIEW_INSTANCING ViewInstancingDesc; + D3DX12_MESH_SHADER_PIPELINE_STATE_DESC MeshShaderDescV0() const noexcept + { + D3DX12_MESH_SHADER_PIPELINE_STATE_DESC D; + D.Flags = this->Flags; + D.NodeMask = this->NodeMask; + D.pRootSignature = this->pRootSignature; + D.PrimitiveTopologyType = this->PrimitiveTopologyType; + D.PS = this->PS; + D.AS = this->AS; + D.MS = this->MS; + D.BlendState = this->BlendState; + D.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(D3D12_DEPTH_STENCIL_DESC1(this->DepthStencilState)); + D.DSVFormat = this->DSVFormat; + D.RasterizerState = this->RasterizerState; + D.NumRenderTargets = D3D12_RT_FORMAT_ARRAY(this->RTVFormats).NumRenderTargets; + memcpy(D.RTVFormats, D3D12_RT_FORMAT_ARRAY(this->RTVFormats).RTFormats, sizeof(D.RTVFormats)); + D.SampleDesc = this->SampleDesc; + D.SampleMask = this->SampleMask; + D.CachedPSO = this->CachedPSO; + return D; + } +}; + +// CD3DX12_PIPELINE_STATE_STREAM works on OS Build 15063+ but does not support new subobject(s) added in OS Build 16299+. +// See CD3DX12_PIPELINE_STATE_STREAM1 for instance. +struct CD3DX12_PIPELINE_STATE_STREAM +{ + CD3DX12_PIPELINE_STATE_STREAM() = default; + CD3DX12_PIPELINE_STATE_STREAM(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , InputLayout(Desc.InputLayout) + , IBStripCutValue(Desc.IBStripCutValue) + , PrimitiveTopologyType(Desc.PrimitiveTopologyType) + , VS(Desc.VS) + , GS(Desc.GS) + , StreamOutput(Desc.StreamOutput) + , HS(Desc.HS) + , DS(Desc.DS) + , PS(Desc.PS) + , BlendState(CD3DX12_BLEND_DESC(Desc.BlendState)) + , DepthStencilState(CD3DX12_DEPTH_STENCIL_DESC1(Desc.DepthStencilState)) + , DSVFormat(Desc.DSVFormat) + , RasterizerState(CD3DX12_RASTERIZER_DESC(Desc.RasterizerState)) + , RTVFormats(CD3DX12_RT_FORMAT_ARRAY(Desc.RTVFormats, Desc.NumRenderTargets)) + , SampleDesc(Desc.SampleDesc) + , SampleMask(Desc.SampleMask) + , CachedPSO(Desc.CachedPSO) + , ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT())) + {} + CD3DX12_PIPELINE_STATE_STREAM(const D3DX12_MESH_SHADER_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , PrimitiveTopologyType(Desc.PrimitiveTopologyType) + , PS(Desc.PS) + , AS(Desc.AS) + , MS(Desc.MS) + , BlendState(CD3DX12_BLEND_DESC(Desc.BlendState)) + , DepthStencilState(CD3DX12_DEPTH_STENCIL_DESC1(Desc.DepthStencilState)) + , DSVFormat(Desc.DSVFormat) + , RasterizerState(CD3DX12_RASTERIZER_DESC(Desc.RasterizerState)) + , RTVFormats(CD3DX12_RT_FORMAT_ARRAY(Desc.RTVFormats, Desc.NumRenderTargets)) + , SampleDesc(Desc.SampleDesc) + , SampleMask(Desc.SampleMask) + , CachedPSO(Desc.CachedPSO) + , ViewInstancingDesc(CD3DX12_VIEW_INSTANCING_DESC(CD3DX12_DEFAULT())) + {} + CD3DX12_PIPELINE_STATE_STREAM(const D3D12_COMPUTE_PIPELINE_STATE_DESC& Desc) noexcept + : Flags(Desc.Flags) + , NodeMask(Desc.NodeMask) + , pRootSignature(Desc.pRootSignature) + , CS(CD3DX12_SHADER_BYTECODE(Desc.CS)) + , CachedPSO(Desc.CachedPSO) + {} + CD3DX12_PIPELINE_STATE_STREAM_FLAGS Flags; + CD3DX12_PIPELINE_STATE_STREAM_NODE_MASK NodeMask; + CD3DX12_PIPELINE_STATE_STREAM_ROOT_SIGNATURE pRootSignature; + CD3DX12_PIPELINE_STATE_STREAM_INPUT_LAYOUT InputLayout; + CD3DX12_PIPELINE_STATE_STREAM_IB_STRIP_CUT_VALUE IBStripCutValue; + CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY PrimitiveTopologyType; + CD3DX12_PIPELINE_STATE_STREAM_VS VS; + CD3DX12_PIPELINE_STATE_STREAM_GS GS; + CD3DX12_PIPELINE_STATE_STREAM_STREAM_OUTPUT StreamOutput; + CD3DX12_PIPELINE_STATE_STREAM_HS HS; + CD3DX12_PIPELINE_STATE_STREAM_DS DS; + CD3DX12_PIPELINE_STATE_STREAM_PS PS; + CD3DX12_PIPELINE_STATE_STREAM_AS AS; + CD3DX12_PIPELINE_STATE_STREAM_MS MS; + CD3DX12_PIPELINE_STATE_STREAM_CS CS; + CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC BlendState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL1 DepthStencilState; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_FORMAT DSVFormat; + CD3DX12_PIPELINE_STATE_STREAM_RASTERIZER RasterizerState; + CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS RTVFormats; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_DESC SampleDesc; + CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_MASK SampleMask; + CD3DX12_PIPELINE_STATE_STREAM_CACHED_PSO CachedPSO; + CD3DX12_PIPELINE_STATE_STREAM_VIEW_INSTANCING ViewInstancingDesc; + + // Xbox + CD3DX12_PIPELINE_STATE_STREAM_PIXEL_SHADER_OPTIONS PixelShaderOptionsX; + CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_OPTIONS DepthStencilOptionsX; + CD3DX12_PIPELINE_STATE_STREAM_GRAPHICS_SHADER_LIMITS GraphicsShaderLimitsX; + CD3DX12_PIPELINE_STATE_STREAM_TESSELLATION_PARAMETERS TessellationParametersX; + CD3DX12_PIPELINE_STATE_STREAM_COMPUTE_SHADER_LIMITS ComputeShaderLimitsX; + + D3D12_GRAPHICS_PIPELINE_STATE_DESC GraphicsDescV0() const noexcept + { + D3D12_GRAPHICS_PIPELINE_STATE_DESC D; + D.Flags = this->Flags; + D.NodeMask = this->NodeMask; + D.pRootSignature = this->pRootSignature; + D.InputLayout = this->InputLayout; + D.IBStripCutValue = this->IBStripCutValue; + D.PrimitiveTopologyType = this->PrimitiveTopologyType; + D.VS = this->VS; + D.GS = this->GS; + D.StreamOutput = this->StreamOutput; + D.HS = this->HS; + D.DS = this->DS; + D.PS = this->PS; + D.BlendState = this->BlendState; + D.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(D3D12_DEPTH_STENCIL_DESC1(this->DepthStencilState)); + D.DSVFormat = this->DSVFormat; + D.RasterizerState = this->RasterizerState; + D.NumRenderTargets = D3D12_RT_FORMAT_ARRAY(this->RTVFormats).NumRenderTargets; + memcpy(D.RTVFormats, D3D12_RT_FORMAT_ARRAY(this->RTVFormats).RTFormats, sizeof(D.RTVFormats)); + D.SampleDesc = this->SampleDesc; + D.SampleMask = this->SampleMask; + D.CachedPSO = this->CachedPSO; + return D; + } + D3D12_COMPUTE_PIPELINE_STATE_DESC ComputeDescV0() const noexcept + { + D3D12_COMPUTE_PIPELINE_STATE_DESC D; + D.Flags = this->Flags; + D.NodeMask = this->NodeMask; + D.pRootSignature = this->pRootSignature; + D.CS = this->CS; + D.CachedPSO = this->CachedPSO; + return D; + } +}; + +struct CD3DX12_PIPELINE_STATE_STREAM2_PARSE_HELPER : public ID3DX12PipelineParserCallbacks +{ + CD3DX12_PIPELINE_STATE_STREAM2 PipelineStream; + CD3DX12_PIPELINE_STATE_STREAM2_PARSE_HELPER() noexcept + : SeenDSS(false) + { + // Adjust defaults to account for absent members. + PipelineStream.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + + // Depth disabled if no DSV format specified. + static_cast(PipelineStream.DepthStencilState).DepthEnable = false; + } + + // ID3DX12PipelineParserCallbacks + void FlagsCb(D3D12_PIPELINE_STATE_FLAGS Flags) override {PipelineStream.Flags = Flags;} + void NodeMaskCb(UINT NodeMask) override {PipelineStream.NodeMask = NodeMask;} + void RootSignatureCb(ID3D12RootSignature* pRootSignature) override {PipelineStream.pRootSignature = pRootSignature;} + void InputLayoutCb(const D3D12_INPUT_LAYOUT_DESC& InputLayout) override {PipelineStream.InputLayout = InputLayout;} + void IBStripCutValueCb(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE IBStripCutValue) override {PipelineStream.IBStripCutValue = IBStripCutValue;} + void PrimitiveTopologyTypeCb(D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType) override {PipelineStream.PrimitiveTopologyType = PrimitiveTopologyType;} + void VSCb(const D3D12_SHADER_BYTECODE& VS) override {PipelineStream.VS = VS;} + void GSCb(const D3D12_SHADER_BYTECODE& GS) override {PipelineStream.GS = GS;} + void StreamOutputCb(const D3D12_STREAM_OUTPUT_DESC& StreamOutput) override {PipelineStream.StreamOutput = StreamOutput;} + void HSCb(const D3D12_SHADER_BYTECODE& HS) override {PipelineStream.HS = HS;} + void DSCb(const D3D12_SHADER_BYTECODE& DS) override {PipelineStream.DS = DS;} + void PSCb(const D3D12_SHADER_BYTECODE& PS) override {PipelineStream.PS = PS;} + void CSCb(const D3D12_SHADER_BYTECODE& CS) override {PipelineStream.CS = CS;} + void ASCb(const D3D12_SHADER_BYTECODE& AS) override {PipelineStream.AS = AS;} + void MSCb(const D3D12_SHADER_BYTECODE& MS) override {PipelineStream.MS = MS;} + void BlendStateCb(const D3D12_BLEND_DESC& BlendState) override {PipelineStream.BlendState = CD3DX12_BLEND_DESC(BlendState);} + void DepthStencilStateCb(const D3D12_DEPTH_STENCIL_DESC& DepthStencilState) override + { + PipelineStream.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(DepthStencilState); + SeenDSS = true; + } + void DepthStencilState1Cb(const D3D12_DEPTH_STENCIL_DESC1& DepthStencilState) override + { + PipelineStream.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(DepthStencilState); + SeenDSS = true; + } + void DSVFormatCb(DXGI_FORMAT DSVFormat) override + { + PipelineStream.DSVFormat = DSVFormat; + if (!SeenDSS && DSVFormat != DXGI_FORMAT_UNKNOWN) + { + // Re-enable depth for the default state. + static_cast(PipelineStream.DepthStencilState).DepthEnable = true; + } + } + void RasterizerStateCb(const D3D12_RASTERIZER_DESC& RasterizerState) override {PipelineStream.RasterizerState = CD3DX12_RASTERIZER_DESC(RasterizerState);} + void RTVFormatsCb(const D3D12_RT_FORMAT_ARRAY& RTVFormats) override {PipelineStream.RTVFormats = RTVFormats;} + void SampleDescCb(const DXGI_SAMPLE_DESC& SampleDesc) override {PipelineStream.SampleDesc = SampleDesc;} + void SampleMaskCb(UINT SampleMask) override {PipelineStream.SampleMask = SampleMask;} + void ViewInstancingCb(const D3D12_VIEW_INSTANCING_DESC& ViewInstancingDesc) override {PipelineStream.ViewInstancingDesc = CD3DX12_VIEW_INSTANCING_DESC(ViewInstancingDesc);} + void CachedPSOCb(const D3D12_CACHED_PIPELINE_STATE& CachedPSO) override {PipelineStream.CachedPSO = CachedPSO;} + +private: + bool SeenDSS; +}; + + +struct CD3DX12_PIPELINE_STATE_STREAM3_PARSE_HELPER : public ID3DX12PipelineParserCallbacks +{ + CD3DX12_PIPELINE_STATE_STREAM3 PipelineStream; + CD3DX12_PIPELINE_STATE_STREAM3_PARSE_HELPER() noexcept + : SeenDSS(false) + { + // Adjust defaults to account for absent members. + PipelineStream.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + + // Depth disabled if no DSV format specified. + static_cast(PipelineStream.DepthStencilState).DepthEnable = false; + } + + // ID3DX12PipelineParserCallbacks + void FlagsCb(D3D12_PIPELINE_STATE_FLAGS Flags) override { PipelineStream.Flags = Flags; } + void NodeMaskCb(UINT NodeMask) override { PipelineStream.NodeMask = NodeMask; } + void RootSignatureCb(ID3D12RootSignature* pRootSignature) override { PipelineStream.pRootSignature = pRootSignature; } + void InputLayoutCb(const D3D12_INPUT_LAYOUT_DESC& InputLayout) override { PipelineStream.InputLayout = InputLayout; } + void IBStripCutValueCb(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE IBStripCutValue) override { PipelineStream.IBStripCutValue = IBStripCutValue; } + void PrimitiveTopologyTypeCb(D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType) override { PipelineStream.PrimitiveTopologyType = PrimitiveTopologyType; } + void VSCb(const D3D12_SHADER_BYTECODE& VS) override { PipelineStream.VS = VS; } + void GSCb(const D3D12_SHADER_BYTECODE& GS) override { PipelineStream.GS = GS; } + void StreamOutputCb(const D3D12_STREAM_OUTPUT_DESC& StreamOutput) override { PipelineStream.StreamOutput = StreamOutput; } + void HSCb(const D3D12_SHADER_BYTECODE& HS) override { PipelineStream.HS = HS; } + void DSCb(const D3D12_SHADER_BYTECODE& DS) override { PipelineStream.DS = DS; } + void PSCb(const D3D12_SHADER_BYTECODE& PS) override { PipelineStream.PS = PS; } + void CSCb(const D3D12_SHADER_BYTECODE& CS) override { PipelineStream.CS = CS; } + void ASCb(const D3D12_SHADER_BYTECODE& AS) override { PipelineStream.AS = AS; } + void MSCb(const D3D12_SHADER_BYTECODE& MS) override { PipelineStream.MS = MS; } + void BlendStateCb(const D3D12_BLEND_DESC& BlendState) override { PipelineStream.BlendState = CD3DX12_BLEND_DESC(BlendState); } + void DepthStencilStateCb(const D3D12_DEPTH_STENCIL_DESC& DepthStencilState) override + { + PipelineStream.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(DepthStencilState); + SeenDSS = true; + } + void DepthStencilState1Cb(const D3D12_DEPTH_STENCIL_DESC1& DepthStencilState) override + { + PipelineStream.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(DepthStencilState); + SeenDSS = true; + } + void DSVFormatCb(DXGI_FORMAT DSVFormat) override + { + PipelineStream.DSVFormat = DSVFormat; + if (!SeenDSS && DSVFormat != DXGI_FORMAT_UNKNOWN) + { + // Re-enable depth for the default state. + static_cast(PipelineStream.DepthStencilState).DepthEnable = true; + } + } + void RasterizerStateCb(const D3D12_RASTERIZER_DESC& RasterizerState) override { PipelineStream.RasterizerState = CD3DX12_RASTERIZER_DESC(RasterizerState); } + void RTVFormatsCb(const D3D12_RT_FORMAT_ARRAY& RTVFormats) override { PipelineStream.RTVFormats = RTVFormats; } + void SampleDescCb(const DXGI_SAMPLE_DESC& SampleDesc) override { PipelineStream.SampleDesc = SampleDesc; } + void SampleMaskCb(UINT SampleMask) override { PipelineStream.SampleMask = SampleMask; } + void ViewInstancingCb(const D3D12_VIEW_INSTANCING_DESC& ViewInstancingDesc) override { PipelineStream.ViewInstancingDesc = CD3DX12_VIEW_INSTANCING_DESC(ViewInstancingDesc); } + void CachedPSOCb(const D3D12_CACHED_PIPELINE_STATE& CachedPSO) override { PipelineStream.CachedPSO = CachedPSO; } + +private: + bool SeenDSS; +}; + +struct CD3DX12_PIPELINE_STATE_STREAM_PARSE_HELPER : public ID3DX12PipelineParserCallbacks +{ + CD3DX12_PIPELINE_STATE_STREAM PipelineStream; + CD3DX12_PIPELINE_STATE_STREAM_PARSE_HELPER() noexcept + : SeenDSS(false) + { + // Adjust defaults to account for absent members. + PipelineStream.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + + // Depth disabled if no DSV format specified. + static_cast(PipelineStream.DepthStencilState).DepthEnable = false; + } + + // ID3DX12PipelineParserCallbacks + void FlagsCb(D3D12_PIPELINE_STATE_FLAGS Flags) override {PipelineStream.Flags = Flags;} + void NodeMaskCb(UINT NodeMask) override {PipelineStream.NodeMask = NodeMask;} + void RootSignatureCb(ID3D12RootSignature* pRootSignature) override {PipelineStream.pRootSignature = pRootSignature;} + void InputLayoutCb(const D3D12_INPUT_LAYOUT_DESC& InputLayout) override {PipelineStream.InputLayout = InputLayout;} + void IBStripCutValueCb(D3D12_INDEX_BUFFER_STRIP_CUT_VALUE IBStripCutValue) override {PipelineStream.IBStripCutValue = IBStripCutValue;} + void PrimitiveTopologyTypeCb(D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType) override {PipelineStream.PrimitiveTopologyType = PrimitiveTopologyType;} + void VSCb(const D3D12_SHADER_BYTECODE& VS) override {PipelineStream.VS = VS;} + void GSCb(const D3D12_SHADER_BYTECODE& GS) override {PipelineStream.GS = GS;} + void StreamOutputCb(const D3D12_STREAM_OUTPUT_DESC& StreamOutput) override {PipelineStream.StreamOutput = StreamOutput;} + void HSCb(const D3D12_SHADER_BYTECODE& HS) override {PipelineStream.HS = HS;} + void DSCb(const D3D12_SHADER_BYTECODE& DS) override {PipelineStream.DS = DS;} + void PSCb(const D3D12_SHADER_BYTECODE& PS) override {PipelineStream.PS = PS;} + void CSCb(const D3D12_SHADER_BYTECODE& CS) override {PipelineStream.CS = CS;} + void ASCb(const D3D12_SHADER_BYTECODE& AS) override {PipelineStream.AS = AS;} + void MSCb(const D3D12_SHADER_BYTECODE& MS) override {PipelineStream.MS = MS;} + void BlendStateCb(const D3D12_BLEND_DESC& BlendState) override {PipelineStream.BlendState = CD3DX12_BLEND_DESC(BlendState);} + void DepthStencilStateCb(const D3D12_DEPTH_STENCIL_DESC& DepthStencilState) override + { + PipelineStream.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(DepthStencilState); + SeenDSS = true; + } + void DepthStencilState1Cb(const D3D12_DEPTH_STENCIL_DESC1& DepthStencilState) override + { + PipelineStream.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC1(DepthStencilState); + SeenDSS = true; + } + void DSVFormatCb(DXGI_FORMAT DSVFormat) override + { + PipelineStream.DSVFormat = DSVFormat; + if (!SeenDSS && DSVFormat != DXGI_FORMAT_UNKNOWN) + { + // Re-enable depth for the default state. + static_cast(PipelineStream.DepthStencilState).DepthEnable = true; + } + } + void RasterizerStateCb(const D3D12_RASTERIZER_DESC& RasterizerState) override {PipelineStream.RasterizerState = CD3DX12_RASTERIZER_DESC(RasterizerState);} + void RTVFormatsCb(const D3D12_RT_FORMAT_ARRAY& RTVFormats) override {PipelineStream.RTVFormats = RTVFormats;} + void SampleDescCb(const DXGI_SAMPLE_DESC& SampleDesc) override {PipelineStream.SampleDesc = SampleDesc;} + void SampleMaskCb(UINT SampleMask) override {PipelineStream.SampleMask = SampleMask;} + void ViewInstancingCb(const D3D12_VIEW_INSTANCING_DESC& ViewInstancingDesc) override {PipelineStream.ViewInstancingDesc = CD3DX12_VIEW_INSTANCING_DESC(ViewInstancingDesc);} + void CachedPSOCb(const D3D12_CACHED_PIPELINE_STATE& CachedPSO) override {PipelineStream.CachedPSO = CachedPSO;} + + + // Xbox + void XboxSetPixelShaderOptions(const D3D12XBOX_PIXEL_SHADER_OPTIONS_DESC& desc) override {PipelineStream.PixelShaderOptionsX = CD3D12XBOX_PIXEL_SHADER_OPTIONS_DESC(desc);} + void XboxSetDepthStencilOptions(const D3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC& desc) override {PipelineStream.DepthStencilOptionsX = CD3D12XBOX_DEPTH_STENCIL_OPTIONS_DESC(desc);} + void XboxSetGraphicsShaderLimits(const D3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC& desc) override {PipelineStream.GraphicsShaderLimitsX = CD3D12XBOX_GRAPHICS_SHADER_LIMITS_DESC(desc);} + void XboxSetTessellationParameters(const D3D12XBOX_TESSELLATION_PARAMETERS_DESC& desc) override {PipelineStream.TessellationParametersX = CD3D12XBOX_TESSELLATION_PARAMETERS_DESC(desc);} + void XboxSetComputeShaderLimits(const D3D12XBOX_COMPUTE_SHADER_LIMITS_DESC& desc) override {PipelineStream.ComputeShaderLimitsX = CD3D12XBOX_COMPUTE_SHADER_LIMITS_DESC(desc);} + +private: + bool SeenDSS; +}; + + +inline D3D12_PIPELINE_STATE_SUBOBJECT_TYPE D3DX12GetBaseSubobjectType(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE SubobjectType) noexcept +{ + switch (SubobjectType) + { + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: + return D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL; + default: + return SubobjectType; + } +} + +inline HRESULT D3DX12ParsePipelineStream(const D3D12_PIPELINE_STATE_STREAM_DESC& Desc, ID3DX12PipelineParserCallbacks* pCallbacks) +{ + if (pCallbacks == nullptr) + { + return E_INVALIDARG; + } + + if (Desc.SizeInBytes == 0 || Desc.pPipelineStateSubobjectStream == nullptr) + { + pCallbacks->ErrorBadInputParameter(1); // first parameter issue + return E_INVALIDARG; + } + + bool SubobjectSeen[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID] = {}; + for (SIZE_T CurOffset = 0, SizeOfSubobject = 0; CurOffset < Desc.SizeInBytes; CurOffset += SizeOfSubobject) + { + BYTE* pStream = static_cast(Desc.pPipelineStateSubobjectStream)+CurOffset; + auto SubobjectType = *reinterpret_cast(pStream); + if (SubobjectType < 0 || SubobjectType >= D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID) + { + pCallbacks->ErrorUnknownSubobject(SubobjectType); + return E_INVALIDARG; + } + if (SubobjectSeen[D3DX12GetBaseSubobjectType(SubobjectType)]) + { + pCallbacks->ErrorDuplicateSubobject(SubobjectType); + return E_INVALIDARG; // disallow subobject duplicates in a stream + } + SubobjectSeen[SubobjectType] = true; + switch (SubobjectType) + { + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: + pCallbacks->RootSignatureCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::pRootSignature); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: + pCallbacks->VSCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::VS); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: + pCallbacks->PSCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::PS); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: + pCallbacks->DSCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::DS); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: + pCallbacks->HSCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::HS); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: + pCallbacks->GSCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::GS); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: + pCallbacks->CSCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::CS); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: + pCallbacks->ASCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM_AS); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: + pCallbacks->MSCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM_MS); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: + pCallbacks->StreamOutputCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::StreamOutput); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND: + pCallbacks->BlendStateCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::BlendState); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK: + pCallbacks->SampleMaskCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::SampleMask); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER: + pCallbacks->RasterizerStateCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::RasterizerState); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL: + pCallbacks->DepthStencilStateCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: + pCallbacks->DepthStencilState1Cb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::DepthStencilState); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: + pCallbacks->InputLayoutCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::InputLayout); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE: + pCallbacks->IBStripCutValueCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::IBStripCutValue); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY: + pCallbacks->PrimitiveTopologyTypeCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::PrimitiveTopologyType); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS: + pCallbacks->RTVFormatsCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::RTVFormats); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT: + pCallbacks->DSVFormatCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::DSVFormat); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC: + pCallbacks->SampleDescCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::SampleDesc); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK: + pCallbacks->NodeMaskCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::NodeMask); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: + pCallbacks->CachedPSOCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::CachedPSO); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS: + pCallbacks->FlagsCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::Flags); + break; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING: + pCallbacks->ViewInstancingCb(*reinterpret_cast(pStream)); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM::ViewInstancingDesc); + break; + + // + // Xbox + // + case D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_PIXEL_SHADER_OPTIONS: + pCallbacks->XboxSetPixelShaderOptions(static_cast(*reinterpret_cast(pStream))); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM_PIXEL_SHADER_OPTIONS); + break; + case D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_OPTIONS: + pCallbacks->XboxSetDepthStencilOptions(static_cast(*reinterpret_cast(pStream))); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL_OPTIONS); + break; + case D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_GRAPHICS_SHADER_LIMITS: + pCallbacks->XboxSetGraphicsShaderLimits(static_cast(*reinterpret_cast(pStream))); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM_GRAPHICS_SHADER_LIMITS); + break; + case D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_TESSELLATION_PARAMETERS: + pCallbacks->XboxSetTessellationParameters(static_cast(*reinterpret_cast(pStream))); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM_TESSELLATION_PARAMETERS); + break; + case D3D12XBOX_PIPELINE_STATE_SUBOBJECT_TYPE_COMPUTE_SHADER_LIMITS: + pCallbacks->XboxSetComputeShaderLimits(static_cast(*reinterpret_cast(pStream))); + SizeOfSubobject = sizeof(CD3DX12_PIPELINE_STATE_STREAM_COMPUTE_SHADER_LIMITS); + break; + default: + pCallbacks->ErrorUnknownSubobject(SubobjectType); + return E_INVALIDARG; + } + } + + return S_OK; +} + +//------------------------------------------------------------------------------------------------ +inline bool operator==( const D3D12_CLEAR_VALUE &a, const D3D12_CLEAR_VALUE &b) noexcept +{ + if (a.Format != b.Format) return false; + if (a.Format == DXGI_FORMAT_D24_UNORM_S8_UINT + || a.Format == DXGI_FORMAT_D16_UNORM + || a.Format == DXGI_FORMAT_D32_FLOAT + || a.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT) + { + return (a.DepthStencil.Depth == b.DepthStencil.Depth) && + (a.DepthStencil.Stencil == b.DepthStencil.Stencil); + } else { + return (a.Color[0] == b.Color[0]) && + (a.Color[1] == b.Color[1]) && + (a.Color[2] == b.Color[2]) && + (a.Color[3] == b.Color[3]); + } +} +inline bool operator==( const D3D12_RENDER_PASS_BEGINNING_ACCESS_CLEAR_PARAMETERS &a, const D3D12_RENDER_PASS_BEGINNING_ACCESS_CLEAR_PARAMETERS &b) noexcept +{ + return a.ClearValue == b.ClearValue; +} +inline bool operator==( const D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS &a, const D3D12_RENDER_PASS_ENDING_ACCESS_RESOLVE_PARAMETERS &b) noexcept +{ + if (a.pSrcResource != b.pSrcResource) return false; + if (a.pDstResource != b.pDstResource) return false; + if (a.SubresourceCount != b.SubresourceCount) return false; + if (a.Format != b.Format) return false; + if (a.ResolveMode != b.ResolveMode) return false; + if (a.PreserveResolveSource != b.PreserveResolveSource) return false; + return true; +} +inline bool operator==( const D3D12_RENDER_PASS_BEGINNING_ACCESS &a, const D3D12_RENDER_PASS_BEGINNING_ACCESS &b) noexcept +{ + if (a.Type != b.Type) return false; + if (a.Type == D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR && !(a.Clear == b.Clear)) return false; + return true; +} +inline bool operator==( const D3D12_RENDER_PASS_ENDING_ACCESS &a, const D3D12_RENDER_PASS_ENDING_ACCESS &b) noexcept +{ + if (a.Type != b.Type) return false; + if (a.Type == D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE && !(a.Resolve == b.Resolve)) return false; + return true; +} +inline bool operator==( const D3D12_RENDER_PASS_RENDER_TARGET_DESC &a, const D3D12_RENDER_PASS_RENDER_TARGET_DESC &b) noexcept +{ + if (a.cpuDescriptor.ptr != b.cpuDescriptor.ptr) return false; + if (!(a.BeginningAccess == b.BeginningAccess)) return false; + if (!(a.EndingAccess == b.EndingAccess)) return false; + return true; +} +inline bool operator==( const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC &a, const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC &b) noexcept +{ + if (a.cpuDescriptor.ptr != b.cpuDescriptor.ptr) return false; + if (!(a.DepthBeginningAccess == b.DepthBeginningAccess)) return false; + if (!(a.StencilBeginningAccess == b.StencilBeginningAccess)) return false; + if (!(a.DepthEndingAccess == b.DepthEndingAccess)) return false; + if (!(a.StencilEndingAccess == b.StencilEndingAccess)) return false; + return true; +} + + +#ifndef D3DX12_NO_STATE_OBJECT_HELPERS + +//================================================================================================ +// D3DX12 State Object Creation Helpers +// +// Helper classes for creating new style state objects out of an arbitrary set of subobjects. +// Uses STL +// +// Start by instantiating CD3DX12_STATE_OBJECT_DESC (see its public methods). +// One of its methods is CreateSubobject(), which has a comment showing a couple of options for +// defining subobjects using the helper classes for each subobject (CD3DX12_DXIL_LIBRARY_SUBOBJECT +// etc.). The subobject helpers each have methods specific to the subobject for configuring its +// contents. +// +//================================================================================================ +#include +#include +#include +#include +#ifndef D3DX12_USE_ATL +#include +#define D3DX12_COM_PTR Microsoft::WRL::ComPtr +#define D3DX12_COM_PTR_GET(x) x.Get() +#define D3DX12_COM_PTR_ADDRESSOF(x) x.GetAddressOf() +#else +#include +#define D3DX12_COM_PTR ATL::CComPtr +#define D3DX12_COM_PTR_GET(x) x.p +#define D3DX12_COM_PTR_ADDRESSOF(x) &x.p +#endif + +//------------------------------------------------------------------------------------------------ +class CD3DX12_STATE_OBJECT_DESC +{ +public: + CD3DX12_STATE_OBJECT_DESC() noexcept + { + Init(D3D12_STATE_OBJECT_TYPE_COLLECTION); + } + CD3DX12_STATE_OBJECT_DESC(D3D12_STATE_OBJECT_TYPE Type) noexcept + { + Init(Type); + } + void SetStateObjectType(D3D12_STATE_OBJECT_TYPE Type) noexcept { m_Desc.Type = Type; } + CD3DX12_STATE_OBJECT_DESC(const CD3DX12_STATE_OBJECT_DESC& other) = delete; + CD3DX12_STATE_OBJECT_DESC& operator=(const CD3DX12_STATE_OBJECT_DESC& other) = delete; + CD3DX12_STATE_OBJECT_DESC(CD3DX12_STATE_OBJECT_DESC&& other) = default; + CD3DX12_STATE_OBJECT_DESC& operator=(CD3DX12_STATE_OBJECT_DESC&& other) = default; + operator const D3D12_STATE_OBJECT_DESC&() + { + // Do final preparation work + m_RepointedAssociations.clear(); + m_SubobjectArray.clear(); + m_SubobjectArray.reserve(m_Desc.NumSubobjects); + // Flatten subobjects into an array (each flattened subobject still has a + // member that's a pointer to its desc that's not flattened) + for (auto Iter = m_SubobjectList.begin(); + Iter != m_SubobjectList.end(); Iter++) + { + m_SubobjectArray.push_back(*Iter); + // Store new location in array so we can redirect pointers contained in subobjects + Iter->pSubobjectArrayLocation = &m_SubobjectArray.back(); + } + // For subobjects with pointer fields, create a new copy of those subobject definitions + // with fixed pointers + for (UINT i = 0; i < m_Desc.NumSubobjects; i++) + { + if (m_SubobjectArray[i].Type == D3D12_STATE_SUBOBJECT_TYPE_SUBOBJECT_TO_EXPORTS_ASSOCIATION) + { + auto pOriginalSubobjectAssociation = + static_cast(m_SubobjectArray[i].pDesc); + D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION Repointed = *pOriginalSubobjectAssociation; + auto pWrapper = + static_cast(pOriginalSubobjectAssociation->pSubobjectToAssociate); + Repointed.pSubobjectToAssociate = pWrapper->pSubobjectArrayLocation; + m_RepointedAssociations.push_back(Repointed); + m_SubobjectArray[i].pDesc = &m_RepointedAssociations.back(); + } + } + // Below: using ugly way to get pointer in case .data() is not defined + m_Desc.pSubobjects = m_Desc.NumSubobjects ? &m_SubobjectArray[0] : nullptr; + return m_Desc; + } + operator const D3D12_STATE_OBJECT_DESC*() + { + // Cast calls the above final preparation work + return &static_cast(*this); + } + + // CreateSubobject creates a sububject helper (e.g. CD3DX12_HIT_GROUP_SUBOBJECT) + // whose lifetime is owned by this class. + // e.g. + // + // CD3DX12_STATE_OBJECT_DESC Collection1(D3D12_STATE_OBJECT_TYPE_COLLECTION); + // auto Lib0 = Collection1.CreateSubobject(); + // Lib0->SetDXILLibrary(&pMyAppDxilLibs[0]); + // Lib0->DefineExport(L"rayGenShader0"); // in practice these export listings might be + // // data/engine driven + // etc. + // + // Alternatively, users can instantiate sububject helpers explicitly, such as via local + // variables instead, passing the state object desc that should point to it into the helper + // constructor (or call mySubobjectHelper.AddToStateObject(Collection1)). + // In this alternative scenario, the user must keep the subobject alive as long as the state + // object it is associated with is alive, else its pointer references will be stale. + // e.g. + // + // CD3DX12_STATE_OBJECT_DESC RaytracingState2(D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE); + // CD3DX12_DXIL_LIBRARY_SUBOBJECT LibA(RaytracingState2); + // LibA.SetDXILLibrary(&pMyAppDxilLibs[4]); // not manually specifying exports + // // - meaning all exports in the libraries + // // are exported + // etc. + + template + T* CreateSubobject() + { + T* pSubobject = new T(*this); + m_OwnedSubobjectHelpers.emplace_back(pSubobject); + return pSubobject; + } + +private: + D3D12_STATE_SUBOBJECT* TrackSubobject(D3D12_STATE_SUBOBJECT_TYPE Type, void* pDesc) + { + SUBOBJECT_WRAPPER Subobject; + Subobject.pSubobjectArrayLocation = nullptr; + Subobject.Type = Type; + Subobject.pDesc = pDesc; + m_SubobjectList.push_back(Subobject); + m_Desc.NumSubobjects++; + return &m_SubobjectList.back(); + } + void Init(D3D12_STATE_OBJECT_TYPE Type) noexcept + { + SetStateObjectType(Type); + m_Desc.pSubobjects = nullptr; + m_Desc.NumSubobjects = 0; + m_SubobjectList.clear(); + m_SubobjectArray.clear(); + m_RepointedAssociations.clear(); + } + typedef struct SUBOBJECT_WRAPPER : public D3D12_STATE_SUBOBJECT + { + D3D12_STATE_SUBOBJECT* pSubobjectArrayLocation; // new location when flattened into array + // for repointing pointers in subobjects + } SUBOBJECT_WRAPPER; + D3D12_STATE_OBJECT_DESC m_Desc; + std::list m_SubobjectList; // Pointers to list nodes handed out so + // these can be edited live + std::vector m_SubobjectArray; // Built at the end, copying list contents + + std::list + m_RepointedAssociations; // subobject type that contains pointers to other subobjects, + // repointed to flattened array + + class StringContainer + { + public: + LPCWSTR LocalCopy(LPCWSTR string, bool bSingleString = false) + { + if (string) + { + if (bSingleString) + { + m_Strings.clear(); + m_Strings.push_back(string); + } + else + { + m_Strings.push_back(string); + } + return m_Strings.back().c_str(); + } + else + { + return nullptr; + } + } + void clear() noexcept { m_Strings.clear(); } + private: + std::list m_Strings; + }; + + class SUBOBJECT_HELPER_BASE + { + public: + SUBOBJECT_HELPER_BASE() noexcept { Init(); } + virtual ~SUBOBJECT_HELPER_BASE() = default; + virtual D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept = 0; + SUBOBJECT_HELPER_BASE(const SUBOBJECT_HELPER_BASE& other) = delete; + SUBOBJECT_HELPER_BASE& operator=(const SUBOBJECT_HELPER_BASE& other) = delete; + SUBOBJECT_HELPER_BASE(SUBOBJECT_HELPER_BASE&& other) = default; + SUBOBJECT_HELPER_BASE& operator=(SUBOBJECT_HELPER_BASE&& other) = default; + void AddToStateObject(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + m_pSubobject = ContainingStateObject.TrackSubobject(Type(), Data()); + } + protected: + virtual void* Data() noexcept = 0; + void Init() noexcept { m_pSubobject = nullptr; } + D3D12_STATE_SUBOBJECT* m_pSubobject; + }; + +#if(__cplusplus >= 201103L) + std::list> m_OwnedSubobjectHelpers; +#else + class OWNED_HELPER + { + public: + OWNED_HELPER(const SUBOBJECT_HELPER_BASE* pHelper) noexcept { m_pHelper = pHelper; } + ~OWNED_HELPER() { delete m_pHelper; } + const SUBOBJECT_HELPER_BASE* m_pHelper; + }; + + std::list m_OwnedSubobjectHelpers; +#endif + + friend class CD3DX12_DXIL_LIBRARY_SUBOBJECT; + friend class CD3DX12_EXISTING_COLLECTION_SUBOBJECT; + friend class CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT; + friend class CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION; + friend class CD3DX12_HIT_GROUP_SUBOBJECT; + friend class CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT; + friend class CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT; + friend class CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT; + friend class CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT; + friend class CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT; + friend class CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT; + friend class CD3DX12_NODE_MASK_SUBOBJECT; + + + // XBOX + friend class CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_DXIL_LIBRARY_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_DXIL_LIBRARY_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_DXIL_LIBRARY_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_DXIL_LIBRARY_SUBOBJECT(const CD3DX12_DXIL_LIBRARY_SUBOBJECT& other) = delete; + CD3DX12_DXIL_LIBRARY_SUBOBJECT& operator=(const CD3DX12_DXIL_LIBRARY_SUBOBJECT& other) = delete; + CD3DX12_DXIL_LIBRARY_SUBOBJECT(CD3DX12_DXIL_LIBRARY_SUBOBJECT&& other) = default; + CD3DX12_DXIL_LIBRARY_SUBOBJECT& operator=(CD3DX12_DXIL_LIBRARY_SUBOBJECT&& other) = default; + void SetDXILLibrary(const D3D12_SHADER_BYTECODE* pCode) noexcept + { + static const D3D12_SHADER_BYTECODE Default = {}; + m_Desc.DXILLibrary = pCode ? *pCode : Default; + } + void DefineExport( + LPCWSTR Name, + LPCWSTR ExportToRename = nullptr, + D3D12_EXPORT_FLAGS Flags = D3D12_EXPORT_FLAG_NONE) + { + D3D12_EXPORT_DESC Export; + Export.Name = m_Strings.LocalCopy(Name); + Export.ExportToRename = m_Strings.LocalCopy(ExportToRename); + Export.Flags = Flags; + m_Exports.push_back(Export); + m_Desc.pExports = &m_Exports[0]; // using ugly way to get pointer in case .data() is not defined + m_Desc.NumExports = static_cast(m_Exports.size()); + } + template + void DefineExports(LPCWSTR(&Exports)[N]) + { + for (UINT i = 0; i < N; i++) + { + DefineExport(Exports[i]); + } + } + void DefineExports(const LPCWSTR* Exports, UINT N) + { + for (UINT i = 0; i < N; i++) + { + DefineExport(Exports[i]); + } + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_DXIL_LIBRARY_DESC&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + m_Strings.clear(); + m_Exports.clear(); + } + void* Data() noexcept override { return &m_Desc; } + D3D12_DXIL_LIBRARY_DESC m_Desc; + CD3DX12_STATE_OBJECT_DESC::StringContainer m_Strings; + std::vector m_Exports; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_EXISTING_COLLECTION_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_EXISTING_COLLECTION_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_EXISTING_COLLECTION_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_EXISTING_COLLECTION_SUBOBJECT(const CD3DX12_EXISTING_COLLECTION_SUBOBJECT& other) = delete; + CD3DX12_EXISTING_COLLECTION_SUBOBJECT& operator=(const CD3DX12_EXISTING_COLLECTION_SUBOBJECT& other) = delete; + CD3DX12_EXISTING_COLLECTION_SUBOBJECT(CD3DX12_EXISTING_COLLECTION_SUBOBJECT&& other) = default; + CD3DX12_EXISTING_COLLECTION_SUBOBJECT& operator=(CD3DX12_EXISTING_COLLECTION_SUBOBJECT&& other) = default; + void SetExistingCollection(ID3D12StateObject*pExistingCollection) noexcept + { + m_Desc.pExistingCollection = pExistingCollection; + m_CollectionRef = pExistingCollection; + } + void DefineExport( + LPCWSTR Name, + LPCWSTR ExportToRename = nullptr, + D3D12_EXPORT_FLAGS Flags = D3D12_EXPORT_FLAG_NONE) + { + D3D12_EXPORT_DESC Export; + Export.Name = m_Strings.LocalCopy(Name); + Export.ExportToRename = m_Strings.LocalCopy(ExportToRename); + Export.Flags = Flags; + m_Exports.push_back(Export); + m_Desc.pExports = &m_Exports[0]; // using ugly way to get pointer in case .data() is not defined + m_Desc.NumExports = static_cast(m_Exports.size()); + } + template + void DefineExports(LPCWSTR(&Exports)[N]) + { + for (UINT i = 0; i < N; i++) + { + DefineExport(Exports[i]); + } + } + void DefineExports(const LPCWSTR* Exports, UINT N) + { + for (UINT i = 0; i < N; i++) + { + DefineExport(Exports[i]); + } + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_EXISTING_COLLECTION; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_EXISTING_COLLECTION_DESC&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + m_CollectionRef = nullptr; + m_Strings.clear(); + m_Exports.clear(); + } + void* Data() noexcept override { return &m_Desc; } + D3D12_EXISTING_COLLECTION_DESC m_Desc; + D3DX12_COM_PTR m_CollectionRef; + CD3DX12_STATE_OBJECT_DESC::StringContainer m_Strings; + std::vector m_Exports; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT(const CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT& other) = delete; + CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT& operator=(const CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT& other) = delete; + CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT(CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT&& other) = default; + CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT& operator=(CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT&& other) = default; + void SetSubobjectToAssociate(const D3D12_STATE_SUBOBJECT& SubobjectToAssociate) noexcept + { + m_Desc.pSubobjectToAssociate = &SubobjectToAssociate; + } + void AddExport(LPCWSTR Export) + { + m_Desc.NumExports++; + m_Exports.push_back(m_Strings.LocalCopy(Export)); + m_Desc.pExports = &m_Exports[0]; // using ugly way to get pointer in case .data() is not defined + } + template + void AddExports(LPCWSTR (&Exports)[N]) + { + for (UINT i = 0; i < N; i++) + { + AddExport(Exports[i]); + } + } + void AddExports(const LPCWSTR* Exports, UINT N) + { + for (UINT i = 0; i < N; i++) + { + AddExport(Exports[i]); + } + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_SUBOBJECT_TO_EXPORTS_ASSOCIATION; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + m_Strings.clear(); + m_Exports.clear(); + } + void* Data() noexcept override { return &m_Desc; } + D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION m_Desc; + CD3DX12_STATE_OBJECT_DESC::StringContainer m_Strings; + std::vector m_Exports; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION() noexcept + { + Init(); + } + CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION(const CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION& other) = delete; + CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION& operator=(const CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION& other) = delete; + CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION(CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION&& other) = default; + CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION& operator=(CD3DX12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION&& other) = default; + void SetSubobjectNameToAssociate(LPCWSTR SubobjectToAssociate) + { + m_Desc.SubobjectToAssociate = m_SubobjectName.LocalCopy(SubobjectToAssociate, true); + } + void AddExport(LPCWSTR Export) + { + m_Desc.NumExports++; + m_Exports.push_back(m_Strings.LocalCopy(Export)); + m_Desc.pExports = &m_Exports[0]; // using ugly way to get pointer in case .data() is not defined + } + template + void AddExports(LPCWSTR (&Exports)[N]) + { + for (UINT i = 0; i < N; i++) + { + AddExport(Exports[i]); + } + } + void AddExports(const LPCWSTR* Exports, UINT N) + { + for (UINT i = 0; i < N; i++) + { + AddExport(Exports[i]); + } + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + m_Strings.clear(); + m_SubobjectName.clear(); + m_Exports.clear(); + } + void* Data() noexcept override { return &m_Desc; } + D3D12_DXIL_SUBOBJECT_TO_EXPORTS_ASSOCIATION m_Desc; + CD3DX12_STATE_OBJECT_DESC::StringContainer m_Strings; + CD3DX12_STATE_OBJECT_DESC::StringContainer m_SubobjectName; + std::vector m_Exports; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_HIT_GROUP_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_HIT_GROUP_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_HIT_GROUP_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_HIT_GROUP_SUBOBJECT(const CD3DX12_HIT_GROUP_SUBOBJECT& other) = delete; + CD3DX12_HIT_GROUP_SUBOBJECT& operator=(const CD3DX12_HIT_GROUP_SUBOBJECT& other) = delete; + CD3DX12_HIT_GROUP_SUBOBJECT(CD3DX12_HIT_GROUP_SUBOBJECT&& other) = default; + CD3DX12_HIT_GROUP_SUBOBJECT& operator=(CD3DX12_HIT_GROUP_SUBOBJECT&& other) = default; + void SetHitGroupExport(LPCWSTR exportName) + { + m_Desc.HitGroupExport = m_Strings[0].LocalCopy(exportName, true); + } + void SetHitGroupType(D3D12_HIT_GROUP_TYPE Type) noexcept { m_Desc.Type = Type; } + void SetAnyHitShaderImport(LPCWSTR importName) + { + m_Desc.AnyHitShaderImport = m_Strings[1].LocalCopy(importName, true); + } + void SetClosestHitShaderImport(LPCWSTR importName) + { + m_Desc.ClosestHitShaderImport = m_Strings[2].LocalCopy(importName, true); + } + void SetIntersectionShaderImport(LPCWSTR importName) + { + m_Desc.IntersectionShaderImport = m_Strings[3].LocalCopy(importName, true); + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_HIT_GROUP; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_HIT_GROUP_DESC&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + for (UINT i = 0; i < m_NumStrings; i++) + { + m_Strings[i].clear(); + } + } + void* Data() noexcept override { return &m_Desc; } + D3D12_HIT_GROUP_DESC m_Desc; + static constexpr UINT m_NumStrings = 4; + CD3DX12_STATE_OBJECT_DESC::StringContainer + m_Strings[m_NumStrings]; // one string for every entrypoint name +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT(const CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT& other) = delete; + CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT& operator=(const CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT& other) = delete; + CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT(CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT&& other) = default; + CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT& operator=(CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT&& other) = default; + void Config(UINT MaxPayloadSizeInBytes, UINT MaxAttributeSizeInBytes) noexcept + { + m_Desc.MaxPayloadSizeInBytes = MaxPayloadSizeInBytes; + m_Desc.MaxAttributeSizeInBytes = MaxAttributeSizeInBytes; + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_SHADER_CONFIG; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_RAYTRACING_SHADER_CONFIG&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + } + void* Data() noexcept override { return &m_Desc; } + D3D12_RAYTRACING_SHADER_CONFIG m_Desc; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT(const CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT& other) = delete; + CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT& operator=(const CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT& other) = delete; + CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT(CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT&& other) = default; + CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT& operator=(CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT&& other) = default; + void Config(UINT MaxTraceRecursionDepth) noexcept + { + m_Desc.MaxTraceRecursionDepth = MaxTraceRecursionDepth; + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_PIPELINE_CONFIG; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_RAYTRACING_PIPELINE_CONFIG&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + } + void* Data() noexcept override { return &m_Desc; } + D3D12_RAYTRACING_PIPELINE_CONFIG m_Desc; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT(const CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT& other) = delete; + CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT& operator=(const CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT& other) = delete; + CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT(CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT&& other) = default; + CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT& operator=(CD3DX12_RAYTRACING_PIPELINE_CONFIG1_SUBOBJECT&& other) = default; + void Config(UINT MaxTraceRecursionDepth, D3D12_RAYTRACING_PIPELINE_FLAGS Flags) noexcept + { + m_Desc.MaxTraceRecursionDepth = MaxTraceRecursionDepth; + m_Desc.Flags = Flags; + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_PIPELINE_CONFIG1; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_RAYTRACING_PIPELINE_CONFIG1&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + } + void* Data() noexcept override { return &m_Desc; } + D3D12_RAYTRACING_PIPELINE_CONFIG1 m_Desc; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT(const CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT& other) = delete; + CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT& operator=(const CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT& other) = delete; + CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT(CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT&& other) = default; + CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT& operator=(CD3DX12_GLOBAL_ROOT_SIGNATURE_SUBOBJECT&& other) = default; + void SetRootSignature(ID3D12RootSignature* pRootSig) noexcept + { + m_pRootSig = pRootSig; + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_GLOBAL_ROOT_SIGNATURE; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator ID3D12RootSignature*() const noexcept { return D3DX12_COM_PTR_GET(m_pRootSig); } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_pRootSig = nullptr; + } + void* Data() noexcept override { return D3DX12_COM_PTR_ADDRESSOF(m_pRootSig); } + D3DX12_COM_PTR m_pRootSig; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT(const CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT& other) = delete; + CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT& operator=(const CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT& other) = delete; + CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT(CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT&& other) = default; + CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT& operator=(CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT&& other) = default; + void SetRootSignature(ID3D12RootSignature* pRootSig) noexcept + { + m_pRootSig = pRootSig; + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_LOCAL_ROOT_SIGNATURE; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator ID3D12RootSignature*() const noexcept { return D3DX12_COM_PTR_GET(m_pRootSig); } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_pRootSig = nullptr; + } + void* Data() noexcept override { return D3DX12_COM_PTR_ADDRESSOF(m_pRootSig); } + D3DX12_COM_PTR m_pRootSig; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT(const CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT& other) = delete; + CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT& operator=(const CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT& other) = delete; + CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT(CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT&& other) = default; + CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT& operator=(CD3DX12_STATE_OBJECT_CONFIG_SUBOBJECT&& other) = default; + void SetFlags(D3D12_STATE_OBJECT_FLAGS Flags) noexcept + { + m_Desc.Flags = Flags; + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_STATE_OBJECT_CONFIG; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_STATE_OBJECT_CONFIG&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + } + void* Data() noexcept override { return &m_Desc; } + D3D12_STATE_OBJECT_CONFIG m_Desc; +}; + +//------------------------------------------------------------------------------------------------ +class CD3DX12_NODE_MASK_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3DX12_NODE_MASK_SUBOBJECT() noexcept + { + Init(); + } + CD3DX12_NODE_MASK_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + Init(); + AddToStateObject(ContainingStateObject); + } + CD3DX12_NODE_MASK_SUBOBJECT(const CD3DX12_NODE_MASK_SUBOBJECT& other) = delete; + CD3DX12_NODE_MASK_SUBOBJECT& operator=(const CD3DX12_NODE_MASK_SUBOBJECT& other) = delete; + CD3DX12_NODE_MASK_SUBOBJECT(CD3DX12_NODE_MASK_SUBOBJECT&& other) = default; + CD3DX12_NODE_MASK_SUBOBJECT& operator=(CD3DX12_NODE_MASK_SUBOBJECT&& other) = default; + void SetNodeMask(UINT NodeMask) noexcept + { + m_Desc.NodeMask = NodeMask; + } + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12_STATE_SUBOBJECT_TYPE_NODE_MASK; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + operator const D3D12_NODE_MASK&() const noexcept { return m_Desc; } +private: + void Init() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + m_Desc = {}; + } + void* Data() noexcept override { return &m_Desc; } + D3D12_NODE_MASK m_Desc; +}; + + +// XBOX + +//------------------------------------------------------------------------------------------------ +class CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT + : public CD3DX12_STATE_OBJECT_DESC::SUBOBJECT_HELPER_BASE +{ +public: + CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT() noexcept + { + SUBOBJECT_HELPER_BASE::Init(); + } + CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT(CD3DX12_STATE_OBJECT_DESC& ContainingStateObject) + { + SUBOBJECT_HELPER_BASE::Init(); + AddToStateObject(ContainingStateObject); + } + CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT(const CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT& other) = delete; + CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT& operator=(const CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT& other) = delete; + CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT(CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT&& other) = default; + CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT& operator=(CD3D12XBOX_RAYTRACING_OPTIONS_SUBOBJECT&& other) = default; + D3D12_STATE_SUBOBJECT_TYPE Type() const noexcept override + { + return D3D12XBOX_STATE_SUBOBJECT_TYPE_RAYTRACING_OPTIONS; + } + operator const D3D12_STATE_SUBOBJECT&() const noexcept { return *m_pSubobject; } + + D3D12XBOX_RAYTRACING_OPTIONS m_options {}; + +private: + void* Data() noexcept override { return &m_options; } +}; + +#endif // #ifndef D3DX12_NO_STATE_OBJECT_HELPERS + + +//================================================================================================ +// D3DX12 Enhanced Barrier Helpers +//================================================================================================ + +class CD3DX12_BARRIER_SUBRESOURCE_RANGE : public D3D12_BARRIER_SUBRESOURCE_RANGE +{ +public: + CD3DX12_BARRIER_SUBRESOURCE_RANGE() = default; + CD3DX12_BARRIER_SUBRESOURCE_RANGE(const D3D12_BARRIER_SUBRESOURCE_RANGE &o) noexcept : + D3D12_BARRIER_SUBRESOURCE_RANGE(o) + {} + explicit CD3DX12_BARRIER_SUBRESOURCE_RANGE(UINT Subresource) noexcept : + D3D12_BARRIER_SUBRESOURCE_RANGE{ Subresource, 0, 0, 0, 0, 0 } + {} + CD3DX12_BARRIER_SUBRESOURCE_RANGE( + UINT firstMipLevel, + UINT numMips, + UINT firstArraySlice, + UINT numArraySlices, + UINT firstPlane = 0, + UINT numPlanes = 1) noexcept : + D3D12_BARRIER_SUBRESOURCE_RANGE + { + firstMipLevel, + numMips, + firstArraySlice, + numArraySlices, + firstPlane, + numPlanes + } + {} +}; + +class CD3DX12_GLOBAL_BARRIER : public D3D12_GLOBAL_BARRIER +{ +public: + CD3DX12_GLOBAL_BARRIER() = default; + CD3DX12_GLOBAL_BARRIER(const D3D12_GLOBAL_BARRIER &o) noexcept : D3D12_GLOBAL_BARRIER(o){} + CD3DX12_GLOBAL_BARRIER( + D3D12_BARRIER_SYNC syncBefore, + D3D12_BARRIER_SYNC syncAfter, + D3D12_BARRIER_ACCESS accessBefore, + D3D12_BARRIER_ACCESS accessAfter) noexcept : D3D12_GLOBAL_BARRIER { + syncBefore, + syncAfter, + accessBefore, + accessAfter + } + {} +}; + +class CD3DX12_BUFFER_BARRIER : public D3D12_BUFFER_BARRIER +{ +public: + CD3DX12_BUFFER_BARRIER() = default; + CD3DX12_BUFFER_BARRIER(const D3D12_BUFFER_BARRIER &o) noexcept : D3D12_BUFFER_BARRIER(o){} + CD3DX12_BUFFER_BARRIER( + D3D12_BARRIER_SYNC syncBefore, + D3D12_BARRIER_SYNC syncAfter, + D3D12_BARRIER_ACCESS accessBefore, + D3D12_BARRIER_ACCESS accessAfter, + ID3D12Resource *pRes) noexcept : D3D12_BUFFER_BARRIER { + syncBefore, + syncAfter, + accessBefore, + accessAfter, + pRes, + 0, ULLONG_MAX + } + {} +}; + +class CD3DX12_TEXTURE_BARRIER : public D3D12_TEXTURE_BARRIER +{ +public: + CD3DX12_TEXTURE_BARRIER() = default; + CD3DX12_TEXTURE_BARRIER(const D3D12_TEXTURE_BARRIER &o) noexcept : D3D12_TEXTURE_BARRIER(o){} + CD3DX12_TEXTURE_BARRIER( + D3D12_BARRIER_SYNC syncBefore, + D3D12_BARRIER_SYNC syncAfter, + D3D12_BARRIER_ACCESS accessBefore, + D3D12_BARRIER_ACCESS accessAfter, + D3D12_BARRIER_LAYOUT layoutBefore, + D3D12_BARRIER_LAYOUT layoutAfter, + ID3D12Resource *pRes, + const D3D12_BARRIER_SUBRESOURCE_RANGE &subresources, + D3D12_TEXTURE_BARRIER_FLAGS flag = D3D12_TEXTURE_BARRIER_FLAG_NONE) noexcept : D3D12_TEXTURE_BARRIER { + syncBefore, + syncAfter, + accessBefore, + accessAfter, + layoutBefore, + layoutAfter, + pRes, + subresources, + flag + } + {} +}; + +class CD3DX12_BARRIER_GROUP : public D3D12_BARRIER_GROUP +{ +public: + CD3DX12_BARRIER_GROUP() = default; + CD3DX12_BARRIER_GROUP(const D3D12_BARRIER_GROUP &o) noexcept : D3D12_BARRIER_GROUP(o){} + CD3DX12_BARRIER_GROUP(UINT32 numBarriers, const D3D12_BUFFER_BARRIER *pBarriers) noexcept + { + Type = D3D12_BARRIER_TYPE_BUFFER; + NumBarriers = numBarriers; + pBufferBarriers = pBarriers; + } + CD3DX12_BARRIER_GROUP(UINT32 numBarriers, const D3D12_TEXTURE_BARRIER *pBarriers) noexcept + { + Type = D3D12_BARRIER_TYPE_TEXTURE; + NumBarriers = numBarriers; + pTextureBarriers = pBarriers; + } + CD3DX12_BARRIER_GROUP(UINT32 numBarriers, const D3D12_GLOBAL_BARRIER *pBarriers) noexcept + { + Type = D3D12_BARRIER_TYPE_GLOBAL; + NumBarriers = numBarriers; + pGlobalBarriers = pBarriers; + } +}; + + +#pragma warning( pop ) + +#endif // defined( __cplusplus ) + +#endif //__D3DX12_XBOX_H__ + diff --git a/docs/gdkx/dstorage_xs.h b/docs/gdkx/dstorage_xs.h new file mode 100644 index 0000000..74007af --- /dev/null +++ b/docs/gdkx/dstorage_xs.h @@ -0,0 +1,1052 @@ +/************************************************************************ +* * +* dstorage_xs.h -- This module defines the Xbox DirectStorage APIs * +* * +* Copyright (c) Microsoft Corp. All rights reserved. * +* * +************************************************************************/ + +#if !defined(__cplusplus) + #error C++11 required +#endif + +#pragma once + +#pragma warning(push) +#pragma warning(disable:4201) // nonstandard extension used : nameless struct/union + +#pragma pack(push, 16) + +#include +#include + +interface ID3D12Fence; +interface IDStorageStatusArrayX; + +/// +/// The priority of a DStorage queue. +/// +enum DSTORAGE_PRIORITY : INT8 { + DSTORAGE_PRIORITY_LOW = -1, + DSTORAGE_PRIORITY_NORMAL = 0, + DSTORAGE_PRIORITY_HIGH = 1, + DSTORAGE_PRIORITY_REALTIME = 2, + + /// + /// The following values can be used for iterating over all priority levels. + /// + DSTORAGE_PRIORITY_FIRST = DSTORAGE_PRIORITY_LOW, + DSTORAGE_PRIORITY_LAST = DSTORAGE_PRIORITY_REALTIME, + + DSTORAGE_PRIORITY_COUNT = 4 +}; + +#define DSTORAGE_MIN_QUEUE_CAPACITY 0x80 +#define DSTORAGE_MAX_QUEUE_CAPACITY 0x2000 +#define DSTORAGE_MAX_DESTINATION_SIZE 0x2000000 + +/// +/// The source type of a DStorage request. +/// +enum DSTORAGE_REQUEST_SOURCE_TYPE : UINT64 { + /// + /// The source of the DStorage request is a file. + /// + DSTORAGE_REQUEST_SOURCE_FILE = 0, + + /// + /// The source of the DStorage request is a block of memory. + /// + DSTORAGE_REQUEST_SOURCE_MEMORY = 1, +}; + +/// +/// The DSTORAGE_QUEUE_DESC structure contains the properties of a DStorage +/// queue for the queue's creation. +/// +struct DSTORAGE_QUEUE_DESC { + /// + /// The source type of requests this DStorage queue can accept. + /// + DSTORAGE_REQUEST_SOURCE_TYPE SourceType; + + /// + /// The maximum number of requests the queue can hold. + /// + UINT16 Capacity; + + /// + /// The priority of the requests in this queue. + /// + DSTORAGE_PRIORITY Priority; + + /// + /// Optional name of the queue. Used for debugging. + /// + _In_opt_z_ const CHAR *Name; +}; + +/// +/// The DSTORAGE_QUEUE_OPTIONS structure contains additional flags that are used +/// to control the behaviour of the Queue during creation. +/// +union DSTORAGE_QUEUE_OPTIONS { + struct { + /// + /// Boolean value indicating whether auto submit is disabled. + /// + UINT64 AutoSubmitDisabled : 1; + + /// + /// Reserved fields. Must be 0. + /// + UINT64 Reserved : 63; + }; + UINT64 AsUINT64; +}; + +/// +/// The DSTORAGE_QUEUE_DESC1 structure contains the properties of a DStorage +/// queue for the queue's creation with the addition of an auto submit flag. +/// +struct DSTORAGE_QUEUE_DESC1 { + /// + /// The source type of requests this DStorage queue can accept. + /// + DSTORAGE_REQUEST_SOURCE_TYPE SourceType; + + /// + /// The maximum number of requests the queue can hold. + /// + UINT16 Capacity; + + /// + /// The priority of the requests in this queue. + /// + DSTORAGE_PRIORITY Priority; + + /// + /// Optional name of the queue. Used for debugging. + /// + _In_opt_z_ const CHAR *Name; + + /// + /// Additional flags that are used to control the behaviour of the Queue + /// + DSTORAGE_QUEUE_OPTIONS Options; +}; + +/// +/// The DSTORAGE_QUEUE_INFO structure contains the properties and current state +/// of a DStorage queue. +/// +struct DSTORAGE_QUEUE_INFO { + /// + /// The DSTORAGE_QUEUE_DESC structure used for queue's creation. + /// + DSTORAGE_QUEUE_DESC Desc; + + /// + /// The number of available empty slots. If a queue is empty, the number + /// of empty slots equals capacity - 1. The reserved slot is used to + /// distinguish between empty and full cases. + /// + UINT16 EmptySlotCount; + + /// + /// The number of entries that would need to be enqueued to trigger + /// automatic submission. + /// + UINT16 RequestCountUntilAutoSubmit; +}; + +/// +/// The DSTORAGE_QUEUE_INFO1 structure contains the properties and current state +/// of a DStorage queue including the auto submit flag status. +/// +struct DSTORAGE_QUEUE_INFO1 { + /// + /// The DSTORAGE_QUEUE_DESC1 structure used for queue's creation. + /// + DSTORAGE_QUEUE_DESC1 Desc; + + /// + /// The number of available empty slots. If a queue is empty, the number + /// of empty slots equals capacity - 1. The reserved slot is used to + /// distinguish between empty and full cases. + /// + UINT16 EmptySlotCount; + + /// + /// The number of entries that would need to be enqueued to trigger + /// automatic submission. + /// + UINT16 RequestCountUntilAutoSubmit; +}; + +/// +/// The type of BCPACK decompression to perform after the content is read from +/// the file. +/// +enum DSTORAGE_BCPACK_MODE : UINT64 { + /// + /// Perform no BCPACK decompression. + /// + DSTORAGE_BCPACK_MODE_NONE = 0, + + /// + /// Perform BCPACK decompression of BC1 texture data. + /// + DSTORAGE_BCPACK_MODE_BC1 = 1, + + /// + /// Perform BCPACK decompression of BC2 texture data. + /// + DSTORAGE_BCPACK_MODE_BC2 = 2, + + /// + /// Perform BCPACK decompression of BC3 texture data. + /// + DSTORAGE_BCPACK_MODE_BC3 = 3, + + /// + /// Perform BCPACK decompression of BC4 texture data. + /// + DSTORAGE_BCPACK_MODE_BC4 = 4, + + /// + /// Perform BCPACK decompression of BC5 texture data. + /// + DSTORAGE_BCPACK_MODE_BC5 = 5, + + /// + /// Perform BCPACK decompression of BC6H texture data. + /// + DSTORAGE_BCPACK_MODE_BC6H = 6, + + /// + /// Perform BCPACK decompression of BC7 texture data. + /// + DSTORAGE_BCPACK_MODE_BC7 = 7, +}; + +/// +/// The type of texture swizzling to perform after the content is through the +/// decompression stage. +/// +enum DSTORAGE_SWIZZLE_MODE : UINT64 { + /// + /// Perform no swizzling. + /// + DSTORAGE_SWIZZLE_MODE_NONE = 0, + + /// + /// The output is interleaved with a 4KB+4KB+8KB pattern. + /// + DSTORAGE_SWIZZLE_MODE_4K_4K_8K = 1, + + /// + /// The output is interleaved with a 4KB+4KB+24KB pattern. + /// + DSTORAGE_SWIZZLE_MODE_4K_4K_24K = 2, + + /// + /// The output is interleaved with a 4KB+12KB+4KB+4KB+8KB pattern. + /// + DSTORAGE_SWIZZLE_MODE_4K_12K_4K_4K_8K = 3, + + /// + /// The output is interleaved with a 4KB+12KB+4KB+12KB pattern. + /// + DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K = 4, + + /// + /// The valid swizzle mode values are below DSTORAGE_SWIZZLE_MODE_MAX. + /// + DSTORAGE_SWIZZLE_MODE_MAX +}; + +/// +/// Options for a DStorage request. +/// +union DSTORAGE_REQUEST_OPTIONS { + struct { + /// + /// Boolean value indicating whether to perform RFC 1950 decompression. + /// + UINT64 ZlibDecompress : 1; + + /// + /// DSTORAGE_BCPACK_MODE value indicating the type of BCPACK + /// decompression to perform. + /// + DSTORAGE_BCPACK_MODE BcpackMode : 4; + + /// + /// DSTORAGE_SWIZZLE_MODE value indicating the type of swizzle operation + /// to perform. + /// + DSTORAGE_SWIZZLE_MODE SwizzleMode : 16; + + /// + /// Boolean value indicating that destination memory is an array of physical pages + /// allocated through XMemAllocatePhysicalPages. + /// + UINT64 DestinationIsPhysicalPages : 1; + + /// + /// DSTORAGE_REQUEST_SOURCE_TYPE enum value indicating whether the + /// source of the request is a file or a block of memory. + /// + DSTORAGE_REQUEST_SOURCE_TYPE SourceType : 1; + + /// + /// When SourceType is DSTORAGE_REQUEST_SOURCE_MEMORY, this boolean + /// value indicates that source memory is an array of physical pages + /// allocated through XMemAllocatePhysicalPages. + /// + UINT64 SourceIsPhysicalPages : 1; + + /// + /// Reserved fields. Must be 0. + /// + UINT64 Reserved : 40; + }; + UINT64 AsUINT64; +}; + +/// +/// Flags controlling DirectStorage debug layer. +/// +enum DSTORAGE_DEBUG { + /// + /// DirectStorage debug layer is disabled. + /// + DSTORAGE_DEBUG_NONE = 0x00, + + /// + /// Print error information to a debugger. + /// + DSTORAGE_DEBUG_SHOW_ERRORS = 0x01, + + /// + /// Trigger a debug break each time an error is detected. + /// + DSTORAGE_DEBUG_BREAK_ON_ERROR = 0x02, + + /// + /// Include IDStorageStatusArrayX and ID3D12Fence names in ETW events. + /// + DSTORAGE_DEBUG_RECORD_OBJECT_NAMES = 0x04 +}; + +/// +/// Represents a file to be accessed by DStorage. +/// +DECLARE_INTERFACE_IID_(IDStorageFileX, IUnknown, "43704f9f-27c6-4a9f-8815-d16527894df4") +{ + /// + /// Closes the file, regardless of the reference count on this object. + /// + /// After an IDStorageFileX object is closed, it can no longer be used in + /// DStorage requests. + /// + virtual void Close() = 0; + + /// + /// Get a handle to a file represented by this object. + /// + /// The handle is opened with GENERIC_READ permissions and FILE_SHARE_READ + /// sharing mode. It can be used for querying the file's size, etc. + /// The handle should be closed with CloseHandle() when it's no longer + /// needed. + /// + virtual HANDLE GetHandle() = 0; +}; + +/// +/// Represents a DStorage request. +/// +struct DSTORAGE_REQUEST { + /// + /// Combination of decompression, swizzle and other options for this request. + /// + DSTORAGE_REQUEST_OPTIONS Options; + + union { + /// + /// Address of the buffer to receive the final result of this request. + /// + _Out_writes_bytes_(DestinationSize) void *Destination; + + struct { + /// + /// Address of the page array to receive the final result of this request if + /// DestinationIsPhysicalPages is specified. Each entry is a 64KB page number. + /// + PULONG_PTR DestinationPageArray; + + /// + /// Offset into the 64KB page where the destination starts, if + /// DestinationIsPhysicalPages is specified. + /// + UINT16 DestinationPageOffset; + }; + }; + + /// + /// Size, in bytes, of the buffer to receive the final result of this + /// request. A single request must satisfy one of the following size + /// requirements: + /// * The DestinationSize is equal to or less than 32MiB + /// OR + /// * The combined memory usage of SourceSize (for memory-to-memory requests only) + + /// DestinationSize is equal to or less than 1GiB, and the memory buffers that are + /// larger than 32MiB must use either 64KiB pages or 2MiB pages. + /// + UINT32 DestinationSize; + + union { + struct { + /// + /// The file to perform this read request from, if SourceType is + /// DSTORAGE_REQUEST_SOURCE_FILE. + /// + IDStorageFileX *File; + + /// + /// The offset, in bytes, in the file to start the read request at, + /// if SourceType is DSTORAGE_REQUEST_SOURCE_FILE. + /// + UINT64 FileOffset; + }; + + /// + /// Address of the source buffer to be read from, if SourceType is + /// DSTORAGE_REQUEST_SOURCE_MEMORY and SourceIsPhysicalPages is not + /// specified. + /// + _In_reads_bytes_(SourceSize) void *Source; + + struct { + /// + /// Address of the page array to provide the source buffer to be + /// read from if SourceType is DSTORAGE_REQUEST_SOURCE_MEMORY and + /// SourceIsPhysicalPages is specified. Each entry is a 64KB page + /// number. + /// + PULONG_PTR SourcePageArray; + + /// + /// Offset into the 64KB page where the source starts, if SourceType + /// is DSTORAGE_REQUEST_SOURCE_MEMORY and SourceIsPhysicalPages is + /// specified. + /// + UINT16 SourcePageOffset; + }; + }; + + /// + /// Size, in bytes, to be read from the file or memory source. + /// + UINT32 SourceSize; + + /// + /// The number of bytes of BCPACK compressed data if ZlibDecompress and BcpackMode are both specified. + /// + UINT32 IntermediateSize; + + /// + /// An arbitrary UINT64 number used for cancellation matching. + /// + UINT64 CancellationTag; + + /// + /// Optional name of the request. Used for debugging. If specified, the + /// string should be accessible until the request completes. + /// + _In_opt_z_ const CHAR *Name; +}; + +#define DSTORAGE_REQUEST_MAX_NAME 64 + +enum DSTORAGE_COMMAND_TYPE { + DSTORAGE_COMMAND_TYPE_NONE = -1, + DSTORAGE_COMMAND_TYPE_REQUEST = 0, + DSTORAGE_COMMAND_TYPE_STATUS = 1, + DSTORAGE_COMMAND_TYPE_SIGNAL = 2, + DSTORAGE_COMMAND_TYPE_EVENT = 3, +}; + +/// +/// Structure to receive the detailed record of a failed DStorage request. +/// +struct DSTORAGE_ERROR_RECORD { + /// + /// The number of failed requests in the queue since the last + /// RetrieveErrorRecord call. + /// + UINT32 FailureCount; + + /// + /// Detailed record about the first failed command in the enqueue order. + /// + struct { + + /// + /// The HRESULT code of the failure. + /// + HRESULT HResult; + + /// + /// Type of the Enqueue command that caused the failure. + /// + DSTORAGE_COMMAND_TYPE CommandType; + + union { + /// + /// The parameters passed to the EnqueueRequest call. + /// + struct { + /// + /// Combination of decompression, swizzle and other options of the failed + /// request. + /// + DSTORAGE_REQUEST_OPTIONS Options; + + /// + /// Address of the buffer to receive the final result of the failed + /// request. + /// + void *Destination; + + /// + /// Size, in bytes, of the buffer to receive the final result of + /// the failed request. + /// + UINT32 DestinationSize; + + /// + /// For a file source request, the name of the file the request was + /// targeted to. + /// + WCHAR Filename[MAX_PATH]; + + /// + /// For a file source request, the offset, in bytes, in the file where + /// the read request was supposed to start at. + /// + UINT64 FileOffset; + + /// + /// For a memory source request, the address of the buffer to be read + /// from. + /// + void *Source; + + /// + /// The number of bytes to be read from the source. + /// + UINT32 SourceSize; + + /// + /// An arbitrary UINT64 number used for cancallation matching. + /// + UINT64 CancellationTag; + + /// + /// Name of the request. + /// + CHAR Name[DSTORAGE_REQUEST_MAX_NAME]; + } Request; + + /// + /// The parameters passed to the EnqueueStatus call. + /// + struct { + IDStorageStatusArrayX *StatusArray; + UINT32 Index; + } Status; + + /// + /// The parameters passed to the EnqueueSignal call. + /// + struct { + ID3D12Fence *Fence; + UINT64 Value; + } Signal; + + /// + /// The parameters passed to the EnqueueSetEvent call. + /// + struct { + HANDLE Handle; + } Event; + }; + } FirstFailure; +}; + +/// +/// Defines the valid staging buffer sizes. +/// +enum DSTORAGE_STAGING_BUFFER_SIZE : UINT32 { + DSTORAGE_STAGING_BUFFER_SIZE_0 = 0, + DSTORAGE_STAGING_BUFFER_SIZE_16MB = 16 * 1048576, + DSTORAGE_STAGING_BUFFER_SIZE_20MB = 20 * 1048576, + DSTORAGE_STAGING_BUFFER_SIZE_24MB = 24 * 1048576, + DSTORAGE_STAGING_BUFFER_SIZE_28MB = 28 * 1048576, + DSTORAGE_STAGING_BUFFER_SIZE_32MB = 32 * 1048576, +}; + +/// +/// Represents per-priority statistics. +/// +struct DSTORAGE_PRIORITY_STATS { + + /// + /// The number of currently open queues. + /// + UINT32 CurrentQueueCount; + + /// + /// The highest number of concurrently opened queues. + /// + UINT32 MaxQueueCount; + + /// + /// Cumulative number of opened queues. + /// + UINT32 CumulativeQueueCount; + + /// + /// The total number of status requests. + /// + UINT32 TotalStatusCount; + + /// + /// The total number of fence requests. + /// + UINT32 TotalFenceCount; + + /// + /// The number of currently pending requests. A request is considered + /// to be in a pending state when the DirectStorage subsystem has started + /// processing it, but the request hasn't been completed yet. + /// A IDStorageQueueX::Submit() call is a signal for the DirectStorage + /// to start processing requests in the given queue. There might + /// be a delay between a IDStorageQueueX::Submit() call and when a request + /// is considered pending if lower level DirectStorage resources are busy. + /// + UINT32 PendingRequestCount; + + /// + /// The total number of submitted requests. + /// + UINT32 TotalRequestCount; + + /// + /// The sum of requests' source sizes. + /// + UINT64 TotalRequestSourceByteCount; + + /// + /// The sum of requests' destination sizes. + /// + UINT64 TotalRequestDestinationByteCount; +}; + +/// +/// Represents statistics. +/// +struct DSTORAGE_STATS +{ + /// + /// Statistics of the low priority queues. + /// + DSTORAGE_PRIORITY_STATS LowPriorityStats; + + /// + /// Statistics of the normal priority queues. + /// + DSTORAGE_PRIORITY_STATS NormalPriorityStats; + + /// + /// Statistics of the high priority queues. + /// + DSTORAGE_PRIORITY_STATS HighPriorityStats; + + /// + /// Statistics of the realtime priority queues. + /// + DSTORAGE_PRIORITY_STATS RealtimePriorityStats; + + /// + /// The number of currently open virtual disks (game package, DLC packages, + /// developer scratch, PLS). + /// + UINT8 CurrentOpenVirtualDiskCount; + + /// + /// The highest number of concurrently opened virtual disks. + /// + UINT8 MaxOpenVirtualDiskCount; + + /// + /// Cumulative number of opened virtual disks. + /// + UINT32 CumulativeOpenVirtualDiskCount; + + /// + /// The number of requests sent by DirectStorage to storage devices that + /// haven't been completed by the hardware yet. + /// + UINT32 PendingStorageRequestCount; + + /// + /// The total number of requests sent by DirectStorage to storage devices. + /// + UINT32 TotalStorageRequestCount; + + /// + /// The number of storage device retries. + /// + UINT32 StorageRetries; + + /// + /// The number of storage device errors. + /// + UINT32 StorageErrors; + + /// + /// The number of currently pending decompression requests. + /// + UINT32 PendingDecompressionRequestCount; + + /// + /// The total number of decompression requests. + /// + UINT32 TotalDecompressionRequestCount; + + /// + /// The number of decompression errors. + /// + UINT32 DecompressionErrors; + + /// + /// The number of stalls caused by a full staging buffer. + /// + UINT32 StagingBufferStallCount; + + /// + /// The number of currently open files. + /// + UINT32 CurrentOpenFileCount; + + /// + /// The highest number of concurrently opened files. + /// + UINT32 MaxOpenFileCount; + + /// + /// Cumulative number of opened files. + /// + UINT32 CumulativeOpenFileCount; + + /// + /// The current DirectStorage memory footprint (including + /// the staging buffer, etc.). + /// + UINT32 CurrentTitleMemoryUsageBytes; + + /// + /// The highest DirectStorage memory footprint (including + /// the staging buffer, etc.). + /// + UINT32 MaxTitleMemoryUsageBytes; + + /// + /// The total number of errors. + /// The error count is incremented every time a request fails for any + /// reason. Sample errors are: reading data from an invalid offset, + /// storage device errors, decompression errors, invalid request + /// parameters, etc. + /// + UINT32 ErrorCount; +}; + +/// +/// Represents the static DStorage object used to create DStorage queues, open +/// files for DStorage access, and other global operations. +/// +DECLARE_INTERFACE_IID_(IDStorageFactoryX, IUnknown, "fb3b54ac-bf82-463a-b777-73195837864d") +{ + /// + /// Creates DStorage queue object. + /// + /// Descriptor to specify the properties of the queue. + /// Specifies the DStorage queue interface, such as + /// __uuidof(IDStorageQueueX). + /// Receives the new queue created. + /// Standard HRESULT error code. + virtual HRESULT CreateQueue(const DSTORAGE_QUEUE_DESC *desc, REFIID riid, _COM_Outptr_ void **ppv) = 0; + + /// + /// Opens a file for DStorage access. The file must be stored on a DStorage + /// supported NVMe device. + /// + /// Path of the file to be opened. + /// Specifies the DStorage file interface, such as + /// __uuidof(IDStorageFileX). + /// Receives the new file opened. + /// Standard HRESULT error code. + virtual HRESULT OpenFile(_In_z_ const WCHAR *path, REFIID riid, _COM_Outptr_ void **ppv) = 0; + + /// + /// Creates DStorage status array object. + /// + /// Specifies the number of status the array can + /// hold. + /// Specifies object's name that will appear in + // the ETW events if enabled through the debug layer. This is an optional + // parameter. + /// Specifies the DStorage status interface, such as + /// __uuidof(IDStorageStatusArrayX). + /// Receives the new status array object created. + /// Standard HRESULT error code. + virtual HRESULT CreateStatusArray(UINT32 capacity, _In_opt_ PCSTR name, REFIID riid, _COM_Outptr_ void **ppv) = 0; + + /// + /// Sets a CPU affinity mask for DStorage. All operations DStorage does that + /// aren't performed in the caller's stack will be performed in a thread + /// confined by this affinity mask. + /// + /// The CPU affinity mask. + /// Standard HRESULT error code. + virtual HRESULT SetCpuAffinity(UINT64 affinity) = 0; + + /// + /// Sets flags used to control the debug layer. + /// + /// A set of flags controlling the debug layer. + virtual void SetDebugFlags(UINT32 flags) = 0; + + /// + /// Sets the size of staging buffer used to temporarily store content loaded + /// from the storage device before they are decrypted / decompressed. If + /// only memory sourced queues are used, the staging buffer can be 0 sized. + /// In the current preview release, the only valid staging buffer sizes are + /// enumerated in the DSTORAGE_STAGING_BUFFER_SIZE enum. + /// + /// Size, in bytes, of the staging buffer. + virtual HRESULT SetStagingBufferSize(UINT32 size) = 0; +}; + +/// +/// Represents the static DStorage object used to create DStorage queues, open +/// files for DStorage access, and other global operations. +/// +/// Extends the IDStorageFactoryX interface. +/// +DECLARE_INTERFACE_IID_(IDStorageFactoryX1, IDStorageFactoryX, "c74c2a5b-1e43-46a5-a224-9116358e1118") +{ + /// + /// Gets DirectStorage statistics. + /// The statistics do not include Win32 file IO. + /// + virtual void GetStats(_Out_ DSTORAGE_STATS *stats) = 0; +}; + +/// +/// Represents the static DStorage object used to create DStorage queues, open +/// files for DStorage access, and other global operations. +/// +/// Extends the IDStorageFactoryX1 interface. +/// +DECLARE_INTERFACE_IID_(IDStorageFactoryX2, IDStorageFactoryX1, "62959d11-d45f-4884-a0a3-f7862ea243ae") +{ + /// + /// Creates DStorage queue object. + /// + /// Descriptor to specify the properties of the queue. + /// Specifies the DStorage queue interface, such as + /// __uuidof(IDStorageQueueX). + /// Receives the new queue created. + /// Standard HRESULT error code. + virtual HRESULT CreateQueue1(const DSTORAGE_QUEUE_DESC1 *desc, REFIID riid, _COM_Outptr_ void **ppv) = 0; +}; + +/// +/// Represents an array of status entries to receive completion results for the +/// read requests before them. +/// +/// +/// A status entry receives completion status for all the requests in the +/// DStorageQueue between where it is enqueued and the previously enqueued +/// status entry. Only when all requests enqueued before the status entry +/// complete (ie. IsComplete() for the entry returns true), the status entry +/// can be enqueued again. +/// +DECLARE_INTERFACE_IID_(IDStorageStatusArrayX, IUnknown, "cd66d752-2786-44f7-9070-e2a6fdad3f1b") +{ + /// + /// Returns a boolean value indicating all requests enqueued prior to the + /// specified status entry have completed. + /// + /// Specifies the index of the status entry to retrieve. + /// Boolean value indicating completion. + /// This is equivalent to "GetHResult(index) != E_PENDING". + virtual bool IsComplete(UINT32 index) = 0; + + /// + /// Returns the HRESULT code of all requests between the specified status + /// entry and the status entry enqueued before it. + /// + /// Specifies the index of the status entry to retrieve. + /// HRESULT code of the requests. + /// + /// + /// + /// If any requests have not completed yet, the return value is E_PENDING. + /// + /// + /// If all requests have completed, and there were failure(s), the return + /// value stores the failure code of the first failed request in the enqueue + /// order. + /// + /// + /// If all requests have completed successfully, the return value is S_OK. + /// + /// + /// + virtual HRESULT GetHResult(UINT32 index) = 0; +}; + +/// +/// Represents a DStorage queue to perform read operations. +/// +DECLARE_INTERFACE_IID_(IDStorageQueueX, IUnknown, "a3f6649a-8c2c-4b3a-8b6e-10186a04b9bc") +{ + /// + /// Enqueues a read request to the queue. The request remains in the queue + /// until Submit is called, or until the queue is 1/2 full. + /// + /// The read request to be queued. + virtual void EnqueueRequest(const DSTORAGE_REQUEST *request) = 0; + + /// + /// Enqueues a status write. The status write happens when all requests + /// before the status write entry complete. If there were failure(s) + /// since the previous status write entry, the HResult of the enqueued + /// status entry stores the failure code of the first failed request in the + /// enqueue order. + /// + /// IDStorageStatusArrayX object. + /// Index of the status entry in the + /// IDStorageStatusArrayX object to receive the status. + virtual void EnqueueStatus(IDStorageStatusArrayX *statusArray, UINT32 index) = 0; + + /// + /// Enqueues fence write. The fence write happens when all requests before + /// the fence entry complete. + /// + /// An ID3D12Fence to be written. + /// The value to write to the fence. + virtual void EnqueueSignal(ID3D12Fence *fence, UINT64 value) = 0; + + /// + /// Submits all requests enqueued so far to DStorage to be executed. + /// + virtual void Submit() = 0; + + /// + /// Attempts to cancel a group of previously enqueued read requests. All + /// previously enqueued requests whose CancellationTag matches the formula + /// (CancellationTag & mask ) == value will be cancelled. + /// A cancelled request may or may not complete its original read request. + /// A cancelled request is not counted as a failure in either + /// IDStorageStatusX or DSTORAGE_ERROR_RECORD. + /// + /// The mask for the cancellation formula. + /// The value for the cancellation formula. + virtual void CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0; + + /// + /// Closes the DStorage queue, regardless of the reference count on this + /// object. + /// After the Close function returns, the queue will no longer complete any + /// more requests, even if some are submitted. + /// + virtual void Close() = 0; + + /// + /// Obtains an event to wait on. When there is any error happening for read + /// requests in this queue, the event will be signalled, and + /// RetrieveErrorRecord may be called to retrieve diagnostic information. + /// + /// HANDLE to an event. + virtual HANDLE GetErrorEvent() = 0; + + /// + /// When the error event is signaled, this function can be called to + /// retrieve a DSTORAGE_ERROR_RECORD. Once the error record is retrieved, + /// this function should not be called until the next time the error event + /// is signaled. + /// + /// Receives the error record. + virtual void RetrieveErrorRecord(_Out_ DSTORAGE_ERROR_RECORD *record) = 0; + + /// + /// Obtains information about the queue. It includes the DSTORAGE_QUEUE_DESC + /// structure used for queue's creation as well as the number of empty slots + /// and number of entries that need to be enqueued to trigger automatic + /// submission. + /// + virtual void Query(_Out_ DSTORAGE_QUEUE_INFO *info) = 0; +}; + +/// +/// Represents a DStorage queue to perform read operations. +/// +DECLARE_INTERFACE_IID_(IDStorageQueueX1, IDStorageQueueX, "3c02cb0c-c050-4195-99a1-a1ce94ba33c5") +{ + /// + /// Enqueues an operation to set the specified event object to a signaled state. + /// The event object is set when all requests before it complete. + /// If there are no free entries in the queue the enqueue operation will + /// block until one becomes available. + /// + /// A handle to an event object. + virtual void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) = 0; +}; + +/// +/// Represents a DStorage queue to perform read operations. +/// +DECLARE_INTERFACE_IID_(IDStorageQueueX2, IDStorageQueueX1, "3af5c948-6297-426c-bffc-8f18959fb87b") +{ + /// + /// Obtains information about the queue. It includes the DSTORAGE_QUEUE_DESC1 + /// structure used for queue's creation as well as the number of empty slots + /// and number of entries that need to be enqueued to trigger automatic + /// submission, along with the auto submit flag status. + /// + virtual void Query1(_Out_ DSTORAGE_QUEUE_INFO1 *info) = 0; +}; + +extern "C" { + +/// +/// Returns the static DStorage factory object used to create DStorage queues, +/// open files for DStorage access, and other global operations. +/// +/// Specifies the DStorage factory interface, such as +/// __uuidof(IDStorageFactoryX1) +/// Receives the DStorage factory object. +/// Standard HRESULT error code. +HRESULT WINAPI DStorageGetFactory(REFIID riid, void **ppv); + +} + +#pragma pack(pop) +#pragma warning(pop) + diff --git a/docs/gdkx/dxcapi_xs.h b/docs/gdkx/dxcapi_xs.h new file mode 100644 index 0000000..1980594 --- /dev/null +++ b/docs/gdkx/dxcapi_xs.h @@ -0,0 +1,1534 @@ +/////////////////////////////////////////////////////////////////////////////// +// // +// dxcapi_x.h // +// Copyright (C) Microsoft Corporation. All rights reserved. // +// This file is distributed under the University of Illinois Open Source // +// License. See LICENSE.TXT for details. // +// // +// Provides declarations for Xbox DirectX Compiler API entry point. // +// // +/////////////////////////////////////////////////////////////////////////////// + +#pragma once +#pragma region "Inlined contents of dxcapi.h" + +/////////////////////////////////////////////////////////////////////////////// +// // +// dxcapi.h // +// Copyright (C) Microsoft Corporation. All rights reserved. // +// This file is distributed under the University of Illinois Open Source // +// License. See LICENSE.TXT for details. // +// // +// Provides declarations for the DirectX Compiler API entry point. // +// // +/////////////////////////////////////////////////////////////////////////////// + +#ifndef __DXC_API__ +#define __DXC_API__ + +#ifdef _WIN32 +#ifndef DXC_API_IMPORT +#define DXC_API_IMPORT __declspec(dllimport) +#endif +#else +#ifndef DXC_API_IMPORT +#define DXC_API_IMPORT __attribute__((visibility("default"))) +#endif +#endif + +#ifdef _WIN32 + +#ifndef CROSS_PLATFORM_UUIDOF +// Warning: This macro exists in WinAdapter.h as well +#define CROSS_PLATFORM_UUIDOF(interface, spec) \ + struct __declspec(uuid(spec)) interface; +#endif + +#else + +#include "WinAdapter.h" +#include +#endif + +struct IMalloc; + +struct IDxcIncludeHandler; + +/// \brief Typedef for DxcCreateInstance function pointer. +/// +/// This can be used with GetProcAddress to get the DxcCreateInstance function. +typedef HRESULT(__stdcall *DxcCreateInstanceProc)(_In_ REFCLSID rclsid, + _In_ REFIID riid, + _Out_ LPVOID *ppv); + +/// \brief Typedef for DxcCreateInstance2 function pointer. +/// +/// This can be used with GetProcAddress to get the DxcCreateInstance2 function. +typedef HRESULT(__stdcall *DxcCreateInstance2Proc)(_In_ IMalloc *pMalloc, + _In_ REFCLSID rclsid, + _In_ REFIID riid, + _Out_ LPVOID *ppv); + +/// \brief Creates a single uninitialized object of the class associated with a +/// specified CLSID. +/// +/// \param rclsid The CLSID associated with the data and code that will be used +/// to create the object. +/// +/// \param riid A reference to the identifier of the interface to be used to +/// communicate with the object. +/// +/// \param ppv Address of pointer variable that receives the interface pointer +/// requested in riid. Upon successful return, *ppv contains the requested +/// interface pointer. Upon failure, *ppv contains NULL. +/// +/// While this function is similar to CoCreateInstance, there is no COM +/// involvement. +extern "C" DXC_API_IMPORT + HRESULT __stdcall DxcCreateInstance(_In_ REFCLSID rclsid, _In_ REFIID riid, + _Out_ LPVOID *ppv); + +/// \brief Version of DxcCreateInstance that takes an IMalloc interface. +/// +/// This can be used to create an instance of the compiler with a custom memory +/// allocator. +extern "C" DXC_API_IMPORT + HRESULT __stdcall DxcCreateInstance2(_In_ IMalloc *pMalloc, + _In_ REFCLSID rclsid, _In_ REFIID riid, + _Out_ LPVOID *ppv); + +// For convenience, equivalent definitions to CP_UTF8 and CP_UTF16. +#define DXC_CP_UTF8 65001 +#define DXC_CP_UTF16 1200 +#define DXC_CP_UTF32 12000 +// Use DXC_CP_ACP for: Binary; ANSI Text; Autodetect UTF with BOM +#define DXC_CP_ACP 0 + +/// Codepage for "wide" characters - UTF16 on Windows, UTF32 on other platforms. +#ifdef _WIN32 +#define DXC_CP_WIDE DXC_CP_UTF16 +#else +#define DXC_CP_WIDE DXC_CP_UTF32 +#endif + +/// Indicates that the shader hash was computed taking into account source +/// information (-Zss). +#define DXC_HASHFLAG_INCLUDES_SOURCE 1 + +/// Hash digest type for ShaderHash. +typedef struct DxcShaderHash { + UINT32 Flags; ///< DXC_HASHFLAG_* + BYTE HashDigest[16]; ///< The hash digest +} DxcShaderHash; + +#define DXC_FOURCC(ch0, ch1, ch2, ch3) \ + ((UINT32)(UINT8)(ch0) | (UINT32)(UINT8)(ch1) << 8 | \ + (UINT32)(UINT8)(ch2) << 16 | (UINT32)(UINT8)(ch3) << 24) +#define DXC_PART_PDB DXC_FOURCC('I', 'L', 'D', 'B') +#define DXC_PART_PDB_NAME DXC_FOURCC('I', 'L', 'D', 'N') +#define DXC_PART_PRIVATE_DATA DXC_FOURCC('P', 'R', 'I', 'V') +#define DXC_PART_ROOT_SIGNATURE DXC_FOURCC('R', 'T', 'S', '0') +#define DXC_PART_DXIL DXC_FOURCC('D', 'X', 'I', 'L') +#define DXC_PART_REFLECTION_DATA DXC_FOURCC('S', 'T', 'A', 'T') +#define DXC_PART_SHADER_HASH DXC_FOURCC('H', 'A', 'S', 'H') +#define DXC_PART_INPUT_SIGNATURE DXC_FOURCC('I', 'S', 'G', '1') +#define DXC_PART_OUTPUT_SIGNATURE DXC_FOURCC('O', 'S', 'G', '1') +#define DXC_PART_PATCH_CONSTANT_SIGNATURE DXC_FOURCC('P', 'S', 'G', '1') + +// Some option arguments are defined here for continuity with D3DCompile +// interface. +#define DXC_ARG_DEBUG L"-Zi" +#define DXC_ARG_SKIP_VALIDATION L"-Vd" +#define DXC_ARG_SKIP_OPTIMIZATIONS L"-Od" +#define DXC_ARG_PACK_MATRIX_ROW_MAJOR L"-Zpr" +#define DXC_ARG_PACK_MATRIX_COLUMN_MAJOR L"-Zpc" +#define DXC_ARG_AVOID_FLOW_CONTROL L"-Gfa" +#define DXC_ARG_PREFER_FLOW_CONTROL L"-Gfp" +#define DXC_ARG_ENABLE_STRICTNESS L"-Ges" +#define DXC_ARG_ENABLE_BACKWARDS_COMPATIBILITY L"-Gec" +#define DXC_ARG_IEEE_STRICTNESS L"-Gis" +#define DXC_ARG_OPTIMIZATION_LEVEL0 L"-O0" +#define DXC_ARG_OPTIMIZATION_LEVEL1 L"-O1" +#define DXC_ARG_OPTIMIZATION_LEVEL2 L"-O2" +#define DXC_ARG_OPTIMIZATION_LEVEL3 L"-O3" +#define DXC_ARG_WARNINGS_ARE_ERRORS L"-WX" +#define DXC_ARG_RESOURCES_MAY_ALIAS L"-res_may_alias" +#define DXC_ARG_ALL_RESOURCES_BOUND L"-all_resources_bound" +#define DXC_ARG_DEBUG_NAME_FOR_SOURCE L"-Zss" +#define DXC_ARG_DEBUG_NAME_FOR_BINARY L"-Zsb" + +CROSS_PLATFORM_UUIDOF(IDxcBlob, "8BA5FB08-5195-40e2-AC58-0D989C3A0102") +/// \brief A sized buffer that can be passed in and out of DXC APIs. +/// +/// This is an alias of ID3D10Blob and ID3DBlob. +struct IDxcBlob : public IUnknown { +public: + /// \brief Retrieves a pointer to the blob's data. + virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) = 0; + + /// \brief Retrieves the size, in bytes, of the blob's data. + virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcBlobEncoding, "7241d424-2646-4191-97c0-98e96e42fc68") +/// \brief A blob that might have a known encoding. +struct IDxcBlobEncoding : public IDxcBlob { +public: + /// \brief Retrieve the encoding for this blob. + /// + /// \param pKnown Pointer to a variable that will be set to TRUE if the + /// encoding is known. + /// + /// \param pCodePage Pointer to variable that will be set to the encoding used + /// for this blog. + /// + /// If the encoding is not known then pCodePage will be set to CP_ACP. + virtual HRESULT STDMETHODCALLTYPE GetEncoding(_Out_ BOOL *pKnown, + _Out_ UINT32 *pCodePage) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcBlobWide, "A3F84EAB-0FAA-497E-A39C-EE6ED60B2D84") +/// \brief A blob containing a null-terminated wide string. +/// +/// This uses the native wide character encoding (utf16 on Windows, utf32 on +/// Linux). +/// +/// The value returned by GetBufferSize() is the size of the buffer, in bytes, +/// including the null-terminator. +/// +/// This interface is used to return output name strings DXC. Other string +/// output blobs, such as errors/warnings, preprocessed HLSL, or other text are +/// returned using encodings based on the -encoding option passed to the +/// compiler. +struct IDxcBlobWide : public IDxcBlobEncoding { +public: + /// \brief Retrieves a pointer to the string stored in this blob. + virtual LPCWSTR STDMETHODCALLTYPE GetStringPointer(void) = 0; + + /// \brief Retrieves the length of the string stored in this blob, in + /// characters, excluding the null-terminator. + virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcBlobUtf8, "3DA636C9-BA71-4024-A301-30CBF125305B") +/// \brief A blob containing a UTF-8 encoded string. +/// +/// The value returned by GetBufferSize() is the size of the buffer, in bytes, +/// including the null-terminator. +/// +/// Depending on the -encoding option passed to the compiler, this interface is +/// used to return string output blobs, such as errors/warnings, preprocessed +/// HLSL, or other text. Output name strings always use IDxcBlobWide. +struct IDxcBlobUtf8 : public IDxcBlobEncoding { +public: + /// \brief Retrieves a pointer to the string stored in this blob. + virtual LPCSTR STDMETHODCALLTYPE GetStringPointer(void) = 0; + + /// \brief Retrieves the length of the string stored in this blob, in + /// characters, excluding the null-terminator. + virtual SIZE_T STDMETHODCALLTYPE GetStringLength(void) = 0; +}; + +#ifdef _WIN32 +/// IDxcBlobUtf16 is a legacy alias for IDxcBlobWide on Win32. +typedef IDxcBlobWide IDxcBlobUtf16; +#endif + +CROSS_PLATFORM_UUIDOF(IDxcIncludeHandler, + "7f61fc7d-950d-467f-b3e3-3c02fb49187c") +/// \brief Interface for handling include directives. +/// +/// This interface can be implemented to customize handling of include +/// directives. +/// +/// Use IDxcUtils::CreateDefaultIncludeHandler to create a default +/// implementation that reads include files from the filesystem. +/// +struct IDxcIncludeHandler : public IUnknown { + /// \brief Load a source file to be included by the compiler. + /// + /// \param pFilename Candidate filename. + /// + /// \param ppIncludeSource Resultant source object for included file, nullptr + /// if not found. + virtual HRESULT STDMETHODCALLTYPE + LoadSource(_In_z_ LPCWSTR pFilename, + _COM_Outptr_result_maybenull_ IDxcBlob **ppIncludeSource) = 0; +}; + +/// \brief Structure for supplying bytes or text input to Dxc APIs. +typedef struct DxcBuffer { + /// \brief Pointer to the start of the buffer. + LPCVOID Ptr; + + /// \brief Size of the buffer in bytes. + SIZE_T Size; + + /// \brief Encoding of the buffer. + /// + /// Use Encoding = 0 for non-text bytes, ANSI text, or unknown with BOM. + UINT Encoding; +} DxcText; + +/// \brief Structure for supplying defines to Dxc APIs. +struct DxcDefine { + LPCWSTR Name; ///< The define name. + _Maybenull_ LPCWSTR Value; ///< Optional value for the define. +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompilerArgs, "73EFFE2A-70DC-45F8-9690-EFF64C02429D") +/// \brief Interface for managing arguments passed to DXC. +/// +/// Use IDxcUtils::BuildArguments to create an instance of this interface. +struct IDxcCompilerArgs : public IUnknown { + /// \brief Retrieve the array of arguments. + /// + /// This can be passed directly to the pArguments parameter of the Compile() + /// method. + virtual LPCWSTR *STDMETHODCALLTYPE GetArguments() = 0; + + /// \brief Retrieve the number of arguments. + /// + /// This can be passed directly to the argCount parameter of the Compile() + /// method. + virtual UINT32 STDMETHODCALLTYPE GetCount() = 0; + + /// \brief Add additional arguments to this list of compiler arguments. + virtual HRESULT STDMETHODCALLTYPE AddArguments( + _In_opt_count_(argCount) + LPCWSTR *pArguments, ///< Array of pointers to arguments to add. + _In_ UINT32 argCount ///< Number of arguments to add. + ) = 0; + + /// \brief Add additional UTF-8 encoded arguments to this list of compiler + /// arguments. + virtual HRESULT STDMETHODCALLTYPE AddArgumentsUTF8( + _In_opt_count_(argCount) + LPCSTR *pArguments, ///< Array of pointers to UTF-8 arguments to add. + _In_ UINT32 argCount ///< Number of arguments to add. + ) = 0; + + /// \brief Add additional defines to this list of compiler arguments. + virtual HRESULT STDMETHODCALLTYPE AddDefines( + _In_count_(defineCount) const DxcDefine *pDefines, ///< Array of defines. + _In_ UINT32 defineCount ///< Number of defines. + ) = 0; +}; + +////////////////////////// +// Legacy Interfaces +///////////////////////// + +CROSS_PLATFORM_UUIDOF(IDxcLibrary, "e5204dc7-d18c-4c3c-bdfb-851673980fe7") +/// \deprecated IDxcUtils replaces IDxcLibrary; please use IDxcUtils insted. +struct IDxcLibrary : public IUnknown { + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE SetMalloc(_In_opt_ IMalloc *pMalloc) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE + CreateBlobFromBlob(_In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, + _COM_Outptr_ IDxcBlob **ppResult) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE + CreateBlobFromFile(_In_z_ LPCWSTR pFileName, _In_opt_ UINT32 *codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingFromPinned( + _In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnHeapCopy( + _In_bytecount_(size) LPCVOID pText, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE CreateBlobWithEncodingOnMalloc( + _In_bytecount_(size) LPCVOID pText, IMalloc *pIMalloc, UINT32 size, + UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE + CreateIncludeHandler(_COM_Outptr_ IDxcIncludeHandler **ppResult) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE CreateStreamFromBlobReadOnly( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0; + + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + + // Renamed from GetBlobAsUtf16 to GetBlobAsWide + /// \deprecated + virtual HRESULT STDMETHODCALLTYPE GetBlobAsWide( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) = 0; + +#ifdef _WIN32 + // Alias to GetBlobAsWide on Win32 + /// \deprecated + inline HRESULT GetBlobAsUtf16(_In_ IDxcBlob *pBlob, + _COM_Outptr_ IDxcBlobEncoding **pBlobEncoding) { + return this->GetBlobAsWide(pBlob, pBlobEncoding); + } +#endif +}; + +CROSS_PLATFORM_UUIDOF(IDxcOperationResult, + "CEDB484A-D4E9-445A-B991-CA21CA157DC2") +/// \brief The results of a DXC operation. +/// +/// Note: IDxcResult replaces IDxcOperationResult and should be used wherever +/// possible. +struct IDxcOperationResult : public IUnknown { + /// \brief Retrieve the overall status of the operation. + virtual HRESULT STDMETHODCALLTYPE GetStatus(_Out_ HRESULT *pStatus) = 0; + + /// \brief Retrieve the primary output of the operation. + /// + /// This corresponds to: + /// * DXC_OUT_OBJECT - Compile() with shader or library target + /// * DXC_OUT_DISASSEMBLY - Disassemble() + /// * DXC_OUT_HLSL - Compile() with -P + /// * DXC_OUT_ROOT_SIGNATURE - Compile() with rootsig_* target + virtual HRESULT STDMETHODCALLTYPE + GetResult(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; + + /// \brief Retrieves the error buffer from the operation, if there is one. + /// + // This corresponds to calling IDxcResult::GetOutput() with DXC_OUT_ERRORS. + virtual HRESULT STDMETHODCALLTYPE + GetErrorBuffer(_COM_Outptr_result_maybenull_ IDxcBlobEncoding **ppErrors) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompiler, "8c210bf3-011f-4422-8d70-6f9acb8db617") +/// \deprecated Please use IDxcCompiler3 instead. +struct IDxcCompiler : public IUnknown { + /// \brief Compile a single entry point to the target shader model. + /// + /// \deprecated Please use IDxcCompiler3::Compile() instead. + virtual HRESULT STDMETHODCALLTYPE Compile( + _In_ IDxcBlob *pSource, // Source text to compile. + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in + // errors and include handlers. + _In_opt_z_ LPCWSTR pEntryPoint, // Entry point name. + _In_z_ LPCWSTR pTargetProfile, // Shader profile to compile. + _In_opt_count_(argCount) + LPCWSTR *pArguments, // Array of pointers to arguments. + _In_ UINT32 argCount, // Number of arguments. + _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines. + _In_ UINT32 defineCount, // Number of defines. + _In_opt_ IDxcIncludeHandler + *pIncludeHandler, // User-provided interface to handle #include + // directives (optional). + _COM_Outptr_ IDxcOperationResult * + *ppResult // Compiler output status, buffer, and errors. + ) = 0; + + /// \brief Preprocess source text. + /// + /// \deprecated Please use IDxcCompiler3::Compile() with the "-P" argument + /// instead. + virtual HRESULT STDMETHODCALLTYPE Preprocess( + _In_ IDxcBlob *pSource, // Source text to preprocess. + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in + // errors and include handlers. + _In_opt_count_(argCount) + LPCWSTR *pArguments, // Array of pointers to arguments. + _In_ UINT32 argCount, // Number of arguments. + _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines. + _In_ UINT32 defineCount, // Number of defines. + _In_opt_ IDxcIncludeHandler + *pIncludeHandler, // user-provided interface to handle #include + // directives (optional). + _COM_Outptr_ IDxcOperationResult * + *ppResult // Preprocessor output status, buffer, and errors. + ) = 0; + + /// \brief Disassemble a program. + /// + /// \deprecated Please use IDxcCompiler3::Disassemble() instead. + virtual HRESULT STDMETHODCALLTYPE Disassemble( + _In_ IDxcBlob *pSource, // Program to disassemble. + _COM_Outptr_ IDxcBlobEncoding **ppDisassembly // Disassembly text. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompiler2, "A005A9D9-B8BB-4594-B5C9-0E633BEC4D37") +/// \deprecated Please use IDxcCompiler3 instead. +struct IDxcCompiler2 : public IDxcCompiler { + /// \brief Compile a single entry point to the target shader model with debug + /// information. + /// + /// \deprecated Please use IDxcCompiler3::Compile() instead. + virtual HRESULT STDMETHODCALLTYPE CompileWithDebug( + _In_ IDxcBlob *pSource, // Source text to compile. + _In_opt_z_ LPCWSTR pSourceName, // Optional file name for pSource. Used in + // errors and include handlers. + _In_opt_z_ LPCWSTR pEntryPoint, // Entry point name. + _In_z_ LPCWSTR pTargetProfile, // Shader profile to compile. + _In_opt_count_(argCount) + LPCWSTR *pArguments, // Array of pointers to arguments. + _In_ UINT32 argCount, // Number of arguments. + _In_count_(defineCount) const DxcDefine *pDefines, // Array of defines. + _In_ UINT32 defineCount, // Number of defines. + _In_opt_ IDxcIncludeHandler + *pIncludeHandler, // user-provided interface to handle #include + // directives (optional). + _COM_Outptr_ IDxcOperationResult * + *ppResult, // Compiler output status, buffer, and errors. + _Outptr_opt_result_z_ LPWSTR + *ppDebugBlobName, // Suggested file name for debug blob. Must be + // CoTaskMemFree()'d. + _COM_Outptr_opt_ IDxcBlob **ppDebugBlob // Debug blob. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcLinker, "F1B5BE2A-62DD-4327-A1C2-42AC1E1E78E6") +/// \brief DXC linker interface. +/// +/// Use DxcCreateInstance with CLSID_DxcLinker to obtain an instance of this +/// interface. +struct IDxcLinker : public IUnknown { +public: + /// \brief Register a library with name to reference it later. + virtual HRESULT + RegisterLibrary(_In_opt_ LPCWSTR pLibName, ///< Name of the library. + _In_ IDxcBlob *pLib ///< Library blob. + ) = 0; + + /// \brief Links the shader and produces a shader blob that the Direct3D + /// runtime can use. + virtual HRESULT STDMETHODCALLTYPE Link( + _In_opt_ LPCWSTR pEntryName, ///< Entry point name. + _In_ LPCWSTR pTargetProfile, ///< shader profile to link. + _In_count_(libCount) + const LPCWSTR *pLibNames, ///< Array of library names to link. + _In_ UINT32 libCount, ///< Number of libraries to link. + _In_opt_count_(argCount) + const LPCWSTR *pArguments, ///< Array of pointers to arguments. + _In_ UINT32 argCount, ///< Number of arguments. + _COM_Outptr_ IDxcOperationResult * + *ppResult ///< Linker output status, buffer, and errors. + ) = 0; +}; + +///////////////////////// +// Latest interfaces. Please use these. +//////////////////////// + +CROSS_PLATFORM_UUIDOF(IDxcUtils, "4605C4CB-2019-492A-ADA4-65F20BB7D67F") +/// \brief Various utility functions for DXC. +/// +/// Use DxcCreateInstance with CLSID_DxcUtils to obtain an instance of this +/// interface. +/// +/// IDxcUtils replaces IDxcLibrary. +struct IDxcUtils : public IUnknown { + /// \brief Create a sub-blob that holds a reference to the outer blob and + /// points to its memory. + /// + /// \param pBlob The outer blob. + /// + /// \param offset The offset inside the outer blob. + /// + /// \param length The size, in bytes, of the buffer to reference from the + /// output blob. + /// + /// \param ppResult Address of the pointer that receives a pointer to the + /// newly created blob. + virtual HRESULT STDMETHODCALLTYPE + CreateBlobFromBlob(_In_ IDxcBlob *pBlob, UINT32 offset, UINT32 length, + _COM_Outptr_ IDxcBlob **ppResult) = 0; + + // For codePage, use 0 (or DXC_CP_ACP) for raw binary or ANSI code page. + + /// \brief Create a blob referencing existing memory, with no copy. + /// + /// \param pData Pointer to buffer containing the contents of the new blob. + /// + /// \param size The size of the pData buffer, in bytes. + /// + /// \param codePage The code page to use if the blob contains text. Use + /// DXC_CP_ACP for binary or ANSI code page. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// The user must manage the memory lifetime separately. + /// + /// This replaces IDxcLibrary::CreateBlobWithEncodingFromPinned. + virtual HRESULT STDMETHODCALLTYPE CreateBlobFromPinned( + _In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; + + /// \brief Create a blob, taking ownership of memory allocated with the + /// supplied allocator. + /// + /// \param pData Pointer to buffer containing the contents of the new blob. + /// + /// \param pIMalloc The memory allocator to use. + /// + /// \param size The size of thee pData buffer, in bytes. + /// + /// \param codePage The code page to use if the blob contains text. Use + /// DXC_CP_ACP for binary or ANSI code page. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// This replaces IDxcLibrary::CreateBlobWithEncodingOnMalloc. + virtual HRESULT STDMETHODCALLTYPE MoveToBlob( + _In_bytecount_(size) LPCVOID pData, IMalloc *pIMalloc, UINT32 size, + UINT32 codePage, _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; + + /// \brief Create a blob containing a copy of the existing data. + /// + /// \param pData Pointer to buffer containing the contents of the new blob. + /// + /// \param size The size of thee pData buffer, in bytes. + /// + /// \param codePage The code page to use if the blob contains text. Use + /// DXC_CP_ACP for binary or ANSI code page. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// The new blob and its contents are allocated with the current allocator. + /// This replaces IDxcLibrary::CreateBlobWithEncodingOnHeapCopy. + virtual HRESULT STDMETHODCALLTYPE + CreateBlob(_In_bytecount_(size) LPCVOID pData, UINT32 size, UINT32 codePage, + _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; + + /// \brief Create a blob with data loaded from a file. + /// + /// \param pFileName The name of the file to load from. + /// + /// \param pCodePage Optional code page to use if the blob contains text. Pass + /// NULL for binary data. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// The new blob and its contents are allocated with the current allocator. + /// This replaces IDxcLibrary::CreateBlobFromFile. + virtual HRESULT STDMETHODCALLTYPE + LoadFile(_In_z_ LPCWSTR pFileName, _In_opt_ UINT32 *pCodePage, + _COM_Outptr_ IDxcBlobEncoding **ppBlobEncoding) = 0; + + /// \brief Create a stream that reads data from a blob. + /// + /// \param pBlob The blob to read from. + /// + /// \param ppStream Address of the pointer that receives a pointer to the + /// newly created stream. + virtual HRESULT STDMETHODCALLTYPE CreateReadOnlyStreamFromBlob( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IStream **ppStream) = 0; + + /// \brief Create default file-based include handler. + /// + /// \param ppResult Address of the pointer that receives a pointer to the + /// newly created include handler. + virtual HRESULT STDMETHODCALLTYPE + CreateDefaultIncludeHandler(_COM_Outptr_ IDxcIncludeHandler **ppResult) = 0; + + /// \brief Convert or return matching encoded text blob as UTF-8. + /// + /// \param pBlob The blob to convert. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + virtual HRESULT STDMETHODCALLTYPE GetBlobAsUtf8( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobUtf8 **ppBlobEncoding) = 0; + + /// \brief Convert or return matching encoded text blob as UTF-16. + /// + /// \param pBlob The blob to convert. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + virtual HRESULT STDMETHODCALLTYPE GetBlobAsWide( + _In_ IDxcBlob *pBlob, _COM_Outptr_ IDxcBlobWide **ppBlobEncoding) = 0; + +#ifdef _WIN32 + /// \brief Convert or return matching encoded text blob as UTF-16. + /// + /// \param pBlob The blob to convert. + /// + /// \param ppBlobEncoding Address of the pointer that receives a pointer to + /// the newly created blob. + /// + /// Alias to GetBlobAsWide on Win32. + inline HRESULT GetBlobAsUtf16(_In_ IDxcBlob *pBlob, + _COM_Outptr_ IDxcBlobWide **ppBlobEncoding) { + return this->GetBlobAsWide(pBlob, ppBlobEncoding); + } +#endif + + /// \brief Retrieve a single part from a DXIL container. + /// + /// \param pShader The shader to retrieve the part from. + /// + /// \param DxcPart The part to retrieve (eg DXC_PART_ROOT_SIGNATURE). + /// + /// \param ppPartData Address of the pointer that receives a pointer to the + /// part. + /// + /// \param pPartSizeInBytes Address of the pointer that receives the size of + /// the part. + /// + /// The returned pointer points inside the buffer passed in pShader. + virtual HRESULT STDMETHODCALLTYPE + GetDxilContainerPart(_In_ const DxcBuffer *pShader, _In_ UINT32 DxcPart, + _Outptr_result_nullonfailure_ void **ppPartData, + _Out_ UINT32 *pPartSizeInBytes) = 0; + + /// \brief Create reflection interface from serialized DXIL container or the + /// DXC_OUT_REFLECTION blob contents. + /// + /// \param pData The source data. + /// + /// \param iid The interface ID of the reflection interface to create. + /// + /// \param ppvReflection Address of the pointer that receives a pointer to the + /// newly created reflection interface. + /// + /// Use this with interfaces such as ID3D12ShaderReflection. + virtual HRESULT STDMETHODCALLTYPE CreateReflection( + _In_ const DxcBuffer *pData, REFIID iid, void **ppvReflection) = 0; + + /// \brief Build arguments that can be passed to the Compile method. + virtual HRESULT STDMETHODCALLTYPE BuildArguments( + _In_opt_z_ LPCWSTR pSourceName, ///< Optional file name for pSource. Used + ///< in errors and include handlers. + _In_opt_z_ LPCWSTR pEntryPoint, ///< Entry point name (-E). + _In_z_ LPCWSTR pTargetProfile, ///< Shader profile to compile (-T). + _In_opt_count_(argCount) + LPCWSTR *pArguments, ///< Array of pointers to arguments. + _In_ UINT32 argCount, ///< Number of arguments. + _In_count_(defineCount) const DxcDefine *pDefines, ///< Array of defines. + _In_ UINT32 defineCount, ///< Number of defines. + _COM_Outptr_ IDxcCompilerArgs * + *ppArgs ///< Arguments you can use with Compile() method. + ) = 0; + + /// \brief Retrieve the hash and contents of a shader PDB. + /// + /// \param pPDBBlob The blob containing the PDB. + /// + /// \param ppHash Address of the pointer that receives a pointer to the hash + /// blob. + /// + /// \param ppContainer Address of the pointer that receives a pointer to the + /// bloc containing the contents of the PDB. + /// + virtual HRESULT STDMETHODCALLTYPE + GetPDBContents(_In_ IDxcBlob *pPDBBlob, _COM_Outptr_ IDxcBlob **ppHash, + _COM_Outptr_ IDxcBlob **ppContainer) = 0; +}; + +/// \brief Specifies the kind of output to retrieve from a IDxcResult. +/// +/// Note: text outputs returned from version 2 APIs are UTF-8 or UTF-16 based on +/// the -encoding option passed to the compiler. +typedef enum DXC_OUT_KIND { + DXC_OUT_NONE = 0, ///< No output. + DXC_OUT_OBJECT = 1, ///< IDxcBlob - Shader or library object. + DXC_OUT_ERRORS = 2, ///< IDxcBlobUtf8 or IDxcBlobWide. + DXC_OUT_PDB = 3, ///< IDxcBlob. + DXC_OUT_SHADER_HASH = 4, ///< IDxcBlob - DxcShaderHash of shader or shader + ///< with source info (-Zsb/-Zss). + DXC_OUT_DISASSEMBLY = 5, ///< IDxcBlobUtf8 or IDxcBlobWide - from Disassemble. + DXC_OUT_HLSL = + 6, ///< IDxcBlobUtf8 or IDxcBlobWide - from Preprocessor or Rewriter. + DXC_OUT_TEXT = 7, ///< IDxcBlobUtf8 or IDxcBlobWide - other text, such as + ///< -ast-dump or -Odump. + DXC_OUT_REFLECTION = 8, ///< IDxcBlob - RDAT part with reflection data. + DXC_OUT_ROOT_SIGNATURE = 9, ///< IDxcBlob - Serialized root signature output. + DXC_OUT_EXTRA_OUTPUTS = 10, ///< IDxcExtraOutputs - Extra outputs. + DXC_OUT_REMARKS = + 11, ///< IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout. + DXC_OUT_TIME_REPORT = + 12, ///< IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout. + DXC_OUT_TIME_TRACE = + 13, ///< IDxcBlobUtf8 or IDxcBlobWide - text directed at stdout. + + DXC_OUT_LAST = DXC_OUT_TIME_TRACE, ///< Last value for a counter. + + DXC_OUT_NUM_ENUMS, + DXC_OUT_FORCE_DWORD = 0xFFFFFFFF +} DXC_OUT_KIND; + +static_assert(DXC_OUT_NUM_ENUMS == DXC_OUT_LAST + 1, + "DXC_OUT_* Enum added and last value not updated."); + +CROSS_PLATFORM_UUIDOF(IDxcResult, "58346CDA-DDE7-4497-9461-6F87AF5E0659") +/// \brief Result of a DXC operation. +/// +/// DXC operations may have multiple outputs, such as a shader object and +/// errors. This interface provides access to the outputs. +struct IDxcResult : public IDxcOperationResult { + /// \brief Determines whether or not this result has the specified output. + /// + /// \param dxcOutKind The kind of output to check for. + virtual BOOL STDMETHODCALLTYPE HasOutput(_In_ DXC_OUT_KIND dxcOutKind) = 0; + + /// \brief Retrieves the specified output. + /// + /// \param dxcOutKind The kind of output to retrieve. + /// + /// \param iid The interface ID of the output interface. + /// + /// \param ppvObject Address of the pointer that receives a pointer to the + /// output. + /// + /// \param ppOutputName Optional address of a pointer to receive the name + /// blob, if there is one. + virtual HRESULT STDMETHODCALLTYPE + GetOutput(_In_ DXC_OUT_KIND dxcOutKind, _In_ REFIID iid, + _COM_Outptr_opt_result_maybenull_ void **ppvObject, + _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputName) = 0; + + /// \brief Retrieves the number of outputs available in this result. + virtual UINT32 GetNumOutputs() = 0; + + /// \brief Retrieves the output kind at the specified index. + virtual DXC_OUT_KIND GetOutputByIndex(UINT32 Index) = 0; + + /// \brief Retrieves the primary output kind for this result. + /// + /// See IDxcOperationResult::GetResult() for more information on the primary + /// output kinds. + virtual DXC_OUT_KIND PrimaryOutput() = 0; +}; + +// Special names for extra output that should get written to specific streams. +#define DXC_EXTRA_OUTPUT_NAME_STDOUT L"*stdout*" +#define DXC_EXTRA_OUTPUT_NAME_STDERR L"*stderr*" + +CROSS_PLATFORM_UUIDOF(IDxcExtraOutputs, "319b37a2-a5c2-494a-a5de-4801b2faf989") +/// \brief Additional outputs from a DXC operation. +/// +/// This can be used to obtain outputs that don't have an explicit DXC_OUT_KIND. +/// Use DXC_OUT_EXTRA_OUTPUTS to obtain instances of this. +struct IDxcExtraOutputs : public IUnknown { + /// \brief Retrieves the number of outputs available + virtual UINT32 STDMETHODCALLTYPE GetOutputCount() = 0; + + /// \brief Retrieves the specified output. + /// + /// \param uIndex The index of the output to retrieve. + /// + /// \param iid The interface ID of the output interface. + /// + /// \param ppvObject Optional address of the pointer that receives a pointer + /// to the output if there is one. + /// + /// \param ppOutputType Optional address of the pointer that receives the + /// output type name blob if there is one. + /// + /// \param ppOutputName Optional address of the pointer that receives the + /// output name blob if there is one. + virtual HRESULT STDMETHODCALLTYPE + GetOutput(_In_ UINT32 uIndex, _In_ REFIID iid, + _COM_Outptr_opt_result_maybenull_ void **ppvObject, + _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputType, + _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppOutputName) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcCompiler3, "228B4687-5A6A-4730-900C-9702B2203F54") +/// \brief Interface to the DirectX Shader Compiler. +/// +/// Use DxcCreateInstance with CLSID_DxcCompiler to obtain an instance of this +/// interface. +struct IDxcCompiler3 : public IUnknown { + /// \brief Compile a shader. + /// + /// IDxcUtils::BuildArguments can be used to assist building the pArguments + /// and argCount parameters. + /// + /// Depending on the arguments, this method can be used to: + /// + /// * Compile a single entry point to the target shader model, + /// * Compile a library to a library target (-T lib_*) + /// * Compile a root signature (-T rootsig_*), + /// * Preprocess HLSL source (-P). + virtual HRESULT STDMETHODCALLTYPE Compile( + _In_ const DxcBuffer *pSource, ///< Source text to compile. + _In_opt_count_(argCount) + LPCWSTR *pArguments, ///< Array of pointers to arguments. + _In_ UINT32 argCount, ///< Number of arguments. + _In_opt_ IDxcIncludeHandler + *pIncludeHandler, ///< user-provided interface to handle include + ///< directives (optional). + _In_ REFIID riid, ///< Interface ID for the result. + _Out_ LPVOID *ppResult ///< IDxcResult: status, buffer, and errors. + ) = 0; + + /// \brief Disassemble a program. + virtual HRESULT STDMETHODCALLTYPE Disassemble( + _In_ const DxcBuffer + *pObject, ///< Program to disassemble: dxil container or bitcode. + _In_ REFIID riid, ///< Interface ID for the result. + _Out_ LPVOID + *ppResult ///< IDxcResult: status, disassembly text, and errors. + ) = 0; +}; + +static const UINT32 DxcValidatorFlags_Default = 0; +static const UINT32 DxcValidatorFlags_InPlaceEdit = + 1; // Validator is allowed to update shader blob in-place. +static const UINT32 DxcValidatorFlags_RootSignatureOnly = 2; +static const UINT32 DxcValidatorFlags_ModuleOnly = 4; +static const UINT32 DxcValidatorFlags_ValidMask = 0x7; + +CROSS_PLATFORM_UUIDOF(IDxcValidator, "A6E82BD2-1FD7-4826-9811-2857E797F49A") +/// \brief Interface to DXC shader validator. +/// +/// Use DxcCreateInstance with CLSID_DxcValidator to obtain an instance of this. +struct IDxcValidator : public IUnknown { + /// \brief Validate a shader. + virtual HRESULT STDMETHODCALLTYPE Validate( + _In_ IDxcBlob *pShader, ///< Shader to validate. + _In_ UINT32 Flags, ///< Validation flags. + _COM_Outptr_ IDxcOperationResult * + *ppResult ///< Validation output status, buffer, and errors. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcValidator2, "458e1fd1-b1b2-4750-a6e1-9c10f03bed92") +/// \brief Interface to DXC shader validator. +/// +/// Use DxcCreateInstance with CLSID_DxcValidator to obtain an instance of this. +struct IDxcValidator2 : public IDxcValidator { + /// \brief Validate a shader with optional debug bitcode. + virtual HRESULT STDMETHODCALLTYPE ValidateWithDebug( + _In_ IDxcBlob *pShader, ///< Shader to validate. + _In_ UINT32 Flags, ///< Validation flags. + _In_opt_ DxcBuffer *pOptDebugBitcode, ///< Optional debug module bitcode + ///< to provide line numbers. + _COM_Outptr_ IDxcOperationResult * + *ppResult ///< Validation output status, buffer, and errors. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcContainerBuilder, + "334b1f50-2292-4b35-99a1-25588d8c17fe") +/// \brief Interface to DXC container builder. +/// +/// Use DxcCreateInstance with CLSID_DxcContainerBuilder to obtain an instance +/// of this. +struct IDxcContainerBuilder : public IUnknown { + /// \brief Load a DxilContainer to the builder. + virtual HRESULT STDMETHODCALLTYPE + Load(_In_ IDxcBlob *pDxilContainerHeader) = 0; + + /// \brief Add a part to the container. + /// + /// \param fourCC The part identifier (eg DXC_PART_PDB). + /// + /// \param pSource The source blob. + virtual HRESULT STDMETHODCALLTYPE AddPart(_In_ UINT32 fourCC, + _In_ IDxcBlob *pSource) = 0; + + /// \brief Remove a part from the container. + /// + /// \param fourCC The part identifier (eg DXC_PART_PDB). + /// + /// \return S_OK on success, DXC_E_MISSING_PART if the part was not found, or + /// other standard HRESULT error code. + virtual HRESULT STDMETHODCALLTYPE RemovePart(_In_ UINT32 fourCC) = 0; + + /// \brief Build the container. + /// + /// \param ppResult Pointer to variable to receive the result. + virtual HRESULT STDMETHODCALLTYPE + SerializeContainer(_Out_ IDxcOperationResult **ppResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcAssembler, "091f7a26-1c1f-4948-904b-e6e3a8a771d5") +/// \brief Interface to DxcAssembler. +/// +/// Use DxcCreateInstance with CLSID_DxcAssembler to obtain an instance of this. +struct IDxcAssembler : public IUnknown { + /// \brief Assemble DXIL in LL or LLVM bitcode to DXIL container. + virtual HRESULT STDMETHODCALLTYPE AssembleToContainer( + _In_ IDxcBlob *pShader, ///< Shader to assemble. + _COM_Outptr_ IDxcOperationResult * + *ppResult ///< Assembly output status, buffer, and errors. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcContainerReflection, + "d2c21b26-8350-4bdc-976a-331ce6f4c54c") +/// \brief Interface to DxcContainerReflection. +/// +/// Use DxcCreateInstance with CLSID_DxcContainerReflection to obtain an +/// instance of this. +struct IDxcContainerReflection : public IUnknown { + /// \brief Choose the container to perform reflection on + /// + /// \param pContainer The container to load. If null is passed then this + /// instance will release any held resources. + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pContainer) = 0; + + /// \brief Retrieves the number of parts in the container. + /// + /// \param pResult Pointer to variable to receive the result. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), or other standard HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE GetPartCount(_Out_ UINT32 *pResult) = 0; + + /// \brief Retrieve the kind of a specified part. + /// + /// \param idx The index of the part to retrieve the kind of. + /// + /// \param pResult Pointer to variable to receive the result. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), E_BOUND if idx is out of bounds, or other standard + /// HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE GetPartKind(UINT32 idx, + _Out_ UINT32 *pResult) = 0; + + /// \brief Retrieve the content of a specified part. + /// + /// \param idx The index of the part to retrieve. + /// + /// \param ppResult Pointer to variable to receive the result. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), E_BOUND if idx is out of bounds, or other standard + /// HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE + GetPartContent(UINT32 idx, _COM_Outptr_ IDxcBlob **ppResult) = 0; + + /// \brief Retrieve the index of the first part with the specified kind. + /// + /// \param kind The kind to search for. + /// + /// \param pResult Pointer to variable to receive the index of the matching + /// part. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), HRESULT_FROM_WIN32(ERROR_NOT_FOUND) if there is no + /// part with the specified kind, or other standard HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE + FindFirstPartKind(UINT32 kind, _Out_ UINT32 *pResult) = 0; + + /// \brief Retrieve the reflection interface for a specified part. + /// + /// \param idx The index of the part to retrieve the reflection interface of. + /// + /// \param iid The IID of the interface to retrieve. + /// + /// \param ppvObject Pointer to variable to receive the result. + /// + /// Use this with interfaces such as ID3D12ShaderReflection. + /// + /// \return S_OK on success, E_NOT_VALID_STATE if a container has not been + /// loaded using Load(), E_BOUND if idx is out of bounds, or other standard + /// HRESULT error codes. + virtual HRESULT STDMETHODCALLTYPE GetPartReflection(UINT32 idx, REFIID iid, + void **ppvObject) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcOptimizerPass, "AE2CD79F-CC22-453F-9B6B-B124E7A5204C") +/// \brief An optimizer pass. +/// +/// Instances of this can be obtained via IDxcOptimizer::GetAvailablePass. +struct IDxcOptimizerPass : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetOptionName(_COM_Outptr_ LPWSTR *ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetDescription(_COM_Outptr_ LPWSTR *ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE GetOptionArgCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetOptionArgName(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetOptionArgDescription(UINT32 argIndex, _COM_Outptr_ LPWSTR *ppResult) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcOptimizer, "25740E2E-9CBA-401B-9119-4FB42F39F270") +/// \brief Interface to DxcOptimizer. +/// +/// Use DxcCreateInstance with CLSID_DxcOptimizer to obtain an instance of this. +struct IDxcOptimizer : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetAvailablePassCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetAvailablePass(UINT32 index, _COM_Outptr_ IDxcOptimizerPass **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + RunOptimizer(IDxcBlob *pBlob, _In_count_(optionCount) LPCWSTR *ppOptions, + UINT32 optionCount, _COM_Outptr_ IDxcBlob **pOutputModule, + _COM_Outptr_opt_ IDxcBlobEncoding **ppOutputText) = 0; +}; + +static const UINT32 DxcVersionInfoFlags_None = 0; +static const UINT32 DxcVersionInfoFlags_Debug = 1; // Matches VS_FF_DEBUG +static const UINT32 DxcVersionInfoFlags_Internal = + 2; // Internal Validator (non-signing) + +CROSS_PLATFORM_UUIDOF(IDxcVersionInfo, "b04f5b50-2059-4f12-a8ff-a1e0cde1cc7e") +/// \brief PDB Version information. +/// +/// Use IDxcPdbUtils2::GetVersionInfo to obtain an instance of this. +struct IDxcVersionInfo : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetVersion(_Out_ UINT32 *pMajor, + _Out_ UINT32 *pMinor) = 0; + virtual HRESULT STDMETHODCALLTYPE GetFlags(_Out_ UINT32 *pFlags) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcVersionInfo2, "fb6904c4-42f0-4b62-9c46-983af7da7c83") +/// \brief PDB Version Information. +/// +/// Use IDxcPdbUtils2::GetVersionInfo to obtain a IDxcVersionInfo interface, and +/// then use QueryInterface to obtain an instance of this interface from it. +struct IDxcVersionInfo2 : public IDxcVersionInfo { + virtual HRESULT STDMETHODCALLTYPE GetCommitInfo( + _Out_ UINT32 *pCommitCount, ///< The total number commits. + _Outptr_result_z_ char **pCommitHash ///< The SHA of the latest commit. + ///< Must be CoTaskMemFree()'d. + ) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcVersionInfo3, "5e13e843-9d25-473c-9ad2-03b2d0b44b1e") +/// \brief PDB Version Information. +/// +/// Use IDxcPdbUtils2::GetVersionInfo to obtain a IDxcVersionInfo interface, and +/// then use QueryInterface to obtain an instance of this interface from it. +struct IDxcVersionInfo3 : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE GetCustomVersionString( + _Outptr_result_z_ char * + *pVersionString ///< Custom version string for compiler. Must be + ///< CoTaskMemFree()'d. + ) = 0; +}; + +struct DxcArgPair { + const WCHAR *pName; + const WCHAR *pValue; +}; + +CROSS_PLATFORM_UUIDOF(IDxcPdbUtils, "E6C9647E-9D6A-4C3B-B94C-524B5A6C343D") +/// \deprecated Please use IDxcPdbUtils2 instead. +struct IDxcPdbUtils : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pPdbOrDxil) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetSourceCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSource(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobEncoding **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSourceName(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetFlagCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetFlag(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetArg(_In_ UINT32 uIndex, + _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetArgPair(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pName, + _Outptr_result_z_ BSTR *pValue) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDefineCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetDefine(_In_ UINT32 uIndex, _Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetTargetProfile(_Outptr_result_z_ BSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetEntryPoint(_Outptr_result_z_ BSTR *pResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetMainFileName(_Outptr_result_z_ BSTR *pResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetHash(_COM_Outptr_ IDxcBlob **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetName(_Outptr_result_z_ BSTR *pResult) = 0; + + virtual BOOL STDMETHODCALLTYPE IsFullPDB() = 0; + virtual HRESULT STDMETHODCALLTYPE + GetFullPDB(_COM_Outptr_ IDxcBlob **ppFullPDB) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetVersionInfo(_COM_Outptr_ IDxcVersionInfo **ppVersionInfo) = 0; + + virtual HRESULT STDMETHODCALLTYPE + SetCompiler(_In_ IDxcCompiler3 *pCompiler) = 0; + virtual HRESULT STDMETHODCALLTYPE + CompileForFullPDB(_COM_Outptr_ IDxcResult **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE OverrideArgs(_In_ DxcArgPair *pArgPairs, + UINT32 uNumArgPairs) = 0; + virtual HRESULT STDMETHODCALLTYPE + OverrideRootSignature(_In_ const WCHAR *pRootSignature) = 0; +}; + +CROSS_PLATFORM_UUIDOF(IDxcPdbUtils2, "4315D938-F369-4F93-95A2-252017CC3807") +/// \brief DxcPdbUtils interface. +/// +/// Use DxcCreateInstance with CLSID_DxcPdbUtils to create an instance of this. +struct IDxcPdbUtils2 : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pPdbOrDxil) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetSourceCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSource(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobEncoding **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetSourceName(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetLibraryPDBCount(UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetLibraryPDB( + _In_ UINT32 uIndex, _COM_Outptr_ IDxcPdbUtils2 **ppOutPdbUtils, + _COM_Outptr_opt_result_maybenull_ IDxcBlobWide **ppLibraryName) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetFlagCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetFlag(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetArg(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetArgPairCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE GetArgPair( + _In_ UINT32 uIndex, _COM_Outptr_result_maybenull_ IDxcBlobWide **ppName, + _COM_Outptr_result_maybenull_ IDxcBlobWide **ppValue) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDefineCount(_Out_ UINT32 *pCount) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetDefine(_In_ UINT32 uIndex, _COM_Outptr_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetTargetProfile(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetEntryPoint(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetMainFileName(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetHash(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetName(_COM_Outptr_result_maybenull_ IDxcBlobWide **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetVersionInfo( + _COM_Outptr_result_maybenull_ IDxcVersionInfo **ppVersionInfo) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetCustomToolchainID(_Out_ UINT32 *pID) = 0; + virtual HRESULT STDMETHODCALLTYPE + GetCustomToolchainData(_COM_Outptr_result_maybenull_ IDxcBlob **ppBlob) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetWholeDxil(_COM_Outptr_result_maybenull_ IDxcBlob **ppResult) = 0; + + virtual BOOL STDMETHODCALLTYPE IsFullPDB() = 0; + virtual BOOL STDMETHODCALLTYPE IsPDBRef() = 0; +}; + +// Note: __declspec(selectany) requires 'extern' +// On Linux __declspec(selectany) is removed and using 'extern' results in link +// error. +#ifdef _MSC_VER +#define CLSID_SCOPE __declspec(selectany) extern +#else +#define CLSID_SCOPE +#endif + +CLSID_SCOPE const CLSID CLSID_DxcCompiler = { + 0x73e22d93, + 0xe6ce, + 0x47f3, + {0xb5, 0xbf, 0xf0, 0x66, 0x4f, 0x39, 0xc1, 0xb0}}; + +// {EF6A8087-B0EA-4D56-9E45-D07E1A8B7806} +CLSID_SCOPE const GUID CLSID_DxcLinker = { + 0xef6a8087, + 0xb0ea, + 0x4d56, + {0x9e, 0x45, 0xd0, 0x7e, 0x1a, 0x8b, 0x78, 0x6}}; + +// {CD1F6B73-2AB0-484D-8EDC-EBE7A43CA09F} +CLSID_SCOPE const CLSID CLSID_DxcDiaDataSource = { + 0xcd1f6b73, + 0x2ab0, + 0x484d, + {0x8e, 0xdc, 0xeb, 0xe7, 0xa4, 0x3c, 0xa0, 0x9f}}; + +// {3E56AE82-224D-470F-A1A1-FE3016EE9F9D} +CLSID_SCOPE const CLSID CLSID_DxcCompilerArgs = { + 0x3e56ae82, + 0x224d, + 0x470f, + {0xa1, 0xa1, 0xfe, 0x30, 0x16, 0xee, 0x9f, 0x9d}}; + +// {6245D6AF-66E0-48FD-80B4-4D271796748C} +CLSID_SCOPE const GUID CLSID_DxcLibrary = { + 0x6245d6af, + 0x66e0, + 0x48fd, + {0x80, 0xb4, 0x4d, 0x27, 0x17, 0x96, 0x74, 0x8c}}; + +CLSID_SCOPE const GUID CLSID_DxcUtils = CLSID_DxcLibrary; + +// {8CA3E215-F728-4CF3-8CDD-88AF917587A1} +CLSID_SCOPE const GUID CLSID_DxcValidator = { + 0x8ca3e215, + 0xf728, + 0x4cf3, + {0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1}}; + +// {D728DB68-F903-4F80-94CD-DCCF76EC7151} +CLSID_SCOPE const GUID CLSID_DxcAssembler = { + 0xd728db68, + 0xf903, + 0x4f80, + {0x94, 0xcd, 0xdc, 0xcf, 0x76, 0xec, 0x71, 0x51}}; + +// {b9f54489-55b8-400c-ba3a-1675e4728b91} +CLSID_SCOPE const GUID CLSID_DxcContainerReflection = { + 0xb9f54489, + 0x55b8, + 0x400c, + {0xba, 0x3a, 0x16, 0x75, 0xe4, 0x72, 0x8b, 0x91}}; + +// {AE2CD79F-CC22-453F-9B6B-B124E7A5204C} +CLSID_SCOPE const GUID CLSID_DxcOptimizer = { + 0xae2cd79f, + 0xcc22, + 0x453f, + {0x9b, 0x6b, 0xb1, 0x24, 0xe7, 0xa5, 0x20, 0x4c}}; + +// {94134294-411f-4574-b4d0-8741e25240d2} +CLSID_SCOPE const GUID CLSID_DxcContainerBuilder = { + 0x94134294, + 0x411f, + 0x4574, + {0xb4, 0xd0, 0x87, 0x41, 0xe2, 0x52, 0x40, 0xd2}}; + +// {54621dfb-f2ce-457e-ae8c-ec355faeec7c} +CLSID_SCOPE const GUID CLSID_DxcPdbUtils = { + 0x54621dfb, + 0xf2ce, + 0x457e, + {0xae, 0x8c, 0xec, 0x35, 0x5f, 0xae, 0xec, 0x7c}}; + +#endif +#pragma endregion + +// Xbox-specific content below. +#include + +enum class DxcXboxShaderStatsClass { + V1 = 1, + V2 = 2, + V3 = 3, +}; + +struct DxcXboxShaderStaticsV1 { + uint16_t NumVGPR; + uint16_t NumSGPR; + uint8_t WaveSize; + uint8_t Occupancy; + uint16_t ThreadGroupWaveCount; + + uint32_t LDSSizeInBytes; + uint32_t PerLaneScratchSizeInBytes; +}; + +struct RawInstuctionStat { + uint32_t WholePgm; + uint32_t PgmUncond; + uint32_t PgmCond; + uint32_t PgmInLoop; + uint32_t ShortestPath; + uint32_t LongestPath; +}; + +struct MemoryAccessStat { + RawInstuctionStat Total; + RawInstuctionStat Read; + RawInstuctionStat Write; + RawInstuctionStat Atomic; + RawInstuctionStat Other; +}; + +struct RawInstructionStats { + RawInstuctionStat ScalarALU; + RawInstuctionStat VectorALU; + RawInstuctionStat VALUFullRate; + RawInstuctionStat VALUHalfRate; + RawInstuctionStat VALUQuarterRate; + RawInstuctionStat VALU1_8Rate; + RawInstuctionStat VALU1_16Rate; + RawInstuctionStat ScalarMem; + RawInstuctionStat VectorMem; + MemoryAccessStat VBuf; + MemoryAccessStat Image; + MemoryAccessStat LDS; + MemoryAccessStat GDS; + RawInstuctionStat Export; + RawInstuctionStat UncondBranch; + RawInstuctionStat CondBranch; + RawInstuctionStat PCControl; + RawInstuctionStat Barrier; + RawInstuctionStat WaitCnt; + RawInstuctionStat WaitCntVMem; + RawInstuctionStat WaitCntLGKM; + RawInstuctionStat WaitCntExp; + RawInstuctionStat Message; + RawInstuctionStat Other; +}; + +struct DxcXboxShaderStaticsV2 : DxcXboxShaderStaticsV1 { + uint8_t NumSharedVGPR; + + uint8_t NumUserSGPR; + uint8_t NumSPIVGPR; + uint8_t NumSPISGPR; + uint8_t GPUSaturationInWaves; // occupancy. + // All float elements are in percentage. + // And all these elements are theoretical. + float CUOccupancy; // ((float)occupancy) / total waves in a CU. + float SIMDOccupancy; // ((float)occupancy) / total waves in a SIMD. + float SALUSMemUtilization; // SALUSMemCycles/totalCycles. + float VALUUtilization; // VALUCycles/totalCycles. + float VMEMUtilization; // VMEMCycles/totalCycles. + float LDSAtomUtilization; // LDSAtomCycles/totalCycles. + float EXPUtilization; // EXPCycles/totalCycles. + float BranchUtilization; // BranchCyles/totalCycles. + float IPCUtilization; // IPCCycles/totalCycles. + RawInstructionStats RawInstStats; +}; + +struct InstructionFormatStats { + // SALU instruction formats. + RawInstuctionStat SOP1; + RawInstuctionStat SOP2; + RawInstuctionStat SOPC; + RawInstuctionStat SOPK; + RawInstuctionStat SOPP; + + // VALU instruction formats. + RawInstuctionStat VOP1; + RawInstuctionStat VOP2; + RawInstuctionStat VOPC; + RawInstuctionStat VOP3; + RawInstuctionStat VOP3P; + + RawInstuctionStat VINTRP; + RawInstuctionStat SDWA; + RawInstuctionStat DPP; + + // Memory instruction formats. + RawInstuctionStat MUBUF; + RawInstuctionStat MTBUF; + RawInstuctionStat SMRD; + RawInstuctionStat MIMG; + RawInstuctionStat EXP; + RawInstuctionStat FLAT; + RawInstuctionStat DS; +}; + +struct DxcXboxShaderStaticsV3 : DxcXboxShaderStaticsV2 +{ + InstructionFormatStats InstFormatStats; +}; + + +CROSS_PLATFORM_UUIDOF(IDxcXboxHwShader, "13FC76D2-EDFE-4736-9980-7286B1A5246C") +struct IDxcXboxHwShader : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetStageName(_COM_Outptr_ IDxcBlobUtf8 **ppName) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetCode(_COM_Outptr_ IDxcBlob **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetShaderStats(_In_ DxcXboxShaderStatsClass StatsClass, _In_ uint32_t Flag, + _COM_Outptr_ IDxcBlob **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE + GetDebugInfo(_COM_Outptr_ IDxcBlob **ppResult) = 0; +}; + +// {0B091191-42FC-457B-8938-A76FDCAF02E3} +CLSID_SCOPE const CLSID CLSID_DxcXboxHwShader = +{ 0xb091191, 0x42fc, 0x457b, { 0x89, 0x38, 0xa7, 0x6f, 0xdc, 0xaf, 0x2, 0xe3 } }; + + +CROSS_PLATFORM_UUIDOF(IDxcXboxContainer, "7F3D5E18-D4F0-4BA1-AAC1-CD5C5DA4EBBF") +struct IDxcXboxContainer : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pContainerBlob, + _In_ IDxcBlob *pPDBBlob=nullptr) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetNumShaders(_Out_ UINT32 *pNumber) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetShader( + _In_ UINT32 uIndex, _In_ REFIID riid, _Out_ LPVOID *ppv) = 0; +}; + +// {B3D47A7F-0970-414A-900B-BB140101EC66} +CLSID_SCOPE const CLSID CLSID_DxcXboxContainer = +{ 0xb3d47a7f, 0x970, 0x414a, { 0x90, 0xb, 0xbb, 0x14, 0x1, 0x1, 0xec, 0x66 } }; + + +CROSS_PLATFORM_UUIDOF(IDxcXboxShaderStats, "1F0D2587-018C-4FB9-BC94-5F269802AAE5") +struct IDxcXboxShaderStats : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE + GetShaderStats(_In_ const DxcBuffer *pContainer, + _In_ DxcXboxShaderStatsClass StatsClass, _In_ uint32_t hwStage, + _In_ uint32_t Flag, _COM_Outptr_ IDxcBlob **ppResult) = 0; +}; + +// {EC07AED8-07D5-4B40-9458-C3EB2A80C01A} +CLSID_SCOPE const CLSID CLSID_DxcXboxShaderStats = { + 0xec07aed8, + 0x7d5, + 0x4b40, + {0x94, 0x58, 0xc3, 0xeb, 0x2a, 0x80, 0xc0, 0x1a}}; + +CROSS_PLATFORM_UUIDOF(IDxcXboxBackendDebugInfo, "B3998EF9-0357-49CD-9636-3E3FD4760500") +struct IDxcXboxBackendDebugInfo : public IUnknown { + + virtual HRESULT STDMETHODCALLTYPE Load( + _In_ IDxcBlob *pShaderBlob) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDebugInfoForStage( + _In_ UINT32 hwStage, + _COM_Outptr_ IDxcBlob **ppResult) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetNumStages(_Out_ UINT32 *pNumber) = 0; + virtual HRESULT STDMETHODCALLTYPE GetStage(_In_ UINT32 uIndex, _Out_ UINT32 *pOutStage) = 0; +}; + +// {439ee57d-768c-4a3f-ab56-ededc26c293f} +CLSID_SCOPE const CLSID CLSID_DxcXboxBackendDebugInfo = { + 0x439ee57d, + 0x768c, + 0x4a3f, + {0xab, 0x56, 0xed, 0xed, 0xc2, 0x6c, 0x29, 0x3f}}; + +CROSS_PLATFORM_UUIDOF(IXdxrPdbRecompiler, "72D06A46-03B6-45AA-BC42-3F11910F13F4") +struct IXdxrPdbRecompiler : public IUnknown { + virtual HRESULT Recompile( + _In_ const DxcBuffer *pRootPDB, + _In_ const DxcBuffer *pLibraryDxils, + _In_ UINT uNumLibraryDxils, + _In_ REFIID riid, + _Out_ LPVOID* ppv // IDxcResult or IDxcOperationResult + ) = 0; +}; + +// {b5ff745b-fa20-41b2-89aa-1800a66dcfd6} +CLSID_SCOPE const CLSID CLSID_XdxrPdbRecompiler = { + 0xb5ff745b, + 0xfa20, + 0x41b2, + {0x89, 0xaa, 0x18, 0x00, 0xa6, 0x6d, 0xcf, 0xd6}}; diff --git a/docs/gdkx/executeindirectbundlex.md b/docs/gdkx/executeindirectbundlex.md new file mode 100644 index 0000000..7744547 --- /dev/null +++ b/docs/gdkx/executeindirectbundlex.md @@ -0,0 +1,104 @@ +--- +author: sdgmiller +title: "ExecuteIndirectBundleX (Xbox One family)" +description: "Indirectly executes a bundle from a buffer, where a bundle is a GPU command buffer representation of GPU draws and state setting. This API allows for more efficient creation and management of bundles than can be achieved with the standard ExecuteBundle API." +kindex: +- ID3D12GraphicsCommandList::ExecuteIndirectBundleX +- ExecuteIndirectBundleX +ms.author: mattbron +ms.topic: reference +edited: 07/18/2019 +quality: good +ms.date: '08/01/2022' +permissioned-type: secret +--- + +# ID3D12GraphicsCommandList::ExecuteIndirectBundleX (Xbox One family) + +Indirectly executes a bundle from a buffer, where a bundle is a GPU command buffer representation of GPU draws and state setting. This API allows for more efficient creation and management of bundles than can be achieved with the standard [ExecuteBundle](https://learn.microsoft.com/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-executebundle) Direct3d 12 API. + +## Syntax + +```cpp +void ExecuteIndirectBundleX( + ID3D12Resource* pBundleBuffer, + UINT BundleBufferOffset, + UINT MaxSize, + ID3D12Resource* pSizeBuffer, + UINT SizeBufferOffset, + UINT PredicationBufferOffset +) +``` + +### Parameters + +*pBundleBuffer*   \_In\_ +Type: [ID3D12Resource](https://learn.microsoft.com/windows/win32/api/d3d12/nn-d3d12-id3d12resource)* + +Specifies a pointer to a buffer resource that contains bundle data. The buffer must have been created with the **D3D12XBOX_RESOURCE_FLAG_ALLOW_INDIRECT_BUFFER** attribute set; otherwise, the buffer must be located in **PAGE_GPU_EXECUTE** memory. + +*BundleBufferOffset*   \_In\_ +Type: UINT + +Offset, in bytes, from the start of the bundle buffer to the beginning of the bundle data. Must be a multiple of 4. + +*MaxSize*   \_In\_ +Type: UINT + +The bundle size can be specified in one of two ways: + +1. If *pSizeBuffer* is NULL, then *MaxSize* specifies the exact number of bytes of the bundle to be executed. + +2. If *pSizeBuffer* is not NULL, then *MaxSize* specifies the maximum number of bytes to be executed. If the size specified by *pSizeBuffer* exceeds *MaxSize* at the GPU execution time, then the GPU completely discards the execution of the bundle. This is useful in avoiding a GPU hang when the GPU is used to create the bundle and the data overflows its allotted budget. + +Bundles cannot exceed 4 MB in size. + +*pSizeBuffer*   \_In\_opt\_ +Type: ID3D12Resource* + +Specifies a buffer resource ([ID3D12Resource](https://learn.microsoft.com/windows/win32/api/d3d12/nn-d3d12-id3d12resource)) that contains a 32-bit size, in bytes. This is used for GPU-generated sizes. + +*SizeBufferOffset*   \_In\_ +Type: UINT + +Offset, in bytes, from the start of the size buffer to the 32-bit size, in bytes. + +*PredicationBufferOffset*   \_In\_ +Type: UINT + +Reserved for future use, and must be zero. + +### Return value + +Type: void + +## Remarks + +This API enables Build-Your-Own-Bundles functionality whereby a caller can create GPU command buffers by using their own CPU or GPU code, at runtime or offline. The bundle memory can also be explicitly managed. Both of these attributes contrast with the standard **ExecuteBundle** API, where the bundles can be created only at runtime, on the CPU, using D3D APIs, and with a significant object memory overhead. + +Build-Your-Own-Bundles functionality can contain all of the same kinds of draws and state changes as those that can be recorded into regular bundles. This set includes all high-frequency D3D APIs but no low-frequency D3D APIs, such as those for setting render targets or clears. The Xbox One's GPU command processor natively implements these APIs with very straightforward packet encodings. To create the command buffer data, use the D3D12XBOX_PACKET_* defines in the d3d12_x.h header in conjunction with the pipeline state object and Root Signature object introspection. Use the inlined functions in d3d12_x.h as a reference for how to do this; no additional documentation is provided beyond what is in the header. + +The packet data for a pipeline state object is good only during the lifetime of that pipeline state object. This means that if a bundle is created offline, then all [SetPipelineState](https://learn.microsoft.com/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-setpipelinestate) invocations within that bundle must be fixed up to reflect the versions of those pipeline state objects created at runtime, before the bundle can be executed by the GPU. Similarly, any pointer data recorded offline into a bundle (such as for descriptor tables) must be fixed up at runtime, before execution. + +**ExecuteIndirectBundleX** cannot itself be invoked from a bundle. + +Note the use of [NopX](../gc\reference\graphics\d3d12_x\interfaces\id3d12graphicscommandlist/id3d12graphicscommandlist.md) to add no-operation padding to a Command List. + +Beginning with the March 2024 GDK **ExecuteIndirectBundleX** can be used on Async Compute Command Lists on Xbox Series consoles. When used on Async Compute the count and bundle buffers must reside within the same ID3D12Resource; Additionally, the count value must be located 4 bytes before the bundle contents i.e. *BundleBufferOffset* must be equal to *SizeBufferOffset* plus 4 bytes. + +To execute a command list before it is closed, refer to [CreateCommandListX](../../id3d12device/methods/id3d12device_createcommandlistx.md) and [CloseBundleX](../gc\reference\graphics\d3d12_x\interfaces\id3d12graphicscommandlist/id3d12graphicscommandlist.md). + +## Requirements + +**Header:** d3d12_x.h + +***Library:** d3d12_x.lib + +**Supported platforms:** Xbox One family + +## See also + +[ID3D12GraphicsCommandList](./id3d12graphicscommandlist_dispatchx.md) +[ExecuteBundle](https://learn.microsoft.com/windows/win32/api/d3d12/nf-d3d12-id3d12graphicscommandlist-executebundle) + + diff --git a/docs/gdkx/hardware-overlays.md b/docs/gdkx/hardware-overlays.md new file mode 100644 index 0000000..5c7f3f8 --- /dev/null +++ b/docs/gdkx/hardware-overlays.md @@ -0,0 +1,244 @@ +--- +author: sdgmiller +title: "Hardware overlays and swap resources" +description: "Techniques for Game OS developers to efficiently target the Background and HUD planes." +ms.assetid: 10213ab7-0744-5c43-5ecb-be6fba078cb0 +kindex: +- Hardware overlays and swap resources +- overlay programming +- swap chains +- swap resources +- hdr +- display planes +- compositing +ms.topic: article +edited: 07/03/2019 +ms.date: '08/01/2022' +permissioned-type: private +--- + + +# Hardware overlays and swap resources + + +As a Game OS developer, you can use the following techniques to efficiently target the background and heads up display (HUD) planes. + + * [Overlay overview](#ID4EX) + * [Overlay implementation](#ID4EGC) + * [Performance metrics](#ID4EHE) + * [SDR and HDR](#ID4HDR) + + + + + + +## Overlay overview + + +In graphics programming, the terms *scaler* and *overlay* have been used interchangeably to indicate presentation layers that can be composited by dedicated display hardware. In this topic, we refer to multiplane overlays as simply overlays. If there's only one plane visible, it's usually referred to as the *primary*. + + +On Xbox One, there are three hardware overlay planes. Two of these planes are available for title use. A title might use these planes to separate out HUD and background content and have each rendered at different resolutions or updated at different frequencies. Alternatively, the two planes could be used in other ways than separating HUD and background. + + +| Overlay| Description| +| --- | --- | +| Background plane| The farthest back (in z-order) of the three overlay planes. This order can't be changed. This plane is dedicated to the Game OS. It's never used by the system OS. This plane is called the background plane because most of the time games use this plane for background game content (as opposed to HUD content). | +| HUD plane| The middle (in z-order) of the three overlay planes. This plane is mostly used by the Game OS, but this plane can also be used for video playback UI by the system OS. This plane is called the HUD plane because most of the time games use this plane for higher resolution but sparser HUD content. | +| System plane| The front-most (in z-order) of the three overlay planes. This plane is dedicated to the system OS. It's never used by the Game OS. | + + + + + + +## Overlay implementation + + +On Direct3D for Xbox One, multiplane overlay is implemented as follows. + + * When [PresentX](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/interfaces/id3d12commandqueue/methods/id3d12commandqueue_presentx) is called with two new swap resources (that is, not provided in the previous call) on scaler hardware, these resources are presented on the same vblank. + * The color content of the swap resources must be premultiplied alpha. + * There's a maximum 4:1 downscale and 1:16 upscale factor in both vertical and horizontal resolution. If the source presentation rectangle and destination presentation rectangle dimensions differ by more than this factor, the display behavior is undefined at runtime. In debug mode, the runtime checks for an error, and debug text notifies you that the acceptable upscale or downscale factors have been exceeded. + * Both the HUD and background layers can be explicitly enabled or disabled for display. When disabled (omitted from the PresentX call), the layer is black and with an alpha value of 0. + * For each [PresentX](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/interfaces/id3d12commandqueue/methods/id3d12commandqueue_presentx) call, a swap resource can change its source rectangle parameters. This source rectangle must be equal to or be fully within the boundaries of allocated memory. If the source rectangle violates these conditions, the display behavior is undefined in retail builds. In debug mode, the runtime checks for an error and debug text notifies you and specifies the particular condition violated. The dimensions of the source rectangle are specified by [D3D12_RECT](/windows/desktop/direct3d12/d3d12-rect). + * For each [PresentX](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/interfaces/id3d12commandqueue/methods/id3d12commandqueue_presentx) call, a swap resource can change its destination rectangle parameters. This destination rectangle is specified by using [D3D12XBOX_VIEW_RECT](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/structs/d3d12xbox_view_rect), representing the normalized coordinates of the destination rectangle. These floating-point coordinates must be in the range 0.0 to 1.0, inclusive. If these conditions aren't satisfied, the display behavior is undefined at runtime. In debug mode, the runtime checks for an error and debug text notifies you that you've specified an unacceptable (degenerate) destination rectangle or that the destination region is out of bounds. + * There can only be one overlay plane per process. At presentation time, you must specify the hardware plane each swap resource is targeted to (0 or 1 - background or HUD, based on plane parameter index). The runtime returns an error if a swap resource targets a plane that exceeds the available limit. + + +> [!NOTE] +> Unless multiple views are employed (that is, split-screen multiplayer), the destination rectangle should always be the same size as the game plane, whereas the source rectangle is relative to the swap resource. There's a fixed buffer limit for all 1080p swap resources of 16. A larger number of buffers can be used for jitter absorption. + + +The following sample code shows a Game OS app with a 1080p HUD plane and a 720p background plane, both being displayed at 1080p. + +```cpp + D3D12_HEAP_PROPERTIES heapProperties = {}; + heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT; + heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; + heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; + heapProperties.CreationNodeMask = D3D12XBOX_NODE_MASK; + heapProperties.VisibleNodeMask = D3D12XBOX_NODE_MASK; + + D3D12_RESOURCE_DESC swapResourceDesc = {}; + swapResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + swapResourceDesc.Alignment = 0; + swapResourceDesc.DepthOrArraySize = 1; + swapResourceDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + swapResourceDesc.MipLevels = 1; + swapResourceDesc.SampleDesc.Count = 1; + swapResourceDesc.SampleDesc.Quality = 0; + swapResourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + swapResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + + // Create the descriptor for the background plane. Note that it's a lower resolution than HUD. + swapResourceDesc.Width = 1280; + swapResourceDesc.Height = 720; + + ID3D12Resource* pSwapPool_BG[2]; // Use two buffers to enable the flip effect. + + // Create the swap resource pool for the background plane. + for (UINT i = 0; i < 2; ++i) + { + HRESULT hr = pd3dDevice->CreateCommittedResource( + &heapProperties, + D3D12_HEAP_FLAG_ALLOW_DISPLAY, + &swapResourceDesc, + D3D12_RESOURCE_STATE_PRESENT, + nullptr, + __uuidof(ID3D12Resource), + (void**)&pSwapPool_BG[i]); + + if (FAILED(hr)) + { + return hr; + } + } + + // Create the descriptor for the HUD plane. + swapResourceDesc.Width = 1920; + swapResourceDesc.Height = 1080; + + ID3D12Resource* pSwapPool_HUD[2]; // Use two buffers to enable the flip effect. + + // Create the swap resource pool for the HUD plane. + for (UINT i = 0; i < 2; ++i) + { + HRESULT hr = pd3dDevice->CreateCommittedResource( + &heapProperties, + D3D12_HEAP_FLAG_ALLOW_DISPLAY, + &swapResourceDesc, + D3D12_RESOURCE_STATE_PRESENT, + nullptr, + __uuidof(ID3D12Resource), + (void**)&pSwapPool_HUD[i]); + + if (FAILED(hr)) + { + return hr; + } + } + + // TODO: schedule the frame and wait on its origin event to obtain its identifying token + D3D12XBOX_FRAME_PIPELINE_TOKEN frameToken; + {...} + + // TODO: some rendering using the appropriate swap resources as the appropriate render targets + {...} + + // Prepare to present the swap resources to the display. + D3D12XBOX_PRESENT_PLANE_PARAMETERS arrayPlaneParams[2] = {}; + D3D12_RECT sourceRect; + D3D12XBOX_VIEW_RECT destRect; + + sourceRect.left = 0; + sourceRect.top = 0; + + destRect.left = 0.0f; + destRect.top = 0.0f; + destRect.right = 1.0f; + destRect.bottom = 1.0f; + + // Set up the present plane parameters for the background buffer. + // Note that we are outputting this plane at 1080p. + sourceRect.right = 1280; + sourceRect.bottom = 720; + + arrayPlaneParams[0].Token = token; + arrayPlaneParams[0].ResourceCount = 1; + arrayPlaneParams[0].ppResources = &pSwapPool_BG[frameIndex & 1]; + arrayPlaneParams[0].pSrcViewRects = &sourceRect; // Alternatively, nullptr can be specified to derive a full + // coverage source rect from the dimensions of pSwapPool_BG. + arrayPlaneParams[0].pDestPlacementBase = &destRect; // Alternatively, nullptr can be specified to derive a full + // coverage destination rect from the dimensions of the display. + arrayPlaneParams[0].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; + + // Set up the present parameters for the HUD buffer. + // Note that we are outputting this plane at 1080p. + sourceRect.right = 1920; + sourceRect.bottom = 1080; + + arrayPlaneParams[1].Token = token; + arrayPlaneParams[1].ResourceCount = 1; + arrayPlaneParams[1].ppResources = &pSwapPool_HUD[frameIndex & 1]; + arrayPlaneParams[1].pSrcViewRects = &sourceRect; // Alternatively, nullptr can be specified to derive a full + // coverage source rect from the dimensions of pSwapPool_BG. + arrayPlaneParams[1].pDestPlacementBase = &destRect; // Alternatively, nullptr can be specified to derive a full + // coverage destination rect from the dimensions of the display. + arrayPlaneParams[1].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; + + pd3dCommandQueue->PresentX( + 2, + arrayPlaneParams, + nullptr); +``` + + + + + +## Performance metrics + + +If you're having trouble hitting your target frame-rate at your target resolution on the GPU, consider dynamically resizing your resolution based on GPU load. The [ID3D12CommandQueue::PresentX](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/interfaces/id3d12commandqueue/methods/id3d12commandqueue_presentx) method allows the scaler resolution settings to be synchronously changed frame-to-frame. Remember that you can have your HUD on one overlay plane and your three-dimensional content on another overlay plane with a different resolution and blended by using per-pixel hardware. If your situation allows, you can also render one plane at a slower update rate by providing the same rendered swap resource in [D3D12XBOX_PRESENT_PLANE_PARAMETERS](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/structs/d3d12xbox_present_plane_parameters) over multiple calls to PresentX. + + +To get some metrics on performance, consider using the [GetFrameStatisticsX](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/interfaces/id3d12device/methods/id3d12device_getframestatisticsx) method to obtain timing and other pertinent information about frames that have already been displayed in real time. This information is useful because it allows the app to vary the content of frames rendered in the future to match the latency between calls to [PresentX](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/interfaces/id3d12commandqueue/methods/id3d12commandqueue_presentx) and when the presented frame is actually displayed for viewing. In addition, it's useful for the title to find out if it's queuing more frames than the rate that they can be displayed at, or if it's not generating frames quickly enough. + + + +## SDR and HDR + +The hardware display planes can be setup with different resolutions, and on {% term scarlett-family %} setup with different color spaces and gamma spaces are also supported. This enables compositing in SDR and HDR, and even a mix of SDR and HDR at the same time. + +For example, the title could render an HDR scene at 1440p at 60Hz in one display plane, while rendering its UI/HUD in the other display plane in SDR at 4K at 30Hz. + +Note that HDR compositing is only supported in the March 2024 GDK and onwards. When a title is in HDR mode and presents two swap buffers, the graphics driver needs to determine what those swap buffers should be used for. One scenario is that the second swap buffer contains the title’s own SDR tone mapped image for GameDVR. The other scenario is that it is meant for compositing. The color space information set in [D3D12XBOX_PRESENT_PLANE_PARAMETERS](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/structs/d3d12xbox_present_plane_parameters) is used by the graphics driver to determine which provided planes’ resources are to be selected for display presentation (HDR) and which are to be used for GameDVR encoding (SDR). When compositing in HDR, the system level auto tone mapping will be used to generate an SDR image for GameDVR. + +HDR compositing is done using 200 nits as paper white for the UI. That is, a value of 1.0 in UI will be displayed at 200 nits. Scene values in the display plane with the scene will have to be normalized as usual, therefore a value of 1.0 in the scene display plane will be displayed at 10,000 nits. + +For SDR compositing, the scene must be in display plane 0 and the UI/HUD in display plane 1. But, for HDR, the scene must be in display plane 1 and the UI/HUD in display plane 0. + +Below are two examples of how to setup [D3D12XBOX_PRESENT_PLANE_PARAMETERS](/gaming/xbox-nda-docs/_content/gc/reference/graphics/d3d12_x/structs/d3d12xbox_present_plane_parameters) + +Example: SDR Compositing + +```cpp + planeParameters[0].ppResources = sdrSceneSwapBuffer; + planeParameters[0].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; + planeParameters[1].ppResources = uiSwapBuffer; + planeParameters[1].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; +``` + +Example: HDR Compositing with the HDR scene in linear P3 color space and the UI in sRGB Rec.709 color space + +```cpp + planeParameters[0].ppResources = uiSwapBuffer; + planeParameters[0].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; + planeParameters[1].ppResources = hdrSceneSwapBuffer; + planeParameters[1].ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_D65P3; +``` + + + diff --git a/docs/gdkx/id3d12commandqueue_presentx.md b/docs/gdkx/id3d12commandqueue_presentx.md new file mode 100644 index 0000000..454bd2d --- /dev/null +++ b/docs/gdkx/id3d12commandqueue_presentx.md @@ -0,0 +1,87 @@ +--- +author: sdgmiller +title: "PresentX (Xbox One family)" +description: "Presents a set of resources for display." +kindex: +- PresentX +- ID3D12CommandQueue::PresentX +ms.author: mattbron +ms.topic: reference +edited: 07/30/2019 +quality: good +ms.date: '08/01/2022' +permissioned-type: secret +--- + +# ID3D12CommandQueue::PresentX (Xbox One family) + +Presents a set of resources for display. + +## Syntax + +```cpp +HRESULT PresentX( + UINT PlaneCount, + const D3D12XBOX_PRESENT_PLANE_PARAMETERS* pPlaneParameters, + const D3D12XBOX_PRESENT_PARAMETERS* pPresentParameters) +``` + +### Parameters + +*PlaneCount*   \_In\_range\_(1, D3D12XBOX_PRESENT_PLANES_MAX) +Type: UINT + +The count of planes to present. Multiple planes can consist of a background plane with overlays and/or pairs of standard and High Dynamic Range compositions of the frame. Use a plane count of 0 to swap the display to null, which will set the display color to black. Xbox Series X|S allows blending of planes larger than 1920 x 1080, both of which could be High Dynamic Range. + +*pPlaneParameters*   \_In\_reads\_(PlaneCount) +Type: const [D3D12XBOX_PRESENT_PLANE_PARAMETERS](../../../structs/d3d12xbox_present_plane_parameters.md)* + +Pointer to the first element in an array of parameters that are used to control the presentation of each provided plane. Arrange the array by Z order: back to front. Set the elements by closest proximity and then by color-space (HDR-SDR) pairs. + +*pPresentParameters*   \_In\_opt\_ +Type: const [D3D12XBOX_PRESENT_PARAMETERS](../../../structs/d3d12xbox_present_parameters.md)* + +Optional. A pointer to a set of parameters used to control the presentation. + +### Return value + +Type: HRESULT + +HRESULT success or error code. + +Returns S_OK if the specified swap resources have been successfully queued for presentation. + +Returns ERROR_WAS_STILL_DRAWING if [D3D12XBOX_PRESENT_FLAG_DO_NOT_WAIT](../../../enums/d3d12xbox_present_flags.md) is specified and one or more of the specified *ppResources* of *pPlaneParameters* are currently displayed or queued for presentation. + +Returns E_INVALIDARG on invalid parameters or invalid composition of the presentation. + +Returns D3DERR_DEVICEREMOVED if the GPU becomes unresponsive prior to the call to **PresentX** + +## Remarks + +Resources included in the *ppResources* arrays contained within *pPlaneParameters* serve as a replacement for legacy swap chains and must be created with support for being flipped to a display. To enable support for flipping, call [CreateCommittedResource](https://learn.microsoft.com/windows/win32/api/d3d12/nf-d3d12-id3d12device-createcommittedresource) and set the **D3D12_HEAP_FLAG_ALLOW_DISPLAY** flag ([D3D12_HEAP_FLAGS](../../../enums/d3d12_heap_flags.md)) in the *pDesc* parameter. Resources created without an underlying heap are not permitted yet. + +Swap chains have evolved into a user-managed collection of display-able resources; however, due to TLB limitations, a limited number of this type of resources can be instantiated at one time. A display-able resource can't be released to the point of deallocation if it's currently being scanned out by a display or queued for presentation. You must first flip the display to another set of resources or to null (if the application is shut down). To perform a null presentation, call **PresentX(0, nullptr, nullptr);**. + +With *ppResources* replacing swap chains, the color space of a swap resource is now declared as part of the plane parameters included in *pPlaneParameters*, and automatic tone-mapping for GameDVR is selected for a resource through the [D3D12XBOX_RESOURCE_FLAG_ALLOW_AUTOMATIC_GAMEDVR_TONE_MAP](../../../enums/d3d12_resource_flags.md) resource-creation flag, while incurring additional heap storage and per-Present GPU cost. Xbox Series X|S adds two more swap resource formats **DXGI_FORMAT_R9G9B9E5_SHAREDEXP** and **DXGI_FORMAT_A8_UNORM**. A **DXGI_FORMAT_A8_UNORM** swap resource should always be paired with a **DXGI_FORMAT_R9G9B9E5_SHAREDEXP** swap resource. It serves as the alpha channel for the RGBE resource, when an alpha channel is desired (for instance, when blending more than one plane). Xbox Series X|S also allows swap resources to be Delta Color Compressed through the [D3D12XBOX_RESOURCE_FLAG_ALLOW_DCC](../../../enums/d3d12_resource_flags.md) resource-creation flag. + +Resources might not be presented if identification of the frames used in their production, or at least used in the initiation of their construction, is not provided. This is necessary for the correlation of presentation statistics to individual frames, for measuring full-frame pipeline latency from the origin, and for input sampling to the display. Identification is performed through the *Token* member of the *pPlaneParameters* parameters, where different [D3D12XBOX_FRAME_PIPELINE_TOKEN](../../../enums/d3d12xbox_frame_pipeline_token.md) values can be specified for each composition plane (background and overlay), given the potential for different plane presentation frequencies and thus different basis frames. The pipeline token should be included redundantly for planes that are all sourced from the same frame. + +Frames and their associated swap resources must be presented in the order they were produced. A stream of frame pipeline tokens that originate from [WaitFrameEventX](../../id3d12device/methods/id3d12device_waitframeeventx.md) are terminated through *PresentX*, with no frame drops or re-ordering permitted. The contents of one composition plane may be persisted on the display while one or more other planes are being updated; to do this, pass the same resource and frame token as those provided for the plane in the previous call to *PresentX*. + +To remove a composition plane established during a series of calls to *PresentX*, omit the plane's resources and tokens from the array pointed to by *pPlaneParameters* on a subsequent call to *PresentX*. + +Presented swap resources are flipped to the display at the time of their scheduled VBlank; this assumes that the *PresentX* call is made and processed within the threshold of the target declared in *ImmediateThresholdPercent* of *pPresentParameters*. If **PresentX** misses the VBlank but arrives within the threshold, then it will be flipped to the display immediately. This threshold is based on a percentage of the display scan-out time (VBlank to VBlank), not on a percentage of the defined frame interval. Also, unlike immediate presentation, arranged through the use of the [D3D12XBOX_PRESENT_FLAG_IMMEDIATE](../../../enums/d3d12xbox_present_flags.md) flag in *pPresentParameters* (which immediately triggers the origin of the next frame), immediate flips that are based on the threshold will signal the subsequent frame origin only if that origin's time has already passed. + +## Requirements + +**Header:** d3d12_x.h + +**Library:** d3d12_x.lib + +**Supported platforms:** Xbox One family + +## See also + +[ID3D12CommandQueue](./id3d12commandqueue_beginevent_public.md) + diff --git a/docs/gdkx/pix-gpu-executeindirect.md b/docs/gdkx/pix-gpu-executeindirect.md new file mode 100644 index 0000000..14933a6 --- /dev/null +++ b/docs/gdkx/pix-gpu-executeindirect.md @@ -0,0 +1,40 @@ +--- +author: coleb +title: "PIX ExecuteIndirect Support overview" +description: "Description of PIX ExecuteIndirect support." +kindex: +- PIX ExecuteIndirect +- PIX, ExecuteIndirect +- ExecuteIndirect (PIX) +ms.author: coleb +ms.topic: article +edited: 05/03/2022 +ms.date: '08/01/2022' +permissioned-type: private +--- + +# PIX ExecuteIndirect Analysis Support + +Analysis of ExecuteIndirect calls in PIX poses challenges. When an ExecuteIndirect argument buffer is GPU generated, the child draws/dispatches of the ExecuteIndirect may have a non-deterministic order. This can make both performance analysis and debugging operations in PIX very difficult, as the content of an individual child index be completely different each time it is evaluated. + +## ExecuteIndirect on Xbox Series X|S + +On Xbox Series X|S, ExecuteIndirect analysis support has been updated to significantly improve the PIX user experience. For an ExecuteIndirect call which may result in more than one draw/dispatch, or which has an indirect specification of non draw/dispatch parameters (setting root signature parameters, vertex buffers, index buffers, pipeline state objects, etc), during analysis PIX will "lock" the GPU generated arguments and other GPU generated dependencies consumed by the ExecuteIndirect to a single copy which is generated when analysis starts, while viewing a child draw/dispatch of the ExecuteIndirect call. This allows debugging operations, such as viewing [pipeline](../tools\tools-console\pix/pix.md) bindings, to be consistent and not constantly vary due to non-determinism. + +However, this "lock" of the GPU generated arguments has a significant impact on the GPU performance. For this reason, performance information such as [counters](../tools\tools-console\pix/pix.md) and [Dr. PIX](../tools\tools-console\pix/pix.md) results are not available for individual child indices of these "complex" ExecuteIndirect calls. Performance information is available for the parent ExecuteIndirect, which is selectable by its own unique Global ID in PIX. + +This memory "lock" only applies to the children of an ExecuteIndirect call. For example, if the ExecuteIndirect parent is selected, the entire argument buffer used by all of its children may be viewed in the pipeline view. The content of this buffer may change due to non-determinism of the GPU generated results if refreshed. + +## ExecuteIndirect on prior platforms + +On consoles prior to Xbox Series X|S, PIX does not support the "lock" for ExecuteIndirect arguments described above. For these platforms, an option exists in PIX Setting to "force collapse" all ExecuteIndirect calls, effectively treating the ExecuteIndirect as a single draw/dispatch. + +## See also + +[Pipeline View](../tools\tools-console\pix/pix.md) + +[PIX Counters](../tools\tools-console\pix/pix.md) + +[Dr. PIX](../tools\tools-console\pix/pix.md) + + diff --git a/docs/gdkx/pix3_xbox.h b/docs/gdkx/pix3_xbox.h new file mode 100644 index 0000000..74a2f13 --- /dev/null +++ b/docs/gdkx/pix3_xbox.h @@ -0,0 +1,306 @@ +/*==========================================================================; + * + * Copyright (C) Microsoft Corporation. All Rights Reserved. + * + * File: PIX3_xbox.h + * Content: PIX include file + * Don't include this file directly - use pix3.h + * + ****************************************************************************/ + +#pragma once + +#ifndef _PIX3_XBOX_H_ +#define _PIX3_XBOX_H_ + +#ifdef USE_PIX_MEMORY_TRACE + #include "PIXMemory.h" +#endif + +#include + +// PIXEventsThreadInfo is defined in PIXEventsCommon.h +struct PIXEventsThreadInfo; + +static const UINT64 PIXEventsThreadInfoOffset1 = 48; +static const UINT64 PIXEventsThreadInfoOffset2 = 128; + +#if defined(__d3d12_xs_h__) +#define USE_PIX_RETAIL +#endif + +__forceinline PIXEventsThreadInfo* PIXGetThreadInfo() +{ +#ifdef _X86_ + return nullptr; // Not supported +#else + return (PIXEventsThreadInfo*)(__readgsqword(PIXEventsThreadInfoOffset1) + PIXEventsThreadInfoOffset2); +#endif +} + +#if defined (USE_PIX) +inline void PIXNotifyWakeFromFenceSignal(_In_ HANDLE) +{ + // This is currently not implemented on XBOX +} +extern "C" HRESULT WINAPI PIXSetLinkWorkerThreadAffinityMask(DWORD_PTR); +#else +//extern "C" HRESULT WINAPI PIXSetLinkWorkerThreadAffinityMask(DWORD_PTR) { return S_OK; } +#endif + +// These values denote PIX marker event data that was created by the WinPixEventRuntime. +// In early 2023 we revised the PIX marker format and defined a new version number. +#define WINPIX_EVENT_PIX3BLOB_VERSION 2 +#define WINPIX_EVENT_PIX3BLOB_V2 6345127 // A number that other applications are unlikely to have used before + +#define D3D12_EVENT_METADATA 0 //nothing +#define D3D12_EVENT_METADATA_LEGACY 0 +#define PIXGetTimestampCounter() __rdtsc() + +#if defined(__d3d12_xs_h__) || defined(__d3d12_x_h__) + +// PIX specific error codes for programmatic captures +#define PIX_ERROR_USER_CANCELED 0x8abc0072 // User canceled this request +#define PIX_ERROR_CAPTURE_TIMEOUT_WAITING_FOR_GPU_WORK 0x8abc01f5 // Timeout waiting for GPU work to complete. +#define PIX_ERROR_CAPTURE_NO_WRITEBACK_SPACE 0x8abc01f6 // Insufficent ring space for writeback. +#define PIX_ERROR_CAPTURE_OUT_OF_TOOLING_MEMORY 0x8abc01fb // PIX ran out of tooling memory while a capture was in progress. Increase MaximumToolingMemorySizeMb parameter or adjust capture options. +#define PIX_ERROR_CAPTURE_OUT_OF_RESERVED_TOOLING_MEMORY 0x8abc01fc // PIX couldn't reserve tooling memory. Decrease MaximumToolingMemorySizeMb parameter. + +inline void PIXInsertGPUMarkerOnContextForBeginEvent(_In_ ID3D12GraphicsCommandList* commandList, UINT8 eventType, _In_reads_bytes_(size) void* data, UINT size) +{ + commandList->InsertGpuMarker(eventType, data, size); +} + +inline void PIXInsertGPUMarkerOnContextForSetMarker(_In_ ID3D12GraphicsCommandList* commandList, UINT8 eventType, _In_reads_bytes_(size) void* data, UINT size) +{ + commandList->InsertGpuMarker(eventType, data, size); +} + +inline void PIXInsertGPUMarkerOnContextForEndEvent(_In_ ID3D12GraphicsCommandList* commandList, UINT8 eventType, _In_reads_bytes_(size) void* data, UINT size) +{ + commandList->InsertGpuMarker(eventType, data, size); +} + +inline void PIXInsertGPUMarkerOnContextForBeginEvent(_In_ ID3D12CommandQueue* commandQueue, UINT8 eventType, _In_reads_bytes_(size) void* data, UINT size) +{ + commandQueue->InsertGpuMarker(eventType, data, size); +} + +inline void PIXInsertGPUMarkerOnContextForSetMarker(_In_ ID3D12CommandQueue* commandQueue, UINT8 eventType, _In_reads_bytes_(size) void* data, UINT size) +{ + commandQueue->InsertGpuMarker(eventType, data, size); +} + +inline void PIXInsertGPUMarkerOnContextForEndEvent(_In_ ID3D12CommandQueue* commandQueue, UINT8 eventType, _In_reads_bytes_(size) void* data, UINT size) +{ + commandQueue->InsertGpuMarker(eventType, data, size); +} + +inline void PIXInsertTimingMarkerOnContext(_In_ ID3D12GraphicsCommandList* commandList, UINT8 eventType) +{ + commandList->InsertTimingMarker(eventType); +} + +inline void PIXInsertTimingMarkerOnContext(_In_ ID3D12CommandQueue* commandQueue, UINT8 eventType) +{ + commandQueue->InsertTimingMarker(eventType); +} + +inline void PIXSetGPUMarkerOnContext(_In_ ID3D12XboxDmaCommandList* commandList, _In_reads_bytes_(size) void* data, UINT size) +{ + commandList->SetMarker(D3D12_EVENT_METADATA, data, size); +} + +inline void PIXBeginGPUEventOnContext(_In_ ID3D12XboxDmaCommandList* commandList, _In_reads_bytes_(size) void* data, UINT size) +{ + commandList->BeginEvent(D3D12_EVENT_METADATA, data, size); +} + +inline void PIXEndGPUEventOnContext(_In_ ID3D12XboxDmaCommandList* commandList) +{ + commandList->EndEvent(); +} + +inline void PIXInsertGPUMarkerOnContextForBeginEvent(_In_ ID3D12XboxDmaCommandList* commandList, UINT8 eventType, _In_reads_bytes_(size) void* data, UINT size) +{ + commandList->InsertGpuMarker(eventType, data, size); +} + +inline void PIXInsertGPUMarkerOnContextForSetMarker(_In_ ID3D12XboxDmaCommandList* commandList, UINT8 eventType, _In_reads_bytes_(size) void* data, UINT size) +{ + commandList->InsertGpuMarker(eventType, data, size); +} + +inline void PIXInsertGPUMarkerOnContextForEndEvent(_In_ ID3D12XboxDmaCommandList* commandList, UINT8 eventType, _In_reads_bytes_(size) void* data, UINT size) +{ + commandList->InsertGpuMarker(eventType, data, size); +} + +inline void PIXInsertTimingMarkerOnContext(_In_ ID3D12XboxDmaCommandList* commandList, UINT8 eventType) +{ + commandList->InsertTimingMarker(eventType); +} + +#endif //__d3d12_xs_h__ or __d3d12_x_h__ + +// Performance counter configuration and value retrieval. +// +// The Configure PMC calls will tell the ERA OS to permit the rdpmc instruction to execute (from code use the function/macro below) +// so that counter values can be retrieved, and also set which event each counter will count. Pass an +// index from the following tables. These counters correspond to the ones show in the system monitor in PIX. +// When a title configures the PMCs, Sysmon stops recording and manipulating the counters. +// The correct PMC to read for each event corresponds with the event index number +// +// Configuration of performance counters inside the cores. +// The function sets the PMC events to be the same across all 6 available cores. Note that PMCs count +// independently on each core; you cannot difference PMCs on different cores and expect coherent results. +// +// 0 Reserved +// 1 RetiredSseAvx The number of SSE/AVX operations retired +// 2 DCacheAccesses The number of accesses to the L1 data cache for load and store references +// 3 DCacheMisses The number of L1 data cache references which miss the data cache +// 4 DCacheRefills The number of L1 data cache refills satisfied from the L2 cache (and/or the northbridge) from uncacheable memory +// 5 L1DTLBMissL2DTLBHit The number of L1 data cache accesses that miss in the L1 DTLB and hit in the L2 DTLB +// 6 DtlbMiss The number of L1 data cache accesses that miss in both the L1 and L2 DTLBs +// 7 L1DtlbHit The number of L1 data cache accesses that hit in the L1 DTLB +// 8 L1ITLBMissL2ITLBHit The number of instruction fetches that miss in the L1 ITLB but hit in the L2 ITLB +// 9 ItlbMiss The number of instruction fetches that miss in the 4K ITLB and 2M ITLB +// 10 ItlbInstructionFetchHits The number of instruction fetches that hit in the 4K ITLB and 2M ITLB +// 11 MisalignedAccess The number of L1 data cache accesses that are misaligned. Misaligned accesses incur at least an extra cache access and an extra cycle of latency on reads +// 12 IneffectiveSWPrefetches The number of software prefetches that do not cause an actual L1 data cache refill +// 13 CpuClkNotHalted The number of clocks that the CPU is not in a halted state +// 14 RetiredInstructions The number of instructions retired (execution completed and architectural state updated). This count includes exceptions and interrupts. +// 15 BranchInstructions The number of branch instructions retired. This includes all types of architectural control flow changes, including exceptions and interrupts. +// 16 MispredictedBranch The number of branch instructions retired, of any type, that were not correctly predicted in either target or direction. This includes those for which prediction is not attempted (far control transfers, exceptions and interrupts), and excludes resyncs. , +// 17 RetiredTakenBranch The number of taken branches that were retired. This includes all types of architectural control flow changes, including exceptions and interrupts, and excludes resyncs. +// 18 RetiredFarSyscall The number of far syscalls retired +// 19 RetiredNearReturns The number of near return instructions retired +// 20 RetiredReturnsMispredicted A near return instruction was retired that mispredicted in either target or direction +// 21 MispredictedTakenBranch A taken branch instruction was retired that mispredicted in target address (but not in direction) +// 22 (Depricated) MmxFPInstructions A floating point (x87, MMX, or SSE) instruction was retired +// 23 (Deprecated - Use RetiredMmxInstructions instead) RetiredFPInstructions The number of SSE/AVX operations retired +// 24 RetiredMmxInstructions The number of MMX operations retired +// 25 (Depricated) RetiredSseInstructions The number of SSE operations retired +// 26 InstructionFetchStalls The number cycles that the instruction fetch engine is stalled +// 27 DataCachePrefetches L1 data cache prefetches +// 28 DataCacheReadSize The number of L1 data cache reads +// 29 DataCacheWriteSize The number of L1 data cache writes +// 30 ITLBReloadStalls The number of cycles when the fetch engine is stalled for an ITLB reload +extern "C" +HRESULT WINAPI +ConfigurePMCs(unsigned int eventIndex0, unsigned int eventIndex1, unsigned int eventIndex2, unsigned int eventIndex3); + +// +// !!! NOTE: This API is not implemented on Scarlett. +// +// Configuration of performance counters inside the north bridge +// The north bridge has 4 performance counters which can count events. NB PMC values can be read +// from any core. North bridge memory transactions are 64 bytes. +// +// Events marked with * are recorded from the dram controllers (DCTs). Set eventIndex6 only +// when configuring these events since the same event need to be set for each dram controller +// On Durango, we have 4 dram controllers and 4 counters, so you sum PMC6-PMC9 to get the +// total result. +// Eg: total memory traffic for NBAllReadWrites = (PCM6+PMC7+PCM8+PMC9) * 64 +// On Scorpio, we have 12 dram controllers and 4 counters so we only +// count traffic on every 3rd DCT. Memory traffic is mostly symmetric so it reasonable to +// assume that the total number of events is three times the sum PMC6-PMC9. +// Eg: total memory traffic for NBAllReadWrites = (PCM6+PMC7+PCM8+PMC9) * 3 * 64 +// +// 0 Reserved +// 1 NBGarlicReads* The number of garlic bus reads +// 2 NBGarlicWrites* The number of garlic bus writes +// 3 NBGarlicReadsWrites* The number of garlic bus reads and writes +// 4 NBOnionReads* The number of onion bus reads +// 5 NBOnionWrites* The number of onion bus writes +// 6 NBOnionReadsWrites* The number of onion bus reads and write +// 7 NBAllReadWrites* The number of all NB reads and writes +// 8 NBCPUToMemory The number of CPU transactions to memory +// 9 NBIOToMemory The number of IO transactions to memory +extern "C" +HRESULT WINAPI +ConfigureNBPMCs(unsigned int eventIndex6, unsigned int eventIndex7, unsigned int eventIndex8, unsigned int eventIndex9); + +// Configuration of performance counters inside the L2 caches. +// There are two L2 caches and each L2 cache has 4 performance counters which can count events. +// ConfigureL2IPMCs configures the events of both L2s to be the same. +// The first L2 is tied to cores 0-3. The second is tied to cores 4-7. Events for a specific L2 must be read from a core tired to the specific L2. +// L2 transactions are 64 bytes. +// +// 0 Reserved +// 1 L2MissICFill The number of IC requests that miss the L2 +// 2 L2MissDCFill The number of DC requests that miss the L2 +// 3 L2MissPrefetchFill The number of prefetch requests that miss the L2 +// 4 L2MissAll The total number of L2 Misses +// 5 L2Writeback The number of L2 clean and dirty writebacks +// 6 L2CleanWriteback The number of L2 clean writebacks +// 7 L2Fill The number of L2 Fills +// 8 L2FillWriteback The total number of L2 fills and writebacks +// +// NOTE: On Scarlett, this configures the L3 cache counters. +// The L3 cache uses a different counter set: +// 0 Reserved +// 1 L3MissAll The total number of L3 misses +extern "C" +HRESULT WINAPI +ConfigureL3PMCs(unsigned int eventIndex10, unsigned int eventIndex11, unsigned int eventIndex12, unsigned int eventIndex13); + +// PLEASE READ CAREFULLY! +// +// Retrieving the counter value is wrapped in a try/except block for a good reason. +// The __readpmc() intrinsic emits the rdpmc instruction. On any Xbox One not provisioned as a +// dev kit, this instruction will cause a hard crash unless the exception is handled. +// On a dev kit, rdpmc will cause a hard crash unless the exception is handled OR you +// have called the ConfigurePMCs function below first, which permits using rdpmc safely. +// +// If you choose to take the inline function / macro below to pieces for your own purposes +// and just use __readpmc directly in your own code, remember three things: +// - You are risking a hard crash if you leave rdpmc in your code at cert / release time +// - The code generation for the try/except is far less worrying than you might imagine +// - It will be a Very Good Idea to have an automated mechanism for removing rdpmc from your code +// +// Let's be careful out there. +inline void GetPMCValue(UINT32 index, UINT64* value) +{ + __try + { + *value = __readpmc(index); + } + __except(EXCEPTION_EXECUTE_HANDLER) + { + // Either this is not a dev kit, or we have not yet called ConfigurePMCs to permit __readpmc use + *value = 0; + } +} + +typedef struct _PIXPowerMetrics { + float GpuAvgPowerLoadPct; + float reserved[3]; +} PIXPowerMetrics, *PPIXPowerMetrics; + +extern "C" HRESULT WINAPI PIXGetPowerMetrics(PPIXPowerMetrics metrics); + +enum PIXPerformanceFlag : UINT64 +{ + InMenu = 0x1, + InLevel = 0x2, + InLobby = 0x4, + InCredits = 0x8, + Loading = 0x10, + Pause = 0x20, + Constrained = 0x40, + NetworkUpload = 0x80, + NetworkDownload = 0x100, +}; + +struct PIXPerformanceClass +{ + PIXPerformanceFlag Flags : 48; // 48-bits for flags + UINT64 UserData : 16; // 16-bits for caller defined modifiers (i.e. a counter) +}; + +typedef struct PIXPerformanceClass *PPIXPerformanceClass; + +extern "C" void WINAPI PIXSetPerformanceContext(PPIXPerformanceClass performanceClass, PCSTR dimensions[], ULONG32 countOfDimensions); + +#endif //_PIX3_XBOX_H_ diff --git a/docs/gdkx/xdxcapi.h b/docs/gdkx/xdxcapi.h new file mode 100644 index 0000000..a3a6050 --- /dev/null +++ b/docs/gdkx/xdxcapi.h @@ -0,0 +1,92 @@ +/* + * Copyright © 2025 Microsoft Corporation + * + * SPDX-License-Identifier: MIT + */ + +#ifndef XDXCAPI_H +#define XDXCAPI_H + +#include +#include +#include +#include + +#include "aco_xbox.h" + +#ifdef __cplusplus +extern "C" { +#endif + +DEFINE_GUID(IID_IXdxcCompiler3, + 0xdfa0cafb, 0x039a, 0x4ff4, 0x84, 0x79, 0xa7, 0xe7, 0x4c, 0xc2, 0xb1, 0xdb); + +DEFINE_GUID(IID_IXdxcResult, + 0x04b4ab5f, 0xbbd7, 0x49bf, 0x91, 0xf5, 0x9d, 0x97, 0xec, 0xba, 0x57, 0x43); + +DEFINE_GUID(CLSID_XdxcContainerInspector, + 0x7966321c, 0x50b4, 0x4161, 0xa4, 0xb4, 0x40, 0x9c, 0xc9, 0x4f, 0x2b, 0x8d); +DEFINE_GUID(IID_IXdxcContainerInspector, + 0x8bcaac90, 0x00a7, 0x4d0b, 0xae, 0x91, 0x81, 0x80, 0x2b, 0x01, 0xf0, 0xe5); + +DEFINE_GUID(CLSID_XdxcContainerEditor, + 0x0265e831, 0x619b, 0x42b0, 0x91, 0x79, 0xbb, 0x50, 0x4f, 0x2e, 0xa1, 0x78); +DEFINE_GUID(IID_IXdxcContainerEditor, + 0xd3f2685f, 0x8f92, 0x42a7, 0x9d, 0xe5, 0x2b, 0xd7, 0x8c, 0x10, 0x2e, 0xe4); + +typedef struct XDXC_COMPUTE_INSPECT_RESULT { + UINT32 fileSize; + UINT32 acccSize; + UINT32 acccOffset; + UINT32 packetOffset, packetSize; + UINT32 metadataOffset, metadataSize; + UINT32 csIsaOffset, csIsaSize; + UINT32 csMetaOffset, csMetaSize; +} XDXC_COMPUTE_INSPECT_RESULT; + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#ifdef __cplusplus + +struct DECLSPEC_UUID("dfa0cafb-039a-4ff4-8479-a7e74cc2b1db") +IXdxcCompiler3 : public IDxcCompiler3 { + virtual HRESULT STDMETHODCALLTYPE SetCompileOptions( + const aco_compile_options *pOpts) = 0; +}; + +struct DECLSPEC_UUID("04b4ab5f-bbd7-49bf-91f5-9d97ecba5743") +IXdxcResult : public IDxcResult { + virtual HRESULT STDMETHODCALLTYPE GetRawDxil(IDxcBlob **ppRawDxil) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetCookPayload( + IDxcBlob **ppPayload, UINT32 *pFourCC) = 0; +}; + +struct DECLSPEC_UUID("8bcaac90-00a7-4d0b-ae91-81802b01f0e5") +IXdxcContainerInspector : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE InspectComputeContainer( + const void *pContainer, UINT32 cbContainer, + XDXC_COMPUTE_INSPECT_RESULT *pOut) = 0; +}; + +struct DECLSPEC_UUID("d3f2685f-8f92-42a7-9de5-2bd78c102ee4") +IXdxcContainerEditor : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE EnumParts( + const void *pContainer, UINT32 cbContainer, + aco_dxbc_part_info *pParts, UINT32 maxParts, UINT32 *pCount) = 0; + + virtual HRESULT STDMETHODCALLTYPE RewriteParts( + const void *pContainer, UINT32 cbContainer, + const UINT32 *pFourccs, UINT32 numFourccs, BOOL keepOnly, + IDxcBlob **ppOut) = 0; + + virtual HRESULT STDMETHODCALLTYPE StripDxilBitcode( + const void *pContainer, UINT32 cbContainer, + IDxcBlob **ppOut) = 0; +}; + +#endif /* __cplusplus */ + +#endif /* XDXCAPI_H */ diff --git a/docs/gdkx/xg_xs.h b/docs/gdkx/xg_xs.h new file mode 100644 index 0000000..9cd1a69 --- /dev/null +++ b/docs/gdkx/xg_xs.h @@ -0,0 +1,1182 @@ +//------------------------------------------------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All Rights Reserved. +// +// XG library for Xbox Next. +// +// XG is an auxiliary graphics library that is used for preparing resources and other +// graphics-related tasks that are performed outside the bounds of the Direct3D runtime +// interfaces. +// + +#pragma once + +#pragma warning(push) + +#pragma warning (disable: 4619 4616 5204 4820) + +#include + +typedef UINT64 XG_GPU_VIRTUAL_ADDRESS; + +//-------------------------------------------------------------------------------------------------- +// XG GPU page size represents a 64KB page. +#define XG_GPU_PAGE_SIZE_SHIFT (16) +#define XG_GPU_PAGE_SIZE_BYTES (1 << XG_GPU_PAGE_SIZE_SHIFT) +#define XG_GPU_PAGE_SIZE_MASK (XG_GPU_PAGE_SIZE_BYTES - 1) + +enum XG_SWIZZLE_MODE +{ + XG_SWIZZLE_MODE_LINEAR = 0x00000000, + XG_SWIZZLE_MODE_256B_S = 0x00000001, + XG_SWIZZLE_MODE_256B_D = 0x00000002, + XG_SWIZZLE_MODE_256B_R = 0x00000003, + XG_SWIZZLE_MODE_4KB_Z = 0x00000004, + XG_SWIZZLE_MODE_4KB_S = 0x00000005, + XG_SWIZZLE_MODE_4KB_D = 0x00000006, + XG_SWIZZLE_MODE_4KB_R = 0x00000007, + XG_SWIZZLE_MODE_64KB_Z = 0x00000008, + XG_SWIZZLE_MODE_64KB_S = 0x00000009, + XG_SWIZZLE_MODE_64KB_D = 0x0000000a, + XG_SWIZZLE_MODE_64KB_R = 0x0000000b, + XG_SWIZZLE_MODE_VAR_Z = 0x0000000c, + XG_SWIZZLE_MODE_VAR_S = 0x0000000d, + XG_SWIZZLE_MODE_VAR_D = 0x0000000e, + XG_SWIZZLE_MODE_VAR_R = 0x0000000f, + XG_SWIZZLE_MODE_64KB_Z_T = 0x00000010, + XG_SWIZZLE_MODE_64KB_S_T = 0x00000011, + XG_SWIZZLE_MODE_64KB_D_T = 0x00000012, + XG_SWIZZLE_MODE_64KB_R_T = 0x00000013, + XG_SWIZZLE_MODE_4KB_Z_X = 0x00000014, + XG_SWIZZLE_MODE_4KB_S_X = 0x00000015, + XG_SWIZZLE_MODE_4KB_D_X = 0x00000016, + XG_SWIZZLE_MODE_4KB_R_X = 0x00000017, + XG_SWIZZLE_MODE_64KB_Z_X = 0x00000018, + XG_SWIZZLE_MODE_64KB_S_X = 0x00000019, + XG_SWIZZLE_MODE_64KB_D_X = 0x0000001a, + XG_SWIZZLE_MODE_64KB_R_X = 0x0000001b, + XG_SWIZZLE_MODE_VAR_Z_X = 0x0000001c, + XG_SWIZZLE_MODE_VAR_S_X = 0x0000001d, + XG_SWIZZLE_MODE_VAR_D_X = 0x0000001e, + XG_SWIZZLE_MODE_VAR_R_X = 0x0000001f, + XG_SWIZZLE_MODE_INVALID = 0xffffffff, +}; + +typedef enum XG_TEXTURE_LAYOUT +{ + XG_TEXTURE_LAYOUT_UNKNOWN = 0, + XG_TEXTURE_LAYOUT_DEFAULT = XG_TEXTURE_LAYOUT_UNKNOWN, + XG_TEXTURE_LAYOUT_ROW_MAJOR = 1, + XG_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE = 2, + XG_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE = 3, + + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR = (0x100 | XG_SWIZZLE_MODE_LINEAR ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_256B_S = (0x100 | XG_SWIZZLE_MODE_256B_S ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_256B_D = (0x100 | XG_SWIZZLE_MODE_256B_D ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_256B_R = (0x100 | XG_SWIZZLE_MODE_256B_R ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_Z = (0x100 | XG_SWIZZLE_MODE_4KB_Z ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_S = (0x100 | XG_SWIZZLE_MODE_4KB_S ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_D = (0x100 | XG_SWIZZLE_MODE_4KB_D ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_R = (0x100 | XG_SWIZZLE_MODE_4KB_R ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_Z = (0x100 | XG_SWIZZLE_MODE_64KB_Z ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S = (0x100 | XG_SWIZZLE_MODE_64KB_S ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_D = (0x100 | XG_SWIZZLE_MODE_64KB_D ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_R = (0x100 | XG_SWIZZLE_MODE_64KB_R ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_Z = (0x100 | XG_SWIZZLE_MODE_VAR_Z ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_S = (0x100 | XG_SWIZZLE_MODE_VAR_S ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_D = (0x100 | XG_SWIZZLE_MODE_VAR_D ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_R = (0x100 | XG_SWIZZLE_MODE_VAR_R ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_Z_T = (0x100 | XG_SWIZZLE_MODE_64KB_Z_T), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S_T = (0x100 | XG_SWIZZLE_MODE_64KB_S_T), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_D_T = (0x100 | XG_SWIZZLE_MODE_64KB_D_T), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_R_T = (0x100 | XG_SWIZZLE_MODE_64KB_R_T), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_Z_X = (0x100 | XG_SWIZZLE_MODE_4KB_Z_X ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_S_X = (0x100 | XG_SWIZZLE_MODE_4KB_S_X ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_D_X = (0x100 | XG_SWIZZLE_MODE_4KB_D_X ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_4KB_R_X = (0x100 | XG_SWIZZLE_MODE_4KB_R_X ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_Z_X = (0x100 | XG_SWIZZLE_MODE_64KB_Z_X), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S_X = (0x100 | XG_SWIZZLE_MODE_64KB_S_X), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_D_X = (0x100 | XG_SWIZZLE_MODE_64KB_D_X), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_R_X = (0x100 | XG_SWIZZLE_MODE_64KB_R_X), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_Z_X = (0x100 | XG_SWIZZLE_MODE_VAR_Z_X ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_S_X = (0x100 | XG_SWIZZLE_MODE_VAR_S_X ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_D_X = (0x100 | XG_SWIZZLE_MODE_VAR_D_X ), + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_R_X = (0x100 | XG_SWIZZLE_MODE_VAR_R_X ), + + XG_TEXTURE_LAYOUT_SWIZZLE_MODE_MASK = 0x11F, +} XG_TEXTURE_LAYOUT; + +inline bool XGConvertSwizzleModeToExtensionTextureLayout(XG_SWIZZLE_MODE SwizzleMode, XG_TEXTURE_LAYOUT* pTextureLayout) +{ + if (SwizzleMode > XG_SWIZZLE_MODE_VAR_R_X) + { + return false; + } + *pTextureLayout = (XG_TEXTURE_LAYOUT)(XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR + (UINT)SwizzleMode); + return true; +} + +inline bool XGConvertExtensionTextureLayoutToSwizzleMode(XG_TEXTURE_LAYOUT TextureLayout, XG_SWIZZLE_MODE* pSwizzleMode) +{ + if (TextureLayout < XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR || TextureLayout > XG_TEXTURE_LAYOUT_SWIZZLE_MODE_VAR_R_X) + { + return false; + } + *pSwizzleMode = (XG_SWIZZLE_MODE)(TextureLayout & 0x1F); + return true; +} + +//------------------------------------------------------------------------------------------------- +// XG_FORMAT is identical to DXGI_FORMAT on Xbox, and is a superset of DXGI_FORMAT for D3D 11.1 on Windows 8. + +enum XG_FORMAT +{ + XG_FORMAT_UNKNOWN = 0, + XG_FORMAT_R32G32B32A32_TYPELESS = 1, + XG_FORMAT_R32G32B32A32_FLOAT = 2, + XG_FORMAT_R32G32B32A32_UINT = 3, + XG_FORMAT_R32G32B32A32_SINT = 4, + XG_FORMAT_R32G32B32_TYPELESS = 5, + XG_FORMAT_R32G32B32_FLOAT = 6, + XG_FORMAT_R32G32B32_UINT = 7, + XG_FORMAT_R32G32B32_SINT = 8, + XG_FORMAT_R16G16B16A16_TYPELESS = 9, + XG_FORMAT_R16G16B16A16_FLOAT = 10, + XG_FORMAT_R16G16B16A16_UNORM = 11, + XG_FORMAT_R16G16B16A16_UINT = 12, + XG_FORMAT_R16G16B16A16_SNORM = 13, + XG_FORMAT_R16G16B16A16_SINT = 14, + XG_FORMAT_R32G32_TYPELESS = 15, + XG_FORMAT_R32G32_FLOAT = 16, + XG_FORMAT_R32G32_UINT = 17, + XG_FORMAT_R32G32_SINT = 18, + XG_FORMAT_R32G8X24_TYPELESS = 19, + XG_FORMAT_D32_FLOAT_S8X24_UINT = 20, + XG_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, + XG_FORMAT_X32_TYPELESS_G8X24_UINT = 22, + XG_FORMAT_R10G10B10A2_TYPELESS = 23, + XG_FORMAT_R10G10B10A2_UNORM = 24, + XG_FORMAT_R10G10B10A2_UINT = 25, + XG_FORMAT_R11G11B10_FLOAT = 26, + XG_FORMAT_R8G8B8A8_TYPELESS = 27, + XG_FORMAT_R8G8B8A8_UNORM = 28, + XG_FORMAT_R8G8B8A8_UNORM_SRGB = 29, + XG_FORMAT_R8G8B8A8_UINT = 30, + XG_FORMAT_R8G8B8A8_SNORM = 31, + XG_FORMAT_R8G8B8A8_SINT = 32, + XG_FORMAT_R16G16_TYPELESS = 33, + XG_FORMAT_R16G16_FLOAT = 34, + XG_FORMAT_R16G16_UNORM = 35, + XG_FORMAT_R16G16_UINT = 36, + XG_FORMAT_R16G16_SNORM = 37, + XG_FORMAT_R16G16_SINT = 38, + XG_FORMAT_R32_TYPELESS = 39, + XG_FORMAT_D32_FLOAT = 40, + XG_FORMAT_R32_FLOAT = 41, + XG_FORMAT_R32_UINT = 42, + XG_FORMAT_R32_SINT = 43, + XG_FORMAT_R24G8_TYPELESS = 44, + XG_FORMAT_D24_UNORM_S8_UINT = 45, + XG_FORMAT_R24_UNORM_X8_TYPELESS = 46, + XG_FORMAT_X24_TYPELESS_G8_UINT = 47, + XG_FORMAT_R8G8_TYPELESS = 48, + XG_FORMAT_R8G8_UNORM = 49, + XG_FORMAT_R8G8_UINT = 50, + XG_FORMAT_R8G8_SNORM = 51, + XG_FORMAT_R8G8_SINT = 52, + XG_FORMAT_R16_TYPELESS = 53, + XG_FORMAT_R16_FLOAT = 54, + XG_FORMAT_D16_UNORM = 55, + XG_FORMAT_R16_UNORM = 56, + XG_FORMAT_R16_UINT = 57, + XG_FORMAT_R16_SNORM = 58, + XG_FORMAT_R16_SINT = 59, + XG_FORMAT_R8_TYPELESS = 60, + XG_FORMAT_R8_UNORM = 61, + XG_FORMAT_R8_UINT = 62, + XG_FORMAT_R8_SNORM = 63, + XG_FORMAT_R8_SINT = 64, + XG_FORMAT_A8_UNORM = 65, + XG_FORMAT_R1_UNORM = 66, + XG_FORMAT_R9G9B9E5_SHAREDEXP = 67, + XG_FORMAT_R8G8_B8G8_UNORM = 68, + XG_FORMAT_G8R8_G8B8_UNORM = 69, + XG_FORMAT_BC1_TYPELESS = 70, + XG_FORMAT_BC1_UNORM = 71, + XG_FORMAT_BC1_UNORM_SRGB = 72, + XG_FORMAT_BC2_TYPELESS = 73, + XG_FORMAT_BC2_UNORM = 74, + XG_FORMAT_BC2_UNORM_SRGB = 75, + XG_FORMAT_BC3_TYPELESS = 76, + XG_FORMAT_BC3_UNORM = 77, + XG_FORMAT_BC3_UNORM_SRGB = 78, + XG_FORMAT_BC4_TYPELESS = 79, + XG_FORMAT_BC4_UNORM = 80, + XG_FORMAT_BC4_SNORM = 81, + XG_FORMAT_BC5_TYPELESS = 82, + XG_FORMAT_BC5_UNORM = 83, + XG_FORMAT_BC5_SNORM = 84, + XG_FORMAT_B5G6R5_UNORM = 85, + XG_FORMAT_B5G5R5A1_UNORM = 86, + XG_FORMAT_B8G8R8A8_UNORM = 87, + XG_FORMAT_B8G8R8X8_UNORM = 88, + XG_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, + XG_FORMAT_B8G8R8A8_TYPELESS = 90, + XG_FORMAT_B8G8R8A8_UNORM_SRGB = 91, + XG_FORMAT_B8G8R8X8_TYPELESS = 92, + XG_FORMAT_B8G8R8X8_UNORM_SRGB = 93, + XG_FORMAT_BC6H_TYPELESS = 94, + XG_FORMAT_BC6H_UF16 = 95, + XG_FORMAT_BC6H_SF16 = 96, + XG_FORMAT_BC7_TYPELESS = 97, + XG_FORMAT_BC7_UNORM = 98, + XG_FORMAT_BC7_UNORM_SRGB = 99, + XG_FORMAT_AYUV = 100, + XG_FORMAT_Y410 = 101, + XG_FORMAT_Y416 = 102, + XG_FORMAT_NV12 = 103, + XG_FORMAT_P010 = 104, + XG_FORMAT_P016 = 105, + XG_FORMAT_420_OPAQUE = 106, + XG_FORMAT_YUY2 = 107, + XG_FORMAT_Y210 = 108, + XG_FORMAT_Y216 = 109, + XG_FORMAT_NV11 = 110, + XG_FORMAT_AI44 = 111, + XG_FORMAT_IA44 = 112, + XG_FORMAT_P8 = 113, + XG_FORMAT_A8P8 = 114, + XG_FORMAT_B4G4R4A4_UNORM = 115, + XG_FORMAT_R10G10B10_7E3_A2_FLOAT = 116, + XG_FORMAT_R10G10B10_6E4_A2_FLOAT = 117, + XG_FORMAT_D16_UNORM_S8_UINT = 118, + XG_FORMAT_R16_UNORM_X8_TYPELESS = 119, + XG_FORMAT_X16_TYPELESS_G8_UINT = 120, + XG_FORMAT_R10G10B10_SNORM_A2_UNORM = 189, + XG_FORMAT_R4G4_UNORM = 190, + XG_FORMAT_R24G8_UNORM = 191, + XG_FORMAT_FORCE_UINT = 0xffffffff +}; + +//------------------------------------------------------------------------------------------------- +// XG_RESOURCE_DIMENSION is the same as D3D11_RESOURCE_DIMENSION. + +enum XG_RESOURCE_DIMENSION +{ + XG_RESOURCE_DIMENSION_UNKNOWN = 0, + XG_RESOURCE_DIMENSION_BUFFER = 1, + XG_RESOURCE_DIMENSION_TEXTURE1D = 2, + XG_RESOURCE_DIMENSION_TEXTURE2D = 3, + XG_RESOURCE_DIMENSION_TEXTURE3D = 4 +}; + +//------------------------------------------------------------------------------------------------- +// XG_USAGE is the same as D3D11_USAGE. + +enum XG_USAGE +{ + XG_USAGE_DEFAULT = 0, + XG_USAGE_IMMUTABLE = 1, + XG_USAGE_DYNAMIC = 2, + XG_USAGE_STAGING = 3 +}; + +//------------------------------------------------------------------------------------------------- +// XG_PLANE_USAGE is a value returned by the XG texture layout APIs to indicate the purpose of each +// of the 1-4 planes comprising a texture resource. + +enum XG_PLANE_USAGE +{ + XG_PLANE_USAGE_UNUSED = 0, + XG_PLANE_USAGE_DEFAULT = 1, + XG_PLANE_USAGE_COLOR_MASK = 2, + XG_PLANE_USAGE_FRAGMENT_MASK = 3, + XG_PLANE_USAGE_HTILE = 4, + XG_PLANE_USAGE_LUMA = 5, + XG_PLANE_USAGE_CHROMA = 6, + XG_PLANE_USAGE_DEPTH = 7, + XG_PLANE_USAGE_STENCIL = 8, + XG_PLANE_USAGE_DELTA_COLOR_COMPRESSION = 9, +}; + +//------------------------------------------------------------------------------------------------- +// XG_BIND_FLAG is equivalent to D3D11_BIND_FLAG. + +enum XG_BIND_FLAG +{ + XG_BIND_VERTEX_BUFFER = 0x1L, + XG_BIND_INDEX_BUFFER = 0x2L, + XG_BIND_CONSTANT_BUFFER = 0x4L, + XG_BIND_SHADER_RESOURCE = 0x8L, + XG_BIND_STREAM_OUTPUT = 0x10L, + XG_BIND_RENDER_TARGET = 0x20L, + XG_BIND_DEPTH_STENCIL = 0x40L, + XG_BIND_UNORDERED_ACCESS = 0x80L, + XG_BIND_DECODER = 0x200L, + XG_BIND_VIDEO_ENCODER = 0x400L +}; +DEFINE_ENUM_FLAG_OPERATORS(XG_BIND_FLAG); + +//------------------------------------------------------------------------------------------------- +// XG_CPU_ACCESS_FLAG is equivalent to D3D11_CPU_ACCESS_FLAG. + +enum XG_CPU_ACCESS_FLAG +{ + XG_CPU_ACCESS_WRITE = 0x10000L, + XG_CPU_ACCESS_READ = 0x20000L +}; +DEFINE_ENUM_FLAG_OPERATORS(XG_CPU_ACCESS_FLAG); + +//------------------------------------------------------------------------------------------------- +// XG_RESOURCE_MISC_FLAG is a subset of D3D11_RESOURCE_MISC_FLAG. +// The set of flags that exist in XG_RESOURCE_MISC_FLAG match the values of their corresponding +// flags in D3D11_RESOURCE_MISC_FLAG found in d3d11_x.h. + +enum XG_RESOURCE_MISC_FLAG +{ + XG_RESOURCE_MISC_GENERATE_MIPS = 0x1L, + XG_RESOURCE_MISC_TEXTURECUBE = 0x4L, + XG_RESOURCE_MISC_DRAWINDIRECT_ARGS = 0x10L, + XG_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS = 0x20L, + XG_RESOURCE_MISC_BUFFER_STRUCTURED = 0x40L, + XG_RESOURCE_MISC_RESOURCE_CLAMP = 0x80L, + XG_RESOURCE_MISC_RESTRICTED_CONTENT = 0x1000L, + XG_RESOURCE_MISC_ESRAM_RESIDENT = 0x20000L, + XG_RESOURCE_MISC_NO_COLOR_COMPRESSION = 0x80000L, + XG_RESOURCE_MISC_NO_DEPTH_COMPRESSION = 0x100000L, + XG_RESOURCE_MISC_NO_STENCIL_COMPRESSION = 0x200000L, + XG_RESOURCE_MISC_ALLOW_DCC = 0x400000L, + XG_RESOURCE_MISC_FORCE_TEXTURE_COMPATIBILITY = 0x8000L, + XG_RESOURCE_MISC_TILE_POOL = 0x4000000L, + XG_RESOURCE_MISC_TILED = 0x8000000L, +}; +DEFINE_ENUM_FLAG_OPERATORS(XG_RESOURCE_MISC_FLAG); + +//------------------------------------------------------------------------------------------------- +// XG12_RESOURCE_MISC_FLAG is a subset of D3D12_RESOURCE_FLAG from D3D12.XS. +typedef enum XG12_RESOURCE_MISC_FLAG +{ + XG12_RESOURCE_MISC_NONE = 0, + XG12_RESOURCE_MISC_ALLOW_RENDER_TARGET = 0x1, + XG12_RESOURCE_MISC_ALLOW_DEPTH_STENCIL = 0x2, + XG12_RESOURCE_MISC_ALLOW_UNORDERED_ACCESS = 0x4, + XG12_RESOURCE_MISC_DENY_SHADER_RESOURCE = 0x8, + XG12_RESOURCE_MISC_ALLOW_SIMULTANEOUS_ACCESS = 0x20, + XG12_RESOURCE_MISC_DENY_COMPRESSION_DATA = 0x300000, + XG12_RESOURCE_MISC_FLAG_DENY_DEPTH_COMPRESSION_DATA = 0x100000, + XG12_RESOURCE_MISC_FLAG_DENY_STENCIL_COMPRESSION_DATA = 0x200000, + XG12_RESOURCE_MISC_ALLOW_DCC = 0x400000, + XG12_RESOURCE_MISC_FORCE_TEXTURE_COMPATIBILITY = 0x800000, + XG12_RESOURCE_MISC_FLAG_DENY_DEPTH_STENCIL_HTILE = 0x80000000, +} XG12_RESOURCE_MISC_FLAG; +DEFINE_ENUM_FLAG_OPERATORS(XG12_RESOURCE_MISC_FLAG); + +typedef enum XG_HARDWARE_VERSION +{ + XG_HARDWARE_VERSION_XBOX_ONE = 0, + XG_HARDWARE_VERSION_XBOX_ONE_S = 1, + XG_HARDWARE_VERSION_XBOX_ONE_X = 2, + XG_HARDWARE_VERSION_XBOX_ONE_X_DEVKIT = 3, + XG_HARDWARE_VERSION_XBOX_SCARLETT_LOCKHART = 4, + XG_HARDWARE_VERSION_XBOX_SCARLETT_ANACONDA = 5, + XG_HARDWARE_VERSION_XBOX_SCARLETT_DEVKIT = 6, +} XG_HARDWARE_VERSION; + +//------------------------------------------------------------------------------------------------- +// XG_SAMPLE_DESC is equivalent to DXGI_SAMPLE_DESC. + +struct XG_SAMPLE_DESC +{ + UINT Count; + UINT Quality; +}; + +//------------------------------------------------------------------------------------------------- +// XG_BUFFER_DESC is equivalent to D3D11_BUFFER_DESC. + +struct XG_BUFFER_DESC +{ + UINT ByteWidth; + XG_USAGE Usage; + UINT BindFlags; // Any of XG_BIND_FLAG. + UINT CPUAccessFlags; // Any of XG_CPU_ACCESS_FLAG. + UINT MiscFlags; // Any of XG_RESOURCE_MISC_FLAG. + UINT StructureByteStride; +}; + +//------------------------------------------------------------------------------------------------- +// XG_TEXTURE1D_DESC is a superset of D3D11_TEXTURE1D_DESC, and contains additional parameters used +// to describe a 1D texture for the XG texture layout APIs. + +struct XG_TEXTURE1D_DESC +{ + UINT Width; + UINT MipLevels; + UINT ArraySize; + XG_FORMAT Format; + XG_USAGE Usage; + UINT BindFlags; // Any of XG_BIND_FLAG. + UINT CPUAccessFlags; // Any of XG_CPU_ACCESS_FLAG. + UINT MiscFlags; // Any of XG_RESOURCE_MISC_FLAG. + XG_SWIZZLE_MODE SwizzleMode; + UINT Pitch; +}; + +//------------------------------------------------------------------------------------------------- +// XG_TEXTURE2D_DESC is a superset of D3D11_TEXTURE2D_DESC, and contains additional parameters used +// to describe a 2D texture for the XG texture layout APIs. + +struct XG_TEXTURE2D_DESC +{ + UINT Width; + UINT Height; + UINT MipLevels; + UINT ArraySize; + XG_FORMAT Format; + XG_SAMPLE_DESC SampleDesc; + XG_USAGE Usage; + UINT BindFlags; // Any of XG_BIND_FLAG. + UINT CPUAccessFlags; // Any of XG_CPU_ACCESS_FLAG. + UINT MiscFlags; // Any of XG_RESOURCE_MISC_FLAG. + XG_SWIZZLE_MODE SwizzleMode; + UINT Pitch; +}; + +//------------------------------------------------------------------------------------------------- +// XG_TEXTURE3D_DESC is a superset of D3D11_TEXTURE3D_DESC, and contains additional parameters used +// to describe a 3D texture for the XG texture layout APIs. + +struct XG_TEXTURE3D_DESC +{ + UINT Width; + UINT Height; + UINT Depth; + UINT MipLevels; + XG_FORMAT Format; + XG_USAGE Usage; + UINT BindFlags; // Any of XG_BIND_FLAG. + UINT CPUAccessFlags; // Any of XG_CPU_ACCESS_FLAG. + UINT MiscFlags; // Any of XG_RESOURCE_MISC_FLAG. + XG_SWIZZLE_MODE SwizzleMode; + UINT Pitch; +}; + +//------------------------------------------------------------------------------------------------- +// XG_RESOURCE_DESC is identical to D3D12_RESOURCE_DESC, and can describe a texture of any +// dimension to XG. + +typedef struct XG_RESOURCE_DESC +{ + XG_RESOURCE_DIMENSION Dimension; + UINT64 Alignment; + UINT64 Width; + UINT Height; + UINT16 DepthOrArraySize; + UINT16 MipLevels; + XG_FORMAT Format; + XG_SAMPLE_DESC SampleDesc; + XG_TEXTURE_LAYOUT Layout; + XG12_RESOURCE_MISC_FLAG MiscFlags; +} XG_RESOURCE_DESC; + + +//------------------------------------------------------------------------------------------------- +// XG_MIPLEVEL_LAYOUT describes a single mip level in the hardware layout of a texture. +// Note that each mip level comprises a number of contiguous slices in the case of volume textures only. + +struct XG_MIPLEVEL_LAYOUT +{ + UINT64 SizeBytes; + UINT64 OffsetBytes; + UINT64 Slice2DSizeBytes; + UINT32 PitchPixels; + UINT32 PitchBytes; + UINT32 AlignmentBytes; + UINT32 PaddedWidthElements; + UINT32 PaddedHeightElements; + UINT32 PaddedDepthOrArraySize; + UINT32 WidthElements; + UINT32 HeightElements; + UINT32 WidthPixels; + UINT32 HeightPixels; + UINT32 DepthOrArraySize; + UINT32 SampleCount; + XG_SWIZZLE_MODE SwizzleMode; + UINT64 BankRotationAddressBitMask; + UINT64 BankRotationBytesPerSlice; + UINT32 SliceDepthElements; + UINT32 IsMipTail; + + // If this mip level is a mip tail, and OffsetBytes is 0, then the mip image + // location within the mip tail is described by these offsets in elements: + UINT32 MipTailOffsetElementsX : 11; + UINT32 MipTailOffsetElementsY : 11; + UINT32 MipTailOffsetElementsZ : 10; +}; + +//------------------------------------------------------------------------------------------------- +// XG_PLANE_LAYOUT describes a single plane in the hardware layout of a resource. + +struct XG_PLANE_LAYOUT +{ + // Usage is the purpose of this plane - whether it's the primary plane (DEFAULT), or a compression metadata surface. + XG_PLANE_USAGE Usage; + + // SizeBytes is the total size of the plane, including all slices. + UINT64 SizeBytes; + + // SliceSizeBytes is the size of a single array slice, which is an entire mip chain. + // For 1D/2D array textures, a slice is always one texel element in depth. + // For 3D (volume) textures, a slice may be more than one texel element in depth. + // See SliceDepthElements on the mip level structs. + UINT64 SliceSizeBytes; + + // BaseOffsetBytes is the offset of this plane from the base address of the resource. + UINT64 BaseOffsetBytes; + + // BaseAlignmentBytes is the alignment of this plane within the resource. + UINT64 BaseAlignmentBytes; + + // BytesPerElement is the number of bytes per texel element of all texels in this plane. + // Note that a BC compression block (4x4 decompressed texels) is one texel element. + UINT32 BytesPerElement; + + // StandardMipCount is the number of mip levels that are not part of the mip chain. + UINT32 StandardMipCount; + + // MipTailMipCount is the number of mip levels that are part of the mip chain. + UINT32 MipTailMipCount; + + // The array of mip level layouts comprising this plane. + XG_MIPLEVEL_LAYOUT MipLayout[15]; +}; + +//------------------------------------------------------------------------------------------------- +// XG_RESOURCE_LAYOUT describes the entire hardware layout of a single resource. Certain resource +// configurations include up to 4 planes, each plane being a single mip chain. + +struct XG_RESOURCE_LAYOUT +{ + UINT64 SizeBytes; + UINT64 BaseAlignmentBytes; + UINT32 MipLevels; + UINT32 Planes; + XG_PLANE_LAYOUT Plane[4]; + XG_RESOURCE_DIMENSION Dimension; +}; + +//-------------------------------------------------------------------------------------------------- +typedef struct XG_SUBRESOURCE_TILING +{ + UINT32 WidthInTiles; + UINT16 HeightInTiles; + UINT16 DepthInTiles; + UINT32 StartTileIndexInOverallResource; +} XG_SUBRESOURCE_TILING; + +#define XG_PACKED_TILE ( 0xffffffff ) + +//-------------------------------------------------------------------------------------------------- +typedef struct XG_TILE_SHAPE +{ + UINT32 WidthInTexels; + UINT32 HeightInTexels; + UINT32 DepthInTexels; +} XG_TILE_SHAPE; + +//-------------------------------------------------------------------------------------------------- +typedef struct XG_TILE_SHAPE_ELEMENTS +{ + UINT32 WidthInElements; + UINT32 HeightInElements; + UINT32 DepthInElements; +} XG_TILE_SHAPE_ELEMENTS; + +//-------------------------------------------------------------------------------------------------- +typedef struct XG_PACKED_MIP_DESC +{ + UINT8 NumStandardMips; + UINT8 NumPackedMips; + UINT32 NumTilesForPackedMips; + UINT32 StartTileIndexInOverallResource; +} XG_PACKED_MIP_DESC; + +//-------------------------------------------------------------------------------------------------- +#define XG_TILED_RESOURCE_TILE_SIZE_IN_BYTES ( 65536 ) + +//-------------------------------------------------------------------------------------------------- +typedef struct XG_DESCRIPTOR_TEXTURE_VIEW +{ + UINT32 Dword[8]; +} XG_DESCRIPTOR_TEXTURE_VIEW; + +//------------------------------------------------------------------------------------------------- +typedef struct XG_SWIZZLE_PATTERN_INFO +{ + // Internal: swizzle pattern equation index. + UINT32 EquationIndex; + + // Dimensions (in elements) of the underlying swizzle block size. + UINT32 BlockWidth; + UINT32 BlockHeight; + UINT32 BlockSlices; +} XG_SWIZZLE_PATTERN_INFO; + +//------------------------------------------------------------------------------------------------- +// XGComputeBufferLayout computes the hardware alignment for a buffer. + +HRESULT __cdecl XGComputeBufferLayout( + _In_ const XG_BUFFER_DESC* pDesc, + _Out_ XG_RESOURCE_LAYOUT* pLayout +); + +//------------------------------------------------------------------------------------------------- +// XGComputeTexture1DLayout computes the hardware layout for a 1D texture. + +HRESULT __cdecl XGComputeTexture1DLayout( + _In_ const XG_TEXTURE1D_DESC* pDesc, + _Out_ XG_RESOURCE_LAYOUT* pLayout +); + +//------------------------------------------------------------------------------------------------- +// XGComputeTexture2DLayout computes the hardware layout for a 2D texture. + +HRESULT __cdecl XGComputeTexture2DLayout( + _In_ const XG_TEXTURE2D_DESC* pDesc, + _Out_ XG_RESOURCE_LAYOUT* pLayout +); + +//------------------------------------------------------------------------------------------------- +// XGComputeTexture3DLayout computes the hardware layout for a 3D texture. + +HRESULT __cdecl XGComputeTexture3DLayout( + _In_ const XG_TEXTURE3D_DESC* pDesc, + _Out_ XG_RESOURCE_LAYOUT* pLayout +); + +//------------------------------------------------------------------------------------------------- +// XGSuggestSwizzleMode returns the driver's suggested swizzle mode for the given resource configuration. +// If neither optimize for performance or optimize for memory footprint are specified, the driver's suggestion +// will optimize for performance. +// The Layout field in the pResourceDesc parameter is ignored if it contains one of the extension +// XG_TEXTURE_LAYOUT_SWIZZLE_MODE_* values. Use a Layout value of XG_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE +// to indicate a reserved/tiled resource. +// The swizzle mode is returned either in XG_SWIZZLE_MODE or XG_TEXTURE_LAYOUT encoding. + +typedef enum XG_SUGGEST_SWIZZLE_MODE_FLAGS +{ + XG_SUGGEST_SWIZZLE_MODE_FLAG_NONE = 0, + XG_SUGGEST_SWIZZLE_MODE_FLAG_OPTIMIZE_FOR_PERFORMANCE = 1, + XG_SUGGEST_SWIZZLE_MODE_FLAG_OPTIMIZE_FOR_MEMORY_FOOTPRINT = 2, +} XG_SUGGEST_SWIZZLE_MODE_FLAGS; + +HRESULT __cdecl XGSuggestSwizzleMode( + _In_ const XG_RESOURCE_DESC* pResourceDesc, + _In_ XG_SUGGEST_SWIZZLE_MODE_FLAGS Flags, + _Out_ XG_TEXTURE_LAYOUT* pTextureLayout +); + +//------------------------------------------------------------------------------------------------- +// XGComputeOptimalSwizzleMode computes the bandwidth optimal swizzle mode for the given texture configuration. +// This API is deprecated; please use XGSuggestSwizzleMode instead. + +XG_SWIZZLE_MODE __cdecl XGComputeOptimalSwizzleMode( + _In_ XG_RESOURCE_DIMENSION ResourceDimension, + _In_ XG_FORMAT Format, + _In_ UINT32 Width, + _In_ UINT32 Height, + _In_ UINT32 DepthOrArraySize, + _In_ UINT32 SampleCount, + _In_ UINT BindFlags, // Any of XG_BIND_FLAG. + _In_ UINT MiscFlags = 0 // Any of XG_RESOURCE_MISC_FLAG. +); + +//------------------------------------------------------------------------------------------------- +// XGComputeOptimalDepthStencilTileModes computes the correct swizzle mode for the given depth +// stencil configuration. +// This API is deprecated; please use XGSuggestSwizzleMode instead. + +VOID __cdecl XGComputeOptimalDepthStencilSwizzleMode( + _In_ XG_FORMAT Format, + _In_ UINT32 Width, + _In_ UINT32 Height, + _In_ UINT32 DepthOrArraySize, + _In_ UINT32 SampleCount, + _In_ BOOL Compressed, + _In_ BOOL TiledResource, + _In_ BOOL TextureCompatible, + _Out_ XG_SWIZZLE_MODE* pDepthSwizzleMode +); + +//------------------------------------------------------------------------------------------------- +// XGValidateDepthStencilSwizzleMode returns S_OK if the given tile mode is valid for the depth +// stencil format and sample count, or E_FAIL if the given tile mode is not valid. E_INVALIDARG is +// returned if the format is not a valid depth format or the tile mode is not appropriate for use +// as a depth buffer in any circumstances. + +HRESULT __cdecl XGValidateDepthStencilSwizzleMode( + _In_ XG_FORMAT Format, + _In_ UINT32 SampleCount, + _In_ XG_SWIZZLE_MODE SwizzleMode +); + +//------------------------------------------------------------------------------------------------- +// XGTextureAddressComputer holds a computed texture layout for a given texture resource, along with +// additional state that allows the user to perform texture element microtiling and macrotiling. +// The class is refcounted and will delete itself when its refcount reaches 0. + +class XGTextureAddressComputer +{ +public: + //------------------------------------------------------------------------------------------------- + // Increments the refcount and returns the new value. + virtual ULONG __cdecl AddRef() = 0; + + //------------------------------------------------------------------------------------------------- + // Decrements the refcount and returns the new value. If the new value is 0, the object is deleted. + virtual ULONG __cdecl Release() = 0; + + //------------------------------------------------------------------------------------------------- + // Returns the XG_RESOURCE_LAYOUT that was computed for this texture resource. + virtual HRESULT __cdecl GetResourceLayout( + _Out_ XG_RESOURCE_LAYOUT* pLayout + ) = 0; + + //------------------------------------------------------------------------------------------------- + // Returns the resource's total size in bytes. Equivalent to calling GetResourceLayout and using + // the SizeBytes field. + virtual UINT64 GetResourceSizeBytes() = 0; + + //------------------------------------------------------------------------------------------------- + // Returns the resource's total size in 64KB pages, rounded up to the next whole page. + UINT64 GetResourceSizePages() { return ((GetResourceSizeBytes() + XG_GPU_PAGE_SIZE_MASK) >> XG_GPU_PAGE_SIZE_SHIFT); } + + //------------------------------------------------------------------------------------------------- + // Returns the resource's base alignment in bytes. Equivalent to calling GetResourceLayout and + // using the BaseAlignmentBytes field. + virtual UINT64 GetResourceBaseAlignmentBytes() = 0; + + //------------------------------------------------------------------------------------------------- + // Computes the offset in bytes of the given mip level on the given plane, from the base address + // of the resource. + virtual UINT64 __cdecl GetMipLevelOffsetBytes( + _In_ UINT32 Plane, + _In_ UINT32 MipLevel + ) = 0; + + //------------------------------------------------------------------------------------------------- + // Computes the offset in bytes of the given texel element, from the base address of the resource. + virtual UINT64 __cdecl GetTexelElementOffsetBytes( + _In_ UINT32 Plane, + _In_ UINT32 MipLevel, + _In_ UINT64 X, + _In_ UINT32 Y, + _In_ UINT32 ZOrSlice, + _In_ UINT32 Sample, + _Out_opt_ UINT32 * pBitPosition + ) = 0; + + //------------------------------------------------------------------------------------------------- + // Compute texel element coordinate of the given offset to the base address of the resource. + // Return E_INVALIDARGS, if the offset is not within the memory range of the resource. + virtual HRESULT __cdecl GetTexelCoordinate( + _In_ UINT64 Offset, + _Out_opt_ UINT32 * Plane, + _Out_opt_ UINT32 * MipLevel, + _Out_opt_ UINT64 * X, + _Out_opt_ UINT32 * Y, + _Out_opt_ UINT32 * ZOrSlice, + _Out_opt_ UINT32 * Sample + ) = 0; + + //------------------------------------------------------------------------------------------------- + // Copies the 2D or 3D linear input data into the given subresource (mip + slice) of the resource, + // using pTiledResourceBaseAddress as the resource's base address. For offline texture preparation, + // pTiledResourceBaseAddress does not need to be properly aligned. + virtual HRESULT __cdecl CopyIntoSubresource( + _Inout_ VOID* pTiledResourceBaseAddress, + _In_ UINT32 Plane, + _In_ UINT32 Subresource, + _In_ const VOID* pLinearData, + _In_ UINT32 RowPitchBytes, + _In_ UINT32 SlicePitchBytes + ) = 0; + + //------------------------------------------------------------------------------------------------- + // Copies texel data out of the given subresource (mip + slice) into the 2D or 3D linear output buffer, + // using pTiledResourceBaseAddress as the resource's base address. For offline texture preparation, + // pTiledResourceBaseAddress does not need to be properly aligned. + virtual HRESULT __cdecl CopyFromSubresource( + _Inout_ VOID* pLinearData, + _In_ UINT32 Plane, + _In_ UINT32 Subresource, + _In_ UINT32 Sample, + _In_ const VOID* pTiledResourceBaseAddress, + _In_ UINT32 RowPitchBytes, + _In_ UINT32 SlicePitchBytes + ) = 0; + + //------------------------------------------------------------------------------------------------- + // Returns the resource tiling layout, if the resource is created as a tiled resource using the + // XG_RESOURCE_MISC_TILED flag. + virtual HRESULT __cdecl GetResourceTiling( + _Out_opt_ UINT32 *pNumTilesForEntireResource, + _Out_opt_ XG_PACKED_MIP_DESC *pPackedMipDesc, + _Out_opt_ XG_TILE_SHAPE *pStandardTileShapeForNonPackedMips, + _Inout_opt_ UINT32 *pNumSubresourceTilings, + _In_ UINT32 FirstSubresourceTilingToGet, + _Out_writes_(*pNumSubresourceTilings) XG_SUBRESOURCE_TILING *pSubresourceTilingsForNonPackedMips + ) = 0; + + //---------------------------------------------------------------------------------------------- + // Returns the texture view descriptor for the given plane. Returns E_INVALIDARG if the given + // plane cannot be described with a descriptor. + virtual HRESULT GetTextureViewDescriptor( + _In_ UINT32 PlaneIndex, + _Out_ XG_DESCRIPTOR_TEXTURE_VIEW* pDescriptor + ) = 0; + + //---------------------------------------------------------------------------------------------- + // Returns true if the resource is created as a tiled resource + virtual bool IsTiledResource() const = 0; + + //---------------------------------------------------------------------------------------------- + // Returns the swizzle pattern information + virtual HRESULT GetSwizzlePatternInfo( + _In_ UINT32 PlaneIndex, + _Out_ XG_SWIZZLE_PATTERN_INFO* pInfo + ) const = 0; +}; + +//------------------------------------------------------------------------------------------------- +// XGCreateTexture1DComputer creates a texture address computer object for the given 1D texture desc. + +HRESULT __cdecl XGCreateTexture1DComputer( + _In_ const XG_TEXTURE1D_DESC* pDesc, + _Out_ XGTextureAddressComputer** ppComputer +); + +//------------------------------------------------------------------------------------------------- +// XGCreateTexture2DComputer creates a texture address computer object for the given 2D texture desc. + +HRESULT __cdecl XGCreateTexture2DComputer( + _In_ const XG_TEXTURE2D_DESC* pDesc, + _Out_ XGTextureAddressComputer** ppComputer +); + +//------------------------------------------------------------------------------------------------- +// XGCreateTexture3DComputer creates a texture address computer object for the given 3D texture desc. + +HRESULT __cdecl XGCreateTexture3DComputer( + _In_ const XG_TEXTURE3D_DESC* pDesc, + _Out_ XGTextureAddressComputer** ppComputer +); + +//-------------------------------------------------------------------------------------------------- +// XGCreateTextureComputerFromDescriptor creates a texture address computer object for the given +// texture descriptor. + +HRESULT __cdecl XGCreateTextureComputerFromDescriptor( + _In_ const XG_DESCRIPTOR_TEXTURE_VIEW* pDescriptor, + _Out_ XGTextureAddressComputer** ppComputer +); + +//-------------------------------------------------------------------------------------------------- +// XGCreateTextureComputer creates a texture address computer object for the given D3D12-style +// resource desc. Buffer descs are not supported and will return E_INVALIDARG. + +HRESULT __cdecl XGCreateTextureComputer( + _In_ const XG_RESOURCE_DESC* pDesc, + _Out_ XGTextureAddressComputer** ppComputer +); + +//-------------------------------------------------------------------------------------------------- +// XGComputeTileShape returns the shape of a single tiled resource tile for the given format. +// If Format is XG_FORMAT_UNKNOWN, then the BytesPerElement parameter is used instead; +// in that case BytesPerElement must be 1, 2, 4, 8, or 16 bytes. If Format is not +// XG_FORMAT_UNKNOWN, then the value of BytesPerElement is ignored and is computed by this function. +// SampleCount must be 1 for all resource dimensions other than Texture2D. +// For Texture2D, SampleCount must be one of 1, 2, 4, or 8. +// The tile shape is returned both in units of texels and elements. If Format is XG_FORMAT_UNKNOWN, +// then pTileShapeInTexels will be filled with zeros if present. +HRESULT __cdecl XGComputeTileShape( + _In_ XG_RESOURCE_DIMENSION Dimension, + _In_ XG_FORMAT Format, + _In_ UINT32 BytesPerElement, + _In_ UINT32 SampleCount, + _Out_opt_ XG_TILE_SHAPE* pTileShapeInTexels, + _Out_opt_ XG_TILE_SHAPE_ELEMENTS* pTileShapeInElements ); + + +//-------------------------------------------------------------------------------------------------- +// XGComputeBankRotationAddress computes a bank rotated address for a 2D tiled surface. +// The bank rotation index can be an arbitrary value; the rotation offset will be clamped to the +// bank rotation address mask associated with the selected mip level. +// If input parameters are invalid or bank rotation is not supported on the selected mip level, +// then this function returns false. +inline bool XGComputeBankRotationAddress( + _In_ XG_GPU_VIRTUAL_ADDRESS BaseAddress, + _In_ const XG_RESOURCE_LAYOUT* pLayout, + _In_ UINT32 PlaneIndex, + _In_ UINT32 MipLevelIndex, + _In_ UINT32 BankRotationIndex, + _Out_ XG_GPU_VIRTUAL_ADDRESS* pBankRotatedBaseAddress) +{ + // Validate inputs and outputs: + if (pLayout == nullptr || pBankRotatedBaseAddress == nullptr) + { + return false; + } + + // Output the base address as a default return value: + *pBankRotatedBaseAddress = BaseAddress; + + if (PlaneIndex >= pLayout->Planes || MipLevelIndex >= pLayout->MipLevels) + { + return false; + } + + const XG_MIPLEVEL_LAYOUT& MipLayout = pLayout->Plane[PlaneIndex].MipLayout[MipLevelIndex]; + + // Ensure that the base address is properly aligned to the mip level alignment: + if ((BaseAddress % MipLayout.AlignmentBytes) != 0) + { + return false; + } + + // If the mip level does not support bank rotation, then the bit mask will be 0: + if (MipLayout.BankRotationAddressBitMask == 0) + { + return false; + } + + // Compute the bank rotation offset in bytes: + UINT64 RotationOffsetBytes = MipLayout.BankRotationBytesPerSlice * BankRotationIndex; + RotationOffsetBytes &= MipLayout.BankRotationAddressBitMask; + + // Apply the bank rotation offset to the base address and return the value: + *pBankRotatedBaseAddress = BaseAddress + RotationOffsetBytes; + + return true; +} + +//-------------------------------------------------------------------------------------------------- +// Call XGSetHardwareVersion before calling other XG APIs to ensure that XG's behavior matches the +// desired hardware platform behavior. +void __cdecl XGSetHardwareVersion( + _In_ XG_HARDWARE_VERSION Version); + +//-------------------------------------------------------------------------------------------------- +// If you need to call XGSetHardwareVersion at runtime to switch between hardware versions, use +// the XG exclusive locking APIs to synchronize creation of XG texture computer objects. +// +// Exclusive locking is disabled by default. When enabled, XG will acquire a critical section +// within all of the XGCreateTexture*Computer* and XGComputeTexture*Layout APIs. +// +// Before creating any texture computers, and before the D3D device is created, call +// XGEnableExclusiveLocking to enable exclusive locking. +void __cdecl XGEnableExclusiveLocking(_In_ BOOL LocksEnabled); + +// To synchronize calls to XGSetHardwareVersion around XG texture computer creation, use the +// XGEnter/LeaveExclusiveLock APIs to manually acquire and release the XG critical section. +// If exclusive locking is disabled, these APIs will do nothing (and XGEnterExclusiveLock will +// return FALSE). +BOOL __cdecl XGEnterExclusiveLock(); +void __cdecl XGLeaveExclusiveLock(); + +//-------------------------------------------------------------------------------------------------- +// XGInitializeLibrary will perform one-time allocation and initialization of global state within +// XG_XS. It is safe to call multiple times; if XG_XS is already initialized, XGInitializeLibrary +// will return S_FALSE instead of S_OK. +// XGInitializeLibrary is not thread safe; please ensure it is not called at the same time as +// any other XG API. +// A call to XGInitializeLibrary is optional - all texture computer creation methods, as well as +// XGSetHardwareVersion, contain an implicit call to XGInitializeLibrary. +HRESULT __cdecl XGInitializeLibrary(); + +//-------------------------------------------------------------------------------------------------- +// XGTerminateLibrary will deallocate global state within XG_XS. +// It is safe to call multiple times; if XG_XS is already terminated, XGTerminateLibrary will +// return S_FALSE instead of S_OK. +// XGTerminateLibrary is not thread safe; please ensure it is not called at the same time as +// any other XG API. +// Following a call to XGTerminateLibrary, XG_XS can be reinitialized via a call to XGInitializeLibrary +// or implicitly via other XG APIs. +HRESULT __cdecl XGTerminateLibrary(); + +//------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------------------------- +// XGBVHComputer + +struct D3D12_SERIALIZED_RAYTRACING_ACCELERATION_STRUCTURE_HEADER; +struct D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC; +struct ID3D12GraphicsCommandList; +struct ID3D12Device; +typedef UINT64 D3D12_GPU_VIRTUAL_ADDRESS; + +class XGBVHComputer +{ +public: + + virtual ~XGBVHComputer() {} + + //------------------------------------------------------------------------------------------------- + // Increments the refcount and returns the new value. + virtual ULONG __cdecl AddRef() = 0; + + //------------------------------------------------------------------------------------------------- + // Decrements the refcount and returns the new value. If the new value is 0, the object is deleted. + virtual ULONG __cdecl Release() = 0; + + //------------------------------------------------------------------------------------------------- + // Deserialize a BVH "in place". The blob is validated as a serialized BVH and that it has the + // proper 256-byte alignment and that the BVH was built using the current GDK version. This buffer + // should be GPU-visible (e.g. write combined memory.) + // + // pSerializedHeader : A pointer to the start of the serialized BVH blob (256B-aligned) + // vaBvhStartAddress : The resultant address of the start of the BVH (located within the blob) + + virtual HRESULT DeserializeBVH( + _In_ const D3D12_SERIALIZED_RAYTRACING_ACCELERATION_STRUCTURE_HEADER* pSerializedHeader, + _Out_ D3D12_GPU_VIRTUAL_ADDRESS& vaBvhStartAddress) = 0; + + + //------------------------------------------------------------------------------------------------- + // Decompresses a compressed BVH blob to a destination BVH address. + // + // Desc.SourceAccelerationStructureData : Dehydrated BVH blob + // Desc.DestAccelerationStructureData : Rehydrated BVH destination + // Desc.ScratchAccelerationStructureData : Ignored + // Desc.Inputs : Description of input geometry + + virtual HRESULT DecompressBVH( + _In_ const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC& Desc) = 0; + + //------------------------------------------------------------------------------------------------- + // Legacy API (before March 2023). This API does not support geometry transforms. + + virtual HRESULT DecompressBVH( + _In_ const void* CompressedBuffer, + _In_ void* DestinationBuffer, + _In_ UINT64 DestinationBufferSize, + _In_reads_(NumGeometries) const void** VertexBuffers, + _In_reads_(NumGeometries) UINT32* VertexStrides, + _In_reads_(NumGeometries) XG_FORMAT* VertexFormats, + _In_reads_(NumGeometries) const void** IndexBuffers, + _In_reads_(NumGeometries) XG_FORMAT* IndexFormats, + _In_ UINT32 NumGeometries ) = 0; + + //------------------------------------------------------------------------------------------------- + // Validates the Decompressed BVH structure against the Original BVH + // For tests / validation purposes (not performant) + + virtual HRESULT ValidateDecompressedBVH( + _In_ const void* OriginalBVHStructure, + _In_ const void* DecompressedBVHStructure ) = 0; + + //------------------------------------------------------------------------------------------------- + // Determine how much scratch memory is needed to decompress a BVH with the GPU + // + // For each BVH, query the scratch space and provide a pointer to the allocated region in the + // Desc.ScratchAccelerationStructureData. + + virtual UINT64 GetRequiredGpuScratchSizeInBytes( + _In_ UINT NumGeometry) = 0; + + //------------------------------------------------------------------------------------------------- + // Decompress one or more BVHs using the GPU. (Unavailable in the desktop build of XG.) + // + // Requires XGCreateBVHComputer2 and a non-null device. + // + // ScratchAccelerationStructureData must be allocated per BVH. Use GetRequiredGpuScratchSizeInBytes() + // to determine allocation size. + + virtual HRESULT DecompressBVH_BatchedGPU( + _In_ ID3D12GraphicsCommandList* pCommandList, + _In_reads_(NumDescs) const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC Descs[], + _In_ UINT32 NumDescs) = 0; +}; + +//-------------------------------------------------------------------------------------------------- +// XGCreateBVHComputer creates a BVH computer for manipulating BVH structures at runtime + +HRESULT __cdecl XGCreateBVHComputer( + _Out_ XGBVHComputer** ppComputer ); + +//-------------------------------------------------------------------------------------------------- +// Same as above but adds capability for decompressing BVHs on the GPU + +HRESULT __cdecl XGCreateBVHComputer2( + _In_ ID3D12Device* pD3DDevice, + _Out_ XGBVHComputer** ppComputer ); + +//------------------------------------------------------------------------------------------------- + +#define XG_DCC_BLOCK_SIZE_BYTES 256 + +typedef enum XG_DCC_COMPRESSION_LEVEL +{ + XG_DCC_COMPRESSION_LEVEL_64B = 0, + XG_DCC_COMPRESSION_LEVEL_128B_TEXTURE_COMPATIBLE = 1, + XG_DCC_COMPRESSION_LEVEL_256B = 2 +} XG_DCC_COMPRESSION_LEVEL; + +typedef enum XG_DCC_COLOR_TRANSFORM +{ + XG_DCC_COLOR_TRANSFORM_AUTO_TEXTURE_COMPATIBLE = 0, + XG_DCC_COLOR_TRANSFORM_NONE_TEXTURE_COMPATIBLE = 1, + XG_DCC_COLOR_TRANSFORM_LSC_CORRELATED = 2, + XG_DCC_COLOR_TRANSFORM_MSC_CORRELATED = 3 +} XG_DCC_COLOR_TRANSFORM; + +typedef struct XG_DCC_OPTIONS +{ + XG_DCC_COMPRESSION_LEVEL CompressionLevel; + XG_DCC_COLOR_TRANSFORM ColorTransform; +} XG_DCC_OPTIONS; + +//------------------------------------------------------------------------------------------------- + +HRESULT __cdecl XGEncodeDCC( + _In_ UINT32 DataSizeBlocks, + _In_reads_bytes_(DataSizeBlocks * XG_DCC_BLOCK_SIZE_BYTES) const void* pSourceData, + _Out_writes_bytes_(DataSizeBlocks * XG_DCC_BLOCK_SIZE_BYTES) void* pDestData, + _Out_writes_bytes_(DataSizeBlocks) void* pDestKeys, + _Out_writes_opt_(DataSizeBlocks) UINT* pDestCompressedSizes, + _In_ XG_FORMAT Format, + _In_ XG_SWIZZLE_MODE SwizzleMode, + _In_ XG_RESOURCE_DIMENSION Dimension, + _In_ const XG_DCC_OPTIONS* pDccOptions); + +//------------------------------------------------------------------------------------------------- + +HRESULT __cdecl XGDecodeDCC( + _In_ UINT32 DataSizeBlocks, + _In_reads_bytes_(DataSizeBlocks * XG_DCC_BLOCK_SIZE_BYTES) const void* pSourceData, + _In_reads_bytes_(DataSizeBlocks) const void* pSourceKeys, + _Out_writes_bytes_(DataSizeBlocks * XG_DCC_BLOCK_SIZE_BYTES) void* pDestData, + _In_ XG_FORMAT Format, + _In_ XG_SWIZZLE_MODE SwizzleMode, + _In_ XG_RESOURCE_DIMENSION Dimension, + _In_ const XG_DCC_OPTIONS* pDccOptions); + +//------------------------------------------------------------------------------------------------- + +HRESULT __cdecl XGValidateDescriptor( + _In_ UINT32 DescriptorDwordCount, + _In_ const UINT32* pDescriptor, + _In_ UINT32 Flags); + +//------------------------------------------------------------------------------------------------- + +// Transform block compressed texture data for improved compressibility. Use DirectStorage to +// transform the data back to its original form using the SwizzleMode option. +// +HRESULT __cdecl XGShuffleTextureBufferForDirectStorage( + _In_reads_bytes_(BufferSizeBytes) const void* pSourceData, // Source BC texture stream + _Out_writes_bytes_(BufferSizeBytes) void* pDestData, // Destination buffer + _In_ SIZE_T BufferSizeBytes, // Source and destination buffer sizes + _In_ XG_FORMAT TextureFormat, // Only BC1, BC3, BC4, and BC5 will be transformed + _Out_opt_ UINT32* DStorageSwizzleMode); // Returns the swizzle mode selected + +#pragma warning(pop) diff --git a/docs/media/gtavi_finish_setup.jpg b/docs/media/gtavi_finish_setup.jpg new file mode 100644 index 0000000..da888ab Binary files /dev/null and b/docs/media/gtavi_finish_setup.jpg differ diff --git a/docs/media/gtavi_intro_preview.gif b/docs/media/gtavi_intro_preview.gif new file mode 100644 index 0000000..72ad88e Binary files /dev/null and b/docs/media/gtavi_intro_preview.gif differ diff --git a/docs/media/gtavi_legal_policies.jpg b/docs/media/gtavi_legal_policies.jpg new file mode 100644 index 0000000..522800b Binary files /dev/null and b/docs/media/gtavi_legal_policies.jpg differ diff --git a/docs/media/gtavi_on_mac_demo.mp4 b/docs/media/gtavi_on_mac_demo.mp4 new file mode 100644 index 0000000..3ae616b Binary files /dev/null and b/docs/media/gtavi_on_mac_demo.mp4 differ diff --git a/docs/media/gtavi_splash_mural.jpg b/docs/media/gtavi_splash_mural.jpg new file mode 100644 index 0000000..3c99bdb Binary files /dev/null and b/docs/media/gtavi_splash_mural.jpg differ diff --git a/scripts/gen_bcpack_victory_tables.py b/scripts/gen_bcpack_victory_tables.py new file mode 100644 index 0000000..83073c7 --- /dev/null +++ b/scripts/gen_bcpack_victory_tables.py @@ -0,0 +1,152 @@ +"""Turn VIctory's bcpack-tables.bin into Rust constants for XCL. + +bcpack-tables.bin is from the VIctory repo (github.com/Marvisak/VIctory), +victory-formats/bcpack-tables.bin. + +Layout is that of the format's constant tables: 128 x 9 u16 model frequencies, the +rank tables, 512 u16 BC7 control words, then 255 dictionary entries per format. +BC7 entries follow VIctory PR #658: after the two index widths, two bytes repeat +them and there are 16 + 15 signed indices, not 32. + + python -I scripts/gen_bcpack_victory_tables.py +""" +import struct +import sys + +MODELS, BUCKETS, DICTIONARY = 128, 9, 255 + + +class R: + def __init__(self, b): + self.b, self.i = b, 0 + + def take(self, n): + v = self.b[self.i:self.i + n] + self.i += n + return v + + def u8(self): + return self.take(1)[0] + + def u16(self): + return struct.unpack("= 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('