diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a47..ddf9664ba0 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -109,6 +109,23 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i modules::describe_address(addr) ); crate::xlog_error!("{msg}"); + // what happened lately at the title pages the registers point into + if !ctx.is_null() { + let c = &*ctx; + let mut seen: Vec = Vec::new(); + for (n, v) in [("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)] { + let p = v as usize; + if p < 0x1_0000 || seen.contains(&(p & !0xFFFF)) { + continue; + } + seen.push(p & !0xFFFF); + let d = crate::hle::kernelx::pagelog::describe(p); + if !d.is_empty() { + crate::xlog_error!("page of {n}={p:#x}: {d}"); + } + } + crate::xlog_error!("page events so far: {}", crate::hle::kernelx::pagelog::counts()); + } crate::report::write_final(Some(msg)); crate::log::flush(); } diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 94ce0b37d0..bbfa3e27f3 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -38,7 +38,7 @@ pub struct KernelOptions { /// identity (`recomp::pso`): bump it when `pso::direct_compute` / `direct_graphics` change the /// containers. An edit of `gpu/dxil` needs no bump, `XCL_DIRECT_DXIL_SOURCE_ID` is its hash /// (the `gpu/dxil` sources are not in build.rs's translator source hash). -pub const TRANSLATOR_VERSION: u32 = 9; +pub const TRANSLATOR_VERSION: u32 = 10; /// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this /// translator, with the HLSL path as the fallback for what it cannot translate yet. @@ -447,7 +447,8 @@ impl Lw { if stage == Stage::Pixel && uses_pops(insts) { s.enable_rov(); } - let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, cs.is_some()); + let coherent = cs.is_some() && crate::gpu::recomp::needs_coherent_mem(insts); + let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, coherent); let i32 = s.m.i32(); let z = s.m.i32c(0); let mut lw = Lw { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 8f257a043f..9d522391ce 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -68,6 +68,8 @@ 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, + /// compute program needs `globallycoherent` on flat memory windows (`needs_coherent_mem`) + pub coherent_mem: bool, } /// Instructions without an effect in this execution model. @@ -594,6 +596,7 @@ impl Em { dynamic_f16_rm: false, track_frexp_denorm: false, safe_barrier: false, + coherent_mem: false, } } @@ -4658,8 +4661,9 @@ impl Em { h.push_str("RWByteAddressBuffer io : register(u0);\nRWByteAddressBuffer res : register(u1);\n"); // compute work across workgroups (bottom-up BVH builds: atomics, then reading what // other groups wrote) relies on GLC / cache invalidation on the console: keep the flat - // memory coherent across the GPU there; graphics keeps the cached (faster) view - let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" }; + // memory coherent across the GPU only when the program actually uses those; otherwise + // keep the cached (faster) view + let coherent = if self.coherent_mem { "globallycoherent " } else { "" }; let max_win = if self.opt.heap_windows { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; let windows = self.opt.mem_windows.clamp(1, max_win); let _ = writeln!(h, "{coherent}RWByteAddressBuffer mem : register(u2);"); @@ -5127,7 +5131,7 @@ impl Em { } } if windows > 1 { - let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" }; + let coherent = if self.coherent_mem { "globallycoherent " } else { "" }; h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent)); } h diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 2c200c7888..688c45cb72 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -45,7 +45,7 @@ struct DxilIr { impl DxilIr { /// The builder state for `insts` at `entry` (a kernel or a compute program), with one memory - /// window; a compute program's is coherent, as the HLSL path declares it. + /// window; a compute program's is coherent when `needs_coherent_mem` holds, matching the HLSL path. fn new(insts: &[Decoded], wave64: bool, entry: &Entry) -> DxilIr { Self::with(insts, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, entry) } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index d1e7d8bc4e..70a92bc955 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1383,6 +1383,34 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> B out } +/// Does the program require `globallycoherent` flat memory windows (`mem`, `mem1`…)? +/// +/// Compute work that coordinates across workgroups (e.g. bottom-up BVH builds: atomics, +/// then reading what other groups wrote) relies on `GLC`/`DLC`/`SLC`, memory atomics, or +/// cache invalidation on the console. Programs without any of those only access read-only +/// or disjointly written memory within the dispatch, so keeping their flat memory windows +/// un-qualified lets the GPU cache them in L1. +pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool { + insts.iter().any(|d| { + let name = d.inst.name; + if matches!(name, "S_DCACHE_INV" | "S_GL1_INV" | "BUFFER_GL0_INV" | "BUFFER_GL1_INV") { + return true; + } + if name.starts_with("BUFFER_ATOMIC_") + || name.starts_with("GLOBAL_ATOMIC_") + || name.starts_with("FLAT_ATOMIC_") + { + return true; + } + matches!( + d.enc.name, + "ENC_SMEM" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" + ) && ["GLC", "DLC", "SLC"] + .iter() + .any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)) + }) +} + pub fn translate(code: &[u8], opt: &Options) -> Result { let program = code; let normalized; @@ -1433,6 +1461,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } } let mut em = emit::Em::new(opt.clone()); + em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts); em.configure_round_modes(&insts, branches == 0); em.static_ss = constant_samplers(&insts, &leaders); // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b6dd120ff1..1fb2a9a828 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -696,6 +696,21 @@ pub fn compute_user_sgprs(blob: &[u8]) -> Option { } } +/// A console compute shader's thread group size, whether its program is wave64 and the bytes +/// of its RDNA2 code (`XCL_GPU_PROFILE` names a program by them). None: not a console compute +/// shader. +pub fn compute_shape(blob: &[u8]) -> Option<([u32; 3], bool, usize)> { + if let Some(f) = fspx(blob) { + return Some((f.threads, super::detect_wave64(f.code), f.code.len())); + } + let sh = xbox::parse(blob)?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; + let Mode::Compute(cs) = interface(blob, &sh, f)? else { return None }; + let p = f.programs.first()?; + let code = f.data.get(p.offset..p.offset + p.len)?; + Some((cs.threads, super::detect_wave64(code), code.len())) +} + /// The HLSL and profile a console program compiles from at pipeline creation (for /// `xcl shaders --export-hlsl`: compile-time investigations outside a title). pub fn console_hlsl(blob: &[u8], stage: Stage, windows: u32, split_wave64: bool) -> Result<(String, &'static str), String> { diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index ed683350f7..c680fdea68 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1476,22 +1476,39 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result = Vec::new(); + // a D3D12 without heaps over process memory (D3DMetal: E_NOTIMPL): each window is a + // buffer in video memory, filled from the window before the dispatch and copied back + // after it -- (upload, readback) per window + let mut copies: Vec<(ID3D12Resource, ID3D12Resource)> = Vec::new(); for &(base, size) in &arena.windows { - let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void).map_err(|x| format!("OpenExistingHeapFromAddress: {x}"))?; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size as u64, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, - ..Default::default() - }; - let mut mem_buf: Option = None; - dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut mem_buf).map_err(|x| format!("CreatePlacedResource: {x}"))?; - bufs.push(mem_buf.ok_or("arena")?); + let heap: ID3D12Heap = match dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void) { + Ok(h) => h, + Err(x) if x.code() == windows::Win32::Foundation::E_NOTIMPL => { + let up = buffer(dev, size as u64, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).map_err(e)?; + std::ptr::copy_nonoverlapping(base, p as *mut u8, size); + up.Unmap(0, None); + bufs.push(buffer(dev, size as u64, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?); + copies.push((up, buffer(dev, size as u64, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?)); + continue; + } + Err(x) => return Err(format!("OpenExistingHeapFromAddress: {x}")), + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, + ..Default::default() + }; + let mut mem_buf: Option = None; + dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut mem_buf).map_err(|x| format!("CreatePlacedResource: {x}"))?; + bufs.push(mem_buf.ok_or("arena")?); } let mem_buf = bufs[0].clone(); let pso: ID3D12PipelineState = dev @@ -1514,13 +1531,18 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result in_a (sparse VRAM) + arg_table constant 77 (Window 3) record_and_run(1, true); + gpu_wrote(); + // the copy back of what the shader stored lands asynchronously: before a CPU read the + // title's lists are done for, XCL settles it (as in Map and the CPU memory waits) + crate::hle::d3d12x::sparse::settle_readbacks(); for l in 0..64usize { let got = *((out_buf + 4 * l) as *const u32); assert_eq!(got, 1000 + l as u32 + 77, "submit 1 lane {l} mismatch"); @@ -4166,12 +4180,22 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { *((in_b + 4 * 3) as *mut u32) = 9999; crate::hle::d3d12x::console_heap::write(&slot0, &vsharp(in_b)); record_and_run(2, false); + gpu_wrote(); + crate::hle::d3d12x::sparse::settle_readbacks(); for l in 0..64usize { let expected = if l == 3 { 9999 + 13 } else { 5000 + 2 * l as u32 + 13 }; let got = *((out_buf + 4 * l) as *const u32); assert_eq!(got, expected, "submit 2 (mutated sparse descriptor + XMem buffer) lane {l} mismatch"); } + // Submits 3..: a constant the CPU rewrites before every submit reaches the shader each time + for n in 0..40u32 { + *(arg_table as *mut u32) = 100 + n; + record_and_run(3 + n as u64, false); + gpu_wrote(); + assert_eq!(*(out_buf as *const u32), 5000 + 100 + n, "submit {} (constant rewritten in window 3)", 3 + n); + } + // Clean up crate::hle::d3d12x::console_heap::unregister(heap_obj); crate::hle::kernelx::XMemFreeDefault(in_a as *mut _, gfx_attrs); @@ -9027,3 +9051,145 @@ fn gpu_scalar_sext_mulhi_and_vector_i24_sub_co_ci_u64_shifts() { assert_eq!(v[22], subrev, "lane {l} v_subrev_co_ci_u32"); } } + +/// Compute shaders only declare `globallycoherent` on their flat memory windows (`mem`, `mem1`… +/// and `XCL_HEAP_WINDOWS` heap views) when the program uses cross-workgroup coherence: memory +/// atomics, `GLC`/`DLC`/`SLC` memory ops, or cache invalidations. Both the HLSL and direct DXIL +/// backends follow the same predicate. +#[test] +fn compute_globallycoherent_only_when_needed() { + let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let prog = |insts: &[(&str, &str, &[(&str, u64)])]| { + let mut c = Vec::new(); + for &(n, e, f) in insts { + c.extend(enc(n, e, f)); + } + c.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + c + }; + + // Plain compute: SMEM + MUBUF load/store + LDS + s_barrier, no GLC/DLC/SLC/atomics/inv. + let plain = prog(&[ + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0)]), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)]), + ("S_BARRIER", "ENC_SOPP", &[]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 1), ("SADDR", 0)]), + ]); + + let coherent_cases: Vec<(&str, Vec)> = vec![ + ("smem glc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("GLC", 1)])])), + ("smem dlc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("DLC", 1)])])), + ("mubuf glc", prog(&[("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("GLC", 1)])])), + ("global dlc", prog(&[("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0), ("DLC", 1)])])), + ("mubuf slc", prog(&[("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("SLC", 1)])])), + ("buffer_atomic", prog(&[("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128)])])), + ("global_atomic", prog(&[("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("DATA", 2), ("SADDR", 0)])])), + ("flat_atomic", prog(&[("FLAT_ATOMIC_ADD", "ENC_FLAT", &[("VDST", 1), ("ADDR", 2), ("DATA", 4)])])), + ("s_dcache_inv", prog(&[("S_DCACHE_INV", "ENC_SMEM", &[])])), + ("s_gl1_inv", prog(&[("S_GL1_INV", "ENC_SMEM", &[])])), + ("buffer_gl0_inv", prog(&[("BUFFER_GL0_INV", "ENC_MUBUF", &[])])), + ("buffer_gl1_inv", prog(&[("BUFFER_GL1_INV", "ENC_MUBUF", &[])])), + ]; + + for (windows, heap) in [(1u32, false), (2, false), (2, true)] { + let opt = Options { mode: Mode::Compute(cs.clone()), wave64: false, mem_windows: windows, heap_windows: heap, ..Default::default() }; + let t = translate(&plain, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert!(!t.hlsl.contains("globallycoherent"), "plain CS (windows={windows}, heap={heap}) must not emit globallycoherent:\n{}", t.hlsl); + + for (label, code) in &coherent_cases { + let t = translate(code, &opt).unwrap(); + assert!(t.complete(), "{label}: {:?}", t.unsupported_why); + assert!(t.hlsl.contains("globallycoherent"), "{label} (windows={windows}, heap={heap}) must emit globallycoherent"); + if heap { + assert!(t.hlsl.contains("#define XCL_MW globallycoherent RWByteAddressBuffer"), "{label}: heap window accessor must be globallycoherent"); + } + } + } + + // Kernel mode stays non-coherent even with atomics. + let k = translate(&coherent_cases[6].1, &Options { mode: Mode::Kernel, wave64: false, ..Default::default() }).unwrap(); + assert!(!k.hlsl.contains("globallycoherent"), "kernel mode must not emit globallycoherent"); + + // Direct DXIL backend: check the IsGloballyCoherent bit (0x4000) in annotateHandle properties + // (RAW_BUFFER=11 | IsUAV=0x1000 = 4107 vs RAW_BUFFER=11 | IsUAV=0x1000 | IsGloballyCoherent=0x4000 = 20491). + for mw in [1u32, super::HEAP_WINDOWS | 2] { + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: mw, sampler_base: 0 }; + let plain_k = crate::gpu::dxil::kernel::translate_compute(&plain, o, &cs).unwrap(); + let coh_k = crate::gpu::dxil::kernel::translate_compute(&coherent_cases[6].1, o, &cs).unwrap(); + if super::dxc::location().is_ok() { + let plain_dis = crate::gpu::dxil::validate::disassemble(&plain_k.dxil).unwrap(); + let coh_dis = crate::gpu::dxil::validate::disassemble(&coh_k.dxil).unwrap(); + assert!(!plain_dis.contains("i32 20491"), "direct DXIL plain CS (mw={mw:#x}) must not set IsGloballyCoherent:\n{plain_dis}"); + assert!(coh_dis.contains("i32 20491"), "direct DXIL atomic CS (mw={mw:#x}) must set IsGloballyCoherent:\n{coh_dis}"); + } + } +} + +/// Real GPU check of both non-coherent (cached) and coherent (cross-workgroup atomic + GLC) +/// compute shaders across HLSL and direct DXIL. +#[test] +fn gpu_compute_coherent_and_cached_loads() { + if !gpu_ready() { + return; + } + let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + + // 1. Plain cached compute: each thread reads a uniform dword via SMEM (s[0:1] = 0x100) and + // writes (val + group_id * 32 + tid) to mem[0x200 + (group_id * 32 + tid) * 4]. + let mut plain = Vec::new(); + plain.extend(enc("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)])); + plain.extend(enc("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 133)])); // s3 = tgid * 32 + plain.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 3), ("VSRC1", 0)])); // v1 = tgid * 32 + v0 + plain.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 1)])); // v2 = mem[0x100] + idx + plain.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 1)])); // v3 = idx * 4 + plain.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)])); + plain.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0x200)])); + plain.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + + let t_plain = translate(&plain, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t_plain.complete(), "{:?}", t_plain.unsupported_why); + assert!(!t_plain.hlsl.contains("globallycoherent")); + let dxil_plain_hlsl = super::dxc::compile(&t_plain.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil_plain_direct = crate::gpu::dxil::kernel::translate_compute(&plain, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs).unwrap().dxil; + + let mut io = vec![0u32; super::KERNEL_SGPRS]; + io[0] = 0x100; + let mut mem = vec![0u32; 0x400 / 4]; + mem[0x100 / 4] = 0x1234_0000; + for (tag, dxil) in [("hlsl", &dxil_plain_hlsl), ("direct", &dxil_plain_direct)] { + let out = runner::dispatch(dxil, [4, 1, 1], &io, &mem).unwrap(); + for idx in 0..128usize { + assert_eq!(out[(0x200 + idx * 4) / 4], 0x1234_0000 + idx as u32, "{tag} plain cached idx={idx}"); + } + } + + // 2. Cross-workgroup coherent compute: 16 groups of 32 threads atomically increment a shared + // counter at mem[0x100] and record their returned ticket at mem[0x200 + ticket * 4]. + let mut coh = Vec::new(); + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])); // v1 = 0 + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)])); // v2 = 1 + coh.extend(enc("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 1), ("DATA", 2), ("SADDR", 0), ("GLC", 1)])); + coh.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 130), ("VSRC1", 3)])); // v4 = ticket * 4 + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)])); + coh.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 3), ("SADDR", 0x7D), ("OFFSET", 0x200), ("GLC", 1)])); + coh.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + + let t_coh = translate(&coh, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t_coh.complete(), "{:?}", t_coh.unsupported_why); + assert!(t_coh.hlsl.contains("globallycoherent")); + let dxil_coh_hlsl = super::dxc::compile(&t_coh.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil_coh_direct = crate::gpu::dxil::kernel::translate_compute(&coh, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs).unwrap().dxil; + + let mem2 = vec![0u32; (0x200 + 512 * 4) / 4]; + for (tag, dxil) in [("hlsl", &dxil_coh_hlsl), ("direct", &dxil_coh_direct)] { + let out = runner::dispatch(dxil, [16, 1, 1], &io, &mem2).unwrap(); + assert_eq!(out[0x100 / 4], 512, "{tag} coherent cross-group counter"); + for ticket in 0..512usize { + assert_eq!(out[(0x200 + ticket * 4) / 4], ticket as u32, "{tag} coherent ticket={ticket}"); + } + } +} diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index c29522ab39..4fed93037a 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -303,10 +303,24 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items record_into(&up.list, res, subs, l, states, states, &staging, mapped, *base); } up.list.Close().map_err(err)?; - queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(err)?)]); + let list: ID3D12CommandList = windows::core::Interface::cast(&up.list).map_err(err)?; + use crate::hle::d3d12x::queue_probe; + let id = queue_probe::submit("texture-upload", key, &[windows::core::Interface::as_raw(&list)]); + if id != 0 { + queue_probe::event("texture-upload-info", key, 0, id, total, planned.len() as u64); + for (index, copy, _) in &planned { + let (res, subs, _) = &items[*index]; + queue_probe::event("texture-upload-target", key, windows::core::Interface::as_raw(res) as usize, + id, copy.total, subs.len() as u64); + } + } + queue.ExecuteCommandLists(&[Some(list)]); 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)))?; + let signal = queue.Signal(&up.fence, up.value); + queue_probe::signal("texture-fence", key, &up.fence, id, up.value, + signal.as_ref().err().map_or(0, |e| e.code().0)); + signal.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 diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7592d044b0..81ec3907c9 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -14,6 +14,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::{Mutex, OnceLock}; use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; @@ -112,6 +113,8 @@ pub struct Uma { inner: Mutex, /// free ranges of the sparse windows (address → length) and the reservations in them sparse_free: Mutex<(BTreeMap, BTreeMap)>, + /// the committed windows are not the GPU's memory: it has copies of them (`set_shadowed`) + shadowed: AtomicBool, /// XCL's own pool in window 0 for `Arena` blocks: (start, end, free blocks). The title /// cannot take it – a title that commits all of unified memory at start (Unicorn /// Overlord: 2046 of 2048 MB) left no room for draw arguments, and draws were skipped. @@ -300,6 +303,7 @@ impl Uma { win_allocs, inner: Mutex::new(inner), sparse_free: Mutex::new(sparse_free), + shadowed: AtomicBool::new(false), pool: Mutex::new((0, 0, Vec::new())), }; u.reserve_pool(POOL); @@ -384,6 +388,23 @@ impl Uma { len > 0 && self.is_committed(p) && p.checked_add(len - 1).is_some_and(|e| self.window_of(e) == self.window_of(p)) } + /// The GPU could not open the committed windows as heaps (`OpenExistingHeapFromAddress` + /// not implemented: D3DMetal): each has a buffer in video memory instead, a copy that + /// `d3d12x::sparse` keeps in step like a sparse window's tiles. + pub fn set_shadowed(&self) { + self.shadowed.store(true, Ordering::Release); + } + + pub fn shadowed(&self) -> bool { + self.shadowed.load(Ordering::Acquire) + } + + /// Whether the GPU works on a copy of the memory at `p` (a sparse window, or a committed + /// one that is shadowed): what the GPU writes there the CPU sees only after a readback. + pub fn is_gpu_copy(&self, p: usize) -> bool { + self.is_sparse(p) || (self.shadowed() && self.is_committed(p)) + } + /// Address space for a title reservation of `size` bytes in the sparse windows (64 KiB /// aligned, first fit; not committed). Prefers windows 1+ so window 0 stays uncluttered for /// small allocations, falling back to all of the title's sparse space (never `desc_range`). @@ -511,6 +532,7 @@ impl Uma { win_allocs, inner: Mutex::new(inner), sparse_free: Mutex::new(Default::default()), + shadowed: AtomicBool::new(false), pool: Mutex::new((0, 0, Vec::new())), }); } diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index f5ed20cec1..37a4683959 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -32,7 +32,7 @@ struct Backing { impl Backing { unsafe fn free(&self) -> bool { - self.users.is_empty() && self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v) + self.users.is_empty() && self.marks.values().all(|(f, v)| super::real::fence_completed(&f) >= *v) } } @@ -127,7 +127,7 @@ pub fn created_on(list: usize, raw: usize, ty: i32) { } /// `lists` were just submitted to `queue`. -pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { +pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void], submission: u64) { if !enabled() || queue.is_null() { return; } @@ -145,9 +145,10 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { } let (fence, value) = { let (f, v) = s.fences.get_mut(&key).unwrap(); - if q.Signal(&*f, *v + 1).is_err() { - return; - } + let signal = q.Signal(&*f, *v + 1); + super::queue_probe::signal("allocator-fence", key, f, submission, *v + 1, + signal.as_ref().err().map_or(0, |e| e.code().0)); + if signal.is_err() { return; } *v += 1; (f.clone(), *v) }; @@ -399,7 +400,7 @@ mod tests { }; queue.ExecuteCommandLists(&lists); - executed(queue.as_raw(), &[l]); + executed(queue.as_raw(), &[l], 0); done(1); // the title resets its allocator (through the hook: `real::alloc_reset`) … @@ -408,7 +409,7 @@ mod tests { assert_ne!(second, a as usize, "the list still holds its recording: another PC allocator takes the place"); // … and submits the recording again queue.ExecuteCommandLists(&lists); - executed(queue.as_raw(), &[l]); + executed(queue.as_raw(), &[l], 0); done(2); assert!(dev.GetDeviceRemovedReason().is_ok(), "the recording was still there"); @@ -420,7 +421,7 @@ mod tests { }), 0); list.Close().unwrap(); queue.ExecuteCommandLists(&lists); - executed(queue.as_raw(), &[l]); + executed(queue.as_raw(), &[l], 0); done(3); // the next reset: the first PC allocator holds nothing now and is used again diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index da5b15ef42..ffe7815400 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -34,6 +34,46 @@ struct State { uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + res_buf: Option<(ID3D12Resource, u64, usize)>, + res_retired: Vec<(ID3D12Resource, u64, usize)>, + /// rewritten indirect arguments (`scratch_args`): the block, its bytes in use, and the + /// bytes of blocks this recording took + scratch: Option<(ID3D12Resource, u64, usize)>, + scratch_used: u64, + scratch_taken: u64, +} + +/// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its +/// two-pass ExecuteIndirects are skipped) +const SCRATCH_BLOCK: u64 = 1 << 20; +const SCRATCH_CAP: u64 = 16 << 20; +/// Most bytes of buffers kept for reuse (`FREE_RES`) +const FREE_RES_CAP: u64 = 256 << 20; + +static ALLOC_RES: Mutex>>> = Mutex::new(None); +static FREE_RES: Mutex> = Mutex::new(Vec::new()); + +fn hold_res_until_reset(allocator: usize, mut bufs: Vec<(ID3D12Resource, u64, usize)>) { + if bufs.is_empty() || allocator == 0 { + return; + } + ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); +} + +pub(super) fn release_allocator_res(allocator: usize) { + let Some(bufs) = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) else { return }; + let mut free = FREE_RES.lock().unwrap(); + for b in bufs { + let held: u64 = free.iter().map(|f| f.1).sum(); + if pool_keeps(free.len(), held, b.1) { + free.push(b); + } + } +} + +/// Whether `FREE_RES`, holding `count` buffers of `held` bytes, keeps one of `bytes` more. +fn pool_keeps(count: usize, held: u64, bytes: u64) -> bool { + count < 16 && held + bytes <= FREE_RES_CAP } static STATES: Mutex>> = Mutex::new(None); @@ -73,7 +113,8 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { /// recording's memory is the previous allocator's until that one is reset, and pipeline /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { - let (old, blocks) = with(list, |s| { + super::queue_probe::reset(list as usize); + let (old, blocks, res_bufs) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.pso = initial_pso; @@ -82,9 +123,16 @@ 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; - (old, std::mem::take(&mut s.uma)) + // (the scratch blocks are in `res_retired` already) + (s.scratch, s.scratch_used, s.scratch_taken) = (None, 0, 0); + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + (old, std::mem::take(&mut s.uma), res_bufs) }); console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults @@ -123,8 +171,13 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u /// The list is gone. pub(super) fn forget(list: *mut c_void) { - if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { + super::queue_probe::forget(list as usize); + if let Some(mut s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { console_list::hold_until_reset(s.allocator, s.uma); + if let Some(b) = s.res_buf.take() { + s.res_retired.push(b); + } + hold_res_until_reset(s.allocator, s.res_retired); } } @@ -225,6 +278,15 @@ fn note_address(va: u64) { /// command signatures that change root arguments (they need the title's root signature) static ROOT_SIGNATURES: Mutex>> = Mutex::new(None); +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DispatchMeshSig { + companion_dispatch: usize, + byte_stride: u32, + mesh_offset: u32, +} + +static DISPATCH_MESH_SIGS: Mutex>> = Mutex::new(None); + pub(super) fn note_root_changing_signature(sig: usize) { ROOT_SIGNATURES.lock().unwrap().get_or_insert_with(Default::default).insert(sig); } @@ -247,15 +309,457 @@ fn signature_dispatches(sig: usize) -> bool { DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } +pub(super) fn note_dispatch_mesh_signature(sig: usize, companion_dispatch: usize, byte_stride: u32, mesh_offset: u32) { + DISPATCH_MESH_SIGS + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert(sig, DispatchMeshSig { companion_dispatch, byte_stride, mesh_offset }); +} + +fn dispatch_mesh_sig_of(sig: usize) -> Option { + DISPATCH_MESH_SIGS.lock().unwrap().as_ref()?.get(&sig).copied() +} + +unsafe fn emit_uav_barrier(list: &ID3D12GraphicsCommandList, res: Option<&ID3D12Resource>) { + let mut b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(res.cloned()), + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.UAV).pResource); +} + +unsafe fn emit_transition(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }; + list.ResourceBarrier(&[std::ptr::read(&b)]); + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); +} + +unsafe fn default_uav_buffer(dev: &ID3D12Device, bytes: u64, what: &str) -> Result { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + 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, + }; + let mut res: 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 res, + ) + .map_err(|e| format!("{what} ({bytes:#x} B): {e}"))?; + res.ok_or_else(|| format!("null {what}")) +} + +/// Groups of a two-pass dispatch that have a record: one record a group in `cap_bytes` of +/// records of `record_bytes`, and every group in X, the mesh pass's `split` times as many (at most +/// 65 535 a dimension). The compute pass writes record `gid.x` with no bound of its own. +fn record_groups(cap_bytes: u64, record_bytes: u64, split: u32) -> u32 { + (cap_bytes / record_bytes.max(1)).min(65_535 / split.max(1) as u64) as u32 +} + +/// The ExecuteIndirects of a two-pass ExecuteIndirect of `max` commands, each of one command and +/// followed by a UAV barrier on the records: (command, compute pass). Each command's compute pass +/// writes its records from record 0, so the next one goes only after the mesh pass drew them. +fn two_pass_steps(max: u32) -> impl Iterator { + (0..max).flat_map(|k| [(k, true), (k, false)]) +} + +/// The record buffer of this list for `need_bytes` (at most 128 MiB): buffer, address, bytes. +unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64, u64), String> { + let need = need_bytes.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); + if let Some((buf, cap, _dev)) = with(this, |s| s.res_buf.as_ref().filter(|(_, cap, _)| *cap >= need).cloned()) { + let va = buf.GetGPUVirtualAddress(); + return Ok((buf, va, cap)); + } + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= need).map(|i| free.swap_remove(i)) + }; + let entry = match picked { + Some(e) => e, + None => (default_uav_buffer(&dev, need, "two-pass res buffer")?, need, dev_key), + }; + let (buf, cap) = (entry.0.clone(), entry.1); + let va = buf.GetGPUVirtualAddress(); + with(this, |s| { + if let Some(old) = s.res_buf.replace(entry) { + s.res_retired.push(old); + } + }); + Ok((buf, va, cap)) +} + +/// The `io` block of a two-pass stage: its user SGPRs (`compute_pass`: the MS layout) with the +/// argument table at `table_at`, and the high dword of unified memory's base, as the other binds +/// write it (the translated pair picks each access's memory window from it). +fn two_pass_io(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize) -> Vec { + let mut io = match layout { + Some(l) if compute_pass => console_list::user_data_ms(l, args, table_at), + Some(l) => console_list::user_data_gfx(l, args, table_at), + None if compute_pass => { + let mut v = vec![0u32; 16]; + v[8] = table_at as u32; + v[9] = (table_at >> 32) as u32; + v + } + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + io +} + +unsafe fn bind_two_pass_stage( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + real_mesh_pso: usize, + tp: &super::real::TwoPassPso, + res_va: u64, + compute_pass: bool, +) -> Result<(), String> { + // the pair is translated with heap windows when they are on (`pso::mem_windows`): as `bind_abi` + super::list_x::ensure_view_heap(this); + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let windows = super::real::uma_window_vas(); + let first = *windows.first().ok_or("unified memory is not open on the GPU")?; + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let copy = |bytes: &[u8]| -> Result { + 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) + }; + let inline = layout + .as_ref() + .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) + .min(args.len()); + let table_at = copy(&args[inline..])?; + let io = two_pass_io(layout.as_deref(), &args, table_at as u64, compute_pass, u.base()); + let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; + let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); + let rs_raw = if compute_pass { tp.compute_rs } else { tp.mesh_rs } as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs_raw).ok_or("two-pass root signature")?; + let views = [va(io_at), res_va].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); + if compute_pass { + list.SetComputeRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, v); + } + let pso_raw = tp.compute as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass compute pipeline")?; + list.SetPipelineState(pc); + } else { + list.SetGraphicsRootSignature(rs); + for (k, v) in views.enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, v); + } + let pso_raw = real_mesh_pso as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass mesh pipeline")?; + list.SetPipelineState(pc); + } + Ok(()) +} + +/// The pass that rewrites a two-pass ExecuteIndirect's arguments, on XCL's ABI: u0 = `count`, +/// `stride`, `offset` (of the DispatchMesh argument), `split`, `cap` (groups with a record), and +/// where the commands are (u2) and go (u3), in bytes. Each command goes out twice, for the compute +/// pass and then (at `count · stride`) for the mesh pass, with at most `cap` groups, all in X: +/// both passes find a group's record by `gid.x` alone. With a count buffer (u0 dword 7 set: the +/// count at dword 8's byte offset in u4), the commands past its count get no groups: they are run +/// one by one (`two_pass_steps`), so without one. +pub(super) const SCALE_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer src : register(u2); +RWByteAddressBuffer dst : register(u3); +RWByteAddressBuffer cnt : register(u4); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + uint count = io.Load(0), stride = io.Load(4), offset = io.Load(8), split = io.Load(12), cap = io.Load(16); + if (tid >= count) return; + uint live = io.Load(28) != 0u ? min(count, cnt.Load(io.Load(32))) : count; + uint s = io.Load(20) + tid * stride, d = io.Load(24) + tid * stride, m = d + count * stride; + for (uint i = 0u; i < stride; i += 4u) { + uint w = src.Load(s + i); + dst.Store(d + i, w); + dst.Store(m + i, w); + } + uint3 g = src.Load3(s + offset); + uint n = 0u; + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { + n = min(g.x, cap); + n = g.y > cap / n ? cap : n * g.y; + n = g.z > cap / n ? cap : n * g.z; + } + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); +} +"#; + +unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: Mutex>> = Mutex::new(None); + let key = dev.as_raw() as usize; + if let Some(pair) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let dxil = crate::gpu::recomp::dxc::compile_cached(SCALE_ARGS_HLSL, "main", "cs_6_6")?.0; + let rs = crate::gpu::recomp::pso::abi_root_signature(dev, false)?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("scale pso create: {e}"))?; + CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + +/// `bytes` of this recording's scratch blocks (COMMON between uses): the block and the offset. +/// Past `SCRATCH_CAP` a recording gets no more. +unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let bytes = bytes.next_multiple_of(256); + if let Some(r) = with(this, |s| { + let (b, cap, _) = s.scratch.as_ref()?; + (s.scratch_used + bytes <= *cap).then(|| { + s.scratch_used += bytes; + (b.clone(), s.scratch_used - bytes) + }) + }) { + return Ok(r); + } + let size = bytes.max(SCRATCH_BLOCK); + let remaining = SCRATCH_CAP.saturating_sub(with(this, |s| s.scratch_taken)); + if size > remaining { + return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); + } + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= size && *cap <= remaining).map(|i| free.swap_remove(i)) + }; + let block = match picked { + Some(e) => e, + None => (default_uav_buffer(dev, size, "two-pass argument scratch")?, size, dev_key), + }; + let b = block.0.clone(); + with(this, |s| { + s.scratch_taken += block.1; + s.scratch_used = bytes; + s.scratch = Some(block.clone()); + s.res_retired.push(block); + }); + Ok((b, 0)) +} + +/// The arguments of `max` commands at UMA address `src`, rewritten for the two passes +/// (`SCALE_ARGS_HLSL`) into a scratch block: the block (INDIRECT_ARGUMENT until the caller puts +/// it back to COMMON) and where the compute pass's commands are; the mesh pass's follow them. +/// +/// They are read through the memory window over them, as translated shaders read memory, not +/// through the title's buffer: its state on the PC is the title's and not known here. So is the +/// count (`count`: its UMA address, when the title gave a count buffer). +#[allow(clippy::too_many_arguments)] +unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, count: Option, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32) -> Result<(ID3D12Resource, u64), String> { + let dev = super::real::list_device(this).ok_or("no device")?; + let (rs, pso) = scale_indirect_pipeline(&dev)?; + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let commands = (max as u64).saturating_mul(stride as u64); + super::real::uma_window_buffer(src, commands as usize).ok_or("the indirect arguments are not in one memory window")?; + let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + let count_va = match count { + Some(p) => { + super::real::uma_window_buffer(p, 4).ok_or("the indirect count is not in a memory window")?; + Some(super::real::uma_va_of(p).ok_or("unified memory is not open on the GPU")?) + } + None => None, + }; + let (dst, dst_off) = scratch_args(this, &dev, commands.saturating_mul(2))?; + let consts: Vec = [max, stride, mesh_offset, split, cap, 0, 0, count_va.is_some() as u32, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); + let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + emit_uav_barrier(list, None); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, consts_va); + list.SetComputeRootUnorderedAccessView(2, src_va); + list.SetComputeRootUnorderedAccessView(3, dst.GetGPUVirtualAddress() + dst_off); + if let Some(va) = count_va { + list.SetComputeRootUnorderedAccessView(4, va); + } + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + Ok((dst, dst_off)) +} + +pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { + type PcDm = unsafe extern "system" fn(*mut c_void, u32, u32, u32); + let pc_dm: PcDm = std::mem::transmute(super::real::orig_fn(this, 79)); + let raw_pso = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(raw_pso); + if let Some(tp) = super::real::two_pass_of(pso) { + let groups = x.saturating_mul(y).saturating_mul(z); + if groups == 0 { + return; + } + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let record_bytes = tp.record.record_dwords() as u64 * 4; + let need = (groups as u64).saturating_mul(record_bytes); + let run = (|| -> Result<(), String> { + let (res_buf, res_va, cap) = ensure_res_buffer(this, need)?; + let n = groups.min(record_groups(cap, record_bytes, tp.mesh_groups_per_record)); + if n == 0 { + return Err(format!("a record of {record_bytes} B does not fit the record buffer")); + } + if n < groups { + 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: two-pass DispatchMesh of {groups} groups: {} past the record buffer dropped", groups - n); + } + } + bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + list.Dispatch(n, 1, 1); + emit_uav_barrier(list, Some(&res_buf)); + bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + pc_dm(this, n * tp.mesh_groups_per_record, 1, 1); + emit_uav_barrier(list, Some(&res_buf)); + Ok(()) + })(); + match run { + Ok(()) => { + super::queue_probe::op(this as usize, "mesh-direct", pso, [x, y, z]); + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass DispatchMesh #{n} ({groups} groups, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_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: two-pass DispatchMesh skipped: {e}"); + } + } + } + return; + } + if super::pso_async::is_pending(raw_pso) { + count(DRAWS_SKIPPED); + return; + } + 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); + } + count(DRAWS_PC); + pc_dm(this, x, y, z); +} + /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a /// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root /// arguments themselves cannot be – skipped, logged) pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); - let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + let raw_pso = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(raw_pso); + // where the commands are in unified memory (a console buffer's offsets are the title's) + let commands_at = super::real::console_buffer(args).map(|(p, n)| (p + args_off as usize, n.saturating_sub(args_off as usize))); + let count_at = super::real::console_buffer(count_buf).filter(|&(_, n)| count_off as usize + 4 <= n).map(|(p, _)| p + count_off as usize); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); + if let Some(tp) = super::real::two_pass_of(pso) { + if let Some(msig) = dispatch_mesh_sig_of(sig) { + let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + let run = (|| -> Result<(), String> { + if max == 0 || args == 0 { + return Ok(()); + } + let commands = max as usize * msig.byte_stride as usize; + let src = match commands_at { + Some((p, n)) if commands <= n => p, + _ => return Err("its arguments are not in a console buffer in unified memory".into()), + }; + let record_bytes = tp.record.record_dwords() as u64 * 4; + let (res_buf, res_va, cap) = ensure_res_buffer(this, 32 << 20)?; + let cap = record_groups(cap, record_bytes, tp.mesh_groups_per_record); + if cap == 0 { + return Err(format!("a record of {record_bytes} B does not fit the record buffer")); + } + let count = match (count_buf, count_at) { + (0, _) => None, + (_, Some(p)) => Some(p), + _ => return Err("its count is not in a console buffer in unified memory".into()), + }; + // the groups past the record buffer, and the commands past the count, are dropped + // on the GPU (`SCALE_ARGS_HLSL`) + let (scaled, at) = make_scaled_args_buffer(this, list, src, count, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap)?; + let passes = (|| -> Result<(), String> { + for (k, compute) in two_pass_steps(max) { + bind_two_pass_stage(this, list, pso, &tp, res_va, compute)?; + let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; + pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); + emit_uav_barrier(list, Some(&res_buf)); + } + Ok(()) + })(); + emit_transition(list, &scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + passes + })(); + match run { + Ok(()) => { + super::queue_probe::op(this as usize, "mesh-indirect", pso, [max, 0, 0]); + count(DRAWS); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: two-pass ExecuteIndirect(DispatchMesh) #{n} (max {max}, split {}, kind {})", tp.mesh_groups_per_record, tp.kind); + } + } + Err(e) => { + count(DRAWS_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: two-pass ExecuteIndirect skipped: {e}"); + } + } + } + return; + } + } + 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 @@ -287,7 +791,10 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { list.SetGraphicsRootSignature(r); } - return fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); + let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::PcIndirect, [max, 0, 0]); + fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); + super::gpu_profile::end(this, t); + return; } if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -300,7 +807,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us match bind_abi(this, list, pso, gfx) { Ok(()) => { count(if gfx { DRAWS } else { DISPATCHES }); - fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) + let t = super::gpu_profile::begin(this, pso, if gfx { super::gpu_profile::Kind::IndirectDraw } else { super::gpu_profile::Kind::IndirectDispatch }, [max, 0, 0]); + fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); + super::gpu_profile::end(this, t); } Err(e) => { count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); @@ -444,11 +953,12 @@ fn cpu_rect_expansion(pso: usize) -> bool { pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); if let Some(list) = graphics_bound(this) { - if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { - return; + let t = super::gpu_profile::begin(this, with(this, |s| s.pso), super::gpu_profile::Kind::Draw, [vertices, instances, 0]); + if !draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { + super::list_x::sync_title_buffers(this, None, first_vertex, vertices, if first_instance != 0 { instances.max(2) } else { instances }); + list.DrawInstanced(vertices, instances, first_vertex, first_instance); } - super::list_x::sync_title_buffers(this, None, first_vertex, vertices, if first_instance != 0 { instances.max(2) } else { instances }); - list.DrawInstanced(vertices, instances, first_vertex, first_instance); + super::gpu_profile::end(this, t); } } @@ -486,7 +996,10 @@ pub(super) unsafe fn emit_prepared_indexed_draw( base_vertex: i32, first_instance: u32, ) { + let this = list.as_raw(); + let t = super::gpu_profile::begin(this, with(this, |s| s.pso), super::gpu_profile::Kind::Draw, [indices, instances, 0]); list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); + super::gpu_profile::end(this, t); } /// Before a draw: with a translated pipeline its ABI root signature and the kept graphics @@ -935,7 +1448,9 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis trace_fullscreen(this, pso, [x, y, z]); } bind_abi(this, list, pso, false)?; + let t = super::gpu_profile::begin(this, pso, super::gpu_profile::Kind::Dispatch, [x, y, z]); list.Dispatch(x, y, z); + super::gpu_profile::end(this, t); Ok(()) } @@ -947,6 +1462,11 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; + // shadowed unified memory whose sparse windows could not be made (no reserved resources + // either): descriptor tables are read from window 0, and a null root descriptor is not bound + 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()) }); // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) let copy = |bytes: &[u8]| -> Result { @@ -1531,4 +2051,367 @@ void main(uint t : SV_GroupIndex) { let _ = pso_async::released(standin); } } + + #[test] + fn dispatch_mesh_signature_tracking_returns_companion_and_layout() { + let sig = 0x7400_0001usize; + let companion = 0x7400_0002usize; + assert_eq!(dispatch_mesh_sig_of(sig), None); + note_dispatch_mesh_signature(sig, companion, 28, 16); + assert_eq!( + dispatch_mesh_sig_of(sig), + Some(DispatchMeshSig { companion_dispatch: companion, byte_stride: 28, mesh_offset: 16 }) + ); + DISPATCH_MESH_SIGS.lock().unwrap().as_mut().unwrap().remove(&sig); + assert_eq!(dispatch_mesh_sig_of(sig), None); + } + + #[test] + fn two_pass_io_carries_the_unified_memory_base() { + use crate::gpu::recomp::{IO_UMA_BASE_HI, KERNEL_SGPRS}; + let base = 0x4_0000_0000usize; + for compute_pass in [true, false] { + let io = two_pass_io(None, &[], 0x4_1234_5600, compute_pass, base); + assert_eq!(io.len(), KERNEL_SGPRS); + assert_eq!(io[IO_UMA_BASE_HI], 4, "compute pass {compute_pass}"); + } + let io = two_pass_io(None, &[], 0x4_1234_5600, true, base); + assert_eq!((io[8], io[9]), (0x1234_5600, 4)); + } + + #[test] + fn two_pass_groups_stay_inside_the_record_buffer() { + // #304's transform record: 11 908 dwords + let record = 11_908 * 4; + assert_eq!(record_groups(32 << 20, record, 1), 704); + assert_eq!(record_groups(128 << 20, record, 1), 2817); + // the mesh pass's groups, `split` a record, all in X + assert_eq!(record_groups(1 << 30, 64, 7), 65_535 / 7); + assert_eq!(record_groups(1 << 20, 2 << 20, 1), 0); + } + + /// `SCALE_ARGS_HLSL` on `commands` (dwords each, the DispatchMesh argument at dword 1): + /// the compute pass's and the mesh pass's commands. + fn scale_args(commands: &[[u32; 4]], split: u32, cap: u32) -> Option<(Vec<[u32; 4]>, Vec<[u32; 4]>)> { + scale_args_counted(commands, split, cap, None) + } + + /// `scale_args` with a count buffer holding `count` + fn scale_args_counted(commands: &[[u32; 4]], split: u32, cap: u32, count: Option) -> Option<(Vec<[u32; 4]>, Vec<[u32; 4]>)> { + use crate::gpu::recomp::runner; + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return None; + } + let dxil = crate::gpu::recomp::dxc::compile(SCALE_ARGS_HLSL, "main", "cs_6_6", &[]).unwrap(); + let n = commands.len(); + let (src, dst) = (0u32, 256u32); + let mut mem: Vec = commands.iter().flatten().copied().collect(); + mem.resize(64 + 2 * 4 * n, 0xDEAD); + // the count at dword 60 (u4 is the same memory in the runner) + assert!(4 * n <= 60); + mem[60] = count.unwrap_or(0); + let io = [n as u32, 16, 4, split, cap, src, dst, count.is_some() as u32, 240]; + let out = runner::dispatch(&dxil, [(n as u32).div_ceil(64), 1, 1], &io, &mem).unwrap(); + let cmd = |k: usize| [out[64 + 4 * k], out[65 + 4 * k], out[66 + 4 * k], out[67 + 4 * k]]; + Some(((0..n).map(cmd).collect(), (n..2 * n).map(cmd).collect())) + } + + #[test] + fn gpu_indirect_two_pass_groups_stay_inside_the_record_buffer() { + let Some((compute, mesh)) = scale_args(&[[7, 100, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]], 2, 10) else { return }; + assert_eq!(compute, [[7, 10, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]]); + assert_eq!(mesh, [[7, 20, 1, 1], [8, 6, 1, 1], [9, 0, 1, 1]]); + } + + #[test] + fn gpu_indirect_two_pass_groups_go_in_x() { + let commands = [[1, 1, 2, 1], [2, 2, 3, 4], [3, 300, 300, 1], [4, 5, 0, 2], [5, 70_000, 70_000, 70_000], [6, 1000, 1, 1], [7, 5000, 1, 1], [8, 5000, 1, 0]]; + let Some((compute, mesh)) = scale_args(&commands, 3, 1000) else { return }; + assert_eq!(compute, [[1, 2, 1, 1], [2, 24, 1, 1], [3, 1000, 1, 1], [4, 0, 1, 1], [5, 1000, 1, 1], [6, 1000, 1, 1], [7, 1000, 1, 1], [8, 0, 1, 1]]); + assert_eq!(mesh, [[1, 6, 1, 1], [2, 72, 1, 1], [3, 3000, 1, 1], [4, 0, 1, 1], [5, 3000, 1, 1], [6, 3000, 1, 1], [7, 3000, 1, 1], [8, 0, 1, 1]]); + } + + #[test] + fn freed_two_pass_buffers_kept_for_reuse_are_capped() { + assert!(pool_keeps(0, 0, 128 << 20)); + assert!(pool_keeps(1, 128 << 20, 128 << 20)); + assert!(!pool_keeps(2, 256 << 20, 4 << 20)); + assert!(!pool_keeps(16, 0, 1 << 20)); + } + + #[test] + fn gpu_two_pass_argument_scratch_is_shared_and_capped() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let mut dev: Option = None; + if unsafe { 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 list = 0x7500_0001usize as *mut c_void; + unsafe { + // small rewrites share one block + let (a, at_a) = scratch_args(list, &dev, 100).unwrap(); + let (b, at_b) = scratch_args(list, &dev, 300).unwrap(); + assert_eq!((a.as_raw(), at_a), (b.as_raw(), 0)); + assert_eq!(at_b, 256); + // a recording takes at most SCRATCH_CAP of blocks + let mut taken = 1; + while scratch_args(list, &dev, SCRATCH_BLOCK).is_ok() { + taken += 1; + assert!(taken <= SCRATCH_CAP / SCRATCH_BLOCK, "past the cap"); + } + assert!(with(list, |s| s.scratch_taken) <= SCRATCH_CAP); + // the next recording starts again + reset(list, 0, 0); + assert!(scratch_args(list, &dev, SCRATCH_BLOCK).is_ok()); + } + forget(list); + } + + #[test] + fn gpu_indirect_two_pass_commands_past_the_count_get_no_groups() { + let commands = [[1, 3, 1, 1], [2, 2, 1, 1], [3, 4, 1, 1]]; + let Some((compute, mesh)) = scale_args_counted(&commands, 2, 1000, Some(2)) else { return }; + assert_eq!(compute, [[1, 3, 1, 1], [2, 2, 1, 1], [3, 0, 1, 1]]); + assert_eq!(mesh, [[1, 6, 1, 1], [2, 4, 1, 1], [3, 0, 1, 1]]); + let Some((compute, _)) = scale_args_counted(&commands, 2, 1000, Some(7)) else { return }; + assert_eq!(compute, [[1, 3, 1, 1], [2, 2, 1, 1], [3, 4, 1, 1]]); + } + + /// Commands of one two-pass ExecuteIndirect run in `two_pass_steps` order on the GPU, with + /// stand-ins for the two passes: the "compute pass" writes each group's record (from record 0) + /// with its command's constant, the "mesh pass" copies the records it reads out by command. + #[test] + fn gpu_two_pass_indirect_commands_keep_their_own_records() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + let src = r#" +#define RS "RootConstants(num32BitConstants=1, b0), UAV(u0), UAV(u1)" +cbuffer C : register(b0) { uint v; }; +RWByteAddressBuffer rec : register(u0); +RWByteAddressBuffer o : register(u1); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void cs(uint3 g : SV_GroupID) { rec.Store(g.x * 4u, v); } +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u)); } +"#; + // (constant, groups) of each command + let commands = [(1u32, 3u32), (2, 2), (3, 4)]; + 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 cs = crate::gpu::recomp::dxc::compile(src, "cs", "cs_6_6", &[]).unwrap(); + let ms = crate::gpu::recomp::dxc::compile(src, "ms", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &cs).unwrap(); + let pso = |dxil: &[u8]| -> ID3D12PipelineState { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }; + dev.CreateComputePipelineState(&desc).unwrap() + }; + let (pass1, pass2) = (pso(&cs), pso(&ms)); + let args = [ + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, + Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { RootParameterIndex: 0, DestOffsetIn32BitValues: 0, Num32BitValuesToSet: 1 } }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }, + ]; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 2, pArgumentDescs: args.as_ptr(), NodeMask: 0 }, &rs, &mut sig).unwrap(); + let sig = sig.unwrap(); + let buffer = |bytes: u64, cpu: bool| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = if cpu { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + let (indirect, rec, out) = (buffer(256, true), buffer(256, false), buffer(1024, true)); + let map = |b: &ID3D12Resource| -> *mut u32 { + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).unwrap(); + p as *mut u32 + }; + let (a, o) = (map(&indirect), map(&out)); + for (k, &(v, x)) in commands.iter().enumerate() { + std::ptr::copy_nonoverlapping([v, x, 1, 1].as_ptr(), a.add(4 * k), 4); + } + std::ptr::write_bytes(o, 0, 256); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, &pass1).unwrap(); + emit_transition(&list, &indirect, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(1, rec.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress()); + for (k, compute) in two_pass_steps(commands.len() as u32) { + list.SetPipelineState(if compute { &pass1 } else { &pass2 }); + list.ExecuteIndirect(&sig, 1, &indirect, k as u64 * 16, None::<&ID3D12Resource>, 0); + emit_uav_barrier(&list, Some(&rec)); + } + emit_transition(&list, &indirect, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + for &(v, x) in &commands { + let got: Vec = (0..x).map(|g| *o.add((v * 16 + g) as usize)).collect(); + assert_eq!(got, vec![v; x as usize], "the records the mesh pass of command {v} read"); + } + indirect.Unmap(0, None); + out.Unmap(0, None); + } + } + + /// With heap windows the two-pass programs read the memory windows from the shared heap + /// (`pso::mem_windows`): both passes' binds set it on a list that has none, as `bind_abi` does. + /// (Heap windows are opt-in: run with `XCL_HEAP_WINDOWS=1`, else skipped.) + #[test] + fn two_pass_binds_set_the_shared_view_heap() { + use crate::gpu::recomp::runner::skip_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + if !crate::gpu::recomp::pso::heap_windows() { + skip_test("no heap windows (opt-in: XCL_HEAP_WINDOWS=1)"); + return; + } + #[repr(C)] + struct FakeList { + vt: *const usize, + calls: Mutex>>, + } + unsafe extern "system" fn fake_set_heaps(this: *mut c_void, n: u32, heaps: *const usize) { + let v = if heaps.is_null() { Vec::new() } else { std::slice::from_raw_parts(heaps, n as usize).to_vec() }; + (*(this as *const FakeList)).calls.lock().unwrap().push(v); + } + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + // the shared heap with a window view, unless the backend made it already + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1 << 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut window: 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 window).unwrap(); + let window = window.unwrap(); + if super::super::console_heap::global_heap().is_none() && !super::super::console_heap::set_window_views(&dev, &[(window.as_raw() as usize, 1 << 16)]) { + skip_test("no shared heap"); + return; + } + let g = super::super::console_heap::global_heap().unwrap().as_raw() as usize; + let mut orig_vt = [0usize; 64]; + orig_vt[28] = fake_set_heaps as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeList { vt: ext_vt.as_ptr().add(1), calls: Mutex::new(Vec::new()) }); + let this = &*fake as *const FakeList as *mut c_void; + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this).unwrap(); + // no root signatures: the bind stops before it records anything else + let tp = super::super::real::TwoPassPso { compute: 0, compute_rs: 0, mesh_rs: 0, record: Default::default(), mesh_groups_per_record: 1, kind: "MS" }; + for compute_pass in [true, false] { + super::super::list_x::set_descriptor_heaps_x(this, 0, std::ptr::null()); + assert!(super::super::list_x::bound_heaps(this, false).is_empty()); + assert!(bind_two_pass_stage(this, list, 0, &tp, 0, compute_pass).is_err()); + assert_eq!(super::super::list_x::bound_heaps(this, false), vec![g], "compute pass {compute_pass}: the shared heap is bound"); + assert_eq!(fake.calls.lock().unwrap().last(), Some(&vec![g]), "compute pass {compute_pass}"); + } + super::super::list_x::bound_heaps(this, true); + forget(this); + } + } + + + /// A reusable block must fit the recording's remaining budget, not just its request. + #[test] + fn gpu_two_pass_pooled_scratch_respects_remaining_budget() { + use windows::Win32::Graphics::{Direct3D::D3D_FEATURE_LEVEL_12_0, Dxgi::*}; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); + let wanted = std::env::var("XCL_ADAPTER").unwrap_or_default(); + let mut chosen = None; + for i in 0.. { + let Ok(adapter) = factory.EnumAdapters1(i) else { break }; + let desc = adapter.GetDesc1().unwrap(); + let end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..end]); + if !wanted.is_empty() && !name.contains(&wanted) { continue; } + let mut dev: Option = None; + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).is_ok() { + chosen = Some((name, dev.unwrap())); + break; + } + } + let Some((name, dev)) = chosen else { + crate::gpu::recomp::runner::skip_test("no selected D3D12 adapter"); + return; + }; + println!("POOLED_SCRATCH_ADAPTER={name}"); + let key = dev.as_raw() as usize; + // These are state keys only; scratch_args does not call through a list pointer. + let (consumer, producer, empty) = (0x7500_1011usize as *mut c_void, 0x7500_1012usize as *mut c_void, 0x7500_1013usize as *mut c_void); + let allocator = 0x7500_1014usize; + let first = scratch_args(consumer, &dev, SCRATCH_BLOCK).unwrap(); + assert_eq!(with(consumer, |s| s.scratch_taken), SCRATCH_BLOCK); + reset(producer, allocator, 0); + let large = scratch_args(producer, &dev, SCRATCH_CAP).unwrap(); + assert_eq!(large.0.GetDesc().Width, SCRATCH_CAP); + reset(producer, 0, 0); + release_allocator_res(allocator); + let second = scratch_args(consumer, &dev, SCRATCH_BLOCK).unwrap(); + let taken = with(consumer, |s| s.scratch_taken); + println!("POOLED_SCRATCH taken={taken} second_bytes={} cap={SCRATCH_CAP}", second.0.GetDesc().Width); + // If it was too large for consumer, the cached block remains reusable by an empty recording. + let reused = if taken <= SCRATCH_CAP { + let r = scratch_args(empty, &dev, SCRATCH_CAP).unwrap(); + assert_eq!(r.0.as_raw(), large.0.as_raw()); + assert_eq!(with(empty, |s| s.scratch_taken), SCRATCH_CAP); + assert!(scratch_args(empty, &dev, 256).is_err()); + Some(r) + } else { None }; + drop((first, second, large, reused)); + for list in [consumer, producer, empty] { forget(list); } + FREE_RES.lock().unwrap().retain(|(_, _, d)| *d != key); + assert!(taken <= SCRATCH_CAP, "pooled block exceeds recording budget: {taken} > {SCRATCH_CAP}"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 3a3480f18b..8628541a06 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -74,6 +74,7 @@ pub struct Layout { pub size: u32, pub inline: u32, pub inline_gfx: u32, + pub inline_ms: u32, } /// User SGPRs the console's compiler gives root arguments: compute s4…s15 (s0…s3 are the @@ -81,8 +82,10 @@ pub struct Layout { /// fetch shader) – both measured on its output (`tests/console_shaders.rs`). const INLINE_SGPRS: u32 = 12; const INLINE_SGPRS_GFX: u32 = 24; +const INLINE_SGPRS_MS: u32 = 16; const FIRST_SGPR: usize = 4; const FIRST_SGPR_GFX: usize = 8; +const FIRST_SGPR_MS: usize = 16; /// Most bytes of root arguments a layout has. The PC's limit is 64 DWORDs (256 bytes: a /// constant or a table 1, a root descriptor 2, D3D12 "Root Signature Limits"); the console's /// is not known, so 16 times that. A malformed blob (a count of 0x3FFF_FFFF constants) gets no @@ -104,7 +107,7 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { // the parameters go into user SGPRs in order while each fits whole; from the first one // that does not, the rest go to the table (packed from its start) – as the console's // compiler expects them (HANDOFF: root argument binding) - let (mut spilled, mut spilled_gfx) = (false, false); + let (mut spilled, mut spilled_gfx, mut spilled_ms) = (false, false, false); for k in 0..n { let (ty, pay) = (r(poff + 12 * k)?, r(poff + 12 * k + 8)? as usize); let p = match ty { @@ -127,6 +130,10 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { if !spilled_gfx { l.inline_gfx += bytes; } + spilled_ms |= l.inline_ms + bytes > 4 * INLINE_SGPRS_MS; + if !spilled_ms { + l.inline_ms += bytes; + } l.size = size; l.params.push(p); } @@ -170,6 +177,19 @@ pub fn user_data_gfx(l: &Layout, args: &[u8], table_at: u64) -> Vec { sgprs(FIRST_SGPR_GFX, l.inline_gfx, args, table_at) } +pub fn user_data_ms(l: &Layout, args: &[u8], table_at: u64) -> Vec { + let mut s = vec![0u32; FIRST_SGPR_MS]; + s[8] = table_at as u32; + s[9] = (table_at >> 32) as u32; + let inline = &args[..(l.inline_ms as usize).min(args.len())]; + s.extend(inline.chunks(4).map(|c| { + let mut w = [0u8; 4]; + w[..c.len()].copy_from_slice(c); + u32::from_le_bytes(w) + })); + s +} + fn sgprs(first: usize, inline: u32, args: &[u8], table_at: u64) -> Vec { let mut s = vec![0u32; first]; s[0] = table_at as u32; @@ -331,6 +351,7 @@ pub fn allocator_reset(allocator: *mut c_void) { if let Some(b) = blocks { unsafe { free_uma(&b) }; } + super::bind::release_allocator_res(allocator as usize); } fn with_list(obj: usize, f: impl FnOnce(&mut ListState) -> R) -> Option { @@ -679,6 +700,7 @@ pub struct Translation { /// Turn the recorded console commands into commands on the PC list and close it. pub unsafe fn close(obj: *mut c_void) -> Result { let obj = obj as usize; + super::title_textures::note_list_closed(obj); let mut guard = LISTS.lock().unwrap(); let st = guard.as_mut().and_then(|m| m.get_mut(&obj)).ok_or("not an XCL console list")?; if let Some(last) = st.chunks.last_mut() { @@ -854,7 +876,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let raw = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; list.SetPipelineState(pc); + let t = super::gpu_profile::begin(list.as_raw(), real, super::gpu_profile::Kind::Dispatch, [x, y, z]); list.Dispatch(x, y, z); + super::gpu_profile::end(list.as_raw(), t); out.dispatches += 1; } _ => out.skipped_dispatches += 1, @@ -1016,4 +1040,19 @@ mod tests { let args: Vec = [1u32, 2, 0x5000, 4, 0x80].iter().flat_map(|w| w.to_le_bytes()).collect(); assert_eq!(user_data_gfx(&l, &args, 0x200), vec![0x200, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0x5000, 4, 0x80]); } + + #[test] + fn mesh_arguments_go_in_user_sgprs_from_s16() { + let inline = |p: &[(u32, u32)]| layout_from_blob(&rts0(p)).unwrap().inline_ms; + assert_eq!(inline(&[(1, 2), (2, 0), (0, 0)]), 20); + assert_eq!(inline(&[(1, 14), (2, 0)]), 64); + assert_eq!(inline(&[(1, 15), (2, 0)]), 60); + assert_eq!(inline(&[(1, 17), (2, 0)]), 0); + let l = layout_from_blob(&rts0(&[(1, 2), (2, 0), (0, 0)])).unwrap(); + let args: Vec = [1u32, 2, 0x5000, 4, 0x80].iter().flat_map(|w| w.to_le_bytes()).collect(); + let got = user_data_ms(&l, &args, 0x7_0000_0200); + assert_eq!(got[8], 0x200); + assert_eq!(got[9], 7); + assert_eq!(&got[16..], &[1, 2, 0x5000, 4, 0x80]); + } } diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 3fedb32253..53525f2657 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -60,13 +60,13 @@ fn worker() -> &'static Mutex> { let spawned = std::thread::Builder::new().name("xcl-cpu-writes".into()).spawn(move || unsafe { let event = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); for job in rx { - if job.fence.GetCompletedValue() < job.value && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { + if super::real::fence_completed(&job.fence) < job.value && job.fence.SetEventOnCompletion(job.value, HANDLE(event as *mut c_void)).is_ok() { th::WaitForSingleObject(event, WAIT_MS); - if job.fence.GetCompletedValue() < job.value { + if super::real::fence_completed(&job.fence) < job.value { 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: {k} writes after the GPU so far done although their queue had not got there after {WAIT_MS} ms (fence at {}, wanted {}; {} writes)", job.fence.GetCompletedValue(), job.value, job.writes.len()); + crate::xlog_warn!("D3D12.X: {k} writes after the GPU so far done although their queue had not got there after {WAIT_MS} ms (fence at {}, wanted {}; {} writes)", super::real::fence_completed(&job.fence), job.value, job.writes.len()); } } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 8dec7b1c27..ec9fd0bfa4 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1029,6 +1029,19 @@ pub(super) unsafe extern "system" fn get_copyable_footprints_x( /// device #41 CreateCommandSignature(desc, root signature, riid, signature): the console's /// DispatchX argument (105) is a PC Dispatch; the root signature only goes with arguments /// that need one (constants, CBV / SRV / UAV) +fn indirect_arg_bytes(arg: &[u32; 4]) -> u32 { + match arg[0] { + 0 => 16, + 1 => 20, + 2 | 10 => 12, + 3 | 4 => 16, + 5 => arg[3].saturating_mul(4), + 6..=8 => 8, + 9 => 108, + _ => 0, + } +} + pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_void, desc: *const u8, root: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { if desc.is_null() || ppv.is_null() { return E_INVALIDARG; @@ -1046,8 +1059,22 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); - if hr >= 0 && !ppv.is_null() && needs_root { - super::bind::note_root_changing_signature(*ppv as usize); + if hr >= 0 && !ppv.is_null() { + if needs_root { + super::bind::note_root_changing_signature(*ppv as usize); + } else if let Some(idx) = list.iter().position(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32) { + let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); + let byte_stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let mut dispatch_list = list.clone(); + dispatch_list[idx][0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; + let mut dpc = pc; + dpc[8..16].copy_from_slice(&(dispatch_list.as_ptr() as u64).to_le_bytes()); + let mut companion: *mut c_void = std::ptr::null_mut(); + let hr2 = real::dev_create_command_signature(this, dpc.as_ptr() as usize, 0, riid, &mut companion); + if hr2 >= 0 && !companion.is_null() { + super::bind::note_dispatch_mesh_signature(*ppv as usize, companion as usize, byte_stride, offset); + } + } } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index aea8e598d5..d5b2ad54cd 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -53,7 +53,7 @@ fn refresh() { let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); for (&p, f) in g.iter().flatten() { if let Some(c) = f.cell { - if let Some(v) = unsafe { borrowed(p, |f| f.GetCompletedValue()) } { + if let Some(v) = unsafe { borrowed(p, |f| super::real::fence_completed(&f)) } { c.0.store(v, Ordering::Release); } } @@ -99,7 +99,7 @@ pub(super) fn pending_summary() -> String { let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); let mut parts = Vec::new(); for (&p, f) in g.iter().flatten() { - let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); + let done = unsafe { borrowed(p, |f| super::real::fence_completed(&f)) }.unwrap_or(0); if done < f.signalled || done < f.waited { parts.push(format!("{p:#x}(done={done:#x}/sig={:#x}/wait={:#x},cell={})", f.signalled, f.waited, f.cell.is_some())); } diff --git a/crates/xcl/src/hle/d3d12x/gpu_profile.rs b/crates/xcl/src/hle/d3d12x/gpu_profile.rs new file mode 100644 index 0000000000..c5f9ac41b9 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gpu_profile.rs @@ -0,0 +1,477 @@ +//! `XCL_GPU_PROFILE=1`: the GPU time each console program takes. +//! +//! Each draw, dispatch and ExecuteIndirect of console code gets a timestamp query on its PC +//! list right before it and one right after it, and the pair is resolved into a readback buffer +//! right behind them. The resolve waits on the GPU for the op to finish, so with the profile on +//! a queue runs its ops one after the other. Nothing on the CPU waits for them: a reporter thread looks at the pairs +//! every 100 ms, adds the ones the GPU has written to their program, and every 2 s logs the 15 +//! programs that took the most GPU time in those 2 s (every 20 s: since the start), with their +//! calls, longest call, group counts and, for compute, thread group size, wave size and code size. +//! +//! A pair measures the GPU clock between the two stamps (ticks of a title queue's +//! `GetTimestampFrequency`): the time the op held its queue. Queues run on the GPU at the same +//! time, so the time of ops that overlap is counted for each of them, and the sum over programs +//! can exceed the wall time. The driver decides when a stamp is taken relative to the work +//! around it. Bundles get no stamps (no queries in bundles), and a recording that runs again +//! without a Reset is counted once. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::{offset_of, size_of, transmute}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use windows::core::{Interface, HRESULT}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +use super::real; + +/// begin / end pairs in flight (a ring): two queries and 16 readback bytes each +const PAIRS: usize = 1 << 17; +/// programs a log names +const TOP: usize = 15; +const POLL: Duration = Duration::from_millis(100); +const WINDOW: Duration = Duration::from_secs(2); +/// windows between two logs of the totals since the start +const SINCE_START_EVERY: u32 = 10; + +pub(super) fn on() -> bool { + static ON: LazyLock = LazyLock::new(|| std::env::var("XCL_GPU_PROFILE").is_ok_and(|v| v.trim() == "1")); + *ON +} + +/// The op a pair times. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(super) enum Kind { + Dispatch, + /// an ExecuteIndirect of dispatches with a translated pipeline + IndirectDispatch, + Draw, + /// an ExecuteIndirect of draws with a translated pipeline + IndirectDraw, + /// an ExecuteIndirect with a PC pipeline + PcIndirect, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::Dispatch => "Dispatch", + Kind::IndirectDispatch => "ExecuteIndirect (dispatches)", + Kind::Draw => "draw", + Kind::IndirectDraw => "ExecuteIndirect (draws)", + Kind::PcIndirect => "ExecuteIndirect with a PC pipeline", + } + } +} + +/// A program: the kind of op and its console shaders, (CS, 0) or (VS, PS); (0, 0): none known. +type Key = (Kind, u64, u64); + +struct Op { + key: Key, + /// a dispatch's groups, a draw's (vertices or indices, instances, 0), an ExecuteIndirect's + /// (max count, 0, 0) + size: [u32; 3], +} + +#[derive(Default, Clone, Debug, PartialEq)] +struct Total { + calls: u64, + ticks: u64, + /// ticks of the longest call, and its size + max: u64, + size: [u32; 3], +} + +/// What a pair of readback words holds. +#[derive(Debug, PartialEq)] +enum Stamps { + /// not both written yet + Pending, + /// the end before the begin: the GPU wrote an earlier op's pair over the slot + Bad, + Span(u64), +} + +fn stamps(begin: u64, end: u64) -> Stamps { + match (begin, end) { + (0, _) | (_, 0) => Stamps::Pending, + (b, e) if e < b => Stamps::Bad, + (b, e) => Stamps::Span(e - b), + } +} + +fn add(totals: &mut HashMap, key: Key, ticks: u64, size: [u32; 3]) { + let t = totals.entry(key).or_default(); + t.calls += 1; + t.ticks += ticks; + if ticks >= t.max { + t.max = ticks; + t.size = size; + } +} + +/// The `n` programs of `totals` with the most ticks, most first. +fn top(totals: &HashMap, n: usize) -> Vec<(Key, Total)> { + let mut v: Vec<(Key, Total)> = totals.iter().map(|(k, t)| (*k, t.clone())).collect(); + v.sort_by(|a, b| b.1.ticks.cmp(&a.1.ticks).then(b.1.calls.cmp(&a.1.calls)).then((a.0 .1, a.0 .2).cmp(&(b.0 .1, b.0 .2)))); + v.truncate(n); + v +} + +/// A console compute program as its pipeline was made. +#[derive(Clone, Copy)] +struct Shape { + threads: [u32; 3], + wave64: bool, + /// run as two 32-lane halves (`docs/wave64-on-wave32.md`) + split: bool, + code: usize, + dxil: usize, +} + +/// console CS hash → its shape +static SHAPES: Mutex>> = Mutex::new(None); + +/// A translated compute pipeline of console shader `blob` (hash `hash`, `dxil` bytes of DXIL) +/// was made, on a device that runs wave64 programs split (`split_device`). +pub(super) fn note_compute(hash: u64, blob: &[u8], dxil: usize, split_device: bool) { + if !on() { + return; + } + let mut g = SHAPES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if m.contains_key(&hash) { + return; + } + if let Some((threads, wave64, code)) = crate::gpu::recomp::pso::compute_shape(blob) { + m.insert(hash, Shape { threads, wave64, split: wave64 && split_device, code, dxil }); + } +} + +/// ticks a second of the title queues' timestamps (0: no queue seen yet) +static FREQUENCY: AtomicU64 = AtomicU64::new(0); + +/// `queue` (a title queue) executes lists: its timestamp frequency converts the pairs' ticks. +pub(super) unsafe fn note_queue(queue: *mut c_void) { + if !on() || queue.is_null() || FREQUENCY.load(Ordering::Relaxed) != 0 { + return; + } + const SLOT: usize = offset_of!(ID3D12CommandQueue_Vtbl, GetTimestampFrequency) / size_of::(); + let f: unsafe extern "system" fn(*mut c_void, *mut u64) -> HRESULT = transmute(pc_fn(queue, SLOT)); + let mut hz = 0u64; + if f(queue, &mut hz).is_ok() && hz != 0 && FREQUENCY.swap(hz, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: XCL_GPU_PROFILE: GPU timestamps at {hz} Hz"); + } +} + +struct Profile { + _heap: ID3D12QueryHeap, + _buf: ID3D12Resource, + heap: usize, + buf: usize, + /// the readback buffer's mapping: two u64 a pair + words: usize, + next: usize, + ops: Vec>, + in_flight: usize, + window: HashMap, + since_start: HashMap, + /// pairs taken again before the GPU wrote them, and pairs the GPU wrote out of order + lost: u64, + bad: u64, +} + +// SAFETY: the readback mapping lives as long as `_buf`; D3D12 objects are free-threaded. +unsafe impl Send for Profile {} + +static STATE: Mutex> = Mutex::new(None); + +unsafe fn init(dev: &ID3D12Device) -> Option { + let mut heap: Option = None; + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 2 * PAIRS as u32, NodeMask: 0 }; + if let Err(e) = dev.CreateQueryHeap(&desc, &mut heap) { + crate::xlog_warn!("D3D12.X: XCL_GPU_PROFILE: no timestamp query heap ({e})"); + return None; + } + let heap = heap?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (PAIRS * 16) as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let mut buf: Option = None; + if let Err(e) = dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut buf) { + crate::xlog_warn!("D3D12.X: XCL_GPU_PROFILE: no readback buffer ({e})"); + return None; + } + let buf = buf?; + let mut p = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + std::ptr::write_bytes(p.cast::(), 0, PAIRS * 16); + let _ = std::thread::Builder::new().name("xcl-gpu-profile".into()).spawn(|| { + let (mut last, mut windows) = (Instant::now(), 0u32); + loop { + std::thread::sleep(POLL); + poll(); + if last.elapsed() >= WINDOW && report(last.elapsed(), (windows + 1) % SINCE_START_EVERY == 0) { + windows += 1; + last = Instant::now(); + } + } + }); + crate::xlog_info!("D3D12.X: XCL_GPU_PROFILE: draws, dispatches and ExecuteIndirects of console code are timed on the GPU; the programs that take the most GPU time are logged every 2 s"); + Some(Profile { + heap: heap.as_raw() as usize, + buf: buf.as_raw() as usize, + _heap: heap, + _buf: buf, + words: p as usize, + next: 0, + ops: (0..PAIRS).map(|_| None).collect(), + in_flight: 0, + window: HashMap::new(), + since_start: HashMap::new(), + lost: 0, + bad: 0, + }) +} + +/// The profile, made on first use with `dev` (outside the lock: the device calls go through +/// XCL's hooks). +fn with_state(dev: impl FnOnce() -> Option, f: impl FnOnce(&mut Profile) -> R) -> Option { + static INIT: std::sync::Once = std::sync::Once::new(); + if !INIT.is_completed() { + let dev = dev()?; + INIT.call_once(|| { + let s = unsafe { init(&dev) }; + *STATE.lock().unwrap() = s; + }); + } + STATE.lock().unwrap().as_mut().map(f) +} + +impl Profile { + fn word(&self, i: usize) -> &AtomicU64 { + unsafe { &*(self.words as *const AtomicU64).add(i) } + } +} + +/// The PC method in `slot` of `obj` (an adopted object's own, not XCL's console-layout entry). +unsafe fn pc_fn(obj: *mut c_void, slot: usize) -> usize { + if real::is_adopted(obj) { + real::orig_fn(obj, slot) + } else { + *(*(obj as *const *const usize)).add(slot) + } +} + +type EndQueryFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32); +type ResolveFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); + +/// The begin stamp of an op on a list: `end` records the end stamp and the resolve. +pub(super) struct Pair { + k: u32, + heap: usize, + buf: usize, + end_query: EndQueryFn, + resolve: ResolveFn, +} + +/// Before the PC call of an op of console code on `list` (`pso`: its pipeline as bound). +pub(super) unsafe fn begin(list: *mut c_void, pso: usize, kind: Kind, size: [u32; 3]) -> Option { + super::queue_probe::op(list as usize, kind.name(), pso, size); + if !on() || list.is_null() { + return None; + } + const GET_TYPE: usize = offset_of!(ID3D12CommandList_Vtbl, GetType) / size_of::(); + const END_QUERY: usize = offset_of!(ID3D12GraphicsCommandList_Vtbl, EndQuery) / size_of::(); + const RESOLVE: usize = offset_of!(ID3D12GraphicsCommandList_Vtbl, ResolveQueryData) / size_of::(); + let get_type: unsafe extern "system" fn(*mut c_void) -> D3D12_COMMAND_LIST_TYPE = transmute(pc_fn(list, GET_TYPE)); + let ty = get_type(list); + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return None; + } + let (a, b) = real::pso_shaders(super::pso_async::resolve(pso)).unwrap_or((0, 0)); + let key = (kind, a, b); + let (k, heap, buf) = with_state( + || { + let mut dev: Option = None; + ID3D12GraphicsCommandList::from_raw_borrowed(&list)?.GetDevice(&mut dev).ok()?; + dev + }, + |s| { + let k = s.next; + s.next = (k + 1) % PAIRS; + if s.ops[k].is_some() { + s.lost += 1; + } else { + s.in_flight += 1; + } + s.word(2 * k).store(0, Ordering::Release); + s.word(2 * k + 1).store(0, Ordering::Release); + s.ops[k] = Some(Op { key, size }); + (k as u32, s.heap, s.buf) + }, + )?; + let pair = Pair { k, heap, buf, end_query: transmute(pc_fn(list, END_QUERY)), resolve: transmute(pc_fn(list, RESOLVE)) }; + (pair.end_query)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k); + Some(pair) +} + +/// After the PC call of the op `begin` gave `pair` for. +pub(super) unsafe fn end(list: *mut c_void, pair: Option) { + let Some(p) = pair else { return }; + (p.end_query)(list, p.heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * p.k + 1); + (p.resolve)(list, p.heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * p.k, 2, p.buf, 16 * p.k as u64); +} + +/// Add the pairs the GPU has written to their programs. +fn poll() { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + let mut left = s.in_flight; + for k in 0..PAIRS { + if left == 0 { + break; + } + let Some(op) = &s.ops[k] else { continue }; + left -= 1; + let span = match stamps(s.word(2 * k).load(Ordering::Acquire), s.word(2 * k + 1).load(Ordering::Acquire)) { + Stamps::Pending => continue, + Stamps::Bad => None, + Stamps::Span(t) => Some(t), + }; + let (key, size) = (op.key, op.size); + match span { + Some(t) => { + add(&mut s.window, key, t, size); + add(&mut s.since_start, key, t, size); + } + None => s.bad += 1, + } + s.ops[k] = None; + s.in_flight -= 1; + } +} + +fn program(key: Key, shapes: &HashMap) -> String { + let (kind, a, b) = key; + match kind { + Kind::Dispatch | Kind::IndirectDispatch => { + let shape = shapes.get(&a).map_or(String::new(), |s| { + format!( + "; {}x{}x{} threads, {}, {} B code, {} B DXIL", + s.threads[0], + s.threads[1], + s.threads[2], + if s.split { "wave64 split in halves" } else if s.wave64 { "wave64" } else { "wave32" }, + s.code, + s.dxil + ) + }); + format!("CS {a:016x} {}{shape}", kind.name()) + } + Kind::Draw | Kind::IndirectDraw if a != 0 => format!("VS {a:016x} PS {b:016x} {}", kind.name()), + Kind::Draw | Kind::IndirectDraw => format!("{} with no console shader known", kind.name()), + Kind::PcIndirect => kind.name().to_owned(), + } +} + +fn size_text(kind: Kind, size: [u32; 3]) -> String { + match kind { + Kind::Dispatch => format!("{}x{}x{} groups", size[0], size[1], size[2]), + Kind::Draw => format!("{} vertices or indices x {} instances", size[0], size[1]), + Kind::IndirectDispatch | Kind::IndirectDraw | Kind::PcIndirect => format!("max count {} (its counts are the GPU's)", size[0]), + } +} + +/// Calls and ticks of `totals`, summed. +fn sums(totals: &HashMap) -> (u64, u64) { + totals.values().fold((0, 0), |(n, ticks), t| (n + t.calls, ticks + t.ticks)) +} + +/// Log the programs that took the most GPU time in the last `elapsed` (and since the start). +/// False: nothing logged (no queue's timestamp frequency yet); the window goes on. +fn report(elapsed: Duration, since_start: bool) -> bool { + let hz = FREQUENCY.load(Ordering::Relaxed); + if hz == 0 { + return false; + } + let (window, all, in_flight, lost, bad) = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return false }; + let all = since_start.then(|| (top(&s.since_start, TOP), sums(&s.since_start))); + (std::mem::take(&mut s.window), all, s.in_flight, s.lost, s.bad) + }; + let ms = |ticks: u64| ticks as f64 * 1000.0 / hz as f64; + let shapes = SHAPES.lock().unwrap().clone().unwrap_or_default(); + let lines = |what: &str, totals: Vec<(Key, Total)>, (ops, ticks): (u64, u64)| { + crate::xlog_info!( + "D3D12.X: XCL_GPU_PROFILE: {what}: {:.1} ms of GPU time in {ops} op(s) of console code ({in_flight} in flight, {lost} lost, {bad} out of order); the {} that took most:", + ms(ticks), + totals.len() + ); + for (i, ((kind, a, b), t)) in totals.into_iter().enumerate() { + crate::xlog_info!( + "D3D12.X: XCL_GPU_PROFILE: {:>2}. {:>9.1} ms {}: {} call(s), longest {:.1} ms ({})", + i + 1, + ms(t.ticks), + program((kind, a, b), &shapes), + t.calls, + ms(t.max), + size_text(kind, t.size) + ); + } + }; + if !window.is_empty() { + lines(&format!("last {:.1} s", elapsed.as_secs_f64()), top(&window, TOP), sums(&window)); + } + if let Some((all, sum)) = all { + lines("since the start", all, sum); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pair_counts_once_both_stamps_are_written_and_in_order() { + assert_eq!(stamps(0, 0), Stamps::Pending); + // (the resolve's copy can be seen half done) + assert_eq!(stamps(1_000, 0), Stamps::Pending); + assert_eq!(stamps(0, 1_000), Stamps::Pending); + assert_eq!(stamps(2_000, 1_000), Stamps::Bad); + assert_eq!(stamps(1_000, 1_000), Stamps::Span(0)); + assert_eq!(stamps(1_000, 4_500), Stamps::Span(3_500)); + } + + #[test] + fn programs_are_ranked_by_their_total_and_keep_their_longest_call() { + let mut t = HashMap::new(); + let (a, b, c) = ((Kind::Dispatch, 0xA, 0), (Kind::IndirectDispatch, 0xB, 0), (Kind::Draw, 0xC, 0xD)); + add(&mut t, a, 10, [1, 1, 1]); + add(&mut t, a, 30, [8, 4, 1]); + add(&mut t, a, 20, [2, 1, 1]); + add(&mut t, b, 100, [1, 0, 0]); + add(&mut t, c, 5, [3, 1, 0]); + let r = top(&t, 2); + assert_eq!(r.len(), 2); + assert_eq!(r[0], (b, Total { calls: 1, ticks: 100, max: 100, size: [1, 0, 0] })); + assert_eq!(r[1], (a, Total { calls: 3, ticks: 60, max: 30, size: [8, 4, 1] })); + // the same op with the same program under two kinds stays two programs + add(&mut t, (Kind::IndirectDispatch, 0xA, 0), 1, [1, 0, 0]); + assert_eq!(top(&t, 10).len(), 4); + } +} diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..59fec0473c 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -21,8 +21,14 @@ const SEAL_EVERY: Duration = Duration::from_millis(10); /// how often the thread here looks for batches that can go const TICK: Duration = Duration::from_millis(4); +#[derive(Debug, PartialEq, Eq)] +struct HeldResource { + raw: usize, + small_slot: bool, +} + struct Batch { - dead: Vec, + dead: Vec, /// (fence, value) a queue: all reached = nothing submitted before the batch closed is left marks: Vec<(ID3D12Fence, u64)>, } @@ -31,7 +37,7 @@ struct Batch { struct Held { /// queue → its fence here and the last value signalled on it fences: HashMap, - open: Vec, + open: Vec, sealed: VecDeque, last_seal: Option, } @@ -46,7 +52,7 @@ impl Held { /// 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 { + 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; @@ -77,7 +83,7 @@ impl Held { } } let mut gone = Vec::new(); - while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { + while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| super::real::fence_completed(&f) >= *v)) { gone.extend(self.sealed.pop_front().unwrap().dead); } gone @@ -99,8 +105,8 @@ const IDLE_WAIT: Duration = Duration::from_micros(300); /// 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) { - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(res); +pub unsafe fn hold(res: usize, small_slot: bool) { + HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(HeldResource { raw: res, small_slot }); let start = Instant::now(); drain_known(true); while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { @@ -143,8 +149,11 @@ pub unsafe fn drain_known(seal_now: bool) { }; // (outside the lock: a release may end other objects, whose releases come back here) for res in gone { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(res as *mut c_void, 2)); - f(res as *mut c_void); + if res.small_slot { + super::vram_small::forget(res.raw, false); + } + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(res.raw as *mut c_void, 2)); + f(res.raw as *mut c_void); } } @@ -180,7 +189,7 @@ mod tests { let raw = res.unwrap().into_raw() as usize; let mut held = Held::default(); - held.open.push(raw); + held.open.push(HeldResource { raw, small_slot: true }); 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)); @@ -194,7 +203,7 @@ mod tests { 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_eq!(gone, vec![HeldResource { raw, small_slot: true }], "retirement carries the slot until the fence passes"); assert!(held.is_empty()); drop(ID3D12Resource::from_raw(raw as *mut c_void)); } @@ -204,8 +213,8 @@ mod tests { #[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]); + held.open.push(HeldResource { raw: 0x1000, small_slot: false }); + assert_eq!(unsafe { held.drain(&[], false) }, vec![HeldResource { raw: 0x1000, small_slot: false }]); assert!(held.is_empty()); } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 06cca160a5..31fda3397e 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -258,6 +258,8 @@ impl PendingWait { Duration::from_millis(1) }; std::thread::sleep(step); + // a value a list wrote into a sparse window reaches this memory with its copy back + super::sparse::settle_readbacks(); if self.is_satisfied() { return true; } @@ -439,6 +441,17 @@ fn with_bindings(list: *mut c_void, f: impl FnOnce(&mut Bindings)) { f(&mut g.get_or_insert_with(HashMap::new).entry(list as usize).or_default().bindings); } +/// (tests) The view heaps XCL counts as bound on `list`; forgetting the list with `forget`. +#[cfg(test)] +pub(super) fn bound_heaps(list: *mut c_void, forget: bool) -> Vec { + let mut heaps = Vec::new(); + with_bindings(list, |b| heaps = b.heaps.clone()); + if forget { + LISTS.lock().unwrap().as_mut().map(|m| m.remove(&(list as usize))); + } + heaps +} + const PC_IA_SET_PRIMITIVE_TOPOLOGY: usize = 20; const PC_RS_SET_VIEWPORTS: usize = 21; const PC_RS_SET_SCISSOR_RECTS: usize = 22; @@ -589,6 +602,10 @@ struct ListState { /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, /// `CopyMemoryToMemoryX`, timestamps) to copy back to the CPU view after execution. sparse_writes: Vec<(usize, usize)>, + /// Bottom-of-pipe immediates into a window the GPU has a copy of: (address, value, bytes). + /// XCL knows what the GPU writes there, so the CPU's view gets the value from XCL once the + /// submission is done on the GPU (`sparse::readback_after_execute`), without a copy back. + sparse_imm: Vec<(usize, u64, u8)>, /// Non-timestamp 64-bit `(va, value)` writes recorded by `Write64BitValue{Bottom,Top}OfPipeX` /// so `ExecuteCommandLists` / `KickoffX` can signal per-address GPU fences for cross-queue /// `Wait64BitValueX` without blocking the submitter thread on the CPU. @@ -619,20 +636,39 @@ impl ListState { last.0 = last.0.min(va); last.1 = last.1.max(end); } - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { - if self.sparse_writes.is_empty() { + if crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(va as usize)) { + if !self.has_sparse() { SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); } self.sparse_writes.push((va as usize, size as usize)); } } - fn clear_sparse_writes(&mut self) -> Vec<(usize, usize)> { - if self.sparse_writes.is_empty() { - return Vec::new(); + fn has_sparse(&self) -> bool { + !self.sparse_writes.is_empty() || !self.sparse_imm.is_empty() + } + + /// `note_write` for an immediate of `bytes` (4 or 8) into a window the GPU has a copy of + fn note_imm(&mut self, va: u64, value: u64, bytes: u8) { + let end = va.saturating_add((bytes & 0x7f) as u64); + if self.written_ranges.len() < MAX_WRITTEN_RANGES { + self.written_ranges.push((va, end)); + } else if let Some(last) = self.written_ranges.last_mut() { + last.0 = last.0.min(va); + last.1 = last.1.max(end); + } + if !self.has_sparse() { + SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); + } + self.sparse_imm.push((va as usize, value, bytes)); + } + + fn clear_sparse_writes(&mut self) -> (Vec<(usize, usize)>, Vec<(usize, u64, u8)>) { + if !self.has_sparse() { + return (Vec::new(), Vec::new()); } SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); - std::mem::take(&mut self.sparse_writes) + (std::mem::take(&mut self.sparse_writes), std::mem::take(&mut self.sparse_imm)) } fn push_write64_signal(&mut self, va: u64, value: u64) { @@ -763,7 +799,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C if !old.pending_waits.is_empty() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); } - if !old.sparse_writes.is_empty() { + if old.has_sparse() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } if !old.write64_signals.is_empty() { @@ -799,7 +835,7 @@ pub(super) fn on_release(list: usize) { if !old.pending_waits.is_empty() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); } - if !old.sparse_writes.is_empty() { + if old.has_sparse() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } if !old.write64_signals.is_empty() { @@ -972,6 +1008,17 @@ fn note_write(list: usize, va: u64, size: u64) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); } +/// A PC copy into `[offset, offset + n)` of console buffer `dst` whose memory the GPU only has +/// a copy of in a committed window (`Uma::shadowed`: readback buffers live there, and titles +/// read them through a pointer they keep mapped, without another Map): the bytes come back to +/// the CPU's view after the submit, like the lists' own memory writes. +fn note_copy_into(list: usize, dst: usize, offset: u64, n: u64) { + let Some(u) = crate::gpu::uma::get().filter(|u| u.shadowed()) else { return }; + let Some((p, bytes)) = real::console_buffer(dst).filter(|&(p, _)| u.is_committed(p)) else { return }; + let offset = offset.min(bytes as u64); + note_write(list, p as u64 + offset, n.min(bytes as u64 - offset)); +} + // --------------------------------------------------------------------------------------- // per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX // --------------------------------------------------------------------------------------- @@ -1114,19 +1161,136 @@ static QUEUE_IDS: Mutex> = Mutex::new(Vec::new()); /// producer queue that stands behind one of them shows in the log. struct InternalWait { what: &'static str, + /// the cell's address for a bridged `Wait64BitValueX` (0: not one) + va: u64, fence: ID3D12Fence, value: u64, at: Instant, } +/// queue → its private progress fence, the submits signalled on it, and when each of the +/// last ones was signalled (diagnostic: how far behind a queue is, and since when) +struct Progress { + fence: ID3D12Fence, + submitted: u64, + recent: std::collections::VecDeque<(u64, Instant)>, +} + +unsafe impl Send for Progress {} + +static PROGRESS: Mutex>> = Mutex::new(None); + +/// After a submit to `queue`: a Signal of its private progress fence. +pub(super) unsafe fn note_submitted(queue: *mut c_void, submission: u64) { + if queue.is_null() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let mut g = PROGRESS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if !m.contains_key(&(queue as usize)) { + let mut dev: Option = None; + if q.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; + m.insert(queue as usize, Progress { fence, submitted: 0, recent: Default::default() }); + } + let p = m.get_mut(&(queue as usize)).unwrap(); + p.submitted += 1; + let signal = q.Signal(&p.fence, p.submitted); + super::queue_probe::signal("progress-fence", queue as usize, &p.fence, submission, p.submitted, + signal.as_ref().err().map_or(0, |e| e.code().0)); + if signal.is_ok() { + p.recent.push_back((p.submitted, Instant::now())); + while p.recent.len() > 4096 { + p.recent.pop_front(); + } + } +} + +/// `q / submits (oldest unfinished for ms)` for every queue behind. +fn progress_summary() -> String { + let rows: Vec<(usize, String)> = { + let mut g = PROGRESS.lock().unwrap(); + g.iter_mut() + .flat_map(|m| m.iter_mut()) + .filter_map(|(&q, p)| { + let done = unsafe { super::real::fence_completed(&p.fence) }; + while p.recent.front().is_some_and(|&(n, _)| n <= done) { + p.recent.pop_front(); + } + (done < p.submitted).then(|| (q, format!("{done}/{} submits (oldest unfinished for {} ms)", p.submitted, p.recent.front().map_or(0, |&(_, t)| t.elapsed().as_millis())))) + }) + .collect() + }; + if rows.is_empty() { + return "no queue is behind".into(); + } + let mut rows: Vec = rows.into_iter().map(|(q, s)| format!("q{} {s}", queue_id(q))).collect(); + rows.sort(); + rows.join(", ") +} + +/// Diagnostic: the wait-for edges of the sync graph, one per GPU wait not yet met: who waits +/// for which value of which cell (or title fence), and which submitted signal (queue, its +/// place among that queue's calls) will meet it. A wait for a value no signal has been submitted +/// for says what was recorded instead. +fn edges_summary() -> String { + let mut rows: Vec = Vec::new(); + let g = SYNC_GRAPH.lock().unwrap(); + let Some(graph) = g.as_ref() else { return "none".into() }; + for (&va, cell) in &graph.cells { + let done = cell.fence.as_ref().map_or(0, |f| unsafe { super::real::fence_completed(f) }); + for aw in &cell.armed_waits { + if aw.val <= done { + continue; + } + let met = cell.submitted_signals.iter().find(|s| s.val >= aw.val); + let by = match met { + Some(s) => format!("q{}@{} (signal {:#x})", queue_id(s.queue), s.seq, s.val), + None => format!("none submitted (recorded up to {:#x}, submitted up to {:#x} by {:?})", cell.recorded_max, cell.submitted_max, cell.submitted_queue.map(queue_id)), + }; + rows.push(format!("q{}@{} waits {va:#x} >= {:#x} (done {done:#x}) <- {by}", queue_id(aw.waiting_queue), aw.wait_seq, aw.val)); + } + } + for (&f, tf) in &graph.title_fences { + for &(val, q, seq) in &tf.waits { + let met = tf.signals.iter().find(|s| s.val >= val); + let by = match met { + Some(s) => format!("q{}@{} (signal {:#x})", queue_id(s.queue), s.seq, s.val), + None => "none submitted".to_string(), + }; + rows.push(format!("q{}@{seq} waits title fence {f:#x} >= {val:#x} <- {by}", queue_id(q))); + } + } + rows.sort(); + let n = rows.len(); + rows.truncate(90); + format!("{n} waits: {}", rows.join("; ")) +} + +/// `queue` was made to wait for the fence of the cell at `va` to reach `value` (a bridged +/// `Wait64BitValueX`): listed with XCL's own waits while it is unmet, whatever the sync graph +/// has done with it since. +fn note_cell_wait(queue: usize, va: u64, fence: &ID3D12Fence, value: u64) { + let mut g = INTERNAL_WAITS.lock().unwrap(); + let waits = g.get_or_insert_with(HashMap::new).entry(queue).or_default(); + waits.retain(|w| unsafe { super::real::fence_completed(&w.fence) } < w.value); + super::queue_probe::event("Wait64 cell", queue, fence.as_raw() as usize, 0, value, va as u64); + waits.push(InternalWait { what: "Wait64 cell", va, fence: fence.clone(), value, at: Instant::now() }); +} + static INTERNAL_WAITS: Mutex>>> = Mutex::new(None); /// `queue` was made to wait for `fence` >= `value` by XCL (`what` says for what). pub(super) fn note_internal_wait(queue: usize, what: &'static str, fence: &ID3D12Fence, value: u64) { let mut g = INTERNAL_WAITS.lock().unwrap(); let waits = g.get_or_insert_with(HashMap::new).entry(queue).or_default(); - waits.retain(|w| unsafe { w.fence.GetCompletedValue() } < w.value); - waits.push(InternalWait { what, fence: fence.clone(), value, at: Instant::now() }); + waits.retain(|w| unsafe { super::real::fence_completed(&w.fence) } < w.value); + super::queue_probe::event(what, queue, fence.as_raw() as usize, 0, value, 0); + waits.push(InternalWait { what, va: 0, fence: fence.clone(), value, at: Instant::now() }); } /// The internal waits not yet met: `q: >= (done , ms)`. @@ -1137,8 +1301,9 @@ fn internal_waits_summary() -> String { .flat_map(|m| m.iter()) .flat_map(|(&q, waits)| waits.iter().map(move |w| (q, w))) .filter_map(|(q, w)| { - let done = unsafe { w.fence.GetCompletedValue() }; - (done < w.value).then(|| (q, format!("{} >= {:#x} (done {done:#x}, {} ms)", w.what, w.value, w.at.elapsed().as_millis()))) + let done = unsafe { super::real::fence_completed(&w.fence) }; + let what = if w.va != 0 { format!("{} {:#x}", w.what, w.va) } else { w.what.to_string() }; + (done < w.value).then(|| (q, format!("{what} >= {:#x} (done {done:#x}, {} ms)", w.value, w.at.elapsed().as_millis()))) }) .collect() }; @@ -1163,7 +1328,7 @@ fn queue_id(q: usize) -> usize { /// was removed). Returns the fence's current completed value (or `0` if no fence exists yet). unsafe fn prune_completed_waits(cell: &mut SyncCell) -> u64 { let Some(ref fence) = cell.fence else { return 0 }; - let completed = fence.GetCompletedValue(); + let completed = super::real::fence_completed(&fence); if completed == u64::MAX { let removed = cell.armed_waits.len(); cell.armed_waits.clear(); @@ -1194,7 +1359,7 @@ unsafe fn prune_title_fence(fence_raw: usize, tf: &mut TitleFenceSync) { } let p = fence_raw as *mut c_void; let Some(f) = ID3D12Fence::from_raw_borrowed(&p) else { return }; - let completed = f.GetCompletedValue(); + let completed = super::real::fence_completed(&f); if completed == u64::MAX { tf.waits.clear(); tf.signals.clear(); @@ -1509,6 +1674,11 @@ fn wake_sync_watchdog() { if had_expired { crate::xlog_warn!("D3D12.X: pending title ID3D12Fences during GPU wait timeout: {}", super::fence_x::pending_summary()); crate::xlog_warn!("D3D12.X: XCL's own queue waits unmet during GPU wait timeout: {}", internal_waits_summary()); + crate::xlog_warn!("D3D12.X: queues behind during GPU wait timeout: {}", progress_summary()); + static PRINTED: AtomicU64 = AtomicU64::new(0); + if PRINTED.fetch_add(1, Ordering::Relaxed) < 3 { + crate::xlog_warn!("D3D12.X: wait edges at that time-out: {}", edges_summary()); + } } }); }); @@ -1848,6 +2018,8 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, let completed = prune_completed_waits(cell); if completed >= w.value { // Fence already reached `w.value`: trust it if CPU memory agrees (not reset). + drop(g); + super::sparse::settle_readbacks(); return if w.is_satisfied() { GpuWaitOutcome::Handled } else { GpuWaitOutcome::FallbackCpu }; } if cell.submitted_max >= w.value && cell.submitted_queue == Some(q_raw) { @@ -1883,6 +2055,7 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, return GpuWaitOutcome::FallbackCpu; } + note_cell_wait(q_raw, w.va, &fence, w.value); wake_sync_watchdog(); if unsubmitted { static LOGGED: AtomicU64 = AtomicU64::new(0); @@ -1918,8 +2091,9 @@ unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait], list_writes: &[ if !w.wait_until_satisfied(timeout) && once(&TIMEOUTS, 40) { let cell_diag = { let g = SYNC_GRAPH.lock().unwrap(); - g.as_ref().and_then(|gr| gr.cells.get(&w.va)).map(|c| (c.recorded_max, c.submitted_max, c.non_monotonic, c.recorded_list_type.map(|t| t.0))) + g.as_ref().and_then(|gr| gr.cells.get(&w.va)).map(|c| (c.recorded_max, c.submitted_max, c.non_monotonic, c.recorded_list_type.map(|t| t.0), c.submitted_queue.map(queue_id))) }; + let behind = progress_summary(); crate::xlog_warn!( "D3D12.X: Wait{}BitValueX timed out after {} ms at {:#x} (op {}, want {:#x}, mask {:#x}; memory holds {:x?}; queue_type={}, after_write64={}, sync={cell_diag:x?})", w.width * 8, @@ -1932,6 +2106,9 @@ unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait], list_writes: &[ q_ty, w.after_write64 ); + if !behind.is_empty() { + crate::xlog_warn!("D3D12.X: queues behind at that time-out: {behind}"); + } if once(&RING_DUMPED, 2) { let (total, entries) = WRITE_TRACE.lock().unwrap().snapshot(); let summary: Vec = entries @@ -1952,22 +2129,23 @@ pub(super) unsafe fn readback_sparse_writes(queue: *mut c_void, lists: &[*mut c_ if SPARSE_WRITE_LISTS.load(Ordering::Acquire) == 0 || queue.is_null() || lists.is_empty() { return; } - let ranges: Vec<(usize, usize)> = { + let (ranges, imms): (Vec<(usize, usize)>, Vec<(usize, u64, u8)>) = { let g = LISTS.lock().unwrap(); let Some(m) = g.as_ref() else { return }; - let mut out = Vec::new(); + let (mut out, mut imm) = (Vec::new(), Vec::new()); for &l in lists { if let Some(s) = m.get(&(l as usize)) { out.extend_from_slice(&s.sparse_writes); + imm.extend_from_slice(&s.sparse_imm); } } - out + (out, imm) }; - if ranges.is_empty() { + if ranges.is_empty() && imms.is_empty() { return; } if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { - super::sparse::readback_after_execute(q, &ranges); + super::sparse::readback_after_execute(q, &ranges, &imms); } } @@ -2087,7 +2265,7 @@ struct CopyScratch { impl CopyScratch { fn idle(&mut self) -> bool { - self.marks.retain(|_, (fence, value)| unsafe { fence.GetCompletedValue() < *value }); + self.marks.retain(|_, (fence, value)| unsafe { super::real::fence_completed(&fence) < *value }); !self.untracked_submission && self.marks.is_empty() } } @@ -2328,6 +2506,16 @@ pub(super) unsafe extern "system" fn fill128_x(this: *mut c_void, va: u64, size: } } +/// `XCL_IMM_BY_CPU=0`: a bottom-of-pipe immediate into a window the GPU has a copy of comes +/// back to the CPU's view with a copy, like the lists' other memory writes. Otherwise XCL stores +/// the value it was given there once the submission is done on the GPU. A retail title's CPU +/// waits on such cells; copied back, one of them held a value up to 46 frames old in the CPU's +/// view (and older than it had held before) while its GPU fence was reached. +fn imm_by_cpu() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_IMM_BY_CPU").map_or(true, |v| v.trim() != "0")) +} + /// Values written by the GPU at `va` (WriteBufferImmediate: MARKER_IN = when the command is /// reached, MARKER_OUT = when the work before it is done). unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFFERIMMEDIATE_MODE, what: &str) { @@ -2346,7 +2534,17 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF } return warn(&N, what, format_args!("{va:#x} is not in unified memory")); }; - note_write(list as usize, va, n); + // into a window the GPU only has a copy of: the CPU's view gets the value from XCL + if words.len() <= 2 && imm_by_cpu() && crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(va as usize)) { + let value = words.iter().enumerate().fold(0u64, |v, (i, &w)| v | (w as u64) << (32 * i)); + // a counter the title's queues write in turn (a `SyncCell` whose values only rose): a list + // that runs late does not take the CPU's view of it back (`sparse::IMM_KEEP_MAX`) + let counter = words.len() == 2 && SYNC_GRAPH.lock().unwrap().as_ref().and_then(|g| g.cells.get(&va)).is_some_and(|c| !c.non_monotonic && c.recorded_max != 0); + let bytes = n as u8 | if counter { super::sparse::IMM_KEEP_MAX } else { 0 }; + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default().note_imm(va, value, bytes); + } else { + note_write(list as usize, va, n); + } let params: Vec = words.iter().enumerate().map(|(i, &w)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + 4 * i as u64, Value: w }).collect(); let modes = vec![mode; words.len()]; type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); @@ -2583,7 +2781,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { if !o.pending_waits.is_empty() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); } - if !o.sparse_writes.is_empty() { + if o.has_sparse() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } if !o.write64_signals.is_empty() { @@ -3019,6 +3217,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let q_raw = queue as *mut c_void; super::title_textures::refresh(q_raw); + super::gpu_profile::note_queue(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)); @@ -3028,12 +3227,15 @@ 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()); + let id = super::queue_probe::submit("kickoff-prior", q_raw as usize, chunk); + super::sparse::ordered_submit(q_raw, || exec(q_raw, chunk.len() as u32, chunk.as_ptr())); + super::queue_probe::event("execute-return", q_raw as usize, 0, id, 0, 0); copy_scratch_submitted(q_raw, chunk); - super::alloc_pool::executed(q_raw, chunk); + super::alloc_pool::executed(q_raw, chunk, id); signal_write64_fences(q_raw, chunk); readback_sparse_writes(q_raw, chunk); cpu_writes_after(q_raw, chunk); + note_submitted(q_raw, id); }); super::title_textures::submitted(prior); for &p in prior { @@ -3047,16 +3249,18 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } let one = [this]; - exec(q_raw, 1, one.as_ptr()); + let id = super::queue_probe::submit("kickoff", q_raw as usize, &one); + super::sparse::ordered_submit(q_raw, || exec(q_raw, 1, one.as_ptr())); + super::queue_probe::event("execute-return", q_raw as usize, 0, id, 0, 0); copy_scratch_submitted(q_raw, &one); - super::alloc_pool::executed(q_raw, &one); + super::alloc_pool::executed(q_raw, &one, id); signal_write64_pairs(q_raw, &write64_signals); // what ran is in the textures' states; the list records anew after its Reset below super::title_textures::submitted(&one); super::title_textures::list_reset(this as usize); - if !sparse_writes.is_empty() { + if !sparse_writes.0.is_empty() || !sparse_writes.1.is_empty() { if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { - super::sparse::readback_after_execute(q, &sparse_writes); + super::sparse::readback_after_execute(q, &sparse_writes.0, &sparse_writes.1); } } super::cpu_writes::after(q_raw, cpu_writes); @@ -3867,6 +4071,7 @@ pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst note_gpu_write("CopyBufferRegion", a + dst_off as usize, n); } } + note_copy_into(this as usize, dst, dst_off, n); pc::(this, PC_COPY_BUFFER_REGION)(this, dst, dst_off + real::buffer_delta(dst), src, src_off + real::buffer_delta(src), n) } @@ -3966,6 +4171,12 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds } } } + if let Some(l) = dst.as_ref().filter(|l| l.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) { + // (the rows of the footprint: at most what the copy writes) + let f = &l.Anonymous.PlacedFootprint; + let n = f.Footprint.RowPitch as u64 * f.Footprint.Height.max(1) as u64 * f.Footprint.Depth.max(1) as u64; + note_copy_into(this as usize, transmute_copy::<_, usize>(&l.pResource), f.Offset, n); + } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); std::mem::forget((d, s)); // borrowed resource pointers @@ -4052,6 +4263,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi } let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { + note_copy_into(this as usize, dst, 0, u64::MAX); return pc::(this, PC_COPY_RESOURCE)(this, dst, src); } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); @@ -4108,6 +4320,8 @@ pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize, /// ResolveQueryData wants the destination). Buffers placed below their console address add /// `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) { + // (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 }); let pc_offset = offset.saturating_add(real::buffer_delta(dest)); type F = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); pc::(this, PC_RESOLVE_QUERY_DATA)(this, heap, ty, first, count, dest, pc_offset); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f0357981..81dfab9830 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -18,6 +18,8 @@ pub mod dxgi_device; mod cpu_writes; mod fence_x; pub mod frame; +mod gpu_profile; +pub(crate) mod queue_probe; pub mod guard; mod late_release; pub mod layout; @@ -31,6 +33,7 @@ pub mod sparse; pub mod title_list; pub mod title_textures; pub mod vram; +mod vram_small; use std::ffi::c_void; use std::sync::OnceLock; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 01b3c92a4a..02bdb66190 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -254,15 +254,16 @@ pub fn activity() -> (u64, u64) { (PRESENTS.load(Ordering::Relaxed), EXECUTES.load(Ordering::Relaxed)) } +pub(super) unsafe fn remember_queue(queue: *mut c_void) { + let mut queues = QUEUES.lock().unwrap(); + if !queues.contains(&(queue as usize)) { + add_ref(queue as usize); + queues.push(queue as usize); + } +} + pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { EXECUTES.fetch_add(1, Ordering::Relaxed); - { - let mut q = QUEUES.lock().unwrap(); - if !q.contains(&(queue as usize)) { - add_ref(queue as usize); - q.push(queue as usize); - } - } super::late_release::drain_known(false); if !enabled() || IN_PRESENT.with(|c| c.get()) || PRESENTX.load(Ordering::Relaxed) { return; @@ -733,11 +734,15 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { let qraw = queue as *mut c_void; let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qraw) else { return }; let Ok(cl) = p.list.cast::() else { return }; + let id = super::queue_probe::submit("present-copy", queue, &[cl.as_raw()]); q.ExecuteCommandLists(&[Some(cl)]); p.copy_source = Some(src); p.dumps = dumps; p.value += 1; - if let Err(e) = q.Signal(&p.fence, p.value) { + let signal = q.Signal(&p.fence, p.value); + super::queue_probe::signal("present-fence", queue, &p.fence, id, p.value, + signal.as_ref().err().map_or(0, |e| e.code().0)); + if let Err(e) = signal { // The copy is already submitted. Without its signal, keep its resources and allocator. p.disabled = true; let e = fence::api_error(&p.dev, "Signal", e); @@ -778,11 +783,23 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, usize)>) { /// (`frame_.bmp`, a quarter of each side; `XCL_FRAME_DUMP_FULL=1`: full size) – what the title presented, before the window. fn frame_dump_due() -> bool { static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + static LATE: std::sync::OnceLock> = std::sync::OnceLock::new(); + let frame = PRESENTS.load(Ordering::Relaxed); + // XCL_FRAME_DUMP_LATE=, increases capture density near a known transition. + if let Some((first, interval)) = *LATE.get_or_init(|| { + let value = std::env::var("XCL_FRAME_DUMP_LATE").ok()?; + let (first, interval) = value.split_once(',')?; + Some((first.parse().ok()?, interval.parse::().ok().filter(|&n| n != 0)?)) + }) { + if frame >= first { + return (frame - first) % interval == 0; + } + } let every = *EVERY.get_or_init(|| match std::env::var("XCL_FRAME_DUMP") { Ok(v) => v.parse().ok().filter(|&n| n > 1).unwrap_or(120), Err(_) => 0, }); - every > 0 && PRESENTS.load(Ordering::Relaxed) % every == 20.min(every - 1) + every > 0 && frame % every == 20.min(every - 1) } /// Frames shown so far. diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 39f338143f..56f0f5d6d6 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -392,6 +392,19 @@ fn preload() -> Option<&'static Preload> { mod used_tests { use super::*; + #[test] + fn release_drops_an_unclaimed_job_even_while_the_queue_owns_pending() { + let standin = 0x7E57_B827usize; + let bytes = Arc::new(vec![0x5a; 4096]); + let weak = Arc::downgrade(&bytes); + submit_lazy(standin, true, Box::new(move || bytes.len()), 0); + let queued = entry(standin).unwrap(); + assert_eq!(released(standin), 0); + assert!(weak.upgrade().is_none(), "the queued descriptor was cancelled"); + assert!(queued.job.lock().unwrap().is_none()); + assert!(*queued.done.lock().unwrap(), "a concurrent binder can finish waiting"); + } + /// While a bind waits for a pipeline still being built, the title is held (`title_held`): /// `kernelx::Sleep` does not count that time. #[test] @@ -620,14 +633,21 @@ pub fn resolve_for_bind(pso: usize) -> usize { /// the worker's result is then released when it arrives). pub fn released(pso: usize) -> usize { let Some(p) = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; - let done = p.done.lock().unwrap(); + let mut done = p.done.lock().unwrap(); if *done { - p.real.swap(0, Ordering::AcqRel) - } else { - // the worker stores its result into a Pending nobody will read: mark it orphaned - p.orphan.store(true, Ordering::Release); - 0 + return p.real.swap(0, Ordering::AcqRel); } + p.orphan.store(true, Ordering::Release); + // A queue can still own Pending. Take an unclaimed job here to release its descriptor + // immediately. A worker that already took it owns the descriptor until it finishes. + let cancelled = p.job.lock().unwrap().take(); + if cancelled.is_some() { + *done = true; + p.cv.notify_all(); + } + drop(done); + drop(cancelled); + 0 } /// `pso` is a stand-in whose real pipeline is still being built. diff --git a/crates/xcl/src/hle/d3d12x/queue_probe.rs b/crates/xcl/src/hle/d3d12x/queue_probe.rs new file mode 100644 index 0000000000..8c16457633 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/queue_probe.rs @@ -0,0 +1,363 @@ +//! Bounded submission diagnostics, based on the earlier XCL queue timeline experiment. +use std::collections::{HashMap, VecDeque}; +use std::io::{BufWriter, Write}; +use std::sync::{Arc, LazyLock, Mutex, Once}; +use std::time::Duration; +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::ID3D12Fence; + +const EVENTS: usize = 16_384; +const LISTS: usize = 1024; +const FENCES: usize = 48; +const OPS: usize = 4; + +#[derive(Clone, Copy)] +struct Event { + seq: u64, + us: u64, + thread: u32, + name: &'static str, + queue: usize, + object: usize, + link: u64, + value: u64, + detail: u64, +} +#[derive(Clone, Copy)] +struct Op { + name: &'static str, + pipeline: usize, + hashes: (u64, u64), + size: [u32; 3], +} +struct List { + generation: u64, + count: u64, + tail: [Option; OPS], + last_mesh_indirect: Option<(u64, Op)>, +} +struct Fence { + raw: Arc, + queue: usize, + completed: Option, + removed: bool, +} +struct Trace { + next: u64, + events: VecDeque, + lists: HashMap, + fences: HashMap, +} +impl Trace { + fn new() -> Self { + Self { + next: 0, + events: VecDeque::with_capacity(EVENTS), + lists: HashMap::new(), + fences: HashMap::new(), + } + } + fn push( + &mut self, + name: &'static str, + queue: usize, + object: usize, + link: u64, + value: u64, + detail: u64, + ) -> u64 { + self.next += 1; + if self.events.len() == EVENTS { + self.events.pop_front(); + } + self.events.push_back(Event { + seq: self.next, + us: (crate::log::uptime() * 1_000_000.0) as u64, + thread: unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }, + name, + queue, + object, + link, + value, + detail, + }); + self.next + } + fn reset(&mut self, list: usize) { + if self.lists.contains_key(&list) || self.lists.len() < LISTS { + let generation = self.push("list-reset", 0, list, 0, 0, 0); + self.lists.insert( + list, + List { + generation, + count: 0, + tail: [None; OPS], + last_mesh_indirect: None, + }, + ); + } + } +} + +static TRACE: LazyLock> = LazyLock::new(|| Mutex::new(Trace::new())); +pub(crate) fn enabled() -> bool { + static ON: LazyLock = LazyLock::new(|| std::env::var_os("XCL_QUEUE_PROBE").is_some()); + *ON +} + +pub(crate) fn event( + name: &'static str, + queue: usize, + object: usize, + link: u64, + value: u64, + detail: u64, +) -> u64 { + if !enabled() { + return 0; + } + TRACE + .lock() + .unwrap() + .push(name, queue, object, link, value, detail) +} +pub(super) fn reset(list: usize) { + if enabled() { + TRACE.lock().unwrap().reset(list); + } +} +pub(super) fn forget(list: usize) { + if enabled() { + TRACE.lock().unwrap().lists.remove(&list); + } +} +pub(super) fn op(list: usize, name: &'static str, pipeline: usize, size: [u32; 3]) { + if !enabled() { + return; + } + let hashes = super::real::pso_shaders(pipeline).unwrap_or_default(); + let mut t = TRACE.lock().unwrap(); + if !t.lists.contains_key(&list) { + t.reset(list); + } + if let Some(s) = t.lists.get_mut(&list) { + let op = Op { + name, + pipeline, + hashes, + size, + }; + s.tail[s.count as usize % OPS] = Some(op); + if name == "mesh-indirect" { + s.last_mesh_indirect = Some((s.count, op)); + } + s.count += 1; + } +} +pub(crate) fn submit(name: &'static str, queue: usize, lists: &[*mut std::ffi::c_void]) -> u64 { + if !enabled() { + return 0; + } + let mut t = TRACE.lock().unwrap(); + let id = t.push(name, queue, 0, 0, lists.len() as u64, 0); + for &list in lists.iter().take(32) { + let raw = list as usize; + let data = t.lists.get(&raw).map(|s| (s.generation, s.count, s.tail, s.last_mesh_indirect)); + let (generation, count) = data.as_ref().map_or((0, 0), |(g, n, _, _)| (*g, *n)); + let entry = t.push("list", queue, raw, id, generation, count); + if let Some((_, _, ops, last_mesh_indirect)) = data { + let oldest = count.saturating_sub(OPS as u64); + let older_mesh = last_mesh_indirect.filter(|(index, _)| *index < oldest).map(|(_, op)| op); + let tail = (oldest..count).filter_map(|index| ops[index as usize % OPS]); + for op in older_mesh.into_iter().chain(tail) { + let [x, y, z] = op.size; + let shader = t.push(op.name, queue, op.pipeline, entry, op.hashes.0, op.hashes.1); + t.push( + "groups", + queue, + z as usize, + shader, + u64::from(x), + u64::from(y), + ); + } + } + } + id +} + +/// Observe a signal already issued by XCL. This never enqueues additional GPU work. +pub(crate) fn signal( + name: &'static str, + queue: usize, + fence: &ID3D12Fence, + link: u64, + value: u64, + hr: i32, +) { + if !enabled() { + return; + } + let raw = fence.as_raw() as usize; + let candidate = { + let mut t = TRACE.lock().unwrap(); + t.push(name, queue, raw, link, value, u64::from(hr as u32)); + hr >= 0 && !t.fences.contains_key(&raw) && t.fences.len() < FENCES + }; + if candidate { + let fence = Arc::new(fence.clone()); + let mut t = TRACE.lock().unwrap(); + if t.fences.len() < FENCES { + t.fences.entry(raw).or_insert_with(|| Fence { + raw: fence.clone(), + queue, + completed: None, + removed: false, + }); + } + } +} +fn update_completed(last: &mut Option, removed: &mut bool, value: u64) -> bool { + if *removed { + return false; + } + if value == u64::MAX { + *removed = true; + } else if last.is_none_or(|old| value > old) { + *last = Some(value); + } else { + return false; + } + true +} + +fn completed(fence: usize, value: u64) { + if !enabled() { + return; + } + let mut t = TRACE.lock().unwrap(); + if let Some(f) = t.fences.get_mut(&fence) { + if !update_completed(&mut f.completed, &mut f.removed, value) { + return; + } + let (queue, last, removed) = (f.queue, f.completed.unwrap_or(0), f.removed); + t.push( + if removed { + "fence-removed" + } else { + "completed" + }, + queue, + fence, + 0, + value, + last, + ); + } +} +pub(crate) fn start() { + static STARTED: Once = Once::new(); + if !enabled() { + return; + } + STARTED.call_once(|| { + let _ = std::thread::Builder::new() + .name("xcl-queue-probe".into()) + .spawn(|| { + loop { + std::thread::sleep(Duration::from_millis(25)); + let mut watches = [const { None }; FENCES]; + let used = { + let t = TRACE.lock().unwrap(); + let mut used = 0; + for f in t.fences.values().filter(|f| !f.removed) { + watches[used] = Some(f.raw.clone()); + used += 1; + } + used + }; + for f in watches.into_iter().take(used).flatten() { + // Bypass the title hook and its sparse readback settlement. + let value = unsafe { super::real::fence_completed(&f) }; + completed(f.as_raw() as usize, value); + } + } + }); + }); +} + +pub(crate) fn snapshot(filename: &str) { + if !enabled() { + return; + } + let (events, fences) = { + let t = TRACE.lock().unwrap(); + let fences: Vec<_> = t + .fences + .iter() + .map(|(&raw, f)| (raw, f.queue, f.completed, f.removed)) + .collect(); + (t.events.clone(), fences) + }; + let result = (|| -> std::io::Result<()> { + let path = crate::state::data_dir().join("logs").join(filename); + let mut out = BufWriter::new(std::fs::File::create(path)?); + writeln!(out, "# clock xcl.log uptime, microseconds")?; + for (raw, queue, completed, removed) in fences { + writeln!( + out, + "# fence {raw:#x} queue {queue:#x} last_completed {completed:?} removed {removed}" + )?; + } + writeln!( + out, + "sequence\tmicroseconds\tthread\toperation\tqueue\tobject\tlink\tvalue\tdetail" + )?; + for e in events { + writeln!( + out, + "{}\t{}\t{}\t{}\t{:#x}\t{:#x}\t{}\t{}\t{}", + e.seq, e.us, e.thread, e.name, e.queue, e.object, e.link, e.value, e.detail + )?; + } + out.flush() + })(); + if let Err(e) = result { + crate::xlog_warn!("D3D12 queue probe: failed to save {filename}: {e}"); + } +} + +pub(super) fn device_removed() { + static SAVED: Once = Once::new(); + if enabled() { + SAVED.call_once(|| snapshot("queue-device-removed.tsv")); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn device_removal_keeps_last_valid_completion() { + let mut last = None; + let mut removed = false; + assert!(update_completed(&mut last, &mut removed, 19)); + assert!(!update_completed(&mut last, &mut removed, 18)); + assert!(update_completed(&mut last, &mut removed, u64::MAX)); + assert_eq!(last, Some(19)); + assert!(removed); + assert!(!update_completed(&mut last, &mut removed, 20)); + } + + #[test] + fn timeline_retains_the_latest_events() { + let mut trace = Trace::new(); + for _ in 0..EVENTS + 2 { + trace.push("test", 0, 0, 0, 0, 0); + } + assert_eq!(trace.events.len(), EVENTS); + assert_eq!(trace.events.front().unwrap().seq, 3); + assert_eq!(trace.events.back().unwrap().seq, EVENTS as u64 + 2); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9241a3a18d..b53013ed8b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -138,6 +138,9 @@ static FALLBACK_PSO: AtomicU64 = AtomicU64::new(0); static FAILED_PSO: AtomicU64 = AtomicU64::new(0); static FALLBACK_RS: AtomicU64 = AtomicU64::new(0); static TRANSLATED_PSO: AtomicU64 = AtomicU64::new(0); +/// console MS containers moved from the AS slot and translated (logged sparsely: a title +/// creates tens of thousands of these pipelines during boot) +static AS_SLOT_MS: AtomicU64 = AtomicU64::new(0); static TRANSLATE_ERRORS: Mutex> = Mutex::new(Vec::new()); /// XCL shader ABI root signature on the backend device (raw, kept for the process lifetime) static ABI_RS: AtomicUsize = AtomicUsize::new(0); @@ -198,6 +201,29 @@ pub fn uma_window_vas() -> Vec { UMA_BUFFER.lock().map(|g| g.iter().map(|b| b.1).collect()).unwrap_or_default() } +fn locate_gpu_window(va: u64, ranges: impl IntoIterator) -> Option<(usize, u64)> { + ranges.into_iter().enumerate().find_map(|(index, (base, size))| { + if base == 0 { + return None; + } + let offset = va.checked_sub(base)?; + (offset < size).then_some((index, offset)) + }) +} + +#[cfg(test)] +#[test] +fn dred_gpu_window_excludes_null_slots_and_unbacked_tails() { + let windows = [(0, 1 << 32), (0x1000, 0), (0x4000, 0x0800), (0x5000, 0x1000)]; + assert_eq!(locate_gpu_window(0, windows), None); + assert_eq!(locate_gpu_window(0x1000, windows), None); + assert_eq!(locate_gpu_window(0x4000, windows), Some((2, 0))); + assert_eq!(locate_gpu_window(0x47ff, windows), Some((2, 0x07ff))); + assert_eq!(locate_gpu_window(0x4800, windows), None); + assert_eq!(locate_gpu_window(0x524a, windows), Some((3, 0x024a))); + assert_eq!(locate_gpu_window(u64::MAX, windows), None); +} + /// The window buffer holding `len` bytes at UMA address `p`, and their offset in it. pub(super) fn uma_window_buffer(p: usize, len: usize) -> Option<(usize, u64)> { let u = crate::gpu::uma::get()?; @@ -298,40 +324,78 @@ unsafe fn check_uma_import(device: &ID3D12Device, u: &crate::gpu::uma::Uma, bufs Ok(format!("ok, {} window(s), {} µs", probes.len(), t0.elapsed().as_micros())) } +/// `XCL_UMA_SHADOW`: 1 = the committed windows get GPU copies without asking for a heap over +/// them (to try the path on a GPU that has `OpenExistingHeapFromAddress`), 0 = never. +fn shadow_choice() -> Option { + std::env::var("XCL_UMA_SHADOW").ok().map(|v| v != "0") +} + unsafe fn open_uma(device: &ID3D12Device) { let Some(u) = crate::gpu::uma::get() else { *UMA_ERROR.lock().unwrap() = "no UMA region".into(); return; }; - let open = |k: usize| -> Result<(usize, u64, usize), String> { - let (base, size) = u.window(k); + let buffer = |size: usize, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size 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, + Flags: flags, + ..Default::default() + }; + let open = |k: usize| -> Result, String> { + if shadow_choice() == Some(true) { + return Ok(None); + } let dev3: ID3D12Device3 = device.cast().map_err(|e| format!("ID3D12Device3: {e}"))?; - let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const c_void).map_err(|e| format!("OpenExistingHeapFromAddress (window {k}): {e}"))?; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size 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, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER, - ..Default::default() + match dev3.OpenExistingHeapFromAddress::(u.window(k).0 as *const c_void) { + Ok(heap) => Ok(Some(heap)), + Err(e) if e.code() == windows::Win32::Foundation::E_NOTIMPL && shadow_choice() != Some(false) => { + *UMA_ERROR.lock().unwrap() = format!("OpenExistingHeapFromAddress (window {k}): {e}"); + Ok(None) + } + Err(e) => Err(format!("OpenExistingHeapFromAddress (window {k}): {e}")), + } + }; + let shadow = |k: usize| -> Result { + let desc = D3D12_HEAP_DESC { + SizeInBytes: u.window(k).1 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 mut buf: Option = None; - device.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; - let buf = buf.ok_or("CreatePlacedResource")?; - let va = buf.GetGPUVirtualAddress(); - Ok((buf.into_raw() as usize, va, heap.into_raw() as usize)) + let mut heap: Option = None; + super::title_textures::own_work(|| device.CreateHeap(&desc, &mut heap)).map_err(|e| format!("CreateHeap (window {k}, {} MB of video memory): {e}", u.window(k).1 >> 20))?; + heap.ok_or_else(|| "CreateHeap".to_string()) }; let n = u.shader_windows(); let mut bufs: Vec<(usize, u64)> = vec![(0, 0); n]; let mut heaps: Vec> = vec![None; n]; + let mut shadows: Vec<(usize, ID3D12Resource)> = Vec::new(); for k in 0..n { if !u.is_committed_window(k) { continue; } - match open(k) { + let made = open(k).and_then(|heap| { + let shadowed = heap.is_none(); + let heap = match heap { + Some(h) => h, + None => shadow(k)?, + }; + let flags = if shadowed { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER }; + let mut buf: Option = None; + device.CreatePlacedResource(&heap, 0, &buffer(u.window(k).1, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; + let buf = buf.ok_or("CreatePlacedResource")?; + if shadowed { + shadows.push((k, buf.clone())); + } + let va = buf.GetGPUVirtualAddress(); + Ok((buf.into_raw() as usize, va, heap.into_raw() as usize)) + }); + match made { Ok((buf_raw, va, heap_raw)) => { bufs[k] = (buf_raw, va); heaps[k] = Some(heap_raw); @@ -343,7 +407,9 @@ unsafe fn open_uma(device: &ID3D12Device) { } } } - let check = if std::env::var("XCL_UMA_CHECK").is_ok_and(|v| v == "0") { + let check = if !shadows.is_empty() { + Ok("not run: the coherent window has a copy in video memory (no host-memory heaps on this D3D12)".into()) + } else if std::env::var("XCL_UMA_CHECK").is_ok_and(|v| v == "0") { Ok("off (XCL_UMA_CHECK=0)".into()) } else { check_uma_import(device, u, &bufs) @@ -367,6 +433,23 @@ unsafe fn open_uma(device: &ID3D12Device) { w0_va ); *UMA_HEAPS.lock().unwrap() = heaps; + for (k, buf) in &shadows { + let (base, size) = u.window(*k); + u.set_shadowed(); + if super::sparse::shadow_window(device, base, size, buf) { + crate::xlog_warn!( + "D3D12.X: UMA window {k} is not shared with the GPU ({}) \u{2013} {} MB of video memory at VA {:#x} stand for it: CPU writes are uploaded before each submit, GPU writes read back on Map and after the lists' memory writes", + match shadow_choice() { + Some(true) => "XCL_UMA_SHADOW=1", + _ => "OpenExistingHeapFromAddress is not implemented", + }, + size >> 20, + bufs[*k].1 + ); + } else { + crate::xlog_warn!("D3D12.X: UMA window {k} is not shared with the GPU and its copy in video memory is not kept in step"); + } + } // shaders take the windows from the shared descriptor heap (`pso::heap_windows`) if n > 1 && crate::gpu::recomp::pso::heap_windows() { let views: Vec<(usize, usize)> = bufs.iter().enumerate().map(|(k, b)| (b.0, u.window(k).1)).collect(); @@ -423,8 +506,8 @@ pub fn device_raw() -> *mut c_void { DEVICE.load(Ordering::Acquire) as *mut c_void } -/// The process's video memory on the device's adapter: (local, non-local) bytes in use. -pub fn video_memory() -> Option<(u64, u64)> { +/// The process's current usage and budget in bytes, for local and then non-local video memory. +pub fn video_memory() -> Option<[(u64, u64); 2]> { use windows::Win32::Graphics::Dxgi::*; let raw = device_raw(); let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }?; @@ -436,7 +519,7 @@ pub fn video_memory() -> Option<(u64, u64)> { let mut non_local = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut local).ok()?; adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut non_local).ok()?; - Some((local.CurrentUsage, non_local.CurrentUsage)) + Some([(local.CurrentUsage, local.Budget), (non_local.CurrentUsage, non_local.Budget)]) } } @@ -539,6 +622,9 @@ pub fn init() -> Result { d } }; + if std::env::var("XCL_D3D12_DUMP").is_ok_and(|value| value == "1") { + configure_directx_dump(&device); + } if debug { // the debug layer's messages into XCL's log (they otherwise go to a debugger only) if let Ok(q) = device.cast::() { @@ -556,6 +642,73 @@ pub fn init() -> Result { } } +/// Agility SDK 620 dump support is newer than the workspace's Windows bindings. +unsafe fn configure_directx_dump(device: &ID3D12Device) { + use windows::core::{GUID, HRESULT, IUnknown, IUnknown_Vtbl}; + + #[repr(C)] + #[derive(Default)] + struct DumpSupport { + supported_by_os: i32, + driver_tier: i32, + driver_options: u32, + } + + #[repr(C)] + struct DumpFileVtable { + base: IUnknown_Vtbl, + configure: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT, + set_callbacks: unsafe extern "system" fn( + *mut c_void, + Option u32>, + Option, + ), + add_blob: unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u64) -> HRESULT, + retain: unsafe extern "system" fn(*mut c_void, i32), + } + + #[repr(transparent)] + #[derive(Clone)] + struct DumpFile(IUnknown); + + unsafe impl Interface for DumpFile { + type Vtable = DumpFileVtable; + const IID: GUID = GUID::from_u128(0xdb82bfed_784d_40ea_aebf_08bcd7f0a9e4); + } + + const D3D12_FEATURE_DUMP_FILE: D3D12_FEATURE = D3D12_FEATURE(71); + const NO_OVERHEAD: u32 = 1; + let mut support = DumpSupport::default(); + if let Err(error) = device.CheckFeatureSupport( + D3D12_FEATURE_DUMP_FILE, + (&mut support as *mut DumpSupport).cast(), + std::mem::size_of::() as u32, + ) { + crate::xlog_warn!("D3D12 dump support query failed: {error}"); + return; + } + crate::xlog_info!( + "D3D12 dump support: OS {}, driver tier {}, options {:#x}", + support.supported_by_os != 0, support.driver_tier, support.driver_options, + ); + if support.supported_by_os == 0 { + return; + } + match device.cast::() { + Ok(dump) => { + if support.driver_options & NO_OVERHEAD != 0 { + let hr = (dump.vtable().configure)(dump.as_raw(), NO_OVERHEAD); + if hr.is_err() { + crate::xlog_warn!("D3D12 dump driver configuration failed: {hr:?}"); + } + } + (dump.vtable().retain)(dump.as_raw(), 1); + crate::xlog_info!("D3D12 dump retention enabled"); + } + Err(error) => crate::xlog_warn!("D3D12 dump interface unavailable: {error}"), + } +} + /// A debug layer message: errors and warnings into the log – the first 8 of each message id /// (3 000 in all). One cap for all of them (200) was used up in seconds by two per-frame state /// errors of a retail game, long before the message that came with its device removal. @@ -578,6 +731,21 @@ unsafe extern "system" fn debug_message(_category: D3D12_MESSAGE_CATEGORY, sever } let t = if text.is_null() { String::new() } else { String::from_utf8_lossy(text.as_bytes()).into_owned() }; crate::xlog_warn!("D3D12 debug layer ({}, id {}): {t}", if severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { "error" } else { "warning" }, id.0); + if id.0 == 1047 && super::queue_probe::enabled() { + static MAP_LOGGED: AtomicBool = AtomicBool::new(false); + static EXEC_LOGGED: AtomicBool = AtomicBool::new(false); + let mapping = t.contains("::UpdateTileMappings:"); + let seen = if mapping { &MAP_LOGGED } else { &EXEC_LOGGED }; + if !seen.swap(true, Ordering::Relaxed) { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + let mut stack = [std::ptr::null_mut::(); 20]; + let n = RtlCaptureStackBackTrace(1, stack.len() as u32, stack.as_mut_ptr(), std::ptr::null_mut()); + let frames: Vec<_> = stack[..n as usize].iter().map(|&raw| crate::modules::describe_address(raw as usize)).collect(); + crate::xlog_warn!("D3D12 validation 1047 on {}: {}", if mapping { "mapping" } else { "submission" }, frames.join(" < ")); + super::queue_probe::event("validation-1047", 0, 0, 0, u64::from(mapping), 0); + super::queue_probe::snapshot(if mapping { "queue-validation-map-1047.tsv" } else { "queue-validation-submit-1047.tsv" }); + } + } } type QiFn = unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT; @@ -726,6 +894,63 @@ pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { *(obj as *mut usize) = ext; } +/// A successful QueryInterface owns a reference to the returned interface. +unsafe fn supports_pc_interface(obj: *mut c_void, qi: QiFn, iid: &GUID) -> bool { + let mut queried = std::ptr::null_mut(); + if qi(obj, iid, &mut queried) < 0 || queried.is_null() { + return false; + } + // The debug layer can return a pointer with a different Release implementation. + drop(windows::core::IUnknown::from_raw(queried)); + true +} + +#[cfg(test)] +mod interface_probe_tests { + use super::*; + + #[repr(C)] + struct InterfaceStub { + vtable: *const usize, + queried: *mut c_void, + release_calls: u32, + } + + unsafe extern "system" fn query(this: *mut c_void, _: *const GUID, out: *mut *mut c_void) -> HRESULT { + *out = (*this.cast::()).queried; + S_OK + } + + unsafe extern "system" fn release_caller(_: *mut c_void) -> u32 { + 1 + } + + unsafe extern "system" fn release_queried(this: *mut c_void) -> u32 { + (*this.cast::()).release_calls += 1; + 1 + } + + #[test] + fn probe_releases_the_returned_interface_with_its_vtable() { + let queried_vtable = [query as usize, release_caller as usize, release_queried as usize]; + let mut queried = InterfaceStub { + vtable: queried_vtable.as_ptr(), + queried: std::ptr::null_mut(), + release_calls: 0, + }; + let caller_vtable = [query as usize, release_caller as usize, release_caller as usize]; + let mut caller = InterfaceStub { + vtable: caller_vtable.as_ptr(), + queried: (&mut queried as *mut InterfaceStub).cast(), + release_calls: 0, + }; + let iid = layout::parse_guid("00000000-0000-0000-c000-000000000046"); + + assert!(unsafe { supports_pc_interface((&mut caller as *mut InterfaceStub).cast(), query, &iid) }); + assert_eq!(queried.release_calls, 1); + } +} + unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { if let Some(c) = CLASSES.lock().unwrap().iter().find(|c| c.orig == orig && c.kind == kind) { return c.ext; @@ -734,13 +959,9 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { // most derived PC interface this object implements let chain = layout::chain(kind.base()); let qi: QiFn = std::mem::transmute(*ot); - let release: RefFn = std::mem::transmute(*ot.add(2)); let mut iface = *chain.last().expect("layout chain"); for i in &chain { - let iid = layout::parse_guid(i.iid); - let mut out = std::ptr::null_mut(); - if qi(obj, &iid, &mut out) >= 0 && !out.is_null() { - release(out); + if supports_pc_interface(obj, qi, &layout::parse_guid(i.iid)) { iface = i; break; } @@ -1036,6 +1257,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (90, l::write32_bottom_of_shader_x as usize), (93, l::kickoff_x as usize), (94, l::set_depth_bias_x as usize), + (127, b::dispatch_mesh as usize), // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) (146, l::uav_barrier_x as usize), (148, b::allocate_upload_memory as usize), @@ -1324,11 +1546,19 @@ unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC None } +fn uma_shadowed() -> bool { + crate::gpu::uma::get().is_some_and(|u| u.shadowed()) +} + /// Sanitize a console buffer description and initial state for placement in a coherent /// cross-adapter UMA heap (`OpenExistingHeapFromAddress`). fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize) -> (D3D12_RESOURCE_DESC, u32) { let mut d = *desc; - d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF) | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF); + // a shadowed window's heap is video memory, not a cross-adapter heap over process memory + if !uma_shadowed() { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; (d, state as u32 & PC_RESOURCE_STATES) @@ -1378,6 +1608,10 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta return None; } UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + // a readback buffer in a shadowed window: what the GPU copied into it is in video memory + if readback_on_null_map && u.shadowed() { + note_sparse_readback(*ppv as usize); + } // Map must hand out the same memory the shaders read (checked once) static CHECKED: AtomicU64 = AtomicU64::new(0); if CHECKED.fetch_add(1, Ordering::Relaxed) == 0 { @@ -1423,7 +1657,9 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: return Some(hr); } let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; - d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + if !u.shadowed() { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; d.Width = (delta + bytes) as u64; @@ -1492,7 +1728,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v // 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) { - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p)) { + if crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(p)) { if !range.is_null() { let r = *(range as *const D3D12_RANGE); if r.End > r.Begin { @@ -1593,6 +1829,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { // (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 mut small_slot_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 { @@ -1623,7 +1860,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { m.remove(&(this as usize)); } super::sparse::forget_buffer(this as usize); - super::vram::forget(this as usize); + small_slot_held = super::vram::forget(this as usize, held); super::title_textures::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { @@ -1635,7 +1872,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } } if held { - super::late_release::hold(this as usize); + super::late_release::hold(this as usize, small_slot_held); } n } @@ -2523,7 +2760,11 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::PipelineState => v.push(("Release", pso_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), Kind::Heap => v.push(("Release", mem_heap_release as usize)), - Kind::Fence => v.push(("Signal", fence_signal as usize)), + Kind::Fence => v.extend_from_slice(&[ + ("Signal", fence_signal as usize), + ("GetCompletedValue", fence_get_completed_value as usize), + ("SetEventOnCompletion", fence_set_event_on_completion as usize), + ]), _ => {} } v @@ -2807,7 +3048,7 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v let d = super::device_x::pc_resource_desc(&x); let st = state as u32 & PC_RESOURCE_STATES; if let Some(hr) = place_at_title_address(this, block + offset, &d, st, clear as *const c_void, riid, ppv) { - if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && cpu_readback && crate::gpu::uma::get().is_some_and(|u| u.is_sparse(block + offset)) { + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && cpu_readback && crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(block + offset)) { let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); if st == D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 && (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 as u32) == 0 { note_sparse_readback(*ppv as usize); @@ -3597,6 +3838,7 @@ fn compile_slots(bytes: usize) -> &'static Slots { /// A driver compile of `bytes` of DXIL through `build`: a huge one on an `xcl-pso*` worker /// waits for its slot first (`big_compile_turn`; not a title thread's, nor one the title waits /// for). Logs its time, size and whether it was gated. +#[cfg(test)] fn driver_compile(kind: &str, bytes: usize, gate: bool, build: impl FnOnce() -> R) -> R { driver_compile_identified(kind, bytes, gate, None, build).0 } @@ -3913,8 +4155,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { - keep_compute_blob(key, *ppv, dxil.len()); - if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { + if let (Some(p), Some(b)) = (disk.as_deref(), keep_compute_blob(key, *ppv, dxil.len())) { driver_cache::keep(p, &b, in_driver); } } else if reused && from_disk { @@ -3944,6 +4185,11 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } note_translated_compute(hr, ppv); + if super::gpu_profile::on() { + let hash = crate::gpu::shader::fnv64(cs); + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (hash, 0)); + super::gpu_profile::note_compute(hash, cs, dxil.len(), wave32_only(this)); + } crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", dxil.len(), @@ -3983,7 +4229,7 @@ pub(crate) mod driver_cache { format!("gfx-{hash:016x}-{bytes:x}.pso") } - fn enabled() -> bool { + pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0")) } @@ -3996,16 +4242,26 @@ pub(crate) mod driver_cache { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) } + pub(super) fn two_pass_threshold() -> std::time::Duration { + static MIN: std::sync::OnceLock = std::sync::OnceLock::new(); + *MIN.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE_MIN_MS").ok() + .and_then(|v| v.trim().parse().ok()).map_or(KEEP, std::time::Duration::from_millis)) + } + pub fn load(p: &Path) -> Option> { std::fs::read(p).ok().filter(|b| !b.is_empty()) } + pub(super) fn stats() -> (u64, u64, u64) { + (HITS.load(Ordering::Relaxed), STALE.load(Ordering::Relaxed), STORED.load(Ordering::Relaxed)) + } + /// A pipeline was made from a kept blob (`ok`), or the driver refused the blob: dropped. pub fn note(ok: bool, p: Option<&Path>) { if ok { let n = HITS.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { - crate::xlog_info!("D3D12.X: {n} compute pipelines made from the driver's blob of an earlier run (kept on disk)"); + crate::xlog_info!("D3D12.X: {n} pipelines made from the driver's blob of an earlier run (kept on disk)"); } } else { if let Some(p) = p { @@ -4055,7 +4311,11 @@ pub(crate) mod driver_cache { /// Keep `blob`, of a build that took `took`, for the next run. pub fn keep(p: &Path, blob: &[u8], took: std::time::Duration) { - if took >= KEEP && write(p, blob) { + keep_at(p, blob, took, KEEP); + } + + pub(super) fn keep_at(p: &Path, blob: &[u8], took: std::time::Duration, min: std::time::Duration) { + if took >= min && write(p, blob) { let n = STORED.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { crate::xlog_info!("D3D12.X: {n} driver blobs kept on disk for the next run (this one: {} ms, {} KB)", took.as_millis(), blob.len() >> 10); @@ -4141,8 +4401,8 @@ pub(crate) mod driver_cache { } } -/// The driver's compiled form of translated compute programs (`GetCachedBlob`), -/// by (DXIL hash, root signature, flags), up to `COMPUTE_BLOBS_MAX` bytes in all. +/// Driver blobs, keyed by (identity hash, root signature, domain or compute flags), +/// up to `COMPUTE_BLOBS_MAX` bytes across ordinary compute and both two-pass PSOs. static COMPUTE_BLOBS: Mutex>>, usize)>> = Mutex::new(None); const COMPUTE_BLOBS_MAX: usize = 512 << 20; /// smaller programs compile in milliseconds: not kept @@ -4186,10 +4446,32 @@ mod compute_blob_tests { *total += 3; } assert_eq!(super::compute_blob(key).as_deref().map(|v| v.len()), Some(3)); - let before = super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1; super::forget_compute_blob(key); - assert!(super::compute_blob(key).is_none()); - assert_eq!(super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1, before - 3); + let guard = super::COMPUTE_BLOBS.lock().unwrap(); + let (map, total) = guard.as_ref().unwrap(); + assert!(!map.contains_key(&key)); + assert_eq!(*total, map.values().map(|blob| blob.len()).sum::()); + } + + /// A blob the in-memory store has no room for still goes back to its caller (which writes + /// it to the disk cache); one that fits is kept in memory as well. + #[test] + fn a_blob_over_the_memory_budget_still_reaches_its_caller() { + let mut store = (super::HashMap::new(), 0usize); + let fits = super::remember_compute_blob(&mut store, (1, 2, 0), std::sync::Arc::new(vec![7u8; 64])).expect("a blob that fits"); + assert_eq!(fits.len(), 64); + assert_eq!(store.1, 64); + assert!(store.0.contains_key(&(1, 2, 0))); + + // the store is full: nothing more is kept in memory … + store.1 = super::COMPUTE_BLOBS_MAX; + let over = super::remember_compute_blob(&mut store, (3, 4, 0), std::sync::Arc::new(vec![9u8; 128])); + assert!(!store.0.contains_key(&(3, 4, 0))); + assert_eq!(store.1, super::COMPUTE_BLOBS_MAX, "a blob that is not kept is not charged"); + // … but the caller gets it for the disk + assert_eq!(over.expect("the blob for the disk cache").as_slice(), &[9u8; 128][..]); + + assert!(super::remember_compute_blob(&mut store, (5, 6, 0), std::sync::Arc::new(Vec::new())).is_none(), "an empty blob is nothing to keep"); } } @@ -4216,20 +4498,44 @@ unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option> { (!bytes.is_empty()).then_some(bytes) } +/// Insert an already-read blob into the same bounded store used by ordinary compute PSOs. +fn store_compute_blob(key: (u64, usize, i32), bytes: std::sync::Arc>) { + let mut store = COMPUTE_BLOBS.lock().unwrap(); + let _ = remember_compute_blob(store.get_or_insert_with(Default::default), key, bytes); +} + /// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute -/// passes owned by `TwoPassPso`). -unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || compute_blob(key).is_some() { - return; +/// passes owned by `TwoPassPso`), for the disk cache; kept in memory too while `COMPUTE_BLOBS_MAX` +/// has room. +unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) -> Option>> { + if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() { + return None; } - let Some(bytes) = read_pso_cached_blob(pso) else { return }; + if let Some(b) = compute_blob(key) { + return Some(b); + } + let bytes = read_pso_cached_blob(pso)?; let mut g = COMPUTE_BLOBS.lock().unwrap(); - let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > COMPUTE_BLOBS_MAX { - return; + remember_compute_blob(g.get_or_insert_with(Default::default), key, std::sync::Arc::new(bytes)) +} + +/// `bytes`, the driver's blob of the pipeline `key`, for its caller – and in `store` (the blobs +/// kept in memory and their bytes in all) while `COMPUTE_BLOBS_MAX` has room. The blob is +/// returned either way: it used to reach the disk cache only when the store had taken it, so +/// once the store was full no later build was kept on disk, and a retail title's slowest +/// pipelines (20 to 150 s each in the driver) were built again in every run. +fn remember_compute_blob(store: &mut (HashMap<(u64, usize, i32), std::sync::Arc>>, usize), key: (u64, usize, i32), bytes: std::sync::Arc>) -> Option>> { + if bytes.is_empty() { + return None; } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + if let Some(current) = store.0.get(&key) { + return Some(current.clone()); + } + if bytes.len() <= COMPUTE_BLOBS_MAX - store.1 { + store.1 += bytes.len(); + store.0.insert(key, bytes.clone()); + } + Some(bytes) } /// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), @@ -4714,6 +5020,10 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const note_pso_rs(*ppv, rs); TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); + if super::gpu_profile::on() && !super::present::trace_frame() { + let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); + } if super::present::trace_frame() { let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); @@ -4782,19 +5092,23 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const /// The root signature pointer is kept as is (the translated paths replace it). #[allow(dead_code)] // the vectors only keep the copies alive enum OwnedDesc { - Compute(Box, Vec>), - Graphics(Box, Vec>, Vec, Vec), - Stream(Box<[usize; 2]>, Vec, Vec>), + Compute(Box, Vec), + Graphics(Box, Vec, Vec, Vec), + Stream(Box<[usize; 2]>, Vec, Vec), } 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. -pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { +pub(crate) fn shaders_key>(blobs: &[B]) -> u64 { + shaders_key_from_hashes(blobs.iter().map(|b| crate::gpu::shader::fnv64(b.as_ref()))) +} + +fn shaders_key_from_hashes(hashes: impl Iterator) -> 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 shader in hashes { + h = (h ^ shader).wrapping_mul(0x0000_0100_0000_01b3); } h | 1 } @@ -4809,17 +5123,53 @@ mod shaders_key_tests { assert_ne!(key, super::shaders_key(&[b.clone(), a.clone()])); assert_ne!(key, super::shaders_key(&[a.clone()])); assert_ne!(key, super::shaders_key(&[a, vec![4u8, 6]])); - assert_ne!(super::shaders_key(&[]), 0); + assert_ne!(super::shaders_key::>(&[]), 0); + } + + #[test] + fn pipelines_with_the_same_shader_share_one_copy_of_its_bytes() { + let a = super::intern_shader_blob(&[7u8, 1, 2, 3, 0x5a]); + let b = super::intern_shader_blob(&[7u8, 1, 2, 3, 0x5a]); + assert!(std::sync::Arc::ptr_eq(&a, &b)); + let c = super::intern_shader_blob(&[7u8, 1, 2, 3, 0x5b]); + assert!(!std::sync::Arc::ptr_eq(&a, &c)); + assert_eq!(&*c.bytes, &[7u8, 1, 2, 3, 0x5b]); + assert_eq!(super::shaders_key_from_hashes([a.hash].into_iter()), super::shaders_key(&[vec![7u8, 1, 2, 3, 0x5a]])); + drop((a, b)); + let d = super::intern_shader_blob(&[7u8, 1, 2, 3, 0x5a]); + assert_eq!(&*d.bytes, &[7u8, 1, 2, 3, 0x5a], "a copy every pipeline released is made again"); + } + + #[test] + fn colliding_shaders_keep_their_bytes_and_release_their_entries() { + use std::sync::Arc; + let hash = 0x827_2024_0000; + let a = super::intern_shader_with_hash(hash, b"same length a"); + let b = super::intern_shader_with_hash(hash, b"same length b"); + assert!(!Arc::ptr_eq(&a, &b)); + assert_eq!(&*a.bytes, b"same length a"); + assert_eq!(&*b.bytes, b"same length b"); + let weak = Arc::downgrade(&a); + std::thread::scope(|scope| { + let find = scope.spawn(|| super::intern_shader_with_hash(hash, b"same length a")); + assert!(Arc::ptr_eq(&a, &find.join().unwrap())); + }); + drop(a); + assert!(weak.upgrade().is_none()); + assert!(Arc::ptr_eq(&b, &super::intern_shader_with_hash(hash, b"same length b"))); + let key = (hash, b.bytes.len()); + drop(b); + let table = super::SHADER_BLOBS.lock().unwrap(); + assert!(!table.as_ref().is_some_and(|t| t.contains_key(&key))); } } impl OwnedDesc { fn shaders_key(&self) -> u64 { - shaders_key(match self { - OwnedDesc::Compute(_, b) => b, - OwnedDesc::Graphics(_, b, ..) => b, - OwnedDesc::Stream(_, _, b) => b, - }) + let blobs = match self { + Self::Compute(_, b) | Self::Graphics(_, b, ..) | Self::Stream(_, _, b) => b, + }; + shaders_key_from_hashes(blobs.iter().map(|blob| blob.hash)) } fn ptr(&self) -> *const c_void { @@ -4831,12 +5181,88 @@ impl OwnedDesc { } } -/// Copy a shader blob into `blobs` and point `b` at the copy. -unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>) { +type SharedShader = std::sync::Arc; +type WeakShader = std::sync::Weak; +type ShaderBlobTable = HashMap<(u64, usize), Vec>; +static SHADER_BLOBS: Mutex> = Mutex::new(None); + +struct ShaderBlob { + hash: u64, + // The last strong owner releases the payload even if a weak reference survives. + bytes: Box<[u8]>, +} + +impl Drop for ShaderBlob { + fn drop(&mut self) { + let mut guard = SHADER_BLOBS.lock().unwrap(); + let Some(table) = guard.as_mut() else { return }; + let key = (self.hash, self.bytes.len()); + if let std::collections::hash_map::Entry::Occupied(mut entry) = table.entry(key) { + // An intern may already have added a replacement while this destructor waited. + entry.get_mut().retain(|blob| !std::ptr::eq(blob.as_ptr(), self)); + if entry.get().is_empty() { + entry.remove(); + } + } + if table.is_empty() { + *guard = None; + } else if table.capacity() > table.len().saturating_mul(4).max(256) { + table.shrink_to(table.len().saturating_mul(2)); + } + } +} + +fn intern_shader_blob(bytes: &[u8]) -> SharedShader { + intern_shader_with_hash(crate::gpu::shader::fnv64(bytes), bytes) +} + +fn intern_shader_with_hash(hash: u64, bytes: &[u8]) -> SharedShader { + // Nonmatching upgraded owners must be dropped after the table lock. A final owner + // needs the same lock to remove its entry. The ordinary hit needs no temporary allocation. + let mut collisions = Vec::new(); + let mut guard = SHADER_BLOBS.lock().unwrap(); + let bucket = guard.get_or_insert_with(HashMap::new).entry((hash, bytes.len())).or_insert_with(|| Vec::with_capacity(1)); + for blob in bucket.iter().filter_map(WeakShader::upgrade) { + if &*blob.bytes == bytes { + return blob; + } + collisions.push(blob); + } + let blob = std::sync::Arc::new(ShaderBlob { hash, bytes: bytes.into() }); + bucket.push(std::sync::Arc::downgrade(&blob)); + blob +} + +/// Current bytecode ownership for the activity log. Metadata counts the usable hash-table +/// slots, weak-reference vector capacities and Arc headers, excluding allocator overhead. +pub fn pending_shader_memory() -> (usize, usize, usize, usize) { + let guard = SHADER_BLOBS.lock().unwrap(); + let Some(table) = guard.as_ref() else { return (0, 0, 0, 0) }; + let mut unique = 0; + let mut referenced = 0; + let mut live = 0; + let mut metadata = table.capacity() * std::mem::size_of::<((u64, usize), Vec)>(); + for (&(_, size), bucket) in table { + let arc = std::mem::size_of::() + 2 * std::mem::size_of::(); + metadata += bucket.capacity() * std::mem::size_of::() + bucket.len() * arc; + for weak in bucket { + let refs = weak.strong_count(); + if refs != 0 { + live += 1; + unique += size; + referenced += size * refs; + } + } + } + (live, unique, referenced, metadata) +} + +/// Share or copy a shader blob into `blobs` and point `b` at it. +unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec) { if let Some(bytes) = shader_bytes(b) { - blobs.push(bytes.to_vec()); + blobs.push(intern_shader_blob(bytes)); let v = blobs.last().unwrap(); - *b = bytecode(v); + *b = bytecode(&v.bytes); } else { *b = D3D12_SHADER_BYTECODE::default(); } @@ -4883,7 +5309,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { return None; } let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); - let mut blobs: Vec> = Vec::new(); + let mut blobs: Vec = Vec::new(); let mut off = 0usize; while off + 8 <= size { let ty = u32::from_le_bytes(buf[off..off + 4].try_into().ok()?); @@ -4894,8 +5320,9 @@ unsafe fn own_stream(desc: *const c_void) -> Option { 1..=6 | 24 | 25 => { let (p, n) = (word(&buf, 0) as usize, word(&buf, 1) as usize); 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()); + let slice = std::slice::from_raw_parts(p as *const u8, n); + blobs.push(intern_shader_blob(slice)); + buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().bytes.as_ptr() as u64).to_le_bytes()); } } 7 | 12 | 22 if buf[at..at + psize].iter().any(|&b| b != 0) => return None, @@ -5276,10 +5703,116 @@ fn passthrough_mesh_stream_accepts_a_triangle_driver_blob() { } } -#[allow(dead_code)] // Consumed by the stacked driver-cache integration. mod two_pass_identity; +use two_pass_identity::{two_pass_cs_key, two_pass_stream_key, Fnv64}; + +/// Persistent driver-cache counters for the current process: (hits, rejected, saved). +#[doc(hidden)] +pub fn driver_cache_stats() -> (u64, u64, u64) { + driver_cache::stats() +} + +fn two_pass_driver_id(device: *mut c_void) -> Option { + use windows::Win32::Graphics::Dxgi::*; + let dev = unsafe { ID3D12Device::from_raw_borrowed(&device) }?; + let luid = unsafe { dev.GetAdapterLuid() }; + let key = (luid.HighPart, luid.LowPart); + static IDS: OnceLock>>> = OnceLock::new(); + let mut ids = IDS.get_or_init(Default::default).lock().unwrap(); + *ids.entry(key).or_insert_with(|| unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(luid).ok()?; + let desc = adapter.GetDesc().ok()?; + let version = adapter.CheckInterfaceSupport(&IDXGIDevice::IID).ok()?; + let mut h = Fnv64::new(); + h.u32(desc.VendorId); + h.u32(desc.DeviceId); + h.u32(desc.SubSysId); + h.u32(desc.Revision); + h.u64(version as u64); + Some(h.finish()) + }) +} + +struct TwoPassBlob { + key: (u64, usize, i32), + disk: Option, +} + +impl TwoPassBlob { + fn new(hash: u64, bytes: usize, rs: *mut c_void, mesh: bool, persist: bool) -> Self { + let (prefix, tag) = if mesh { ("tp-ms", 0x5450_0001) } else { ("tp-cs", 0x5450_0002) }; + let disk = persist.then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join( + format!("{prefix}-{hash:016x}-{bytes:x}-0.pso"), + )); + Self { key: (hash, rs as usize, tag), disk } + } +} + +/// Try the shared RAM cache first, then disk. Discard the disk counterpart of a +/// rejected RAM blob as well, so a later process cannot load the rejected entry. +unsafe fn build_two_pass_pso( + kind: &str, + bytes: usize, + cache: Option<&TwoPassBlob>, + take_cold_slot: &mut impl FnMut(), + mut create: impl FnMut(Option<&[u8]>, *mut *mut c_void) -> HRESULT, +) -> Result<(HRESULT, ID3D12PipelineState, bool), HRESULT> { + let mut attempt = |blob: Option<&[u8]>| { + let mut raw = std::ptr::null_mut(); + let (hr, took) = driver_compile_identified(kind, bytes, false, cache.map(|c| (c.key.0, blob.is_some())), || { + create(blob, &mut raw) + }); + // Own even a partial result so any failure releases it before a retry. + let pso = (!raw.is_null()).then(|| ID3D12PipelineState::from_raw(raw)); + match pso { + Some(pso) if hr >= 0 => Ok((hr, pso, took)), + _ => Err(if hr < 0 { hr } else { E_INVALIDARG }), + } + }; + if let Some(cache) = cache { + let disk = cache.disk.as_deref(); + let mem = compute_blob(cache.key); + let from_disk = mem.is_none(); + let cached = mem.or_else(|| disk.and_then(driver_cache::load).map(std::sync::Arc::new)); + if let Some(blob) = cached { + if let Ok((hr, pso, _)) = attempt(Some(&blob)) { + if from_disk { + driver_cache::note(true, None); + store_compute_blob(cache.key, blob); + } + return Ok((hr, pso, true)); + } + // A different thread may already have installed a replacement. + if let Some((map, total)) = COMPUTE_BLOBS.lock().unwrap().as_mut() { + if map.get(&cache.key).is_some_and(|b| std::sync::Arc::ptr_eq(b, &blob)) { + *total -= map.remove(&cache.key).unwrap().len(); + } + } + if from_disk || disk.is_some_and(|p| p.is_file()) { + driver_cache::note(false, disk); + } + } + } + take_cold_slot(); + let (hr, pso, took) = attempt(None)?; + if let Some(cache) = cache { + let min = driver_cache::two_pass_threshold(); + let disk = cache.disk.as_deref().filter(|_| took >= min); + let keep_ram = bytes >= COMPUTE_BLOB_MIN_DXIL || took >= min; + let blob = (disk.is_some() || keep_ram).then(|| read_pso_cached_blob(pso.as_raw())).flatten(); + if let Some(blob) = blob.filter(|b| !b.is_empty()) { + if let Some(path) = disk { + driver_cache::keep_at(path, &blob, took, min); + } + if keep_ram { + store_compute_blob(cache.key, std::sync::Arc::new(blob)); + } + } + } + Ok((hr, pso, false)) +} -/// The console PS of a two-pass pipeline (a PC PS passes as it is). /// The PS of a two-pass pipeline (DXIL, static samplers – a PC PS passes as it is). fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option>, Vec), String> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; @@ -5290,86 +5823,233 @@ fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option> } } -/// Create the mesh pipeline (`stream`, RS and shaders already in it) and the compute pass; -/// the title gets the mesh pipeline state. +/// Build both PSOs. A draw executes the NGG compute pass first, then the passthrough mesh graphics pass. #[allow(clippy::too_many_arguments)] -unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, ps_samplers: &[crate::gpu::recomp::pso::StaticSampler], kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; - let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); - let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; - // the mesh pass and its compute pass: one turn for both - let bytes = stream.shader_bytes() + tp.cs.len(); - let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); - let waited = std::time::Instant::now(); - let _slot = gate.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)).flatten(); - if gate { - crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated: {}, waited {} ms", _slot.is_some(), waited.elapsed().as_millis()); - } - let hr = driver_compile(kind, stream.shader_bytes(), false, || finish_pso(this, fs, desc.as_ptr() as *const c_void, riid, ppv)); - if hr < 0 { - note_translation_error(format!("the driver rejected the mesh pipeline from the console {kind} ({hr:#x})")); - return E_INVALIDARG; + if ppv.is_null() { return E_INVALIDARG } + *ppv = std::ptr::null_mut(); + + let driver = two_pass_driver_id(this); + let persist = driver.is_some() && driver_cache::enabled(); + let windows = crate::gpu::recomp::pso::mem_windows(); + let cs = TwoPassBlob::new(two_pass_cs_key(&tp.cs, &tp.samplers, driver.unwrap_or(0), windows), tp.cs.len(), rs, false, persist); + let mesh = two_pass_stream_key(&stream.0, ps_samplers, driver.unwrap_or(0), windows) + .map(|(h, n)| TwoPassBlob::new(h, n, mesh_rs, true, persist)); + if mesh.is_none() && pso_trace() { + static REJECTED_KEYS: AtomicU64 = AtomicU64::new(0); + if REJECTED_KEYS.fetch_add(1, Ordering::Relaxed) < 12 { + let types = stream_subobjects(&stream.0).map(|s| s.into_iter().map(|(ty, _)| ty).collect::>()); + crate::xlog_info!("D3D12.X: two-pass {kind} graphics cache key unavailable for stream subobjects {types:?}"); + } } + + // Take at most one cold turn for the pair, also when a cached attempt needs a retry. + let bytes = stream.shader_bytes() + tp.cs.len(); + let mut cold_slot = None; + let mut take_cold_slot = || { + cold_slot.get_or_insert_with(|| { + let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + gate.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)).flatten() + }); + }; + + let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); + let mesh_result = build_two_pass_pso("passthrough mesh graphics pass", stream.shader_bytes(), mesh.as_ref(), &mut take_cold_slot, |blob, out| { + let mut cached_stream; + let stream = if let Some(blob) = blob { + cached_stream = StreamOut(stream.0.clone(), stream.1); + cached_stream.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: blob.as_ptr().cast(), CachedBlobSizeInBytes: blob.len(), + }); + &cached_stream + } else { + stream + }; + let desc = [stream.0.len(), stream.0.as_ptr() as usize]; + finish_pso(this, fs, desc.as_ptr().cast(), riid, out) + }); + let (hr, mesh_pso, mesh_reused) = match mesh_result { + Ok(result) => result, + Err(hr) => { + note_translation_error(format!("the driver rejected the mesh pipeline from the console {kind} ({hr:#x})")); + return E_INVALIDARG; + } + }; + let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); - let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); - cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); - cdesc.CS = bytecode(&tp.cs); - // Reuse the compiled driver blob of the compute pass across all `(MS/GS, PS)` pipelines that - // share `tp.cs` (in memory and on disk), matching `translated_compute_pso_once`. - let ckey = compute_blob_key(&tp.cs, rs as usize, 0); - let mut ccached = compute_blob(ckey); - let cdisk = driver_cache::path(&tp.cs, 0); - let cfrom_disk = ccached.is_none(); - if cfrom_disk { - ccached = cdisk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); - } - if let Some(b) = &ccached { - cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; - } + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + desc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + desc.CS = bytecode(&tp.cs); let iid = pc_iid(Kind::PipelineState); - let mut compute: *mut c_void = std::ptr::null_mut(); - let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, || { - driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) - }); - if hc < 0 && ccached.is_some() { - forget_compute_blob(ckey); - if cfrom_disk { - driver_cache::note(false, cdisk.as_deref()); - } - cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); - compute = std::ptr::null_mut(); - let (retried, took) = driver_compile_identified("compute pass retry", tp.cs.len(), false, None, || { - driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) + let compute_result = build_two_pass_pso("NGG compute pass", tp.cs.len(), Some(&cs), &mut take_cold_slot, |blob, out| { + desc.CachedPSO = blob.map_or_else(Default::default, |b| D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: b.as_ptr().cast(), CachedBlobSizeInBytes: b.len(), }); - hc = retried; - cin_driver += took; - } - let creused = hc >= 0 && ccached.is_some() && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; - if hc >= 0 && !creused && !compute.is_null() { - keep_compute_blob(ckey, compute, tp.cs.len()); - if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { - driver_cache::keep(p, &b, cin_driver); + driver_pso(fc, this, (&desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC).cast(), &iid, out) + }); + drop(cold_slot); + let (_, compute, cs_reused) = match compute_result { + Ok(result) => result, + Err(hr) => { + note_translation_error(format!("the driver rejected the NGG compute pass of the console {kind} ({hr:#x})")); + return E_INVALIDARG; } - } else if creused && cfrom_disk { - driver_cache::note(true, None); - } - drop(_slot); - if hc < 0 || compute.is_null() { - note_translation_error(format!("the driver rejected the compute pass of the console {kind} ({hc:#x})")); - let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(*ppv as *const *const usize)).add(2)); - release(*ppv); - *ppv = std::ptr::null_mut(); - return E_INVALIDARG; - } + }; + + *ppv = mesh_pso.into_raw(); note_pso_rs(*ppv, mesh_rs); - TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, std::sync::Arc::new(TwoPassPso { compute: compute.into_raw() as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); - if n < 5 || n % 1000 == 0 { - crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B + mesh {} B DXIL)", tp.cs.len(), tp.ms.len()); + if n < 5 || n % 1000 == 0 || pso_trace() { + crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (NGG compute {} B, blob reused: {cs_reused}; passthrough mesh graphics {} B, blob reused: {mesh_reused})", tp.cs.len(), tp.ms.len()); } hr } +/// The mesh and amplification shaders of a stream, as XCL translates them: a console MS +/// container in the AS slot with no MS subobject (a retail game's minimap pipelines) is the +/// mesh shader it says it is. It used to be refused – translated, the title rendered nothing +/// from then on, which was the translated mesh shaders failing their output budget (ms_6_6), +/// not the slot. With the chunk budget fixed they translate and the title keeps rendering. +/// Returns (MS to translate, AS left): the moved shader is not an AS any more. +fn mesh_shader_slots<'a>(ms_slot: Option<&'a [u8]>, as_slot: Option<&'a [u8]>) -> (Option<&'a [u8]>, Option<&'a [u8]>) { + use crate::gpu::recomp::pso::is_console; + match (ms_slot, as_slot) { + (None, Some(a)) if is_console(a) && crate::gpu::xbox::parse(a).is_some_and(|sh| sh.stage == "MS") => (Some(a), None), + (ms, a) => (ms, a), + } +} + +#[cfg(test)] +mod mesh_slot_tests { + use super::{console_ms_in_as_slot, fallback_stream, mesh_shader_slots}; + use crate::gpu::xbox::tests::{sample, fssm, CODE}; + + /// A stream subobject: its type, then the payload at 4 (align 4) or 8 (align 8). + fn sub(ty: u32, payload: &[u8]) -> Vec { + let (_, palign) = super::super::null::subobject_payload(ty).unwrap(); + let poff = if palign == 8 { 8 } else { 4 }; + let mut b = vec![0u8; (poff + payload.len() + 7) & !7]; + b[..4].copy_from_slice(&ty.to_le_bytes()); + b[poff..poff + payload.len()].copy_from_slice(payload); + b + } + + fn bytecode(s: &[u8]) -> Vec { + let mut b = Vec::new(); + b.extend_from_slice(&(s.as_ptr() as u64).to_le_bytes()); + b.extend_from_slice(&(s.len() as u64).to_le_bytes()); + b + } + + /// The stream the retail title's AS-slot MS pipelines have: a console MS container in the + /// AS subobject, no MS subobject, a PS and the graphics state (`mesh_shader_slots` moves it). + fn as_slot_ms_stream(ms: &[u8], ps: &[u8]) -> Vec { + let mut s = sub(0, &0u64.to_le_bytes()); // ROOT_SIGNATURE: null + s.extend_from_slice(&sub(24, &bytecode(ms))); + s.extend_from_slice(&sub(2, &bytecode(ps))); + s.extend_from_slice(&sub(8, &vec![0u8; 328])); // BLEND + s.extend_from_slice(&sub(9, &u32::MAX.to_le_bytes())); // SAMPLE_MASK + s.extend_from_slice(&sub(10, &vec![0u8; 44])); // RASTERIZER + s.extend_from_slice(&sub(11, &vec![0u8; 52])); // DEPTH_STENCIL + s.extend_from_slice(&sub(15, &vec![0u8; 36])); // RENDER_TARGET_FORMATS + s.extend_from_slice(&sub(17, &[1, 0, 0, 0, 0, 0, 0, 0])); // SAMPLE_DESC + s + } + + /// The stand-in for a console MS alone in the AS slot is a mesh pipeline: the subobject is + /// retyped to MS with the dummy MS (as `translated_mesh_stream` reads the title's stream), + /// the PS is the dummy PS. Left an empty AS and a PS, the stream had neither an MS nor a VS + /// and the driver refused it (E_INVALIDARG, NishantParajuli's and Chrysana's runs). + #[test] + fn the_stand_in_of_a_moved_ms_is_a_mesh_pipeline() { + let ms = sample(13, &[fssm(&CODE, &[(8, 13)])]); + let ps = b"DXBC-a-pixel-shader".to_vec(); + let stream = as_slot_ms_stream(&ms, &ps); + let desc = [stream.len(), stream.as_ptr() as usize]; + let subs = super::stream_subobjects(&stream).unwrap(); + assert!(unsafe { console_ms_in_as_slot(&subs) }); + let (buf, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.expect("a stand-in stream"); + let out = super::stream_subobjects(&buf).unwrap(); + assert!(!out.iter().any(|s| s.0 == 24), "no AS subobject left"); + let m = out.iter().find(|s| s.0 == 25).expect("an MS subobject"); + let dm = super::dummy_mesh().expect("DXC for the stand-in shaders"); + let got = unsafe { super::payload_shader(m.1) }.unwrap(); + assert_eq!(got, dm.0.as_slice(), "the dummy MS"); + let p = out.iter().find(|s| s.0 == 2).unwrap(); + assert_eq!(unsafe { super::payload_shader(p.1) }.unwrap(), dm.1.as_slice(), "the dummy PS"); + // a real AS with no MS is not moved, and its stand-in keeps the AS slot empty + let as_ = sample(14, &[fssm(&CODE, &[(8, 14)])]); + let stream = as_slot_ms_stream(&as_, &ps); + let desc = [stream.len(), stream.as_ptr() as usize]; + assert!(!unsafe { console_ms_in_as_slot(&super::stream_subobjects(&stream).unwrap()) }); + let (buf, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.unwrap(); + let out = super::stream_subobjects(&buf).unwrap(); + assert!(out.iter().any(|s| s.0 == 24) && !out.iter().any(|s| s.0 == 25)); + } + + /// The stand-in's target formats are the PC's, as the real pipeline's: the console's + /// D16_UNORM_S8_UINT (118) is D24_UNORM_S8_UINT (45) and a B4G4R4A4 target (115) is + /// R8G8B8A8 (28). With the console's the driver refuses the stand-in (the title's depth-only + /// mesh pipelines; NishantParajuli's follow-up, reproduced natively by thehollowedone). + #[test] + fn the_stand_in_of_a_stream_has_the_pcs_target_formats() { + let mut s = sub(15, &{ + let mut p = Vec::new(); + for f in [115u32, 28, 0, 0, 0, 0, 0, 0, 2] { + p.extend_from_slice(&f.to_le_bytes()); + } + p + }); + s.extend_from_slice(&sub(16, &118u32.to_le_bytes())); + let desc = [s.len(), s.as_ptr() as usize]; + let (out, _) = unsafe { fallback_stream(desc.as_ptr() as *const u8) }.expect("a stand-in stream"); + let subs = super::stream_subobjects(&out).unwrap(); + let word = |p: &[u8], k: usize| u32::from_le_bytes(p[4 * k..4 * k + 4].try_into().unwrap()); + assert_eq!((subs[0].0, word(subs[0].1, 0), word(subs[0].1, 1), word(subs[0].1, 8)), (15, 28, 28, 2)); + assert_eq!((subs[1].0, word(subs[1].1, 0)), (16, 45)); + } + + /// A console MS container alone in the AS slot becomes the MS; a real AS (console or PC), + /// an MS already present, or a PC shader in the AS slot are left as they are. + #[test] + fn a_console_ms_in_the_as_slot_is_the_mesh_shader() { + let ms = sample(13, &[fssm(&CODE, &[(8, 13)])]); + let as_ = sample(14, &[fssm(&CODE, &[(8, 14)])]); + let pc = b"DXBC-not-a-console-container".to_vec(); + // MS in the AS slot, no MS: moved, and not an AS any more + let (m, a) = mesh_shader_slots(None, Some(&ms)); + assert!(m.is_some_and(|m| std::ptr::eq(m, ms.as_slice())) && a.is_none()); + // an MS present: both slots untouched, whatever the AS holds + let (m, a) = mesh_shader_slots(Some(&ms), Some(&as_)); + assert!(m.is_some_and(|m| std::ptr::eq(m, ms.as_slice())) && a.is_some_and(|a| std::ptr::eq(a, as_.as_slice()))); + // a console AS (not an MS) stays in the AS slot + let (m, a) = mesh_shader_slots(None, Some(&as_)); + assert!(m.is_none() && a.is_some_and(|a| std::ptr::eq(a, as_.as_slice()))); + // a PC shader in the AS slot stays too + let (m, a) = mesh_shader_slots(None, Some(&pc)); + assert!(m.is_none() && a.is_some()); + // nothing: nothing + assert!(mesh_shader_slots(None, None) == (None, None)); + } + + /// The cached-only attempt defers a moved MS like a console compute pipeline: `defer` + /// marks the attempt missed, so `dev_create_pipeline_state` takes the background path + /// (stand-in now, translation on the worker / first bind) instead of translating on the + /// title's thread – tens of thousands of these pipelines during boot delayed the intro + /// by seconds on NVIDIA and past a minute on AMD wave64. Outside the attempt (the + /// worker's build) nothing is deferred. + #[test] + fn a_moved_ms_defers_in_the_attempt_only() { + let (_, missed) = crate::gpu::recomp::dxc::cached_only(|| { + assert!(crate::gpu::recomp::dxc::defer(), "inside the attempt: deferred"); + }); + assert!(missed, "the attempt is missed: the caller takes the background path"); + assert!(!crate::gpu::recomp::dxc::defer(), "outside: the build translates"); + } +} + /// CreatePipelineState with a console MS: Some(hr) when it was a console mesh pipeline /// (translated, or E_INVALIDARG – console bytecode must not reach the driver). unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { @@ -5388,17 +6068,11 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri 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)); - // A console MS container in the AS slot and no MS subobject (a retail game's minimap - // pipelines): refused. Translated as the mesh shader they are, the title rendered nothing - // from then on (a black screen every run); refused, it goes on to its menus. What it - // expects of them is not known yet. - if let (None, Some(a)) = (ms_slot, as_slot) { - if is_console(a) && crate::gpu::xbox::parse(a).is_some_and(|sh| sh.stage == "MS") { - note_translation_error(format!("mesh pipeline with its MS {:016x} in the AS slot – refused", crate::gpu::shader::fnv64(a))); - return Some(E_INVALIDARG); - } - } - let ms = ms_slot?; + // a console MS in the AS slot with no MS subobject: moved, and translated when first + // bound (below), not on the title's thread for each of tens of thousands + let moved = ms_slot.is_none(); + let (ms, as_slot) = mesh_shader_slots(ms_slot, as_slot); + let Some(ms) = ms else { return None }; if !is_console(ms) { return None; } @@ -5415,6 +6089,12 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return None; } + if moved { + let n = AS_SLOT_MS.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: mesh pipeline with its MS {:016x} in the AS slot – translating as MS (#{})", crate::gpu::shader::fnv64(ms), n + 1); + } + } let ps = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32).and_then(|s| payload_shader(s.1)); 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), @@ -5447,7 +6127,7 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri out.raw(*ty, payload, palign == 8); } } - Some(finish_two_pass(this, &out, tp, rs, "MS", riid, ppv)) + Some(finish_two_pass(this, &out, tp, rs, &ps_samplers, "MS", riid, ppv)) } /// A graphics PSO with a console VS + GS: the GS pipeline in two passes, as a mesh pipeline @@ -5513,7 +6193,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) + finish_two_pass(this, &out, tp, rs, &ps_samplers, "GS", riid, ppv) +} + +/// A console MS container in the stream's AS subobject and no MS subobject (`mesh_shader_slots`). +unsafe fn console_ms_in_as_slot(subs: &[(u32, &[u8])]) -> bool { + let shader = |ty: i32| subs.iter().find(|s| s.0 == ty as u32).and_then(|s| payload_shader(s.1)); + shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0).is_none() + && shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0).is_some_and(|a| crate::gpu::recomp::pso::is_console(a) && crate::gpu::xbox::parse(a).is_some_and(|sh| sh.stage == "MS")) } /// Rewrite a pipeline state stream with stand-in shaders. None if not possible. @@ -5525,7 +6212,12 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { } let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); let d = dummy(); - let mesh = stream_subobjects(&buf).is_some_and(|subs| subs.iter().any(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32)); + // A console MS alone in the AS slot is the stream's mesh shader (`mesh_shader_slots`), so its + // stand-in is a mesh pipeline too, with the dummy MS in that subobject as an MS. Left an AS + // without a shader, the stream had a PS and neither an MS nor a VS: the driver refused it + // (E_INVALIDARG) and every such pipeline was built in the title's call (NishantParajuli). + let ms_in_as = stream_subobjects(&buf).is_some_and(|subs| console_ms_in_as_slot(&subs)); + let mesh = ms_in_as || stream_subobjects(&buf).is_some_and(|subs| subs.iter().any(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32)); let dm = if mesh { Some(dummy_mesh()?) } else { None }; let mut off = 0usize; while off + 8 <= size { @@ -5547,8 +6239,22 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { 1 => put(&mut buf, &d.vs), 2 => put(&mut buf, dm.map_or(&d.ps[..], |m| &m.1[..])), 6 => put(&mut buf, &d.cs), + 24 if ms_in_as => { + buf[off..off + 4].copy_from_slice(&(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32).to_le_bytes()); + put(&mut buf, &dm?.0) + } 3 | 4 | 5 | 24 => put(&mut buf, &[]), 25 => put(&mut buf, &dm?.0), + // RENDER_TARGET_FORMATS, DEPTH_STENCIL_FORMAT: the console's formats as the PC's, as + // the real pipeline gets them (`translated_mesh_stream`) – with a console-only one + // (a retail game's depth-only mesh pipelines: D16_UNORM_S8_UINT) the driver refuses + // the stand-in (E_INVALIDARG) and the pipeline is built in the title's call + 15 | 16 => { + for k in 0..if ty == 15 { 8 } else { 1 } { + let f = super::device_x::pc_target_format(u32::from_le_bytes(buf[at + 4 * k..at + 4 * k + 4].try_into().ok()?)); + buf[at + 4 * k..at + 4 * k + 4].copy_from_slice(&f.to_le_bytes()); + } + } 12 | 19 => buf[at..at + 16].fill(0), // input layout, cached PSO 7 => buf[at..at + 32].fill(0), // stream output _ => {} @@ -6040,7 +6746,19 @@ pub(super) static QUEUE_SHIFTED: AtomicBool = AtomicBool::new(false); static QUEUE_OLDER: AtomicBool = AtomicBool::new(false); /// command list slots of the newer layout → the older layout's slot of the same method -const NEWER_LIST_SLOTS: [(usize, usize); 21] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (139, 10)]; +const NEWER_LIST_SLOTS: [(usize, usize); 22] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (129, 127), (139, 10)]; + +pub(super) unsafe fn list_device(list: *mut c_void) -> Option { + type F = unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(list, 7)); + let iid = pc_iid(Kind::Device); + let mut raw: *mut c_void = std::ptr::null_mut(); + if f(list, &iid, &mut raw) >= 0 && !raw.is_null() { + Some(ID3D12Device::from_raw(raw)) + } else { + None + } +} /// The title called device method `slot`, which only runtimes with the newer layouts have (a retail game /// records its first lists before any queue call could tell). @@ -6084,6 +6802,8 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a } let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(if older == 14 { PC_SIGNAL } else { PC_WAIT })); let hr = f(this, a1, a2); + super::queue_probe::event(if older == 14 { "title-signal" } else { "title-wait" }, + this as usize, a1, 0, a2 as u64, u64::from(hr as u32)); if hr >= 0 { if older == 14 { super::fence_x::note_queue_signal(a1, a2 as u64); @@ -6185,6 +6905,92 @@ unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, valu hr } +/// GetCompletedValue of `fence` as the PC has it, without what the hook below does for the title +/// on the way (it lands copies back, which takes the sparse state's lock): for XCL's own queries, +/// the ones made with that lock held above all. With the hook, each such query stood ~2 ms +/// trying for the lock its own thread held, and a pass over the pending copies took seconds +/// with every submitting thread behind it. +pub(super) unsafe fn fence_completed(fence: &ID3D12Fence) -> u64 { + const PC_GET_COMPLETED_VALUE: usize = 8; + let p = fence.as_raw(); + let f: unsafe extern "system" fn(*mut c_void) -> u64 = if is_adopted(p) { + std::mem::transmute(orig_fn(p, slot_of(p, "GetCompletedValue"))) + } else { + std::mem::transmute(*(*(p as *const *const usize)).add(PC_GET_COMPLETED_VALUE)) + }; + f(p) +} + +/// Fence::GetCompletedValue. What the title's lists wrote into its sparse memory comes back +/// asynchronously (`sparse::readback_after_execute`): the copies back the value covers land first. +unsafe extern "system" fn fence_get_completed_value(this: *mut c_void) -> u64 { + let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, slot_of(this, "GetCompletedValue"))); + let v = f(this); + super::sparse::settle_readbacks_try(); + v +} + +/// A `fence_set_event_on_completion` wait: the title's event, XCL's own event the fence sets, and +/// the thread-pool wait on it (0 until registered) +struct FenceWait { + own: *mut c_void, + title: *mut c_void, + wait: AtomicUsize, +} + +unsafe extern "system" fn fence_wait_fired(ctx: *mut c_void, _timed_out: bool) { + use windows_sys::Win32::System::Threading::{SetEvent, UnregisterWaitEx}; + let w = ctx as *mut FenceWait; + super::sparse::settle_readbacks_try(); + SetEvent((*w).title); + let mut wh = (*w).wait.load(Ordering::Acquire); + while wh == 0 { + std::hint::spin_loop(); + wh = (*w).wait.load(Ordering::Acquire); + } + // no completion event: the registration goes once this callback returns + UnregisterWaitEx(wh as *mut c_void, std::ptr::null_mut()); + windows_sys::Win32::Foundation::CloseHandle((*w).own); + drop(Box::from_raw(w)); +} + +/// Fence::SetEventOnCompletion. Once copies back land asynchronously, the title's event is set +/// after the fence is reached and the copies back it covers landed: the fence sets an event of +/// XCL's own, and a thread-pool wait on that settles them and sets the title's. A null event +/// (a blocking wait) settles them after it. +unsafe extern "system" fn fence_set_event_on_completion(this: *mut c_void, value: u64, event: *mut c_void) -> HRESULT { + use windows_sys::Win32::System::Threading::{CreateEventW, RegisterWaitForSingleObject, UnregisterWaitEx, INFINITE, WT_EXECUTEONLYONCE}; + let f: unsafe extern "system" fn(*mut c_void, u64, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "SetEventOnCompletion"))); + if event.is_null() || !super::sparse::readbacks_async() { + let hr = f(this, value, event); + if event.is_null() { + super::sparse::settle_readbacks_try(); + } + return hr; + } + let own = CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); + if own.is_null() { + return f(this, value, event); + } + let w = Box::into_raw(Box::new(FenceWait { own, title: event, wait: AtomicUsize::new(0) })); + let mut wh = std::ptr::null_mut(); + if RegisterWaitForSingleObject(&mut wh, own, Some(fence_wait_fired), w as *const c_void, INFINITE, WT_EXECUTEONLYONCE) == 0 { + windows_sys::Win32::Foundation::CloseHandle(own); + drop(Box::from_raw(w)); + return f(this, value, event); + } + (*w).wait.store(wh as usize, Ordering::Release); + let hr = f(this, value, own); + if hr < 0 { + // the event will not be set: take the wait back (waiting for a running callback) + if UnregisterWaitEx(wh, windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE) != 0 { + windows_sys::Win32::Foundation::CloseHandle(own); + drop(Box::from_raw(w)); + } + } + hr +} + /// 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"))); @@ -6202,7 +7008,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis return; } // textures in title memory the CPU wrote since: uploaded again first - super::title_textures::refresh(this); + super::title_textures::refresh_for(this, std::slice::from_raw_parts(lists, n as usize)); // 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); @@ -6214,13 +7020,17 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis } } super::list_x::note_queue_for_lists(this as usize, &mapped); + super::gpu_profile::note_queue(this); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { - f(this, chunk.len() as u32, chunk.as_ptr()); + let id = super::queue_probe::submit("title-execute", this as usize, chunk); + super::sparse::ordered_submit(this, || f(this, chunk.len() as u32, chunk.as_ptr())); + super::queue_probe::event("execute-return", this as usize, 0, id, 0, 0); super::list_x::copy_scratch_submitted(this, chunk); - super::alloc_pool::executed(this, chunk); + super::alloc_pool::executed(this, chunk, id); super::list_x::signal_write64_fences(this, chunk); super::list_x::readback_sparse_writes(this, chunk); super::list_x::cpu_writes_after(this, chunk); + super::list_x::note_submitted(this, id); }); // the next uploads into textures kept in step start from the states these lists leave super::title_textures::submitted(&mapped); @@ -6333,6 +7143,7 @@ pub fn log_device_removed() { let raw = device_raw(); let Some(dev) = (unsafe { ID3D12Device::from_raw_borrowed(&raw) }) else { return }; let Err(e) = (unsafe { dev.GetDeviceRemovedReason() }) else { return }; + super::queue_probe::device_removed(); if DONE.swap(true, Ordering::AcqRel) { return; } @@ -6351,10 +7162,22 @@ pub fn log_device_removed() { v.join(", ") }; let va = pf.PageFaultVA; - let window = uma_window_vas().iter().position(|&w| va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); + let windows = uma_window_vas(); + let position = if va == 0 || windows.is_empty() { + None + } else { + crate::gpu::uma::get().and_then(|uma| { + let ranges = windows.iter().enumerate().map(|(k, &base)| (base, uma.window(k).1 as u64)); + locate_gpu_window(va, ranges) + }) + }; + let window = position.map(|(k, offset)| format!(" = window {k} + {offset:#x}")).unwrap_or_default(); crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); } if let Ok(bc) = dred.GetAutoBreadcrumbsOutput() { + if bc.pHeadAutoBreadcrumbNode.is_null() { + crate::xlog_error!("DRED: auto-breadcrumb list is empty"); + } report_dred_lists(bc.pHeadAutoBreadcrumbNode, |node, done| { let count = node.BreadcrumbCount as usize; let ops: Vec = (done.saturating_sub(3)..(done + 3).min(count)).map(|i| format!("{}{}", if i == done { ">" } else { "" }, (*node.pCommandHistory.add(i)).0)).collect(); diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index 6ca0572281..d295ec4b30 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -200,12 +200,31 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp for (ty, payload) in subs { match ty { 0 | 19 => {} // RS replaced by ABI RS via ps_samplers; CACHED_PSO is the lookup input - 7 | 12 | 22 => { - if payload.iter().any(|&b| b != 0) { + // These descriptors can carry inert pointers and padding in a title stream. + // Their counts and flags determine whether any state needs to be hashed. + 7 => { + let state = read_state::(payload)?; + if state.NumEntries != 0 || state.NumStrides != 0 || state.RasterizedStream != 0 { + return None; + } + } + 12 => { + let state = read_state::(payload)?; + if state.NumElements != 0 { + return None; + } + } + 22 => { + let state = read_state::(payload)?; + if state.ViewInstanceCount != 0 || state.Flags.0 != 0 { return None; } } 1..=6 | 24 | 25 => { + let state = read_state::(payload)?; + if state.BytecodeLength == 0 && ty != 25 { + continue; + } let code = payload_shader(payload)?; shader_bytes = shader_bytes.checked_add(code.len())?; h.u32(ty); @@ -333,6 +352,37 @@ mod tests { } } + #[test] + fn empty_stream_descriptors_do_not_change_the_key() { + let ms = [1u8, 2, 3, 4]; + let mut base = StreamOut::default(); + base.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, &ms); + let mut with_empty = StreamOut(base.0.clone(), base.1); + with_empty.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, &D3D12_STREAM_OUTPUT_DESC { + pSODeclaration: 0x2000 as *const _, + pBufferStrides: 0x3000 as *const _, + ..Default::default() + }); + let mut input = [0u8; std::mem::size_of::()]; + input[..8].copy_from_slice(&0x4000u64.to_le_bytes()); + let padding = std::mem::offset_of!(D3D12_INPUT_LAYOUT_DESC, NumElements) + std::mem::size_of::(); + input[padding..].fill(0xaa); + with_empty.raw(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32, &input, true); + with_empty.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, &D3D12_VIEW_INSTANCING_DESC { + pViewInstanceLocations: 0x5000 as *const _, + ..Default::default() + }); + with_empty.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &D3D12_SHADER_BYTECODE { + pShaderBytecode: 0x6000 as *const _, + BytecodeLength: 0, + }); + + unsafe { + let key = two_pass_stream_key(&base.0, &[], 1, 4).expect("base mesh key"); + assert_eq!(two_pass_stream_key(&with_empty.0, &[], 1, 4), Some(key)); + } + } + #[test] fn two_pass_keys_cover_mem_windows_invalid_counts_and_duplicates() { let mut s = StreamOut::default(); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 91eb2ba351..dacfdb915b 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -197,16 +197,94 @@ struct UploadSlot { fence_val: u64, } +/// A copy back on `State::rbq`: its list, its readback buffer, the `rb_fence` value it waits +/// for, the `rbq` fence value that marks it done, and the copies into the title's memory +/// (address, offset in `buf`, bytes). +struct RbJob { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + buf: ID3D12Resource, + ptr: *mut u8, + cap: usize, + rb_v: u64, + done_v: u64, + copies: Vec<(usize, usize, usize)>, + /// the type of queue `list` is for (a copy back runs on the title's own queue) + ty: D3D12_COMMAND_LIST_TYPE, + /// the title queue's fences for it (`State::rb_queue_fences`): the first reaches `rb_v` when + /// the lists it follows are done, the second `done_v` when the copy is. None: `rb_fence` and + /// the readback queue's fence (the form before) + fences: Option<(ID3D12Fence, ID3D12Fence)>, + /// place among the submissions' jobs (`State::job_seq`): copies and immediates land in it + seq: u64, +} + +/// In an immediate's byte count: the cell is a counter that the title's queues write in turn, +/// with values that only rise as they are recorded. A list that runs late – a retail title's +/// compute jobs, tens of frames after their recording when its submits are slow – writes an +/// earlier value over a later one; the title's CPU waits for "at least" the later one, which +/// was reached. The CPU's view keeps the larger value. +pub(super) const IMM_KEEP_MAX: u8 = 0x80; + +/// Immediates the title's lists wrote into a window (`list_x::imm_by_cpu`): stored in the +/// title's memory once `fence` reaches `value` (the lists are done on the GPU). +struct ImmJob { + /// place among the copies back (`RbJob::seq`) + seq: u64, + fence: ID3D12Fence, + value: u64, + /// (address, value, bytes) + writes: Vec<(usize, u64, u8)>, +} + +/// How far `drain_readbacks` goes +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Drain { + /// only copies the GPU has finished + Finished, + /// also those whose title work is done (waiting for the copy itself): before a CPU read + /// the title made sure of, e.g. after its wait for the value a list wrote + TitleDone, +} + +struct TitleAccess { + // Retain the queue while its pointer is a key for this fence. + _queue: ID3D12CommandQueue, + fence: ID3D12Fence, + submitted: u64, + ordered: u64, +} + struct State { + /// Title queue -> its latest potentially sparse-writing submission. + title_access: FxHashMap, dev: ID3D12Device, queue: ID3D12CommandQueue, fence: ID3D12Fence, value: u64, /// reusable auto-reset Win32 event for fence waits (no per-wait CreateEventW/CloseHandle) event: HANDLE, - /// fence signalled on title queues so `queue` waits before copying GPU writes back to CPU + /// fence signalled on title queues after their lists, so a copy back waits for them rb_fence: ID3D12Fence, rb_value: u64, + /// title queue -> the two fences it signals around a copy back, and the last value. One set + /// a queue: with one fence for all, a queue that got to its Signal first let the copies of a + /// queue still waiting run early + rb_queue_fences: FxHashMap, + /// copies back after the title's submissions (`readback_after_execute`): on a queue of their + /// own (`rbq`, None: on `queue`, waited for on the CPU), landing in the title's memory once + /// done (`drain_readbacks`). The title's queues can wait for work the title submits after + /// this one, from the same thread: waiting here for its lists stopped that submission – and, + /// on `queue`, every upload behind it (`before_execute` waiting for ring room). + rbq: Option<(ID3D12CommandQueue, ID3D12Fence)>, + rbq_value: u64, + /// submitted copies back, oldest first, and finished ones to reuse + rb_jobs: VecDeque, + rb_pool: Vec, + /// immediates of the title's submissions, oldest first, and the count that orders them + /// with `rb_jobs` + imm_jobs: VecDeque, + job_seq: u64, /// (window start, reserved buffer) of each sparse window windows: Vec<(usize, ID3D12Resource)>, /// video-memory pool heaps (None: given back, its index free for the next one) @@ -226,8 +304,13 @@ struct State { /// decommits and commits again thousands of tiles a second, and each `UpdateTileMappings` /// took ~0.15 ms.) parked: FxHashMap, - /// placed buffers → the pool tiles they use - buffers: FxHashMap>, + /// tile address → pool tile of decommitted tiles a placed buffer uses: they stay mapped in + /// their window until the buffer is gone. Memory committed there again is then the same for + /// the window (what shaders write) and the buffer (what an ExecuteIndirect or a copy of the + /// title reads); with a new tile in the window the buffer kept the old one, with old bytes + kept: FxHashMap, + /// placed buffers → the tiles they use (address, pool tile) + buffers: FxHashMap>, /// reused tiles / decommitted partial pages to clear: (address, bytes) to_zero: Vec<(usize, usize)>, /// ring-buffered upload staging heap (`STAGING` bytes, persistently mapped) @@ -488,6 +571,108 @@ fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC { } } +unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) -> windows::core::Result { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; + let rbq = (|| -> windows::core::Result<(ID3D12CommandQueue, ID3D12Fence)> { + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; + let _ = q.SetName(windows::core::w!("xcl sparse readback queue")); + Ok((q, dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?)) + })() + .ok(); + let mut slots = Vec::with_capacity(UPLOAD_SLOTS); + for _ in 0..UPLOAD_SLOTS { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; + list.Close()?; + let _ = list.SetName(windows::core::w!("xcl sparse upload list")); + let _ = alloc.SetName(windows::core::w!("xcl sparse upload allocator")); + slots.push(UploadSlot { alloc, list, fence_val: 0 }); + } + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; + rb_list.Close()?; + let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); + let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); + let _ = queue.SetName(windows::core::w!("xcl sparse queue")); + Ok(State { + dev: dev.clone(), + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + rb_queue_fences: FxHashMap::default(), + rbq, + rbq_value: 0, + rb_jobs: VecDeque::new(), + rb_pool: Vec::new(), + imm_jobs: VecDeque::new(), + job_seq: 0, + windows, + pools: Vec::new(), + free: Vec::new(), + retired: Vec::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + kept: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: Vec::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + zero_buf: None, + slots, + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + title_access: FxHashMap::default(), + runs: None, + scratch_runs: Vec::new(), + }) +} + +/// pool heap number of the tiles of a shadowed window: they are the window's own buffer, not +/// pool tiles (never mapped, freed or pinned) +const SHADOW_POOL: u32 = u32::MAX; + +/// A committed window the GPU could not open as a heap (`real::open_uma`): `buf` in video +/// memory stands for `[base, base + size)` and is kept in step like the tiles of a sparse +/// window -- the CPU's writes (write-watch, changed 64-byte chunks) go to it before each +/// ExecuteCommandLists, GPU writes come back on Map and after the lists' memory operations. +/// All of it counts as mapped from the start: the window is committed. False: no queue for +/// the copies (the buffer then never sees the CPU's writes). +pub unsafe fn shadow_window(dev: &ID3D12Device, base: usize, size: usize, buf: &ID3D12Resource) -> bool { + let mut g = STATE.lock().unwrap(); + 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), + Err(e) => { + crate::xlog_warn!("shadowed window at {base:#x}: {e}"); + return false; + } + } + } + let Some(s) = g.as_mut() else { return false }; + s.windows.push((base, buf.clone())); + for (i, t) in (base..base + size).step_by(TILE).enumerate() { + s.mapped.insert(t, TileEntry::with_holes((SHADOW_POOL, i as u32), 0)); + } + s.runs = None; + MAPPED_GEN.fetch_add(1, Ordering::Release); + true +} + /// The sparse windows' buffers on `dev`: `(window_index, buffer_raw, gpu_va)` for each /// sparse window in `gpu::uma` (empty: no sparse windows). pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { @@ -511,60 +696,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { if out.is_empty() { return out; } - let made = (|| -> windows::core::Result { - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; - let mut slots = Vec::with_capacity(UPLOAD_SLOTS); - for _ in 0..UPLOAD_SLOTS { - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; - list.Close()?; - let _ = list.SetName(windows::core::w!("xcl sparse upload list")); - let _ = alloc.SetName(windows::core::w!("xcl sparse upload allocator")); - slots.push(UploadSlot { alloc, list, fence_val: 0 }); - } - let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; - rb_list.Close()?; - let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); - let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); - let _ = queue.SetName(windows::core::w!("xcl sparse queue")); - Ok(State { - dev: dev.clone(), - queue, - fence, - value: 0, - event, - rb_fence, - rb_value: 0, - windows, - pools: Vec::new(), - free: Vec::new(), - retired: Vec::new(), - mapped: FxHashMap::default(), - pinned: FxHashMap::default(), - parked: FxHashMap::default(), - buffers: FxHashMap::default(), - to_zero: Vec::new(), - staging: None, - ring_write: 0, - ring_submitted: 0, - ring_free: 0, - inflight: VecDeque::new(), - zero_buf: None, - slots, - next_slot: 0, - readback: None, - rb_alloc, - rb_list, - rb_last_fence: 0, - waited: FxHashMap::default(), - runs: None, - scratch_runs: Vec::new(), - }) - })(); + let made = new_state(dev, windows); match made { Ok(s) => { crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len()); @@ -646,7 +778,7 @@ 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() }; + let done = unsafe { super::real::fence_completed(&self.fence) }; self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); if self.free.len() < POOL_TILES as usize { return; @@ -669,10 +801,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))]) { + unsafe fn map_tiles(&mut self, res: &ID3D12Resource, res_base: usize, tiles: &[(usize, (u32, u32))]) { if tiles.is_empty() { return; } + self.order_after_title(); 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)); @@ -703,6 +836,10 @@ impl State { counts.push(run); i += run as usize; } + super::queue_probe::event( + "sparse-map", self.queue.as_raw() as usize, res.as_raw() as usize, + 0, pairs.len() as u64, coords.len() as u64, + ); self.queue.UpdateTileMappings( res, coords.len() as u32, @@ -718,10 +855,11 @@ impl State { } } - unsafe fn unmap_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[usize]) { + unsafe fn unmap_tiles(&mut self, res: &ID3D12Resource, res_base: usize, tiles: &[usize]) { if tiles.is_empty() { return; } + self.order_after_title(); 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()); @@ -741,6 +879,10 @@ impl State { counts.push(run); i += run as usize; } + super::queue_probe::event( + "sparse-unmap", self.queue.as_raw() as usize, res.as_raw() as usize, + 0, tiles.len() as u64, coords.len() as u64, + ); self.queue.UpdateTileMappings( res, coords.len() as u32, @@ -755,6 +897,50 @@ impl State { ); } + /// Put writes and mapping changes behind the title queues already using the windows. + unsafe fn order_after_title(&mut self) { + let queue = self.queue.as_raw() as usize; + for access in self.title_access.values_mut() { + if access.ordered < access.submitted { + // Keep the dependency explicit for the D3D12 debug layer even + // if GetCompletedValue would already report the producer done. + expect_queue_order(self.queue.Wait(&access.fence, access.submitted), "sparse wait for title access"); + super::list_x::note_internal_wait(queue, "sparse write behind title access", &access.fence, access.submitted); + access.ordered = access.submitted; + } + } + } + + unsafe fn order_after_sparse(&mut self, queue: &ID3D12CommandQueue) { + let key = queue.as_raw() as usize; + if self.waited.get(&key).copied().unwrap_or(0) < self.value { + expect_queue_order(queue.Wait(&self.fence, self.value), "title wait for sparse writes"); + super::list_x::note_internal_wait(key, "sparse uploads and tile mappings", &self.fence, self.value); + self.waited.insert(key, self.value); + } + } + + unsafe fn submit_title(&mut self, queue: &ID3D12CommandQueue, submit: impl FnOnce() -> R) -> R { + let key = queue.as_raw() as usize; + if key == self.queue.as_raw() as usize { + return submit(); + } + self.order_after_sparse(queue); + let access = self.title_access.entry(key).or_insert_with(|| TitleAccess { + _queue: queue.clone(), + fence: self.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("sparse title access fence"), + submitted: 0, + ordered: 0, + }); + let result = submit(); + access.submitted += 1; + let signal = queue.Signal(&access.fence, access.submitted); + super::queue_probe::signal("sparse-title-fence", key, &access.fence, 0, access.submitted, + signal.as_ref().err().map_or(0, |e| e.code().0)); + expect_queue_order(signal, "title sparse access signal"); + result + } + /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_holes` supplies /// the initial 16-bit hole mask for each newly mapped 64 KiB tile. unsafe fn ensure_mapped(&mut self, a: usize, n: usize, mut initial_holes: impl FnMut(usize) -> u16) { @@ -769,7 +955,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).or_else(|| self.kept.remove(&t)) { self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); self.runs = None; self.to_zero.push((t, TILE)); @@ -813,19 +999,33 @@ impl State { #[inline] unsafe fn signal(&mut self) { self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + let signal = self.queue.Signal(&self.fence, self.value); + super::queue_probe::signal("sparse-fence", self.queue.as_raw() as usize, &self.fence, 0, self.value, + signal.as_ref().err().map_or(0, |e| e.code().0)); } #[inline] unsafe fn wait_for(&self, target: u64) { - if target == 0 || self.fence.GetCompletedValue() >= target { + if target == 0 || super::real::fence_completed(&self.fence) >= target { return; } - let _ = self.fence.SetEventOnCompletion(target, self.event); - 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()); + // The event is one for all waits here, and a wait that gave up leaves its registration + // behind: that one sets the event later, and the next wait would return at once with the + // queue not there (10 such "after 5 s" lines within 100 ms in one run, each followed by a + // Reset of an allocator the GPU was still in). So: until the fence says so, or 5 s. + let t0 = std::time::Instant::now(); + loop { + let _ = self.fence.SetEventOnCompletion(target, self.event); + let left = 5000u64.saturating_sub(t0.elapsed().as_millis() as u64).max(1) as u32; + windows::Win32::System::Threading::WaitForSingleObject(self.event, left); + if super::real::fence_completed(&self.fence) >= target { + return; + } + if t0.elapsed().as_millis() >= 5000 { + break; + } } + crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", super::real::fence_completed(&self.fence)); } #[inline] @@ -833,7 +1033,7 @@ impl State { if self.inflight.is_empty() { return; } - let completed = self.fence.GetCompletedValue(); + let completed = super::real::fence_completed(&self.fence); while let Some(&(fv, end_pos)) = self.inflight.front() { if fv <= completed { self.ring_free = end_pos; @@ -850,7 +1050,7 @@ impl State { let idx = self.next_slot; self.next_slot = (self.next_slot + 1) % self.slots.len(); let fv = self.slots[idx].fence_val; - if fv > 0 && self.fence.GetCompletedValue() < fv { + if fv > 0 && super::real::fence_completed(&self.fence) < fv { self.wait_for(fv); self.reclaim_ring(); } @@ -866,7 +1066,9 @@ impl State { let closed = self.slots[idx].list.Close().is_ok(); if closed { if let Ok(l) = self.slots[idx].list.cast::() { + self.order_after_title(); super::title_textures::own_work(|| { + super::queue_probe::submit("sparse-upload", self.queue.as_raw() as usize, &[l.as_raw()]); self.queue.ExecuteCommandLists(&[Some(l)]); }); } @@ -1005,9 +1207,212 @@ impl State { } } + /// `len` bytes from readback memory `p + off` into the title's `dst` (committed pages only) + unsafe fn copy_back(&mut self, p: *mut u8, dst: usize, off: usize, len: usize) { + let mut at = dst; + let mut src_off = off; + let end = dst + len; + while at < end { + let pg = at & !(PAGE - 1); + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; + let step = (pg + PAGE).min(end) - at; + if self.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { + std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + } + at += step; + src_off += step; + } + self.sync_sent_range(dst, len); + } + + /// An immediate the GPU wrote at `va` (`bytes`: 4 or 8), into the title's memory there + unsafe fn store_imm(&mut self, va: usize, value: u64, bytes: u8) { + let pg = va & !(PAGE - 1); + let t = pg & !(TILE - 1); + if !self.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << ((pg - t) / PAGE)) == 0) { + return; + } + match bytes & 0x7f { + 4 => (*(va as *const std::sync::atomic::AtomicU32)).store(value as u32, Ordering::Release), + 8 if bytes & IMM_KEEP_MAX != 0 => { + if (*(va as *const AtomicU64)).fetch_max(value, Ordering::AcqRel) > value { + static LATE: AtomicU64 = AtomicU64::new(0); + let k = LATE.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_info!("sparse: {k} immediates so far left out – their cell is a counter that held a later value ({value:#x} for {va:#x})"); + } + return; + } + } + 8 => (*(va as *const AtomicU64)).store(value, Ordering::Release), + _ => return, + } + self.sync_sent_range(va, (bytes & 0x7f) as usize); + } + + /// A copy back's list and a readback buffer of at least `need` bytes (reused when one fits) + unsafe fn rb_job(&mut self, need: usize, ty: D3D12_COMMAND_LIST_TYPE) -> Option { + if let Some(i) = self.rb_pool.iter().enumerate().filter(|(_, j)| j.cap >= need && j.ty == ty).min_by_key(|(_, j)| j.cap).map(|(i, _)| i) { + return Some(self.rb_pool.swap_remove(i)); + } + let cap = need.max(64 << 10).next_power_of_two().min(READBACK_STAGING); + let alloc: ID3D12CommandAllocator = self.dev.CreateCommandAllocator(ty).ok()?; + let list: ID3D12GraphicsCommandList = self.dev.CreateCommandList(0, ty, &alloc, None).ok()?; + list.Close().ok()?; + let _ = list.SetName(windows::core::w!("xcl sparse readback list")); + let mut d = buffer_desc(cap as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut r: Option = None; + self.dev + .CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r) + .ok()?; + let buf = r?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + Some(RbJob { alloc, list, buf, ptr: p as *mut u8, cap, rb_v: 0, done_v: 0, copies: Vec::new(), ty, fences: None, seq: 0 }) + } + + /// Land submitted copies back in the title's memory as far as `how` says: every job that is + /// done, a queue's own in their order (a job of a queue that waits does not hold back the + /// other queues' jobs). + unsafe fn drain_readbacks(&mut self, how: Drain) { + let rbq_done = self.rbq.as_ref().map(|(_, f)| f.clone()); + let mut i = 0; + let mut k = 0; + loop { + // the immediates of submissions before the next copy back first + while k < self.imm_jobs.len() && self.rb_jobs.get(i).is_none_or(|j| self.imm_jobs[k].seq < j.seq) { + if super::real::fence_completed(&self.imm_jobs[k].fence) < self.imm_jobs[k].value { + k += 1; + continue; + } + let Some(job) = self.imm_jobs.remove(k) else { break }; + for &(va, value, bytes) in &job.writes { + self.store_imm(va, value, bytes); + } + RB_PENDING.fetch_sub(1, Ordering::Release); + } + if i >= self.rb_jobs.len() { + break; + } + let (title_f, done_f, rb_v, done_v) = { + let j = &self.rb_jobs[i]; + match (&j.fences, &rbq_done) { + (Some((a, b)), _) => (a.clone(), b.clone(), j.rb_v, j.done_v), + (None, Some(d)) => (self.rb_fence.clone(), d.clone(), j.rb_v, j.done_v), + (None, None) => { + i += 1; + continue; + } + } + }; + if super::real::fence_completed(&done_f) < done_v { + if how == Drain::Finished || super::real::fence_completed(&title_f) < rb_v { + i += 1; + continue; + } + // the title's lists are done: only the copy itself is left + // (for 2 ms at most: the state's lock is held here, and every submit needs it; a copy + // that stands behind something else on its queue lands when it is done) + // (no event: `self.event` is the tile queue's, see `wait_for`) + let t0 = std::time::Instant::now(); + while super::real::fence_completed(&done_f) < done_v && t0.elapsed().as_micros() < 2000 { + std::thread::yield_now(); + } + if super::real::fence_completed(&done_f) < done_v { + static LATE: AtomicU64 = AtomicU64::new(0); + let k = LATE.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_warn!("sparse: {k} copies back so far not finished 2 ms after the title's work they follow – left for later"); + } + i += 1; + continue; + } + } + let Some(mut job) = self.rb_jobs.remove(i) else { break }; + let copies = std::mem::take(&mut job.copies); + for &(dst, off, len) in &copies { + self.copy_back(job.ptr, dst, off, len); + } + RB_PENDING.fetch_sub(1, Ordering::Release); + job.copies = copies; + job.copies.clear(); + self.rb_pool.push(job); + } + } + + /// `readback_ranges` without a CPU wait: the copies are recorded on the title's own `queue`, + /// right behind the lists that wrote `ranges` (so they wait for those lists and for nothing + /// else), and land in the title's memory in `drain_readbacks` once `fences.1` reaches `v`. + unsafe fn readback_async(&mut self, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], fences: &(ID3D12Fence, ID3D12Fence), v: u64) { + let ty = queue.GetDesc().Type; + // the mapped parts, in readback-buffer sized batches: (window, address, bytes) + let mut batches: Vec> = vec![Vec::new()]; + let mut used = 0usize; + for &(a, n) in ranges { + let mut at = 0usize; + while at < n { + let cur = a + at; + let tile = cur & !(TILE - 1); + let Some(wi) = self.window_index(cur) else { break }; + let to_tile_end = (tile + TILE) - cur; + if !self.mapped.contains_key(&tile) { + at += (n - at).min(to_tile_end); + continue; + } + if used == READBACK_STAGING { + batches.push(Vec::new()); + used = 0; + } + let to_win_end = (self.windows[wi].0 + crate::gpu::uma::WINDOW) - cur; + let chunk = (n - at).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); + batches.last_mut().expect("batch").push((wi, cur, chunk)); + used += chunk; + at += chunk; + } + } + for batch in batches.into_iter().filter(|b| !b.is_empty()) { + let need = batch.iter().map(|c| c.2).sum::(); + let Some(mut job) = self.rb_job(need, ty) else { + crate::xlog_warn!("sparse: no readback buffer for a copy back of {need} bytes – left out"); + return; + }; + let _ = job.alloc.Reset(); + let _ = job.list.Reset(&job.alloc, None); + let mut off = 0usize; + for (wi, cur, chunk) in batch { + let (base, res) = (self.windows[wi].0, self.windows[wi].1.clone()); + job.list.CopyBufferRegion(&job.buf, off as u64, &res, (cur - base) as u64, chunk as u64); + job.copies.push((cur, off, chunk)); + off += chunk; + } + if job.list.Close().is_ok() { + if sparse_order_enabled() { + // This path calls the native queue directly and bypasses + // the title ExecuteCommandLists hook. + self.submit_title(queue, || pc_execute(queue, &job.list)); + } else { + pc_execute(queue, &job.list); + } + } + job.rb_v = v; + job.done_v = v; + job.fences = Some(fences.clone()); + self.job_seq += 1; + job.seq = self.job_seq; + self.rb_jobs.push_back(job); + RB_PENDING.fetch_add(1, Ordering::Release); + RB_ASYNC.store(true, Ordering::Relaxed); + } + let _ = queue.Signal(&fences.1, v); + } + /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { + // copies back of earlier submissions first: their data is older than this one's + self.drain_readbacks(Drain::TitleDone); let Some((rb, p)) = self.readback_buf() else { return }; let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) let mut used = 0usize; @@ -1018,6 +1423,7 @@ impl State { if s.rb_list.Close().is_ok() { if let Ok(l) = s.rb_list.cast::() { super::title_textures::own_work(|| { + super::queue_probe::submit("sparse-readback", s.queue.as_raw() as usize, &[l.as_raw()]); s.queue.ExecuteCommandLists(&[Some(l)]); }); } @@ -1028,22 +1434,7 @@ impl State { s.reclaim_ring(); } for &(dst, off, len) in pending.iter() { - // copy only committed (non-hole) bytes - let mut at = dst; - let mut src_off = off; - let end = dst + len; - while at < end { - let pg = at & !(PAGE - 1); - let t = pg & !(TILE - 1); - let idx = (pg - t) / PAGE; - let step = (pg + PAGE).min(end) - at; - if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { - std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); - } - at += step; - src_off += step; - } - s.sync_sent_range(dst, len); + s.copy_back(p, dst, off, len); } pending.clear(); *used = 0; @@ -1231,34 +1622,152 @@ pub fn queue() -> Option { QUEUE.lock().unwrap().clone() } -pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { - if ranges.is_empty() { +pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { + if ranges.is_empty() && imms.is_empty() { return; } let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; - let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); - if filtered.is_empty() { + s.after_execute(queue, ranges, imms); +} + +/// The PC `ExecuteCommandLists` of `queue` for `list` (an adopted title queue's own method, +/// not XCL's hook: this is not a submit of the title's). +unsafe fn pc_execute(queue: &ID3D12CommandQueue, list: &ID3D12GraphicsCommandList) { + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + const SLOT: usize = 10; + let q = queue.as_raw(); + let f: ExecFn = if super::real::is_adopted(q) { std::mem::transmute(super::real::orig_fn(q, SLOT)) } else { std::mem::transmute(*(*(q as *const *const usize)).add(SLOT)) }; + let one = [list.as_raw()]; + f(q, 1, one.as_ptr()); +} + +/// copies back submitted and not landed yet, and whether any ran on the readback queue +static RB_PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static RB_ASYNC: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Whether copies back land asynchronously (any ran on the readback queue so far) +pub fn readbacks_async() -> bool { + RB_ASYNC.load(Ordering::Relaxed) +} + +/// Copies back that are done on the GPU, into the title's memory, and those whose title work +/// is done (waiting for the copy): before a CPU read of memory the title's lists wrote. +pub unsafe fn settle_readbacks() { + if RB_PENDING.load(Ordering::Acquire) == 0 { return; } - filtered.sort_unstable(); - let mut merged: Vec<(usize, usize)> = Vec::with_capacity(filtered.len()); - for (a, n) in filtered { - match merged.last_mut() { - Some(last) if a <= last.0.saturating_add(last.1) => { - let end = (last.0 + last.1).max(a + n); - last.1 = end - last.0; + if let Some(s) = lock_state().as_mut() { + s.drain_readbacks(Drain::TitleDone); + } +} + +/// `settle_readbacks` from a fence observation: the state's lock is only tried (for ~2 ms), as +/// XCL may be waiting on a fence of its own with the lock held. +pub unsafe fn settle_readbacks_try() { + if RB_PENDING.load(Ordering::Acquire) == 0 { + return; + } + let t0 = std::time::Instant::now(); + loop { + if let Ok(mut g) = STATE.try_lock() { + forget_released(&mut g); + if let Some(s) = g.as_mut() { + s.drain_readbacks(Drain::TitleDone); } - _ => merged.push((a, n)), + return; + } + if t0.elapsed() >= std::time::Duration::from_millis(2) { + return; } + std::thread::yield_now(); } - s.rb_value += 1; - let v = s.rb_value; - if queue.Signal(&s.rb_fence, v).is_ok() { - let _ = s.queue.Wait(&s.rb_fence, v); - super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); +} + +/// The thread that moves finished copies back into the title's memory, so it sees what its +/// lists wrote without submitting again (started with the first copy back). +fn start_readback_thread() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-sparse-readback".into()).spawn(|| loop { + std::thread::sleep(std::time::Duration::from_micros(500)); + if let Ok(mut g) = STATE.try_lock() { + forget_released(&mut g); + if let Some(s) = g.as_mut().filter(|s| !s.rb_jobs.is_empty() || !s.imm_jobs.is_empty()) { + unsafe { s.drain_readbacks(Drain::Finished) }; + } + } + }); + }); +} + +impl State { + /// `readback_after_execute` on this state + unsafe fn after_execute(&mut self, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { + let s = self; + let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); + // immediates: stored by XCL when the lists are done. One that another write of these + // lists overlaps, and all of them without a queue of the title's to order them on, + // come back with a copy like the rest. + let mut imm: Vec<(usize, u64, u8)> = Vec::new(); + for &(a, v, n) in imms { + if s.window_index(a).is_none() { + continue; + } + let len = (n & 0x7f) as usize; + if s.rbq.is_none() || ranges.iter().any(|&(ra, rn)| a < ra + rn && ra < a + len) { + filtered.push((a, len)); + } else { + imm.push((a, v, n)); + } + } + if filtered.is_empty() && imm.is_empty() { + return; + } + filtered.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(filtered.len()); + for (a, n) in filtered { + match merged.last_mut() { + Some(last) if a <= last.0.saturating_add(last.1) => { + let end = (last.0 + last.1).max(a + n); + last.1 = end - last.0; + } + _ => merged.push((a, n)), + } + } + if s.rbq.is_some() { + // on this queue: [the title's lists] Signal(first, v) [the copies] Signal(second, v) + let key = queue.as_raw() as usize; + if !s.rb_queue_fences.contains_key(&key) { + let (Ok(a), Ok(b)) = (s.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE), s.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE)) else { return }; + s.rb_queue_fences.insert(key, (a, b, 0)); + } + let (fences, v) = { + let e = s.rb_queue_fences.get_mut(&key).expect("fences"); + e.2 += 1; + ((e.0.clone(), e.1.clone()), e.2) + }; + let _ = queue.Signal(&fences.0, v); + if !imm.is_empty() { + s.job_seq += 1; + s.imm_jobs.push_back(ImmJob { seq: s.job_seq, fence: fences.0.clone(), value: v, writes: imm }); + RB_PENDING.fetch_add(1, Ordering::Release); + RB_ASYNC.store(true, Ordering::Relaxed); + } + if !merged.is_empty() { + s.readback_async(queue, &merged, &fences, v); + } + start_readback_thread(); + return; + } + s.rb_value += 1; + let v = s.rb_value; + if queue.Signal(&s.rb_fence, v).is_ok() { + let _ = s.queue.Wait(&s.rb_fence, v); + super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); + } + s.readback_ranges(&merged); } - s.readback_ranges(&merged); } /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with @@ -1392,9 +1901,18 @@ impl State { } } - /// a pool tile no window maps, none is parked on and no buffer uses goes back to the free list - fn release_if_unused(&mut self, tile: (u32, u32)) { - if !self.pinned.contains_key(&tile) && !self.mapped.values().any(|e| e.pool == tile) && !self.parked.values().any(|&p| p == tile) { + /// A pool tile a buffer used at `t` goes back to the free list, unless its window maps it, it + /// is parked there, or another buffer uses it. Kept mapped for the buffer: parked from here on. + fn release_if_unused(&mut self, t: usize, tile: (u32, u32)) { + if self.pinned.contains_key(&tile) { + return; + } + if self.kept.get(&t) == Some(&tile) { + self.kept.remove(&t); + self.parked.insert(t, tile); + return; + } + if self.mapped.get(&t).is_none_or(|e| e.pool != tile) && self.parked.get(&t) != Some(&tile) { self.free.push(tile); } } @@ -1408,12 +1926,18 @@ impl State { } let mut by_window: FxHashMap> = FxHashMap::default(); for (t, tile) in std::mem::take(&mut self.parked) { + // (a placed buffer uses it) + if self.pinned.contains_key(&tile) { + self.kept.insert(t, tile); + continue; + } if let Some(wi) = self.window_index(t) { by_window.entry(wi).or_default().push(t); } - if !self.pinned.contains_key(&tile) { - self.free.push(tile); - } + self.free.push(tile); + } + if by_window.is_empty() { + return false; } for (wi, ts) in by_window { let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); @@ -1461,6 +1985,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let t0 = std::time::Instant::now(); let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; + s.drain_readbacks(Drain::Finished); // the title's work sees what was decommitted unmapped, as it was if s.flush_parked() { s.retire_free_pools(); @@ -1544,6 +2069,34 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } } +fn expect_queue_order(result: windows::core::Result<()>, operation: &str) { + if let Err(error) = result { + super::real::stop_if_device_removed(); + panic!("{operation} failed: {error}"); + } +} + +fn sparse_order_enabled() -> bool { + static ENABLED: std::sync::LazyLock = std::sync::LazyLock::new(|| std::env::var_os("XCL_SPARSE_QUEUE_ORDER").is_some()); + *ENABLED +} + +/// Pair the native submission and its fence under the same lock as sparse mutations. +/// The opt-in is isolated while forward title queue waits are being exercised. +pub(super) unsafe fn ordered_submit(raw: *mut c_void, submit: impl FnOnce() -> R) -> R { + if super::title_textures::is_own_work() { + return submit(); + } + super::present::remember_queue(raw); + if !sparse_order_enabled() { + return submit(); + } + let Some(queue) = ID3D12CommandQueue::from_raw_borrowed(&raw) else { return submit() }; + let mut state = lock_state(); + let Some(s) = state.as_mut() else { return submit() }; + s.submit_title(queue, submit) +} + /// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC /// description): a reserved resource over the window's tiles there, starting at the 64 KiB /// below `va` (returned: its distance from there). @@ -1581,7 +2134,7 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D for &(_, tile) in &tiles { *s.pinned.entry(tile).or_default() += 1; } - s.buffers.insert(raw as usize, tiles.iter().map(|x| x.1).collect()); + s.buffers.insert(raw as usize, tiles); s.signal(); Some((hr, delta)) } @@ -1621,12 +2174,12 @@ pub fn forget_buffer(res: usize) { fn forget_in(s: &mut State, res: usize) { let Some(tiles) = s.buffers.remove(&res) else { return }; - for tile in tiles { + for (address, tile) in tiles { if let Some(c) = s.pinned.get_mut(&tile) { *c -= 1; if *c == 0 { s.pinned.remove(&tile); - s.release_if_unused(tile); + s.release_if_unused(address, tile); } } } @@ -1636,6 +2189,277 @@ fn forget_in(s: &mut State, res: usize) { mod tests { use super::*; + #[test] + fn mappings_and_title_writes_wait_in_both_directions() { + use crate::gpu::fence::{self, FenceError}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIFactory6}; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + + unsafe { + // Run this test on its own with the switch set because the debug + // layer must be configured before the process creates a device. + let validate = std::env::var_os("XCL_TEST_SPARSE_DEBUG").is_some(); + if validate { + crate::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) + .expect("D3D12 debug layer").EnableDebugLayer(); + } + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no DXGI factory"); + return; + }; + let selector = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((adapter, _)) = crate::gpu::adapter::candidates(&factory, &selector).into_iter().next() else { + crate::gpu::recomp::runner::skip_test("no selected adapter"); + return; + }; + let mut dev: Option = None; + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return; + } + let dev = dev.unwrap(); + let mut reserved = None; + if dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved).is_err() { + crate::gpu::recomp::runner::skip_test("no reserved buffers"); + return; + } + let reserved: ID3D12Resource = reserved.unwrap(); + let base = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let mut s = new_state(&dev, vec![(base, reserved.clone())]).expect("sparse state"); + let title: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("CPU gate"); + + let mut upload = None; + let desc = D3D12_RESOURCE_DESC { Flags: D3D12_RESOURCE_FLAG_NONE, ..buffer_desc(4) }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut upload).expect("upload buffer"); + let upload: ID3D12Resource = upload.unwrap(); + let mut ptr = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut ptr)).expect("upload map"); + *ptr.cast::() = 0x1234_5678; + upload.Unmap(0, None); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("title allocator"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("title list"); + list.CopyBufferRegion(&reserved, 0, &upload, 0, 4); + list.Close().expect("close title list"); + + // A title write queued while the initial mapping is blocked cannot overtake it. + s.queue.Wait(&gate, 1).expect("block initial mapping"); + s.commit_range(base, TILE); + assert!(s.mapped.contains_key(&base)); + s.submit_title(&title, || pc_execute(&title, &list)); + let done = s.title_access[&(title.as_raw() as usize)].fence.clone(); + let held_by_map = fence::wait(&done, 1, &dev, None, 100); + gate.Signal(1).expect("release initial mapping"); + fence::wait(&done, 1, &dev, None, 5000).expect("title write completed"); + assert!(matches!(held_by_map, Err(FenceError::Timeout(_)))); + s.readback_ranges(&[(base, 4)]); + assert_eq!(*(base as *const u32), 0x1234_5678); + + // A later unmap cannot overtake a blocked write to the previous mapping. + title.Wait(&gate, 2).expect("block title write"); + s.submit_title(&title, || pc_execute(&title, &list)); + s.decommit_range(base, TILE); + assert!(s.flush_parked()); + let held_by_title = fence::wait(&s.fence, s.value, &dev, None, 100); + gate.Signal(2).expect("release title write"); + fence::wait(&s.fence, s.value, &dev, None, 5000).expect("unmap completed"); + assert!(matches!(held_by_title, Err(FenceError::Timeout(_)))); + if validate { + let info: ID3D12InfoQueue = dev.cast().expect("D3D12 debug info queue"); + let mut conflicts = 0; + for index in 0..info.GetNumStoredMessagesAllowedByRetrievalFilter() { + let mut size = 0; + info.GetMessage(index, None, &mut size).unwrap(); + let mut data = vec![0usize; size.div_ceil(std::mem::size_of::())]; + let msg = data.as_mut_ptr().cast::(); + info.GetMessage(index, Some(msg), &mut size).unwrap(); + if (*msg).ID.0 == 1047 { + conflicts += 1; + } + if (*msg).Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 { + let text = std::ffi::CStr::from_ptr((*msg).pDescription.cast()).to_string_lossy(); + println!("sparse fixture debug error {}: {text}", (*msg).ID.0); + } + } + println!("sparse fixture: byte-exact readback with {conflicts} D3D12 error 1047 messages"); + } + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A copy back after a title submission does not wait for the title's queue: that queue can + /// be waiting for work the title submits next, from the thread that is in here. The copy + /// lands once the title's work is done (`drain_readbacks`). Before, the sparse queue + /// GPU-waited for the title's queue and this thread waited for the copy (5 s, then on). + #[test] + fn a_copy_back_does_not_wait_for_the_title_queue() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + let base = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(base != 0 && base % TILE == 0); + assert!(!VirtualAlloc(base as *const c_void, TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + let mut reserved: Option = None; + dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved).expect("CreateReservedResource"); + let reserved = reserved.expect("reserved buffer"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); + rb_list.Close().expect("rb_list close"); + let rbq_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("readback queue"); + let rbq_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("readback fence"); + + let mut s = State { + dev: dev.clone(), + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + rb_queue_fences: FxHashMap::default(), + rbq: Some((rbq_queue, rbq_fence)), + rbq_value: 0, + rb_jobs: VecDeque::new(), + rb_pool: Vec::new(), + imm_jobs: VecDeque::new(), + job_seq: 0, + windows: vec![(base, reserved.clone())], + pools: Vec::new(), + free: Vec::new(), + retired: Vec::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + kept: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: Vec::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + zero_buf: None, + slots: Vec::new(), + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + title_access: FxHashMap::default(), + runs: None, + scratch_runs: Vec::new(), + }; + s.commit_range(base, TILE); + assert!(s.mapped.contains_key(&base)); + std::ptr::write_bytes(base as *mut u8, 0, TILE); + + // Queue A waits for the CPU while B writes a different range of the same tile. + // The CPU must see B's copy before releasing A, and then see A's later write. + const BYTES: usize = 256; + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate"); + let submit = |offset: usize, tag: u32, blocked: bool| { + let title: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let mut up: Option = None; + let desc = D3D12_RESOURCE_DESC { Flags: D3D12_RESOURCE_FLAG_NONE, ..buffer_desc(BYTES as u64) }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up) + .expect("upload buffer"); + let up = up.expect("upload buffer"); + let mut p: *mut c_void = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("Map"); + for i in 0..BYTES / 4 { + *p.cast::().add(i) = tag | i as u32; + } + up.Unmap(0, None); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("allocator"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&reserved, offset as u64, &up, 0, BYTES as u64); + list.Close().expect("close"); + title.Wait(&s.fence, s.value).expect("wait for the tile mapping"); + if blocked { + title.Wait(&gate, 1).expect("wait for the gate"); + } + title.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + // Keep the allocator, list and upload buffer alive through GPU completion. + (title, alloc, list, up) + }; + let first = submit(0, 0xA000_0000, true); + let second = submit(PAGE, 0xB000_0000, false); + // Signal after B's original write, before submitting its readback. If both + // direct queues share a blocked execution lane, B itself may be unable to run. + let b_uploaded: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("B upload fence"); + second.0.Signal(&b_uploaded, 1).expect("B upload signal"); + let t0 = std::time::Instant::now(); + s.after_execute(&first.0, &[(base, BYTES)], &[]); + let took = t0.elapsed(); + s.after_execute(&second.0, &[(base + PAGE, BYTES)], &[]); + + // Observe the title's memory instead of assuming which private fence owns a copy. + let matches = |offset: usize, tag: u32| { + (0..BYTES / 4).all(|i| *((base + offset) as *const u32).add(i) == (tag | i as u32)) + }; + let land_until = |s: &mut State, offset, tag| { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3); + loop { + s.drain_readbacks(Drain::Finished); + if matches(offset, tag) { return true; } + if std::time::Instant::now() >= deadline { return false; } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + let second_landed = land_until(&mut s, PAGE, 0xB000_0000); + let first_pending = s.rb_jobs.len() == 1; + let first_untouched = std::slice::from_raw_parts(base as *const u32, BYTES / 4).iter().all(|&v| v == 0); + let b_before_release = b_uploaded.GetCompletedValue(); + gate.Signal(1).expect("release first queue"); + let first_landed = land_until(&mut s, 0, 0xA000_0000); + let second_after_release = land_until(&mut s, PAGE, 0xB000_0000); + // A broken implementation may have consumed its readback job early. Its original + // upload still needs to finish before we release the D3D12 objects below. + for queue in [&first.0, &second.0] { + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("completion fence"); + queue.Signal(&done, 1).expect("queue completion"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3); + while done.GetCompletedValue() < 1 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(done.GetCompletedValue(), 1, "title queue completed"); + } + assert!(took < std::time::Duration::from_secs(1), "the copy back waited {took:?} for the title's queue"); + eprintln!("B upload fence before A release = {b_before_release}, B readback = {second_landed}, A pending = {first_pending}, A untouched = {first_untouched}"); + assert!(b_before_release <= 1, "B upload fence reports device removal"); + assert!(second_after_release, "B must publish all its words by the end"); + assert!(first_landed, "A must publish all its words after the gate opens"); + assert!(matches(PAGE, 0xB000_0000), "A must preserve B's earlier write"); + assert!(s.rb_jobs.is_empty(), "both copies were consumed"); + assert_eq!(s.rb_pool.len(), 2, "both buffers are kept for the next submission"); + if b_before_release == 0 { + assert!(!second_landed, "B cannot publish a readback before its own fence"); + crate::gpu::recomp::runner::skip_test("queue B's upload did not finish while A was gated; independent queue progress unverified"); + } else { + assert!(second_landed, "B uploaded before A was released, so its readback must land independently"); + assert!(first_pending && first_untouched, "B must not retire or publish A's readback"); + } + drop(s); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`). @@ -1743,11 +2567,19 @@ mod tests { event, rb_fence, rb_value: 0, + rb_queue_fences: FxHashMap::default(), + rbq: None, + rbq_value: 0, + rb_jobs: VecDeque::new(), + rb_pool: Vec::new(), + imm_jobs: VecDeque::new(), + job_seq: 0, windows: Vec::new(), pools: Vec::new(), free: Vec::new(), retired: Vec::new(), parked: FxHashMap::default(), + kept: FxHashMap::default(), mapped: FxHashMap::default(), pinned: FxHashMap::default(), buffers: FxHashMap::default(), @@ -1765,6 +2597,7 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + title_access: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), }; @@ -1949,6 +2782,13 @@ mod tests { event, rb_fence, rb_value: 0, + rb_queue_fences: FxHashMap::default(), + rbq: None, + rbq_value: 0, + rb_jobs: VecDeque::new(), + rb_pool: Vec::new(), + imm_jobs: VecDeque::new(), + job_seq: 0, windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), @@ -1956,6 +2796,7 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + kept: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), staging: None, @@ -1971,6 +2812,7 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + title_access: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), }; @@ -2015,13 +2857,22 @@ mod tests { use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no DXGI factory"); + return; + }; + let selector = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &selector).into_iter().next() else { + crate::gpu::recomp::runner::skip_test("no selected adapter"); + return; + }; let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); - D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no D3D12 device on the selected adapter"); + return; } let dev = dev.expect("D3D12 device"); + eprintln!("sparse tile-lifetime GPU: {}", crate::gpu::adapter::name(&desc)); let base = VirtualAlloc(std::ptr::null(), 2 * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; assert!(base != 0 && base % TILE == 0); let mut reserved: Option = None; @@ -2044,6 +2895,13 @@ mod tests { event, rb_fence, rb_value: 0, + rb_queue_fences: FxHashMap::default(), + rbq: None, + rbq_value: 0, + rb_jobs: VecDeque::new(), + rb_pool: Vec::new(), + imm_jobs: VecDeque::new(), + job_seq: 0, windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), @@ -2051,6 +2909,7 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + kept: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), staging: None, @@ -2066,6 +2925,7 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + title_access: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), }; @@ -2081,7 +2941,7 @@ mod tests { assert_eq!(s.parked.get(&base), Some(&tile)); assert!(!s.free.contains(&tile)); assert_eq!(s.value, v, "no tile mapping changed"); - s.release_if_unused(tile); + s.release_if_unused(base, tile); assert!(!s.free.contains(&tile), "a parked tile is not free"); // committed again: the same tile, cleared, no new mapping @@ -2113,6 +2973,38 @@ mod tests { assert_eq!(s.mapped[&(base + TILE)].pool, tile); assert!(!s.mapped.contains_key(&base)); + // a placed buffer uses the tile: the window keeps it when it is decommitted and + // flushed, memory committed there again is the buffer's, and it is free only once + // the buffer is gone and it was decommitted + let at = base + TILE; + let mut alias: Option = None; + s.dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut alias) + .expect("placed buffer"); + let alias = alias.expect("reserved alias"); + let alias_id = alias.as_raw() as usize; + s.map_tiles(&alias, at, &[(at, tile)]); + s.signal(); + s.buffers.insert(alias_id, vec![(at, tile)]); + *s.pinned.entry(tile).or_default() += 1; + s.decommit_range(at, TILE); + assert!(!s.flush_parked(), "nothing to unmap"); + assert_eq!(s.kept.get(&at), Some(&tile)); + assert!(!s.free.contains(&tile)); + let v = s.value; + s.to_zero.clear(); + s.commit_range(at, TILE); + assert_eq!(s.mapped[&at].pool, tile, "the buffer's tile"); + assert_eq!(s.to_zero, vec![(at, TILE)]); + assert_eq!(s.value, v, "no tile mapping changed"); + s.decommit_range(at, TILE); + assert!(!s.flush_parked()); + s.wait_for(s.value); + drop(alias); + forget_in(&mut s, alias_id); + assert!(s.kept.is_empty() && !s.free.contains(&tile)); + assert!(s.flush_parked()); + 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/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 05de94b66d..c3935c8595 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -129,6 +129,7 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { let pc = *((this as usize + F_BACKING) as *const *mut c_void); let f: unsafe extern "system" fn(*mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 9)); let hr = f(pc); + super::title_textures::note_list_closed(this as usize); let n = *((this as usize + F_RING_AT) as *const usize); if hr < 0 && n > 0 { let first = n.saturating_sub(RING); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ac38429be7..141809fd91 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -389,13 +389,23 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); clone_resources(&unmap_ptrs) }; - for r in &to_unmap { - super::vram::unmap_superseded(r); - } + unmap_superseded_all(&to_unmap); TEXTURES_GEN.fetch_add(1, Ordering::Release); Ok(()) } +/// Unmap superseded placed textures after any in-flight `refresh` / `upload_batch` has finished +/// on `upload_queue` (lock order: `REFRESH` after dropping `TEXTURES`). +unsafe fn unmap_superseded_all(to_unmap: &[ID3D12Resource]) { + if to_unmap.is_empty() { + return; + } + let _refresh = REFRESH.lock().unwrap(); + for r in to_unmap { + super::vram::unmap_superseded(r); + } +} + /// Where a texture at `va` is read from: the CPU view behind a GPU view (`kernelx::mirrors`) /// when nothing is mapped at `va` itself, else `va`. A physical page mapped at `va` counts /// before its first use too, while it is still reserved memory (`kernelx::physical_page_at`). @@ -457,13 +467,39 @@ fn recheck_source(e: &mut Entry) -> bool { /// by the GPU). The first upload, if still pending, stays: it runs before the title's submit /// that copies. pub fn note_gpu_write(res: usize) { - let mut t = TEXTURES.lock().unwrap(); - if let Some(e) = t.get_mut(res) { + if is_own_work() { + return; + } + { + let mut t = TEXTURES.lock().unwrap(); + let Some(e) = t.get_mut(res) else { return }; if !e.gpu_written { e.gpu_written = true; GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); } } + super::vram::prepare_gpu_write(res); +} + +/// Tiles skipped by an earlier upload now have backing. Schedule another upload even if +/// the source hash is unchanged, so the newly resident tiles receive their texels. +pub(super) fn backing_added(resources: &[usize]) { + if resources.is_empty() { + return; + } + { + let mut hashes = LAST_CONTENT.lock().unwrap(); + for res in resources { + hashes.remove(res); + } + } + let mut t = TEXTURES.lock().unwrap(); + for &res in resources { + if let Some(e) = t.by_res.get_mut(&res).filter(|e| !e.gpu_written && !e.pending) { + e.pending = true; + PENDING.fetch_add(1, Ordering::Relaxed); + } + } } static GPU_WRITTEN: AtomicU64 = AtomicU64::new(0); @@ -487,9 +523,7 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); (retired, clone_resources(&unmap_ptrs)) }; - for r in &to_unmap { - super::vram::unmap_superseded(r); - } + unmap_superseded_all(&to_unmap); if retired > 0 { TEXTURES_GEN.fetch_add(1, Ordering::Release); } @@ -660,7 +694,61 @@ pub(super) unsafe fn refresh(queue: *mut c_void) { return; } let _refresh = REFRESH.lock().unwrap(); - own_work(|| refresh_once(queue)); + own_work(|| refresh_once(queue, true)); +} + +/// microseconds since the first call, never 0 +fn now_us() -> u64 { + static T0: std::sync::OnceLock = std::sync::OnceLock::new(); + T0.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 + 1 +} + +/// when the last look for CPU writes began (`now_us`; 0: none yet) +static LOOK_BEGAN: AtomicU64 = AtomicU64::new(0); +/// title list -> when the title closed it (`now_us`) +static CLOSED: Mutex>> = Mutex::new(None); + +/// The title closed `list` (its own pointer): what the list's GPU work reads was written by now. +pub(super) fn note_list_closed(list: usize) { + CLOSED.lock().unwrap().get_or_insert_with(Default::default).insert(list, now_us()); +} + +/// `XCL_LOOK_SKIP=1`: a submit all of whose lists were closed before the last look for CPU writes +/// began goes without a look of its own (that look took what the lists read). Off unless set: +/// a title may write what a closed list reads until it submits the list. +fn look_skip() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_LOOK_SKIP").is_ok_and(|v| v.trim() == "1")) +} + +fn closed_before_last_look(lists: &[*mut c_void]) -> bool { + let began = LOOK_BEGAN.load(Ordering::Acquire); + if began == 0 || lists.is_empty() { + return false; + } + let g = CLOSED.lock().unwrap(); + let Some(m) = g.as_ref() else { return false }; + lists.iter().all(|&l| m.get(&(l as usize)).is_some_and(|&t| t < began)) +} + +/// `refresh` before the title's ExecuteCommandLists of `lists` (its own pointers). +pub(super) unsafe fn refresh_for(queue: *mut c_void, lists: &[*mut c_void]) { + if BUSY.with(|b| b.get()) { + return; + } + let _refresh = REFRESH.lock().unwrap(); + // with the lock: the look before this one is done, and its uploads are submitted + let old = closed_before_last_look(lists); + static N: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + let n = N[0].fetch_add(1, Ordering::Relaxed) + 1; + let k = N[1].fetch_add(old as u64, Ordering::Relaxed) + old as u64; + if n % 1024 == 0 { + crate::xlog_info!( + "D3D12.X: {k} of {n} ExecuteCommandLists so far had all their lists closed before the last look for CPU writes began ({})", + if look_skip() { "their looks were left out" } else { "XCL_LOOK_SKIP=1 leaves their looks out" } + ); + } + own_work(|| refresh_once(queue, !(old && look_skip()))); } /// The pages of `[base, base + size)` written since the last look, added to `dirty` and reset @@ -683,7 +771,7 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: } } -unsafe fn refresh_once(queue: *mut c_void) { +unsafe fn refresh_once(queue: *mut c_void, look: bool) { let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); if !sparse && TEXTURES_LEN.load(Ordering::Relaxed) == 0 { @@ -696,6 +784,10 @@ unsafe fn refresh_once(queue: *mut c_void) { let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); dirty.clear(); + if !look { + return 0; + } + LOOK_BEGAN.store(now_us(), Ordering::Release); WATCH_BUF.with(|wcell| { let mut buf = wcell.borrow_mut(); if buf.len() < 16384 { @@ -708,7 +800,9 @@ unsafe fn refresh_once(queue: *mut c_void) { dirty.sort_unstable(); dirty.len() }); - super::sparse::note_watch(watch_t0.elapsed(), dirty_len); + if look { + super::sparse::note_watch(watch_t0.elapsed(), dirty_len); + } if super::present::trace_frame() { // every 600th look: what the CPU's view of a few textures holds now (does the title's // data reach the address at all, and is the texture still kept in step?) @@ -1599,6 +1693,179 @@ mod tests { } } + unsafe fn read_texture_subresource(dev: &ID3D12Device, queue: &ID3D12CommandQueue, r: &ID3D12Resource, sub: u32) -> Vec { + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + let rd = r.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&rd, sub, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + 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 = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = 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(|| { + super::super::vram::before_execute(queue); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(dev, queue).unwrap(); + }); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let slice_pitch = fp.Footprint.RowPitch as usize * rows as usize; + let mut out = Vec::with_capacity(fp.Footprint.Depth as usize * rows as usize * row_bytes as usize); + for z in 0..fp.Footprint.Depth as usize { + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(z * slice_pitch + y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + } + rb.Unmap(0, None); + out + } + + /// A title requesting an address from MapTitlePhysicalPages receives the page at home. + /// Retaining that target and mapping the page at a chosen address must also share the tile. + #[test] + fn render_target_at_physical_page_home_inherits_texels_after_move() { + use crate::gpu::recomp::runner::skip_test; + use crate::hle::kernelx; + use std::mem::ManuallyDrop; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + const SIDE: usize = 128; + unsafe { + let Ok(factory) = CreateDXGIFactory1::() else { return skip_test("no GPU") }; + let selector = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((adapter, info)) = crate::gpu::adapter::candidates(&factory, &selector).into_iter().next() else { + return skip_test("no selected GPU"); + }; + println!("GPU: {}", crate::gpu::adapter::name(&info)); + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { return skip_test("no GPU") }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() { + return skip_test("D3D12 options unavailable"); + } + if opts.ResourceHeapTier.0 < D3D12_RESOURCE_HEAP_TIER_2.0 { + return skip_test("resource heap tier < 2"); + } + if std::env::var_os("XCL_VRAM_ARENAS").is_some() { + return skip_test("XCL_VRAM_ARENAS selects the arena backend"); + } + if opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 { + return skip_test("tiled tier < 2"); + } + if crate::gpu::uma::get().is_none() { + return skip_test("no UMA"); + } + + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let mut desc = console_desc(3, SIDE as u64, SIDE as u32, 1, 1, 28, 0x109); + desc[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); // ALLOW_RENDER_TARGET + let space = VirtualAlloc(std::ptr::null(), 3 << 20, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(space, 0); + let (mut count, mut pages) = (2usize, [0usize; 2]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + assert_eq!(count, pages.len()); + let place = |va: usize, page: &mut usize| -> ID3D12Resource { + let mapped = kernelx::MapTitlePhysicalPages(va as *mut c_void, 1, 0, 4, page) as usize; + assert_ne!(mapped, 0); + if va != 0 { + assert_eq!(mapped, va); + } + 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(dev.as_raw(), mapped 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: {hr:#x}"); + let target = ID3D12Resource::from_raw(p); + assert_eq!(target.GetDesc().Layout, D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, "expected a reserved target"); + target + }; + let a = place(0, &mut pages[0]); + let b = place(space + (1 << 20), &mut pages[0]); + let c = place(space + (2 << 20), &mut pages[1]); + + // Submit tile mappings, full-subresource initializations and alias hand-offs on + // one direct queue. Each write/hand-off is fenced; both aliases are in COMMON. + let write = |r: &ID3D12Resource, seed: u8| -> Vec { + let data: Vec = (0..SIDE * SIDE).flat_map(|i| [seed, (i % SIDE) as u8, (i / SIDE) as u8, 255]).collect(); + let sub = Subresource { rows: SIDE, row_bytes: SIDE * 4, depth: 1, data: data.clone() }; + own_work(|| { + super::super::vram::before_execute(&queue); + texture::upload(&dev, &queue, r, &[sub], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON).unwrap(); + }); + data + }; + let switch = |before: &ID3D12Resource, after: &ID3D12Resource| { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::transmute_copy(before), + pResourceAfter: std::mem::transmute_copy(after), + }), + }, + }; + list.ResourceBarrier(&[barrier]); + list.Close().unwrap(); + own_work(|| { + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&dev, &queue).unwrap(); + }); + }; + let check = |label: &str, r: &ID3D12Resource, expected: &[u8]| { + let actual = read_texture_subresource(&dev, &queue, r, 0); + assert_eq!(actual.len(), SIDE * SIDE * 4); + let matches = actual.chunks_exact(4).zip(expected.chunks_exact(4)).filter(|(a, e)| a == e).count(); + println!("{label}: {matches}/{} matching texels, first RGBA {:?}, expected {:?}", SIDE * SIDE, &actual[..4], &expected[..4]); + matches == SIDE * SIDE + }; + let canary = write(&c, 0x33); + write(&b, 0x44); // Deterministic stale data if B has private backing. + switch(&b, &a); + let from_a = write(&a, 0x11); + let a_write = check("A direct", &a, &from_a); + switch(&a, &b); + let a_to_b = check("A to B", &b, &from_a); + let from_b = write(&b, 0x22); + let b_write = check("B direct", &b, &from_b); + switch(&b, &a); + let b_to_a = check("B to A", &a, &from_b); + let independent = check("independent", &c, &canary); + + drop((a, b, c)); + for va in [space + (1 << 20), space + (2 << 20)] { + let mut empty = 0usize; + assert_eq!(kernelx::MapTitlePhysicalPages(va as *mut c_void, 1, 0, 4, &mut empty) as usize, va); + } + assert_eq!(kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + assert_ne!(VirtualFree(space as *mut c_void, 0, MEM_RELEASE), 0); + assert!(a_write && b_write && independent, "direct writes and the independent page must survive"); + assert!(a_to_b && b_to_a, "writes through either physical alias must be visible through the other"); + } + } + fn console_desc(dim: u32, w: u64, h: u32, array_or_depth: u16, mips: u16, format: u32, layout: u32) -> [u8; 0x38] { let mut d = [0u8; 0x38]; d[0..4].copy_from_slice(&dim.to_le_bytes()); @@ -1664,6 +1931,100 @@ mod tests { assert!(tbl.by_res.contains_key(&10) && tbl.by_res.contains_key(&11)); 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)); + // Unaligned 88 KiB mip-chain siblings at +0x4000 own page +0x1_0000 plus 1 extra_page; + // an aligned 64 KiB cover at +0x1_0000 supersedes both without allocating a new base page. + let tex_88k = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 8, 28, 0x105)).unwrap()); + assert_eq!(tex_88k.size(), 0x1_6000); + assert_eq!(tbl.insert(30, entry(0x30_4000, &tex_88k, true, true)), (1, vec![])); + assert_eq!(tbl.insert(31, entry(0x30_4000, &tex_88k, true, true)), (0, vec![])); + let (_, mut unmap_unaligned) = tbl.insert(32, entry(0x31_0000, &tex_64k, true, true)); + unmap_unaligned.sort_unstable(); + assert_eq!(unmap_unaligned, vec![30, 31]); + } + + /// Real GPU: render targets at two addresses of one physical page (mapped at the second after + /// the first, as a retail game aliases its targets) share one page of video memory, as on the + /// console; a target on another physical page gets its own. + #[test] + fn render_targets_on_one_physical_page_share_its_video_memory() { + // (a test that panicked holding these locks does not fail this one too) + 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 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, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const NAME: &str = "render_targets_on_one_physical_page_share_its_video_memory"; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory1().expect("DXGI factory"); + let selector = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((adapter, info)) = crate::gpu::adapter::candidates(&factory, &selector).into_iter().next() else { + return println!("SKIPPED {NAME}: no selected hardware adapter"); + }; + println!("GPU: {}", crate::gpu::adapter::name(&info)); + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { return println!("SKIPPED {NAME}: no D3D12 device") }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 + { + return println!("SKIPPED {NAME}: tiled tier < 2"); + } + // (`vram::place` keeps no render target on pages below resource heap tier 2) + if opts.ResourceHeapTier.0 < 2 { + return println!("SKIPPED {NAME}: resource heap tier < 2"); + } + if crate::gpu::uma::get().is_none() { + return println!("SKIPPED {NAME}: no UMA"); + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + // a 128x128 R8G8B8A8 render target: one 64 KiB page on the console and on the PC + let mut rt = console_desc(3, 128, 128, 1, 1, 28, 0x109); + rt[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); + let place = |va: usize| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), va as u64, rt.as_ptr(), D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, std::ptr::null(), riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "CreatePlacedResourceX at {va:#x}: {hr:#x}"); + assert!(super::super::vram::is_placed_texture(p as usize), "expected a vram::Pages target at {va:#x}"); + ID3D12Resource::from_raw(p) + }; + let dev_pages = || super::super::vram::page_bytes_for(dev.as_raw() as usize).0; + let lost = || super::super::vram::tiles_unaccounted_for(dev.as_raw() as usize); + let space = VirtualAlloc(std::ptr::null(), 4 << 20, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(space, 0); + let (a, b, c, d) = (space, space + (1 << 20), space + (2 << 20), space + (3 << 20)); + let (mut n, mut pages) = (3usize, [0usize; 3]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let (before, lost_before) = (dev_pages(), lost()); + assert_eq!(kernelx::MapTitlePhysicalPages(a as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, a); + let first = place(a); + // the same page at a second address: the console's alias of `a` + assert_eq!(kernelx::MapTitlePhysicalPages(b as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, b); + let second = place(b); + let shared = dev_pages() - before; + // another physical page: video memory of its own + assert_eq!(kernelx::MapTitlePhysicalPages(c as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(1)) as usize, c); + let third = place(c); + let all = dev_pages() - before; + // a target at `d` with no page mapped (keyed by its address), then a page mapped there + // and a second target: its page is keyed by the physical page, which has none yet + let fourth = place(d); + assert_eq!(kernelx::MapTitlePhysicalPages(d as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(2)) as usize, d); + let fifth = place(d); + let lost_after = lost(); + drop((first, second, third, fourth, fifth)); + let mut none = [0usize; 1]; + kernelx::MapTitlePhysicalPages(b as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::MapTitlePhysicalPages(c as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::MapTitlePhysicalPages(d as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()); + VirtualFree(space as *mut c_void, 0, MEM_RELEASE); + assert_eq!(shared, 0x1_0000, "two targets on one physical page: one page of video memory"); + assert_eq!(all, 0x2_0000, "a target on another physical page: a page of its own"); + assert_eq!(lost_after, lost_before, "every pool tile taken is a page's"); + } } /// Real GPU (#248): placed title textures share `vram::Pages` so streaming unreleased @@ -1675,14 +2036,21 @@ mod tests { let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); let _guard = TEST_LOCK.lock().unwrap(); use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; use windows::Win32::Graphics::Dxgi::*; unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); - let Ok(adapter) = factory.EnumAdapters1(0) else { - println!("SKIPPED placed_title_textures_share_vram_and_preserve_pixels: no adapter"); + let requested = std::env::var("XCL_ADAPTER").unwrap_or_default().to_ascii_lowercase(); + let adapter = (0..).map_while(|i| factory.EnumAdapters1(i).ok()).find(|a| { + a.GetDesc1().is_ok_and(|d| { + String::from_utf16_lossy(&d.Description).to_ascii_lowercase().contains(&requested) + }) + }); + let Some(adapter) = adapter else { + println!("SKIPPED placed_title_textures_share_vram_and_preserve_pixels: no matching adapter"); return; }; + let adapter_desc = adapter.GetDesc1().unwrap(); + println!("texture residency GPU: {}", String::from_utf16_lossy(&adapter_desc.Description).trim_end_matches('\0')); if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { println!("SKIPPED placed_title_textures_share_vram_and_preserve_pixels: software adapter"); return; @@ -1757,49 +2125,12 @@ mod tests { } } }; - let read_sub = |r: &ID3D12Resource, sub: u32| -> Vec { - let rd = r.GetDesc(); - let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); - let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); - dev.GetCopyableFootprints(&rd, sub, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); - let mut rb: Option = None; - 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 = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = 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(|| { - super::super::vram::before_execute(&queue); - queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); - texture::wait(&dev, &queue).unwrap(); - }); - let mut p = std::ptr::null_mut(); - rb.Map(0, None, Some(&mut p)).unwrap(); - let slice_pitch = fp.Footprint.RowPitch as usize * rows as usize; - let mut out = Vec::with_capacity(fp.Footprint.Depth as usize * rows as usize * row_bytes as usize); - for z in 0..fp.Footprint.Depth as usize { - for y in 0..rows as usize { - out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(z * slice_pitch + y * fp.Footprint.RowPitch as usize), row_bytes as usize)); - } - } - rb.Unmap(0, None); - out - }; + let read_sub = |r: &ID3D12Resource, sub: u32| read_texture_subresource(&dev, &queue, r, sub); // 1. Streaming 512 unreleased 1 MiB textures (512 MiB placed) across 16 MiB stays bounded // with zero additional page growth after the 16 MiB working set is covered. let dev_key = dev.as_raw() as usize; + super::super::vram::flush_idle_for(dev_key); let dev_pages = || super::super::vram::page_bytes_for(dev_key).0; let stream_desc = console_desc(3, 512, 512, 1, 1, 28, 0x109); // 64KB_S, 1 MiB let (pages0, vram0, kept0) = (dev_pages(), local_vram(), counts().0); @@ -1869,10 +2200,13 @@ mod tests { assert_eq!(read_sub(&old_res, 0), subresources(base, &xg::Texture::new(&old_desc).unwrap())[0].data, "reactivated unmapped texture remapped cleanly"); drop(old_res); - // 3. 4 KiB-aligned adjacent textures inside one 64 KiB page + straddling page boundary, - // plus reclaiming dead extra_pages when overwritten by a larger placement without Release. + // 3. 4 KiB-aligned adjacent small textures pack into 4 KiB sub-allocated slots (no 64 KiB + // bloat per small texture), reuse the exact slot at the same va without crosstalk, and + // >= 64 KiB unaligned textures reclaim dead extra_pages immediately when overwritten. + super::super::vram::flush_idle_for(dev_key); let d16 = console_desc(3, 64, 64, 1, 1, 28, 0x105); // 4KB_S, 16 KiB let d64 = console_desc(3, 128, 128, 1, 1, 28, 0x105); // 4KB_S, 64 KiB + let adj_base_pages = dev_pages(); let adj_specs = [(0x0000usize, d16, 0x11u8), (0x4000, d16, 0x22), (0x8000, d16, 0x33), (0xC000, d64, 0x44), (0x1_C000, d16, 0x55)]; let adj: Vec<_> = adj_specs.iter().map(|&(off, d, _)| place_tex(base + off, &d)).collect(); for &(off, d, seed) in &adj_specs { @@ -1883,17 +2217,37 @@ mod tests { assert_eq!(read_sub(r, 0), subresources(base + off, &xg::Texture::new(&d).unwrap())[0].data, "4 KiB neighbour at +{off:#x} crosstalk"); } let pages_before_reuse = dev_pages(); + let adj_delta = pages_before_reuse - adj_base_pages; + assert!(adj_delta <= 128 * 1024, "four 16 KiB + one 64 KiB textures should use <= 128 KiB, got {adj_delta} B"); let reused = place_tex(base + 0x4000, &d16); - assert_eq!(dev_pages(), pages_before_reuse, "reusing unaligned va must share extra_pages tile"); - // Overwrite the first 64 KiB (covering +0x0000, +0x4000 (both adj[1] & reused), +0x8000, +0xC000) - // WITHOUT releasing adj/reused: dead extra_pages (+0x4000, +0x8000) must drop immediately! - let cover = place_tex(base, &d64); + assert_eq!(dev_pages(), pages_before_reuse, "reusing unaligned va must share backing slot"); + drop((reused, adj)); + + // Reclaiming dead extra_pages immediately when a >= 64 KiB unaligned tiled texture is + // overwritten by an overlapping placement without Release: + // `unaligned_a`/`b` at `base + 0x4000` (88 KiB, 2 tiles) own page `base + 0x1_0000` + // plus 1 `extra_pages` tile; `cover` at `base + 0x1_0000` reuses that already-live + // owned page (+0 new pages) while superseding both unaligned siblings and reclaiming + // their `extra_pages` tile immediately (-64 KiB). + super::super::vram::flush_idle_for(dev_key); + let d64_mips = console_desc(3, 128, 128, 1, 8, 28, 0x105); // 88 KiB, 2 tiles (mip 0 + packed mips) + let extra_before = super::super::vram::extra_page_bytes_for(dev_key); + let unaligned_a = place_tex(base + 0x4000, &d64_mips); + let extra_after_a = super::super::vram::extra_page_bytes_for(dev_key); + assert!(extra_after_a > extra_before, "unaligned >= 64 KiB tiled texture must allocate extra_pages ({extra_before} -> {extra_after_a})"); + let unaligned_b = place_tex(base + 0x4000, &d64_mips); + assert_eq!(super::super::vram::extra_page_bytes_for(dev_key), extra_after_a, "reusing unaligned va must share extra_pages tile"); + let pages_with_extra = dev_pages(); + let cover = place_tex(base + 0x1_0000, &d64); let pages_after_cover = dev_pages(); - assert!(pages_after_cover < pages_before_reuse, "superseded unaligned extra_pages must be reclaimed immediately ({pages_before_reuse} -> {pages_after_cover})"); - drop((cover, reused, adj)); + let extra_after_cover = super::super::vram::extra_page_bytes_for(dev_key); + assert_eq!(extra_after_cover, extra_before, "superseded unaligned extra_pages must drop back to baseline ({extra_after_a} -> {extra_after_cover})"); + assert!(pages_after_cover < pages_with_extra, "superseded unaligned extra_pages must be reclaimed immediately ({pages_with_extra} -> {pages_after_cover})"); + drop((cover, unaligned_b, unaligned_a)); // 4. Full mip chain (standard + packed mips, RGBA8 & BC7), tiny all-packed mips, // 6-slice cubemap (exercises extra_pages reuse), and 3D volume texture (Tier 3). + super::super::vram::flush_idle_for(dev_key); let shapes = [ ("2D 512x512 RGBA8 10 mips", console_desc(3, 512, 512, 1, 10, 28, 0x109)), ("2D 1024x1024 BC7 11 mips", console_desc(3, 1024, 1024, 1, 11, 98, 0x109)), @@ -1950,6 +2304,80 @@ mod tests { } drop(res); } + // A sampled texture in a GPU-only view starts with a NULL tile. Committing the + // paired CPU view must allocate exactly that tile and upload the real texels. + use crate::hle::kernelx::{self, mirrors, MEM_GRAPHICS}; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + const TILE: usize = 64 << 10; + let cpu = kernelx::VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_GRAPHICS, PAGE_READWRITE); + let gpu = kernelx::VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_GRAPHICS, PAGE_NOACCESS); + assert!(!cpu.is_null() && !gpu.is_null()); + mirrors::reserved(cpu as usize, TILE, MEM_RESERVE | 0x2040_0000, PAGE_READWRITE); + mirrors::reserved(gpu as usize, TILE, MEM_RESERVE | 0x2040_0000, PAGE_NOACCESS | 0x800); + assert_eq!(mirrors::source(gpu as usize), Some(cpu as usize)); + let deferred_desc = console_desc(3, 128, 128, 1, 1, 28, 0x109); + let deferred = place_tex(gpu as usize, &deferred_desc); + let key = deferred.as_raw() as usize; + let pending = || super::super::vram::deferred_tiles_for(key); + assert_eq!(pending(), 1, "reserved-only texture must defer its only tile"); + refresh(queue.as_raw()); + assert!(read_sub(&deferred, 0).iter().all(|&byte| byte == 0), "NULL tile must read zero"); + + assert_eq!(kernelx::VirtualAlloc(cpu, TILE, MEM_COMMIT, PAGE_READWRITE), cpu); + write_tiled(cpu as usize, &deferred_desc, 0x47); + let expected = subresources(cpu as usize, &xg::Texture::new(&deferred_desc).unwrap()).remove(0).data; + refresh(queue.as_raw()); + assert_eq!(pending(), 0, "the CPU view commit must back the GPU tile"); + assert_eq!(read_sub(&deferred, 0), expected, "late-backed texture pixels"); + + assert_ne!(kernelx::VirtualFree(cpu, TILE, MEM_DECOMMIT), 0); + super::super::vram::before_execute(&queue); + assert_eq!(read_sub(&deferred, 0), expected, "a live tile survives CPU decommit"); + drop(deferred); + assert_ne!(kernelx::VirtualFree(gpu, 0, MEM_RELEASE), 0); + assert_ne!(kernelx::VirtualFree(cpu, 0, MEM_RELEASE), 0); + // A multi-mip texture with no backing maps all of its PC tiles on + // the first CPU commit. Its tile order need not match the CPU pages. + let span = 32 * TILE; + let cpu = kernelx::VirtualAlloc(std::ptr::null(), span, MEM_RESERVE | MEM_GRAPHICS, PAGE_READWRITE); + let gpu = kernelx::VirtualAlloc(std::ptr::null(), span, MEM_RESERVE | MEM_GRAPHICS, PAGE_NOACCESS); + assert!(!cpu.is_null() && !gpu.is_null()); + mirrors::reserved(cpu as usize, span, MEM_RESERVE | 0x2040_0000, PAGE_READWRITE); + mirrors::reserved(gpu as usize, span, MEM_RESERVE | 0x2040_0000, PAGE_NOACCESS | 0x800); + let mip_desc = console_desc(3, 512, 512, 1, 3, 28, 0x109); + let mips = place_tex(gpu as usize, &mip_desc); + let key = mips.as_raw() as usize; + assert!(super::super::vram::deferred_tiles_for(key) > 1, "the multi-mip fixture must defer multiple tiles"); + assert_eq!(kernelx::VirtualAlloc(cpu, TILE, MEM_COMMIT, PAGE_READWRITE), cpu); + std::ptr::write_bytes(cpu.cast::(), 0x6D, TILE); + let expected_mips = subresources(cpu as usize, &xg::Texture::new(&mip_desc).unwrap()); + refresh(queue.as_raw()); + assert_eq!(super::super::vram::deferred_tiles_for(key), 0, "one commit maps all PC tiles"); + for (i, sub) in expected_mips.iter().enumerate() { + assert_eq!(read_sub(&mips, i as u32), sub.data, "partial backing mip {i}"); + } + drop(mips); + assert_ne!(kernelx::VirtualFree(gpu, 0, MEM_RELEASE), 0); + assert_ne!(kernelx::VirtualFree(cpu, 0, MEM_RELEASE), 0); + println!("partially committed multi-mip texture is byte-exact"); + // A GPU copy must receive backing even without a committed CPU source. + let dst_va = kernelx::VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_GRAPHICS, PAGE_READWRITE); + assert!(!dst_va.is_null()); + let dst = place_tex(dst_va as usize, &deferred_desc); + let key = dst.as_raw() as usize; + assert_eq!(super::super::vram::deferred_tiles_for(key), 1); + refresh(queue.as_raw()); + note_gpu_write(key); + assert_eq!(super::super::vram::deferred_tiles_for(key), 0); + let data = texture::Subresource { rows: 128, row_bytes: 512, depth: 1, data: expected.clone() }; + own_work(|| { + super::super::vram::before_execute(&queue); + texture::upload(&dev, &queue, &dst, &[data], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON).unwrap(); + }); + assert_eq!(read_sub(&dst, 0), expected, "GPU copy to an uncommitted address"); + drop(dst); + assert_ne!(kernelx::VirtualFree(dst_va, 0, MEM_RELEASE), 0); + println!("late texture backing verified on GPU: NULL read, paired-view commit, upload, retained pixels, GPU copy"); uma.free(base); } } @@ -2048,4 +2476,75 @@ mod tests { // Different device always starts a new batch. assert!(!batch_fits(1, 4096, 1, 2, 4096)); } + + /// Unmapping a superseded placed texture waits for any in-flight `refresh` (`upload_batch`) + /// to finish so `Pages.queue` cannot unmap tiles out from under `upload_queue`. + #[test] + fn superseded_unmap_waits_for_in_flight_refresh() { + use std::sync::atomic::AtomicBool; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + unsafe { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no DXGI factory"); + return; + }; + let selector = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((adapter, _)) = crate::gpu::adapter::candidates(&factory, &selector).into_iter().next() else { + crate::gpu::recomp::runner::skip_test("no adapter"); + return; + }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + crate::gpu::recomp::runner::skip_test("software adapter"); + return; + } + 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 D3D12 device"); + return; + }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.ResourceHeapTier.0 < 2 + || opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 + { + crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + return; + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let Some(uma) = crate::gpu::uma::get() else { + crate::gpu::recomp::runner::skip_test("no UMA"); + return; + }; + let Some(base) = uma.alloc(0x1_0000, 0x1_0000).map(|p| p as usize) else { + crate::gpu::recomp::runner::skip_test("UMA alloc failed"); + return; + }; + let d = console_desc(3, 128, 128, 1, 1, 28, 0x105); // 64 KiB + 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(dev.as_raw(), base as u64, d.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}"); + let res = ID3D12Resource::from_raw(p); + assert!(super::super::vram::is_placed_texture(res.as_raw() as usize)); + + let refresh_guard = REFRESH.lock().unwrap(); + let done = Arc::new(AtomicBool::new(false)); + let done_bg = Arc::clone(&done); + let t = std::thread::spawn(move || { + retire_overlapping(base, 0x1_0000); + done_bg.store(true, Ordering::Release); + }); + std::thread::sleep(std::time::Duration::from_millis(30)); + assert!(!done.load(Ordering::Acquire), "unmapping superseded tiles must wait while refresh holds REFRESH"); + drop(refresh_guard); + t.join().unwrap(); + assert!(done.load(Ordering::Acquire)); + drop(res); + uma.free(base); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 8a727aaf12..f3666351b0 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -117,14 +117,20 @@ pub(super) fn is_placed_texture(resource: usize) -> bool { PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } -pub(super) fn forget(resource: usize) { +/// Forget the title's placement. Returns whether a retained COM resource still owns a small slot. +pub(super) fn forget(resource: usize, held: bool) -> bool { let placed = PLACED_TEXTURES.lock().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); - if placed { + if !placed { + return false; + } + let small = super::vram_small::forget(resource, held); + if !small { forget_pages(resource); - if let Some(id) = ARENA_OF.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) { - ARENAS.lock().unwrap().release(id, std::time::Instant::now()); - } } + if let Some(id) = ARENA_OF.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) { + ARENAS.lock().unwrap().release(id, std::time::Instant::now()); + } + small && held } /// Whether a console texture with these D3D12_RESOURCE_FLAGS is the GPU's (render target, @@ -218,6 +224,65 @@ struct Target { mapped: bool, used: Vec, used_extra: Vec<(usize, usize)>, + /// its owned pages in graphics reservations (`Pages::follow`) + follows: Vec, + follow_backing: bool, + gpu_owned: bool, +} + +/// A tile that starts NULL and has no allocation in the tile pools. +const UNBACKED: Tile = (u32::MAX, 0); + +/// Title pages with sampled texture tiles waiting for backing. +struct Follow { + users: Vec<(usize, u32)>, +} + +/// Ranges of title memory that gained backing since the last submit (`title_memory_changed`): the pages there are mapped or unmapped before the next one. +static BACKING: Mutex> = Mutex::new(Vec::new()); + +fn follow_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TEXTURE_FOLLOW_BACKING").is_ok_and(|v| v.trim() == "1")) +} + +/// The title committed or mapped `[a, a + n)` of a graphics reservation: +/// deferred texture tiles there are mapped before the title's next submit (`before_execute`). +pub fn title_memory_changed(a: usize, n: usize) { + if follow_enabled() && n > 0 { + // a CPU view's change is its GPU view's too + let gpu = crate::hle::kernelx::mirrors::gpu_of(a); + let mut b = BACKING.lock().unwrap(); + b.push((a, n)); + if let Some(g) = gpu { + b.push((g, n)); + } + } +} + +/// Whether the title has memory at the 64 KiB page `a`: committed, a physical page mapped there, +/// or one mapped and not touched yet (`lazy`). In a GPU view of the title's CPU memory +/// (`kernelx::mirrors`) that is the memory of the CPU view behind it. +fn title_backed(a: usize) -> bool { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let a = crate::hle::kernelx::mirrors::source(a).unwrap_or(a); + let end = a.saturating_add(PAGE); + let mut at = a; + while at < end { + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(at as *const c_void, &mut info, std::mem::size_of_val(&info)) } == 0 { + return true; // unknown memory state: preserve backing + } + if info.State == MEM_COMMIT { + return true; + } + let next = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if next <= at { + return true; + } + at = next; + } + crate::hle::kernelx::lazy::is_lazy(a) || crate::hle::kernelx::physical_page_at(a) } /// Per-heap free-tile allocator for `Pages`. @@ -381,10 +446,12 @@ unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { + device: ID3D12Device, queue: ID3D12CommandQueue, /// signalled after each mapping; title queues wait for it before their next work fence: ID3D12Fence, value: u64, + signal_error: Option, pools: Vec, pool: TilePool, /// title page address → its video memory @@ -398,6 +465,8 @@ struct Pages { targets: std::collections::HashMap, /// queue → the fence value it last waited for waited: std::collections::HashMap, + /// title queue → marker ordered after already submitted texture accesses + queue_fences: std::collections::HashMap, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, /// reusable scratch buffers for `map()` @@ -405,6 +474,9 @@ struct Pages { scratch_flags: Vec, scratch_offsets: Vec, scratch_counts: Vec, + /// owned pages of textures in graphics reservations → their textures (`Follow`) + follow: std::collections::BTreeMap, + aliased: HashSet, } // D3D12 objects are free-threaded @@ -427,9 +499,11 @@ impl Pages { let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); Some(Pages { + device: dev.clone(), queue, fence, value: 0, + signal_error: None, pools: Vec::new(), pool: TilePool::new(), pages: std::collections::HashMap::new(), @@ -437,11 +511,14 @@ impl Pages { idle: std::collections::VecDeque::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + queue_fences: std::collections::HashMap::new(), reservable_cache: std::collections::HashMap::new(), scratch_heaps: Vec::new(), scratch_flags: Vec::new(), scratch_offsets: Vec::new(), scratch_counts: Vec::new(), + follow: std::collections::BTreeMap::new(), + aliased: HashSet::new(), }) } @@ -456,9 +533,15 @@ impl Pages { return; } self.scratch_heaps.clear(); - self.scratch_heaps.extend(tiles.iter().map(|t| t.0)); + self.scratch_heaps.extend(tiles.iter().map(|t| t.0).filter(|&h| h != UNBACKED.0)); self.scratch_heaps.sort_unstable(); self.scratch_heaps.dedup(); + if self.scratch_heaps.is_empty() { + return; + } + let queue = self.queue.as_raw() as usize; + let resource = res.as_raw() as usize; + let id = super::queue_probe::event("texture-map", queue, resource, 0, tiles.len() as u64, 0); for i in 0..self.scratch_heaps.len() { let h = self.scratch_heaps[i]; let ranges = heap_ranges_trimmed(h, tiles); @@ -491,18 +574,53 @@ impl Pages { ); } self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + let signal = self.queue.Signal(&self.fence, self.value); + let hr = signal.as_ref().err().map(|e| e.code().0); + self.signal_error = self.signal_error.or(hr.map(|hr| hr as u32)); + super::queue_probe::signal("mapping-fence", queue, &self.fence, id, self.value, hr.unwrap_or(0)); } /// 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) { + unsafe fn unmap(&mut self, res: &ID3D12Resource, total: u32) -> bool { if total == 0 { - return; + return true; + } + let mapping_queue = self.queue.as_raw() as usize; + for raw in super::present::known_queues() { + if raw == mapping_queue { + continue; + } + let raw_ptr = raw as *mut c_void; + let Some(queue) = ID3D12CommandQueue::from_raw_borrowed(&raw_ptr) else { continue }; + if !self.queue_fences.contains_key(&raw) { + let Ok(fence) = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE) else { + crate::xlog_warn!("D3D12.X: could not create texture-use fence; keeping mapping"); + return false; + }; + self.queue_fences.insert(raw, (fence, 0)); + } + let (fence, value) = self.queue_fences.get_mut(&raw).unwrap(); + *value += 1; + let signal = queue.Signal(&*fence, *value); + super::queue_probe::signal("texture-retire-title-fence", raw, fence, 0, *value, + signal.as_ref().err().map_or(0, |error| error.code().0)); + if let Err(error) = signal { + crate::xlog_warn!("D3D12.X: could not fence texture use before unmap: {error}"); + return false; + } + if let Err(error) = self.queue.Wait(&*fence, *value) { + crate::xlog_warn!("D3D12.X: could not order texture unmap after title work: {error}"); + return false; + } + super::list_x::note_internal_wait(mapping_queue, "texture unmap behind title access", fence, *value); } 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; + let queue = self.queue.as_raw() as usize; + let resource = res.as_raw() as usize; + let id = super::queue_probe::event("texture-unmap", queue, resource, 0, u64::from(total), 0); self.queue.UpdateTileMappings( res, 1, @@ -516,7 +634,11 @@ impl Pages { D3D12_TILE_MAPPING_FLAG_NONE, ); self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + let signal = self.queue.Signal(&self.fence, self.value); + let hr = signal.as_ref().err().map(|e| e.code().0); + self.signal_error = self.signal_error.or(hr.map(|hr| hr as u32)); + super::queue_probe::signal("mapping-fence", queue, &self.fence, id, self.value, hr.unwrap_or(0)); + true } fn release_tiles(&mut self, used: Vec, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) { @@ -552,78 +674,167 @@ impl Pages { } } - /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. - unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { + /// Reserve tiles for backed pages in one batch. Defer only sampled, console-owned pages + /// where the title has reserved address space without supplying memory yet. + unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, key: usize, va: usize, console_bytes: Option, total: u32, follow_backing: bool, phys: &[Option]) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); + // The title's CPU page order can differ from the PC driver's tile order. + // A texture is either fully mapped or wholly deferred, including packed mips. + let defer = follow_backing && own == total as usize && (0..own).all(|i| { + let a = first + i * PAGE; + !self.pages.get(&a).is_some_and(|p| p.users != 0) + && crate::hle::kernelx::tracks_texture_backing(a) + && !title_backed(a) + }); let mut missing = 0usize; - let mut preferred: Option = None; + let mut preferred = None; for i in 0..total as usize { + if defer { + break; + } let existing = if i < own { - self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) + self.pages.get(&page_key(first + i * PAGE, phys.get(i).copied().flatten())) } else { - self.extra_pages.get(&(va, i)).map(|p| p.tile.0) + self.extra_pages.get(&(va, i)) }; - match existing { - Some(h) if preferred.is_none() => preferred = Some(h), - Some(_) => {} - None => missing += 1, + if let Some(p) = existing { + preferred.get_or_insert(p.tile.0); + } else { + missing += 1; } } - let pools = &mut self.pools; - let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, now, POOL_PAGES, || { - let heap = alloc_pool_heap(dev)?; - pools.push(heap); - Some(pools.len() as u32 - 1) - })?; - let mut fresh_iter = fresh.into_iter(); - + let mut fresh = self.take_tiles(dev, missing, preferred, now)?.into_iter(); let mut tiles = Vec::with_capacity(total as usize); let mut used = Vec::with_capacity(own); let mut used_extra = Vec::new(); + let mut follows = Vec::new(); for i in 0..total as usize { let tile = if i < own { let a = first + i * PAGE; - let t = match self.pages.get_mut(&a) { - Some(p) => { - p.users += 1; - p.idle_since = None; - p.tile - } - None => { - let t = fresh_iter.next().unwrap(); - self.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); - t - } - }; - used.push(a); - t + if defer { + follows.push(a); + self.follow.entry(a).or_insert_with(|| Follow { users: Vec::new() }).users.push((key, i as u32)); + tiles.push(UNBACKED); + continue; + } + let backing_key = page_key(a, phys.get(i).copied().flatten()); + let p = self.pages.entry(backing_key).or_insert_with(|| Page { tile: fresh.next().unwrap(), users: 0, idle_since: None }); + p.users += 1; + p.idle_since = None; + used.push(backing_key); + if self.follow.contains_key(&a) { + self.aliased.insert(a); + } + p.tile } else { let k = (va, i); - let t = match self.extra_pages.get_mut(&k) { - Some(p) => { - p.users += 1; - p.idle_since = None; - p.tile - } - None => { - let t = fresh_iter.next().unwrap(); - self.extra_pages.insert(k, Page { tile: t, users: 1, idle_since: None }); - t - } - }; + let p = self.extra_pages.entry(k).or_insert_with(|| Page { tile: fresh.next().unwrap(), users: 0, idle_since: None }); + p.users += 1; + p.idle_since = None; used_extra.push(k); - t + p.tile }; tiles.push(tile); } + debug_assert!(fresh.next().is_none()); self.map(res, &tiles); - Some((used, used_extra)) + Some((used, used_extra, follows)) } + + unsafe fn take_tiles(&mut self, dev: &ID3D12Device, count: usize, preferred: Option, now: std::time::Instant) -> Option> { + let pools = &mut self.pools; + self.pool.take_batch(count, preferred, now, POOL_PAGES, || { + let heap = alloc_pool_heap(dev)?; + pools.push(heap); + Some(pools.len() as u32 - 1) + }) + } + + /// Texture `key` no longer at its followed pages `addrs`. + fn unfollow(&mut self, key: usize, addrs: &[usize]) { + for a in addrs { + if let Some(f) = self.follow.get_mut(a) { + f.users.retain(|u| u.0 != key); + if f.users.is_empty() { + self.follow.remove(a); + self.aliased.remove(a); + } + } + } + } + + /// Map newly backed pages. Once mapped, a tile stays live until the texture is retired. + /// CPU decommit alone does not prove that older GPU submissions stopped using the tile. + unsafe fn apply_backing(&mut self, dev: &ID3D12Device, ranges: &[(usize, usize)], force: &[usize]) -> Result, u32> { + let mut ready = std::mem::take(&mut self.aliased); + ready.retain(|a| self.pages.get(a).is_some_and(|p| p.users != 0)); + ready.extend(force.iter().copied().filter(|a| self.follow.contains_key(a))); + for &(a, n) in ranges { + let start = a & !(PAGE - 1); + ready.extend(self.follow.range(start..a.saturating_add(n)) + .filter_map(|(&p, _)| title_backed(p).then_some(p))); + } + if ready.is_empty() { + return Ok(Vec::new()); + } + // One backed page activates the texture's full PC mapping. A shared page + // also activates each deferred alias that uses it, transitively. + let mut pending: Vec<_> = ready.iter().copied().collect(); + let mut activating = HashSet::new(); + while let Some(a) = pending.pop() { + if let Some(follow) = self.follow.get(&a) { + for &(key, _) in &follow.users { + if activating.insert(key) { + if let Some(target) = self.targets.get(&key) { + for &tile_addr in &target.follows { + if ready.insert(tile_addr) { + pending.push(tile_addr); + } + } + } + } + } + } + } + let now = std::time::Instant::now(); + self.sweep(now); + let mut ready: Vec = ready.into_iter().collect(); + ready.sort_unstable(); + let missing = ready.iter().filter(|a| !self.pages.contains_key(a)).count(); + let preferred = ready.iter().find_map(|a| self.pages.get(a).map(|p| p.tile.0)); + let mut fresh = self.take_tiles(dev, missing, preferred, now).ok_or(0x8007_000Eu32)?.into_iter(); + + let mut changes: std::collections::HashMap> = std::collections::HashMap::new(); + for a in ready { + let Some(pending) = self.follow.remove(&a) else { continue }; + let p = self.pages.entry(a).or_insert_with(|| Page { tile: fresh.next().unwrap(), users: 0, idle_since: None }); + p.idle_since = None; + for (key, index) in pending.users { + let Some(target) = self.targets.get_mut(&key) else { continue }; + target.used.push(a); + p.users += 1; + changes.entry(key).or_default().push((index as usize, p.tile)); + } + } + debug_assert!(fresh.next().is_none()); + let mut mapped = Vec::with_capacity(changes.len()); + for (key, tiles) in changes { + let raw = key as *mut c_void; + let Some(res) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; + let mut batch = vec![UNBACKED; self.targets[&key].total as usize]; + for (index, tile) in tiles { + batch[index] = tile; + } + self.map(res, &batch); + mapped.push(key); + } + Ok(mapped) + } + } /// The ranges of one UpdateTileMappings call for pool heap `heap` over a resource whose overall @@ -694,6 +905,30 @@ unsafe fn reservable(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> bool { can_reserve(f.Support2.0, samples, m.NumQualityLevels) } +/// Keys of `Pages::pages` for the title's physical pages (title addresses never have bit 63). +const PHYS_KEY: usize = 1 << 63; + +/// The key of the page of video memory for title page address `a`: the physical page mapped +/// there (`phys`), else the address. A retail game maps one physical page under render targets +/// at two addresses (aliasing, as on the console): keyed by address, each got video memory of +/// its own (1.85 GB more in its first 40 s) and what the GPU wrote through one never showed in +/// the other. +fn page_key(a: usize, phys: Option) -> usize { + phys.map_or(a, |p| PHYS_KEY | p) +} + +/// The physical pages under a GPU-owned texture's owned pages (`require_aligned`), asked before +/// `PAGES` is taken; empty for others (keyed by address) and without the console size. +fn physical_pages_under(va: usize, console_bytes: Option, require_aligned: bool) -> Vec> { + if !require_aligned { + return Vec::new(); + } + match console_bytes.and_then(|b| owned_pages(va, Some(b), usize::MAX)) { + Some((first, n)) if n > 0 => crate::hle::kernelx::physical_pages(first, n), + _ => Vec::new(), + } +} + /// A texture at `va` as a reserved resource on the title's shared 64 KiB pages /// (`console_bytes`: its size on the console; tiles past the owned page boundaries are shared by /// `(va, tile_index)` so repeated placements at the same address do not leak). None: it cannot be. @@ -716,6 +951,7 @@ unsafe fn place_on_pages( if (require_aligned || console_bytes.is_none()) && va % PAGE != 0 { return None; } + let phys = physical_pages_under(va, console_bytes, require_aligned); // reserved textures have the PC's 64 KiB tiles let tiled = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*desc }; static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -748,8 +984,9 @@ unsafe fn place_on_pages( let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { - if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); + let follow_backing = follow_enabled() && !require_aligned; + if let Some((used, used_extra, follows)) = pages.bind(dev, res, raw as usize, va, console_bytes, total, follow_backing, &phys) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, follows, follow_backing, gpu_owned: require_aligned }); true } else { false @@ -774,16 +1011,17 @@ pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { let mut g = PAGES.lock().unwrap(); let now = std::time::Instant::now(); for pages in g.values_mut().flatten() { - let Some(t) = pages.targets.get_mut(&key) else { continue }; - if !t.mapped { + let Some(t) = pages.targets.get(&key) else { continue }; + if !t.mapped || !pages.unmap(res, t.total) { return; } - let total = t.total; + let t = pages.targets.get_mut(&key).unwrap(); let used = std::mem::take(&mut t.used); let used_extra = std::mem::take(&mut t.used_extra); + let follows = std::mem::take(&mut t.follows); t.mapped = false; - pages.unmap(res, total); pages.release_tiles(used, used_extra, now, true); + pages.unfollow(key, &follows); return; } } @@ -796,25 +1034,43 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { } let Some(dev) = dev else { return false }; let key = res.as_raw() as usize; - let mut g = PAGES.lock().unwrap(); - let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; - let Some((va, console_bytes, total, mapped)) = pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped)) else { - return false; + let dev_key = dev.as_raw() as usize; + let (va, console_bytes, gpu_owned) = { + let g = PAGES.lock().unwrap(); + let Some(target) = g.get(&dev_key).and_then(Option::as_ref).and_then(|p| p.targets.get(&key)) else { return false }; + if target.mapped { + return true; + } + (target.va, target.console_bytes, target.gpu_owned) }; - if mapped { + // The physical-page table can be locked by a CPU mapping update, so query it outside PAGES. + let phys = physical_pages_under(va, console_bytes, gpu_owned); + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { return false }; + let Some(target) = pages.targets.get(&key) else { return false }; + if target.mapped { return true; } - let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { + let Some((used, used_extra, follows)) = pages.bind(&dev, res, key, va, console_bytes, target.total, target.follow_backing, &phys) else { return false; }; if let Some(t) = pages.targets.get_mut(&key) { t.used = used; t.used_extra = used_extra; + t.follows = follows; t.mapped = true; } true } +/// Pool tiles that are neither free, cooling, nor owned by a page. +#[cfg(test)] +pub(super) fn tiles_unaccounted_for(device: usize) -> usize { + let g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get(&device) else { return 0 }; + (p.pools.len() * POOL_PAGES as usize).saturating_sub(p.pool.free_total + p.pool.cooling.len() + p.pages.len() + p.extra_pages.len()) +} + /// A resource released: its pages are no longer its. fn forget_pages(resource: usize) { let mut g = PAGES.lock().unwrap(); @@ -824,42 +1080,157 @@ fn forget_pages(resource: usize) { if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); } + pages.unfollow(resource, &t.follows); return; } } -/// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device. -pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { +/// Make the current texture tile mapping visible to a queue before it can execute. +unsafe fn prepare_queue(queue: &ID3D12CommandQueue) -> Result, u32> { let mut dev: Option = None; if queue.GetDevice(&mut dev).is_err() { - return; + return Ok(Vec::new()); } - let Some(dev) = dev else { return }; + let Some(dev) = dev else { return Ok(Vec::new()) }; let mut g = PAGES.lock().unwrap(); - let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return }; + let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return Ok(Vec::new()) }; + let mapped = if follow_enabled() { + let changed = std::mem::take(&mut *BACKING.lock().unwrap()); + let mapped = pages.apply_backing(&dev, &changed, &[])?; + if let Some(hr) = pages.signal_error { + return Err(hr); + } + mapped + } else { + Vec::new() + }; let key = queue.as_raw() as usize; if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { - let _ = queue.Wait(&pages.fence, pages.value); + let wait = queue.Wait(&pages.fence, pages.value); + if follow_enabled() { + wait.map_err(|e| e.code().0 as u32)?; + } super::list_x::note_internal_wait(key, "texture page mappings", &pages.fence, pages.value); pages.waited.insert(key, pages.value); } + Ok(mapped) +} + +fn mapping_failed(hr: u32) -> ! { + super::real::log_device_removed(); + let message = format!("D3D12.X: required texture backing or queue synchronization failed ({hr:#010x})"); + crate::xlog_error!("{message}"); + crate::report::write_final(Some(message)); + crate::log::flush(); + std::process::exit(hr as i32); +} + +pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { + match prepare_queue(queue) { + Ok(mapped) => super::title_textures::backing_added(&mapped), + Err(hr) => mapping_failed(hr), + } +} + +/// A texture copy can write tiles that have no CPU backing. Map them before the copy is submitted. +pub(super) fn prepare_gpu_write(resource: usize) { + if !follow_enabled() { + return; + } + let result = (|| unsafe { + let mut g = PAGES.lock().unwrap(); + for (&key, pages) in g.iter_mut().filter_map(|(key, pages)| pages.as_mut().map(|p| (key, p))) { + let Some(target) = pages.targets.get(&resource).filter(|t| t.mapped && !t.follows.is_empty()) else { continue }; + let raw = key as *mut c_void; + let Some(dev) = ID3D12Device::from_raw_borrowed(&raw) else { continue }; + let addresses = target.follows.clone(); + pages.targets.get_mut(&resource).unwrap().follow_backing = false; + return pages.apply_backing(dev, &[], &addresses); + } + Ok(Vec::new()) + })(); + match result { + Ok(mapped) => super::title_textures::backing_added(&mapped), + Err(hr) => mapping_failed(hr), + } } #[cfg(test)] pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); +/// Whether `va` already has a live (or still within `IDLE`) 64 KiB page on `device` (e.g., an +/// existing GPU-owned render target that a sampled view at the same 64 KiB-aligned address should +/// alias). +fn has_live_page(device: usize, va: usize) -> bool { + let g = PAGES.lock().unwrap(); + let now = std::time::Instant::now(); + g.get(&device) + .and_then(|p| p.as_ref()) + .is_some_and(|p| p.pages.get(&va).is_some_and(|pg| pg.idle_since.is_none_or(|s| now.duration_since(s) < IDLE))) +} + #[cfg(test)] -pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { +pub(super) fn deferred_tiles_for(resource: usize) -> usize { let g = PAGES.lock().unwrap(); - let Some(Some(p)) = g.get(&device) else { return (0, 0) }; - ((p.pages.len() + p.extra_pages.len()) * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) + g.values().flatten().find_map(|p| p.targets.get(&resource).map(|target| { + target.follows.iter().filter(|a| p.follow.get(a).is_some_and(|f| f.users.iter().any(|&(r, _)| r == resource))).count() + })).unwrap_or(0) +} + +#[cfg(test)] +pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { + let (su, sp) = super::vram_small::bytes_for(device); + let mut g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get_mut(&device) else { return (su, sp) }; + p.sweep(std::time::Instant::now()); + ((p.pages.len() + p.extra_pages.len()) * PAGE + su, p.pools.len() * POOL_PAGES as usize * PAGE + sp) +} + +#[cfg(test)] +pub(super) fn extra_page_bytes_for(device: usize) -> usize { + let mut g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get_mut(&device) else { return 0 }; + p.sweep(std::time::Instant::now()); + p.extra_pages.len() * PAGE +} + +/// Immediately evict all unreferenced idle pages and small-pool slots on `device` so GPU tests +/// sharing the process's singleton `ID3D12Device` do not observe stale `IDLE` expiries mid-test. +#[cfg(test)] +pub(super) fn flush_idle_for(device: usize) { + super::vram_small::flush_idle_for(device); + let mut g = PAGES.lock().unwrap(); + if let Some(Some(p)) = g.get_mut(&device) { + let now = std::time::Instant::now(); + while let Some((key, since)) = p.idle.pop_front() { + let still_idle = |pg: &Page| pg.idle_since == Some(since); + let page = match key { + PageKey::Own(a) if p.pages.get(&a).is_some_and(still_idle) => p.pages.remove(&a), + PageKey::Extra(va, i) if p.extra_pages.get(&(va, i)).is_some_and(still_idle) => p.extra_pages.remove(&(va, i)), + _ => None, + }; + if let Some(pg) = page { + p.pool.push_cooling(pg.tile, now); + } + } + } } -/// (bytes of pages in use by tiled textures, bytes of pool heaps) – `XCL_ACTIVITY` -pub fn page_bytes() -> (usize, usize) { +/// (bytes in assigned small-texture slots, bytes in small-texture heaps). +pub fn small_texture_backing_bytes() -> (usize, usize) { + super::vram_small::bytes() +} + +/// Backed texture bytes, pool heap bytes and deferred unique title-page bytes – `XCL_ACTIVITY` +pub fn page_bytes() -> (usize, usize, usize) { + let (su, sp) = super::vram_small::bytes(); let g = PAGES.lock().unwrap(); - g.values().flatten().fold((0, 0), |(used, pools), p| { - (used + (p.pages.len() + p.extra_pages.len()) * PAGE, pools + p.pools.len() * POOL_PAGES as usize * PAGE) + g.values().flatten().fold((su, sp, 0), |(used, pools, deferred), p| { + ( + used + (p.pages.len() + p.extra_pages.len()) * PAGE, + pools + p.pools.len() * POOL_PAGES as usize * PAGE, + deferred + p.follow.len() * PAGE, + ) }) } @@ -870,8 +1241,9 @@ fn tier2(dev: &ID3D12Device) -> bool { } /// A sampled texture of the title at `va` (`desc`: the PC description, `console_bytes` its size on -/// the console) backed by shared 64 KiB video-memory pages; None when reserved placement is not -/// available (the caller falls back to a committed resource). +/// the console) backed by shared 4 KiB small-resource heaps (when < 64 KiB and not aliasing an +/// existing 64 KiB GPU page) or shared 64 KiB video-memory pages; None when neither applies (the +/// caller falls back to a committed resource). #[allow(clippy::too_many_arguments)] pub unsafe fn place_pages( this: *mut c_void, @@ -890,6 +1262,12 @@ pub unsafe fn place_pages( if console_has_packed_3d_mips(desc) { return None; } + if !(va % PAGE == 0 && has_live_page(dev.as_raw() as usize, va)) { + if let Some(hr) = super::vram_small::place(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { + PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + return Some(hr); + } + } place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, riid, ppv) } @@ -1114,6 +1492,13 @@ mod tests { assert_eq!(pages.len(), 199_998); } + #[test] + fn deferred_tiles_are_skipped_in_contiguous_heap_ranges() { + let tiles = [UNBACKED, (0, 7), (0, 8), UNBACKED, (1, 0), UNBACKED]; + assert_eq!(heap_ranges_trimmed(0, &tiles), [(false, 0, 1), (true, 7, 2)]); + assert_eq!(heap_ranges_trimmed(1, &tiles), [(false, 0, 4), (true, 0, 1)]); + } + /// Any 64 KiB page boundary inside `[va, va + bytes)` belongs to that range alone, so /// non-overlapping ranges never share an owned page even when only 4 KiB aligned. #[test] @@ -1258,6 +1643,96 @@ mod tests { assert!(late <= early, "arenas grow over time: {early} then {late} bytes"); } + /// A title queue held behind a fence must keep a superseded texture mapped until its queued + /// work passes the queue marker. The mapping queue must then complete the unmap afterwards. + #[test] + fn superseded_texture_unmap_waits_for_title_queue_work() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap(); + use crate::gpu::fence::{self, FenceError}; + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let selector = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &selector).into_iter().next() else { + crate::gpu::recomp::runner::skip_test("no selected GPU"); + return; + }; + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev.filter(|d| tier2(d)) else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + eprintln!("texture retirement GPU: {}", crate::gpu::adapter::name(&desc)); + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let mut raw = std::ptr::null_mut(); + let hr = place(dev.as_raw(), 0x6A00_0000_0000, &desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(64 * 64 * 4), riid, &mut raw); + if hr.is_none_or(|hr| hr < 0) || raw.is_null() { + crate::gpu::recomp::runner::skip_test("reserved texture unavailable"); + return; + } + let resource = ID3D12Resource::from_raw(raw); + if !is_placed_texture(raw as usize) { + drop(resource); + forget(raw as usize, false); + crate::gpu::recomp::runner::skip_test("reserved texture unavailable"); + return; + } + + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let transition = D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&resource), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_COMMON, + StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + }; + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(transition) }, + ..Default::default() + }]); + list.Close().unwrap(); + super::super::present::remember_queue(queue.as_raw()); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + + unmap_superseded(&resource); + let key = dev.as_raw() as usize; + let (completion, unmap_value, mapped) = { + let g = PAGES.lock().unwrap(); + let pages = g.get(&key).and_then(Option::as_ref).unwrap(); + (pages.fence.clone(), pages.value, pages.targets[&(raw as usize)].mapped) + }; + let held = fence::wait(&completion, unmap_value, &dev, None, 100); + gate.Signal(1).unwrap(); + fence::wait(&completion, unmap_value, &dev, None, 5000).expect("unmap completed after title queue work"); + assert!(!mapped, "unmap was queued"); + assert!(matches!(held, Err(FenceError::Timeout(_))), "unmap completed before the title queue marker"); + drop(resource); + forget(raw as usize, false); + } + } + /// On the GPU: D32S8 targets 256 MiB apart take their own size of video memory, not an arena /// of 256 MiB each; depth and stencil survive a clear, CopyResource and a read of both planes; /// arenas no target uses go. Needs a hardware adapter (skips on WARP). diff --git a/crates/xcl/src/hle/d3d12x/vram_small.rs b/crates/xcl/src/hle/d3d12x/vram_small.rs new file mode 100644 index 0000000000..25c11f88fe --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/vram_small.rs @@ -0,0 +1,574 @@ +//! 4 KiB sub-allocated default heaps for small (< 64 KiB) sampled textures. +//! +//! A console title packs thousands of small mip-tails, icons, decals and LUTs at 256 B – 4 KiB +//! offsets inside its texture pools. Backing each one with a 64 KiB reserved resource in +//! `vram::Pages` wastes up to 16× video memory (one full 64 KiB `extra_pages` tile per small +//! texture) and submits a `CreateReservedResource` + `GetResourceTiling` + `UpdateTileMappings` +//! round trip for every placement. +//! +//! Direct3D 12 supports 4 KiB placement (`D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT`) for +//! single-sample non-RT/DS textures whose allocation info fits under 64 KiB. Placing those in +//! shared 16 MiB default heaps packs up to 4 096 textures into one heap with zero tile mappings, +//! shares the exact `(heap, offset)` across repeated placements at the same `(va, size)` so +//! same-address aliases see each other's uploads, and recycles released blocks by size class +//! after `IDLE` + `COOL`. `XCL_VRAM_SMALL=0` disables this path. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::util::HRESULT; + +/// Allocation unit: 4 KiB (`D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT`). +const UNIT: usize = 0x1000; +/// Largest small-resource size handled here: 60 KiB (`15 * 4 KiB < 64 KiB`). +const MAX_UNITS: u32 = 15; +/// Units per shared default heap: 16 MiB (`4096 * 4 KiB`). +const POOL_UNITS: u32 = 4096; +/// Keep an unreferenced `(va, units)` slot this long so immediate re-placements reuse it. +const IDLE: Duration = Duration::from_secs(2); +/// Wait before reusing a freed block for a different address (in-flight GPU work). +const COOL: Duration = Duration::from_secs(2); + +/// Key identifying a shared small-texture backing slot: `(title_va, size_in_4k_units)`. +type SlotKey = (usize, u32); + +/// Block location inside a device's small pools: `(pool_index, offset_in_4k_units, size_in_4k_units)`. +type Block = (u32, u32, u32); + +struct Pool { + heap: H, + /// Bump pointer in 4 KiB units (`0..=POOL_UNITS`). + next_unit: u32, +} + +struct Slot { + pool: u32, + offset: u32, + users: u32, + idle_since: Option, +} + +struct SmallPools { + pools: Vec>, + /// Per-size-class (`1..=MAX_UNITS`) reusable blocks `(pool, offset)`. + free: [Vec<(u32, u32)>; (MAX_UNITS as usize) + 1], + /// Blocks given back, reusable after `COOL`. + cooling: VecDeque<(Block, Instant)>, + /// Live or idle-kept `(va, units)` → backing block. + slots: HashMap, + /// Idle slots, oldest first (`sweep_idle`). + idle: VecDeque<(SlotKey, Instant)>, + /// Live resource raw pointer → `(va, units)`. + resources: HashMap, + /// Total 4 KiB units currently held by `slots` (live + idle-kept). + used_units: usize, +} + +impl SmallPools { + fn new() -> Self { + SmallPools { + pools: Vec::new(), + free: std::array::from_fn(|_| Vec::new()), + cooling: VecDeque::new(), + slots: HashMap::new(), + idle: VecDeque::new(), + resources: HashMap::new(), + used_units: 0, + } + } + + fn sweep_idle(&mut self, now: Instant) { + while self.idle.front().is_some_and(|&(_, since)| now.duration_since(since) >= IDLE) { + let Some((key, since)) = self.idle.pop_front() else { break }; + if self.slots.get(&key).is_some_and(|s| s.idle_since == Some(since)) { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.cooling.push_back(((s.pool, s.offset, key.1), now)); + } + } + } + } + + fn drain_cooling(&mut self, now: Instant) { + while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + if let Some(((pool, offset, units), _)) = self.cooling.pop_front() { + self.free[units as usize].push((pool, offset)); + } + } + } + + /// Try to acquire an existing shared slot for `(va, units)` or allocate a block from existing + /// pools / free lists without creating a new D3D12 heap. + fn try_acquire(&mut self, key: SlotKey, now: Instant) -> Option<(H, u32)> { + self.sweep_idle(now); + if let Some(s) = self.slots.get_mut(&key) { + s.users += 1; + s.idle_since = None; + return Some((self.pools[s.pool as usize].heap.clone(), s.offset)); + } + let units = key.1; + debug_assert!((1..=MAX_UNITS).contains(&units)); + self.drain_cooling(now); + let (pool, offset) = if let Some(b) = self.free[units as usize].pop() { + b + } else if let Some((idx, p)) = self.pools.iter_mut().enumerate().rev().find(|(_, p)| p.next_unit + units <= POOL_UNITS) { + let off = p.next_unit; + p.next_unit += units; + (idx as u32, off) + } else { + return None; + }; + let heap = self.pools[pool as usize].heap.clone(); + self.slots.insert(key, Slot { pool, offset, users: 1, idle_since: None }); + self.used_units += units as usize; + Some((heap, offset)) + } + + /// Register a newly created pool heap and acquire `(va, units)`. + /// Re-checks `try_acquire` first under the lock so two threads racing to create a new 16 MiB + /// pool do not push a redundant empty heap (the extra `heap` drops cleanly if another thread + /// already added room or created the same slot). + fn add_pool_and_acquire(&mut self, heap: H, key: SlotKey, now: Instant) -> (H, u32) { + if let Some(got) = self.try_acquire(key, now) { + return got; + } + let pool_idx = self.pools.len() as u32; + self.pools.push(Pool { heap, next_unit: 0 }); + if let Some(got) = self.try_acquire(key, now) { + return got; + } + // `pool_idx` has `next_unit == 0` and `units <= MAX_UNITS < POOL_UNITS`, so `try_acquire` + // above always succeeds. + unreachable!("fresh pool {pool_idx} must fit {} units", key.1); + } + + fn note_resource(&mut self, res: usize, key: SlotKey) { + self.resources.insert(res, key); + } + + /// Release one user of `key`. When `rollback` is true (creation failed before the GPU ever saw + /// the resource), the block returns directly to `free` if this was its only user. + fn release_key(&mut self, key: SlotKey, now: Instant, rollback: bool) { + let Some(s) = self.slots.get_mut(&key) else { return }; + s.users = s.users.saturating_sub(1); + if s.users == 0 { + if rollback { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.free[key.1 as usize].push((s.pool, s.offset)); + } + } else { + s.idle_since = Some(now); + self.idle.push_back((key, now)); + } + } + } + + fn forget(&mut self, res: usize, now: Instant) -> bool { + let Some(key) = self.resources.remove(&res) else { + return false; + }; + self.release_key(key, now, false); + true + } + + fn bytes(&self) -> (usize, usize) { + (self.used_units * UNIT, self.pools.len() * POOL_UNITS as usize * UNIT) + } + + #[cfg(test)] + fn flush_idle(&mut self, now: Instant) { + while let Some((key, since)) = self.idle.pop_front() { + if self.slots.get(&key).is_some_and(|s| s.idle_since == Some(since)) { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.cooling.push_back(((s.pool, s.offset, key.1), now)); + } + } + } + } +} + +// D3D12 heaps are free-threaded. +unsafe impl Send for SmallPools {} + +static SMALL_POOLS: Mutex>> = Mutex::new(BTreeMap::new()); + +fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_VRAM_SMALL").map_or(true, |v| v.trim() != "0")) +} + +/// Whether `desc` and `console_bytes` are eligible for 4 KiB small-resource sub-allocation. +fn candidate(desc: &D3D12_RESOURCE_DESC, console_bytes: Option) -> bool { + const PAGE: u64 = 0x1_0000; + desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN + && desc.SampleDesc.Count <= 1 + && desc.Flags.0 & 0x7 == 0 + && matches!(desc.Dimension, D3D12_RESOURCE_DIMENSION_TEXTURE2D | D3D12_RESOURCE_DIMENSION_TEXTURE3D) + && console_bytes.is_some_and(|b| b > 0 && b < PAGE) +} + +/// Place a sub-64 KiB sampled texture at 4 KiB granularity in a shared default heap. +/// Returns `None` if the texture is not a small resource (the caller falls back to `vram::Pages` +/// or a committed resource). +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn place( + dev: &ID3D12Device, + this: *mut c_void, + va: usize, + desc: &D3D12_RESOURCE_DESC, + state: u32, + clear: *const c_void, + console_bytes: Option, + riid: *const windows_sys::core::GUID, + ppv: *mut *mut c_void, +) -> Option { + if !enabled() || !candidate(desc, console_bytes) { + return None; + } + let small_desc = D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..*desc }; + let info = dev.GetResourceAllocationInfo(0, &[small_desc]); + if info.SizeInBytes == u64::MAX || info.SizeInBytes == 0 || info.Alignment != UNIT as u64 || info.SizeInBytes >= 0x1_0000 { + return None; + } + let units = (info.SizeInBytes as usize).div_ceil(UNIT) as u32; + if !(1..=MAX_UNITS).contains(&units) { + return None; + } + let dev_key = dev.as_raw() as usize; + let key = (va, units); + let now = Instant::now(); + + let (heap, offset_units) = { + let mut g = SMALL_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(SmallPools::new); + pools.try_acquire(key, now) + } + .or_else(|| { + // Create a new 16 MiB default heap outside `SMALL_POOLS.lock()`. + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_UNITS as u64 * UNIT as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + // 64 KiB heap alignment is valid for 4 KiB-aligned small resources at any 4 KiB offset. + Alignment: D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut new_heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&heap_desc, &mut new_heap)) { + crate::xlog_warn!("D3D12.X: small texture pool CreateHeap: {e}"); + return None; + } + let new_heap = new_heap?; + let mut g = SMALL_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(SmallPools::new); + Some(pools.add_pool_and_acquire(new_heap, key, Instant::now())) + })?; + + let hr = super::real::dev_create_placed_resource( + this, + heap.as_raw() as usize, + offset_units as usize * UNIT, + &small_desc as *const _ as usize, + state as usize, + clear as usize, + riid, + ppv, + ); + if hr < 0 || (*ppv).is_null() { + let mut g = SMALL_POOLS.lock().unwrap(); + if let Some(pools) = g.get_mut(&dev_key) { + pools.release_key(key, Instant::now(), true); + } + return None; + } + let raw = *ppv as usize; + SMALL_POOLS.lock().unwrap().entry(dev_key).or_insert_with(SmallPools::new).note_resource(raw, key); + Some(hr) +} + +/// Returns whether the resource belongs to a small pool. A fence-held COM reference +/// also keeps its slot assigned until late release, even when the CPU idle period passes. +pub(super) fn forget(resource: usize, held: bool) -> bool { + let mut g = SMALL_POOLS.lock().unwrap(); + if held { + return g.values().any(|pools| pools.resources.contains_key(&resource)); + } + let now = Instant::now(); + for pools in g.values_mut() { + if pools.forget(resource, now) { + return true; + } + } + false +} + +/// `(used_bytes, pool_bytes)` across all devices. +pub(super) fn bytes() -> (usize, usize) { + let g = SMALL_POOLS.lock().unwrap(); + g.values().fold((0, 0), |(used, pools), p| { + let (u, t) = p.bytes(); + (used + u, pools + t) + }) +} + +#[cfg(test)] +pub(super) fn bytes_for(device: usize) -> (usize, usize) { + let mut g = SMALL_POOLS.lock().unwrap(); + let Some(p) = g.get_mut(&device) else { return (0, 0) }; + p.sweep_idle(Instant::now()); + p.bytes() +} + +#[cfg(test)] +pub(super) fn flush_idle_for(device: usize) { + let mut g = SMALL_POOLS.lock().unwrap(); + if let Some(p) = g.get_mut(&device) { + p.flush_idle(Instant::now()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn small_pool_packs_shares_and_recycles_by_size_class() { + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + let mut p: SmallPools = SmallPools::new(); + let alloc = |p: &mut SmallPools, va: usize, units: u32, res: usize, now: Instant| -> (u32, u32) { + let got = p.try_acquire((va, units), now).unwrap_or_else(|| { + let id = p.pools.len() as u32; + p.add_pool_and_acquire(id, (va, units), now) + }); + p.note_resource(res, (va, units)); + got + }; + + // Sixteen 4 KiB textures pack into 64 KiB (not 16 * 64 KiB = 1 MiB). + for i in 0..16usize { + let (h, off) = alloc(&mut p, 0x10_0000 + i * UNIT, 1, 100 + i, at(0)); + assert_eq!((h, off), (0, i as u32)); + } + assert_eq!(p.bytes(), (16 * UNIT, POOL_UNITS as usize * UNIT)); + + // Re-placing the exact same (va, units) shares the exact same (heap, offset) with zero growth. + let (h_dup, off_dup) = alloc(&mut p, 0x10_4000, 1, 200, at(10)); + assert_eq!((h_dup, off_dup), (0, 4)); + assert_eq!(p.bytes().0, 16 * UNIT); + + // Releasing one of the two aliases keeps the slot alive; releasing both makes it idle. + assert!(p.forget(200, at(20))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 1); + assert!(p.forget(104, at(30))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 0); + + // Re-acquiring within IDLE reuses the exact same slot. + let (h_re, off_re) = alloc(&mut p, 0x10_4000, 1, 201, at(1000)); + assert_eq!((h_re, off_re), (0, 4)); + assert!(p.forget(201, at(1100))); + + // After IDLE (2 s) + COOL (2 s), the 4 KiB block is recycled for a new address. + let (h_wait, off_wait) = alloc(&mut p, 0x20_0000, 1, 202, at(3200)); + assert_eq!((h_wait, off_wait), (0, 16), "still cooling at +2.1s, must not reuse yet"); + let (h_rec, off_rec) = alloc(&mut p, 0x20_1000, 1, 203, at(5300)); + assert_eq!((h_rec, off_rec), (0, 4), "block (0, 4) recycled after IDLE + COOL"); + + // Rollback on creation failure immediately returns the block to the free list. + let (h_fail, off_fail) = p.try_acquire((0x30_0000, 4), at(5400)).unwrap(); + assert_eq!((h_fail, off_fail), (0, 17)); + p.release_key((0x30_0000, 4), at(5400), true); + let (h_next, off_next) = alloc(&mut p, 0x30_4000, 4, 204, at(5400)); + assert_eq!((h_next, off_next), (0, 17)); + + // Concurrent CreateHeap race: if room already exists in pool 0, `add_pool_and_acquire` + // must reuse existing room instead of pushing a redundant empty 16 MiB pool. + let pools_before = p.pools.len(); + let (h_raced, _) = p.add_pool_and_acquire(999, (0x40_0000, 1), at(5500)); + assert_eq!(h_raced, 0); + assert_eq!(p.pools.len(), pools_before, "must not push redundant pool when room already exists"); + + // `flush_idle` clears unreferenced idle slots while keeping live (`users > 0`) slots intact. + let used_before_flush = p.bytes().0; + let _ = alloc(&mut p, 0x50_0000, 2, 205, at(5600)); + assert!(p.forget(205, at(5610))); + assert_eq!(p.bytes().0, used_before_flush + 2 * UNIT); + p.flush_idle(at(5620)); + assert_eq!(p.bytes().0, used_before_flush, "flush_idle must reclaim unreferenced slots immediately"); + } + + #[test] + fn candidate_filters_large_gpu_owned_and_msaa_textures() { + let mut d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(candidate(&d, Some(16 * 1024))); + assert!(!candidate(&d, Some(64 * 1024)), "64 KiB stays on vram::Pages"); + assert!(!candidate(&d, None)); + assert!(!candidate(&d, Some(0))); + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + assert!(!candidate(&d, Some(16 * 1024))); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + d.SampleDesc.Count = 4; + assert!(!candidate(&d, Some(16 * 1024))); + d.SampleDesc.Count = 1; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + assert!(!candidate(&d, Some(16 * 1024))); + } + + /// On the GPU: 512 small 4 KiB (64x64 BC1) and 16 KiB (64x64 RGBA8) sampled textures pack at + /// 4 KiB granularity inside a single 16 MiB heap (16x and 4x smaller than 64 KiB tiles), + /// same-address placements alias their pixels on hardware, adjacent 4 KiB textures have zero + /// crosstalk, and a small sampled texture over an existing 64 KiB GPU target falls back to + /// `vram::Pages` so target aliasing is preserved. + #[test] + fn gpu_small_textures_pack_at_4k_granularity_and_preserve_pixels() { + let _vram_guard = super::super::vram::VRAM_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::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory1().expect("DXGI factory"); + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let mut dev: Option = None; + for (adapter, _) in crate::gpu::adapter::candidates(&factory, &sel) { + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() && dev.is_some() { + break; + } + } + let Some(dev) = dev else { return }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + + let desc_of = |w: u64, h: u32, fmt: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: fmt, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + ..Default::default() + }; + let place_sampled = |va: usize, d: &D3D12_RESOURCE_DESC, cbytes: u64| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::vram::place_pages(dev.as_raw(), va, d, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(cbytes), riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "place_pages at {va:#x} failed: {hr:x?}"); + assert!(super::super::vram::is_placed_texture(p as usize)); + ID3D12Resource::from_raw(p) + }; + + // 1. 512 x 64x64 BC1 (2 KiB on console -> 4 KiB small resource on PC): must pack into + // 2 MiB (16x smaller than 512 x 64 KiB = 32 MiB!) inside a single 16 MiB heap. + super::super::vram::flush_idle_for(dev_key); + let bc1 = desc_of(64, 64, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE); + let (small0, _) = bytes_for(dev_key); + let (pages0, _) = super::super::vram::page_bytes_for(dev_key); + let bc1_base = 0x60_0000_0000usize; + let mut bc1_res = Vec::with_capacity(512); + for k in 0..512usize { + bc1_res.push(place_sampled(bc1_base + k * 0x1000, &bc1, 2048)); + } + let (small_after_bc1, small_pool_after_bc1) = bytes_for(dev_key); + let bc1_small_delta = small_after_bc1 - small0; + let bc1_total_delta = super::super::vram::page_bytes_for(dev_key).0 - pages0; + println!("512 x 64x64 BC1: +{bc1_small_delta} B in small pools (pool={small_pool_after_bc1} B), +{bc1_total_delta} B total (vs 33554432 B as 64 KiB tiles)"); + assert_eq!(bc1_small_delta, 512 * UNIT, "each 64x64 BC1 must take 4 KiB in small pool"); + assert_eq!(bc1_total_delta, 512 * UNIT, "zero 64 KiB Pages tiles allocated for 4 KiB BC1 textures"); + drop(bc1_res); + + // 2. Hardware upload + readback: two adjacent 64x64 RGBA8 (16 KiB) textures and a + // same-address alias verify zero crosstalk and exact pixel sharing on the GPU. + super::super::vram::flush_idle_for(dev_key); + let rgba = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); + let va_a = 0x61_0000_1000usize; + let va_b = 0x61_0000_5000usize; + let a1 = place_sampled(va_a, &rgba, 16384); + let (small_after_a1, _) = bytes_for(dev_key); + let a2 = place_sampled(va_a, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_after_a1, "same-va small texture must share slot"); + let b = place_sampled(va_b, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0 - small_after_a1, 16384, "64x64 RGBA8 must take 16 KiB"); + + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fill_a = vec![0x3Cu8; 64 * 64 * 4]; + let fill_b = vec![0xA5u8; 64 * 64 * 4]; + let sub = |data: Vec| crate::gpu::texture::Subresource { rows: 64, row_bytes: 64 * 4, depth: 1, data }; + let batch = vec![ + (a2.clone(), vec![sub(fill_a.clone())], vec![D3D12_RESOURCE_STATE_COMMON]), + (b.clone(), vec![sub(fill_b.clone())], vec![D3D12_RESOURCE_STATE_COMMON]), + ]; + let failed = crate::gpu::texture::upload_batch(&dev, &queue, &batch).unwrap(); + assert!(failed.is_empty(), "upload failed: {failed:?}"); + + let readback_tex = |r: &ID3D12Resource| -> Vec { + let rd = r.GetDesc(); + 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)); + let mut rb: Option = None; + 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 = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = 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: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &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(y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + rb.Unmap(0, None); + out + }; + + assert_eq!(readback_tex(&a1), fill_a, "same-va alias a1 must see pixels uploaded to a2"); + assert_eq!(readback_tex(&b), fill_b, "adjacent 4 KiB texture b must not crosstalk with a"); + drop((b, a2, a1)); + + // 3. A small sampled texture at a 64 KiB-aligned va occupied by an existing GPU-owned + // render target must stay on vram::Pages (not vram_small) so it aliases the target. + super::super::vram::flush_idle_for(dev_key); + let rt_va = 0x62_0000_0000usize; + let rt_desc = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let mut rt_raw = std::ptr::null_mut(); + let hr = super::super::vram::place(dev.as_raw(), rt_va, &rt_desc, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, std::ptr::null(), Some(16384), riid, &mut rt_raw); + assert!(hr.is_some_and(|h| h >= 0) && !rt_raw.is_null()); + let rt = ID3D12Resource::from_raw(rt_raw); + let small_before_alias = bytes_for(dev_key).0; + let sampled_view = place_sampled(rt_va, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_before_alias, "sampled view over live GPU target must alias vram::Pages, not vram_small"); + drop((sampled_view, rt)); + } + } +} diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 5dd9d2e708..1af7c54e7b 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -6,7 +6,8 @@ //! riid, out), CreateStatusArray(capacity, name, riid, out), SetCpuAffinity(mask), //! SetDebugFlags(flags), SetStagingBufferSize(bytes), then 7 more, //! * queue desc (0x18): source type u32 @0 (0 file, 1 memory), capacity u16 @8, priority i8 -//! @10 (-1 … 2; memory queues 2), name @0x10, +//! @10 (-1 … 2; memory queues 2), name @0x10; the newer factory's desc (0x20) adds options +//! u64 @0x18 (`DSTORAGE_QUEUE_OPTIONS`: bit 0 `AutoSubmitDisabled`), //! * request (0x48): options u64 @0 (`DSTORAGE_REQUEST_OPTIONS`: bit 0 `ZlibDecompress`, //! bits 1–4 `BcpackMode`, bits 5–20 `SwizzleMode`, bit 21 `DestinationIsPhysicalPages`, //! bit 22 `SourceType` (0 file / 1 memory), bit 23 `SourceIsPhysicalPages`), @@ -482,17 +483,25 @@ unsafe extern "system" fn factory_unknown(_p: *mut c_void) -> HRESULT { E_NOTIMPL } +/// `DSTORAGE_QUEUE_OPTIONS` bit 0: the queue runs its requests only at `Submit`, not when it is +/// half full. +const AUTO_SUBMIT_DISABLED: u64 = 1; + /// Slot 10 of the newer factory: CreateQueue with a 0x20-byte desc – the 0x18 of -/// `factory_create_queue`, then a u64 (a retail game: 1). -unsafe extern "system" fn factory_create_queue1(p: *mut c_void, desc: *const u8, riid: *const GUID, out: *mut *mut c_void) -> HRESULT { +/// `factory_create_queue`, then the queue's options u64 (a retail game: `AutoSubmitDisabled`). +unsafe extern "system" fn factory_create_queue1(_p: *mut c_void, desc: *const u8, riid: *const GUID, out: *mut *mut c_void) -> HRESULT { + let mut options = 0; if !desc.is_null() { - let extra = (desc.add(0x18) as *const u64).read_unaligned(); + options = (desc.add(0x18) as *const u64).read_unaligned(); static SEEN: AtomicBool = AtomicBool::new(false); if !SEEN.swap(true, Ordering::Relaxed) { - crate::xlog_info!("DirectStorage: CreateQueue (0x20 desc), u64 @0x18 = {extra:#x}"); + crate::xlog_info!("DirectStorage: CreateQueue (0x20 desc), options {options:#x}"); + } + if options & !AUTO_SUBMIT_DISABLED != 0 { + warn_once("DSTORAGE_QUEUE_OPTIONS", format_args!("unknown queue option bits {:#x}", options & !AUTO_SUBMIT_DISABLED)); } } - factory_create_queue(p, desc, riid, out) + create_queue(desc, riid, out, options & AUTO_SUBMIT_DISABLED == 0) } unsafe extern "system" fn factory_set_cpu_affinity(_p: *mut c_void, _mask: u64) -> HRESULT { @@ -777,6 +786,13 @@ impl Request { } } +/// Whether the page array overlaps the enqueuing thread's stack. +fn on_callers_stack(ptr: usize, bytes: usize) -> bool { + let (mut low, mut high) = (0usize, 0usize); + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits(&mut low, &mut high) }; + ptr < high && ptr.saturating_add(bytes.max(1)) > low +} + /// Snapshot a `PULONG_PTR` physical page array at enqueue time (callers often stack-allocate it). unsafe fn snapshot_page_array(ptr: u64, offset: u16, byte_len: u32) -> Result, HRESULT> { if byte_len == 0 { @@ -870,7 +886,7 @@ fn note_request(r: &Request) { } /// 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<&[usize]>, dest_on_stack: bool, src_pages: Option<&[usize]>) -> Result<(), HRESULT> { let n = r.destination_size as usize; note_request(r); if !r.dest_physical_pages() && !writable(r.destination as usize, n) { @@ -927,11 +943,31 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us if r.dest_physical_pages() { let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; + // The console reads the page list when it runs the request. A retail title keeps its + // lists in slots of its own table and writes a slot's pages after EnqueueRequest, so at + // enqueue a slot can still name the pages of its previous request: written there, the + // data lands in memory the title has since used for something else, or in freed pages. + // A list on the caller's stack keeps its snapshot, because stack slots may now name + // unrelated live pages. + let mut current = vec![0usize; pages.len()]; + let pages = if !dest_on_stack + && read_own(r.destination as usize, current.as_mut_ptr() as *mut u8, std::mem::size_of_val(pages)) + && current[..] != pages[..] + && crate::hle::kernelx::physical_pages_live(¤t) + { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed) + 1; + if k == 1 || k.is_power_of_two() { + crate::xlog_info!("DirectStorage: {k} page lists written after their request was enqueued: the pages named at execution are used"); + } + ¤t[..] + } else { + pages + }; // 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). The title keeps an array with such an entry + // with page 0. The title keeps an array with such an entry // until the request is done: one it has freed or reused meanwhile cannot be told from // a late fill. Read like the snapshot (`read_own`): an array unmapped since then fails // the request instead of faulting in this worker (#476). @@ -951,6 +987,7 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us return Err(E_ACCESS_VIOLATION); } } else if n > 0 { + crate::hle::kernelx::pagelog::note("DirectStorage write", r.destination as usize, 0, n); std::ptr::copy_nonoverlapping(payload.as_ptr(), r.destination as *mut u8, n); } Ok(()) @@ -988,6 +1025,7 @@ enum Entry { req: Request, file: Option>, dest_pages: Option>, + dest_on_stack: bool, src_pages: Option>, }, /// refused at enqueue: reported in queue order by the worker (unless cancelled, as a request) @@ -1042,6 +1080,11 @@ struct QueueInner { pool_override: OnceLock>>, #[cfg(test)] test_hook: OnceLock, + /// a half-full queue submits by itself (not when made with `AutoSubmitDisabled`) + auto_submit: bool, + /// signalled when pending entries leave (`Submit`, a cancel, `Close`): a full queue made with + /// `AutoSubmitDisabled` holds its next enqueue until then + room: Condvar, } impl QueueInner { @@ -1072,6 +1115,7 @@ impl QueueInner { return; } let batch = std::mem::take(&mut self.pending.lock().unwrap().entries); + self.room.notify_all(); if batch.is_empty() { return; } @@ -1136,12 +1180,12 @@ impl QueueInner { return; } match e { - Entry::Request { seq, req, file, dest_pages, src_pages } => { + Entry::Request { seq, req, file, dest_pages, dest_on_stack, src_pages } => { if self.is_cancelled(seq, req.tag) { // Cancelled requests are skipped without affecting status or error record. return; } - if let Err(hr) = unsafe { execute(&req, file.as_deref(), dest_pages.as_deref(), src_pages.as_deref()) } { + if let Err(hr) = unsafe { execute(&req, file.as_deref(), dest_pages.as_deref(), dest_on_stack, src_pages.as_deref()) } { self.update_error(hr, req, file.as_deref(), since_status); } } @@ -1172,9 +1216,19 @@ impl QueueInner { } } + /// A queue made with `AutoSubmitDisabled` that holds `capacity` entries: wait until the title's + /// `Submit` (from another thread), a cancel or `Close` takes some, as the console's queue + /// stalls an enqueue at capacity. Others never wait: they submit when half full. + fn wait_for_room<'a>(&self, mut p: std::sync::MutexGuard<'a, Pending>) -> std::sync::MutexGuard<'a, Pending> { + while !self.auto_submit && p.entries.len() >= self.capacity && !self.closed.load(Ordering::Acquire) { + p = self.room.wait(p).unwrap(); + } + p + } + fn enqueue(self: &Arc, e: Entry) { let n = { - let mut p = self.pending.lock().unwrap(); + let mut p = self.wait_for_room(self.pending.lock().unwrap()); if self.closed.load(Ordering::Acquire) { return; } @@ -1187,13 +1241,13 @@ impl QueueInner { p.entries.len() }; // as on PC: a half-full queue submits by itself - if n >= (self.capacity / 2).max(1) { + if self.auto_submit && n >= (self.capacity / 2).max(1) { self.submit(); } } - 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>, dest_on_stack: bool, src_pages: Option>) { + self.enqueue_numbered(|seq| Entry::Request { seq, req, file, dest_pages, dest_on_stack, src_pages }); } /// A request refused at enqueue, numbered as a request so `CancelRequestsWithTag` covers it. @@ -1203,7 +1257,7 @@ impl QueueInner { fn enqueue_numbered(self: &Arc, entry: impl FnOnce(u64) -> Entry) { let n = { - let mut p = self.pending.lock().unwrap(); + let mut p = self.wait_for_room(self.pending.lock().unwrap()); if self.closed.load(Ordering::Acquire) { return; } @@ -1212,7 +1266,7 @@ impl QueueInner { p.entries.push(entry(seq)); p.entries.len() }; - if n >= (self.capacity / 2).max(1) { + if self.auto_submit && n >= (self.capacity / 2).max(1) { self.submit(); } } @@ -1249,6 +1303,11 @@ fn queue_vtbl() -> &'static [usize] { } unsafe extern "system" fn factory_create_queue(_p: *mut c_void, desc: *const u8, riid: *const GUID, out: *mut *mut c_void) -> HRESULT { + create_queue(desc, riid, out, true) +} + +/// A queue from the 0x18 bytes of `desc` (`auto_submit`: a half-full queue submits by itself). +unsafe fn create_queue(desc: *const u8, riid: *const GUID, out: *mut *mut c_void, auto_submit: bool) -> HRESULT { if out.is_null() { return E_POINTER; } @@ -1289,6 +1348,8 @@ unsafe extern "system" fn factory_create_queue(_p: *mut c_void, desc: *const u8, pool_override: OnceLock::new(), #[cfg(test)] test_hook: OnceLock::new(), + auto_submit, + room: Condvar::new(), }); let o = new_object(queue_vtbl(), inner); let hr = queue_qi(o, riid, out); @@ -1376,7 +1437,10 @@ unsafe extern "system" fn queue_enqueue_request(p: *mut c_void, req: *const u8) } else { None }; - q.enqueue_request(r, file, dest_pages, src_pages); + let dest_on_stack = dest_pages.as_deref().is_some_and(|pages| { + on_callers_stack(r.destination as usize, std::mem::size_of_val(pages)) + }); + q.enqueue_request(r, file, dest_pages, dest_on_stack, src_pages); } unsafe extern "system" fn queue_enqueue_status(p: *mut c_void, array: *mut c_void, index: u32) { @@ -1420,6 +1484,7 @@ unsafe extern "system" fn queue_cancel(p: *mut c_void, mask: u64, value: u64) { let cutoff = { let mut pend = q.pending.lock().unwrap(); pend.entries.retain(|e| !matches!(e, Entry::Request { req, .. } | Entry::Refused { req, .. } if req.tag & mask == value)); + q.room.notify_all(); pend.next_seq.saturating_sub(1) }; if cutoff == 0 { @@ -1447,6 +1512,8 @@ unsafe extern "system" fn queue_close(p: *mut c_void) { std::mem::take(&mut pend.entries) } }; + // an enqueue held by a full queue goes on (and finds the queue closed) + q.room.notify_all(); for e in drained { if let Entry::Status(s, i) = e { if let Some(slot) = s.slots.get(i as usize) { @@ -1546,6 +1613,114 @@ mod tests { b } + /// A queue the newer factory makes with `AutoSubmitDisabled` runs its requests at `Submit` + /// only, not when it is half full; one made without the option still submits by itself. + #[test] + fn a_queue_with_auto_submit_disabled_waits_for_submit() { + use std::time::{Duration, Instant}; + unsafe { + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY_X1, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue1: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(10)); + for (options, by_itself) in [(AUTO_SUBMIT_DISABLED, false), (0, true)] { + let mut desc = [0u8; 0x20]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); // memory source + desc[8..10].copy_from_slice(&4u16.to_le_bytes()); // capacity 4: half full at 2 + desc[10] = 2; + desc[0x18..0x20].copy_from_slice(&options.to_le_bytes()); + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue1(f, desc.as_ptr(), &IID_QUEUE_X1, &mut q), 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 submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + + let src = [0x5Au8; 64]; + let dst = [vec![0u8; 64], vec![0u8; 64]]; + for d in &dst { + enqueue(q, request(SOURCE_MEMORY_BIT, d.as_ptr() as u64, 64, src.as_ptr() as u64, 0, 64).as_ptr()); + } + let done = || dst.iter().all(|d| d.iter().all(|b| std::ptr::read_volatile(b) == 0x5A)); + let t = Instant::now(); + while !done() && t.elapsed() < Duration::from_millis(300) { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(done(), by_itself, "options {options:#x}: a half-full queue submits by itself only without AutoSubmitDisabled"); + if !by_itself { + submit(q); + let t = Instant::now(); + while !done() && t.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(done(), "Submit runs the queue's requests"); + } + queue_close(q); + queue_release(q); + } + } + } + + /// A full queue made with `AutoSubmitDisabled` holds the next enqueue until another thread's + /// `Submit` takes its entries, and `Close` lets a held enqueue go (into the closed queue). + #[test] + fn a_full_queue_with_auto_submit_disabled_holds_an_enqueue_until_submit() { + use std::time::{Duration, Instant}; + unsafe { + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY_X1, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue1: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(10)); + let mut desc = [0u8; 0x20]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); // memory source + desc[8..10].copy_from_slice(&2u16.to_le_bytes()); // capacity 2 + desc[10] = 2; + desc[0x18..0x20].copy_from_slice(&AUTO_SUBMIT_DISABLED.to_le_bytes()); + for close_instead in [false, true] { + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue1(f, desc.as_ptr(), &IID_QUEUE_X1, &mut q), 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 submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + + let src = [0x3Cu8; 64]; + let dst = [vec![0u8; 64], vec![0u8; 64], vec![0u8; 64]]; + let req = |k: usize| request(SOURCE_MEMORY_BIT, dst[k].as_ptr() as u64, 64, src.as_ptr() as u64, 0, 64); + enqueue(q, req(0).as_ptr()); + enqueue(q, req(1).as_ptr()); + // the queue is full: a third enqueue waits + let (third, qa) = (req(2), q as usize); + let t = std::thread::spawn(move || { + let e: unsafe extern "system" fn(*mut c_void, *const u8) = enqueue; + e(qa as *mut c_void, third.as_ptr()); + }); + std::thread::sleep(Duration::from_millis(200)); + assert!(!t.is_finished(), "an enqueue into a full queue waits"); + if close_instead { + queue_close(q); + } else { + submit(q); + } + let t0 = Instant::now(); + while !t.is_finished() && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(t.is_finished(), "{} lets the held enqueue go", if close_instead { "Close" } else { "Submit" }); + t.join().unwrap(); + if !close_instead { + submit(q); + let done = || dst.iter().all(|d| d.iter().all(|b| std::ptr::read_volatile(b) == 0x3C)); + let t0 = Instant::now(); + while !done() && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(done(), "all three requests ran"); + queue_close(q); + } + queue_release(q); + } + } + } + #[test] fn a_refused_factory_iid_returns_e_nointerface_and_clears_out() { unsafe { @@ -2314,6 +2489,95 @@ mod tests { } } + /// A title's table slot still names its previous request's page at enqueue and gets this + /// request's page before Submit: the data goes to the page named at execution, and the old + /// page (in use for something else by then) is left alone. A list on the enqueuing thread's + /// stack keeps its snapshot: a page written there since, though allocated, is not taken. + #[test] + fn a_destination_page_rewritten_after_enqueue() { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; + if crate::gpu::uma::get().is_none() { + return; + } + unsafe { + let mut count = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3)); + let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5)); + let mut desc = [0u8; 0x18]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); + desc[8..10].copy_from_slice(&16u16.to_le_bytes()); + desc[10] = 2; + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + let sv = *(s as *const *const usize); + let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3)); + let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4)); + + let reserved = windows_sys::Win32::System::Memory::VirtualAlloc( + std::ptr::null(), + 2 * 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, 2, 0, 4, pages.as_mut_ptr()), reserved); + let old_page = std::slice::from_raw_parts_mut(reserved as *mut u8, 0x100); + old_page.fill(0xAB); + + let data: Vec = (0..0x100u32).map(|i| (i * 7 + 1) as u8).collect(); + let mut slot = Box::new([pages[0]]); + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, slot.as_ptr() as u64, 0, data.len() as u32, data.as_ptr() as u64, 0, data.len() as u32, 0, 0).as_ptr()); + std::ptr::write_volatile(&mut slot[0], pages[1]); + status(q, s, 0); + submit(q); + let t = std::time::Instant::now(); + while !complete(s, 0) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!(hresult(s, 0), S_OK); + let new_page = std::slice::from_raw_parts((reserved as *const u8).add(PHYS_PAGE_SIZE), data.len()); + assert_eq!(new_page, &data[..], "the data goes to the page the slot names at execution"); + assert!(old_page.iter().all(|&b| b == 0xAB), "the slot's previous page is left alone"); + + // the same on the enqueuing thread's stack: rewritten after enqueue with another live + // page, the list keeps its snapshot + let other = std::slice::from_raw_parts_mut((reserved as *mut u8).add(PHYS_PAGE_SIZE), data.len()); + other.fill(0xCD); + let data2: Vec = (0..0x100u32).map(|i| (i * 3 + 5) as u8).collect(); + let mut on_stack = [pages[0]]; + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, on_stack.as_ptr() as u64, 0, data2.len() as u32, data2.as_ptr() as u64, 0, data2.len() as u32, 0, 0).as_ptr()); + std::ptr::write_volatile(&mut on_stack[0], pages[1]); + status(q, s, 1); + submit(q); + let t = std::time::Instant::now(); + while !complete(s, 1) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!(hresult(s, 1), S_OK); + assert_eq!(&old_page[..], &data2[..], "a list on the stack: the page of its snapshot"); + assert!(other.iter().all(|&b| b == 0xCD), "the page written on the stack since is left alone"); + + MapTitlePhysicalPages(reserved, 2, 0, 4, std::ptr::null_mut()); + windows_sys::Win32::System::Memory::VirtualFree(reserved, 0, windows_sys::Win32::System::Memory::MEM_RELEASE); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + queue_close(q); + queue_release(q); + status_release(s); + } + } + #[test] fn physical_page_destinations_and_sources() { use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index afa86c30c8..1b962b352b 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -158,6 +158,13 @@ pub fn in_graphics_reservation(p: usize) -> bool { GRAPHICS_RESERVATIONS.lock().unwrap().range(..=p).next_back().is_some_and(|(&b, &s)| p < b + s) } +/// Reservations where the console explicitly supplies backing for sampled texture pages. +pub fn tracks_texture_backing(p: usize) -> bool { + in_graphics_reservation(p) + || mirrors::source(p).is_some() + || crate::gpu::uma::get().is_some_and(|u| u.sparse_reservation(p).is_some()) +} + const MEM_WRITE_WATCH: u32 = 0x20_0000; /// GPU views of the title's CPU memory. A retail game reserves 24 GB of 64 KiB pages twice @@ -217,6 +224,14 @@ pub mod mirrors { s.gpu.retain(|_, &mut (_, c)| c != base); } + /// The GPU-view address paired with a CPU-view address. + pub fn gpu_of(va: usize) -> Option { + let s = STATE.lock().unwrap(); + s.gpu.iter().find_map(|(&gpu, &(size, cpu))| { + va.checked_sub(cpu).filter(|&offset| offset < size).map(|offset| gpu + offset) + }) + } + /// The CPU-view address behind `va` when `va` lies in a GPU view. pub fn source(va: usize) -> Option { let s = STATE.lock().unwrap(); @@ -238,6 +253,7 @@ unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, sanitize_protect(p)); if !q.is_null() { crate::hle::d3d12x::sparse::committed(q as usize, n); + crate::hle::d3d12x::vram::title_memory_changed(q as usize, n); } q } @@ -351,6 +367,10 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: } let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p)); trace_mem("VirtualAlloc", addr as usize, size, t as u64, p, q as usize); + // memory committed in a graphics reservation: the texture pages there follow it + if !q.is_null() && t & mem::MEM_COMMIT != 0 && (tracks_texture_backing(q as usize) || mirrors::gpu_of(q as usize).is_some()) { + crate::hle::d3d12x::vram::title_memory_changed(q as usize, size); + } q } @@ -869,11 +889,70 @@ pub unsafe extern "system" fn XMemIsToolsMemAvailable() -> BOOL { /// video-memory tiles, they took the system's commit.) const PHYS_PAGE: usize = 0x1_0000; +/// Diagnostic: the last events on the title's 64 KiB pages, for the report of an unhandled +/// exception (`describe`): what happened lately at the pages the registers point into. +pub mod pagelog { + use std::collections::VecDeque; + use std::sync::Mutex; + + const KEEP: usize = 400_000; + const PAGE: usize = 0x1_0000; + + #[derive(Clone, Copy)] + struct Event { + at_ms: u64, + what: &'static str, + /// the address the event is at, a second address (a move's source) and a number (page / bytes) + a: usize, + b: usize, + n: usize, + } + + static LOG: Mutex> = Mutex::new(VecDeque::new()); + static COUNTS: Mutex> = Mutex::new(Vec::new()); + + fn now_ms() -> u64 { + static T0: std::sync::OnceLock = std::sync::OnceLock::new(); + T0.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 + } + + /// `what` happened at address `a` (`b`: another address it involves, `n`: a page number or bytes). + pub fn note(what: &'static str, a: usize, b: usize, n: usize) { + let mut g = LOG.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() >= KEEP { + g.pop_front(); + } + g.push_back(Event { at_ms: now_ms(), what, a, b, n }); + drop(g); + let mut c = COUNTS.lock().unwrap_or_else(|e| e.into_inner()); + match c.iter_mut().find(|e| e.0 == what) { + Some(e) => e.1 += 1, + None => c.push((what, 1)), + } + } + + /// The events so far by kind. + pub fn counts() -> String { + let c = COUNTS.lock().unwrap_or_else(|e| e.into_inner()); + c.iter().map(|(w, n)| format!("{n} {w}")).collect::>().join(", ") + } + + /// The last events (up to 6) at the 64 KiB page of `addr`, newest first; empty: none kept. + pub fn describe(addr: usize) -> String { + let page = addr & !(PAGE - 1); + let Ok(g) = LOG.try_lock() else { return String::new() }; + let now = now_ms(); + let hit = |e: &&Event| (e.a..e.a + if e.what.starts_with("DirectStorage") { e.n.max(1) } else { PAGE }).contains(&addr) || e.a & !(PAGE - 1) == page || (e.b != 0 && e.b & !(PAGE - 1) == page); + g.iter().rev().filter(hit).take(6).map(|e| format!("{} ms ago: {} at {:#x}{}{}", now.saturating_sub(e.at_ms), e.what, e.a, if e.b != 0 { format!(" (other address {:#x})", e.b) } else { String::new() }, if e.n != 0 { format!(" [{:#x}]", e.n) } else { String::new() })).collect::>().join("; ") + } +} + /// Size of one console physical page (64 KiB). pub const PHYS_PAGE_SIZE: usize = PHYS_PAGE; /// first page index → (pages in the block, pages still allocated, the block's home) -static PHYS_BLOCKS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +type PhysicalBlocks = std::collections::BTreeMap; +static PHYS_BLOCKS: std::sync::Mutex = std::sync::Mutex::new(std::collections::BTreeMap::new()); /// the next page index handed out (page numbers are not addresses: a block's home is in a /// sparse window, the coherent one, or – without room there – plain reserved memory) @@ -884,10 +963,23 @@ static NEXT_PAGE_INDEX: AtomicUsize = AtomicUsize::new(0); struct Away { at: std::collections::BTreeMap, page: std::collections::HashMap, + /// Homes explicitly mapped by the title. An away mapping takes precedence while a + /// page is elsewhere; freeing or explicitly unmapping a home removes its entry. + mapped_homes: std::collections::HashMap, /// homes in a sparse window whose pages went away in this call, given back at its end in /// runs (`give_back_homes`): one page at a time, a retail game's start took 20 s gone: Vec, } + +impl Away { + fn mapped_away(&mut self, at: usize, page: usize) { + // A new mapping at the same address displaces a previously requested home. + self.mapped_homes.remove(&at); + self.at.insert(at, page); + self.page.insert(page, at); + } +} + static AWAY: std::sync::Mutex> = std::sync::Mutex::new(None); /// Whether a physical page is mapped at the page holding `va` away from its home – committed @@ -896,6 +988,17 @@ 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)))) } +/// The mapped physical page at each of the `n` 64 KiB addresses from `va`, including homes +/// requested by the title. A GPU resource retains the page it had at placement across a move. +pub fn physical_pages(va: usize, n: usize) -> Vec> { + let g = AWAY.lock().unwrap(); + let Some(a) = g.as_ref() else { return vec![None; n] }; + (0..n).map(|i| { + let at = va.checked_add(i.checked_mul(PHYS_PAGE)?)?; + a.at.get(&at).copied().or_else(|| a.mapped_homes.get(&at).copied().filter(|p| !a.page.contains_key(p))) + }).collect() +} + /// 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); @@ -926,12 +1029,21 @@ fn page_index(page: usize) -> Option { /// The home address of page `page` if it belongs to a live allocation. fn page_home(page: usize) -> Option { - let index = page_index(page)?; let blocks = PHYS_BLOCKS.lock().ok()?; + page_home_in(&blocks, page) +} + +fn page_home_in(blocks: &PhysicalBlocks, page: usize) -> Option { + let index = page_index(page)?; let (&first, &(count, live, home)) = blocks.range(..=index).next_back()?; (live > 0 && index < first.checked_add(count)?).then(|| home.checked_add((index - first).checked_mul(PHYS_PAGE)?)).flatten() } +/// Whether every page of `pages` (at least one) is a physical page allocated now. +pub fn physical_pages_live(pages: &[usize]) -> bool { + !pages.is_empty() && pages.iter().all(|&p| page_home(p).is_some()) +} + /// Whether a home is only reserved until it is used (a sparse window's, or plain memory's – /// the coherent window is committed as a whole). fn lazy_home(home: usize) -> bool { @@ -993,6 +1105,7 @@ pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) - let mut page_off = offset; for addr in addrs { let chunk = (PHYS_PAGE - page_off).min(src.len() - done); + pagelog::note("DirectStorage write by page number", addr + page_off, 0, chunk); std::ptr::copy_nonoverlapping(src.as_ptr().add(done), (addr + page_off) as *mut u8, chunk); done += chunk; page_off = 0; @@ -1145,8 +1258,10 @@ unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range bool { + LAZY.read().unwrap_or_else(|e| e.into_inner()).contains(&page) +} + /// `page` is unmapped: true if it was never used (nothing to keep of it). pub(super) fn unmark(page: usize) -> bool { LAZY.write().unwrap_or_else(|e| e.into_inner()).remove(&page) diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index f3e57ce5fb..fa45717386 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -35,9 +35,11 @@ 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()); + crate::hle::d3d12x::queue_probe::start(); // `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() { let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| { + let pso_memory = std::env::var_os("XCL_PSO_MEMORY").is_some(); let snap = || { let (p, e) = crate::hle::d3d12x::present::activity(); let (d, x) = crate::hle::d3d12x::bind::activity(); @@ -46,6 +48,7 @@ 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(); + let mut checkpoint = 0; loop { std::thread::sleep(std::time::Duration::from_secs(2)); let now = snap(); @@ -62,10 +65,11 @@ pub fn host_main(boot_path: &Path) -> i32 { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); c.PrivateUsage }; - let (local, non_local) = crate::hle::d3d12x::real::video_memory().unwrap_or((0, 0)); + let video = crate::hle::d3d12x::real::video_memory(); + let [(local, local_budget), (non_local, non_local_budget)] = video.unwrap_or_default(); 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 (pages, page_pools, deferred) = 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)", @@ -79,6 +83,30 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(pools as u64), mb(pools_mapped as u64) ); + if deferred != 0 { + crate::xlog_info!("title texture backing: {deferred} bytes deferred"); + } + if pso_memory { + let (shaders, unique, referenced, metadata) = crate::hle::d3d12x::real::pending_shader_memory(); + let (built, failed, pending) = crate::hle::d3d12x::pso_async::counts(); + crate::xlog_info!( + "PSO memory: {} live shaders, {} unique bytes, {} referenced bytes, {} estimated interner metadata bytes, {} pending / {} built / {} failed pipelines", + shaders, unique, referenced, metadata, pending, built, failed, + ); + } + if video.is_some() { + crate::xlog_info!("DXGI memory budgets: {} MiB local, {} MiB non-local", mb(local_budget), mb(non_local_budget)); + let (slots, heaps) = crate::hle::d3d12x::vram::small_texture_backing_bytes(); + crate::xlog_info!("small texture backing: {slots} bytes in assigned slots, {heaps} bytes in heaps"); + } + if crate::hle::d3d12x::queue_probe::enabled() { + checkpoint ^= 1; + crate::hle::d3d12x::queue_probe::snapshot(if checkpoint == 0 { + "queue-checkpoint-0.tsv" + } else { + "queue-checkpoint-1.tsv" + }); + } last = now; } }); diff --git a/crates/xcl/tests/gpu_two_pass_cache_e2e.rs b/crates/xcl/tests/gpu_two_pass_cache_e2e.rs new file mode 100644 index 0000000000..c1c74a9840 --- /dev/null +++ b/crates/xcl/tests/gpu_two_pass_cache_e2e.rs @@ -0,0 +1,656 @@ +//! Cross-process E2E verification for persistent two-pass (`MS` stream and `VS+GS`) driver PSO caching. + +use std::fs; +use std::path::PathBuf; +use std::process::Command; +use std::time::{SystemTime, UNIX_EPOCH}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::Interface; + +use xcl::gpu::rdna2::encode; +use xcl::gpu::recomp::{dxc, runner, IO_GS_PRIMS}; +use xcl::hle::d3d12x::{pso_async, real}; + +const V: u64 = 256; + +fn le32(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); +} + +fn container(parts: &[(&[u8; 4], &[u8])]) -> Vec { + let header = 32 + parts.len() * 4; + let mut v = vec![0u8; header]; + v[0..4].copy_from_slice(b"DXBC"); + v[20..24].copy_from_slice(&1u32.to_le_bytes()); + v[28..32].copy_from_slice(&(parts.len() as u32).to_le_bytes()); + for (i, (cc, data)) in parts.iter().enumerate() { + let off = v.len() as u32; + v[32 + i * 4..36 + i * 4].copy_from_slice(&off.to_le_bytes()); + v.extend_from_slice(*cc); + v.extend_from_slice(&(data.len() as u32).to_le_bytes()); + v.extend_from_slice(data); + } + let total = v.len() as u32; + v[24..28].copy_from_slice(&total.to_le_bytes()); + v +} + +fn fssm(code: &[u8], stages: &[(u8, u8)]) -> Vec { + let code_at = 0x308usize; + let mut v = vec![0u8; code_at]; + v[0..4].copy_from_slice(b"FSSM"); + v[4..8].copy_from_slice(&0x101u32.to_le_bytes()); + for q in (0x18..0xC0).step_by(8) { + v[q..q + 8].copy_from_slice(&0xDEAD_BEEF_DEAD_BEEFu64.to_le_bytes()); + } + v[0xC0..0xC8].copy_from_slice(&((code_at - 0x10) as u64).to_le_bytes()); + v[0xC8..0xD0].copy_from_slice(&(code.len() as u64 + 8).to_le_bytes()); + for (i, &(hw, api)) in stages.iter().enumerate() { + let o = 0x100 + i * 0x88; + let q = 0x0000_00C0_0002_0000u64 | ((api as u64) << 8) | hw as u64; + v[o..o + 8].copy_from_slice(&q.to_le_bytes()); + } + v.extend_from_slice(code); + v.extend_from_slice(&[0x00, 0x00, 0x9f, 0xbf, 0x00, 0x00, 0x9f, 0xbf]); + v.extend_from_slice(b"\x03\0\0\0metadata\0\0\0\0"); + let size = (v.len() - 0x10) as u32; + v[8..12].copy_from_slice(&size.to_le_bytes()); + v +} + +fn xbch(fssm_bytes: &[u8]) -> Vec { + let z = miniz_oxide::deflate::compress_to_vec_zlib(fssm_bytes, 6); + let mut v = b"XBCH".to_vec(); + le32(&mut v, 3); + le32(&mut v, z.len() as u32); + le32(&mut v, 0); + le32(&mut v, fssm_bytes.len() as u32); + le32(&mut v, 0); + v.extend_from_slice(&z); + v +} + +fn program_header(kind: u32, size_dw: u32, bitcode_off: u32) -> Vec { + let mut v = Vec::new(); + le32(&mut v, (kind << 16) | 0x66); + le32(&mut v, size_dw); + v.extend_from_slice(b"DXIL"); + le32(&mut v, 0x106); + le32(&mut v, bitcode_off); + le32(&mut v, 4); + v +} + +fn dxil_part(kind: u32, fssms: &[Vec]) -> Vec { + let mut blobs: Vec<(u32, Vec)> = vec![(0x12, (0u8..16).collect())]; + for f in fssms { + blobs.push((0x0D, xbch(f))); + } + let mut nested = program_header(kind, 0x8000_0007, 0x10); + nested.extend_from_slice(b"NOBC"); + blobs.push((0x07, nested)); + let table = 0x18 + 12; + let mut data_at = table + blobs.len() * 12; + let mut xdat = b"XDAT".to_vec(); + le32(&mut xdat, blobs.len() as u32); + le32(&mut xdat, table as u32); + for (id, b) in &blobs { + le32(&mut xdat, *id); + le32(&mut xdat, data_at as u32); + le32(&mut xdat, b.len() as u32); + data_at += b.len(); + } + for (_, b) in &blobs { + xdat.extend_from_slice(b); + } + while (0x18 + xdat.len()) % 4 != 0 { + xdat.push(0); + } + let nobc_at = 0x18 + xdat.len(); + let mut v = program_header(kind, ((nobc_at + 4) / 4) as u32, (nobc_at - 8) as u32); + v.extend_from_slice(&xdat); + v.extend_from_slice(b"NOBC"); + v +} + +fn sig_part(entries: &[(&str, u32, u32, u32, u8)]) -> Vec { + let mut d = Vec::new(); + le32(&mut d, entries.len() as u32); + le32(&mut d, 8); + let mut names = Vec::new(); + let base = 8 + entries.len() * 32; + for &(name, sv, ct, reg, mask) in entries { + let off = (base + names.len()) as u32; + names.extend_from_slice(name.as_bytes()); + names.push(0); + le32(&mut d, 0); + le32(&mut d, off); + le32(&mut d, 0); + le32(&mut d, sv); + le32(&mut d, ct); + le32(&mut d, reg); + d.extend_from_slice(&[mask, mask, 0, 0]); + le32(&mut d, 0); + } + d.extend_from_slice(&names); + d +} + +fn mesh_psv(max_v: u16, max_p: u16, threads: [u32; 3]) -> Vec { + let mut r = vec![0u8; 48]; + r[12..14].copy_from_slice(&max_v.to_le_bytes()); + r[14..16].copy_from_slice(&max_p.to_le_bytes()); + r[16..20].copy_from_slice(&64u32.to_le_bytes()); + r[20..24].copy_from_slice(&64u32.to_le_bytes()); + r[24] = 13; // MS + r[27] = 2; // triangles + r[36..40].copy_from_slice(&threads[0].to_le_bytes()); + r[40..44].copy_from_slice(&threads[1].to_le_bytes()); + r[44..48].copy_from_slice(&threads[2].to_le_bytes()); + let mut p = 48u32.to_le_bytes().to_vec(); + p.extend_from_slice(&r); + le32(&mut p, 0); + p +} + +fn gs_psv(max_v: u16) -> Vec { + let mut r = vec![0u8; 48]; + r[0..4].copy_from_slice(&3u32.to_le_bytes()); // input primitive: triangles + r[4..8].copy_from_slice(&5u32.to_le_bytes()); // output topology: triangle strip + r[16..20].copy_from_slice(&64u32.to_le_bytes()); + r[20..24].copy_from_slice(&64u32.to_le_bytes()); + r[24] = 2; // GS + r[26..28].copy_from_slice(&max_v.to_le_bytes()); + let mut p = 48u32.to_le_bytes().to_vec(); + p.extend_from_slice(&r); + le32(&mut p, 0); + p +} + +fn ms_code(alt: bool) -> Vec { + let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { + ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None) + }; + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("S_BFE_U32", "ENC_SOP2", vec![("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x40018)), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", 128)], None), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", V)], None), + ("V_LSHL_ADD_U32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 0), ("SRC1", 134), ("SRC2", V)], None), + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 124), ("SSRC0", 255)], Some((1 << 12) | 3)), + ("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 9)], None), + ("S_BARRIER", "ENC_SOPP", vec![], None), + // Keep threads 0..3 active; build full-viewport triangle (-1,-1), (4,-1), (-1,4). + ("V_CMPX_GT_U32", "ENC_VOPC", vec![("SRC0", 131), ("VSRC1", 0)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 10), ("SRC0", 243)], None), // -1.0 + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 11), ("SRC0", 243)], None), // -1.0 + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 12), ("SRC0", 128)], None), // 0.0 + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 13), ("SRC0", 242)], None), // 1.0 + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 15), ("SRC0", 246)], None), // 4.0 + ("V_CMP_EQ_U32", "ENC_VOPC", vec![("SRC0", 129), ("VSRC1", 0)], None), + ("V_CNDMASK_B32", "ENC_VOP2", vec![("VDST", 10), ("SRC0", V + 10), ("VSRC1", 15)], None), + ("V_CMP_EQ_U32", "ENC_VOPC", vec![("SRC0", 130), ("VSRC1", 0)], None), + ("V_CNDMASK_B32", "ENC_VOP2", vec![("VDST", 11), ("SRC0", V + 11), ("VSRC1", 15)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14), ("SRC0", if alt { 240 } else { 242 })], None), + ]; + list.push(exp(12, 0xF, [10, 11, 12, 13], 1)); + list.push(exp(32, 0xF, [14, 12, 12, 13], 0)); + list.push(("V_CMPX_EQ_U32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 0)], None)); + list.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 21), ("SRC0", 255)], Some((1 << 10) | (2 << 20)))); + list.push(exp(20, 1, [21, 0, 0, 0], 1)); + list.push(("S_ENDPGM", "ENC_SOPP", vec![], None)); + list.iter().flat_map(|(n, e, f, l)| encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))).collect() +} + +fn synthetic_ms_container(alt: bool) -> Vec { + let osg1 = sig_part(&[("SV_Position", 1, 3, 0, 0xF), ("TEXCOORD", 0, 3, 1, 0xF)]); + let psv0 = mesh_psv(128, 128, [128, 1, 1]); + let dxil = dxil_part(13, &[fssm(&ms_code(alt), &[(7, 6)])]); + container(&[(b"SFI0", &[0; 8]), (b"OSG1", &osg1), (b"PSV0", &psv0), (b"HASH", &[0; 20]), (b"DXIL", &dxil)]) +} + +fn synthetic_vs_gs_containers() -> (Vec, Vec) { + let e = |n: &str, enc: &str, f: &[(&str, u64)]| encode(n, enc, f, None).unwrap(); + let mut es = Vec::new(); + es.extend(e("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 6)])); + // GS emits 1 full-viewport green triangle (0, 1, 0, 1) from lane 0 at LDS base s2. + let mut gs = Vec::new(); + gs.extend(e("S_BFE_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)])); + // Re-encode S_BFE_U32 with literal 0x80008 for wave primitive count in s3[15:8]. + gs.truncate(gs.len() - 4); + gs.extend(encode("S_BFE_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x80008)).unwrap()); + gs.extend(e("S_BFM_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 0), ("SSRC1", 128)])); + gs.extend(e("V_MOV_B32", "ENC_VOP1", &[("VDST", 50), ("SRC0", 2)])); // s2 LDS base + gs.extend(e("V_MOV_B32", "ENC_VOP1", &[("VDST", 40), ("SRC0", 243)])); // -1.0 + gs.extend(e("V_MOV_B32", "ENC_VOP1", &[("VDST", 41), ("SRC0", 246)])); // 4.0 + gs.extend(e("V_MOV_B32", "ENC_VOP1", &[("VDST", 42), ("SRC0", 128)])); // 0.0 + gs.extend(e("V_MOV_B32", "ENC_VOP1", &[("VDST", 43), ("SRC0", 242)])); // 1.0 + let verts = [(40u64, 40u64), (41, 40), (40, 41)]; + for (k, (vx, vy)) in verts.into_iter().enumerate() { + let o = 8 * k as u64; + gs.extend(e("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 50), ("DATA0", vx), ("DATA1", vy), ("OFFSET0", o), ("OFFSET1", o + 1)])); + gs.extend(e("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 50), ("DATA0", 42), ("DATA1", 43), ("OFFSET0", o + 2), ("OFFSET1", o + 3)])); + gs.extend(e("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 50), ("DATA0", 42), ("DATA1", 43), ("OFFSET0", o + 4), ("OFFSET1", o + 5)])); + gs.extend(e("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 50), ("DATA0", 42), ("DATA1", 43), ("OFFSET0", o + 6), ("OFFSET1", o + 7)])); + gs.extend(e("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 0x22)])); + } + gs.extend(e("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 0x12)])); + gs.extend(e("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 0x3)])); + gs.extend(e("S_ENDPGM", "ENC_SOPP", &[])); + let vs_osg1 = sig_part(&[("SV_Position", 1, 3, 0, 0xF)]); + let gs_osg1 = sig_part(&[("SV_Position", 1, 3, 0, 0xF), ("TEXCOORD", 0, 3, 1, 0xF)]); + let vs = container(&[(b"SFI0", &[0; 8]), (b"OSG1", &vs_osg1), (b"DXIL", &dxil_part(1, &[fssm(&es, &[(2, 0)])]))]); + let gs = container(&[(b"SFI0", &[0; 8]), (b"OSG1", &gs_osg1), (b"PSV0", &gs_psv(3)), (b"DXIL", &dxil_part(2, &[fssm(&gs, &[(3, 2), (4, 2)])]))]); + (vs, gs) +} + +#[repr(C, align(8))] +struct Sub { + ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, + val: T, +} + +#[repr(C)] +struct MeshStream { + rs: Sub<*mut std::ffi::c_void>, + ms: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + rast: Sub, + depth: Sub, + rtv: Sub, + samples: Sub, +} + +fn empty_rs(dev: &ID3D12Device) -> ID3D12RootSignature { + unsafe { + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap() + } +} + +fn build_ms_pso(dev: &ID3D12Device, rs: &ID3D12RootSignature, ms: &[u8], ps: &[u8]) -> ID3D12PipelineState { + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let rast = D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }; + let mut rtv_formats = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 1, ..Default::default() }; + rtv_formats.RTFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + let mut stream = MeshStream { + rs: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, val: rs.as_raw() }, + ms: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, val: D3D12_SHADER_BYTECODE { pShaderBytecode: ms.as_ptr() as _, BytecodeLength: ms.len() } }, + ps: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, val: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() } }, + blend: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, val: blend }, + mask: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, val: u32::MAX }, + rast: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, val: rast }, + depth: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, val: D3D12_DEPTH_STENCIL_DESC::default() }, + rtv: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, val: rtv_formats }, + samples: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, val: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 } }, + }; + let dev2: ID3D12Device2 = dev.cast().unwrap(); + let pso: ID3D12PipelineState = unsafe { + dev2.CreatePipelineState(&D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: std::mem::size_of::(), + pPipelineStateSubobjectStream: &mut stream as *mut MeshStream as *mut std::ffi::c_void, + }) + } + .expect("CreatePipelineState two-pass MS"); + let raw = pso_async::resolve_wait(pso.as_raw() as usize); + let tp = real::two_pass_of(raw).expect("two-pass MS entry"); + assert_eq!(tp.kind, "MS"); + pso +} + +fn build_gs_pso(dev: &ID3D12Device, rs: &ID3D12RootSignature, vs: &[u8], gs: &[u8], ps: &[u8]) -> ID3D12PipelineState { + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, + GS: D3D12_SHADER_BYTECODE { pShaderBytecode: gs.as_ptr() as _, BytecodeLength: gs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + let pso: ID3D12PipelineState = unsafe { dev.CreateGraphicsPipelineState(&desc) }.expect("CreateGraphicsPipelineState two-pass GS"); + unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) }; + let raw = pso_async::resolve_wait(pso.as_raw() as usize); + let tp = real::two_pass_of(raw).expect("two-pass GS entry"); + assert_eq!(tp.kind, "GS"); + pso +} + +fn buf_res(dev: &ID3D12Device, heap_ty: D3D12_HEAP_TYPE, size: u64, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let mut out: Option = None; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let hp = D3D12_HEAP_PROPERTIES { Type: heap_ty, ..Default::default() }; + unsafe { dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) }.unwrap(); + out.unwrap() +} + +fn info_queue_errors(dev: &ID3D12Device) -> (u64, u64) { + let Ok(iq) = dev.cast::() else { return (0, 0) }; + let n = unsafe { iq.GetNumStoredMessagesAllowedByRetrievalFilter() }; + let (mut other, mut corrupt_blob) = (0u64, 0u64); + for i in 0..n { + let mut sz = 0usize; + if unsafe { iq.GetMessage(i, None, &mut sz) }.is_ok() && sz > 0 { + let mut raw = vec![0u8; sz]; + let msg = raw.as_mut_ptr() as *mut D3D12_MESSAGE; + if unsafe { iq.GetMessage(i, Some(msg), &mut sz) }.is_ok() { + let (sev, id) = unsafe { ((*msg).Severity, (*msg).ID.0) }; + if sev == D3D12_MESSAGE_SEVERITY_ERROR || sev == D3D12_MESSAGE_SEVERITY_CORRUPTION { + // Intentional corrupt-blob tests feed unparseable garbage to trigger ID 884. + if id == D3D12_MESSAGE_ID_CREATEPIPELINESTATE_INVALIDCACHEDBLOB.0 { + corrupt_blob += 1; + } else { + other += 1; + } + } + } + } + } + (other, corrupt_blob) +} + +/// Execute both passes of `pso` (`compute` -> UAV barrier -> `DispatchMesh`) and return +/// the center pixel `[f32; 4]` (verifying uniform 8x8 RTV fill and zeroed-`res` ordering when `run_compute == false`). +fn draw_two_pass_and_read(dev: &ID3D12Device, pso: &ID3D12PipelineState, gs_prims: u32, run_compute: bool) -> [f32; 4] { + const DIM: u32 = 8; + const RES_SIZE: u64 = 128 << 10; + let clear = [0.25f32, 0.25, 0.25, 0.25]; + let raw = pso_async::resolve_wait(pso.as_raw() as usize); + let tp = real::two_pass_of(raw).expect("two-pass pipeline entry"); + let cpso = unsafe { ID3D12PipelineState::from_raw_borrowed(&(tp.compute as *mut std::ffi::c_void)) }.unwrap().clone(); + let crs = unsafe { ID3D12RootSignature::from_raw_borrowed(&(tp.compute_rs as *mut std::ffi::c_void)) }.unwrap().clone(); + let mrs = unsafe { ID3D12RootSignature::from_raw_borrowed(&(tp.mesh_rs as *mut std::ffi::c_void)) }.unwrap().clone(); + + unsafe { + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList6 = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + + let io_up = buf_res(dev, D3D12_HEAP_TYPE_UPLOAD, 4096, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + let io_gpu = buf_res(dev, D3D12_HEAP_TYPE_DEFAULT, 4096, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + let zero_up = buf_res(dev, D3D12_HEAP_TYPE_UPLOAD, RES_SIZE, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + let res_gpu = buf_res(dev, D3D12_HEAP_TYPE_DEFAULT, RES_SIZE, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + let mem_gpu = buf_res(dev, D3D12_HEAP_TYPE_DEFAULT, 4096, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + let cbv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, ..Default::default() }) + .unwrap(); + let samp_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, ..Default::default() }) + .unwrap(); + + let mut p_io: *mut std::ffi::c_void = std::ptr::null_mut(); + io_up.Map(0, None, Some(&mut p_io)).unwrap(); + let io_words = std::slice::from_raw_parts_mut(p_io as *mut u32, 1024); + io_words.fill(0); + if gs_prims != 0 { + io_words[IO_GS_PRIMS] = gs_prims; + } + io_up.Unmap(0, None); + + let mut p_z: *mut std::ffi::c_void = std::ptr::null_mut(); + zero_up.Map(0, None, Some(&mut p_z)).unwrap(); + std::ptr::write_bytes(p_z, 0, RES_SIZE as usize); + zero_up.Unmap(0, None); + + let tex_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: DIM as u64, + Height: DIM, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let cv = D3D12_CLEAR_VALUE { Format: DXGI_FORMAT_R32G32B32A32_FLOAT, Anonymous: D3D12_CLEAR_VALUE_0 { Color: clear } }; + let mut rtv_tex: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &tex_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, Some(&cv), &mut rtv_tex).unwrap(); + let rtv_tex = rtv_tex.unwrap(); + let rtv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }).unwrap(); + let rtv_cpu = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&rtv_tex, None, rtv_cpu); + + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total_bytes = 0u64; + dev.GetCopyableFootprints(&tex_desc, 0, 1, 0, Some(&mut fp), None, None, Some(&mut total_bytes)); + let rb = buf_res(dev, D3D12_HEAP_TYPE_READBACK, total_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + + let trans = |res: &ID3D12Resource, from: D3D12_RESOURCE_STATES, to: D3D12_RESOURCE_STATES| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::ManuallyDrop::new(Some(res.clone())), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: from, StateAfter: to }), + }, + }; + let uav_b = |res: &ID3D12Resource| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(Some(res.clone())) }), + }, + }; + + list.CopyBufferRegion(&io_gpu, 0, &io_up, 0, 4096); + list.CopyBufferRegion(&res_gpu, 0, &zero_up, 0, RES_SIZE); + let init_bars = [ + trans(&io_gpu, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + trans(&res_gpu, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + trans(&mem_gpu, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]; + list.ResourceBarrier(&init_bars); + for b in init_bars { + let transition = std::mem::ManuallyDrop::into_inner(b.Anonymous.Transition); + drop(std::mem::ManuallyDrop::into_inner(transition.pResource)); + } + list.SetDescriptorHeaps(&[Some(cbv_heap.clone()), Some(samp_heap.clone())]); + + if run_compute { + list.SetPipelineState(&cpso); + list.SetComputeRootSignature(&crs); + list.SetComputeRootUnorderedAccessView(0, io_gpu.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, res_gpu.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, mem_gpu.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + let ub = [uav_b(&res_gpu)]; + list.ResourceBarrier(&ub); + for b in ub { + let barrier = std::mem::ManuallyDrop::into_inner(b.Anonymous.UAV); + drop(std::mem::ManuallyDrop::into_inner(barrier.pResource)); + } + } + + list.ClearRenderTargetView(rtv_cpu, &clear, None); + list.OMSetRenderTargets(1, Some(&rtv_cpu), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { Width: DIM as f32, Height: DIM as f32, MaxDepth: 1.0, ..Default::default() }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { right: DIM as i32, bottom: DIM as i32, ..Default::default() }]); + list.SetPipelineState(pso); + list.SetGraphicsRootSignature(&mrs); + list.SetGraphicsRootUnorderedAccessView(0, io_gpu.GetGPUVirtualAddress()); + list.SetGraphicsRootUnorderedAccessView(1, res_gpu.GetGPUVirtualAddress()); + list.SetGraphicsRootUnorderedAccessView(2, mem_gpu.GetGPUVirtualAddress()); + list.DispatchMesh(tp.mesh_groups_per_record, 1, 1); + + let end_bars = [trans(&rtv_tex, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]; + list.ResourceBarrier(&end_bars); + for b in end_bars { + let transition = std::mem::ManuallyDrop::into_inner(b.Anonymous.Transition); + drop(std::mem::ManuallyDrop::into_inner(transition.pResource)); + } + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::ManuallyDrop::new(Some(rtv_tex.clone())), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::ManuallyDrop::new(Some(rb.clone())), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + std::mem::ManuallyDrop::into_inner(src.pResource); + std::mem::ManuallyDrop::into_inner(dst.pResource); + + list.Close().unwrap(); + let cls = [Some(list.cast::().unwrap())]; + q.ExecuteCommandLists(&cls); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let ev = windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap(); + q.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, ev).unwrap(); + let wait = windows::Win32::System::Threading::WaitForSingleObject(ev, 5000); + windows::Win32::Foundation::CloseHandle(ev).unwrap(); + assert_eq!(wait, windows::Win32::Foundation::WAIT_OBJECT_0); + + let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut ptr)).unwrap(); + let row_pitch = fp.Footprint.RowPitch as usize; + let pixel_at = |x: usize, y: usize| -> [f32; 4] { + let p = (ptr as *const u8).add(y * row_pitch + x * 16) as *const [f32; 4]; + std::ptr::read_unaligned(p) + }; + let center = pixel_at((DIM / 2) as usize, (DIM / 2) as usize); + for y in 0..DIM as usize { + for x in 0..DIM as usize { + assert_eq!(pixel_at(x, y), center, "non-uniform pixel at ({x},{y})"); + } + } + rb.Unmap(0, None); + center + } +} + +fn mesh_ready(dev: &ID3D12Device) -> bool { + let mut o7 = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &mut o7 as *mut _ as _, std::mem::size_of_val(&o7) as u32) }.is_ok() + && o7.MeshShaderTier.0 >= D3D12_MESH_SHADER_TIER_1.0 +} + +const CHILD_CASE: &str = "XCL_TEST_TWO_PASS_CACHE_CASE"; +const TEST: &str = "two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs"; + +#[test] +fn two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs() { + if let Ok(case) = std::env::var(CHILD_CASE) { + return run_case(&case); + } + struct TempDir(PathBuf); + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let root = TempDir(std::env::temp_dir().join(format!("xcl-two-pass-{}-{nonce}", std::process::id()))); + let exe = std::env::current_exe().unwrap(); + let run = |case: &str, disk: bool, seed: bool| { + let mut cmd = Command::new(&exe); + cmd.args(["--exact", TEST, "--nocapture"]).env(CHILD_CASE, case) + .env("XCL_DXIL_CACHE", &root.0) + .env("XCL_PSO_DISK_CACHE", if disk { "1" } else { "0" }) + .env("XCL_ASYNC_PSO", "1").env("XCL_D3D12_DEBUG", "1") + .env_remove("XCL_PSO_DISK_CACHE_MIN_MS"); + if seed { + cmd.env("XCL_PSO_DISK_CACHE_MIN_MS", "0"); + } + let out = cmd.output().unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{case}: {} +{stderr}", String::from_utf8_lossy(&out.stdout)); + let prefix = format!("SKIPPED {TEST}: "); + stderr.lines().find_map(|line| line.strip_prefix(&prefix)).map(str::to_owned) + }; + + if let Some(reason) = run("disabled", false, true) { + return runner::skip_test(&reason); + } + let driver = root.0.join("driver"); + assert!(!driver.exists(), "disabled cache must not create the driver directory"); + assert_eq!(run("seed", true, true), None); + assert_eq!(run("warm", true, false), None); + let files = fs::read_dir(&driver).unwrap().map(|e| e.unwrap().path()).collect::>(); + let by_prefix = |prefix: &str| files.iter() + .filter(|p| p.file_name().unwrap().to_string_lossy().starts_with(prefix)).count(); + assert_eq!((by_prefix("tp-cs-"), by_prefix("tp-ms-")), (3, 2)); + for prefix in ["tp-cs-", "tp-ms-"] { + for path in files.iter().filter(|p| p.file_name().unwrap().to_string_lossy().starts_with(prefix)) { + fs::write(path, b"invalid driver blob").unwrap(); + } + // Even with existing corrupt files, the disabled run must leave the files alone. + assert_eq!(run("disabled", false, true), None); + assert_eq!(run(prefix, true, true), None); + } + assert_eq!(run("warm", true, false), None); +} + +fn run_case(case: &str) { + if dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + if xcl::hle::d3d12x::backend() != xcl::hle::d3d12x::Backend::Real { + return runner::skip_test("no GPU"); + } + if runner::wave64_programs_supported() != Ok(true) { + return runner::skip_test("no wave64"); + } + let raw = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone(); + if !mesh_ready(&dev) { + return runner::skip_test("no mesh shaders"); + } + let ps = dxc::compile("struct V { float4 pos : SV_Position; float4 p0 : TEXCOORD0; }; +float4 main(V v) : SV_Target0 { return v.p0; } +", "main", "ps_6_6", &[]).unwrap(); + let rs = empty_rs(&dev); + let (vs, gs) = synthetic_vs_gs_containers(); + let before = real::two_pass_count(); + let (errors, corrupt) = info_queue_errors(&dev); + let expected = match case { + "disabled" => [(0, 0, 0); 3], + "seed" => [(0, 0, 2), (0, 0, 3), (0, 0, 5)], + "warm" => [(2, 0, 0), (3, 0, 0), (5, 0, 0)], + "tp-cs-" => [(1, 1, 1), (1, 2, 2), (2, 3, 3)], + "tp-ms-" => [(1, 1, 1), (2, 1, 1), (3, 2, 2)], + _ => panic!("unknown case {case}"), + }; + + let ms1 = build_ms_pso(&dev, &rs, &synthetic_ms_container(false), &ps); + assert_eq!(real::driver_cache_stats(), expected[0]); + assert_eq!(draw_two_pass_and_read(&dev, &ms1, 0, false), [0.25; 4]); + assert_eq!(draw_two_pass_and_read(&dev, &ms1, 0, true), [1.0, 0.0, 0.0, 1.0]); + + // The second MS shares the passthrough mesh graphics PSO but has a distinct NGG compute PSO. + let ms2 = build_ms_pso(&dev, &rs, &synthetic_ms_container(true), &ps); + assert_eq!(real::driver_cache_stats(), expected[1]); + assert_eq!(draw_two_pass_and_read(&dev, &ms2, 0, true), [0.5, 0.0, 0.0, 1.0]); + + let gs = build_gs_pso(&dev, &rs, &vs, &gs, &ps); + assert_eq!(real::driver_cache_stats(), expected[2]); + assert_eq!(draw_two_pass_and_read(&dev, &gs, 1, false), [0.25; 4]); + assert_eq!(draw_two_pass_and_read(&dev, &gs, 1, true), [0.0, 1.0, 0.0, 1.0]); + assert_eq!(real::two_pass_count(), before + 3); + drop((ms1, ms2, gs)); + assert_eq!(real::two_pass_count(), before, "releasing the title PSOs releases their two-pass state"); + + if dev.cast::().is_ok() { + let (after_errors, after_corrupt) = info_queue_errors(&dev); + assert_eq!(after_errors, errors, "unexpected D3D12 debug message in {case}"); + assert_eq!(after_corrupt - corrupt, expected[2].1, "unexpected corrupt-blob error count in {case}"); + } +}