diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index d5618eb12f..f1339e9d99 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5729,6 +5729,92 @@ fn gpu_direct_compute_waves_take_consecutive_threads_of_2d_and_3d_groups() { } } +/// A 2-D group takes the same course through `pso::direct_compute` (the route #3189 restores) as +/// through the HLSL path (`pso::console_dxil_noremap`) with this tree's compute entry +/// (nvidia-dev's branch-free thread limits, `kernel::compute_gate`), including when a DispatchX +/// thread limit cuts inside a group. The program is 8 x 8 groups. Each thread stores its console +/// thread index, its group (y << 16 | x), its wave's first thread and its lane at its own slot. +/// It runs as 2 x 2 groups, with no limit and with limits in X, in Y and in both. The wave64 +/// program runs split on a GPU with only 32-lane waves. With a group barrier first, the direct +/// translator leaves the program to the HLSL path (`routed_to_hlsl`, as the runtime does when +/// the group is several hardware waves) and the HLSL form alone must give the table. +#[test] +fn gpu_2d_group_direct_route_matches_the_hlsl_path_under_thread_limits() { + use super::IO_THREAD_LIMIT; + if !gpu_ready() { + return; + } + const NONE: u32 = u32::MAX; + let program = |wave64: bool, barrier: bool| { + program_of(&[ + if barrier { ins("S_BARRIER", "ENC_SOPP", &[], None) } else { Vec::new() }, + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)], None), + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 3)], None), // thread index + ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", 193), ("SRC1", 128)], None), + if wave64 { ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", 193), ("SRC1", V + 14)], None) } else { Vec::new() }, // lane + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 3)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", 6)], None), // the wave's first thread + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None), + ins("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", 4), ("SRC1", 144), ("SRC2", 3)], None), // group y << 16 | x + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 129), ("SRC2", 3)], None), // group y · 2 + x + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 9), ("SRC1", 134), ("SRC2", V + 3)], None), // slot + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 132), ("VSRC1", 10)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 0), ("VSRC1", 7)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None), + ins("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 11), ("SADDR", 0x7D)], None), + ]) + }; + // `cs_container` with the group ids in s3 (x) and s4 (y) + let container = |code: &[u8], wave64: bool| { + use crate::gpu::xbox::tests::{fssm, sample}; + let mut f = fssm(code, &[(6, 0)]); + f[0x138..0x13C].copy_from_slice(&(3u32 << 1 | 1 << 7 | 1 << 8 | 2 << 11).to_le_bytes()); + for (k, t) in [8u32, 8, 1].iter().enumerate() { + f[0x13C + 4 * k..0x140 + 4 * k].copy_from_slice(&t.to_le_bytes()); + } + if !wave64 { + f[0xD4..0xD8].copy_from_slice(&0x20u32.to_le_bytes()); + } + sample(5, &[f]) + }; + let base = 0x100usize; + for (wave64, barrier) in [(true, false), (false, false), (true, true), (false, true)] { + let lanes = if wave64 { 64 } else { 32 }; + let split = wave64 && runner::split_wave64(); + let blob = container(&program(wave64, barrier), wave64); + let what = format!("wave64 {wave64}, split {split}, barrier {barrier}"); + let direct = match super::pso::direct_compute(&blob, 0, 1, split) { + Ok(c) => Some(c), + Err(e) if barrier && routed_to_hlsl(&e) => None, + Err(e) => panic!("{what}: direct: {e}"), + }; + assert!(direct.as_ref().is_none_or(|c| c.dispatch_chain.is_none()), "{what}: a chain"); + let hlsl = super::pso::console_dxil_noremap(&blob, split, 1).unwrap_or_else(|e| panic!("{what}: HLSL: {e}")); + for (lx, ly) in [(0u32, 0u32), (11, 0), (0, 13), (11, 13), (3, 5)] { + let mut io = vec![0u32; 128]; + io[..3].copy_from_slice(&[base as u32, 8, 64]); + (io[IO_THREAD_LIMIT[0]], io[IO_THREAD_LIMIT[1]]) = (lx, ly); + let mem = vec![NONE; (base + 4 * 64 * 16) / 4]; + let d = direct.as_ref().map(|c| runner::dispatch(&c.dxil, [2, 2, 1], &io, &mem).unwrap_or_else(|e| panic!("{what}: direct: {e}"))); + let h = runner::dispatch(&hlsl, [2, 2, 1], &io, &mem).unwrap_or_else(|e| panic!("{what}: HLSL: {e}")); + for s in 0..4 * 64usize { + let (g, t) = (s / 64, s % 64); + let (gx, gy) = (g % 2, g / 2); + let (x, y) = ((gx * 8 + t % 8) as u32, (gy * 8 + t / 8) as u32); + let ran = (lx == 0 || x < lx) && (ly == 0 || y < ly); + // (the lowest thread of a console wave has its lowest x and y: it runs if any does) + let want = if ran { [t as u32, (gy << 16 | gx) as u32, (t - t % lanes) as u32, (t % lanes) as u32] } else { [NONE; 4] }; + let at = (base + s * 16) / 4; + let where_ = format!("{what}, limit {lx} x {ly}: group ({gx}, {gy}) thread {t}"); + if let Some(d) = &d { + assert_eq!(d[at..at + 4], want, "{where_}: direct (thread, group, wave's first thread, lane)"); + } + assert_eq!(h[at..at + 4], want, "{where_}: HLSL (thread, group, wave's first thread, lane)"); + } + } + } +} + /// A wave32 program in a 64-lane hardware wave (what VS / PS may get from the driver): the /// two halves behave as separate waves – ballots, lane counts, readlane and mbcnt per half. #[test] diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 3c9dd506b8..bbf698ad72 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -210,6 +210,19 @@ struct QueueFences(HashMap); unsafe impl Send for QueueFences {} static HEAP_FENCES: Mutex> = Mutex::new(None); + +/// A retired queue (`present::invalidate_queue_caches`): its signal fence goes, rather than stay +/// in `HEAP_FENCES` for every queue address the title ever used. (Retired ranges keep clones of +/// the fences they wait for.) +pub(super) fn forget_queue(id: super::present::QueueId) { + forget_queue_fence(id.raw()); +} + +fn forget_queue_fence(queue: usize) { + let gone = HEAP_FENCES.lock().unwrap().as_mut().and_then(|fences| fences.0.remove(&queue)); + // (dropped outside the lock) + drop(gone); +} static GLOBAL_RETIRED: AtomicBool = AtomicBool::new(false); /// Serialises `drain_global_retired` across `fill_nulls` and `merge_release` so a concurrent /// `slot()` cannot miss ranges popped from `GLOBAL.retired` before they reach `GLOBAL.free`. @@ -1957,6 +1970,34 @@ mod tests { assert!(made.is_ok(), "a shader-visible sampler heap of {}: {made:?}", d.NumDescriptors); } + /// A retired queue's signal fence leaves `HEAP_FENCES`; another queue's stays. + #[test] + fn a_retired_queue_leaves_the_heap_fences() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let dev = unsafe { + let mut dev: Option = None; + match CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) { + Ok(warp) if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() => dev.unwrap(), + _ => return crate::gpu::recomp::runner::skip_test("no WARP device"), + } + }; + let (gone, kept) = (0x7E57_0000_C0A0usize, 0x7E57_0000_C0B0usize); + for key in [gone, kept] { + let fence: ID3D12Fence = unsafe { dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.unwrap(); + HEAP_FENCES.lock().unwrap().get_or_insert_with(|| QueueFences(HashMap::new())).0.insert(key, (fence, 3)); + } + let fence = HEAP_FENCES.lock().unwrap().as_ref().unwrap().0[&gone].0.clone(); + forget_queue_fence(gone); + let g = HEAP_FENCES.lock().unwrap(); + let fences = &g.as_ref().unwrap().0; + assert!(!fences.contains_key(&gone), "the retired queue's fence is gone"); + assert_eq!(fences.get(&kept).map(|f| f.1), Some(3), "the other queue's stays"); + drop(g); + assert_eq!(unsafe { fence.GetCompletedValue() }, 0, "a mark's clone of the fence still works"); + HEAP_FENCES.lock().unwrap().as_mut().unwrap().0.remove(&kept); + } + /// Every descriptor of a range that is not handed out gets a null view, an SRV at even and a /// UAV at odd indices (a range starting at an odd one too), a block at a time. #[test] diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 0210c522f1..011640449c 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -11236,6 +11236,47 @@ mod tests { } } + /// A spare whose Reset fails does not stand in for a list reset while its last submit is on + /// the GPU (`reset_stand_in`), and stays among the list's spares (released with the list) + /// instead of being dropped. (A put-off dispatch's segment is reserved closed, without a + /// Reset: this is where a spare's Reset can fail.) + #[test] + fn a_spare_whose_reset_fails_stays_with_the_list_on_the_software_adapter() { + use super::super::title_list; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()); + if warp.and_then(|w| D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev)).is_err() { + crate::gpu::recomp::runner::skip_test("no WARP adapter"); + return; + } + let dev = dev.unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + real::adopt(alloc.as_raw(), real::Kind::CommandAllocator); + let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + // still open, and of another type than the list's own allocator: its Reset fails + let direct: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let open: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &direct, None).unwrap(); + let pc0 = raw.into_raw(); + real::adopt(pc0, real::Kind::CommandList); + on_create(pc0, alloc.as_raw() as usize, 0, ty); + let wrap = title_list::wrap(pc0); + let spare = open.into_raw(); + real::adopt(spare, real::Kind::CommandList); + title_list::put_spare(wrap, spare); + + assert_eq!(reset_stand_in(wrap, pc0, alloc.as_raw() as usize, 0), None, "the spare whose Reset failed does not stand in"); + assert_eq!(title_list::spares_for_test(wrap), vec![spare as usize], "it stays the list's"); + + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + assert_eq!(rel_fn(wrap), 0); + } + } + /// Reproduces the exact intra-list fork-join pattern seen on retail compute queues: /// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame) /// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d0941c4ea6..fdd12aea5a 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -596,6 +596,7 @@ pub(super) fn invalidate_queue_caches(id: QueueId) { super::sparse::forget_queue(id); super::title_textures::forget_queue(id); super::vram::forget_queue(id); + super::console_heap::forget_queue(id); } fn retirement_worker() -> Option<&'static mpsc::Sender<()>> { diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index df9fabd0da..15cb067885 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -4343,17 +4343,8 @@ pub fn submit(standin: usize, compute: bool, job: Job) { submit_eager_with(standin, compute, job, 0, None, 0); } -pub(super) fn submit_eager( - standin: usize, - compute: bool, - job: Job, - key: u64, - compute_key: Option, -) { - submit_eager_with(standin, compute, job, key, compute_key, 0); -} - -/// `submit_eager`, with a compute pipeline's console program for the log (`record`; 0: not known). +/// `submit` with the shaders' key, a coalescing key and a compute pipeline's console program for +/// the log (`record`; 0: not known). pub(super) fn submit_eager_with( standin: usize, compute: bool, @@ -4383,6 +4374,7 @@ pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { submit_lazy_keyed_with(standin, compute, job, key, None, None, 0); } +#[cfg(test)] pub(super) fn submit_lazy_keyed( standin: usize, compute: bool, @@ -4408,6 +4400,7 @@ pub(super) fn submit_lazy_keyed_with( submit_as(standin, compute, job, None, false, key, compute_key, warm, record); } +#[cfg(test)] pub(super) fn submit_recipe_keyed( standin: usize, compute: bool, diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 1c1c731864..b67449d315 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -11529,13 +11529,17 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis // console-shaped lists run as the PC lists they were translated into (split title lists expand // into all of their recorded PC segments in exact chronological order) let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); + // (the put-off dispatches' waits for their builds are not the submit's cost: the put-off line) + let mut deferred = std::time::Duration::ZERO; for &l in title_lists { if let Some(pc) = super::console_list::pc_list(l) { mapped.push(pc); } else { // Deferred recording can wait for a pipeline. Keep that time solely in PipelineWait. drop(preparation_stall); + let t = std::time::Instant::now(); super::list_x::record_deferred(l); + deferred += t.elapsed(); preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); if !super::title_list::push_segments(l, &mut mapped) { mapped.push(l); @@ -11547,11 +11551,15 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis return; } // textures in title memory the CPU wrote since: uploaded again first + let t_refresh = std::time::Instant::now(); prepare_title_submission(this, title_lists); + let t_lists = std::time::Instant::now(); + super::submit_cost::call(t_lists - t_refresh); super::list_x::note_queue_for_lists(this as usize, &mapped); super::gpu_profile::note_queue(this); let t_exec = std::time::Instant::now(); - super::submit_cost::call(t_exec - submit_t0); + // the lists made ready: mapped to their PC lists before the refresh, noted for the queue after it + super::submit_cost::lists((t_refresh - submit_t0).saturating_sub(deferred) + (t_exec - t_lists)); let plan = super::list_x::submission_plan(&mapped); drop(preparation_stall); let mut chunks = 0usize; @@ -11592,12 +11600,14 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis ) { return (false, None); } + let t_after = std::time::Instant::now(); super::gpu_times::executed(this, lists); chunks += 1; submitted.extend_from_slice(lists); super::list_x::copy_scratch_submitted(this, lists); let effects = chunk.submit_effects(this); super::list_x::note_submitted(this); + super::submit_cost::after(t_after.elapsed()); (true, effects) }) }); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index ed17b4df3a..7fbdcf74b3 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -990,6 +990,9 @@ mod tests { let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + // (adopted as a title's list is: the split binds through the list's original + // SetPipelineState, `real::bind_pipeline_exact`) + super::super::adopt(list.as_raw(), super::super::Kind::CommandList); let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0); let args = pso::chain_commands_buffer(&dev, 1).unwrap(); @@ -1000,7 +1003,10 @@ mod tests { list_reset(raw_list); let next_recording = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap(); assert!(!Arc::ptr_eq(&recorded, &next_recording)); - list.Close().unwrap(); + // (the list's own Close, not XCL's hook of a title list's) + type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT; + let close: Close = std::mem::transmute(super::super::orig_fn(list.as_raw(), 9)); + assert!(close(list.as_raw()) >= 0); allocator_reset(allocator); list_reset(raw_list); forget(key); diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index acf8b51efb..489fc9243b 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -278,6 +278,7 @@ pub(super) unsafe fn graphics_stream_key(stream: &[u8], samplers: &[crate::gpu:: stream_key(stream, samplers, GRAPHICS_STREAM_CACHE_SCHEMA, 3, 0, mem_windows) } +#[allow(dead_code)] // consumed by main's next stacked cache stage pub(super) fn two_pass_cs_key(cs: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], driver_id: u64, mem_windows: u32) -> u64 { let mut h = Fnv64::new(); h.u32(TWO_PASS_CACHE_SCHEMA); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cae13913f2..a99cc163ed 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -2829,8 +2829,6 @@ struct HashUpdate { hash: u64, } -const MAX_BATCH_HASH_UPDATES: usize = STAGING / CHUNK; - /// One synchronously-recorded dirty upload batch. The slot, ring rollback point, and unpublished /// hash plan move together so a failed submission cannot publish bytes that have no fence receipt. struct PreparedDirtyBatch { @@ -2851,23 +2849,11 @@ impl PreparedDirtyBatch { self } - fn hash_plan_would_overflow(&self, bytes: usize) -> bool { - batch_hash_plan_would_overflow(self.updates.len(), bytes) - } - - fn append_hashes(&mut self, at: usize, bytes: &[u8]) { - append_hash_updates(at, bytes, &mut self.updates); - } - fn clear_after_submit(&mut self) { self.updates.clear(); } } -fn batch_hash_plan_would_overflow(current: usize, bytes: usize) -> bool { - bytes / CHUNK > MAX_BATCH_HASH_UPDATES.saturating_sub(current) -} - /// Plan changed 64-byte chunk runs in a 4 KiB page without publishing their hashes. The hashes /// become `sent` only after the corresponding upload has a durable queue-fence receipt. /// This keeps the fresh-zero-page fast path allocation-free. @@ -2912,10 +2898,10 @@ fn scan_page( } } +#[cfg(test)] fn append_hash_updates(at: usize, bytes: &[u8], updates: &mut Vec) { debug_assert_eq!(at % CHUNK, 0); debug_assert_eq!(bytes.len() % CHUNK, 0); - debug_assert!(updates.len() + bytes.len() / CHUNK <= MAX_BATCH_HASH_UPDATES); updates.extend(bytes.chunks_exact(CHUNK).enumerate().map(|(i, chunk)| HashUpdate { at: at + i * CHUNK, hash: chunk_hash(chunk), @@ -10464,33 +10450,23 @@ mod tests { assert_eq!(runs, [(base, CHUNK)]); } - #[test] - fn batch_hash_plan_is_bounded_by_staging() { - assert_eq!(MAX_BATCH_HASH_UPDATES, STAGING / CHUNK); - assert_eq!(MAX_BATCH_HASH_UPDATES * std::mem::size_of::(), STAGING / 4); - assert!(!batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES - 1, CHUNK)); - assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES, CHUNK)); - assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES / 2 + 1, STAGING / 2)); - } - #[test] fn prepared_dirty_batch_keeps_exact_hash_plan_and_rollback_point() { let mut batch = PreparedDirtyBatch::new(3, 0x12_3400); let bytes = [0xA5; 2 * CHUNK]; - batch.append_hashes(0x20_0000, &bytes); + append_hash_updates(0x20_0000, &bytes, &mut batch.updates); assert_eq!(batch.slot, 3); assert_eq!(batch.ring_start, 0x12_3400); assert_eq!(batch.updates.len(), 2); assert_eq!(batch.updates[0], HashUpdate { at: 0x20_0000, hash: chunk_hash(&bytes[..CHUNK]) }); assert_eq!(batch.updates[1], HashUpdate { at: 0x20_0000 + CHUNK, hash: chunk_hash(&bytes[CHUNK..]) }); - assert!(!batch.hash_plan_would_overflow(CHUNK)); let storage = batch.updates.as_ptr(); let capacity = batch.updates.capacity(); for index in 0..3 { batch.clear_after_submit(); batch = batch.reopen(4 + index, 0x20_0000 + index as u64 * PAGE as u64); - batch.append_hashes(0x30_0000, &bytes); + append_hash_updates(0x30_0000, &bytes, &mut batch.updates); assert_eq!(batch.updates.as_ptr(), storage, "batch {index} replaced its hash-plan allocation"); assert_eq!(batch.updates.capacity(), capacity); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2fe0c9e12e..6f0d113534 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1235,7 +1235,8 @@ pub(super) fn is_own_work() -> bool { } /// Before the title's GPU work: textures whose memory the CPU wrote since the last look are -/// uploaded again. +/// uploaded again. Tests only: the runtime's submits call `refresh_for`. +#[cfg(test)] pub(super) unsafe fn refresh(queue: *mut c_void) -> super::sparse::PreparationOutcome { // the uploads' own ExecuteCommandLists come back here if BUSY.with(|b| b.get()) { diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 7cf0d35835..0bbe15f623 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1105,6 +1105,22 @@ impl TexelMeta { } } + /// Levels `levels` got pages (`map_levels`): the texels it adds to the resident ones. + fn levels_got_pages(&mut self, levels: std::ops::Range) -> u64 { + let added = range_texels(self.width, self.height, self.depth, self.dim, levels); + let delta = self.total_texels.saturating_sub(self.resident_texels).min(added); + self.resident_texels += delta; + delta + } + + /// Levels `levels` gave their pages back (`unmap_levels`): the texels it takes from the + /// resident ones. + fn levels_lost_pages(&mut self, levels: std::ops::Range) -> u64 { + let removed = range_texels(self.width, self.height, self.depth, self.dim, levels).min(self.resident_texels); + self.resident_texels -= removed; + removed + } + fn record_srv(&mut self, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> (bool, u64) { let first_srv = self.srv_sampled_texels == 0; let mips = srv_mip_range(self.mips as u32, desc); @@ -2740,10 +2756,8 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> l.group_tiles[k].1.extend(used_extra); } if let Some(tm) = t.texels.as_mut() { - let added = range_texels(tm.width, tm.height, tm.depth, tm.dim, levels.clone()); - let delta = tm.total_texels.saturating_sub(tm.resident_texels).min(added); + let delta = tm.levels_got_pages(levels.clone()); if delta > 0 { - tm.resident_texels += delta; TEXEL_STATS[3].fetch_add(delta, std::sync::atomic::Ordering::Relaxed); } } @@ -2774,6 +2788,7 @@ pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { let Some(t) = pages.targets.get_mut(&key) else { continue }; let Some(lv) = t.levels.as_mut().filter(|_| t.mapped) else { return 0 }; let mut ranges = Vec::new(); + let mut lost_levels = Vec::new(); let (mut gone, mut gone_extra) = (Vec::new(), Vec::new()); for k in 0..lv.groups.len() { if !lv.groups[k].3 || !lv.levels_of(k).all(|l| zero.contains(&l)) { @@ -2782,6 +2797,7 @@ pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { let (sub, _, n, _) = lv.groups[k]; lv.groups[k].3 = false; ranges.push((sub, n)); + lost_levels.push(lv.levels_of(k)); // (the pages the group owns) let (used, used_extra) = std::mem::take(&mut lv.group_tiles[k]); gone.extend(used); @@ -2790,6 +2806,12 @@ pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { if ranges.is_empty() { return 0; } + if let Some(tm) = t.texels.as_mut() { + let removed: u64 = lost_levels.into_iter().map(|levels| tm.levels_lost_pages(levels)).sum(); + if removed > 0 { + TEXEL_STATS[3].fetch_sub(removed, std::sync::atomic::Ordering::Relaxed); + } + } let freed: u64 = ranges.iter().map(|&(_, n)| n as u64).sum(); for (sub, n) in ranges { pages.unmap_range(res, sub, n); @@ -4975,6 +4997,32 @@ mod tests { assert_eq!(tm.srv_sampled_texels, tm.total_texels); } + /// Lazy levels that give their pages back (`unmap_levels`) take their texels from the resident + /// ones, as getting them (`map_levels`) added them: the count comes back to where it was. + #[test] + fn texel_meta_resident_texels_follow_levels_losing_their_pages() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 4, + ..Default::default() + }; + let mut tm = TexelMeta::from_desc(&desc, false); + assert_eq!(tm.levels_got_pages(1..4), 16 + 4 + 1); + assert_eq!(tm.levels_got_pages(0..1), 64); + assert_eq!(tm.resident_texels, tm.total_texels); + // mip 0 gives its pages back, and gets them again + assert_eq!(tm.levels_lost_pages(0..1), 64); + assert_eq!(tm.resident_texels, 16 + 4 + 1); + assert_eq!(tm.levels_got_pages(0..1), 64); + // all of it, then once more: nothing below zero + assert_eq!(tm.levels_lost_pages(0..4), tm.total_texels); + assert_eq!(tm.levels_lost_pages(0..4), 0); + assert_eq!(tm.resident_texels, 0); + } + #[test] fn texel_meta_unions_array_slices_without_counting_the_whole_mip() { let desc = D3D12_RESOURCE_DESC {