diff --git a/HANDOFF.md b/HANDOFF.md index e8bd210..012612e 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -644,6 +644,15 @@ The EXE (+ EOSSDK) imports 31 functions from console libraries: MFPlat `MFResetD - Modes the library takes for 2D: 1 2 5 6 9 10 17 18 21 22 25 26 27, 24 (and VAR 28) for ≤ 8-byte non-BC elements, VAR 31; `Layout` 0 / 2 = its choice (64KB_D for 2, 4KB_S, UAVs 4KB_S_X up to 64 KB else 64KB_R_X). Not modelled (E_NOTIMPL): render targets / depth (CMASK / HTILE planes), planar depth-stencil formats, MSAA, 1D / 3D, VAR modes. +- **Textures in title memory** (`d3d12x/title_textures.rs`): CreatePlacedResourceX of a texture gets a PC texture kept in + step with the title's memory – every mip and slice detiled with the XG layout (`hle::xg`) and uploaded at creation; + unified memory is reserved with MEM_WRITE_WATCH (OpenExistingHeapFromAddress takes it), and before each + ExecuteCommandLists one GetWriteWatch per window finds the textures whose pages the CPU wrote (streamed mips, + DirectStorage reads) and uploads them again (on an XCL queue, waiting for it). Unreadable memory (reserved, not mapped) + reads as zero. The test title writes a 64KB_S_X array through XG, places it, reads every subresource back through + the GPU, rewrites one and sees it after the next ExecuteCommandLists. Not yet: GPU writes into the title's memory + (copies to the address), mapping physical pages into reserved address space (Fortnite's streaming does that), the + upload without a CPU wait, the state if the title moved the texture out of its initial one. - XGameRuntime task queues: handles are looked up in a set of live ones before being read – an XAsync completing on a worker after its queue was closed read freed memory (a rare lib-test panic in `queue_from`). diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 215e438..8323db6 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -17,6 +17,9 @@ use std::sync::{Mutex, OnceLock}; use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; +/// VirtualAlloc: track CPU writes (GetWriteWatch) +const MEM_WRITE_WATCH: u32 = 0x20_0000; + /// allocation granularity (as VirtualAlloc) pub const GRAIN: usize = 0x1_0000; /// largest region D3D12 opens as a heap @@ -59,7 +62,8 @@ impl Uma { let mut got = Vec::new(); for k in 0..windows { let want = base + k * WINDOW; - let p = unsafe { VirtualAlloc(want as *const std::ffi::c_void, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + // write-watched: textures the title keeps here are uploaded again after CPU writes + let p = unsafe { VirtualAlloc(want as *const std::ffi::c_void, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }; if p.is_null() { break; } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 96610d5..c429aaf 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -379,8 +379,8 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { /// device #44 CreatePlacedResourceX(address, desc, initial state, clear value, riid, resource): /// a resource in title memory. A buffer at a 64 KiB-aligned address in unified memory is that -/// memory (placed in its UMA heap); anything else gets memory of its own – a texture's console -/// tiling has no PC equivalent, so what the title writes at the address is not seen there. +/// memory (placed in its UMA heap); a texture gets a PC texture kept in step with the memory +/// (`title_textures`: detiled as the console lays it out, uploaded again after CPU writes). pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, va: u64, desc: *const u8, state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { static N: AtomicU64 = AtomicU64::new(0); if desc.is_null() || ppv.is_null() || !crate::gpu::shader::readable(desc as usize, 0x38) { @@ -396,6 +396,14 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, d.as_ptr() as usize, state as usize, clear as usize, riid, ppv); + if hr >= 0 && !buffer && !(*ppv).is_null() { + static M: AtomicU64 = AtomicU64::new(0); + match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { + Ok(()) => return hr, + Err(e) if once(&M, 4) => crate::xlog_warn!("D3D12.X: CreatePlacedResourceX texture at {va:#x}: not kept in step with the memory ({e})"), + Err(_) => {} + } + } if hr < 0 || once(&N, 4) { let w = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); crate::xlog_info!( diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index b7b37ea..87f0ae5 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -21,6 +21,7 @@ pub mod null; pub mod present; pub mod pso_async; pub mod real; +pub mod title_textures; 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 6e6a6ed..4ad7b32 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -864,6 +864,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); if n == 0 { + super::title_textures::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { u.free(p); @@ -2210,6 +2211,8 @@ unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists"))); + // textures in title memory the CPU wrote since: uploaded again first + super::title_textures::refresh(); // console-shaped lists run as the PC lists they were translated into let mapped: Vec<*mut c_void>; let lists = if n > 0 && !lists.is_null() { diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs new file mode 100644 index 0000000..53895ab --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -0,0 +1,170 @@ +//! Textures a title places in its own memory (CreatePlacedResourceX): on the console the GPU +//! samples that memory, laid out as the console's layout library says (`hle::xg`, checked +//! against the console's own). Here a PC texture holds a detiled copy: uploaded when the +//! texture is created and again before the title's next ExecuteCommandLists once the CPU wrote +//! any of its pages (unified memory is write-watched, `gpu::uma`) – textures streamed in after +//! creation (mips loaded later, DirectStorage) included. +//! +//! The copy waits for the GPU on an XCL queue of the device. Memory that is not readable +//! (reserved, not mapped yet) reads as zero. GPU writes into the title's memory (copies to the +//! address) are not seen; the title's own GPU work on the texture goes to the PC texture. + +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::gpu::texture::{self, Subresource}; +use crate::hle::xg; + +/// GetWriteWatch / ResetWriteWatch +const WRITE_WATCH_FLAG_RESET: u32 = 1; +#[link(name = "kernel32")] +extern "system" { + fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; + fn ResetWriteWatch(base: *const c_void, size: usize) -> u32; +} + +/// (device, address, layout, state) of an upload +type Upload = (usize, usize, Arc, D3D12_RESOURCE_STATES); + +struct Entry { + device: usize, + va: usize, + tex: Arc, + /// the state the texture was created in (uploads leave it there) + state: D3D12_RESOURCE_STATES, +} + +// raw COM pointers of the title's objects; uploads hold a reference while they run +unsafe impl Send for Entry {} + +/// PC texture → its place in the title's memory +static TEXTURES: Mutex> = Mutex::new(BTreeMap::new()); +/// the queue uploads go to, per device +static QUEUES: Mutex> = Mutex::new(BTreeMap::new()); +static UPLOADS: AtomicU64 = AtomicU64::new(0); + +/// Number of textures kept in title memory and uploads done so far. +pub fn counts() -> (usize, u64) { + (TEXTURES.lock().unwrap().len(), UPLOADS.load(Ordering::Relaxed)) +} + +/// A texture the title placed at `va` (its console desc `desc`): kept in step with the memory. +pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, desc: &[u8; 0x38], state: D3D12_RESOURCE_STATES) -> Result<(), String> { + let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?; + let bytes = tex.size() as usize; + let e = Entry { device: device as usize, va, tex: Arc::new(tex), state }; + if crate::gpu::uma::get().is_some_and(|u| u.contains(va)) { + ResetWriteWatch(va as *const c_void, bytes); + } + let upload = (e.device, e.va, Arc::clone(&e.tex), e.state); + TEXTURES.lock().unwrap().insert(res as usize, e); + let r = ID3D12Resource::from_raw_borrowed(&res).ok_or("no resource")?; + run_upload(upload, r) +} + +/// The PC texture was released for good. +pub fn forget(res: usize) { + TEXTURES.lock().unwrap().remove(&res); +} + +/// Before the title's GPU work: textures whose memory the CPU wrote since the last look are +/// uploaded again. +pub(super) unsafe fn refresh() { + thread_local! { + static BUSY: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + // the uploads' own ExecuteCommandLists come back here + if BUSY.with(|b| b.replace(true)) { + return; + } + refresh_once(); + BUSY.with(|b| b.set(false)); +} + +unsafe fn refresh_once() { + if TEXTURES.lock().unwrap().is_empty() { + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + let mut dirty: Vec = Vec::new(); + let mut page = 0x1000u32; + for k in 0..u.windows() { + let (base, size) = u.window(k); + loop { + let mut buf = vec![std::ptr::null_mut::(); 16384]; + let mut n = buf.len(); + if GetWriteWatch(WRITE_WATCH_FLAG_RESET, base as *const c_void, size, buf.as_mut_ptr(), &mut n, &mut page) != 0 { + break; + } + dirty.extend(buf[..n].iter().map(|&p| p as usize)); + if n < buf.len() { + break; + } + } + } + if dirty.is_empty() { + return; + } + dirty.sort_unstable(); + // textures with a written page; a reference each while they are uploaded + let todo: Vec<(ID3D12Resource, Upload)> = { + let t = TEXTURES.lock().unwrap(); + t.iter() + .filter(|(_, e)| { + let i = dirty.partition_point(|&p| p + page as usize <= e.va); + dirty.get(i).is_some_and(|&p| p < e.va + e.tex.size() as usize) + }) + .filter_map(|(&res, e)| { + let p = res as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.va, Arc::clone(&e.tex), e.state))) + }) + .collect() + }; + for (r, u) in todo { + if let Err(e) = run_upload(u, &r) { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("title texture: upload again failed: {e}"); + } + } + } +} + +/// Every subresource (D3D12 order) of a texture from the title's memory at `va`. +unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { + let c = &tex.chain; + let bpe = tex.bpe as usize; + let mut out = Vec::with_capacity(tex.array as usize * c.levels.len()); + for s in 0..tex.array as usize { + let at = va + s * c.slice_bytes; + let slice: &[u8] = if crate::gpu::shader::readable(at, c.slice_bytes) { std::slice::from_raw_parts(at as *const u8, c.slice_bytes) } else { &[] }; + for (i, l) in c.levels.iter().enumerate() { + out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(slice, i, s) }); + } + } + out +} + +unsafe fn run_upload((device, va, tex, state): Upload, res: &ID3D12Resource) -> Result<(), String> { + let d = device as *mut c_void; + let dev = ID3D12Device::from_raw_borrowed(&d).ok_or("no device")?; + let queue = { + let mut q = QUEUES.lock().unwrap(); + if let Some(q) = q.get(&device) { + q.clone() + } else { + let made: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(|e| e.to_string())?; + q.insert(device, made.clone()); + made + } + }; + let subs = subresources(va, &tex); + texture::upload(dev, &queue, res, &subs, state, state)?; + UPLOADS.fetch_add(1, Ordering::Relaxed); + Ok(()) +} diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index 690a65f..def3cf6 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -19,6 +19,12 @@ extern "system" { fn D3D12SerializeRootSignature(desc: *const c_void, v: u32, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT; } +// the console's texture layout library +#[link(name = "xg_xs", kind = "raw-dylib")] +extern "system" { + fn XGCreateTextureComputer(desc: *const D3D12_RESOURCE_DESC, computer: *mut *mut c_void) -> HRESULT; +} + // Fortnite reads its data through the console's DirectStorage #[link(name = "xcrdapi", kind = "raw-dylib")] extern "system" { @@ -530,6 +536,119 @@ pub fn direct_storage() -> Result<(), String> { } } +/// A texture in the title's own memory, as a console title streams one: its layout from the +/// layout library (64KB_S_X, 2 slices x 2 mips), texels written there tiled, the texture placed +/// at that address (#44) - the GPU reads every subresource; then one subresource is written +/// again and the next ExecuteCommandLists sees the new texels. +pub fn title_texture() -> Result<(), String> { + unsafe { + let dev = device()?; + let slot = |obj: *mut c_void, i: usize| *(*(obj as *const *const usize)).add(i); + let mut desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 80, + Height: 40, + DepthOrArraySize: 2, + MipLevels: 2, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.Layout = D3D12_TEXTURE_LAYOUT(0x119); // the console's 64KB_S_X + let mut xg = std::ptr::null_mut(); + ensure!(XGCreateTextureComputer(&desc, &mut xg) == 0, "XGCreateTextureComputer"); + let size = std::mem::transmute:: u64>(slot(xg, 3))(xg) as usize; + type Into = unsafe extern "system" fn(*mut c_void, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT; + let into: Into = std::mem::transmute(slot(xg, 8)); + let graphics = 1u64 << 29; + let mem = crate::XMemAlloc(size, graphics) as *mut u8; + ensure!(!mem.is_null(), "graphics memory"); + let dims = |mip: u32| ((80u32 >> mip).max(1), (40u32 >> mip).max(1)); + let texels = |sub: u32, salt: u8| -> Vec { + let (w, h) = dims(sub % 2); + (0..w * h * 4).map(|i| (i as u8).wrapping_mul(7).wrapping_add(sub as u8 * 31).wrapping_add(salt)).collect() + }; + for sub in 0..4u32 { + let (w, h) = dims(sub % 2); + ensure!(into(xg, mem, 0, sub, texels(sub, 0).as_ptr(), w * 4, w * h * 4) == 0, "CopyIntoSubresource {sub}"); + } + type PlacedX = unsafe extern "system" fn(*mut c_void, u64, *const D3D12_RESOURCE_DESC, u32, *const c_void, *const windows::core::GUID, *mut *mut c_void) -> HRESULT; + let mut raw = std::ptr::null_mut(); + let hr = std::mem::transmute::(slot(dev.as_raw(), 44))(dev.as_raw(), mem as u64, &desc, 0, std::ptr::null(), &ID3D12Resource::IID, &mut raw); + ensure!(hr >= 0 && !raw.is_null(), "CreatePlacedResourceX texture hr={hr:#x}"); + let tex = ID3D12Resource::from_raw(raw); + + // all four subresources through the GPU + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(e)?; + let pc = tex.GetDesc(); + let mut fps = [D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); 4]; + let mut total = 0u64; + dev.GetCopyableFootprints(&pc, 0, 4, 0, Some(fps.as_mut_ptr()), None, None, Some(&mut total)); + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .map_err(e)?; + let rb = rb.ok_or("no readback buffer")?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; + list.Close().map_err(e)?; + let mut step = 0u64; + let mut read_back = |want: &dyn Fn(u32) -> Vec| -> Result<(), String> { + alloc.Reset().map_err(e)?; + list.Reset(&alloc, None).map_err(e)?; + for (sub, fp) in fps.iter().enumerate() { + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&tex), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub as u32 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(list.cast::().map_err(e)?)]); + step += 1; + wait(&queue, &fence, step)?; + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).map_err(e)?; + let mut result = Ok(()); + for (sub, fp) in fps.iter().enumerate() { + let (w, h) = dims(sub as u32 % 2); + let exp = want(sub as u32); + for y in 0..h as usize { + let got = std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), w as usize * 4); + if got != &exp[y * w as usize * 4..(y + 1) * w as usize * 4] { + result = Err(format!("subresource {sub} row {y} differs from the title memory")); + break; + } + } + } + rb.Unmap(0, None); + result + }; + read_back(&|sub| texels(sub, 0))?; + // stream new texels into slice 1 mip 0 (subresource 2) and run work: the GPU sees them + ensure!(into(xg, mem, 0, 2, texels(2, 99).as_ptr(), 80 * 4, 80 * 40 * 4) == 0, "CopyIntoSubresource again"); + read_back(&|sub| texels(sub, if sub == 2 { 99 } else { 0 }))?; + drop(tex); + std::mem::transmute:: u32>(slot(xg, 1))(xg); + crate::XMemFree(mem as *mut c_void, graphics); + Ok(()) + } +} + pub fn render_triangle() -> Result<(), String> { unsafe { let dev = device()?; diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index 8383375..b6b1177 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -478,6 +478,7 @@ fn main() { check("D3D12.X: console device methods (placed title memory, DMA queue + list, page pools)", gpu::console_device_methods); check("D3D12.X: console command list memory methods (writes, timestamp, fill, copy)", gpu::console_list_methods); check("DirectStorage (xcrdapi): a file read into memory, status + D3D12 fence", gpu::direct_storage); + check("D3D12.X: a texture in title memory (XG layout, #44) follows CPU writes", gpu::title_texture); check("XAudio2: console flags/device, XMA2 voice plays silence, PCM passes, callbacks", audio::xaudio2_console_voices); let failures = FAILURES.load(Ordering::SeqCst);