diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a4..61b613169 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -309,6 +309,65 @@ unsafe fn code_bytes_at(rip: usize, most: usize) -> usize { (in_page + 1..=most).rev().find(|&n| crate::gpu::shader::readable(rip, n)).unwrap_or(in_page) } +#[inline] +fn console_only_bit(what: &crate::insn::ConsoleOnly) -> u16 { + use crate::insn::ConsoleOnly; + 1u16 << match what { + ConsoleOnly::Ud2 => 0, + ConsoleOnly::Clwb => 1, + ConsoleOnly::Monitorx => 2, + ConsoleOnly::Mwaitx => 3, + ConsoleOnly::Clzero => 4, + ConsoleOnly::ClzeroLoop { .. } => 5, + ConsoleOnly::Rdpru => 6, + ConsoleOnly::Rdpid(_) => 7, + ConsoleOnly::Extrq { .. } => 8, + ConsoleOnly::Insertq { .. } => 9, + } +} + +fn patch_monitorx_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_NO_PATCH_MONITORX").is_ok_and(|v| !v.is_empty() && v != "0")) +} + +/// Patch `expected.len()` code bytes at `rip` to `replacement` under a global lock, using an +/// atomic aligned 64-bit CAS whenever the instruction lies within one 8-byte word so sibling +/// threads never observe torn instruction bytes. +unsafe fn patch_insn(rip: usize, expected: &[u8], replacement: &[u8]) -> bool { + use std::sync::atomic::AtomicU64; + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + debug_assert_eq!(expected.len(), replacement.len()); + static PATCH_LOCK: Mutex<()> = Mutex::new(()); + let _g = PATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let len = expected.len(); + if std::slice::from_raw_parts(rip as *const u8, len) != expected { + return false; + } + let mut old = 0u32; + if VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + return false; + } + let off = rip & 7; + if off + len <= 8 { + let word_ptr = (rip & !7) as *const AtomicU64; + let cur = (*word_ptr).load(Ordering::Acquire); + let mut bytes = cur.to_ne_bytes(); + bytes[off..off + len].copy_from_slice(replacement); + let next = u64::from_ne_bytes(bytes); + let _ = (*word_ptr).compare_exchange(cur, next, Ordering::AcqRel, Ordering::Acquire); + } else { + std::ptr::copy_nonoverlapping(replacement.as_ptr(), rip as *mut u8, len); + } + VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old); + FlushInstructionCache( + windows_sys::Win32::System::Threading::GetCurrentProcess() as *mut std::ffi::c_void, + rip as *const std::ffi::c_void, + len, + ); + true +} + /// A title's STATUS_ILLEGAL_INSTRUCTION: an instruction the console's Zen 2 has and this CPU /// lacks (`insn`) is emulated and stepped over (EXCEPTION_CONTINUE_EXECUTION); anything else is /// logged with its code bytes and goes on to the title's handlers. @@ -324,31 +383,34 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics crate::xlog_error!("illegal instruction in {}: code bytes {}", modules::describe_address(rip), crate::insn::hex(code)); return 0; }; - static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); - if let Ok(mut seen) = SEEN.lock() { - if !seen.contains(&std::mem::discriminant(&what)) { - seen.push(std::mem::discriminant(&what)); - if what == ConsoleOnly::Ud2 { - crate::xlog_error!("ud2 in {} – the title's own trap; on the stack: {}", modules::describe_address(rip), stack_callers(ctx.Rsp as usize)); - } else { - crate::xlog_warn!("{what:?} in {} – a console CPU instruction this CPU lacks: emulated (logged once)", modules::describe_address(rip)); - } + static SEEN_MASK: std::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(0); + let bit = console_only_bit(&what); + if SEEN_MASK.load(Ordering::Relaxed) & bit == 0 && SEEN_MASK.fetch_or(bit, Ordering::Relaxed) & bit == 0 { + if what == ConsoleOnly::Ud2 { + crate::xlog_error!("ud2 in {} – the title's own trap; on the stack: {}", modules::describe_address(rip), stack_callers(ctx.Rsp as usize)); + } else { + crate::xlog_warn!("{what:?} in {} – a console CPU instruction this CPU lacks: emulated (logged once)", modules::describe_address(rip)); } } let mut step = len; match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { - use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; - let mut old = 0u32; - if unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 { - let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) }; - code.fill(0x90); - unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; + let nops = [0x90u8; 16]; + patch_insn(rip, &code[..len], &nops[..len]); + } + ConsoleOnly::Monitorx => { + // `0F 01 FA` (3 B) is architectural no-op on PC; patch to `nop; nop; nop` so worker + // spin-waits stop taking kernel #UD round-trips. + if patch_monitorx_enabled() && len == 3 { + patch_insn(rip, &code[..3], &[0x90, 0x90, 0x90]); } } - ConsoleOnly::Monitorx => {} ConsoleOnly::Mwaitx => { + // `0F 01 FB` (3 B) emulates as `spin_loop()` (`pause`); patch to `pause; nop` (`F3 90 90`). + if patch_monitorx_enabled() && len == 3 { + patch_insn(rip, &code[..3], &[0xF3, 0x90, 0x90]); + } std::hint::spin_loop(); } ConsoleOnly::Clzero => { @@ -584,6 +646,7 @@ unsafe fn stack_callers_n(rsp: usize, max: usize) -> String { extern "system" { fn GetThreadDescription(thread: *mut std::ffi::c_void, description: *mut *mut u16) -> i32; fn LocalFree(mem: *mut std::ffi::c_void) -> *mut std::ffi::c_void; + fn FlushInstructionCache(process: *mut std::ffi::c_void, base: *const std::ffi::c_void, size: usize) -> i32; } /// A thread's description (SetThreadDescription – engines name their threads). @@ -1151,4 +1214,44 @@ mod tests { VirtualFree(buf as *mut _, 0, MEM_RELEASE); } } + + #[test] + fn monitorx_and_mwaitx_patch_to_nop_and_pause_safely() { + use std::sync::{atomic::AtomicBool, Arc}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + unsafe { + let code = VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(code, 0); + modules::register_mapped(Arc::new(modules::MappedModule { + name: "monitorx_patch.exe".into(), path: "monitorx_patch.exe".into(), base: code, size: 0x1000, entry_rva: 0, is_dll: false, + exports: Default::default(), tls_callbacks: Mutex::new(Vec::new()), no_thread_calls: AtomicBool::new(false), + initialized: AtomicBool::new(true), stack_reserve: 0, + })); + // Place `monitorx` at +5 (straddling 8-byte boundary at +8) and `mwaitx` at +16 (aligned). + let mon_rip = code + 5; + let mw_rip = code + 16; + std::ptr::write_bytes(code as *mut u8, 0xCC, 32); + std::ptr::copy_nonoverlapping([0x0Fu8, 0x01, 0xFA].as_ptr(), mon_rip as *mut u8, 3); + std::ptr::copy_nonoverlapping([0x0Fu8, 0x01, 0xFB].as_ptr(), mw_rip as *mut u8, 3); + + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + ctx.Rip = mon_rip as u64; + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, (mon_rip + 3) as u64); + assert_eq!(std::slice::from_raw_parts(mon_rip as *const u8, 3), &[0x90, 0x90, 0x90]); + // Surrounding sentinel bytes must remain untouched. + assert_eq!(*((mon_rip - 1) as *const u8), 0xCC); + assert_eq!(*((mon_rip + 3) as *const u8), 0xCC); + + ctx.Rip = mw_rip as u64; + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, (mw_rip + 3) as u64); + assert_eq!(std::slice::from_raw_parts(mw_rip as *const u8, 3), &[0xF3, 0x90, 0x90]); + assert_eq!(*((mw_rip - 1) as *const u8), 0xCC); + assert_eq!(*((mw_rip + 3) as *const u8), 0xCC); + + modules::unregister_mapped(code); + VirtualFree(code as *mut _, 0, MEM_RELEASE); + } + } } diff --git a/crates/xcl/src/hle/acphal.rs b/crates/xcl/src/hle/acphal.rs index 83caef448..83156079b 100644 --- a/crates/xcl/src/hle/acphal.rs +++ b/crates/xcl/src/hle/acphal.rs @@ -701,6 +701,9 @@ const XAPU_ACTIVATE: u32 = 1; const XAPU_DEACTIVATE: u32 = 2; const XAPU_PROCESS: u32 = 3; +/// Cap retained per-stream scratch capacities so a rare oversized request never pins extra RAM. +const SCRATCH_CAP_LIMIT: usize = 16_384; + /// What one decoder stream holds between commands. struct XApuStream { /// 1 or 2 (what Activate asked for) @@ -709,11 +712,16 @@ struct XApuStream { decoder: Option, /// between Activate and Deactivate; the decoder is kept across them and reset by the next Activate active: bool, + /// reusable PCM16 decode scratch (avoids per-packet heap allocs across 74k+ world packets) + pcm_scratch: Vec, + /// reusable float32 output scratch + out_scratch: Vec, } struct XApu { results: Mutex>, - channels: Mutex>, + /// Per-stream locks so concurrent title audio threads decode independent streams in parallel. + channels: Box<[Mutex]>, data: usize, ready: usize, frames_per_output: u32, @@ -774,8 +782,22 @@ where clear_out(); return E_OUTOFMEMORY; } - channels.resize_with(n_streams, || XApuStream { channels: 2, decoder: None, active: false }); - let x = Box::new(XApu { results: Mutex::new(VecDeque::new()), channels: Mutex::new(channels), data, ready, frames_per_output: i.frames_per_output }); + channels.resize_with(n_streams, || { + Mutex::new(XApuStream { + channels: 2, + decoder: None, + active: false, + pcm_scratch: Vec::new(), + out_scratch: Vec::new(), + }) + }); + let x = Box::new(XApu { + results: Mutex::new(VecDeque::new()), + channels: channels.into_boxed_slice(), + data, + ready, + frames_per_output: i.frames_per_output, + }); std::ptr::write_unaligned(output, XApuConnectOutput { data: data as *mut c_void, ready: ready as *mut c_void }); *handle = Box::into_raw(x) as *mut c_void; let (process, streams) = (i.process, i.streams); @@ -800,10 +822,11 @@ fn new_decoder(stream: u32, channels: u32) -> Option { } } -/// Decodes a Process command's input (an Opus packet) into `out` (float32 samples, `channels` interleaved): -/// `first_frame` frames of what the decoder produces are skipped, the rest fills `out` (what is not -/// produced stays silent). Returns the frames written (None: nothing was decoded). -unsafe fn decode_into(s: &mut XApuStream, stream: u32, p: &XApuProcess, out: &mut [f32]) -> Option { +/// Decodes a Process command's input (an Opus packet) into `s.out_scratch[..out_samples]` +/// (float32 samples, `channels` interleaved): `first_frame` frames of what the decoder produces +/// are skipped, the rest fills `out_scratch` (what is not produced stays silent). Returns the +/// frames written (None: nothing was decoded). +unsafe fn decode_into(s: &mut XApuStream, stream: u32, p: &XApuProcess, out_samples: usize) -> Option { let (input, input_bytes, first_frame) = (p.input, p.input_bytes, p.first_frame); if !s.active { return None; @@ -813,14 +836,21 @@ unsafe fn decode_into(s: &mut XApuStream, stream: u32, p: &XApuProcess, out: &mu return None; } let packet = std::slice::from_raw_parts(input as *const u8, input_bytes as usize); - let mut pcm: Vec = Vec::with_capacity(960 * 2); + s.pcm_scratch.clear(); + if s.pcm_scratch.capacity() < 960 * 2 { + s.pcm_scratch.reserve(960 * 2); + } let ch = s.channels as usize; - match dec.decode_packet(packet, &mut pcm) { + let res = dec.decode_packet(packet, &mut s.pcm_scratch); + let ret = match res { Ok(frames) if frames > 0 => { let skip = (first_frame as usize).min(frames); - let produced = (frames - skip).min(out.len() / ch); + let produced = (frames - skip).min(out_samples / ch); let mut nonzero = 0u64; - for (o, &v) in out.iter_mut().zip(pcm[skip * ch..(skip + produced) * ch].iter()) { + for (o, &v) in s.out_scratch[..out_samples] + .iter_mut() + .zip(s.pcm_scratch[skip * ch..(skip + produced) * ch].iter()) + { *o = v as f32 / 32768.0; nonzero += (v != 0) as u64; } @@ -834,20 +864,27 @@ unsafe fn decode_into(s: &mut XApuStream, stream: u32, p: &XApuProcess, out: &mu } None } + }; + if s.pcm_scratch.capacity() > SCRATCH_CAP_LIMIT { + s.pcm_scratch.clear(); + s.pcm_scratch.shrink_to(SCRATCH_CAP_LIMIT); } + ret } /// Every 5 s while the decoder works: what it decoded (the log is what a run that is cut short -/// leaves; report.json is written at the start). +/// leaves; report.json is written at the start). Lock-free throttle so 250–700+ pkt/s world audio +/// never contends on a global mutex. fn report_progress() { - static LAST: Mutex> = Mutex::new(None); - let now = Instant::now(); - { - let mut l = LAST.lock().unwrap(); - match *l { - Some(t) if now.duration_since(t) < Duration::from_secs(5) => return, - _ => *l = Some(now), - } + use std::sync::atomic::{AtomicU64, Ordering}; + static LAST_MS: AtomicU64 = AtomicU64::new(u64::MAX); + let now_ms = (crate::log::uptime() * 1000.0) as u64; + let prev = LAST_MS.load(Ordering::Relaxed); + if prev != u64::MAX && now_ms.saturating_sub(prev) < 5_000 { + return; + } + if LAST_MS.compare_exchange(prev, now_ms, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; } let a = xaudio2::stats(); crate::xlog_info!( @@ -905,55 +942,71 @@ pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: * } } let mut r = XApuResult { id: c, state: 0, state_data: 0, time: 0, error: S_OK, frames: 0, output_bytes: 0, output: std::ptr::null_mut(), pitch: 1.0, input_bytes: 0, input: std::ptr::null_mut() }; - { - let mut ch = x.channels.lock().unwrap(); - // a stream the connection does not have: no decoder, no state; a Process answers with silence - // of the length asked for, with the channel count of the first stream (if any; else stereo) - let known = (c.stream as usize) < ch.len(); - if c.kind == XAPU_ACTIVATE { - let n = std::ptr::read_unaligned(command as *const XApuActivate).channels; - let channels = if n == 1 { 1 } else { 2 }; - if let Some(s) = ch.get_mut(c.stream as usize) { - match s.decoder.as_mut() { - // the stream started again with the same layout: its decoder is reset, not - // rebuilt (on Windows a new decoder is a new Media Foundation transform) - Some(d) if s.channels == channels => d.flush(), - _ => s.decoder = new_decoder(c.stream, channels), - } - s.channels = channels; - s.active = true; + let idx = c.stream as usize; + if c.kind == XAPU_ACTIVATE { + let n = std::ptr::read_unaligned(command as *const XApuActivate).channels; + let channels = if n == 1 { 1 } else { 2 }; + if let Some(slot) = x.channels.get(idx) { + let mut s = slot.lock().unwrap(); + let same_channels = s.channels == channels; + match s.decoder.as_mut() { + // the stream started again with the same layout: its decoder is reset, not + // rebuilt (on Windows a new decoder is a new Media Foundation transform) + Some(d) if same_channels => d.flush(), + _ => s.decoder = new_decoder(c.stream, channels), } - } else if c.kind == XAPU_DEACTIVATE { - if let Some(s) = ch.get_mut(c.stream as usize) { - s.active = false; - } - } else if c.kind == XAPU_PROCESS { - let p = std::ptr::read_unaligned(command as *const XApuProcess); - let channels = if known { ch[c.stream as usize].channels } else { ch.first().map_or(2, |s| s.channels) }; + s.channels = channels; + s.active = true; + } + } else if c.kind == XAPU_DEACTIVATE { + if let Some(slot) = x.channels.get(idx) { + slot.lock().unwrap().active = false; + } + } else if c.kind == XAPU_PROCESS { + let p = std::ptr::read_unaligned(command as *const XApuProcess); + let asked = if p.frames != 0 { p.frames } else { x.frames_per_output }; + let (frames, frame_bytes) = if let Some(slot) = x.channels.get(idx) { + let mut s = slot.lock().unwrap(); + let channels = s.channels; let frame_bytes = channels * 4; - let asked = if p.frames != 0 { p.frames } else { x.frames_per_output }; let mut frames = (if asked != 0 { asked } else { 960 }).min(p.output_bytes / frame_bytes); if !p.output.is_null() && frames != 0 { - // decoded here, then copied byte by byte: the title's buffer is not known to be 4-byte aligned - let mut out = vec![0.0f32; (frames * channels) as usize]; + // decoded into the stream's reusable scratch buffer, then copied byte by byte: + // the title's buffer is not known to be 4-byte aligned + let out_samples = (frames * channels) as usize; + s.out_scratch.clear(); + s.out_scratch.resize(out_samples, 0.0f32); // decoded: the frames after first_frame; not decoded: silence of the length asked for - if known { - if let Some(n) = decode_into(&mut ch[c.stream as usize], c.stream, &p, &mut out) { - frames = n as u32; - } + if let Some(n) = decode_into(&mut s, c.stream, &p, out_samples) { + frames = n as u32; + } + std::ptr::copy_nonoverlapping(s.out_scratch.as_ptr() as *const u8, p.output as *mut u8, out_samples * 4); + if s.out_scratch.capacity() > SCRATCH_CAP_LIMIT { + s.out_scratch.clear(); + s.out_scratch.shrink_to(SCRATCH_CAP_LIMIT); } - std::ptr::copy_nonoverlapping(out.as_ptr() as *const u8, p.output as *mut u8, out.len() * 4); } - // output ready, more input wanted - r.state = 1 | 2; - r.frames = frames; - r.output_bytes = frames * frame_bytes; - r.output = p.output; - r.pitch = p.pitch; - r.input_bytes = p.input_bytes; - r.input = p.input; - report_progress(); - } + (frames, frame_bytes) + } else { + // a stream the connection does not have: silence of the length asked for, using stream 0's + // channel count (if any; else stereo), written directly without allocating + let channels = x.channels.first().map_or(2, |s| s.lock().unwrap().channels); + let frame_bytes = channels * 4; + let frames = (if asked != 0 { asked } else { 960 }).min(p.output_bytes / frame_bytes); + if !p.output.is_null() && frames != 0 { + std::ptr::write_bytes(p.output as *mut u8, 0, (frames * frame_bytes) as usize); + } + (frames, frame_bytes) + }; + // output ready, more input wanted + r.state = 1 | 2; + r.frames = frames; + r.output_bytes = frames * frame_bytes; + r.output = p.output; + r.pitch = p.pitch; + r.input_bytes = p.input_bytes; + r.input = p.input; + report_progress(); } let n = { let mut q = x.results.lock().unwrap(); @@ -1308,4 +1361,57 @@ mod tests { assert_eq!(mbi.State, MEM_FREE, "data buffer must be released when event creation fails"); } } + + #[test] + fn xapu_reuses_stream_scratch_and_supports_concurrent_streams() { + unsafe { + let input = XApuConnectInput { process: 1, streams: 4, commands_per_stream: 4, data_bytes: 0, frames_per_output: 256, options: 0 }; + let mut out = XApuConnectOutput { data: std::ptr::null_mut(), ready: std::ptr::null_mut() }; + let mut h = std::ptr::null_mut(); + assert_eq!(XApuConnect(&input, &mut out, &mut h), S_OK); + let h_addr = h as usize; + + // Exercise concurrent Activate + Process + Deactivate across 4 distinct streams. + let threads: Vec<_> = (0..4u32) + .map(|stream| { + std::thread::spawn(move || { + let act = XApuActivate { + id: XApuCommand { kind: XAPU_ACTIVATE, stream, sequence: 1, options: 0, context: std::ptr::null_mut() }, + channels: if stream % 2 == 0 { 1 } else { 2 }, + }; + assert_eq!(XApuEnqueueCommand(h_addr as *mut c_void, &act as *const _ as *const XApuCommand, std::ptr::null_mut()), S_OK); + let mut buf = vec![0xCCu8; 4096]; + for seq in 2..6u32 { + let proc_cmd = XApuProcess { + id: XApuCommand { kind: XAPU_PROCESS, stream, sequence: seq, options: 0, context: std::ptr::null_mut() }, + ramp: 0.0, + pitch: 48_000.0, + first_frame: 0, + frames: 256, + input_bytes: 0, + input: std::ptr::null_mut(), + output_bytes: buf.len() as u32, + output: buf.as_mut_ptr() as *mut c_void, + }; + assert_eq!(XApuEnqueueCommand(h_addr as *mut c_void, &proc_cmd as *const _ as *const XApuCommand, std::ptr::null_mut()), S_OK); + } + let deact = XApuCommand { kind: XAPU_DEACTIVATE, stream, sequence: 6, options: 0, context: std::ptr::null_mut() }; + assert_eq!(XApuEnqueueCommand(h_addr as *mut c_void, &deact, std::ptr::null_mut()), S_OK); + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + + // 4 streams * (1 activate + 4 process + 1 deactivate) = 24 results queued. + assert_eq!(XApuGetResultCount(h, std::ptr::null_mut()), 24); + let mut r: XApuResult = std::mem::zeroed(); + for _ in 0..24 { + assert_eq!(XApuDequeueResult(h, &mut r), S_OK); + } + assert_eq!(XApuDequeueResult(h, &mut r), XAPU_NO_RESULTS); + assert_eq!(XApuDisconnect(h), S_OK); + } + } } diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 5dd9d2e70..d0b383d69 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -869,6 +869,61 @@ fn note_request(r: &Request) { } } +/// Refresh any zero or stale (non-live) page entries in `pages` from the title's live page array +/// at `raw_ptr` via `read_own` (`ReadProcessMemory`), so an array unmapped before the worker's +/// turn fails cleanly instead of faulting (#476). Retail titles reuse persistent page-array table +/// slots and sometimes populate or overwrite entries after `EnqueueRequest` (while stack-allocated +/// arrays that already hold live pages stay as snapshotted). +unsafe fn refresh_stale_pages(pages: &[usize], raw_ptr: u64) -> Option> { + let needs_refresh = pages.iter().any(|&p| p == 0 || !crate::hle::kernelx::is_live_physical_page(p)); + if !needs_refresh { + return None; + } + let mut now = vec![0usize; pages.len()]; + if !read_own(raw_ptr as usize, now.as_mut_ptr() as *mut u8, std::mem::size_of_val(pages)) { + return None; + } + Some( + pages + .iter() + .zip(&now) + .map(|(&then, &cur)| if then != 0 && crate::hle::kernelx::is_live_physical_page(then) { then } else { cur }) + .collect(), + ) +} + +/// Write `payload` into `r`'s physical-page destination, re-reading any zero or stale page entries +/// from `r.destination` if the enqueue-time snapshot is not yet live. +unsafe fn write_dest_physical_pages(r: &Request, dest_pages: Option<&[usize]>, payload: &[u8]) -> Result<(), HRESULT> { + let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; + let offset = r.destination_page_offset as usize; + if crate::hle::kernelx::write_physical_pages(pages, offset, payload) { + return Ok(()); + } + if let Some(late) = refresh_stale_pages(pages, r.destination) { + if crate::hle::kernelx::write_physical_pages(&late, offset, payload) { + return Ok(()); + } + } + Err(E_ACCESS_VIOLATION) +} + +/// Read `dst.len()` bytes from `r`'s physical-page source, re-reading any zero or stale page +/// entries from `r.source` if the enqueue-time snapshot is not yet live. +unsafe fn read_src_physical_pages(r: &Request, src_pages: Option<&[usize]>, dst: &mut [u8]) -> Result<(), HRESULT> { + let pages = src_pages.ok_or(E_ACCESS_VIOLATION)?; + let offset = r.source_page_offset as usize; + if crate::hle::kernelx::read_physical_pages(pages, offset, dst) { + return Ok(()); + } + if let Some(late) = refresh_stale_pages(pages, r.source) { + if crate::hle::kernelx::read_physical_pages(&late, offset, dst) { + return Ok(()); + } + } + Err(E_ACCESS_VIOLATION) +} + /// Run a request; the destination gets the bytes or nothing. unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[usize]>, src_pages: Option<&[usize]>) -> Result<(), HRESULT> { let n = r.destination_size as usize; @@ -879,10 +934,7 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us let src: Vec = if r.memory_source() { let mut b = vec![0u8; r.source_size as usize]; if r.source_physical_pages() { - let pages = src_pages.ok_or(E_ACCESS_VIOLATION)?; - if !crate::hle::kernelx::read_physical_pages(pages, r.source_page_offset as usize, &mut b) { - return Err(E_ACCESS_VIOLATION); - } + read_src_physical_pages(r, src_pages, &mut b)?; } else { if !crate::gpu::shader::readable(r.source as usize, r.source_size as usize) { return Err(E_ACCESS_VIOLATION); @@ -926,30 +978,7 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us let payload = if bc != 0 { bcpack_unpack(r, &stage1, n)? } else { stage1 }; if r.dest_physical_pages() { - let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; - // A page number of 0 in the snapshot taken at enqueue (no page has it): the entry is - // read again now. A retail title keeps its page arrays in its own tables and fills an - // entry after EnqueueRequest – its streaming requests were refused by the thousand - // with page 0. An array that had its pages at enqueue stays as it was snapshotted - // (titles also pass arrays on the stack). The title keeps an array with such an entry - // until the request is done: one it has freed or reused meanwhile cannot be told from - // a late fill. Read like the snapshot (`read_own`): an array unmapped since then fails - // the request instead of faulting in this worker (#476). - let late: Vec; - let pages = if pages.contains(&0) { - let mut now = vec![0usize; pages.len()]; - if read_own(r.destination as usize, now.as_mut_ptr() as *mut u8, std::mem::size_of_val(pages)) { - late = pages.iter().zip(&now).map(|(&then, &now)| if then != 0 { then } else { now }).collect(); - &late[..] - } else { - pages - } - } else { - pages - }; - if !crate::hle::kernelx::write_physical_pages(pages, r.destination_page_offset as usize, &payload[..n]) { - return Err(E_ACCESS_VIOLATION); - } + write_dest_physical_pages(r, dest_pages, &payload[..n])?; } else if n > 0 { std::ptr::copy_nonoverlapping(payload.as_ptr(), r.destination as *mut u8, n); } @@ -1050,7 +1079,14 @@ impl QueueInner { let mut e = self.errors.lock().unwrap(); e.0 += 1; if e.1.is_none() { - crate::xlog_warn!("DirectStorage: a request failed ({hr:#x}): {} bytes from {}", request.destination_size, file.map(|f| String::from_utf16_lossy(&f.path)).unwrap_or_default()); + crate::xlog_warn!( + "DirectStorage: a request failed ({hr:#x}): {} bytes from {} (options={:#x}, dst={:#x}{})", + request.destination_size, + file.map(|f| String::from_utf16_lossy(&f.path)).unwrap_or_default(), + request.options, + request.destination, + if request.dest_physical_pages() { " phys" } else { "" }, + ); e.1 = Some(FirstError { hr, request, file: file.map(|f| f.path.clone()).unwrap_or_default() }); } unsafe { SetEvent(self.error_event as HANDLE) }; diff --git a/crates/xcl/src/hle/dstorage/parallel.rs b/crates/xcl/src/hle/dstorage/parallel.rs index 198f4a86e..98478c517 100644 --- a/crates/xcl/src/hle/dstorage/parallel.rs +++ b/crates/xcl/src/hle/dstorage/parallel.rs @@ -1,7 +1,7 @@ //! Bounded preparation of file-backed zlib requests. The queue thread owns //! file reads, cancellation checks, and retirement; decoders own private buffers. -use super::{note_request, read_exact_at, writable, Entry, FileInner, QueueInner, Request, E_ABORT, E_ACCESS_VIOLATION, E_FILE_HANDLE, E_ZLIB_DATA}; +use super::{bcpack_unpack, note_request, read_exact_at, writable, write_dest_physical_pages, Entry, FileInner, QueueInner, Request, E_ABORT, E_ACCESS_VIOLATION, E_FILE_HANDLE, E_ZLIB_DATA}; use crate::util::{HRESULT, S_OK}; use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; @@ -126,6 +126,7 @@ pub(super) type TestHook = Arc; struct DecompressTask { seq: u64, + req: Request, compressed: StagingBuffer, output: Reservation, codec_state: Reservation, @@ -198,7 +199,7 @@ impl DecompressPool { }; #[cfg(test)] let counters = &shared.budget.metrics; - let DecompressTask { seq, compressed, output, codec_state, target_size, tx, #[cfg(test)] hook } = task; + let DecompressTask { seq, req, compressed, output, codec_state, target_size, tx, #[cfg(test)] hook } = task; // A worker owns each reservation until the associated allocation goes away. // Convert a panicking task into a completion so its queue cannot wait forever. let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { @@ -210,7 +211,25 @@ impl DecompressPool { let _codec_state = codec_state; #[cfg(test)] counters.started.fetch_add(1, Ordering::Relaxed); - let result = decompress_zlib_into(&compressed.bytes, &mut output.bytes[..target_size]); + let bc = req.bcpack(); + let dst_len = req.destination_size as usize; + let result = if bc == 0 { + decompress_zlib_into(&compressed.bytes, &mut output.bytes[..target_size]) + } else { + let stage1: std::borrow::Cow<'_, [u8]> = if req.zlib() { + let d = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&compressed.bytes, target_size) + .map_err(|_| E_ZLIB_DATA)?; + if d.len() != target_size && req.intermediate_size != 0 { + return Err(E_ZLIB_DATA); + } + std::borrow::Cow::Owned(d) + } else { + std::borrow::Cow::Borrowed(&compressed.bytes) + }; + let blocks = bcpack_unpack(&req, &stage1, dst_len)?; + output.bytes[..dst_len].copy_from_slice(&blocks[..dst_len]); + Ok(()) + }; #[cfg(test)] counters.completed.fetch_add(1, Ordering::Relaxed); result?; @@ -308,6 +327,7 @@ struct InFlightTask { seq: u64, req: Request, file: Option>, + dest_pages: Option>, } struct Pipeline<'a> { @@ -423,7 +443,7 @@ impl<'a> Pipeline<'a> { } note_request(&req); let loaded = (|| { - if !writable(req.destination as usize, req.destination_size as usize) { + if !req.dest_physical_pages() && !writable(req.destination as usize, req.destination_size as usize) { return Err(E_ACCESS_VIOLATION); } let handle = task.file.as_ref().and_then(|file| file.handle()).ok_or(E_FILE_HANDLE)?; @@ -438,6 +458,7 @@ impl<'a> Pipeline<'a> { self.outstanding_workers += 1; self.pool.dispatch(DecompressTask { seq, + req, compressed, output: reservation, codec_state, @@ -459,13 +480,17 @@ impl<'a> Pipeline<'a> { notify_test(self.queue, TestEvent::BeforeRetire(task.seq)); let result = result.and_then(|payload| { let n = task.req.destination_size as usize; - 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. - if writable(at, n) && (n == 0 || write_destination(at, &payload.bytes[..n])) { - Ok(()) + if task.req.dest_physical_pages() { + unsafe { write_dest_physical_pages(&task.req, task.dest_pages.as_deref(), &payload.bytes[..n]) } } else { - Err(E_ACCESS_VIOLATION) + 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. + if writable(at, n) && (n == 0 || write_destination(at, &payload.bytes[..n])) { + Ok(()) + } else { + Err(E_ACCESS_VIOLATION) + } } }); if let Err(hr) = result { @@ -497,20 +522,30 @@ fn notify_test(queue: &QueueInner, event: TestEvent) { } } -/// Only file-backed zlib with a virtual destination uses the pool. Drain before -/// handling any other entry or ending a batch, so retirement, statuses and fences -/// retain upstream FIFO semantics even if the producer never submits again. +/// File-backed zlib and/or supported BCPack requests (both virtual and physical-page destinations) +/// use the decompression pool. Drain before handling any other entry or ending a batch, so +/// retirement, statuses and fences retain upstream FIFO semantics even if the producer never submits again. pub(super) fn run(queue: &QueueInner, pool: Arc, rx: mpsc::Receiver>) { let mut pipeline = Pipeline::new(queue, pool); let mut since_status = S_OK; for batch in rx { for entry in batch { - if let Entry::Request { seq, req, ref file, .. } = entry { - if req.zlib() && !req.memory_source() && !req.dest_physical_pages() && req.swizzle() == 0 && req.bcpack() == 0 { + if let Entry::Request { seq, req, ref file, ref dest_pages, .. } = entry { + let bc = req.bcpack(); + let eligible = (req.zlib() || bc != 0) + && !req.memory_source() + && req.swizzle() == 0 + && (bc == 0 || crate::hle::bcpack::can_decode(bc)); + if eligible { let stage1_len = if req.intermediate_size == 0 { req.destination_size } else { req.intermediate_size } as usize; if let Some(cost) = pipeline.charge(&req, stage1_len) { if !queue.closed.load(Ordering::Acquire) { - pipeline.start(InFlightTask { seq, req, file: file.clone() }, stage1_len, cost, &mut since_status); + pipeline.start( + InFlightTask { seq, req, file: file.clone(), dest_pages: dest_pages.clone() }, + stage1_len, + cost, + &mut since_status, + ); } continue; } diff --git a/crates/xcl/src/hle/dstorage/parallel_tests.rs b/crates/xcl/src/hle/dstorage/parallel_tests.rs index 5d5214e4f..1edc7254e 100644 --- a/crates/xcl/src/hle/dstorage/parallel_tests.rs +++ b/crates/xcl/src/hle/dstorage/parallel_tests.rs @@ -339,11 +339,13 @@ fn budget_retires_ready_error_and_payload_without_worker_notification() { seq: 0, req: request, file: None, + dest_pages: None, }, InFlightTask { seq: 1, req: request, file: None, + dest_pages: None, }, ]); pipeline.completed.insert(0, Err(E_FILE_HANDLE)); @@ -645,3 +647,48 @@ fn a_destination_decommitted_during_decode_fails_in_fifo_order() { assert_ne!(unsafe { VirtualFree(destination, 0, MEM_RELEASE) }, 0); }); } + +#[test] +fn parallel_decode_supports_physical_page_destinations_and_late_refresh() { + with_deadline(|| { + let Some(_) = crate::gpu::uma::get() else { return }; + let payload = vec![0x6Au8; 32 * 1024]; + let file = TestFile::compressed(&[&payload]); + + // Allocate a stale page (freed before enqueue) and a live page (written after enqueue). + let mut stale_n = 1usize; + let mut stale_page = [0usize; 1]; + let mut live_n = 1usize; + let mut live_page = [0usize; 1]; + unsafe { + assert_eq!(crate::hle::kernelx::AllocateTitlePhysicalPages(null_mut(), 0, &mut stale_n, stale_page.as_mut_ptr()), 1); + assert_eq!(crate::hle::kernelx::FreeTitlePhysicalPages(null_mut(), 1, stale_page.as_mut_ptr()), 1); + assert_eq!(crate::hle::kernelx::AllocateTitlePhysicalPages(null_mut(), 0, &mut live_n, live_page.as_mut_ptr()), 1); + } + + let mut table = [stale_page[0]]; + let mut req = file.request(0, table.as_mut_ptr() as usize, 101); + req[0..8].copy_from_slice(&(ZLIB_BIT | DEST_PHYS_PAGES_BIT).to_le_bytes()); + + let pool = test_pool(2, TEST_BUDGET); + let queue = TestQueue::new(Some(pool.clone()), None); + let status = TestStatus::new(1); + unsafe { + // Enqueue while table still holds the stale freed page number; then update before submit. + queue.enqueue(&req); + std::ptr::write_volatile(table.as_mut_ptr(), live_page[0]); + } + queue.status(&status, 0); + queue.submit(); + assert_eq!(status.wait(0), S_OK); + assert_eq!(table[0], live_page[0]); + assert_eq!(pool.metrics().jobs_completed, 1); + + let mut readback = vec![0u8; payload.len()]; + unsafe { + assert!(crate::hle::kernelx::read_physical_pages(&live_page, 0, &mut readback)); + assert_eq!(crate::hle::kernelx::FreeTitlePhysicalPages(null_mut(), 1, live_page.as_mut_ptr()), 1); + } + assert_eq!(readback, payload); + }); +} diff --git a/crates/xcl/src/hle/gameinput.rs b/crates/xcl/src/hle/gameinput.rs index e7983a892..095b6601c 100644 --- a/crates/xcl/src/hle/gameinput.rs +++ b/crates/xcl/src/hle/gameinput.rs @@ -16,6 +16,7 @@ #![allow(non_snake_case)] +use std::collections::VecDeque; use std::ffi::c_void; use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; @@ -159,6 +160,8 @@ static PAD_CONNECTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicB /// controller connected the slots are searched at most every `SEARCH_US` static LAST_SEARCH: AtomicU64 = AtomicU64::new(0); const SEARCH_US: u64 = 1_000_000; +/// Last rumble command sent to XInput, packed as `(pad << 32) | (lo << 16) | hi`, or `u64::MAX` when unset. +static LAST_RUMBLE: AtomicU64 = AtomicU64::new(u64::MAX); /// The PC's controller (the XInput slot that answers first: an Xbox pad, or any pad Windows /// exposes through XInput) as a GameInput gamepad state; None without one. @@ -188,6 +191,7 @@ fn xinput_pad() -> Option { if r == 0 { if !connected || k != first { crate::xlog_info!("GameInput: the PC's controller (XInput slot {k}) is the title's gamepad"); + LAST_RUMBLE.store(u64::MAX, Ordering::Relaxed); } PAD.store(k, Ordering::Relaxed); PAD_CONNECTED.store(true, Ordering::Relaxed); @@ -209,6 +213,7 @@ fn xinput_pad() -> Option { if super::kbm::enabled() { " (keyboard and mouse still play)" } else { "" } ); PAD_CONNECTED.store(false, Ordering::Relaxed); + LAST_RUMBLE.store(u64::MAX, Ordering::Relaxed); LAST_SEARCH.store(now_us(), Ordering::Relaxed); } None @@ -234,33 +239,148 @@ fn button_named(name: &str) -> Option { "VIEW" => VIEW, "LB" => LEFT_SHOULDER, "RB" => RIGHT_SHOULDER, + "LS" | "L3" => LEFT_STICK, + "RS" | "R3" => RIGHT_STICK, _ => return None, }) } -/// `XCL_PRESS_AT=s:BUTTON,…` ("14:A,18.5:DOWN,20:A"; buttons A B X Y UP DOWN LEFT RIGHT MENU -/// VIEW LB RB) and `XCL_PRESS_A_AT=s,…`: buttons held for 200 ms at those seconds after the -/// host started (the log's times) – a title's menus walked without a person at the controls. -fn parse_presses(script: &str, a_only: &str) -> Vec<(f64, u32)> { - let mut v: Vec<(f64, u32)> = a_only.split(',').filter_map(|s| s.trim().parse().ok()).map(|s| (s, A)).collect(); +#[derive(Clone, Copy, Debug, PartialEq)] +enum ScriptedKind { + Button(u32), + LeftTrigger, + RightTrigger, + LeftStick(f32, f32), + RightStick(f32, f32), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct ScriptedAction { + start: f64, + duration: f64, + kind: ScriptedKind, +} + +fn action_named(name: &str) -> Option { + if let Some(b) = button_named(name) { + return Some(ScriptedKind::Button(b)); + } + Some(match name.to_ascii_uppercase().as_str() { + "LT" => ScriptedKind::LeftTrigger, + "RT" => ScriptedKind::RightTrigger, + "LUP" => ScriptedKind::LeftStick(0.0, 1.0), + "LDOWN" => ScriptedKind::LeftStick(0.0, -1.0), + "LLEFT" => ScriptedKind::LeftStick(-1.0, 0.0), + "LRIGHT" => ScriptedKind::LeftStick(1.0, 0.0), + "RUP" => ScriptedKind::RightStick(0.0, 1.0), + "RDOWN" => ScriptedKind::RightStick(0.0, -1.0), + "RLEFT" => ScriptedKind::RightStick(-1.0, 0.0), + "RRIGHT" => ScriptedKind::RightStick(1.0, 0.0), + _ => return None, + }) +} + +/// `XCL_PRESS_AT=s:ACTION[:dur],…` ("14:A,18.5:DOWN,20:LUP:1.5"; buttons A B X Y UP DOWN LEFT +/// RIGHT MENU VIEW LB RB LS RS, triggers LT RT, sticks LUP LDOWN LLEFT LRIGHT RUP RDOWN RLEFT +/// RRIGHT) and `XCL_PRESS_A_AT=s,…`: inputs held for `dur` (default 200 ms) at those seconds +/// after host start (the log's times) – menus and world movement walked without a person at +/// the controls. +fn parse_scripted_actions(script: &str, a_only: &str) -> Vec { + const DEFAULT_DUR: f64 = 0.2; + let mut v: Vec = a_only + .split(',') + .filter_map(|s| s.trim().parse::().ok()) + .map(|start| ScriptedAction { start, duration: DEFAULT_DUR, kind: ScriptedKind::Button(A) }) + .collect(); for item in script.split(',').map(str::trim).filter(|s| !s.is_empty()) { - match item.split_once(':').and_then(|(s, b)| Some((s.trim().parse::().ok()?, button_named(b.trim())?))) { + let mut parts = item.split(':').map(str::trim); + let parsed = (|| -> Option { + let start = parts.next()?.parse::().ok()?; + let kind = action_named(parts.next()?)?; + let duration = match parts.next() { + None => DEFAULT_DUR, + Some(d) => { + let secs = d.parse::().ok()?; + if !(secs > 0.0 && secs.is_finite()) { + return None; + } + secs + } + }; + if parts.next().is_some() { + return None; + } + Some(ScriptedAction { start, duration, kind }) + })(); + match parsed { Some(p) => v.push(p), - None => crate::xlog_warn!("GameInput: XCL_PRESS_AT entry {item:?} not understood (seconds:BUTTON)"), + None => crate::xlog_warn!("GameInput: XCL_PRESS_AT entry {item:?} not understood (seconds:ACTION[:duration])"), } } v } -fn scripted() -> u32 { - static AT: OnceLock> = OnceLock::new(); - let at = AT.get_or_init(|| { +#[cfg(test)] +fn parse_presses(script: &str, a_only: &str) -> Vec<(f64, u32)> { + parse_scripted_actions(script, a_only) + .into_iter() + .filter_map(|a| match a.kind { + ScriptedKind::Button(b) => Some((a.start, b)), + _ => None, + }) + .collect() +} + +fn scripted_actions() -> &'static [ScriptedAction] { + static AT: OnceLock> = OnceLock::new(); + AT.get_or_init(|| { let var = |n: &str| std::env::var(n).unwrap_or_default(); - parse_presses(&var("XCL_PRESS_AT"), &var("XCL_PRESS_A_AT")) - }); - // seconds since the host started, as the log's times (not since the title first polled) + parse_scripted_actions(&var("XCL_PRESS_AT"), &var("XCL_PRESS_A_AT")) + }) +} + +fn apply_scripted_actions(s: &mut GamepadState, actions: &[ScriptedAction], t: f64) { + let (mut lx, mut ly, mut rx, mut ry) = (0.0f32, 0.0f32, 0.0f32, 0.0f32); + for &a in actions { + if t < a.start || t >= a.start + a.duration { + continue; + } + match a.kind { + ScriptedKind::Button(b) => s.buttons |= b, + ScriptedKind::LeftTrigger => s.left_trigger = 1.0, + ScriptedKind::RightTrigger => s.right_trigger = 1.0, + ScriptedKind::LeftStick(x, y) => { + lx += x; + ly += y; + } + ScriptedKind::RightStick(x, y) => { + rx += x; + ry += y; + } + } + } + let apply_stick = |dx: f32, dy: f32, sx: &mut f32, sy: &mut f32| { + let len = dx.hypot(dy); + if len > 0.0 { + let scale = if len > 1.0 { 1.0 / len } else { 1.0 }; + *sx = (*sx + dx * scale).clamp(-1.0, 1.0); + *sy = (*sy + dy * scale).clamp(-1.0, 1.0); + } + }; + apply_stick(lx, ly, &mut s.left_x, &mut s.left_y); + apply_stick(rx, ry, &mut s.right_x, &mut s.right_y); +} + +fn scripted() -> u32 { let t = crate::log::uptime(); - at.iter().filter(|&&(s, _)| t >= s && t < s + 0.2).fold(0, |b, &(_, g)| b | g) + scripted_actions() + .iter() + .filter(|a| t >= a.start && t < a.start + a.duration) + .filter_map(|a| match a.kind { + ScriptedKind::Button(b) => Some(b), + _ => None, + }) + .fold(0, |b, g| b | g) } #[link(name = "user32")] @@ -313,6 +433,7 @@ pub fn poll() -> GamepadState { super::kbm::apply, scripted, ); + apply_scripted_actions(&mut s, scripted_actions(), crate::log::uptime()); { // the first presses of each button: worth a line (is input arriving at all?) static SEEN: AtomicU32 = AtomicU32::new(0); @@ -373,7 +494,7 @@ struct DeviceInfo { rest: [u8; 896], } -const DEVICE_ID: [u8; 32] = *b"XCL gamepad 0"; +const DEVICE_ID: [u8; 32] = *b"XCL gamepad 0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; /// The gamepad's APP_LOCAL_DEVICE_ID (XUser's device association names it). pub fn gamepad_device_id() -> [u8; 32] { @@ -454,8 +575,8 @@ fn input() -> *mut Object { (2, release as usize), (3, get_current_timestamp as usize), (4, get_current_reading as usize), - (5, other_reading as usize), - (6, other_reading as usize), + (5, get_next_reading as usize), + (6, get_previous_reading as usize), (7, get_temporal_reading as usize), (8, register_reading_callback as usize), (9, register_device_callback as usize), @@ -515,8 +636,35 @@ fn reading_vtable() -> *const usize { static SEQUENCE: AtomicU64 = AtomicU64::new(0); +/// Bounded ring of recent distinct gamepad readings `(sequence, timestamp, state)` backing +/// `GetNextReading` / `GetPreviousReading`. Only distinct state transitions push a new entry, +/// so `while (SUCCEEDED(GetNextReading(r, ...)))` always terminates cleanly. +const HISTORY_CAP: usize = 32; +static HISTORY: Mutex> = Mutex::new(VecDeque::new()); + +fn new_reading_with(state: GamepadState, sequence: u64, timestamp: u64) -> *mut Reading { + Box::into_raw(Box::new(Reading { vtable: reading_vtable(), refs: AtomicU32::new(1), state, sequence, timestamp })) +} + +fn record_state(state: GamepadState) -> (u64, u64) { + let ts = now_us(); + let mut h = HISTORY.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&(seq, _, last_state)) = h.back() { + if last_state == state { + return (seq, ts); + } + } + let seq = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; + if h.len() >= HISTORY_CAP { + h.pop_front(); + } + h.push_back((seq, ts, state)); + (seq, ts) +} + fn new_reading(state: GamepadState) -> *mut Reading { - Box::into_raw(Box::new(Reading { vtable: reading_vtable(), refs: AtomicU32::new(1), state, sequence: SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1, timestamp: now_us() })) + let (seq, ts) = record_state(state); + new_reading_with(state, seq, ts) } // ---- shared methods ---- @@ -587,12 +735,30 @@ unsafe extern "system" fn get_battery_state(_this: *mut Object, state: *mut [u32 unsafe extern "system" fn motor_powered_on(_this: *mut Object, _motor: u32) -> bool { false } +/// Decide whether a rumble update should be forwarded to `XInputSetState`: skips calls when +/// no XInput controller is connected (avoiding slow empty-slot driver probes every frame) and +/// deduplicates identical motor speeds on the active slot. +fn should_send_rumble(connected: bool, pad: u32, lo: f32, hi: f32, last: &AtomicU64) -> Option<(u32, [u16; 2])> { + if !connected { + return None; + } + let speed = |v: f32| (v.clamp(0.0, 1.0) * 65535.0) as u16; + let motors = [speed(lo), speed(hi)]; + let packed = ((pad as u64) << 32) | ((motors[0] as u64) << 16) | (motors[1] as u64); + if last.swap(packed, Ordering::Relaxed) == packed { + return None; + } + Some((pad, motors)) +} + /// GameInputRumbleParams {low, high, left trigger, right trigger}: the XInput motors unsafe extern "system" fn set_rumble_state(_this: *mut Object, p: *const [f32; 4]) { - let Some((_, set)) = xinput() else { return }; let (lo, hi) = if p.is_null() { (0.0, 0.0) } else { ((*p)[0], (*p)[1]) }; - let speed = |v: f32| (v.clamp(0.0, 1.0) * 65535.0) as u16; - set(PAD.load(Ordering::Relaxed), &[speed(lo), speed(hi)]); + let Some((pad, motors)) = should_send_rumble(PAD_CONNECTED.load(Ordering::Relaxed), PAD.load(Ordering::Relaxed), lo, hi, &LAST_RUMBLE) else { + return; + }; + let Some((_, set)) = xinput() else { return }; + set(pad, &motors); } // ---- IGameInput ---- @@ -633,13 +799,60 @@ unsafe extern "system" fn get_current_reading(_this: *mut Object, kind: u32, dev S_OK } -/// the readings before and after one are not kept -unsafe extern "system" fn other_reading(_this: *mut Object, _reference: *mut c_void, kind: u32, _dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { +/// Return the next distinct reading recorded after `reference`, or `GAMEINPUT_E_READING_NOT_FOUND` +/// once caught up with the latest state. +unsafe extern "system" fn get_next_reading(_this: *mut Object, reference: *mut c_void, kind: u32, dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { note_query("GetNext/PreviousReading", kind); - if !out.is_null() { - *out = std::ptr::null_mut(); + if out.is_null() { + return E_POINTER; + } + *out = std::ptr::null_mut(); + if reference.is_null() || kind & KINDS == 0 || !ours(dev) { + return GAMEINPUT_E_READING_NOT_FOUND; + } + // Capture any fresh host state transition so polling loops using GetNextReading see it. + let _ = record_state(poll()); + let ref_seq = (*(reference as *const Reading)).sequence; + let next = HISTORY + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .find(|&&(seq, _, _)| seq > ref_seq) + .copied(); + match next { + Some((seq, ts, state)) => { + *out = new_reading_with(state, seq, ts); + S_OK + } + None => GAMEINPUT_E_READING_NOT_FOUND, + } +} + +/// Return the previous distinct reading recorded before `reference`, or `GAMEINPUT_E_READING_NOT_FOUND`. +unsafe extern "system" fn get_previous_reading(_this: *mut Object, reference: *mut c_void, kind: u32, dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { + note_query("GetNext/PreviousReading", kind); + if out.is_null() { + return E_POINTER; + } + *out = std::ptr::null_mut(); + if reference.is_null() || kind & KINDS == 0 || !ours(dev) { + return GAMEINPUT_E_READING_NOT_FOUND; + } + let ref_seq = (*(reference as *const Reading)).sequence; + let prev = HISTORY + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .rev() + .find(|&&(seq, _, _)| seq < ref_seq) + .copied(); + match prev { + Some((seq, ts, state)) => { + *out = new_reading_with(state, seq, ts); + S_OK + } + None => GAMEINPUT_E_READING_NOT_FOUND, } - GAMEINPUT_E_READING_NOT_FOUND } unsafe extern "system" fn get_temporal_reading(this: *mut Object, _timestamp: u64, dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { @@ -1360,4 +1573,92 @@ mod tests { assert!(gate.finished.load(Ordering::Acquire)); releaser.join().unwrap(); } + + #[test] + fn rumble_skips_disconnected_pad_and_deduplicates_unchanged_speeds() { + let last = AtomicU64::new(u64::MAX); + assert_eq!(should_send_rumble(false, 0, 1.0, 1.0, &last), None); + assert_eq!(should_send_rumble(true, 0, 0.5, 0.25, &last), Some((0, [32767, 16383]))); + // Identical values on the same pad are skipped. + assert_eq!(should_send_rumble(true, 0, 0.5, 0.25, &last), None); + // Changed intensity or slot forwards immediately. + assert_eq!(should_send_rumble(true, 0, 0.0, 0.0, &last), Some((0, [0, 0]))); + assert_eq!(should_send_rumble(true, 1, 0.0, 0.0, &last), Some((1, [0, 0]))); + } + + #[test] + fn next_and_previous_reading_walk_state_changes_and_terminate() { + unsafe { + let g = input(); + let s1 = GamepadState { buttons: A, ..Default::default() }; + let s2 = GamepadState { buttons: B, left_x: 0.5, ..Default::default() }; + let s3 = GamepadState { buttons: X, right_trigger: 1.0, ..Default::default() }; + let r1 = new_reading(s1); + let r2 = new_reading(s2); + let r3 = new_reading(s3); + assert!(reading_sequence(r1, KIND_GAMEPAD) < reading_sequence(r2, KIND_GAMEPAD)); + assert!(reading_sequence(r2, KIND_GAMEPAD) < reading_sequence(r3, KIND_GAMEPAD)); + + let mut cur = r1; + let mut seen = Vec::new(); + for _ in 0..HISTORY_CAP + 4 { + let mut next = std::ptr::null_mut(); + let hr = get_next_reading(g, cur as *mut c_void, KIND_GAMEPAD, std::ptr::null_mut(), &mut next); + if hr == GAMEINPUT_E_READING_NOT_FOUND { + assert!(next.is_null()); + break; + } + assert_eq!(hr, S_OK); + let mut st = GamepadState::default(); + assert!(reading_gamepad(next, &mut st)); + seen.push(st); + if cur != r1 { + reading_release(cur); + } + cur = next; + } + assert!(seen.contains(&s2) && seen.contains(&s3), "expected s2 and s3 in next chain: {seen:?}"); + + // Walk backward from r3 to r2. + let mut prev = std::ptr::null_mut(); + assert_eq!(get_previous_reading(g, r3 as *mut c_void, KIND_GAMEPAD, std::ptr::null_mut(), &mut prev), S_OK); + let mut pst = GamepadState::default(); + assert!(reading_gamepad(prev, &mut pst)); + assert_eq!(pst, s2); + + if cur != r1 { + reading_release(cur); + } + reading_release(prev); + reading_release(r1); + reading_release(r2); + reading_release(r3); + } + } + + #[test] + fn extended_scripted_actions_drive_triggers_sticks_and_durations() { + let actions = parse_scripted_actions("10:A, 12:RT:1.5, 12:LUP:1.0, 12:LRIGHT:1.0, 15:LS:0.5, 16:RDOWN", "5"); + let mut at5 = GamepadState::default(); + apply_scripted_actions(&mut at5, &actions, 5.05); + assert_eq!(at5.buttons, A); + + let mut at12 = GamepadState::default(); + apply_scripted_actions(&mut at12, &actions, 12.5); + assert_eq!(at12.right_trigger, 1.0); + assert!((at12.left_x - at12.left_y).abs() < 1e-6 && (at12.left_x * at12.left_x + at12.left_y * at12.left_y - 1.0).abs() < 1e-6); + + let mut at13_2 = GamepadState::default(); + apply_scripted_actions(&mut at13_2, &actions, 13.2); + assert_eq!(at13_2.right_trigger, 1.0, "RT lasts 1.5 s"); + assert_eq!((at13_2.left_x, at13_2.left_y), (0.0, 0.0), "LUP/LRIGHT ended at 13.0 s"); + + let mut at15 = GamepadState::default(); + apply_scripted_actions(&mut at15, &actions, 15.2); + assert_eq!(at15.buttons, LEFT_STICK); + + let mut at16 = GamepadState::default(); + apply_scripted_actions(&mut at16, &actions, 16.1); + assert_eq!((at16.right_x, at16.right_y), (0.0, -1.0)); + } } diff --git a/crates/xcl/src/hle/kbm.rs b/crates/xcl/src/hle/kbm.rs index 6d18b1cfb..14a6f0cac 100644 --- a/crates/xcl/src/hle/kbm.rs +++ b/crates/xcl/src/hle/kbm.rs @@ -204,6 +204,8 @@ const SC_E: (u32, i32) = (0x12, 0x45); const SC_A: (u32, i32) = (0x1E, 0x41); const SC_S: (u32, i32) = (0x1F, 0x53); const SC_D: (u32, i32) = (0x20, 0x44); +const SC_Z: (u32, i32) = (0x2C, 0x5A); +const SC_C: (u32, i32) = (0x2E, 0x43); /// the XCL window (raw input goes there; the cursor is held in it) static WINDOW: AtomicIsize = AtomicIsize::new(0); @@ -387,6 +389,28 @@ pub(crate) fn scancode_to_vk(scancode: u32, fallback_vk: i32, layout: *mut c_voi } } +/// Minimum elapsed interval (seconds) before decaying mouse velocity on a zero-delta poll. +/// Avoids high-frequency multi-thread polls (game loop + 250 Hz callback poller) clamping tiny +/// `dt` up to 1 ms and decaying camera velocity faster than wall-clock time. +const MIN_ZERO_DECAY_DT: f32 = 0.0005; + +/// Advance smoothed mouse velocity for raw counts `(dx, dy)` over `dt` seconds. +/// Returns `true` if `dt` should be consumed (advancing the timestamp), `false` if this was a +/// sub-half-millisecond zero-delta poll whose elapsed time should accumulate into the next sample. +pub(crate) fn update_mouse_velocity(velocity: &mut Velocity, dx: i32, dy: i32, dt: f32) -> bool { + if dx == 0 && dy == 0 && dt < MIN_ZERO_DECAY_DT { + return false; + } + velocity.update(dx, dy, dt); + true +} + +/// Whether host mouse buttons (LMB/RMB/MMB) should currently map into gamepad triggers/stick click: +/// only while the cursor is captured inside the client area and not during a window drag/resize. +pub(crate) fn mouse_buttons_active(captured: bool, sizing: bool) -> bool { + captured && !sizing +} + /// The keyboard and the mouse on top of `s` (the real controller), while the XCL window /// has the focus. pub fn apply(s: &mut GamepadState) { @@ -411,29 +435,40 @@ pub fn apply(s: &mut GamepadState) { s.left_y = ly; } // (Space / Enter, Escape / Backspace, arrows, Tab, P: `gameinput::keyboard`) - const VK_KEYS: [(i32, u32); 3] = [ + const VK_KEYS: [(i32, u32); 2] = [ (0xA0, LEFT_STICK), // Left Shift (0xA2, RIGHT_STICK), // Left Ctrl - (0x04, RIGHT_STICK), // middle mouse button ]; - const SC_KEYS: [((u32, i32), u32); 2] = [ - (SC_E, Y), // physical E - (SC_Q, X), // physical Q + // Holdable shoulder buttons (Z = LB, C = RB) complement wheel notches for actions like weapon wheel / cover. + const SC_KEYS: [((u32, i32), u32); 4] = [ + (SC_E, Y), // physical E + (SC_Q, X), // physical Q + (SC_Z, LEFT_SHOULDER), // physical Z (holdable LB) + (SC_C, RIGHT_SHOULDER), // physical C (holdable RB) ]; s.buttons |= VK_KEYS.iter().filter(|(k, _)| key(*k)).fold(0, |b, (_, g)| b | g); s.buttons |= SC_KEYS.iter().filter(|(sc, _)| sc_key(*sc)).fold(0, |b, (_, g)| b | g); - if key(0x01) { - s.right_trigger = 1.0; - } - if key(0x02) { - s.left_trigger = 1.0; + if mouse_buttons_active(CAPTURED.load(Ordering::Acquire), SIZING.load(Ordering::Acquire)) { + if key(0x04) { + s.buttons |= RIGHT_STICK; + } + if key(0x01) { + s.right_trigger = 1.0; + } + if key(0x02) { + s.left_trigger = 1.0; + } } let mut g = MOUSE.lock().unwrap_or_else(|e| e.into_inner()); let m = g.get_or_insert_with(|| Mouse { last: Instant::now(), velocity: Velocity::default(), wheel: Wheel::default(), wheel_rest: 0 }); let now = Instant::now(); let dt = now.duration_since(m.last).as_secs_f32(); - m.last = now; - m.velocity.update(DX.swap(0, Ordering::Relaxed), DY.swap(0, Ordering::Relaxed), dt); + let dx = DX.swap(0, Ordering::Relaxed); + let dy = DY.swap(0, Ordering::Relaxed); + let updated = update_mouse_velocity(&mut m.velocity, dx, dy, dt); + if updated { + m.last = now; + } let (rx, ry) = stick_from_mouse(m.velocity.x, m.velocity.y, crate::state::config().mouse_sensitivity); if (rx != 0.0 || ry != 0.0) && rx * rx + ry * ry >= s.right_x * s.right_x + s.right_y * s.right_y { s.right_x = rx; @@ -443,7 +478,8 @@ pub fn apply(s: &mut GamepadState) { let notches = m.wheel_rest / 120; m.wheel_rest -= notches * 120; m.wheel.notches(notches); - s.buttons |= m.wheel.step(dt.min(0.1)); + let wheel_dt = if updated { dt.min(0.1) } else { 0.0 }; + s.buttons |= m.wheel.step(wheel_dt); } #[cfg(test)] @@ -519,7 +555,7 @@ mod tests { let layout = keyboard_layout_for_window(std::ptr::null_mut()); assert!(!layout.is_null(), "current thread should have an active Windows keyboard layout"); - let cluster = [SC_Q, SC_W, SC_E, SC_A, SC_S, SC_D]; + let cluster = [SC_Q, SC_W, SC_E, SC_A, SC_S, SC_D, SC_Z, SC_C]; let mut seen_vks = Vec::new(); for &(sc, fb) in &cluster { let vk = scancode_to_vk(sc, fb, layout); @@ -590,4 +626,27 @@ mod tests { assert_eq!(m.wheel.step(0.01), 0, "stale wheel notches must not fire after refocusing"); } } + + #[test] + fn mouse_buttons_require_capture_and_not_sizing() { + assert!(mouse_buttons_active(true, false)); + assert!(!mouse_buttons_active(false, false)); + assert!(!mouse_buttons_active(true, true)); + assert!(!mouse_buttons_active(false, true)); + } + + #[test] + fn high_frequency_zero_polls_do_not_prematurely_decay_velocity() { + let mut v = Velocity { x: 2000.0, y: -1500.0 }; + let before = v; + for _ in 0..100 { + assert!(!update_mouse_velocity(&mut v, 0, 0, 0.0001)); + } + assert_eq!(v, before, "sub-half-ms zero polls must not decay velocity"); + // Non-zero movement is always consumed even over tiny dt. + assert!(update_mouse_velocity(&mut v, 10, 0, 0.0001)); + // Normal frame-rate zero poll decays velocity smoothly. + assert!(update_mouse_velocity(&mut v, 0, 0, 0.016)); + assert!(v.x < 2000.0 && v.y > -1500.0); + } } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index a73574718..9c8d5760e 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -633,15 +633,82 @@ pub unsafe fn runtime_free(p: usize, attrs: u64) { } } +/// Maximum virtual address for 40-bit console allocations (`[4 GiB, 1 TiB - 1]`). +/// Console BVH builders (e.g. `XboxBvhBuilder.dll`) and 40-bit tagged pointers reject >40-bit VAs. +const CONSOLE_40BIT_LOW: usize = 0x1_0000_0000; +const CONSOLE_40BIT_HIGH: usize = (1usize << 40) - 1; + +#[repr(C)] +struct MemAddressRequirements { + lowest_starting_address: *mut c_void, + highest_ending_address: *mut c_void, + alignment: usize, +} + +#[repr(C)] +struct MemExtendedParameter { + type_and_reserved: u64, + pointer: *mut c_void, +} + +type VirtualAlloc2Fn = unsafe extern "system" fn( + HANDLE, + *const c_void, + usize, + u32, + u32, + *mut MemExtendedParameter, + u32, +) -> *mut c_void; + +fn virtual_alloc2() -> Option { + static FN: std::sync::OnceLock> = std::sync::OnceLock::new(); + let ptr = *FN.get_or_init(|| unsafe { + let h = ll::GetModuleHandleW(crate::util::wide("kernelbase.dll").as_ptr()); + if h.is_null() { + return None; + } + ll::GetProcAddress(h, b"VirtualAlloc2\0".as_ptr()).map(|f| f as usize) + }); + ptr.map(|p| unsafe { std::mem::transmute::(p) }) +} + +/// Reserve/commit Windows memory within the console's 40-bit address range (`[4 GiB, 1 TiB - 1]`) +/// via `VirtualAlloc2`, falling back to unconstrained `VirtualAlloc` if unavailable or full. +unsafe fn alloc_below_40bit(size: usize, alloc_type: u32, protect: u32) -> *mut c_void { + if let Some(va2) = virtual_alloc2() { + let mut req = MemAddressRequirements { + lowest_starting_address: CONSOLE_40BIT_LOW as *mut c_void, + highest_ending_address: CONSOLE_40BIT_HIGH as *mut c_void, + alignment: 0, + }; + let mut param = MemExtendedParameter { + type_and_reserved: 1, // MemExtendedParameterAddressRequirements + pointer: &mut req as *mut MemAddressRequirements as *mut c_void, + }; + let p = va2(thr::GetCurrentProcess(), std::ptr::null(), size, alloc_type, protect, &mut param, 1); + if !p.is_null() { + return p; + } + } + mem::VirtualAlloc(std::ptr::null(), size, alloc_type, protect) +} + /// `void* XMemVirtualAlloc(void* address, SIZE_T size, DWORD type, XALLOC_ATTRIBUTES attributes, /// DWORD protect)`: VirtualAlloc with an allocator's attributes – a graphics memory type is -/// GPU-visible memory (as MEM_GRAPHICS: sparse VRAM pool). +/// GPU-visible memory (as MEM_GRAPHICS: sparse VRAM pool). Plain CPU fallbacks stay below 40 bits +/// so console BVH builders and 40-bit pointer tables accept them. pub unsafe extern "system" fn XMemVirtualAlloc(addr: *const c_void, size: usize, t: u32, attrs: u64, p: u32) -> *mut c_void { let a = XAllocAttrs::decode(attrs); let mut t = if a.memory_type != 0 { t | MEM_GRAPHICS } else { t }; if a.memory_type != 0 && a.page_size == 2 { t |= 0x8000_0000; } + if addr.is_null() && a.memory_type == 0 && (t & (0x40000 | 0x4000)) == 0 && (t & MEM_64K_PAGES) != MEM_64K_PAGES && (p & PAGE_GRAPHICS_ANY) == 0 && (t & 0x2000_0000) == 0 { + let q = alloc_below_40bit(size, sanitize_alloc_type(t), sanitize_protect(p)); + trace_mem("XMemVirtualAlloc (40-bit)", 0, size, t as u64, p, q as usize); + return q; + } VirtualAlloc(addr, size, t, p) } @@ -859,8 +926,43 @@ const PHYS_PAGE: usize = 0x1_0000; /// Size of one console physical page (64 KiB). pub const PHYS_PAGE_SIZE: usize = PHYS_PAGE; -/// first page index → (pages in the block, pages still allocated, the block's home) -static PHYS_BLOCKS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +struct PhysBlock { + count: usize, + live: usize, + home: usize, + /// 1 bit per 64 KiB page (`1` = still allocated, `0` = freed). + bitmap: Vec, +} + +impl PhysBlock { + fn new(count: usize, home: usize) -> Self { + let words = count.div_ceil(64); + let mut bitmap = vec![u64::MAX; words]; + let rem = count % 64; + if rem != 0 { + bitmap[words - 1] = (1u64 << rem) - 1; + } + Self { count, live: count, home, bitmap } + } + + #[inline] + fn is_live(&self, offset: usize) -> bool { + offset < self.count && (self.bitmap[offset / 64] & (1u64 << (offset % 64))) != 0 + } + + #[inline] + fn free_page(&mut self, offset: usize) -> bool { + if !self.is_live(offset) { + return false; + } + self.bitmap[offset / 64] &= !(1u64 << (offset % 64)); + self.live -= 1; + true + } +} + +/// first page index → live-page metadata and home base address +static PHYS_BLOCKS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); /// the next page index handed out (page numbers are not addresses: a block's home is in a /// sparse window, the coherent one, or – without room there – plain reserved memory) @@ -915,8 +1017,14 @@ fn page_index(page: usize) -> Option { fn page_home(page: usize) -> Option { let index = page_index(page)?; let blocks = PHYS_BLOCKS.lock().ok()?; - let (&first, &(count, live, home)) = blocks.range(..=index).next_back()?; - (live > 0 && index < first.checked_add(count)?).then(|| home.checked_add((index - first).checked_mul(PHYS_PAGE)?)).flatten() + let (&first, block) = blocks.range(..=index).next_back()?; + let off = index - first; + block.is_live(off).then(|| block.home.checked_add(off.checked_mul(PHYS_PAGE)?)).flatten() +} + +/// Whether `page` is currently a live physical page number from `AllocateTitlePhysicalPages`. +pub fn is_live_physical_page(page: usize) -> bool { + page_home(page).is_some() } /// Whether a home is only reserved until it is used (a sparse window's, or plain memory's – @@ -925,9 +1033,34 @@ fn lazy_home(home: usize) -> bool { crate::gpu::uma::get().is_none_or(|u| u.is_sparse(home) || !u.contains(home)) } -/// Resolve the live virtual addresses of the physical pages covering `offset..offset+len`. +/// Where a physical page's bytes live right now for `read_physical_pages`: `None` means the +/// page is untouched (lazy or uncommitted home) and reads as all zeros without committing RAM. +unsafe fn resolve_physical_pages_for_read(away: Option<&Away>, pages: &[usize], offset: usize, len: usize) -> Option>> { + if offset >= PHYS_PAGE { + return None; + } + let span = offset.checked_add(len)?; + let need = span.div_ceil(PHYS_PAGE); + if pages.len() < need { + return None; + } + let mut run = StateRun::default(); + let mut addrs = Vec::with_capacity(need); + for &p in &pages[..need] { + let home = page_home(p)?; + let addr = match away.and_then(|a| a.page.get(&p).copied()) { + Some(at) => (!lazy::is_lazy(at)).then_some(at), + None => (!lazy_home(home) || committed_page_in(home, &mut run)).then_some(home), + }; + addrs.push(addr); + } + Some(addrs) +} + +/// Resolve the live writable virtual addresses of the physical pages covering `offset..offset+len`. +/// Commits lazy mapped-away pages explicitly so writes never raise a page fault under `AWAY`. /// Caller must hold `AWAY`. -unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: usize, len: usize) -> Option> { +unsafe fn resolve_physical_pages_for_write(away: Option<&Away>, pages: &[usize], offset: usize, len: usize) -> Option> { if offset >= PHYS_PAGE { return None; } @@ -940,7 +1073,10 @@ unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: u for &p in &pages[..need] { let home = page_home(p)?; let addr = match away.and_then(|a| a.page.get(&p).copied()) { - Some(at) => at, + Some(at) => { + lazy::ensure(at, PHYS_PAGE); + at + } None => home_again(home)?, }; addrs.push(addr); @@ -950,18 +1086,21 @@ unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: u /// Copy `dst.len()` bytes starting at `offset` within `pages` (each a 64 KiB physical page /// number from `AllocateTitlePhysicalPages`). Returns `false` if `offset >= PHYS_PAGE_SIZE`, -/// `pages` is too short, or any page is not a live allocation. +/// `pages` is too short, or any page is not a live allocation. Never commits untouched pages. pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8]) -> bool { if dst.is_empty() { return offset < PHYS_PAGE; } let g = AWAY.lock().unwrap(); - let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, dst.len()) else { return false }; + let Some(addrs) = resolve_physical_pages_for_read(g.as_ref(), pages, offset, dst.len()) else { return false }; let mut done = 0; let mut page_off = offset; for addr in addrs { let chunk = (PHYS_PAGE - page_off).min(dst.len() - done); - std::ptr::copy_nonoverlapping((addr + page_off) as *const u8, dst.as_mut_ptr().add(done), chunk); + match addr { + Some(a) => std::ptr::copy_nonoverlapping((a + page_off) as *const u8, dst.as_mut_ptr().add(done), chunk), + None => std::ptr::write_bytes(dst.as_mut_ptr().add(done), 0, chunk), + } done += chunk; page_off = 0; } @@ -975,7 +1114,7 @@ pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) - return offset < PHYS_PAGE; } let g = AWAY.lock().unwrap(); - let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, src.len()) else { return false }; + let Some(addrs) = resolve_physical_pages_for_write(g.as_ref(), pages, offset, src.len()) else { return false }; let mut done = 0; let mut page_off = offset; for addr in addrs { @@ -1003,9 +1142,12 @@ unsafe fn move_home_away(away: &mut Away, home: usize) -> bool { false } -/// The homes `move_home_away` collected, decommitted in runs of neighbouring pages. -unsafe fn give_back_homes(away: &mut Away) { - let mut homes = std::mem::take(&mut away.gone); +/// Decommit `homes` (64 KiB aligned home addresses) in coalesced contiguous runs, notifying +/// sparse UMA tile tracking for sparse windows. +unsafe fn decommit_home_runs(homes: &mut Vec) { + if homes.is_empty() { + return; + } homes.sort_unstable(); homes.dedup(); let mut i = 0; @@ -1024,6 +1166,12 @@ unsafe fn give_back_homes(away: &mut Away) { } } +/// The homes `move_home_away` collected, decommitted in runs of neighbouring pages. +unsafe fn give_back_homes(away: &mut Away) { + let mut homes = std::mem::take(&mut away.gone); + decommit_home_runs(&mut homes); +} + /// 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) { @@ -1207,15 +1355,23 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return 0; }; - // (a sparse or plain home is committed when it is used: `home_again`); without room in - // unified memory plain memory (pages mapped into the title's own reservations never use - // their home: a retail game's 6.1 GB of them did not fit next to its GPU heaps) - let block = u.sparse_alloc(bytes, PHYS_PAGE).map(|(p, _)| p).or_else(|| u.alloc(bytes, PHYS_PAGE).map(|p| p as usize)).or_else(|| { - let p = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| crate::xlog_info!("AllocateTitlePhysicalPages({n}): no room in unified memory – their home is plain memory")); - (p != 0).then_some(p) - }); + // (a sparse or plain home is committed when it is used: `home_again`). Only small pools + // fall back to the pre-committed coherent UMA window (preserving headroom for GPU heaps); + // large pools (e.g. a retail game's 6.1 GiB) go straight to zero-commit reserved memory so + // they never double-commit RAM or starve coherent GPU upload heaps. + const COHERENT_PHYS_MAX: usize = 16 << 20; + const COHERENT_PHYS_KEEP: usize = 256 << 20; + let coherent_ok = bytes <= COHERENT_PHYS_MAX && u.size().saturating_sub(u.used()) >= bytes.saturating_add(COHERENT_PHYS_KEEP); + let block = u + .sparse_alloc(bytes, PHYS_PAGE) + .map(|(p, _)| p) + .or_else(|| coherent_ok.then(|| u.alloc(bytes, PHYS_PAGE).map(|p| p as usize)).flatten()) + .or_else(|| { + let p = alloc_below_40bit(bytes, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_info!("AllocateTitlePhysicalPages({n}): no room in sparse UMA – their home is zero-commit reserved memory")); + (p != 0).then_some(p) + }); let Some(block) = block else { crate::xlog_warn!("AllocateTitlePhysicalPages({n}): no room"); fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); @@ -1225,7 +1381,7 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu for i in 0..n { *arr.add(i) = page_number(first + i); } - PHYS_BLOCKS.lock().unwrap().insert(first, (n, n, block)); + PHYS_BLOCKS.lock().unwrap().insert(first, PhysBlock::new(n, block)); 1 } @@ -1236,35 +1392,53 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: return 0; } // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes + let mut freed_lazy = Vec::new(); if let Some(away) = AWAY.lock().unwrap().as_mut() { for i in 0..n { if let Some(at) = away.page.remove(&*arr.add(i)) { away.at.remove(&at); + freed_lazy.push(at); note_mapping_at(at); } } } - let mut g = PHYS_BLOCKS.lock().unwrap(); - for i in 0..n { - let Some(page) = page_index(*arr.add(i)) else { continue }; - // the block holding this page - let Some((&first, &(count, _, home))) = g.range(..=page).next_back() else { continue }; - if page >= first + count { - continue; - } - let e = g.get_mut(&first).unwrap(); - e.1 = e.1.saturating_sub(1); - if e.1 == 0 { - g.remove(&first); - if u.is_sparse(home) { - crate::hle::d3d12x::sparse::free(home); - } else if u.contains(home) { - u.free(home); - } else { - mem::VirtualFree(home as *mut c_void, 0, mem::MEM_RELEASE); + lazy::unmark_batch(&freed_lazy); + // Track partially-freed lazy homes to decommit immediately (reclaiming commit RAM + sparse + // VRAM even while sibling pages in a multi-GB block remain live). + let mut partial_homes: Vec<(usize, usize)> = Vec::new(); + let mut released_blocks: Vec = Vec::new(); + { + let mut g = PHYS_BLOCKS.lock().unwrap(); + for i in 0..n { + let Some(page) = page_index(*arr.add(i)) else { continue }; + let Some((&first, block)) = g.range_mut(..=page).next_back() else { continue }; + let off = page - first; + if !block.free_page(off) { + continue; + } + let home = block.home; + if block.live == 0 { + g.remove(&first); + released_blocks.push(first); + if u.is_sparse(home) { + crate::hle::d3d12x::sparse::free(home); + } else if u.contains(home) { + u.free(home); + } else { + mem::VirtualFree(home as *mut c_void, 0, mem::MEM_RELEASE); + } + } else if lazy_home(home) { + partial_homes.push((first, home + off * PHYS_PAGE)); } } } + if !partial_homes.is_empty() { + let mut to_decommit: Vec = partial_homes + .into_iter() + .filter_map(|(first, addr)| (!released_blocks.contains(&first)).then_some(addr)) + .collect(); + decommit_home_runs(&mut to_decommit); + } 1 } @@ -1321,6 +1495,13 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) // address, or a home not asked about again (the addresses rise; a page mapped twice is // unmapped first) – bar an address that is another page's home (a home in plain memory): // that answer was wrong before the runs too. + struct LazyBatch(Vec); + impl Drop for LazyBatch { + fn drop(&mut self) { + lazy::mark_batch(&self.0); + } + } + let mut fresh_lazy = LazyBatch(Vec::new()); let (mut at_run, mut home_run) = (StateRun::default(), StateRun::default()); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; @@ -1348,11 +1529,12 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) } let fresh = !in_uma(at) && !committed_page_in(at, &mut at_run); let home = page_home(p).unwrap(); + let home_committed = committed_page_in(home, &mut home_run); // a page never used (its home not committed) at the title's own reserved address space: // committed on first use (`lazy`) – GPU-owned targets placed there are never touched let plain = crate::gpu::uma::get().is_none_or(|u| !u.contains(at)); - if fresh && plain && !committed_page_in(home, &mut home_run) { - lazy::mark(at); + if fresh && plain && !home_committed { + fresh_lazy.0.push(at); away.at.insert(at, p); away.page.insert(p, at); continue; @@ -1361,7 +1543,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); } - if committed_page(home) { + if home_committed { std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PHYS_PAGE); if move_home_away(away, home) { (at_run, home_run) = Default::default(); @@ -2972,6 +3154,95 @@ mod tests { } } + #[test] + fn xmem_tools_mem_and_40bit_virtual_alloc() { + unsafe { + assert_eq!(XMemIsToolsMemAvailable(), 0); + let p = XMemVirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE | mem::MEM_COMMIT, 0, mem::PAGE_READWRITE); + assert!(!p.is_null()); + let addr = p as usize; + if virtual_alloc2().is_some() { + assert!(addr >= CONSOLE_40BIT_LOW && addr + PHYS_PAGE - 1 <= CONSOLE_40BIT_HIGH, "40-bit VA expected, got {addr:#x}"); + } + *(p as *mut u32) = 0xCAFE_BABE; + assert_eq!(*(p as *const u32), 0xCAFE_BABE); + assert_eq!(VirtualFree(p, 0, mem::MEM_RELEASE), 1); + } + } + + #[test] + fn physical_page_reads_skip_commit_writes_ensure_lazy_and_free_unmarks() { + unsafe { + let Some(mut pages) = sparse_pages(2) else { return }; + let home0 = page_home(pages[0]).unwrap(); + assert!(is_live_physical_page(pages[0])); + assert!(!committed_page(home0)); + + // Reading an untouched home returns zeros WITHOUT committing the home page. + let mut buf = [0xAAu8; 64]; + assert!(read_physical_pages(&pages[..1], 0, &mut buf)); + assert!(buf.iter().all(|&b| b == 0)); + assert!(!committed_page(home0), "read_physical_pages must not commit an untouched home"); + + // Map both pages lazily into a plain reservation. + let r = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 2, 0, 4, pages.as_mut_ptr()) as usize, r); + assert!(lazy::is_lazy(r) && lazy::is_lazy(r + PHYS_PAGE)); + + // Reading a lazy mapped page returns zeros WITHOUT committing or unmarking it. + buf.fill(0x55); + assert!(read_physical_pages(&pages[..1], 16, &mut buf)); + assert!(buf.iter().all(|&b| b == 0)); + assert!(lazy::is_lazy(r), "read_physical_pages must leave a lazy mapped page lazy"); + + // Writing a lazy mapped page explicitly commits it via lazy::ensure and stores the bytes. + let payload = [0x42u8; 32]; + assert!(write_physical_pages(&pages[..1], 32, &payload)); + assert!(!lazy::is_lazy(r)); + assert_eq!(std::slice::from_raw_parts((r + 32) as *const u8, 32), &payload); + + // Freeing the still-lazy second page unmarks it from LAZY. + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + assert!(!lazy::is_lazy(r + PHYS_PAGE), "FreeTitlePhysicalPages must unmark freed lazy pages"); + assert!(!is_live_physical_page(pages[0])); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + #[test] + fn partial_free_tracks_exact_liveness_decommits_homes_and_ignores_double_free() { + unsafe { + let Some(mut pages) = sparse_pages(4) else { return }; + let homes: Vec = pages.iter().map(|&p| page_home(p).unwrap()).collect(); + + // Commit and write all 4 pages at their homes. + let payload = [0x3Cu8; 32]; + for &p in &pages { + assert!(write_physical_pages(&[p], 0, &payload)); + } + assert!(homes.iter().all(|&h| committed_page(h))); + + // Partially free pages[1] and pages[2]; sibling pages[0] and pages[3] stay live. + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages[1..3].as_mut_ptr()), 1); + assert!(is_live_physical_page(pages[0]) && is_live_physical_page(pages[3])); + assert!(!is_live_physical_page(pages[1]) && !is_live_physical_page(pages[2])); + assert!(!committed_page(homes[1]) && !committed_page(homes[2]), "partially-freed homes must be decommitted"); + assert!(committed_page(homes[0]) && committed_page(homes[3])); + + // Double-freeing already-freed pages must be a no-op and must NOT release sibling pages. + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages[1..3].as_mut_ptr()), 1); + assert!(is_live_physical_page(pages[0]) && is_live_physical_page(pages[3])); + let mut rb = [0u8; 32]; + assert!(read_physical_pages(&[pages[0]], 0, &mut rb) && rb == payload); + assert!(read_physical_pages(&[pages[3]], 0, &mut rb) && rb == payload); + + // Free remaining two pages cleanly. + let mut rest = [pages[0], pages[3]]; + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, rest.as_mut_ptr()), 1); + assert!(!is_live_physical_page(pages[0]) && !is_live_physical_page(pages[3])); + } + } + #[test] fn get_module_handle_matches_load_library_for_console_aliases_and_stubs() { unsafe { diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index fa750b9a4..2f9b4c9bf 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -12,6 +12,7 @@ use std::collections::BTreeSet; use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Once, RwLock}; use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; @@ -22,11 +23,24 @@ use windows_sys::Win32::System::Memory::{ }; const PAGE: usize = 0x1_0000; +/// 4 MiB stripe per shard so contiguous ranges hit 1 shard while 16 threads faulting across +/// different regions commit in parallel without serializing on a single global RwLock. +const SHARDS: usize = 16; +const STRIPE_SHIFT: u32 = 22; +#[cfg(test)] +const STRIPE_SIZE: usize = 1 << STRIPE_SHIFT; const EXCEPTION_CONTINUE_EXECUTION: i32 = -1; const EXCEPTION_CONTINUE_SEARCH: i32 = 0; -/// pages (64 KiB) mapped but not committed yet -static LAZY: RwLock> = RwLock::new(BTreeSet::new()); +/// pages (64 KiB) mapped but not committed yet, sharded by 4 MiB VA stripe +static LAZY: [RwLock>; SHARDS] = [const { RwLock::new(BTreeSet::new()) }; SHARDS]; +static LAZY_COUNT: AtomicUsize = AtomicUsize::new(0); +static LAZY_COMMITTED_ANY: AtomicBool = AtomicBool::new(false); + +#[inline] +fn shard_index(page: usize) -> usize { + (page >> STRIPE_SHIFT) & (SHARDS - 1) +} fn install() { static ONCE: Once = Once::new(); @@ -37,10 +51,12 @@ fn install() { /// Commit `page` if it is a lazy one (true: it was). unsafe fn commit(page: usize) -> bool { - let mut g = LAZY.write().unwrap_or_else(|e| e.into_inner()); + let mut g = LAZY[shard_index(page)].write().unwrap_or_else(|e| e.into_inner()); if !g.remove(&page) { return false; } + LAZY_COUNT.fetch_sub(1, Ordering::Release); + LAZY_COMMITTED_ANY.store(true, Ordering::Release); !VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() } @@ -49,9 +65,14 @@ unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 { return EXCEPTION_CONTINUE_SEARCH; } + let count = LAZY_COUNT.load(Ordering::Acquire); + let committed_any = LAZY_COMMITTED_ANY.load(Ordering::Acquire); + if count == 0 && !committed_any { + return EXCEPTION_CONTINUE_SEARCH; + } let page = r.ExceptionInformation[1] & !(PAGE - 1); - let lazy = LAZY.read().unwrap_or_else(|e| e.into_inner()).contains(&page); - if lazy && commit(page) || allows(r.ExceptionInformation[0], r.ExceptionInformation[1]) { + let lazy = count != 0 && LAZY[shard_index(page)].read().unwrap_or_else(|e| e.into_inner()).contains(&page); + if lazy && commit(page) || (committed_any && allows(r.ExceptionInformation[0], r.ExceptionInformation[1])) { EXCEPTION_CONTINUE_EXECUTION } else { EXCEPTION_CONTINUE_SEARCH @@ -75,26 +96,99 @@ unsafe fn allows(access: usize, at: usize) -> bool { /// `page` (reserved, 64 KiB aligned) is mapped: committed on first use. pub(crate) fn mark(page: usize) { install(); - LAZY.write().unwrap_or_else(|e| e.into_inner()).insert(page); + if LAZY[shard_index(page)].write().unwrap_or_else(|e| e.into_inner()).insert(page) { + LAZY_COUNT.fetch_add(1, Ordering::Release); + } +} + +/// Bulk-mark `pages` (each 64 KiB aligned) as lazy, holding each touched shard lock once per run. +pub(super) fn mark_batch(pages: &[usize]) { + if pages.is_empty() { + return; + } + install(); + let mut added = 0usize; + let mut i = 0; + while i < pages.len() { + let s = shard_index(pages[i]); + let mut g = LAZY[s].write().unwrap_or_else(|e| e.into_inner()); + while i < pages.len() && shard_index(pages[i]) == s { + if g.insert(pages[i]) { + added += 1; + } + i += 1; + } + } + if added != 0 { + LAZY_COUNT.fetch_add(added, Ordering::Release); + } } /// `page` is unmapped: true if it was never used (nothing to keep of it). pub(super) fn unmark(page: usize) -> bool { - LAZY.write().unwrap_or_else(|e| e.into_inner()).remove(&page) + if LAZY_COUNT.load(Ordering::Acquire) == 0 { + return false; + } + let removed = LAZY[shard_index(page)].write().unwrap_or_else(|e| e.into_inner()).remove(&page); + if removed { + LAZY_COUNT.fetch_sub(1, Ordering::Release); + } + removed +} + +/// Bulk-unmark `pages` (each 64 KiB aligned), holding each touched shard lock once per run. +pub(super) fn unmark_batch(pages: &[usize]) { + if pages.is_empty() || LAZY_COUNT.load(Ordering::Acquire) == 0 { + return; + } + let mut removed = 0usize; + let mut i = 0; + while i < pages.len() { + let s = shard_index(pages[i]); + let mut g = LAZY[s].write().unwrap_or_else(|e| e.into_inner()); + while i < pages.len() && shard_index(pages[i]) == s { + if g.remove(&pages[i]) { + removed += 1; + } + i += 1; + } + } + if removed != 0 { + LAZY_COUNT.fetch_sub(removed, Ordering::Release); + } +} + +/// Whether `page` (64 KiB aligned) is currently marked lazy (reserved, never touched, holds zeros). +pub(super) fn is_lazy(page: usize) -> bool { + LAZY_COUNT.load(Ordering::Acquire) != 0 && LAZY[shard_index(page)].read().unwrap_or_else(|e| e.into_inner()).contains(&page) } /// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. pub fn ensure(p: usize, len: usize) { - if len == 0 { + if len == 0 || LAZY_COUNT.load(Ordering::Acquire) == 0 { return; } - let pages: Vec = { - let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); - if g.is_empty() { - return; + let start = p & !(PAGE - 1); + let end = p.saturating_add(len); + let mut pages = Vec::new(); + let first_stripe = start >> STRIPE_SHIFT; + let last_stripe = end.saturating_sub(1) >> STRIPE_SHIFT; + let span = last_stripe.saturating_sub(first_stripe); + if span >= SHARDS - 1 { + for shard in &LAZY { + let g = shard.read().unwrap_or_else(|e| e.into_inner()); + if !g.is_empty() { + pages.extend(g.range(start..end).copied()); + } } - g.range(p & !(PAGE - 1)..p.saturating_add(len)).copied().collect() - }; + } else { + for stripe in first_stripe..=last_stripe { + let g = LAZY[stripe & (SHARDS - 1)].read().unwrap_or_else(|e| e.into_inner()); + if !g.is_empty() { + pages.extend(g.range(start..end).copied()); + } + } + } for page in pages { unsafe { commit(page) }; } @@ -118,12 +212,32 @@ mod tests { assert_eq!(std::ptr::read_volatile((r + 8) as *const u32), 7); assert!(!unmark(r), "used: no longer lazy"); ensure(r + PAGE + 4, 4); - assert!(!LAZY.read().unwrap().contains(&(r + PAGE))); + assert!(!is_lazy(r + PAGE)); assert!(crate::gpu::shader::readable(r + PAGE, 4)); VirtualFree(r as *mut c_void, 0, MEM_RELEASE); } } + #[test] + fn sharded_lazy_batch_spans_stripes_and_unmarks_cleanly() { + unsafe { + // Span 2 full 4 MiB stripes + 1 page so multiple shards are exercised. + let n = (STRIPE_SIZE / PAGE) * 2 + 1; + let r = VirtualAlloc(std::ptr::null(), n * PAGE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(r, 0); + let pages: Vec = (0..n).map(|i| r + i * PAGE).collect(); + mark_batch(&pages); + assert!(is_lazy(pages[0]) && is_lazy(pages[n / 2]) && is_lazy(pages[n - 1])); + // Ensure only the final page across the stripe boundary. + ensure(pages[n - 1], 16); + assert!(!is_lazy(pages[n - 1])); + assert!(is_lazy(pages[0])); + unmark_batch(&pages); + assert!(!is_lazy(pages[0]) && !is_lazy(pages[n / 2])); + VirtualFree(r as *mut c_void, 0, MEM_RELEASE); + } + } + #[test] fn threads_first_touching_one_lazy_page_together_all_go_on() { const THREADS: usize = 8; diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs index ac9c01313..774a5fc8d 100644 --- a/crates/xcl/src/hle/opus.rs +++ b/crates/xcl/src/hle/opus.rs @@ -1076,6 +1076,25 @@ enum OutputSampleFormat { Float32, } +/// Current COM reference count of `obj` (AddRef + Release round-trip). +unsafe fn com_refcount(obj: &T) -> u32 { + let raw = obj.as_raw(); + if raw.is_null() { + return 0; + } + let vt = *(raw as *const *const usize); + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vt.add(1)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vt.add(2)); + add_ref(raw); + release(raw) +} + +/// Whether `(sample, buf)` is owned exclusively by our cache (sample refcount == 1, buffer +/// refcount == 2: one held by `sample`, one held by our cache tuple). +unsafe fn cached_sample_is_unique(sample: &IMFSample, buf: &IMFMediaBuffer) -> bool { + com_refcount(sample) == 1 && com_refcount(buf) == 2 +} + struct MftDecoder { mft: IMFTransform, channels: u16, @@ -1084,6 +1103,8 @@ struct MftDecoder { mft_provides_samples: bool, min_output_bytes: u32, timestamp_100ns: i64, + in_cache: Option<(IMFSample, IMFMediaBuffer, u32)>, + out_cache: Option<(IMFSample, IMFMediaBuffer, u32)>, } impl MftDecoder { @@ -1133,6 +1154,8 @@ impl MftDecoder { mft_provides_samples: false, min_output_bytes: 0, timestamp_100ns: 0, + in_cache: None, + out_cache: None, }; dec.configure_output()?; let _ = dec.mft.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0); @@ -1184,6 +1207,9 @@ impl MftDecoder { }; let max_pkt_bytes = MAX_PACKET_SAMPLES_48K * ch as u32 * bytes_per_sample; self.min_output_bytes = info.cbSize.max(max_pkt_bytes); + if self.out_cache.as_ref().is_some_and(|(_, _, cap)| *cap < self.min_output_bytes) { + self.out_cache = None; + } Ok(()) } @@ -1195,6 +1221,33 @@ impl MftDecoder { self.timestamp_100ns = 0; } + unsafe fn acquire_input_sample(&mut self, rt: &MfRuntime, needed: u32) -> Result<(IMFSample, IMFMediaBuffer, u32), String> { + if let Some((s, b, cap)) = self.in_cache.take() { + if cap >= needed && cached_sample_is_unique(&s, &b) { + return Ok((s, b, cap)); + } + } + let cap = needed.max(1500); + let s = mf_create_sample(rt)?; + let b = mf_create_memory_buffer(rt, cap)?; + s.AddBuffer(&b).map_err(|e| format!("input AddBuffer: {e}"))?; + Ok((s, b, cap)) + } + + unsafe fn acquire_output_sample(&mut self, rt: &MfRuntime) -> Result<(IMFSample, IMFMediaBuffer, u32), String> { + let needed = self.min_output_bytes; + if let Some((s, b, cap)) = self.out_cache.take() { + if cap >= needed && cached_sample_is_unique(&s, &b) { + let _ = b.SetCurrentLength(0); + return Ok((s, b, cap)); + } + } + let s = mf_create_sample(rt)?; + let b = mf_create_memory_buffer(rt, needed)?; + s.AddBuffer(&b).map_err(|e| format!("output AddBuffer: {e}"))?; + Ok((s, b, needed)) + } + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { let info = parse_packet(packet, false) .ok_or_else(|| "invalid RFC 6716 Opus packet".to_string())?; @@ -1203,8 +1256,7 @@ impl MftDecoder { let before = out.len(); unsafe { - let sample = mf_create_sample(rt)?; - let buf = mf_create_memory_buffer(rt, packet.len() as u32)?; + let (sample, buf, cap) = self.acquire_input_sample(rt, packet.len() as u32)?; let mut ptr = std::ptr::null_mut(); buf.Lock(&mut ptr, None, None) .map_err(|e| format!("input Lock: {e}"))?; @@ -1212,23 +1264,22 @@ impl MftDecoder { let _ = buf.Unlock(); buf.SetCurrentLength(packet.len() as u32) .map_err(|e| format!("input SetCurrentLength: {e}"))?; - sample - .AddBuffer(&buf) - .map_err(|e| format!("input AddBuffer: {e}"))?; let _ = sample.SetSampleTime(self.timestamp_100ns); let _ = sample.SetSampleDuration(dur); self.timestamp_100ns = self.timestamp_100ns.saturating_add(dur); - match self.mft.ProcessInput(0, &sample, 0) { - Ok(()) => {} + let input_res = match self.mft.ProcessInput(0, &sample, 0) { + Ok(()) => Ok(()), Err(e) if e.code() == MF_E_NOTACCEPTING => { self.drain_output(rt, out)?; self.mft .ProcessInput(0, &sample, 0) - .map_err(|e2| format!("ProcessInput retry: {e2}"))?; + .map_err(|e2| format!("ProcessInput retry: {e2}")) } - Err(e) => return Err(format!("ProcessInput: {e}")), - } + Err(e) => Err(format!("ProcessInput: {e}")), + }; + self.in_cache = Some((sample, buf, cap)); + input_res?; self.drain_output(rt, out)?; } @@ -1239,13 +1290,11 @@ impl MftDecoder { unsafe fn drain_output(&mut self, rt: &MfRuntime, out: &mut Vec) -> Result<(), String> { loop { - let alloc_sample = if self.mft_provides_samples { - None + let (alloc_sample, cached_meta) = if self.mft_provides_samples { + (None, None) } else { - let s = mf_create_sample(rt)?; - let b = mf_create_memory_buffer(rt, self.min_output_bytes)?; - s.AddBuffer(&b).map_err(|e| format!("output AddBuffer: {e}"))?; - Some(s) + let (s, b, cap) = self.acquire_output_sample(rt)?; + (Some(s), Some((b, cap))) }; let mut out_buf = [MFT_OUTPUT_DATA_BUFFER { @@ -1261,12 +1310,25 @@ impl MftDecoder { let sample = ManuallyDrop::into_inner(std::ptr::read(&out_buf[0].pSample)); let _events = ManuallyDrop::into_inner(std::ptr::read(&out_buf[0].pEvents)); - match res { + let append_res = match &res { Ok(()) => { - if let Some(s) = sample { - self.append_sample_pcm16(&s, out)?; + if let Some(s) = sample.as_ref() { + self.append_sample_pcm16(s, out) + } else { + Ok(()) } } + _ => Ok(()), + }; + if let (Some(s), Some((b, cap))) = (sample, cached_meta) { + if !self.mft_provides_samples && cap >= self.min_output_bytes { + self.out_cache = Some((s, b, cap)); + } + } + append_res?; + + match res { + Ok(()) => {} Err(e) if e.code() == MF_E_TRANSFORM_NEED_MORE_INPUT => break, Err(e) if e.code() == MF_E_TRANSFORM_STREAM_CHANGE => { self.configure_output()?; @@ -2046,4 +2108,24 @@ pub(crate) mod tests { assert!(d24.decode_packet(&[0xFB, 0], &mut out24).is_err()); assert_eq!(d24.decode_packet(MONO_HYBRID_20MS[1], &mut out24).unwrap(), 480); } + + #[test] + fn mft_decoder_reuses_cached_samples_across_packets() { + let Ok(mut dec) = MftDecoder::new(2, 48_000, None) else { + eprintln!("skipping: MSOpusDecoder.dll not available"); + return; + }; + let mut pcm = Vec::new(); + assert_eq!(dec.decode_packet(STEREO_CELT_20MS[0], &mut pcm).unwrap(), 960); + let in_ptr_0 = dec.in_cache.as_ref().expect("input sample cached").0.as_raw(); + let out_ptr_0 = dec.out_cache.as_ref().map(|(s, _, _)| s.as_raw()); + for &pkt in &STEREO_CELT_20MS[1..] { + assert_eq!(dec.decode_packet(pkt, &mut pcm).unwrap(), 960); + } + let in_ptr_1 = dec.in_cache.as_ref().expect("input sample stays cached").0.as_raw(); + assert_eq!(in_ptr_0, in_ptr_1, "MftDecoder should reuse its input IMFSample across packets"); + if !dec.mft_provides_samples { + assert_eq!(out_ptr_0, dec.out_cache.as_ref().map(|(s, _, _)| s.as_raw()), "MftDecoder should reuse its output IMFSample across packets"); + } + } }