diff --git a/README.md b/README.md index 1bd0c54868..141a49eb89 100644 --- a/README.md +++ b/README.md @@ -214,6 +214,9 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o 64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63 can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups made up of complete native waves can use the per-lane form for branches on whole-wave masks. + With four heap-backed memory windows (`XCL_HEAP_WINDOWS=1`) and direct DXIL compute, + `XCL_BYTE_STORE_CS=` enables R8_UINT stores for single-byte writes in + that compute shader on adapters that support them. Use the same settings for precompile and play. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). ```powershell diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a47..0619aae534 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -253,6 +253,7 @@ fn is_writable(va: usize, bytes: usize) -> bool { if bytes > 0 && crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { return true; } + let _trap = crate::hle::d3d12x::watch_trap::guard(va, bytes); let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const std::ffi::c_void, &mut m, std::mem::size_of_val(&m)) } != 0; found diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index e0bb2e8935..e0820359e0 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -209,7 +209,7 @@ fn a_gpu_with_64_lane_waves_keeps_the_first_table_limit() { } let code = two_segments(8192); let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; - let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only).unwrap().dxil.len(); let (compact, plain) = (size(true), size(false)); assert!(compact * 20 < plain, "{compact} B on a GPU with 32-lane waves only, {plain} B on one with 64-lane waves"); diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 7492f54b9c..4e65c61ac5 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -582,6 +582,25 @@ fn gpu_direct_unaligned_multi_dword_format_store() { assert_eq!(&got[0xFC..0x118], &want[0xFC..0x118], "bytes 0xFC..0x118 after the store at 0x102"); } +#[test] +fn typed_byte_store_adds_a_byte_view_and_keeps_the_raw_fallback() { + use crate::gpu::recomp::{BYTE_WINDOWS, HEAP_WINDOWS}; + let code = prog(&[ + ("BUFFER_STORE_FORMAT_X", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], None), + ]); + let disassembly = |windows| { + let ko = KernelOptions { wave64: false, split: false, mem_windows: windows, sampler_base: 0 }; + let dxil = translate(&code, ko).expect("formatted store translates"); + super::validate::validate(&dxil).expect("valid formatted store DXIL"); + super::validate::disassemble(&dxil).expect("disassemble formatted store") + }; + let normal = disassembly(4 | HEAP_WINDOWS); + let typed = disassembly(4 | HEAP_WINDOWS | BYTE_WINDOWS); + let stores = |s: &str| s.matches("call void @dx.op.bufferStore.i32(").count(); + assert_eq!(stores(&typed), stores(&normal) + 1); + assert!(typed.contains("@dx.op.atomicBinOp.i32"), "wider partial stores still use the raw view"); +} + #[test] fn window_at_lowers_to_32bit_carry_without_int64() { let ko = KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; @@ -831,3 +850,41 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { } } } + +#[test] +fn compute_lds_reservation_matches_descriptor_and_lane_storage() { + // Exercise both cache modes on ordinary CI without changing the test process environment. + if std::env::var_os("XCL_TEST_LDS_CHILD").is_none() { + for mode in ["0", "1"] { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "gpu::dxil::core_tests::compute_lds_reservation_matches_descriptor_and_lane_storage"]) + .env("XCL_DECLARED_LDS", mode) + .env("XCL_TEST_LDS_CHILD", "1") + .status().unwrap(); + assert!(status.success(), "declared LDS mode {mode}"); + } + return; + } + use crate::gpu::recomp::CsInterface; + let code = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None)]); + for (threads, blocks, split, expected) in [ + ([64, 1, 1], 2u32, false, 256), + ([8, 8, 1], 1, false, 129), + ([8, 8, 1], 1, true, 135), + ([128, 1, 1], 2, true, 269), + ([8, 8, 1], 0, true, 8192), + ([8, 8, 1], 64, true, 8192), + ] { + let mut descriptor = [0u8; 0x48]; + for (i, v) in [blocks << 15, threads[0], threads[1], threads[2]].into_iter().enumerate() { + descriptor[0x38 + 4*i..0x3c + 4*i].copy_from_slice(&v.to_le_bytes()); + } + let cs = CsInterface::from_descriptor(&descriptor, 0).unwrap(); + assert_eq!(cs.lds_dwords, blocks * 128); + let options = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; + let dxil = super::kernel::translate_compute(&code, options, &cs).unwrap().dxil; + let dis = super::validate::disassemble(&dxil).unwrap(); + let words = if super::kernel::declared_lds_enabled() { expected } else { 8192 }; + assert!(dis.contains(&format!("@xcl_lds = external addrspace(3) global [{words} x i32]")), "{threads:?}, {blocks}, split={split}"); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..dfb97ee569 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -40,6 +40,12 @@ pub struct KernelOptions { /// (the `gpu/dxil` sources are not in build.rs's translator source hash). pub const TRANSLATOR_VERSION: u32 = 9; +/// Opt in for dispatches whose guest LDS contract is fixed by the pipeline header. +pub fn declared_lds_enabled() -> bool { + static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *ENABLED.get_or_init(|| std::env::var("XCL_DECLARED_LDS").is_ok_and(|value| value == "1")) +} + /// `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. pub fn enabled() -> bool { @@ -502,7 +508,7 @@ impl Lw { s.enable_rov(); } 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 (mems, heap_mem) = mem_windows(&mut s, o.mem_windows & !crate::gpu::recomp::BYTE_WINDOWS, coherent); let i32 = s.m.i32(); let z = s.m.i32c(0); let mut lw = Lw { @@ -517,6 +523,7 @@ impl Lw { half: z, mems, heap_mem, + byte_windows: o.mem_windows & crate::gpu::recomp::BYTE_WINDOWS != 0 && heap_mem.is_some(), res, fmt_table: None, fmt_desc_cache: HashMap::new(), @@ -598,7 +605,14 @@ impl Lw { if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); } - lw.setup_storage(uses_lds, if split { slot } else { 1 }); + let (declared, native_counter) = match entry { + Entry::Compute(cs) => { + let declared = if declared_lds_enabled() { cs.lds_dwords } else { 0 }; + (declared, !split && (cs.threads[1] > 1 || cs.threads[2] > 1)) + } + _ => (0, false), + }; + lw.setup_storage(uses_lds, slot, declared, native_counter); if let (Some(t), true) = (group_threads, split) { lw.partner = match t { 0..=32 => Partner::Missing, diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 4ee59b5cc8..1962f17141 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -14,27 +14,30 @@ use super::module::{BinOp, Pred, RmwOp, Value}; use super::ops::barrier; impl Lw { - /// Groupshared storage, created in the entry block before anything else: - /// the program's LDS (`lds_words` > 0) and, in the split form, the halves' - /// exchange words — in the top of the LDS block when there is one (D3D12 - /// allows 32 KB, the whole LDS), as the HLSL kernel lays it out. - pub fn setup_storage(&mut self, lds: bool, slot: u32) { + /// Put private lane-exchange words after the guest LDS. D3D12 permits + /// 8192 dwords in total, including any arrival counter for a native 2-D group. + pub fn setup_storage(&mut self, lds: bool, slot: u32, declared: u32, native_counter: bool) { let i32 = self.s.m.i32(); self.xslot = slot.max(1); if lds { - let g = self.s.groupshared("xcl_lds", i32, 8192); + let slots = 4 * self.xslot * self.waves; + let control = if self.split { slots + 2 * self.waves + 1 } else { u32::from(native_counter) }; + // Unspecified or oversized reservations retain the existing 32 KiB layout. + let fits = declared != 0 && declared <= 8192 - control; + let words = if fits { declared + control } else { 8192 }; + let g = self.s.groupshared("xcl_lds", i32, u64::from(words)); self.lds = Some(g); if self.split { - // HLSL: exchange base = 8192 - slots - counters - 1 (slots = 4 · slot per console - // wave, 2 counters each); the program's LDS stops below it - let slots = 4 * self.xslot * self.waves; - let base = 8192 - slots - 2 * self.waves - 1; + let base = words - control; self.lds_top = base - 1; self.xs = Some((g, base)); self.xc = Some((g, base + slots)); - self.xw = Some((g, 8191)); + self.xw = Some((g, words - 1)); } else { - self.lds_top = 8191; + self.lds_top = if fits { declared - 1 } else { 8191 }; + if native_counter { + self.xw = Some((g, words - 1)); + } } } else if self.split { let w = self.s.groupshared("xcl_xw", i32, 1); @@ -117,7 +120,7 @@ impl Lw { } else if y * z > 1 { let i32 = self.s.m.i32(); let (g, at) = match (self.lds, lds_top_word) { - (Some(l), true) => (l, 8191), + (Some(_), true) => self.xw.expect("compute LDS arrival counter"), _ => (self.s.groupshared("xcl_wt", i32, 1), 0), }; let ai = self.c(at); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..b8da464a1f 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -187,6 +187,7 @@ pub struct Lw { /// the windows come from the descriptor heap (`lower_window`; `mems` only counts them): /// Some(globallycoherent) pub heap_mem: Option, + pub byte_windows: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, @@ -232,7 +233,7 @@ pub struct Lw { pub xn: Value, /// words per half in an exchange pub xslot: u32, - /// the program's LDS (`xcl_lds`, 8192 dwords) and its last usable dword + /// the program's LDS (`xcl_lds`) and its last usable guest dword pub lds: Option, pub lds_top: u32, /// DPP write enable of the instruction being lowered diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cc7cd0116a..8ad7b55895 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -513,6 +513,30 @@ impl Lw { /// `st_bytes`: store the low `n` bytes of `r` at byte address `a` (n ≤ 16; partial /// dwords through atomics so neighbours stay intact). fn st_bytes(&mut self, a: Value, r: [Value; 4], n: Value) -> LResult<()> { + // A row of R8_UINT views spans one raw window. Partial multi-byte stores still use the atomic path. + if self.byte_windows { + let win = self.rd(super::lower::VAR_WIN); + let in_range = self.cmpc(Pred::ULt, win, self.mems.len() as u32); + let byte = self.cmpc(Pred::Eq, n, 1); + let typed = self.land(in_range, byte); + self.guarded(typed, &mut |lw| { + let row = lw.shlc(win, crate::gpu::recomp::BYTE_SEGMENTS.trailing_zeros()); + let segment = lw.lshrc(a, crate::gpu::recomp::BYTE_SEGMENT_SHIFT); + let index = lw.or(row, segment); + let index = lw.addc(index, crate::gpu::recomp::BYTE_HEAP_BASE); + let coherent = lw.heap_mem.unwrap_or(false); + let view = lw.s.heap_typed_buffer_with_coherence(index, true, super::ops::CompType::U32, true, coherent); + let offset = lw.andc(a, (1 << crate::gpu::recomp::BYTE_SEGMENT_SHIFT) - 1); + let value = lw.andc(r[0], 255); + lw.s.buffer_store(view, offset, &[value]); + Ok(()) + })?; + let other = self.lnot(typed); + return self.guarded(other, &mut |lw| lw.st_bytes_raw(a, r, n)); + } + self.st_bytes_raw(a, r, n) + } + fn st_bytes_raw(&mut self, a: Value, r: [Value; 4], n: Value) -> LResult<()> { let s = self.andc(a, 3); let s = self.shlc(s, 3); let b = self.andc(a, !3); @@ -2072,7 +2096,7 @@ impl Lw { fn lds_index(&mut self, at: Value) -> Value { let i = self.lshrc(at, 2); let i = self.andc(i, 8191); - if self.split { + if self.lds_top < 8191 { let k = self.c(self.lds_top); self.umin(i, k) } else { diff --git a/crates/xcl/src/gpu/dxil/ops.rs b/crates/xcl/src/gpu/dxil/ops.rs index cf7d47b145..d91a8f4084 100644 --- a/crates/xcl/src/gpu/dxil/ops.rs +++ b/crates/xcl/src/gpu/dxil/ops.rs @@ -553,8 +553,12 @@ impl Shader { } /// `Buffer` / `RWBuffer` from the descriptor heap. pub fn heap_typed_buffer(&mut self, index: Value, uav: bool, comp: CompType, nonuniform: bool) -> TypedBuffer { + self.heap_typed_buffer_with_coherence(index, uav, comp, nonuniform, false) + } + pub fn heap_typed_buffer_with_coherence(&mut self, index: Value, uav: bool, comp: CompType, nonuniform: bool, coherent: bool) -> TypedBuffer { let h = self.handle_from_heap(index, false, nonuniform); - let handle = self.annotate(h, kind::TYPED_BUFFER | if uav { 0x1000 } else { 0 }, typed_props(comp, 1)); + let properties = kind::TYPED_BUFFER | if uav { 0x1000 } else { 0 } | if coherent { 0x4000 } else { 0 }; + let handle = self.annotate(h, properties, typed_props(comp, 1)); TypedBuffer { handle, comp, binding: None } } fn comp_ty(&mut self, c: CompType) -> Ty { diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index 46a06c63d4..726e8b301e 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -69,7 +69,7 @@ fn translate_all() -> Vec> { input_ena: 0x302, attrs: None, }; - let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; let mut out = Vec::new(); for (w, s) in [(false, false), (true, true), (true, false)] { diff --git a/crates/xcl/src/gpu/recomp/link_tests.rs b/crates/xcl/src/gpu/recomp/link_tests.rs index b2e99dfab9..c28b6acf4f 100644 --- a/crates/xcl/src/gpu/recomp/link_tests.rs +++ b/crates/xcl/src/gpu/recomp/link_tests.rs @@ -162,7 +162,7 @@ fn bench_memory_window_accessors() { for round in 0..3 { for windows in [1, 4] { nonce = nonce.wrapping_mul(0x9E37_79B1) | 1; - let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let t = translate(&program(n, nonce), &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, mem_windows: windows, ..Default::default() })).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let forms = if windows == 1 { @@ -212,7 +212,7 @@ fn linked_programs_keep_their_declarations() { let list = [buf("BUFFER_LOAD_DWORD", 2, coherent), buf("BUFFER_STORE_DWORD", 3, false)]; let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let p = prog(&refs); - let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 16, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 16, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let t = translate(&p, &Options { mode: Mode::Compute(cs), wave64, mem_windows: 4, ..Default::default() }).unwrap(); let size = if wave64 { 64 } else { 32 }; assert!(t.hlsl.contains(&format!("[WaveSize({size})]")), "{}", t.hlsl); diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 0d86a1607e..64446b7233 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -3072,7 +3072,7 @@ pub(crate) mod tests { } pub(crate) fn compute_cs() -> crate::gpu::recomp::CsInterface { - crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 } + crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() } } /// A compute program run on the CPU over `groups` groups (wave32): the memory after. diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 528493d6e5..2259e8cf3c 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -84,6 +84,11 @@ pub const MEM_HEAP_BASE: u32 = 4; /// Flag in a memory-windows count (`pso::mem_windows`, the translation caches' keys): /// `Options::heap_windows`. `translate` takes it out of `mem_windows`. pub const HEAP_WINDOWS: u32 = 0x100; +/// An additional descriptor row for single-byte format stores. The count still describes the raw windows. +pub(crate) const BYTE_WINDOWS: u32 = 0x200; +pub(crate) const BYTE_HEAP_BASE: u32 = MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; +pub(crate) const BYTE_SEGMENT_SHIFT: u32 = 27; +pub(crate) const BYTE_SEGMENTS: u32 = 1 << (32 - BYTE_SEGMENT_SHIFT); pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { windows <= crate::gpu::uma::MAX_WINDOWS @@ -237,6 +242,8 @@ impl GsInterface { /// Compute shader with the console's dispatch ABI (see the module docs). #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct CsInterface { + /// Static workgroup LDS from COMPUTE_PGM_RSRC2, in dwords. Zero means unspecified. + pub lds_dwords: u32, pub threads: [u32; 3], pub user_sgprs: u32, /// TGID_X / Y / Z enabled: the group id follows the user SGPRs in this order @@ -262,6 +269,7 @@ impl CsInterface { fn from_rsrc2(threads: [u32; 3], r: u32) -> Self { Self { threads, + lds_dwords: ((r >> 15) & 0x1ff) * 128, user_sgprs: (r >> 1) & 31, tgid: [(r >> 7) & 1 == 1, (r >> 8) & 1 == 1, (r >> 9) & 1 == 1], tg_size: (r >> 10) & 1 == 1, diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5d000775ef..03aeb8f312 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -118,6 +118,12 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } +/// Scope an experimental byte-store comparison to a single console compute shader. +pub(crate) fn byte_store_program() -> Option { + static PROGRAM: OnceLock> = OnceLock::new(); + *PROGRAM.get_or_init(|| u64::from_str_radix(std::env::var("XCL_BYTE_STORE_CS").ok()?.trim(), 16).ok()) +} + /// A static sampler of a translated program: (S#, comparison) – see `Translation`. pub type StaticSampler = ([u32; 4], bool); @@ -153,12 +159,19 @@ fn shader_cache() -> &'static Mutex { /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { + let hash = crate::gpu::shader::fnv64(blob); + let windows = if stage == Stage::Compute && windows == (super::HEAP_WINDOWS | 4) && byte_store_program() == Some(hash) + && crate::gpu::dxil::kernel::enabled() && !super::lower_dxil::enabled() + && !crate::hle::d3d12x::console_heap::byte_views_unavailable() + { + windows | super::BYTE_WINDOWS + } else { windows }; let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { return compile_one().map(|(c, _)| c); } let key = ShaderKey { - hash: crate::gpu::shader::fnv64(blob), + hash, stage, sampler_base, windows, @@ -257,6 +270,9 @@ mod translated { Backend::current(), direct_version(crate::gpu::dxil::kernel::TRANSLATOR_VERSION, env!("XCL_DIRECT_DXIL_SOURCE_ID")), ); + let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::declared_lds_enabled() { + identity_for(&id.to_string(), "declared-lds") + } else { id }; // `XCL_DIRECT_COMPACT=0` or `1`: the compact form forced off or on is another output let id = match crate::gpu::dxil::kernel::compact_mode() { Some(on) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }), @@ -507,6 +523,9 @@ mod translated { Some(on) => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }), None => id, }; + let id = if crate::gpu::dxil::kernel::declared_lds_enabled() { + identity_for(&id.to_string(), "declared-lds") + } else { id }; let id = match nest_tag { Some(tag) => identity_for(&id.to_string(), tag), None => id, @@ -597,6 +616,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: Err(e) => direct_fallback("CS", &e), } } + let windows = windows & !super::BYTE_WINDOWS; // `XCL_DIRECT_DXIL=all`: vertex / pixel shaders too (not with the PS debug hooks below) let ps_debug = stage == Stage::Pixel && (debug_color(blob).is_some() || ["XCL_DEBUG_LOD0", "XCL_DEBUG_PS_SUB", "XCL_DEBUG_PS_EXPR"].iter().any(|v| std::env::var_os(v).is_some())); @@ -1652,6 +1672,36 @@ mod shader_cache_tests { std::fs::remove_dir_all(&dir).unwrap(); } + #[test] + fn declared_lds_disk_cache_separates_both_direct_routes() { + const CASE: &str = "XCL_TEST_DECLARED_LDS_CACHE"; + if let Ok(case) = std::env::var(CASE) { + let (marker, expected) = case.split_once(':').unwrap(); + let marker = marker.parse().unwrap(); + let rerouted = !crate::gpu::dxil::kernel::enabled(); + let shader = translated::cached(&dxc::cache_dir(), b"console-lds", Stage::Compute, 0, 1, true, + || Ok((compiled(marker), rerouted))).unwrap(); + assert_eq!(shader.dxil[67], expected.parse::().unwrap()); + return; + } + for direct in ["0", "1"] { + let dir = std::env::temp_dir().join(format!("xcl-declared-lds-{}-{direct}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for (lds, case) in [("0", "1:1"), ("1", "2:2"), ("0", "9:1"), ("1", "9:2")] { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "gpu::recomp::pso::shader_cache_tests::declared_lds_disk_cache_separates_both_direct_routes"]) + .env(CASE, case) + .env("XCL_DXIL_CACHE", &dir) + .env("XCL_TRANSLATED_CACHE", "1") + .env("XCL_DIRECT_DXIL", direct) + .env("XCL_DECLARED_LDS", lds) + .status().unwrap(); + assert!(status.success(), "direct={direct}, declared={lds}, case={case}"); + } + std::fs::remove_dir_all(dir).unwrap(); + } + } + fn key(hash: u64) -> ShaderKey { ShaderKey { hash, diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..0f14b83c22 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5151,7 +5151,7 @@ fn gpu_compute_mode_dispatch_abi() { return; } use super::{dxc, CsInterface}; - let cs = CsInterface { threads: [16, 8, 1], user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2 }; + let cs = CsInterface { threads: [16, 8, 1], user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2, ..Default::default() }; let p = prog(&[ ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 132), ("VSRC1", 1)], None), // y · 16 ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 2), ("VSRC1", 0)], None), // index in group @@ -7297,7 +7297,7 @@ fn gpu_split_wave64_local_and_exchanged_masks_in_diverging_waves() { ]); for dims in [[256u32, 1, 1], [8, 8, 4]] { let threads = dims.iter().product::(); - let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; + let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -7376,7 +7376,7 @@ fn gpu_split_wave64_waves_diverge() { ]); for dims in [[256u32, 1, 1], [64, 1, 1], [8, 8, 4], [16, 4, 1]] { let threads = dims.iter().product::(); - let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; + let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -7454,7 +7454,7 @@ fn bench_split_wave64() { let mut ms = Vec::new(); let mut exchanges = 0; for wave64 in [false, true] { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() }); let t = translate(&p, &opt).unwrap(); // the loop's exchanges: masks read whole (`x64_masks`: not the v_cndmask @@ -7505,7 +7505,7 @@ fn gpu_compute_tg_size_counts_a_partial_last_wave() { ]); for (threads, wave64) in [(96u32, true), (96, false), (64, true), (40, false), (128, true)] { let lanes = if wave64 { 64 } else { 32 }; - let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: true, tid_components: 1 }; + let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: true, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -8907,7 +8907,7 @@ fn gpu_safe_s_barrier_multi_warp_and_early_endpgm() { ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 5), ("SADDR", 0x7D)], None), ]); - let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let base = 0x100usize; let mut io = vec![0u32; 128]; io[0] = base as u32; @@ -9825,7 +9825,7 @@ fn gpu_ps_mask_loop_on_a_primitive_edge_ends() { /// 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 cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; 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(); @@ -9902,7 +9902,7 @@ 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 cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; 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 diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 8341c61ed3..3b0e70e70f 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -575,7 +575,11 @@ impl Uma { match self.kinds[k] { WindowKind::None => k += 1, WindowKind::Committed(s) => { - out.push((self.base + k * WINDOW, s)); + if let Some(segs) = driver_watch_segments(k) { + out.extend(segs); + } else { + out.push((self.base + k * WINDOW, s)); + } k += 1; } WindowKind::Sparse => { @@ -861,6 +865,25 @@ impl Uma { /// The title's graphics memory (created on first use; `XCL_UMA_MB`, default 2048; /// `XCL_UMA_WINDOWS=4|8|16`, default 4, with 8/16 requiring `XCL_HEAP_WINDOWS=1`). +/// Per-window write-watched sub-ranges of mixed driver windows (`XCL_UMA_DRIVER=mixed:...`): only +/// their CUSTOM segments are write-watched, not the GPU_UPLOAD one. +static DRIVER_WATCH_SEGMENTS: Mutex)>> = Mutex::new(Vec::new()); + +/// Window `k` was remade as several driver-heap segments; only `segs` are write-watched. +pub fn set_driver_watch_segments(k: usize, segs: Vec<(usize, usize)>) { + let mut g = DRIVER_WATCH_SEGMENTS.lock().unwrap(); + if let Some(entry) = g.iter_mut().find(|(wk, _)| *wk == k) { + entry.1 = segs; + } else { + g.push((k, segs)); + } +} + +fn driver_watch_segments(k: usize) -> Option> { + let g = DRIVER_WATCH_SEGMENTS.lock().unwrap(); + g.iter().find(|(wk, _)| *wk == k).map(|(_, segs)| segs.clone()) +} + pub fn get() -> Option<&'static Uma> { GLOBAL .get_or_init(|| { diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..37ee46c5c6 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -98,6 +98,19 @@ pub(super) fn forget_list(list: usize) { } } +/// `list` (a closed segment) is parked as a spare: its recording is over and it is reset before +/// it records again, so it no longer holds its allocator. Its last submit stays (`in_flight`) +/// and the allocator's own submit marks still keep it until the GPU is past them. +pub(super) fn park_list(list: usize) { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if let Some(backing) = s.of_list.remove(&list) { + if let Some(b) = s.backings.get_mut(&backing) { + b.users.remove(&list); + } + } +} + /// Reset `list` on the title's allocator `alloc`, committing its new recording association /// only after native Reset succeeds. No pool lock is held across the driver call. pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT { @@ -331,6 +344,24 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu mod tests { use super::*; + /// A parked spare stops holding its allocator: once nothing else records on it and no submit + /// is pending, the allocator is free again. + #[test] + fn a_parked_spare_no_longer_holds_its_allocator() { + let mut ids = Box::new([0u8; 2]); + let alloc = ids.as_mut_ptr() as usize; + let spare = alloc + 1; + created_on(spare, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let held = |l: usize| STATE.lock().unwrap().as_ref().unwrap().backings[&alloc].users.contains(&l); + assert!(held(spare), "the new list records on the allocator"); + park_list(spare); + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(!s.of_list.contains_key(&spare) && unsafe { s.backings[&alloc].free() }, "a parked spare must not pin the allocator"); + drop(g); + ids[0] = 0; + } + #[test] fn a_spare_whose_reset_fails_stays_available_for_retry() { let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize); diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 4862abd84c..a8d58ea4ff 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -170,6 +170,13 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { }; crate::xlog_info!("console descriptor heaps: one shader-visible PC heap of {cap} view descriptors for all of them"); null_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + let mut next = crate::gpu::recomp::BYTE_HEAP_BASE; + if crate::gpu::recomp::pso::byte_store_program().is_some() { + next += crate::gpu::uma::MAX_WINDOWS as u32 * crate::gpu::recomp::BYTE_SEGMENTS; + if next > cap { + return false; + } + } *g = Some(Global { dev: dev.clone(), cpu: heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, @@ -177,8 +184,7 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), heap, cap, - // the memory windows' raw UAVs (`set_window_views`) come first - next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, + next, free: Vec::new(), }); } @@ -210,6 +216,12 @@ unsafe fn null_views(dev: &ID3D12Device, cpu: u64, inc: u32) { } } +static BYTE_VIEWS_UNAVAILABLE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub(crate) fn byte_views_unavailable() -> bool { + BYTE_VIEWS_UNAVAILABLE.load(std::sync::atomic::Ordering::Relaxed) +} + static WINDOW_VIEWS_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Whether the memory windows could not be put in the shared heap (`set_window_views`): @@ -231,6 +243,16 @@ pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) - let s = g.as_ref().unwrap(); (s.dev.clone(), s.cpu, s.inc) }; + let mut bytes_enabled = count == 4 && crate::gpu::recomp::pso::byte_store_program().is_some(); + if bytes_enabled { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UINT; + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: DXGI_FORMAT_R8_UINT, ..Default::default() }; + bytes_enabled = device.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, (&raw mut support).cast(), std::mem::size_of_val(&support) as u32).is_ok() + && support.Support1.contains(D3D12_FORMAT_SUPPORT1_BUFFER | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + && support.Support2.contains(D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE); + BYTE_VIEWS_UNAVAILABLE.store(!bytes_enabled, std::sync::atomic::Ordering::Relaxed); + crate::xlog_info!("byte stores: R8_UINT buffer UAVs available={bytes_enabled}, first slot {}", crate::gpu::recomp::BYTE_HEAP_BASE); + } // The device may be adopted: its UAV hook re-enters descriptor bookkeeping. for k in 0..count { let (raw, bytes) = windows.get(k).copied().filter(|w| w.0 != 0).unwrap_or(windows[0]); @@ -238,6 +260,9 @@ pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) - let Some(r) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + (crate::gpu::recomp::MEM_HEAP_BASE as u64 + k as u64) * inc as u64) as usize }; device.CreateUnorderedAccessView(r, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(bytes as u64)), at); + if bytes_enabled { + set_byte_window_views(&device, r, bytes, cpu, inc, k); + } } true }; @@ -248,6 +273,30 @@ pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) - ok } +/// One typed UAV may address at most 2^27 elements. Empty segments use a null UAV +/// so writes outside the valid bytes have the same bounds as the window's raw view. +unsafe fn set_byte_window_views(dev: &ID3D12Device, resource: &ID3D12Resource, bytes: usize, cpu: u64, inc: u32, window: usize) { + use crate::gpu::recomp::{BYTE_HEAP_BASE, BYTE_SEGMENTS, BYTE_SEGMENT_SHIFT}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UINT; + let raw = crate::gpu::recomp::runner::raw_window_uav(bytes as u64); + let size = u64::from(raw.Anonymous.Buffer.NumElements) * 4; + let segment = 1u64 << BYTE_SEGMENT_SHIFT; + for part in 0..BYTE_SEGMENTS { + let offset = u64::from(part) * segment; + let len = size.saturating_sub(offset).min(segment); + let slot = BYTE_HEAP_BASE + window as u32 * BYTE_SEGMENTS + part; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + u64::from(slot) * u64::from(inc)) as usize }; + let view = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R8_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Buffer: D3D12_BUFFER_UAV { + FirstElement: if len > 0 { offset } else { 0 }, NumElements: len.max(1) as u32, ..Default::default() + } }, + }; + dev.CreateUnorderedAccessView((len > 0).then_some(resource), None::<&ID3D12Resource>, Some(&view), at); + } +} + /// `count` descriptors of the shared heap: the index of the first. None: no shared heap, or /// no room left in it. fn reserve_global(count: u32) -> Option { diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 0b20bfbd6a..b0234b0e08 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -92,6 +92,7 @@ fn worker() -> &'static Mutex> { unsafe fn write_now(va: usize, words: &[u32]) { let bytes = 4 * words.len(); if !crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { + let _trap = super::watch_trap::guard(va, bytes); use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { @@ -115,6 +116,7 @@ unsafe fn u64_writable_now(va: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, 8)) { return true; } + let _trap = super::watch_trap::guard(va, 8); use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); if VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { @@ -147,6 +149,7 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { return true; } crate::hle::kernelx::lazy::ensure(va, bytes); + let _trap = super::watch_trap::guard(va, bytes); use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..0ae0f8c803 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3377,6 +3377,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { for seg in reclaimed { super::bind::reset(seg as *mut c_void, 0, 0); clear_segment_state(seg); + // a spare now: it does not hold its allocator until it records again (after both + // submits above, so the allocator keeps their marks) + super::alloc_pool::park_list(seg); } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) { s.allocator = alloc; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index b7c2e38c14..0f214f1c54 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -34,6 +34,7 @@ pub mod title_list; pub mod title_textures; mod uma_driver; pub mod vram; +pub mod watch_trap; use std::ffi::c_void; use std::sync::OnceLock; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 19eedfe6ac..ec65f634c9 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -171,7 +171,21 @@ pub fn abi_root_signature() -> Option { /// lifetime. static UMA_BUFFER: Mutex> = Mutex::new(Vec::new()); /// the committed UMA windows opened as D3D12 heaps (indexed by window `k`; `None` for sparse windows) -static UMA_HEAPS: Mutex>> = Mutex::new(Vec::new()); +/// Window heaps for `CreatePlacedResource` inside coherent UMA windows: for each window `k`, +/// contiguous `(seg_offset, seg_len, heap_raw)` segments (1 entry for single-heap windows, N for +/// `XCL_UMA_DRIVER=mixed:...`). +static UMA_HEAPS: Mutex>> = Mutex::new(Vec::new()); + +fn uma_heap_for(k: usize, offset: usize, len: usize) -> Option<(usize, usize)> { + let g = UMA_HEAPS.lock().unwrap(); + let segs = g.get(k)?; + for &(seg_off, seg_len, heap_raw) in segs { + if offset >= seg_off && offset.saturating_add(len) <= seg_off.saturating_add(seg_len) { + return Some((heap_raw, offset - seg_off)); + } + } + None +} /// console buffers placed in unified memory: resource → (address, bytes) /// address, bytes, whether XCL allocated the memory (not: the title's own, CreatePlacedResourceX) type UmaBuffer = (usize, usize, bool); @@ -303,13 +317,16 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { *UMA_ERROR.lock().unwrap() = "no UMA region".into(); return; }; - let open = |k: usize| -> Result<(usize, u64, usize), String> { + let open = |k: usize| -> Result<(usize, u64, Vec<(usize, usize, usize)>), String> { let (base, size) = u.window(k); if allow_driver_remap && super::uma_driver::wanted(device) { - match super::uma_driver::remake(device, base, size) { - Ok((heap, buf)) => { + match super::uma_driver::remake_window(device, base, size) { + Ok(remade) => { u.set_driver_window(k); - return Ok(super::uma_driver::raw(heap, buf)); + if let Some(segs) = remade.watched_regions { + crate::gpu::uma::set_driver_watch_segments(k, segs); + } + return Ok((remade.buf_raw, remade.gpu_va, remade.heaps)); } Err(e) => crate::xlog_warn!("D3D12.X: coherent window {k} stays imported: {e}"), } @@ -331,19 +348,19 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { 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)) + Ok((buf.into_raw() as usize, va, vec![(0, size, heap.into_raw() as usize)])) }; let n = u.shader_windows(); let mut bufs: Vec<(usize, u64)> = vec![(0, 0); n]; - let mut heaps: Vec> = vec![None; n]; + let mut heaps: Vec> = vec![Vec::new(); n]; for k in 0..n { if !u.is_committed_window(k) { continue; } match open(k) { - Ok((buf_raw, va, heap_raw)) => { + Ok((buf_raw, va, win_heaps)) => { bufs[k] = (buf_raw, va); - heaps[k] = Some(heap_raw); + heaps[k] = win_heaps; } Err(e) => { crate::xlog_warn!("D3D12.X: UMA not available to the GPU: {e}"); @@ -1353,6 +1370,27 @@ const COHERENT_FLOOR: usize = 16 << 20; /// committed textures leave (`COHERENT_KEPT`) is kept for these: with the textures at that /// limit (Unicorn Overlord's), a second 128 MB of headroom sent every readback buffer to the /// sparse windows. +/// A block of `size` bytes from `u` that one heap holds (`heap_of(p)`). A block across two +/// segments of a mixed window has none: it is held while the next fit is tried (which then starts +/// past it), and given back either way. +fn alloc_in_one_heap(u: &crate::gpu::uma::Uma, size: usize, heap_of: impl Fn(usize) -> Option) -> Option<(usize, T)> { + let mut held = Vec::new(); + let found = loop { + let Some(p) = u.alloc(size, 0x1_0000).map(|a| a as usize) else { break None }; + if let Some(h) = heap_of(p) { + break Some((p, h)); + } + held.push(p); + if held.len() == 4 { + break None; + } + }; + for p in held { + u.free(p); + } + found +} + fn has_coherent_headroom(u: &crate::gpu::uma::Uma, rounded: usize) -> bool { u.size().saturating_sub(u.used()) >= COHERENT_FLOOR.min(u.size() / 8).saturating_add(rounded) } @@ -1441,17 +1479,16 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta return Some(hr); } } - let Some(p) = u.alloc(rounded, 0x1_0000).map(|a| a as usize) else { + let heap_of = |p: usize| u.window_of(p).and_then(|k| uma_heap_for(k, p - u.window(k).0, rounded).map(|h| (k, h))); + let Some((p, (k, (heap, heap_off)))) = alloc_in_one_heap(u, rounded, heap_of) else { if prefer_coherent && u.has_sparse() { return place_console_buffer_sparse(this, &d, bytes, st, readback_on_null_map, riid, ppv); } return None; }; // the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + sanitized flags & state - let k = u.window_of(p)?; let (d, st) = sanitize_coherent_buffer(&d, state, !u.is_driver_window(k)); - let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; - let hr = dev_create_placed_resource(this, heap, p - u.window(k).0, &d as *const _ as usize, st as usize, clear, riid, ppv); + let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, st as usize, clear, riid, ppv); if hr < 0 || (*ppv).is_null() { u.free(p); static ONCE: AtomicU64 = AtomicU64::new(0); @@ -1505,14 +1542,14 @@ 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)?)?; + let (heap, heap_off) = uma_heap_for(k, start - base, delta + bytes)?; if !u.is_driver_window(k) { d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; d.Width = (delta + bytes) as u64; - let hr = dev_create_placed_resource(this, heap, start - base, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); + let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); if hr < 0 || (*ppv).is_null() { return None; } @@ -9159,3 +9196,27 @@ void main() { } } + +#[cfg(test)] +mod uma_heap_tests { + use super::*; + + /// A console buffer whose first fit crosses two segments of a mixed window goes to the next + /// fit, and the crossing block is given back (it stayed charged to the window). + #[test] + fn a_block_across_two_segments_is_given_back_and_the_next_fit_used() { + let u = crate::gpu::uma::Uma::with_windows(1, 4 << 20).expect("one UMA window"); + let (w0, _) = u.window(0); + let first = u.alloc(960 << 10, 0x1_0000).expect("first block") as usize; + assert_eq!(first, w0); + let used = u.used(); + let boundary = w0 + (1 << 20); + let heap_of = |p: usize| (p + (128 << 10) <= boundary || p >= boundary).then_some(()); + let (p, ()) = alloc_in_one_heap(&u, 128 << 10, heap_of).expect("a block in one segment"); + assert_eq!(p, w0 + (1088 << 10)); + assert_eq!(u.used(), used + (128 << 10)); + assert_eq!(u.alloc(64 << 10, 0x1_0000).map(|a| a as usize), Some(w0 + (960 << 10))); + assert!(alloc_in_one_heap(&u, 64 << 10, |_| None::<()>).is_none()); + assert_eq!(u.used(), used + (192 << 10)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b7560f861e..7df18978c8 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1327,6 +1327,7 @@ pub unsafe fn committed(a: usize, n: usize) { if n == 0 { return; } + super::watch_trap::changed(a, n); let mut g = lock_state(); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); @@ -1343,6 +1344,7 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } + super::watch_trap::changed(a, n); let mut g = lock_state(); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index a41e5643fc..1cd53cb486 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -194,6 +194,13 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: for seg in moved { super::bind::reset(seg as *mut c_void, 0, 0); super::list_x::clear_segment_state(seg); + // a spare records again only after its next Reset: it does not hold its + // allocator meanwhile + super::alloc_pool::park_list(seg); + } + // nor does the previous recording a stand-in now replaces: it is not reset here either + if stand_in.is_some() { + super::alloc_pool::park_list(primary as usize); } } *((this as usize + F_RING_AT) as *mut usize) = 0; diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index a33d3c7e6e..bc9d4ded35 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -746,11 +746,18 @@ unsafe fn refresh_once(queue: *mut c_void) { if buf.len() < 16384 { buf.resize(16384, std::ptr::null_mut()); } - for &(base, size) in ranges.iter() { - take_written(base, size, &mut buf, &mut dirty, &mut page); + if super::watch_trap::on() { + let mut p = page; + super::watch_trap::look(&ranges, &mut dirty, 0x1000, |a, n, d| take_written(a, n, &mut buf, d, &mut p)); + page = p; + } else { + for &(base, size) in ranges.iter() { + take_written(base, size, &mut buf, &mut dirty, &mut page); + } } }); dirty.sort_unstable(); + dirty.dedup(); dirty.len() }); super::sparse::note_watch(watch_t0.elapsed(), dirty_len); @@ -1494,6 +1501,11 @@ const TITLE_BYTES_KEPT: usize = 64 << 20; /// thread – the title can decommit its other memory from another thread at any moment, and a /// read in place then faults. unsafe fn with_title_bytes(at: usize, len: usize, f: impl FnOnce(&[u8]) -> R) -> R { + // a GPU_UPLOAD segment of a mixed driver window: by the GPU's copy (CPU reads of that video + // memory through the BAR are slow) + if let Some(bytes) = super::uma_driver::read_vram_bytes(at, len) { + return f(&bytes); + } if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { return f(std::slice::from_raw_parts(at as *const u8, len)); } diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs index e68ac4d994..a839724617 100644 --- a/crates/xcl/src/hle/d3d12x/uma_driver.rs +++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs @@ -9,9 +9,21 @@ //! stays in `Uma::watch_regions` and the title's CPU writes reach its textures as before; a driver //! that refuses it, or whose mapping `GetWriteWatch` cannot read, keeps the import. //! -//! `XCL_UMA_DRIVER`: `custom` or `1` on, `0` off; unset: on for an NVIDIA adapter outside Wine. +//! +//! `mixed::[,...]` makes the window several driver heaps instead of one: each +//! range a `GPU_UPLOAD` heap (video memory the CPU writes through the BAR; on NVIDIA it stays in +//! video memory up to 2 GiB) and the rest CUSTOM write-back L0 heaps, each segment's CPU mapping at +//! its place in the window and one reserved buffer over all of them on the GPU +//! (`UpdateTileMappings`). The `GPU_UPLOAD` segments are not write-watched (write-combined pages +//! refuse the watch trap's read-only protection); the title texture code reads them through a copy +//! on the GPU (`read_vram_bytes`). +//! +//! `XCL_UMA_DRIVER`: `custom` or `1` on, `mixed:...` on with the ranges above, `0` off; unset: on +//! (one CUSTOM heap) for an NVIDIA adapter outside Wine. use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -21,6 +33,7 @@ use windows_sys::Win32::System::Memory::{ }; const MEM_WRITE_WATCH: u32 = 0x20_0000; +const TILE: usize = 0x1_0000; #[link(name = "kernel32")] extern "system" { @@ -36,11 +49,32 @@ pub(super) fn wanted(device: &ID3D12Device) -> bool { fn decide(switch: Option<&str>, wine: impl FnOnce() -> bool, vendor: impl FnOnce() -> Option) -> bool { match switch.map(str::trim) { Some("custom" | "1") => true, + Some(s) if s.starts_with("mixed:") => true, Some("0") => false, _ => !wine() && vendor() == Some(0x10DE), } } +/// `XCL_UMA_DRIVER=mixed::[,...]`: the window's `GPU_UPLOAD` ranges +/// `(start, len)` in bytes, in order; None for any other value. +fn mixed_ranges() -> Option> { + parse_mixed(&std::env::var("XCL_UMA_DRIVER").ok()?) +} + +fn parse_mixed(raw: &str) -> Option> { + let list = raw.trim().strip_prefix("mixed:")?; + let mut ranges = Vec::new(); + for part in list.split(',') { + let (a, b) = part.trim().split_once(':')?; + let (start_mb, size_mb): (usize, usize) = (a.trim().parse().ok()?, b.trim().parse().ok()?); + if size_mb != 0 { + ranges.push((start_mb << 20, size_mb << 20)); + } + } + ranges.sort_by_key(|r| r.0); + (!ranges.is_empty()).then_some(ranges) +} + /// PCI vendor id of `device`'s adapter. fn vendor(device: &ID3D12Device) -> Option { use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; @@ -80,6 +114,11 @@ unsafe fn written_pages(base: usize, size: usize) -> Result) /// Reserves every free stretch of 1 GiB or more (but its first 256 MiB, room for the driver's own /// small mappings) outside `[hole, hole + len)`. unsafe fn groom(hole: usize, len: usize) -> Vec { + groom_with(hole, len, 1 << 30, 256 << 20) +} + +/// `groom` for stretches of `min_region` or more, leaving `headroom` at the start of each. +unsafe fn groom_with(hole: usize, len: usize, min_region: usize, headroom: usize) -> Vec { let (top, mut a, mut got) = (0x7FFF_FFFE_0000usize, 0x1_0000usize, Vec::new()); while a < top { let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); @@ -88,10 +127,10 @@ unsafe fn groom(hole: usize, len: usize) -> Vec { } let (base, end) = (m.BaseAddress as usize, (m.BaseAddress as usize + m.RegionSize).min(top)); a = end; - if m.State != MEM_FREE || m.RegionSize < 1 << 30 { + if m.State != MEM_FREE || m.RegionSize < min_region { continue; } - let s = ((base + 0xFFFF) & !0xFFFF) + (256 << 20); + let s = ((base + 0xFFFF) & !0xFFFF).saturating_add(headroom); for (s, e) in [(s, end.min(hole)), (s.max(hole + len), end)] { let mut s = s; while s < e { @@ -219,15 +258,420 @@ unsafe fn remake_with_after_release( } } -/// `heap` and `buf` as the raw pointers `open_uma` keeps. -pub(super) fn raw(heap: ID3D12Heap, buf: ID3D12Resource) -> (usize, u64, usize) { - let va = unsafe { buf.GetGPUVirtualAddress() }; - (buf.into_raw() as usize, va, heap.into_raw() as usize) +/// A coherent window remade as driver heap(s): the buffer shaders bind, the heaps `(offset, len, +/// heap)` that resources placed in the window go to, and the write-watched parts `(va, len)` when +/// they are not the whole window (a mixed window's CUSTOM segments). +pub(super) struct Remade { + pub buf_raw: usize, + pub gpu_va: u64, + pub heaps: Vec<(usize, usize, usize)>, + pub watched_regions: Option>, +} + +/// `remake`, or `remake_mixed` with `XCL_UMA_DRIVER=mixed:...`. +pub(super) unsafe fn remake_window(device: &ID3D12Device, base: usize, size: usize) -> Result { + if let Some(ranges) = mixed_ranges() { + if gpu_upload_heaps(device) { + return remake_mixed(device, base, size, &ranges); + } + crate::xlog_warn!("D3D12.X: XCL_UMA_DRIVER=mixed: the adapter has no GPU_UPLOAD heaps (Resizable BAR off?), so the coherent window is one CUSTOM heap"); + } + let (heap, buf) = remake(device, base, size)?; + let gpu_va = buf.GetGPUVirtualAddress(); + Ok(Remade { buf_raw: buf.into_raw() as usize, gpu_va, heaps: vec![(0, size, heap.into_raw() as usize)], watched_regions: None }) +} + +/// Whether the adapter makes `GPU_UPLOAD` heaps (`D3D12_OPTIONS16`; needs Resizable BAR). Asked +/// before the window is released: a segment's mapping stays with the driver after its heap is +/// dropped, so a window cannot be made whole again once a segment has been mapped. +unsafe fn gpu_upload_heaps(device: &ID3D12Device) -> bool { + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS16, &mut opts as *mut _ as *mut c_void, std::mem::size_of::() as u32) + .is_ok() + && opts.GPUUploadHeapSupported.as_bool() +} + +#[cfg(test)] +thread_local! { + /// tests: `mapped_segment` refuses `GPU_UPLOAD` heaps on this thread + static REFUSE_GPU_UPLOAD: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +fn heap_props(upload: bool) -> D3D12_HEAP_PROPERTIES { + if upload { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_GPU_UPLOAD, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + } + } +} + +fn buffer_desc(size: usize) -> D3D12_RESOURCE_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, + ..Default::default() + } +} + +/// One segment of a mixed window: a heap of `size` bytes (write-watched when `watch`), a buffer +/// over all of it and where the driver mapped it for the CPU. +unsafe fn mapped_segment(device: &ID3D12Device, size: usize, upload: bool, watch: bool) -> Result<(ID3D12Heap, ID3D12Resource, usize), String> { + #[cfg(test)] + if upload && REFUSE_GPU_UPLOAD.with(|r| r.get()) { + return Err("CreateHeap: refused by the test".into()); + } + let flags = if watch { D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH } else { D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; + let desc = D3D12_HEAP_DESC { SizeInBytes: size as u64, Properties: heap_props(upload), Alignment: 0x1_0000, Flags: flags }; + let mut heap: Option = None; + device.CreateHeap(&desc, &mut heap).map_err(|e| format!("CreateHeap{}: {e}", if watch { " (write-watched)" } else { "" }))?; + let heap = heap.ok_or("CreateHeap")?; + let mut buf: Option = None; + device.CreatePlacedResource(&heap, 0, &buffer_desc(size), D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; + let buf = buf.ok_or("CreatePlacedResource")?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, Some(&D3D12_RANGE::default()), Some(&mut p)).map_err(|e| format!("Map: {e}"))?; + Ok((heap, buf, p as usize)) +} + +/// `[0, size)` as contiguous `(offset, len, upload)` segments: `vram_ranges` (sorted) on 64 KiB +/// tiles as `GPU_UPLOAD` segments, the rest CUSTOM. +fn build_segments(size: usize, vram_ranges: &[(usize, usize)]) -> Result, String> { + let mut segs = Vec::new(); + let mut cur = 0usize; + for &(start, len) in vram_ranges { + let s = start.min(size) & !(TILE - 1); + let e = start.saturating_add(len).min(size) & !(TILE - 1); + if e <= s { + continue; + } + if s < cur { + return Err(format!("overlapping mixed ranges at {s:#x} < {cur:#x}")); + } + if s > cur { + segs.push((cur, s - cur, false)); + } + segs.push((s, e - s, true)); + cur = e; + } + if cur < size { + segs.push((cur, size - cur, false)); + } + if !segs.iter().any(|s| s.2) { + return Err("no GPU_UPLOAD range inside the window".into()); + } + Ok(segs) +} + +/// The window could not be made again at its address after it was released: the title's memory +/// there is gone, so the process stops before guest code uses it (as `remake` does). +unsafe fn stop_unbacked(base: usize, size: usize, got: *mut c_void, why: &str) -> ! { + let os_error = windows_sys::Win32::Foundation::GetLastError(); + crate::xlog_error!( + "D3D12.X: coherent window could not be restored at {base:#x} ({size} bytes, got {got:?}, Windows error {os_error}) after {why}; stopping before guest memory is used" + ); + crate::log::flush(); + windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), 0x7C1_0003); + std::process::abort(); +} + +/// `remake` with `XCL_UMA_DRIVER=mixed:...`: the window as one driver heap per segment +/// (`build_segments`), each mapped for the CPU at its place in the window, and one reserved buffer +/// over the window whose tiles map to the segments' heaps. The CUSTOM segments are write-watched +/// (a segment that refuses it fails the remake); the `GPU_UPLOAD` ones are not, and are read +/// through `read_vram_bytes`. On failure the window is the title's memory again, its pages as they +/// were. +unsafe fn remake_mixed(device: &ID3D12Device, base: usize, size: usize, vram_ranges: &[(usize, usize)]) -> Result { + let t0 = std::time::Instant::now(); + let spec = build_segments(size, vram_ranges)?; + let min_seg = spec.iter().map(|s| s.1).min().unwrap_or(64 << 20); + let pages = written_pages(base, size)?; + let kept: usize = pages.iter().map(|p| p.1.len()).sum(); + if VirtualFree(base as *mut c_void, 0, MEM_RELEASE) == 0 { + return Err(format!("VirtualFree of the window at {base:#x} failed")); + } + let restore = |why: String, placed: Vec<(usize, usize, bool, ID3D12Heap, ID3D12Resource)>, placeholders: Vec| -> String { + for (_, _, _, h, b) in placed { + b.Unmap(0, None); + drop((b, h)); + } + for p in placeholders { + if p != 0 { + VirtualFree(p as *mut c_void, 0, MEM_RELEASE); + } + } + let p = VirtualAlloc(base as *const c_void, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE); + if p as usize != base { + stop_unbacked(base, size, p, &why); + } + for (a, bytes) in &pages { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), *a as *mut u8, bytes.len()); + } + why + }; + + // every segment's place reserved on its own, so one segment's mapping cannot land in another's + let mut placeholders: Vec = Vec::with_capacity(spec.len()); + for &(off, len, _) in &spec { + let want = base + off; + let p = VirtualAlloc(want as *const c_void, len, MEM_RESERVE, PAGE_NOACCESS); + if p as usize != want { + if !p.is_null() { + VirtualFree(p, 0, MEM_RELEASE); + } + return Err(restore(format!("placeholder reserve at {want:#x} ({} MB) got {p:?}", len >> 20), Vec::new(), placeholders)); + } + placeholders.push(want); + } + + // every free stretch of `min_seg` or more outside the window reserved, but 16 MiB at its start + // for the driver's own small mappings + let groomed = groom_with(base, size, min_seg, (16 << 20).min(min_seg / 4)); + let reservations = groomed.len(); + let readable = |at: usize, len: usize| { + let (mut one, mut n, mut page) = ([std::ptr::null_mut::(); 1], 1usize, 0u32); + GetWriteWatch(0, at as *const c_void, len, one.as_mut_ptr(), &mut n, &mut page) == 0 + }; + let mut placed: Vec<(usize, usize, bool, ID3D12Heap, ID3D12Resource)> = Vec::with_capacity(spec.len()); + let mut fail: Option = None; + for (idx, &(off, len, upload)) in spec.iter().enumerate() { + let want = base + off; + let ph = std::mem::replace(&mut placeholders[idx], 0); + if VirtualFree(ph as *mut c_void, 0, MEM_RELEASE) == 0 { + fail = Some(format!("VirtualFree of the placeholder at {want:#x} failed")); + break; + } + // (no write watch on GPU_UPLOAD: its write-combined pages refuse the watch trap's + // read-only protection, which then retried tens of thousands of times) + let mut made = mapped_segment(device, len, upload, !upload); + let mut upload = upload; + if upload && !matches!(&made, Ok((_, _, p)) if *p == want) { + // a refused GPU_UPLOAD segment becomes a CUSTOM one: the segments mapped so far cannot + // be given back (their mappings stay with the driver), so the window is kept whole + let why = match &made { + Ok((_, _, p)) => format!("Map gave {p:#x}"), + Err(e) => e.clone(), + }; + if let Ok((heap, buf, _)) = std::mem::replace(&mut made, Err(String::new())) { + buf.Unmap(0, None); + drop((buf, heap)); + } + crate::xlog_warn!("D3D12.X: XCL_UMA_DRIVER=mixed: segment {idx} ({} MB GPU_UPLOAD): {why}; it is a CUSTOM write-watched heap instead", len >> 20); + upload = false; + made = mapped_segment(device, len, false, true); + } + let what = if upload { "GPU_UPLOAD" } else { "CUSTOM" }; + match made { + Ok((heap, buf, p)) if p == want && (upload || readable(want, len)) => placed.push((off, len, upload, heap, buf)), + Ok((heap, buf, p)) => { + buf.Unmap(0, None); + drop((buf, heap)); + fail = Some(if p == want { + format!("segment {idx} ({} MB {what}): GetWriteWatch cannot read its mapping", len >> 20) + } else { + format!("segment {idx} ({} MB {what}): Map gave {p:#x}, wanted {want:#x}", len >> 20) + }); + break; + } + Err(e) => { + fail = Some(format!("segment {idx} ({} MB {what}): {e}", len >> 20)); + break; + } + } + } + ungroom(groomed); + if let Some(why) = fail { + return Err(restore(why, placed, placeholders)); + } + + // one reserved buffer over the window, its 64 KiB tiles mapped onto the segments' heaps + let reserved = (|| -> Result { + let mut res: Option = None; + device.CreateReservedResource(&buffer_desc(size), D3D12_RESOURCE_STATE_COMMON, None, &mut res).map_err(|e| format!("CreateReservedResource: {e}"))?; + let res = res.ok_or("CreateReservedResource")?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .map_err(|e| format!("CreateCommandQueue: {e}"))?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| format!("CreateFence: {e}"))?; + for (off, len, _, heap, _) in &placed { + let count = (*len / TILE) as u32; + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: (*off / TILE) as u32, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: count, UseBox: false.into(), ..Default::default() }; + let flag = D3D12_TILE_RANGE_FLAG_NONE; + queue.UpdateTileMappings(&res, 1, Some(&coord), Some(®ion), heap, 1, Some(&flag), Some(&0u32), Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); + } + queue.Signal(&fence, 1).map_err(|e| format!("Signal: {e}"))?; + crate::gpu::fence::wait(&fence, 1, device, None, 2000).map_err(|e| format!("tile mapping wait: {e}"))?; + Ok(res) + })(); + let res = match reserved { + Ok(r) => r, + Err(why) => return Err(restore(why, placed, placeholders)), + }; + + for (a, bytes) in &pages { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), *a as *mut u8, bytes.len()); + } + let mut parts = Vec::with_capacity(placed.len()); + let mut heaps = Vec::with_capacity(placed.len()); + let mut watched = Vec::new(); + let heaps_upload: Vec<(usize, usize)> = placed.iter().filter(|p| p.2).map(|p| (p.0, p.1)).collect(); + for (off, len, upload, heap, placed_buf) in placed { + parts.push(format!("{off:#x}+{}MB {}", len >> 20, if upload { "GPU_UPLOAD" } else { "CUSTOM, write-watched" })); + if !upload { + watched.push((base + off, len)); + } + heaps.push((off, len, heap.into_raw() as usize)); + // the segment's CPU mapping lives as long as its buffer: kept for the process + std::mem::forget(placed_buf); + } + crate::xlog_info!( + "D3D12.X: the coherent window at {base:#x} ({} MB) is mixed driver heaps mapped at its address [{}] ({reservations} reservations, {} pages kept, {} KB, {} ms)", + size >> 20, + parts.join(", "), + pages.len(), + kept >> 10, + t0.elapsed().as_millis() + ); + let vram: Vec<(usize, usize)> = heaps_upload.iter().map(|&(off, len)| (base + off, base + off + len)).collect(); + if !vram.is_empty() { + init_vram_reader(device, base, size, &res, vram); + } + let gpu_va = res.GetGPUVirtualAddress(); + Ok(Remade { buf_raw: res.into_raw() as usize, gpu_va, heaps, watched_regions: Some(watched) }) +} + +static VRAM_READER_ACTIVE: AtomicBool = AtomicBool::new(false); +static VRAM_READER: Mutex> = Mutex::new(None); + +/// Reads the `GPU_UPLOAD` segments of a mixed window by a copy on the GPU into a readback buffer. +struct VramReader { + window_base: usize, + window_end: usize, + vram_ranges: Vec<(usize, usize)>, + device: ID3D12Device, + src_buf: ID3D12Resource, + queue: ID3D12CommandQueue, + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + fence_val: u64, + readback: ID3D12Resource, + readback_ptr: *mut u8, + readback_cap: usize, +} + +unsafe impl Send for VramReader {} + +unsafe fn make_readback(device: &ID3D12Device, cap: usize) -> Result<(ID3D12Resource, *mut u8), String> { + let mut rb: Option = None; + let desc = D3D12_RESOURCE_DESC { Flags: D3D12_RESOURCE_FLAG_NONE, ..buffer_desc(cap) }; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .map_err(|e| format!("readback CreateCommittedResource({cap}): {e}"))?; + let rb = rb.ok_or("readback")?; + let mut p: *mut c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).map_err(|e| format!("readback Map: {e}"))?; + Ok((rb, p as *mut u8)) +} + +unsafe fn init_vram_reader(device: &ID3D12Device, window_base: usize, window_size: usize, src_buf: &ID3D12Resource, vram_ranges: Vec<(usize, usize)>) { + let made = (|| -> Result { + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() }) + .map_err(|e| format!("copy queue: {e}"))?; + let alloc: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).map_err(|e| format!("copy allocator: {e}"))?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &alloc, None).map_err(|e| format!("copy list: {e}"))?; + list.Close().map_err(|e| format!("copy list Close: {e}"))?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| format!("copy fence: {e}"))?; + let cap = 32 << 20; + let (readback, readback_ptr) = make_readback(device, cap)?; + Ok(VramReader { + window_base, + window_end: window_base + window_size, + vram_ranges, + device: device.clone(), + src_buf: src_buf.clone(), + queue, + alloc, + list, + fence, + fence_val: 0, + readback, + readback_ptr, + readback_cap: cap, + }) + })(); + match made { + Ok(r) => { + *VRAM_READER.lock().unwrap() = Some(r); + VRAM_READER_ACTIVE.store(true, Ordering::Release); + } + Err(e) => crate::xlog_warn!("D3D12.X: no GPU reader for the mixed window's GPU_UPLOAD segments ({e}): they are read through the BAR"), + } +} + +/// `[at, at + len)` read by a copy on the GPU (`CopyBufferRegion` to a readback buffer) where it +/// overlaps a `GPU_UPLOAD` segment of a mixed window: CPU reads of that video memory through the +/// BAR ran at 12-84 MiB/s. None where it does not. +pub(super) unsafe fn read_vram_bytes(at: usize, len: usize) -> Option> { + if len == 0 || !VRAM_READER_ACTIVE.load(Ordering::Acquire) { + return None; + } + let mut g = VRAM_READER.lock().unwrap(); + let r = g.as_mut()?; + let end = at.checked_add(len)?; + if at < r.window_base || end > r.window_end || !r.vram_ranges.iter().any(|&(s, e)| at < e && end > s) { + return None; + } + if len > r.readback_cap { + let cap = len.next_power_of_two().max(32 << 20); + let (rb, ptr) = make_readback(&r.device, cap).ok()?; + r.readback.Unmap(0, None); + r.readback = rb; + r.readback_ptr = ptr; + r.readback_cap = cap; + } + r.alloc.Reset().ok()?; + r.list.Reset(&r.alloc, None).ok()?; + r.list.CopyBufferRegion(&r.readback, 0, &r.src_buf, (at - r.window_base) as u64, len as u64); + r.list.Close().ok()?; + let cl: ID3D12CommandList = r.list.cast().ok()?; + r.queue.ExecuteCommandLists(&[Some(cl)]); + r.fence_val += 1; + r.queue.Signal(&r.fence, r.fence_val).ok()?; + crate::gpu::fence::wait(&r.fence, r.fence_val, &r.device, None, 5000).ok()?; + let mut out = vec![0u8; len]; + std::ptr::copy_nonoverlapping(r.readback_ptr, out.as_mut_ptr(), len); + Some(out) } #[cfg(test)] mod tests { - use super::decide; + use super::{build_segments, decide, parse_mixed}; + + /// The tests that remake a mixed window run one at a time: a remake reserves the process's other + /// free stretches so that the driver maps each segment at its place, and another remake releasing + /// its reservations meanwhile lets a segment land elsewhere, which stops the process. + static MIXED_REMAKE: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// On by default for NVIDIA outside Wine only; the switch overrides either way. #[test] @@ -239,6 +683,130 @@ mod tests { assert!(!decide(Some("0"), || false, || Some(0x10DE))); assert!(decide(Some("custom"), || true, || Some(0x1002))); assert!(decide(Some(" 1 "), || false, || None)); + assert!(decide(Some("mixed:1536:1792"), || true, || Some(0x1002))); + } + + #[test] + fn mixed_ranges_parse_in_order() { + assert_eq!(parse_mixed("mixed:1536:1792"), Some(vec![(1536 << 20, 1792 << 20)])); + assert_eq!(parse_mixed(" mixed:2048:512,512:256 "), Some(vec![(512 << 20, 256 << 20), (2048 << 20, 512 << 20)])); + assert_eq!(parse_mixed("mixed:0:0"), None); + assert_eq!(parse_mixed("mixed:12"), None); + assert_eq!(parse_mixed("custom"), None); + } + + #[test] + fn mixed_segments_cover_the_window() { + let segs = build_segments(4095 << 20, &[(1536 << 20, 1792 << 20)]).unwrap(); + assert_eq!(segs, vec![(0, 1536 << 20, false), (1536 << 20, 1792 << 20, true), (3328 << 20, 767 << 20, false)]); + assert!(build_segments(256 << 20, &[(512 << 20, 64 << 20)]).is_err()); + assert!(build_segments(256 << 20, &[(0, 128 << 20), (64 << 20, 64 << 20)]).is_err()); + } + + /// A mixed window keeps the title's bytes in every segment, and the GPU reads the CPU's later + /// writes to each segment through the one reserved buffer; `read_vram_bytes` reads only the + /// `GPU_UPLOAD` segment. + #[test] + fn mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let _alone = MIXED_REMAKE.lock().unwrap_or_else(|e| e.into_inner()); + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + let dev = dev.unwrap(); + if !unsafe { gpu_upload_heaps(&dev) } { + return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heaps"); + } + unsafe { + let size = 256 << 20; + let base = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let at = [0x1000, (64 << 20) + 0x1000, (192 << 20) + 0x1000]; + for (i, &o) in at.iter().enumerate() { + std::ptr::write_volatile((base + o) as *mut u32, 0x1111_0000 + i as u32); + } + let remade = match remake_mixed(&dev, base, size, &[(64 << 20, 128 << 20)]) { + Ok(r) => r, + Err(e) if e.contains("CreateHeap") => return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heaps"), + Err(e) => panic!("remake_mixed: {e}"), + }; + assert_eq!(remade.heaps.len(), 3); + assert_eq!(remade.watched_regions, Some(vec![(base, 64 << 20), (base + (192 << 20), 64 << 20)])); + for (i, &o) in at.iter().enumerate() { + assert_eq!(std::ptr::read_volatile((base + o) as *const u32), 0x1111_0000 + i as u32); + std::ptr::write_volatile((base + o + 0x1000) as *mut u32, 0xCAFE_0000 + i as u32); + } + let queue: 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: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (rb, ptr) = make_readback(&dev, 256).unwrap(); + let raw = remade.buf_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&raw).unwrap(); + for (i, &o) in at.iter().enumerate() { + list.CopyBufferRegion(&rb, 4 * i as u64, src, (o + 0x1000) as u64, 4); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap(); + assert_eq!(std::slice::from_raw_parts(ptr as *const u32, 3), &[0xCAFE_0000, 0xCAFE_0001, 0xCAFE_0002]); + assert!(read_vram_bytes(base + at[0] + 0x1000, 4).is_none()); + let got = read_vram_bytes(base + at[1] + 0x1000, 4).expect("read of the GPU_UPLOAD segment"); + assert_eq!(u32::from_le_bytes(got.try_into().unwrap()), 0xCAFE_0001); + } + } + + /// A `GPU_UPLOAD` segment refused after a CUSTOM one was mapped (an adapter without Resizable + /// BAR, or one out of BAR space): the window stays whole, that segment a write-watched CUSTOM + /// heap. (It stopped the process: the mapped segment's pages stay with the driver after its + /// heap is dropped, so the window could not be reserved again.) + #[test] + fn a_refused_gpu_upload_segment_becomes_custom() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let _alone = MIXED_REMAKE.lock().unwrap_or_else(|e| e.into_inner()); + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + let dev = dev.unwrap(); + unsafe { + let size = 256 << 20; + let base = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let at = [0x1000, (64 << 20) + 0x1000, (192 << 20) + 0x1000]; + for (i, &o) in at.iter().enumerate() { + std::ptr::write_volatile((base + o) as *mut u32, 0x2222_0000 + i as u32); + } + REFUSE_GPU_UPLOAD.with(|r| r.set(true)); + let remade = remake_mixed(&dev, base, size, &[(64 << 20, 128 << 20)]); + REFUSE_GPU_UPLOAD.with(|r| r.set(false)); + let remade = remade.expect("remake_mixed with the GPU_UPLOAD segment refused"); + assert_eq!(remade.heaps.len(), 3); + assert_eq!(remade.watched_regions, Some(vec![(base, 64 << 20), (base + (64 << 20), 128 << 20), (base + (192 << 20), 64 << 20)])); + for (i, &o) in at.iter().enumerate() { + assert_eq!(std::ptr::read_volatile((base + o) as *const u32), 0x2222_0000 + i as u32); + std::ptr::write_volatile((base + o + 0x1000) as *mut u32, 0xBEEF_0000 + i as u32); + } + let queue: 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: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (rb, ptr) = make_readback(&dev, 256).unwrap(); + let raw = remade.buf_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&raw).unwrap(); + for (i, &o) in at.iter().enumerate() { + list.CopyBufferRegion(&rb, 4 * i as u64, src, (o + 0x1000) as u64, 4); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap(); + assert_eq!(std::slice::from_raw_parts(ptr as *const u32, 3), &[0xBEEF_0000, 0xBEEF_0001, 0xBEEF_0002]); + } } #[test] diff --git a/crates/xcl/src/hle/d3d12x/watch_trap.rs b/crates/xcl/src/hle/d3d12x/watch_trap.rs new file mode 100644 index 0000000000..21f10f5b7e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/watch_trap.rs @@ -0,0 +1,707 @@ +//! `XCL_WATCH_TRAP=1`: the looks before each submit skip watched memory nobody writes. +//! +//! A 2 MiB block of a watched range that no look has found written for `COLD_LOOKS` looks is +//! made read-only (its committed read-write parts) and left out of the looks. The first write +//! there faults into `handler`, which gives the block its protection back and returns it to the +//! looks; the write itself happens after that, so write-watch sees it as before. When a block +//! is made read-only, a last look at it reports what was written since the previous one. +//! +//! What the handler cannot catch: a kernel write into a read-only page fails (ERROR_NOACCESS) +//! instead of faulting. The title's ReadFile buffers are therefore given their protection back +//! and pinned (never made read-only) until the read is over: when ReadFile returns, or for a +//! pending read when a look sees its OVERLAPPED completed. Either way the buffer's pages are +//! then reported as written: an unbuffered read flags its pages when it starts, not when the +//! data lands, so a look in between would reset them. Commits, decommits and protection changes +//! through kernelx and lazy pages (`guard`) and sparse commits (`changed`) give the blocks they +//! meet their protection back first and keep them from going read-only meanwhile. XCL's own +//! checks whether memory is writable (DirectStorage destinations, CPU-side writes for the GPU, +//! emulated stores) give it back too: their writes come from user mode and would be let +//! through, but the check reads the protection. + +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RESERVE}; + +const BLOCK: usize = 2 << 20; +/// looks a block must be found clean before it is made read-only: protecting 2 MiB costs about +/// 36 us, looking at it ~1 us, so it pays once a block stays cold ~40 looks (one to two frames) +const COLD_LOOKS: u32 = 64; +/// blocks made read-only per look at most (~36 us each), so a cold world goes over in steps +const PROTECTS_PER_LOOK: usize = 32; +const PAGE_READWRITE: u32 = 0x04; +const PAGE_READONLY: u32 = 0x02; +/// protection modifiers kept as they are (PAGE_NOCACHE, PAGE_WRITECOMBINE) +const MODIFIERS: u32 = 0x200 | 0x400; +const STATUS_PENDING: usize = 0x103; +const EXCEPTION_CONTINUE_EXECUTION: i32 = -1; +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; + +/// A read-only span: its end and the committed parts with the protection they had. +struct Cold { + end: usize, + parts: Vec<(usize, usize, u32)>, +} + +/// read-only spans by start (one block or the part of it in one watched range) +static COLD: Mutex> = Mutex::new(BTreeMap::new()); +/// blocks with a kernel read into them in flight -> how many +static PINS: Mutex> = Mutex::new(BTreeMap::new()); +/// pending title reads: (OVERLAPPED, buffer, length, byte count output) +static PENDING: Mutex> = Mutex::new(Vec::new()); +/// finished reads whose pages the next look reports as written +static REPORT: Mutex> = Mutex::new(Vec::new()); +/// an OVERLAPPED's size (Internal, InternalHigh, Offset/Pointer, hEvent) +const OVERLAPPED_LEN: usize = 32; +/// the looks' own state (one look at a time: `title_textures::REFRESH`) +static LOOKS: Mutex = Mutex::new(Looks { clean: BTreeMap::new(), n: 0 }); +/// blocks ever made read-only (for `was_ours`) +static EVER: Mutex> = Mutex::new(std::collections::BTreeSet::new()); +static INSTALLED: AtomicBool = AtomicBool::new(false); +/// faults taken, blocks made read-only, spans given back by `changed`, bytes left out of looks, +/// committed regions a thaw could not give back +static STATS: [AtomicU64; 6] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + +struct Looks { + /// block -> (span looked at in it this look, looks found clean in a row) + clean: BTreeMap, + n: u64, +} + +pub fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_WATCH_TRAP").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("watch trap: on (blocks of {} MiB clean for {COLD_LOOKS} looks are made read-only)", BLOCK >> 20); + } + on + }) +} + +fn install() { + if !INSTALLED.swap(true, Ordering::AcqRel) { + unsafe { AddVectoredExceptionHandler(1, Some(handler)) }; + } +} + +unsafe fn protect(a: usize, n: usize, p: u32) -> bool { + let mut old = 0u32; + VirtualProtect(a as *const c_void, n, p, &mut old) != 0 +} + +/// Give a read-only span its protection back. A part with pages decommitted since then cannot +/// be protected as a whole (ERROR_INVALID_ADDRESS): its committed regions are, one by one. +unsafe fn thaw(c: &Cold) { + for &(a, n, p) in &c.parts { + if protect(a, n, p) { + continue; + } + let end = a + n; + let mut at = a; + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 { + break; + } + let next = (m.BaseAddress as usize + m.RegionSize).min(end); + if m.State == MEM_COMMIT && m.Protect & !MODIFIERS == PAGE_READONLY && !protect(at, next - at, p) { + STATS[4].fetch_add(1, Ordering::Relaxed); + } + at = next; + } + } +} + +/// The read-only spans meeting `[a, a + n)` given their protection back and dropped. +unsafe fn thaw_range(cold: &mut BTreeMap, a: usize, n: usize) -> usize { + let end = a.saturating_add(n); + let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s); + let hit: Vec = cold.range(from..end).map(|(&s, _)| s).collect(); + for s in &hit { + if let Some(c) = cold.remove(s) { + thaw(&c); + } + } + hit.len() +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 || r.ExceptionInformation[0] != 1 { + return EXCEPTION_CONTINUE_SEARCH; + } + let at = r.ExceptionInformation[1]; + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let Some(s) = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s) else { + // another thread gave the span back after this write faulted: go on if it may write now + drop(cold); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 + && m.State == MEM_COMMIT + && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | 0x40); + return if now && was_ours(at) { EXCEPTION_CONTINUE_EXECUTION } else { EXCEPTION_CONTINUE_SEARCH }; + }; + let c = cold.remove(&s).unwrap(); + thaw(&c); + STATS[0].fetch_add(1, Ordering::Relaxed); + EXCEPTION_CONTINUE_EXECUTION +} + +/// Whether `at` lies in a block this trap has made read-only at some point (a write fault there +/// that finds the page writable again lost a race with another thread's `thaw`). +fn was_ours(at: usize) -> bool { + EVER.lock().unwrap_or_else(|e| e.into_inner()).contains(&(at & !(BLOCK - 1))) +} + +/// `[a, a + n)` is about to be committed, decommitted, freed or given another protection (or a +/// kernel write goes there): the read-only spans it meets get their protection back first. +pub fn changed(a: usize, n: usize) { + if on() { + changed_now(a, n); + } +} + +/// `guard` for a VirtualFree of `[a, a + n)`; `n == 0` (a release) means the whole allocation. +pub fn guard_free(a: usize, n: usize) -> Guard { + if !on() || a == 0 { + return Guard(0, 0); + } + if n != 0 { + return guard(a, n); + } + let mut at = a; + loop { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 || m.AllocationBase as usize != a { + break; + } + at = m.BaseAddress as usize + m.RegionSize; + } + guard(a, at.saturating_sub(a)) +} + +fn changed_now(a: usize, n: usize) { + if n == 0 { + return; + } + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + if cold.is_empty() { + return; + } + let k = unsafe { thaw_range(&mut cold, a, n) }; + STATS[2].fetch_add(k as u64, Ordering::Relaxed); +} + +fn blocks(a: usize, n: usize) -> impl Iterator { + let first = a & !(BLOCK - 1); + let last = (a + n.max(1) - 1) & !(BLOCK - 1); + (first..=last).step_by(BLOCK) +} + +fn pin(a: usize, n: usize, by: i32) { + let mut pins = PINS.lock().unwrap_or_else(|e| e.into_inner()); + for b in blocks(a, n) { + let e = pins.entry(b).or_insert(0); + *e = e.saturating_add_signed(by); + if *e == 0 { + pins.remove(&b); + } + } +} + +/// Pinned and writable while it lives: memory a call is about to write, commit, decommit or +/// give another protection. +pub struct Guard(usize, usize); + +impl Drop for Guard { + fn drop(&mut self) { + release(self.0, self.1); + } +} + +fn hold(a: usize, n: usize) { + if a != 0 && n != 0 { + pin(a, n, 1); + changed_now(a, n); + } +} + +fn release(a: usize, n: usize) { + if a != 0 && n != 0 { + pin(a, n, -1); + } +} + +/// `[a, a + n)` is about to be committed, decommitted or given another protection by the call +/// made while the guard lives. +pub fn guard(a: usize, n: usize) -> Guard { + if !on() || a == 0 || n == 0 { + return Guard(0, 0); + } + hold(a, n); + Guard(a, n) +} + +/// Before the title's ReadFile into `[buf, buf + n)`: the buffer, its byte count output `read` +/// and the OVERLAPPED `ov` (both written by the kernel too) pinned and writable. +pub fn read_start(buf: usize, n: usize, read: usize, ov: usize) { + if !on() || n == 0 { + return; + } + hold(buf, n); + hold(read, 4); + hold(ov, OVERLAPPED_LEN); +} + +/// After it: a pending read stays pinned until a look sees `ov` completed; a finished one is +/// unpinned and, if it succeeded, its buffer reported as written. +pub fn read_end(buf: usize, n: usize, read: usize, ov: usize, pending: bool, ok: bool) { + if !on() || n == 0 { + return; + } + if pending && ov != 0 { + PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, buf, n, read)); + return; + } + if ok { + REPORT.lock().unwrap_or_else(|e| e.into_inner()).push((buf, n)); + } + release(buf, n); + release(read, 4); + release(ov, OVERLAPPED_LEN); +} + +/// `OVERLAPPED::Internal` without faulting if the title has freed it. +unsafe fn overlapped_status(ov: usize) -> Option { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let (mut v, mut done) = (0usize, 0usize); + (ReadProcessMemory(GetCurrentProcess(), ov as *const c_void, &mut v as *mut usize as *mut c_void, 8, &mut done) != 0 && done == 8).then_some(v) +} + +/// The committed parts of `[a, a + n)` if all of them are plain read-write (modifiers kept), +/// with their protection. None parts (a hole: all of it reserved, nothing committed) is a cold +/// span too: nothing to protect, out of the looks until a commit in it (every commit path holds +/// a guard, which gives it back; one that did not would only delay the look, since the write +/// watch keeps its pages until they are read). +unsafe fn writable_parts(a: usize, n: usize) -> Option> { + let end = a + n; + let mut at = a; + let mut parts = Vec::new(); + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 { + return None; + } + let next = (m.BaseAddress as usize + m.RegionSize).min(end); + if m.State == MEM_COMMIT { + if m.Protect & !MODIFIERS != PAGE_READWRITE { + return None; + } + parts.push((at, next - at, m.Protect)); + } else if m.State != MEM_RESERVE { + return None; + } + at = next; + } + Some(parts) +} + +/// Make `[a, a + n)` read-only unless a block of it is pinned; false if it stays as it is. +unsafe fn freeze(a: usize, n: usize) -> bool { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + { + let pins = PINS.lock().unwrap_or_else(|e| e.into_inner()); + if blocks(a, n).any(|b| pins.contains_key(&b)) { + return false; + } + } + let Some(parts) = writable_parts(a, n) else { return false }; + for (i, &(p, len, prot)) in parts.iter().enumerate() { + if !protect(p, len, PAGE_READONLY | (prot & MODIFIERS)) { + for &(p, len, prot) in &parts[..i] { + protect(p, len, prot); + } + return false; + } + } + cold.insert(a, Cold { end: a + n, parts }); + EVER.lock().unwrap_or_else(|e| e.into_inner()).extend(blocks(a, n)); + true +} + +/// `ranges` minus the read-only spans (`cold`: by start, `end_of` their ends), as pieces within +/// one block each. The spans are walked once while the ranges ascend, as a look's do: two map +/// queries per span were 0.2 ms a look with 9,000 spans. +fn hot_pieces(ranges: &[(usize, usize)], cold: &BTreeMap, end_of: impl Fn(&V) -> usize) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let all = || cold.iter().map(|(&s, v)| (s, end_of(v))).peekable(); + // `last`: the span with the greatest start up to `seen`; `spans`: the ones after it + let (mut spans, mut last, mut seen) = (all(), None::<(usize, usize)>, 0); + for &(base, size) in ranges { + let end = base + size; + let mut at = base; + if base < seen { + (spans, last) = (all(), None); + } + while at < end { + seen = at; + while let Some(&span) = spans.peek().filter(|span| span.0 <= at) { + last = Some(span); + spans.next(); + } + let block_end = ((at & !(BLOCK - 1)) + BLOCK).min(end); + // the read-only span covering `at`, else the next one starting before `block_end` + if let Some((_, e)) = last.filter(|&(_, e)| e > at) { + at = e.min(end); + continue; + } + let stop = spans.peek().map_or(block_end, |&(s, _)| s.min(block_end)); + out.push((at, stop - at)); + at = stop; + } + } + out +} + +/// One look: `take(base, len, dirty)` is called on the watched pieces that are not read-only +/// (neighbours in one call), completed pending reads report their pages, clean blocks are made +/// read-only. +pub unsafe fn look(ranges: &[(usize, usize)], dirty: &mut Vec, page: usize, mut take: impl FnMut(usize, usize, &mut Vec)) { + install(); + // pending reads that are over: unpinned, their pages written + let done: Vec<(usize, usize, usize, usize)> = { + let mut p = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + let (over, still): (Vec<_>, Vec<_>) = p.drain(..).partition(|&(ov, ..)| overlapped_status(ov) != Some(STATUS_PENDING)); + *p = still; + over + }; + let mut report = std::mem::take(&mut *REPORT.lock().unwrap_or_else(|e| e.into_inner())); + for &(ov, buf, n, read) in &done { + release(buf, n); + release(read, 4); + release(ov, OVERLAPPED_LEN); + report.push((buf, n)); + } + for (buf, n) in report { + dirty.extend((buf & !(page - 1)..buf + n).step_by(page)); + } + let pieces = hot_pieces(ranges, &COLD.lock().unwrap_or_else(|e| e.into_inner()), |c| c.end); + let watched: usize = ranges.iter().map(|r| r.1).sum(); + let hot: usize = pieces.iter().map(|p| p.1).sum(); + STATS[3].fetch_add((watched - hot) as u64, Ordering::Relaxed); + // pieces that touch go in one call (a range lies in one allocation; pieces of two ranges + // never merge) + let mut written = std::collections::BTreeSet::new(); + let mut i = 0; + let range_of = |a: usize| ranges.partition_point(|&(b, _)| b <= a).saturating_sub(1); + while i < pieces.len() { + let (a, mut n) = pieces[i]; + let r = range_of(a); + let mut j = i + 1; + while j < pieces.len() && pieces[j].0 == a + n && range_of(pieces[j].0) == r { + n += pieces[j].1; + j += 1; + } + let from = dirty.len(); + take(a, n, dirty); + written.extend(dirty[from..].iter().map(|&p| p & !(BLOCK - 1))); + i = j; + } + let mut looks = LOOKS.lock().unwrap_or_else(|e| e.into_inner()); + looks.n += 1; + // the clean count of each block looked at (a block with two pieces is never made read-only) + let mut clean: BTreeMap = BTreeMap::new(); + let mut shared = std::collections::BTreeSet::new(); + for &(a, n) in &pieces { + let b = a & !(BLOCK - 1); + if clean.contains_key(&b) { + shared.insert(b); + continue; + } + let was = looks.clean.get(&b).filter(|(span, _)| *span == (a, n)).map_or(0, |&(_, k)| k); + clean.insert(b, ((a, n), if written.contains(&b) { 0 } else { was + 1 })); + } + let mut made = 0; + for (&b, ((a, n), k)) in clean.iter_mut() { + if made == PROTECTS_PER_LOOK { + break; + } + if *k < COLD_LOOKS || shared.contains(&b) || *n < 64 << 10 { + continue; + } + if freeze(*a, *n) { + made += 1; + // what was written between this look and the protection + take(*a, *n, dirty); + } else { + // pinned, nothing committed or not all read-write: tried again after another + // COLD_LOOKS looks, not at every look + *k = 0; + STATS[5].fetch_add(1, Ordering::Relaxed); + } + } + for b in shared { + clean.remove(&b); + } + looks.clean = clean; + STATS[1].fetch_add(made as u64, Ordering::Relaxed); + if looks.n.is_power_of_two() || looks.n % 4096 == 0 { + let c = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let mb: usize = c.values().flat_map(|c| c.parts.iter().map(|p| p.1)).sum::() >> 20; + let holes = c.values().filter(|c| c.parts.is_empty()).count(); + let s: Vec = STATS.iter().map(|x| x.load(Ordering::Relaxed)).collect(); + crate::xlog_info!( + "watch trap: look {}, {} spans read-only ({mb} MB) or holes ({holes}), this look {} of {} MB looked at in {} pieces; so far {} faults, {} made read-only, {} given back by changes, {} pending reads, {} regions not given back, {} refused", + looks.n, c.len(), hot >> 20, watched >> 20, pieces.len(), s[0], s[1], s[2], PENDING.lock().unwrap_or_else(|e| e.into_inner()).len(), s[4], s[5] + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{GetWriteWatch, VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE}; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + + #[test] + fn hot_pieces_skip_read_only_spans_and_split_at_blocks() { + let b = 0x4000_0000usize; + let ranges = [(b, 3 * BLOCK)]; + let cold = BTreeMap::from([(b + BLOCK, b + 2 * BLOCK)]); + assert_eq!(hot_pieces(&ranges, &cold, |&e| e), vec![(b, BLOCK), (b + 2 * BLOCK, BLOCK)]); + let cold = BTreeMap::from([(b + 0x1000, b + 0x3000)]); + assert_eq!(hot_pieces(&[(b, 0x5000)], &cold, |&e| e), vec![(b, 0x1000), (b + 0x3000, 0x2000)]); + } + + /// The one walk over the spans gives the pieces a query per span gave: spans that start + /// before a range, end past it, lie between ranges or touch each other, and ranges that + /// ascend, overlap or come out of order. + #[test] + fn hot_pieces_walk_matches_a_query_per_span() { + fn by_query(ranges: &[(usize, usize)], cold: &BTreeMap) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + for &(base, size) in ranges { + let end = base + size; + let mut at = base; + while at < end { + let block_end = ((at & !(BLOCK - 1)) + BLOCK).min(end); + if let Some((_, &e)) = cold.range(..=at).next_back().filter(|(_, &e)| e > at) { + at = e.min(end); + continue; + } + let stop = cold.range(at..block_end).next().map_or(block_end, |(&s, _)| s); + out.push((at, stop - at)); + at = stop; + } + } + out + } + let mut x = 0x2545_F491_4F6C_DD1Du64; + let mut next = move |n: usize| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x % n as u64) as usize + }; + let b = 0x4000_0000usize; + for round in 0..200 { + // disjoint spans of 1..=600 pages, 0..=700 pages apart, from before the ranges on + let mut cold = BTreeMap::new(); + let mut at = b - 0x40_0000; + for _ in 0..next(60) { + at += next(701) * 0x1000; + let end = at + (1 + next(600)) * 0x1000; + cold.insert(at, end); + at = end; + } + let mut ranges = Vec::new(); + let mut at = b; + for _ in 0..1 + next(8) { + at += next(900) * 0x1000; + let size = (1 + next(1500)) * 0x1000; + ranges.push((at, size)); + // every third round the next range starts inside this one + at += if round % 3 == 2 { size / 2 } else { size }; + } + if round % 5 == 4 { + ranges.reverse(); + } + assert_eq!(hot_pieces(&ranges, &cold, |&e| e), by_query(&ranges, &cold), "round {round}: {ranges:x?} {cold:x?}"); + } + } + + /// (from the top of the address space: tests that free an address and expect it to stay free + /// sit low) + const MEM_TOP_DOWN: u32 = 0x10_0000; + + /// The looks keep one state per process (one scanner in a title): tests that look take turns. + static SERIAL: Mutex<()> = Mutex::new(()); + + /// A test's turn, with the clean counts of an earlier test's blocks gone: `MEM_TOP_DOWN` can + /// give the next test the same base, which then started with a count already part way up. + fn serial() -> std::sync::MutexGuard<'static, ()> { + let g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + LOOKS.lock().unwrap_or_else(|e| e.into_inner()).clean.clear(); + g + } + + unsafe fn written(base: usize, n: usize) -> Vec { + let mut buf = vec![std::ptr::null_mut::(); 4096]; + let (mut k, mut g) = (buf.len(), 0u32); + assert_eq!(GetWriteWatch(WRITE_WATCH_FLAG_RESET, base as *const c_void, n, buf.as_mut_ptr(), &mut k, &mut g), 0); + buf[..k].iter().map(|&p| p as usize).collect() + } + + /// A block left clean goes read-only and out of the looks; a write to it faults once, is + /// seen by the next look, and the block is looked at again. A read into it (pinned) works. + #[test] + fn a_cold_block_traps_its_first_write_and_the_look_sees_it() { + let _serial = serial(); + unsafe { + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let raw = VirtualAlloc(std::ptr::null(), 3 * BLOCK, MEM_RESERVE | MEM_WRITE_WATCH | MEM_TOP_DOWN, PAGE_READWRITE) as usize; + assert_ne!(raw, 0); + VirtualFree(raw as *mut c_void, 0, MEM_RELEASE); + let base = (raw + BLOCK - 1) & !(BLOCK - 1); + let at = VirtualAlloc(base as *const c_void, BLOCK, MEM_RESERVE | windows_sys::Win32::System::Memory::MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_eq!(at, base); + let ranges = [(base, BLOCK)]; + let mut dirty = Vec::new(); + let take = |a: usize, n: usize, d: &mut Vec| d.extend(written(a, n)); + for _ in 0..COLD_LOOKS + 1 { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(dirty.is_empty()); + assert!(COLD.lock().unwrap().contains_key(&base), "clean block made read-only"); + std::ptr::write_volatile((base + 5 * 0x1000) as *mut u8, 9); + assert!(!COLD.lock().unwrap().contains_key(&base), "the write gave it back"); + look(&ranges, &mut dirty, 0x1000, take); + assert_eq!(dirty, vec![base + 5 * 0x1000]); + // a pinned read target is writable for the kernel and never made read-only + dirty.clear(); + for _ in 0..COLD_LOOKS + 1 { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(COLD.lock().unwrap().contains_key(&base)); + pin(base + 0x8000, 0x1000, 1); + changed_now(base + 0x8000, 0x1000); + assert!(!COLD.lock().unwrap().contains_key(&base)); + for _ in 0..COLD_LOOKS + 1 { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(!COLD.lock().unwrap().contains_key(&base), "pinned"); + pin(base + 0x8000, 0x1000, -1); + changed_now(base, BLOCK); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A clean block that cannot be made read-only (here: committed read-only by the title) is + /// tried once, then again only after another COLD_LOOKS looks, not at every look. + #[test] + fn a_block_that_cannot_be_made_read_only_waits_before_the_next_try() { + let _serial = serial(); + unsafe { + const MEM_WRITE_WATCH: u32 = 0x20_0000; + use windows_sys::Win32::System::Memory::MEM_COMMIT; + let raw = VirtualAlloc(std::ptr::null(), 3 * BLOCK, MEM_RESERVE | MEM_WRITE_WATCH | MEM_TOP_DOWN, PAGE_READWRITE) as usize; + assert_ne!(raw, 0); + let base = (raw + BLOCK - 1) & !(BLOCK - 1); + assert_eq!(VirtualAlloc(base as *const c_void, BLOCK, MEM_COMMIT, PAGE_READONLY) as usize, base); + let ranges = [(base, BLOCK)]; + let mut dirty = Vec::new(); + let take = |_: usize, _: usize, _: &mut Vec| {}; + let refused = || STATS[5].load(Ordering::Relaxed); + let before = refused(); + for _ in 0..COLD_LOOKS { + look(&ranges, &mut dirty, 0x1000, take); + } + assert_eq!(refused() - before, 1, "tried once it was clean for COLD_LOOKS looks"); + for _ in 1..COLD_LOOKS { + look(&ranges, &mut dirty, 0x1000, take); + } + assert_eq!(refused() - before, 1, "not tried again at every look"); + look(&ranges, &mut dirty, 0x1000, take); + assert_eq!(refused() - before, 2, "tried again after COLD_LOOKS more looks"); + assert!(!COLD.lock().unwrap().contains_key(&base)); + VirtualFree(raw as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A clean block with nothing committed is a hole: out of the looks with nothing protected, + /// until a commit in it (through a guard) gives it back; the write after the commit is seen. + #[test] + fn a_reserved_block_leaves_the_looks_until_a_commit() { + let _serial = serial(); + unsafe { + const MEM_WRITE_WATCH: u32 = 0x20_0000; + use windows_sys::Win32::System::Memory::MEM_COMMIT; + let raw = VirtualAlloc(std::ptr::null(), 3 * BLOCK, MEM_RESERVE | MEM_WRITE_WATCH | MEM_TOP_DOWN, PAGE_READWRITE) as usize; + assert_ne!(raw, 0); + let base = (raw + BLOCK - 1) & !(BLOCK - 1); + let ranges = [(base, BLOCK)]; + let mut dirty = Vec::new(); + let looked = std::cell::Cell::new(0usize); + let take = |a: usize, n: usize, d: &mut Vec| { + looked.set(looked.get() + n); + d.extend(written(a, n)); + }; + for _ in 0..COLD_LOOKS { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(COLD.lock().unwrap().get(&base).is_some_and(|c| c.parts.is_empty()), "a hole"); + looked.set(0); + look(&ranges, &mut dirty, 0x1000, take); + assert_eq!(looked.get(), 0, "out of the looks"); + // what guard() does around a commit (it is a no-op here: the switch is off in tests) + hold(base + 0x3000, 0x1000); + assert_eq!(VirtualAlloc((base + 0x3000) as *const c_void, 0x1000, MEM_COMMIT, PAGE_READWRITE) as usize, base + 0x3000); + pin(base + 0x3000, 0x1000, -1); + assert!(!COLD.lock().unwrap().contains_key(&base), "the commit gave it back"); + std::ptr::write_volatile((base + 0x3000) as *mut u8, 7); + look(&ranges, &mut dirty, 0x1000, take); + assert_eq!(dirty, vec![base + 0x3000]); + changed_now(base, BLOCK); + VirtualFree(raw as *mut c_void, 0, MEM_RELEASE); + } + } + + /// A read-only block with 64 KiB decommitted inside it by a path that did not tell the trap + /// (VirtualProtect of the whole span then fails): giving it back still makes the pages that + /// are left writable, not read-only with no span to catch their writes. + #[test] + fn a_partly_decommitted_cold_block_is_given_back_where_committed() { + let _serial = serial(); + unsafe { + const MEM_WRITE_WATCH: u32 = 0x20_0000; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_DECOMMIT}; + let raw = VirtualAlloc(std::ptr::null(), 3 * BLOCK, MEM_RESERVE | MEM_WRITE_WATCH | MEM_TOP_DOWN, PAGE_READWRITE) as usize; + assert_ne!(raw, 0); + VirtualFree(raw as *mut c_void, 0, MEM_RELEASE); + let base = (raw + BLOCK - 1) & !(BLOCK - 1); + assert_eq!(VirtualAlloc(base as *const c_void, BLOCK, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize, base); + let ranges = [(base, BLOCK)]; + let mut dirty = Vec::new(); + let take = |a: usize, n: usize, d: &mut Vec| d.extend(written(a, n)); + for _ in 0..COLD_LOOKS + 1 { + look(&ranges, &mut dirty, 0x1000, take); + } + assert!(COLD.lock().unwrap().contains_key(&base)); + assert_ne!(VirtualFree((base + 0x10000) as *mut c_void, 0x10000, MEM_DECOMMIT), 0); + changed_now(base, BLOCK); + for at in [base, base + 0x20000, base + BLOCK - 0x1000] { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)), 0); + assert_eq!(m.Protect, PAGE_READWRITE, "{at:#x} given back"); + } + std::ptr::write_volatile((base + 0x20000) as *mut u8, 1); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } +} diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 2ae4fe1b66..d397e37364 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -814,6 +814,8 @@ unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { fn writable(p: usize, n: usize) -> bool { let Some(end) = p.checked_add(n) else { return false }; crate::hle::kernelx::lazy::ensure(p, n); + // a read-only block of the watch trap is writable here: the copy into it faults and is let through + let _trap = crate::hle::d3d12x::watch_trap::guard(p, n); if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, n)) { return true; } diff --git a/crates/xcl/src/hle/dstorage/parallel.rs b/crates/xcl/src/hle/dstorage/parallel.rs index 198f4a86e8..651265be4b 100644 --- a/crates/xcl/src/hle/dstorage/parallel.rs +++ b/crates/xcl/src/hle/dstorage/parallel.rs @@ -462,6 +462,9 @@ impl<'a> Pipeline<'a> { let at = task.req.destination as usize; // The title can unmap the destination while a decoder runs. The late // check resolves lazy pages, and the kernel copy handles a subsequent unmap. + // (The kernel copy cannot be let through a watch-trap read-only block on its + // fault: the destination stays writable from the check to the end of the copy.) + let _trap = crate::hle::d3d12x::watch_trap::guard(at, n); if writable(at, n) && (n == 0 || write_destination(at, &payload.bytes[..n])) { Ok(()) } else { diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 4144a1144e..c5d5f2b40d 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -252,6 +252,7 @@ unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { } pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { + let _trap = crate::hle::d3d12x::watch_trap::guard(addr as usize, size); if let Some(q) = placeholders::alloc(addr, size, t, sanitize_protect(p)) { trace_mem("VirtualAlloc (placeholder)", addr as usize, size, t as u64, p, q as usize); return q; @@ -415,6 +416,7 @@ fn keep_last_error(f: impl FnOnce() -> R) -> R { /// Blocks of the unified memory region go back to it (MEM_RELEASE) or stay (MEM_DECOMMIT /// zeroes them); others to Windows. pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32) -> BOOL { + let _trap = crate::hle::d3d12x::watch_trap::guard_free(addr as usize, size); if let Some(ok) = placeholders::free(addr, size, t) { return ok; } @@ -493,10 +495,12 @@ pub unsafe extern "system" fn VirtualAllocEx(proc_: HANDLE, addr: *const c_void, } pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { + let _trap = crate::hle::d3d12x::watch_trap::guard(addr as usize, size); mem::VirtualProtect(addr, size, sanitize_protect(p), old) } pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { + let _trap = crate::hle::d3d12x::watch_trap::guard(if proc_ == thr::GetCurrentProcess() { addr as usize } else { 0 }, size); mem::VirtualProtectEx(proc_, addr, size, sanitize_protect(p), old) } @@ -1065,6 +1069,7 @@ unsafe fn give_back_homes(away: &mut Away) { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(start)) { crate::hle::d3d12x::sparse::decommitted(start, end - start); } + let _trap = crate::hle::d3d12x::watch_trap::guard(start, end - start); mem::VirtualFree(start as *mut c_void, end - start, mem::MEM_DECOMMIT); } } @@ -1072,6 +1077,7 @@ unsafe fn give_back_homes(away: &mut Away) { /// The page's home, committed again if `move_home_away` gave it back (None: it could not be). unsafe fn home_again(home: usize) -> Option { if lazy_home(home) && !committed_page(home) { + let _trap = crate::hle::d3d12x::watch_trap::guard(home, PHYS_PAGE); if mem::VirtualAlloc(home as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical page: its home {home:#x} could not be committed again"); return None; @@ -1093,6 +1099,7 @@ unsafe fn commit_homes(home: usize, n: usize) -> bool { if committed_range(home, len) { return true; } + let _trap = crate::hle::d3d12x::watch_trap::guard(home, len); if mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical pages: {n} at their home {home:#x} could not be committed"); return false; @@ -1208,6 +1215,7 @@ unsafe fn release_at(at: usize) { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { crate::hle::d3d12x::sparse::decommitted(at, PHYS_PAGE); } + let _trap = crate::hle::d3d12x::watch_trap::guard(at, PHYS_PAGE); mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT); } @@ -1223,6 +1231,7 @@ unsafe fn move_away(away: &mut Away, old: usize, at: usize, page: usize, in_uma: return Ok(false); } // (a destination that cannot be committed leaves the page where it was, mapped as before) + let _trap = crate::hle::d3d12x::watch_trap::guard(at, PHYS_PAGE); if !in_uma && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { return Err(()); } @@ -1418,6 +1427,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) away.page.insert(p, at); continue; } + let _trap = crate::hle::d3d12x::watch_trap::guard(at, PHYS_PAGE); if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index fa750b9a48..e3952526a4 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -41,6 +41,7 @@ unsafe fn commit(page: usize) -> bool { if !g.remove(&page) { return false; } + let _trap = crate::hle::d3d12x::watch_trap::guard(page, PAGE); !VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() } diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 0767cf1e1c..4983b6cd3a 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -533,8 +533,15 @@ unsafe extern "system" fn hk_read_file(h: *mut c_void, buf: *mut c_void, n: u32, let orig = orig!(O_READ_FILE as F); if !buf.is_null() { crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); + crate::hle::d3d12x::watch_trap::read_start(buf as usize, n as usize, read as usize, ov as usize); } - orig(h, buf, n, read, ov) + let r = orig(h, buf, n, read, ov); + if !buf.is_null() { + let e = GetLastError(); + crate::hle::d3d12x::watch_trap::read_end(buf as usize, n as usize, read as usize, ov as usize, r == 0 && e == 997, r != 0); + SetLastError(e); + } + r } unsafe extern "system" fn hk_delete_file_w(n: *const u16) -> i32 {