diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index fb532258fd..1420d7c8fb 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -3528,9 +3528,23 @@ impl State { let h = self.add_pool(heap); return Some(((h, 0), true)); } - let desc = D3D12_HEAP_DESC { + static L0_SPARSE_HEAP_UNSUPPORTED: AtomicBool = AtomicBool::new(false); + let allow_l0 = super::vram::l0_vram_margin() > 0 + && !L0_SPARSE_HEAP_UNSUPPORTED.load(Ordering::Relaxed); + let spill_l0 = allow_l0 && super::vram::should_spill_l0_for_vram(); + let make_desc = |l0: bool| D3D12_HEAP_DESC { SizeInBytes: POOL_TILES as u64 * TILE as u64, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Properties: if l0 { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + CreationNodeMask: 0, + VisibleNodeMask: 0, + } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }, Alignment: 0, Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, }; @@ -3538,14 +3552,44 @@ impl State { // CPU signal that asks meanwhile gives up after 2 ms) self.flush_pending(); let mut heap: Option = None; - if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) { - crate::xlog_warn!("sparse windows: no video memory for more tiles ({e})"); - return None; + let mut placed_l0 = spill_l0; + if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&make_desc(spill_l0), &mut heap)) { + if spill_l0 { + super::vram::note_l0_heap_error(&L0_SPARSE_HEAP_UNSUPPORTED, &e); + placed_l0 = false; + if let Err(e2) = super::title_textures::own_work(|| self.dev.CreateHeap(&make_desc(false), &mut heap)) { + crate::xlog_warn!("sparse windows: no video memory for more tiles ({e2})"); + return None; + } + } else if allow_l0 { + placed_l0 = true; + if let Err(e2) = super::title_textures::own_work(|| self.dev.CreateHeap(&make_desc(true), &mut heap)) { + super::vram::note_l0_heap_error(&L0_SPARSE_HEAP_UNSUPPORTED, &e2); + crate::xlog_warn!("sparse windows: no video memory for more tiles ({e}; L0 fallback: {e2})"); + return None; + } + } else { + crate::xlog_warn!("sparse windows: no video memory for more tiles ({e})"); + return None; + } } let heap = heap?; - let _ = heap.SetName(windows::core::w!("xcl sparse tile pool")); - // (once, when made: a retired pool taken back above keeps the priority it got) - super::vram::set_heap_priority(&self.dev, &heap, super::vram::HeapRole::WindowPool); + if placed_l0 { + let _ = heap.SetName(windows::core::w!("xcl sparse tile pool (L0)")); + static L0_MADE: AtomicU64 = AtomicU64::new(0); + let n = L0_MADE.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + let (used, budget) = super::real::video_memory().map_or((0, 0), |(u, _, b)| (u >> 20, b >> 20)); + crate::xlog_info!( + "sparse windows: tile pool #{n} spilled to L0 system memory ({} MiB spilled so far; local VRAM {used}/{budget} MiB)", + (n * (POOL_TILES as u64 * TILE as u64)) >> 20 + ); + } + } else { + let _ = heap.SetName(windows::core::w!("xcl sparse tile pool")); + // (once, when made: a retired pool taken back above keeps the priority it got) + super::vram::set_heap_priority(&self.dev, &heap, super::vram::HeapRole::WindowPool); + } let h = self.add_pool(heap); Some(((h, 0), false)) } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 3311c24ede..722ef6e28b 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1666,30 +1666,133 @@ impl TilePool { } } -/// Allocate one 64 MiB default heap for `Pages`. -unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { - let desc = D3D12_HEAP_DESC { +/// Opt-in local-VRAM headroom margin (`XCL_L0_VRAM_MARGIN_MB`, default `0` = disabled). +/// When non-zero, new sparse tile pools and sampled-only texture tile pools spill to +/// `D3D12_MEMORY_POOL_L0` (system memory) once DXGI local VRAM usage is within this margin of +/// budget, keeping render targets, depth buffers, and hot arenas in fast local VRAM. +fn parse_l0_vram_margin_bytes(val: Option<&str>) -> u64 { + val.and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0) + .saturating_mul(1 << 20) +} + +pub(super) fn l0_vram_margin() -> u64 { + static MARGIN: std::sync::OnceLock = std::sync::OnceLock::new(); + *MARGIN.get_or_init(|| parse_l0_vram_margin_bytes(std::env::var("XCL_L0_VRAM_MARGIN_MB").ok().as_deref())) +} + +fn vram_within_margin(used: u64, budget: u64, margin: u64) -> bool { + margin > 0 && budget > 0 && used.saturating_add(margin) >= budget +} + +/// Set when the adapter rejects a custom `D3D12_MEMORY_POOL_L0` texture heap for a non-OOM +/// reason so subsequent texture-pool allocations go straight to `D3D12_HEAP_TYPE_DEFAULT`. +static L0_TEX_HEAP_UNSUPPORTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub(super) fn note_l0_heap_error(flag: &std::sync::atomic::AtomicBool, err: &windows::core::Error) { + const E_OUTOFMEMORY: i32 = 0x8007000Eu32 as i32; + if err.code().0 != E_OUTOFMEMORY { + flag.store(true, std::sync::atomic::Ordering::Relaxed); + } +} + +pub(super) fn should_spill_l0_for_vram() -> bool { + let margin = l0_vram_margin(); + if margin == 0 { + return false; + } + static CACHED: Mutex> = Mutex::new(None); + let now = std::time::Instant::now(); + if let Ok(g) = CACHED.try_lock() { + if let Some((at, spill)) = *g { + if now.saturating_duration_since(at) < std::time::Duration::from_millis(250) { + return spill; + } + } + } + let spill = super::real::video_memory().is_some_and(|(used, _, budget)| vram_within_margin(used, budget, margin)); + if let Ok(mut g) = CACHED.try_lock() { + *g = Some((now, spill)); + } + spill +} + +/// Build a 64 MiB texture-pool heap descriptor (`l0 = true` for sampled-only L0 spillover). +fn texture_pool_heap_desc(l0: bool) -> D3D12_HEAP_DESC { + D3D12_HEAP_DESC { SizeInBytes: POOL_PAGES as u64 * PAGE as u64, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Properties: if l0 { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + CreationNodeMask: 0, + VisibleNodeMask: 0, + } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }, Alignment: 0, - // every kind of texture (resource heap tier 2: the only flags for both) - Flags: D3D12_HEAP_FLAG_NONE, - }; + // L0 custom heaps must deny RT/DS textures and buffers; sampled-only (`evictable`) + // pools only ever hold non-RT/DS textures. + Flags: if l0 { + D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_BUFFERS + } else { + // every kind of texture (resource heap tier 2: the only flags for both) + D3D12_HEAP_FLAG_NONE + }, + } +} + +/// Allocate one 64 MiB heap for `Pages`. When `XCL_L0_VRAM_MARGIN_MB` is enabled and local VRAM +/// is within that margin of budget, sampled-only (`evictable`) pools spill to L0 system memory. +unsafe fn alloc_pool_heap(dev: &ID3D12Device, evictable: bool) -> Option<(ID3D12Heap, bool)> { + let allow_l0 = evictable && l0_vram_margin() > 0 && !L0_TEX_HEAP_UNSUPPORTED.load(std::sync::atomic::Ordering::Relaxed); + let spill_l0 = allow_l0 && should_spill_l0_for_vram(); let mut heap: Option = None; - if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&desc, &mut heap)) { - crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); - return None; + let mut placed_l0 = spill_l0; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&texture_pool_heap_desc(spill_l0), &mut heap)) { + if spill_l0 { + note_l0_heap_error(&L0_TEX_HEAP_UNSUPPORTED, &e); + placed_l0 = false; + if let Err(e2) = super::title_textures::own_work(|| dev.CreateHeap(&texture_pool_heap_desc(false), &mut heap)) { + crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e2})"); + return None; + } + } else if allow_l0 { + placed_l0 = true; + if let Err(e2) = super::title_textures::own_work(|| dev.CreateHeap(&texture_pool_heap_desc(true), &mut heap)) { + note_l0_heap_error(&L0_TEX_HEAP_UNSUPPORTED, &e2); + crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e}; L0 fallback: {e2})"); + return None; + } + } else { + crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); + return None; + } } - if let Some(h) = &heap { - set_heap_priority(dev, h, HeapRole::TexturePages); + let h = heap?; + if placed_l0 { + static L0_TEX_POOLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = L0_TEX_POOLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + let (used, budget) = super::real::video_memory().map_or((0, 0), |(u, _, b)| (u >> 20, b >> 20)); + crate::xlog_info!( + "D3D12.X: texture page pool #{n} spilled to L0 system memory ({} MiB spilled so far; local VRAM {used}/{budget} MiB)", + (n * (POOL_PAGES as u64 * PAGE as u64)) >> 20 + ); + } + } else { + set_heap_priority(dev, &h, HeapRole::TexturePages); } - heap + Some((h, placed_l0)) } -/// Backing 64 MiB default heaps for `Pages`, supporting slot reuse when completely empty heaps -/// are reclaimed back to local VRAM. `len()` reports the count of live heaps. +/// Backing 64 MiB heaps for `Pages`, supporting slot reuse when completely empty heaps +/// are reclaimed. `len()` reports the count of live heaps. struct PoolHeaps { slots: Vec>, + is_l0: Vec, free_slots: Vec, live: usize, /// slots whose heap got `HIGH` for the pages of a target (`Pages::keep_pools`) @@ -1698,28 +1801,35 @@ struct PoolHeaps { impl PoolHeaps { fn new() -> Self { - Self { slots: Vec::new(), free_slots: Vec::new(), live: 0, high: HashSet::new() } + Self { slots: Vec::new(), is_l0: Vec::new(), free_slots: Vec::new(), live: 0, high: HashSet::new() } } fn len(&self) -> usize { self.live } - fn push_heap(&mut self, heap: ID3D12Heap) -> u32 { + fn is_l0(&self, idx: u32) -> bool { + self.is_l0.get(idx as usize).copied().unwrap_or(false) + } + + fn push_heap(&mut self, heap: ID3D12Heap, l0: bool) -> u32 { self.live += 1; if let Some(idx) = self.free_slots.pop() { debug_assert!(self.slots[idx as usize].is_none()); self.slots[idx as usize] = Some(heap); + self.is_l0[idx as usize] = l0; idx } else { let idx = self.slots.len() as u32; self.slots.push(Some(heap)); + self.is_l0.push(l0); idx } } fn take_heap(&mut self, idx: u32) -> Option { let h = self.slots.get_mut(idx as usize)?.take()?; + self.is_l0[idx as usize] = false; self.live -= 1; self.high.remove(&idx); self.free_slots.push(idx); @@ -1761,6 +1871,64 @@ struct HeldUnmap { /// Its pages cool at once (`unmap_superseded`), or stay for `IDLE` with what they hold /// (`unmap_superseded_target`). immediate_cool: bool, + /// Set if any page in `used`/`used_extra`/`level_tiles` was promoted from L0 to local VRAM + /// while this unmap was pending; cancelling the unmap must re-map `res` to the new tiles. + stale_mapping: bool, +} + +const PROMO_TILES: usize = 64; +const PROMO_TILE_W: u32 = 128; +const PROMO_TILE_H: u32 = 128; + +/// Lazily-created 0-VRAM scratch resources used to copy 64 KiB tile bytes on `Pages::queue` +/// when an L0 sampled-texture page is promoted in-place to local VRAM for a target. +struct TilePromoter { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + src: ID3D12Resource, + dst: ID3D12Resource, + event: windows::Win32::Foundation::HANDLE, +} + +impl Drop for TilePromoter { + fn drop(&mut self) { + if !self.event.is_invalid() { + unsafe { let _ = windows::Win32::Foundation::CloseHandle(self.event); } + } + } +} + +impl TilePromoter { + unsafe fn new(dev: &ID3D12Device) -> Option { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).ok()?; + list.Close().ok()?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: PROMO_TILE_W as u64, + Height: PROMO_TILE_H * PROMO_TILES as u32, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let mut src: Option = None; + let mut dst: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut src).ok()?; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut dst).ok()?; + let (src, dst) = (src?, dst?); + let mut total = 0u32; + let mut shape = D3D12_TILE_SHAPE::default(); + dev.GetResourceTiling(&src, Some(&mut total), None, Some(&mut shape), None, 0, std::ptr::null_mut()); + if total != PROMO_TILES as u32 || shape.WidthInTexels != PROMO_TILE_W || shape.HeightInTexels != PROMO_TILE_H { + return None; + } + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).ok()?; + Some(Self { alloc, list, src, dst, event }) + } } fn all_marks_complete(marks: &[(F, u64)], mut completed: impl FnMut(&F) -> u64) -> bool { @@ -1804,6 +1972,8 @@ struct Pages { scratch_flags: Vec, scratch_offsets: Vec, scratch_counts: Vec, + /// lazily-created scratch resources for copying promoted L0 tiles to local VRAM + promoter: Option, } // D3D12 objects are free-threaded @@ -1950,6 +2120,7 @@ impl Pages { scratch_flags: Vec::new(), scratch_offsets: Vec::new(), scratch_counts: Vec::new(), + promoter: None, }) } @@ -2184,7 +2355,13 @@ impl Pages { if !residency_priority_wanted() || role_priority(role).is_none() { return; } - let heaps = used.iter().filter_map(|a| self.pages.get(a)).chain(used_extra.iter().filter_map(|k| self.extra_pages.get(k))).map(|p| p.tile.0); + let is_l0 = &self.pools.is_l0; + let heaps = used + .iter() + .filter_map(|a| self.pages.get(a)) + .chain(used_extra.iter().filter_map(|k| self.extra_pages.get(k))) + .map(|p| p.tile.0) + .filter(|&h| !is_l0.get(h as usize).copied().unwrap_or(false)); for h in newly_high(&mut self.pools.high, heaps) { if let Some(heap) = self.pools.get(h as usize) { set_heap_priority(dev, heap, role); @@ -2192,7 +2369,200 @@ impl Pages { } } + /// Whether any existing page in `range` is currently backed by an L0 heap. + fn range_has_l0(&self, va: usize, console_bytes: Option, total: u32, range: std::ops::Range) -> bool { + let Some((first, own)) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten() else { + return false; + }; + for i in range { + let heap = if i < own { + self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) + } else { + self.extra_pages.get(&(va, i)).map(|p| p.tile.0) + }; + if heap.is_some_and(|h| self.pools.is_l0(h)) { + return true; + } + } + false + } + + /// Copy the raw 64 KiB tile bytes of each `(old_l0_tile, new_local_tile)` pair on `self.queue` + /// so in-place promotion from L0 to local VRAM preserves uploaded texels. + unsafe fn copy_promoted_tiles(&mut self, dev: &ID3D12Device, pairs: &[(Tile, Tile)]) { + if pairs.is_empty() { + return; + } + if self.promoter.is_none() { + self.promoter = TilePromoter::new(dev); + } + let Some(promoter) = self.promoter.take() else { + crate::xlog_warn!("D3D12.X: could not initialize L0 tile promoter; promoted page contents may be lost"); + return; + }; + let mut old_tiles = Vec::with_capacity(PROMO_TILES); + let mut new_tiles = Vec::with_capacity(PROMO_TILES); + let mut healthy = true; + let mut in_flight = false; + for chunk in pairs.chunks(PROMO_TILES) { + old_tiles.clear(); + new_tiles.clear(); + for &(old, new) in chunk { + old_tiles.push(old); + new_tiles.push(new); + } + let n = chunk.len() as u32; + // Record and close the copy command list before mapping `src`/`dst` so a Reset/Close + // failure leaves no GPU work in flight on `promoter`. + let recorded = if promoter.alloc.Reset().is_ok() && promoter.list.Reset(&promoter.alloc, None).is_ok() { + let dst_loc = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::ManuallyDrop::new(Some(promoter.dst.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let src_loc = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::ManuallyDrop::new(Some(promoter.src.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let src_box = D3D12_BOX { + left: 0, + top: 0, + front: 0, + right: PROMO_TILE_W, + bottom: n * PROMO_TILE_H, + back: 1, + }; + promoter.list.CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, Some(&src_box)); + let _ = std::mem::ManuallyDrop::into_inner(dst_loc.pResource); + let _ = std::mem::ManuallyDrop::into_inner(src_loc.pResource); + promoter.list.Close().is_ok() + } else { + false + }; + if !recorded { + crate::xlog_warn!("D3D12.X: failed to record L0 tile promotion copy; promoted page contents may be lost"); + healthy = false; + break; + } + self.map(&promoter.src, 0, &old_tiles); + self.map(&promoter.dst, 0, &new_tiles); + let cmd: ID3D12CommandList = promoter.list.clone().into(); + super::title_textures::own_work(|| { + super::real::native_queue_execute(&self.queue, &cmd); + }); + self.unmap(&promoter.src, n); + self.unmap(&promoter.dst, n); + self.value += 1; + let target_val = self.value; + if super::real::native_queue_signal(&self.queue, &self.fence, target_val).is_err() { + crate::xlog_warn!("D3D12.X: failed to signal fence after L0 tile promotion copy"); + healthy = false; + in_flight = super::real::fence_completed(&self.fence) != u64::MAX; + break; + } + // Wait until map + copy + unmap all finish on `self.queue`. `self.queue` never waits + // on any title queue, so INFINITE cannot deadlock; on TDR D3D12 signals `u64::MAX`. + let mut done = super::real::fence_completed(&self.fence); + if done < target_val && done != u64::MAX { + if self.fence.SetEventOnCompletion(target_val, promoter.event).is_ok() { + let _ = windows::Win32::System::Threading::WaitForSingleObject( + promoter.event, + windows::Win32::System::Threading::INFINITE, + ); + done = super::real::fence_completed(&self.fence); + } else { + while done < target_val && done != u64::MAX { + std::thread::sleep(std::time::Duration::from_micros(100)); + done = super::real::fence_completed(&self.fence); + } + } + } + if done < target_val || done == u64::MAX { + crate::xlog_warn!("D3D12.X: L0 tile promotion copy did not complete (device removed or fence error)"); + healthy = false; + break; + } + } + if healthy { + self.promoter = Some(promoter); + } else if in_flight { + // Never release an allocator/resource that may still be executing on the GPU. + std::mem::forget(promoter); + } + } + + /// Re-map every live mapped resource whose tiles include any page promoted in-place from L0 to + /// local VRAM so aliases at the same console address stay pointed at the shared local tile. + /// Also marks any pending `held_unmaps` referencing a promoted page so cancelling that unmap + /// re-maps the resource onto the promoted local tiles instead of keeping the old L0 tile. + unsafe fn remap_promoted(&mut self, exclude: usize, promoted_own: &HashSet, promoted_extra: &HashSet<(usize, usize)>) { + for held in &mut self.held_unmaps { + if held.stale_mapping { + continue; + } + let hit_flat = held.used.iter().any(|a| promoted_own.contains(a)) + || held.used_extra.iter().any(|ek| promoted_extra.contains(ek)); + let hit_levels = held.level_tiles.iter().any(|(u, e)| { + u.iter().any(|a| promoted_own.contains(a)) || e.iter().any(|ek| promoted_extra.contains(ek)) + }); + if hit_flat || hit_levels { + held.stale_mapping = true; + } + } + let mut to_remap: Vec<(usize, u32, Vec)> = Vec::new(); + for (&other_key, t) in &self.targets { + if other_key == exclude || !t.mapped { + continue; + } + if let Some(lv) = &t.levels { + for (k, g) in lv.groups.iter().enumerate() { + if !g.3 { + continue; + } + let (ref g_used, ref g_extra) = lv.group_tiles[k]; + if g_used.iter().any(|a| promoted_own.contains(a)) || g_extra.iter().any(|ek| promoted_extra.contains(ek)) { + let mut tiles = Vec::with_capacity(g_used.len() + g_extra.len()); + let mut ok = true; + for a in g_used { + if let Some(p) = self.pages.get(a) { tiles.push(p.tile); } else { ok = false; break; } + } + if ok { + for ek in g_extra { + if let Some(p) = self.extra_pages.get(ek) { tiles.push(p.tile); } else { ok = false; break; } + } + } + if ok { + to_remap.push((other_key, g.0, tiles)); + } + } + } + } else if t.used.iter().any(|a| promoted_own.contains(a)) || t.used_extra.iter().any(|ek| promoted_extra.contains(ek)) { + let mut tiles = Vec::with_capacity(t.used.len() + t.used_extra.len()); + let mut ok = true; + for a in &t.used { + if let Some(p) = self.pages.get(a) { tiles.push(p.tile); } else { ok = false; break; } + } + if ok { + for ek in &t.used_extra { + if let Some(p) = self.extra_pages.get(ek) { tiles.push(p.tile); } else { ok = false; break; } + } + } + if ok { + to_remap.push((other_key, 0, tiles)); + } + } + } + for (other_key, sub, tiles) in to_remap { + let ptr = other_key as *mut c_void; + if let Some(other_res) = ID3D12Resource::from_raw_borrowed(&ptr) { + self.map(other_res, sub, &tiles); + } + } + } + /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. + #[cfg(test)] unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize, false) } @@ -2216,6 +2586,9 @@ impl Pages { self.extra_pages.get(&(va, i)).map(|p| p.tile.0) }; match existing { + // A non-evictable target (RT/DS/UAV) cannot map onto an L0 heap (`DENY_RT_DS_TEXTURES`); + // allocate a local tile to promote the page in-place and remap any live aliases. + Some(h) if !evictable && self.pools.is_l0(h) => missing += 1, Some(h) if preferred.is_none() => preferred = Some(h), Some(_) => {} None => missing += 1, @@ -2225,19 +2598,29 @@ impl Pages { let pools = &mut self.pools; let pool = &mut self.pool; let fresh = pool.take_batch(missing, preferred, evictable, now, POOL_PAGES, || { - let heap = alloc_pool_heap(dev)?; - Some(pools.push_heap(heap)) + let (heap, l0) = alloc_pool_heap(dev, evictable)?; + Some(pools.push_heap(heap, l0)) })?; let mut fresh_iter = fresh.into_iter(); let mut tiles = Vec::with_capacity(range.len()); let mut used = Vec::with_capacity(own.min(range.len())); let mut used_extra = Vec::new(); + let mut promoted_own: HashSet = HashSet::new(); + let mut promoted_extra: HashSet<(usize, usize)> = HashSet::new(); + let mut promoted_pairs: Vec<(Tile, Tile)> = Vec::new(); for i in range { let tile = if i < own { let a = first + i * PAGE; let t = match self.pages.get_mut(&a) { Some(p) => { + if !evictable && self.pools.is_l0(p.tile.0) { + let old = p.tile; + let new_tile = fresh_iter.next().unwrap(); + p.tile = new_tile; + promoted_pairs.push((old, new_tile)); + promoted_own.insert(a); + } p.users += 1; p.idle_since = None; p.tile @@ -2254,6 +2637,13 @@ impl Pages { let k = (va, i); let t = match self.extra_pages.get_mut(&k) { Some(p) => { + if !evictable && self.pools.is_l0(p.tile.0) { + let old = p.tile; + let new_tile = fresh_iter.next().unwrap(); + p.tile = new_tile; + promoted_pairs.push((old, new_tile)); + promoted_extra.insert(k); + } p.users += 1; p.idle_since = None; p.tile @@ -2269,6 +2659,13 @@ impl Pages { }; tiles.push(tile); } + if !promoted_pairs.is_empty() { + self.copy_promoted_tiles(dev, &promoted_pairs); + for (old, _) in promoted_pairs { + self.pool.push_cooling(old, now); + } + self.remap_promoted(res.as_raw() as usize, &promoted_own, &promoted_extra); + } self.map(res, sub, &tiles); Some((used, used_extra)) } @@ -2289,6 +2686,51 @@ unsafe fn held_unmap_completions(dev_key: usize) -> Vec<(ID3D12Fence, u64)> { }).collect() } +/// Wait for all GPU work already submitted to active title queues, internal texture upload queues, +/// and retiring queues on `dev`. Called outside `PAGES` before promoting L0 tiles to local VRAM so +/// `copy_promoted_tiles` on `Pages::queue` reads completed uploads without creating a GPU-side +/// dependency from `Pages::queue` back to a title queue. +unsafe fn drain_device_queues(dev: &ID3D12Device) { + let dev_key = dev.as_raw() as usize; + let mut completion = super::present::queue_completion_snapshot(); + completion.active.extend(super::title_textures::upload_queues()); + let marked = { + let mut g = PAGES.lock().unwrap(); + g.get_mut(&dev_key) + .and_then(Option::as_mut) + .and_then(|pages| pages.mark_unmap(dev, &completion.active, &completion.retiring, completion.blocked)) + }; + let Some((marks, signals)) = marked else { + crate::xlog_warn!("D3D12.X: could not snapshot device queues before L0 page promotion"); + return; + }; + let mut failed_fences: HashSet = HashSet::new(); + for (queue, fence, value) in signals { + if super::real::native_queue_signal(&queue, &fence, value).is_err() { + failed_fences.insert(fence.as_raw() as usize); + crate::xlog_warn!("D3D12.X: could not signal queue before L0 page promotion"); + } + } + let start = std::time::Instant::now(); + for (fence, value) in marks { + if failed_fences.contains(&(fence.as_raw() as usize)) { + continue; + } + loop { + let done = super::real::fence_completed(&fence); + if done >= value || done == u64::MAX { + break; + } + if start.elapsed() >= std::time::Duration::from_millis(2000) { + crate::xlog_warn!("D3D12.X: timed out waiting for prior GPU work before L0 page promotion"); + return; + } + // Polling without an event avoids leaving a pending SetEventOnCompletion on timeout. + std::thread::sleep(std::time::Duration::from_micros(250)); + } + } +} + /// The ranges of one UpdateTileMappings call for pool heap `heap` over a resource whose overall /// tile i goes to `tiles[i]`: (mapped, tile offset in the heap, count) – runs of consecutive /// tiles of the heap, and skipped runs for tiles of other heaps. @@ -2472,8 +2914,20 @@ unsafe fn place_on_pages( None }; let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); + let evictable = !gpu_owned(desc.Flags.0 as u32) && l0_vram_margin() > 0; let bound = { let mut g = PAGES.lock().unwrap(); + if !evictable + && levels.is_none() + && l0_vram_margin() > 0 + && g.get(&dev_key) + .and_then(Option::as_ref) + .is_some_and(|p| p.range_has_l0(va, console_bytes, total, 0..total as usize)) + { + drop(g); + drain_device_queues(dev); + g = PAGES.lock().unwrap(); + } if let Some(Some(pages)) = g.get_mut(&dev_key) { if levels.is_some() { // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) @@ -2482,7 +2936,7 @@ unsafe fn place_on_pages( record_texel_insert(&texels); pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key }); true - } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { + } else if let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize, evictable) { pages.keep_pools(dev, pages_role(desc.Flags.0 as u32), &used, &used_extra); record_texel_insert(&texels); pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels, recycle: recycle_key }); @@ -2553,6 +3007,7 @@ unsafe fn unmap_placed(res: &ID3D12Resource, immediate_cool: bool) { level_tiles: take_level_tiles(target.levels.as_mut()), marks, immediate_cool, + stale_mapping: false, }; target.mapped = false; pages.held_unmaps.push(held); @@ -2585,9 +3040,11 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { if mapped { return true; } - // A deferred unmap never changed the resource's tiles. Cancel it and restore their ownership. + // A deferred unmap never changed the resource's tiles unless a page was promoted from L0 while + // pending (`stale_mapping`). Cancel it, restore ownership, and re-map if stale. if let Some(index) = pages.held_unmaps.iter().position(|held| held.res.as_raw() as usize == key) { let held = pages.held_unmaps.swap_remove(index); + let stale = held.stale_mapping; if let Some(target) = pages.targets.get_mut(&key) { target.used = held.used; target.used_extra = held.used_extra; @@ -2601,6 +3058,49 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { } target.mapped = true; } + if stale { + let mut remaps: Vec<(u32, Vec)> = Vec::new(); + if let Some(target) = pages.targets.get(&key) { + if let Some(lv) = &target.levels { + for (k, grp) in lv.groups.iter().enumerate() { + if !grp.3 { + continue; + } + let (ref u, ref e) = lv.group_tiles[k]; + let mut tiles = Vec::with_capacity(u.len() + e.len()); + let mut ok = true; + for a in u { + if let Some(p) = pages.pages.get(a) { tiles.push(p.tile); } else { ok = false; break; } + } + if ok { + for ek in e { + if let Some(p) = pages.extra_pages.get(ek) { tiles.push(p.tile); } else { ok = false; break; } + } + } + if ok { + remaps.push((grp.0, tiles)); + } + } + } else { + let mut tiles = Vec::with_capacity(target.used.len() + target.used_extra.len()); + let mut ok = true; + for a in &target.used { + if let Some(p) = pages.pages.get(a) { tiles.push(p.tile); } else { ok = false; break; } + } + if ok { + for ek in &target.used_extra { + if let Some(p) = pages.extra_pages.get(ek) { tiles.push(p.tile); } else { ok = false; break; } + } + } + if ok { + remaps.push((0, tiles)); + } + } + } + for (sub, tiles) in remaps { + pages.map(res, sub, &tiles); + } + } drop(g); drop(held.res); return true; @@ -2610,7 +3110,18 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.mapped = true; return true; } - let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { + let evictable = !gpu_owned(res.GetDesc().Flags.0 as u32) && l0_vram_margin() > 0; + if !evictable && l0_vram_margin() > 0 && pages.range_has_l0(va, console_bytes, total, 0..total as usize) { + drop(g); + drain_device_queues(&dev); + g = PAGES.lock().unwrap(); + } + let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; + let Some(mapped) = pages.targets.get(&key).map(|t| t.mapped) else { return false }; + if mapped { + return true; + } + let Some((used, used_extra)) = pages.bind_range(&dev, res, va, console_bytes, total, 0, 0..total as usize, evictable) else { return false; }; pages.keep_pools(&dev, pages_role(res.GetDesc().Flags.0 as u32), &used, &used_extra); @@ -3121,7 +3632,7 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return Vec::new() }; let mut fresh = Vec::new(); for (k, sub, first, n, levels) in todo { - let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, false) else { continue }; + let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, l0_vram_margin() > 0) else { continue }; let Some(t) = pages.targets.get_mut(&key) else { return fresh }; if let Some(l) = t.levels.as_mut() { l.groups[k].3 = true; @@ -5763,4 +6274,320 @@ mod tests { late_release::drain_known(true); } } + + #[test] + fn l0_vram_margin_parses_opt_in_default_and_checks_budget() { + assert_eq!(parse_l0_vram_margin_bytes(None), 0, "opt-in by default"); + assert_eq!(parse_l0_vram_margin_bytes(Some("0")), 0); + assert_eq!(parse_l0_vram_margin_bytes(Some("2048")), 2048 << 20); + assert_eq!(parse_l0_vram_margin_bytes(Some("bad")), 0); + + let budget = 10 << 30; + let margin = 2 << 30; + assert!(!vram_within_margin(9 << 30, budget, 0), "0 margin never spills"); + assert!(!vram_within_margin(9 << 30, 0, margin), "unknown budget never spills"); + assert!(!vram_within_margin(7 << 30, budget, margin), "3 GiB headroom stays in local VRAM"); + assert!(vram_within_margin(8 << 30, budget, margin), "exact margin triggers spill"); + assert!(vram_within_margin(11 << 30, budget, margin), "over budget triggers spill"); + assert!(vram_within_margin(u64::MAX, budget, margin), "saturating_add avoids overflow"); + + let l0_desc = texture_pool_heap_desc(true); + assert_eq!(l0_desc.Properties.Type, D3D12_HEAP_TYPE_CUSTOM); + assert_eq!(l0_desc.Properties.CPUPageProperty, D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE); + assert_eq!(l0_desc.Properties.MemoryPoolPreference, D3D12_MEMORY_POOL_L0); + assert_eq!(l0_desc.Flags, D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_BUFFERS); + + let local_desc = texture_pool_heap_desc(false); + assert_eq!(local_desc.Properties.Type, D3D12_HEAP_TYPE_DEFAULT); + assert_eq!(local_desc.Flags, D3D12_HEAP_FLAG_NONE); + } + + #[test] + fn pool_heaps_tracks_l0_flag_across_slot_reuse_and_l0_heap_creates() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return; + } + let dev = dev.unwrap(); + let small_local = D3D12_HEAP_DESC { + SizeInBytes: PAGE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_NONE, + }; + let mut h1: Option = None; + let mut h2: Option = None; + unsafe { + dev.CreateHeap(&small_local, &mut h1).expect("create local heap 1"); + dev.CreateHeap(&small_local, &mut h2).expect("create local heap 2"); + } + let mut pools = PoolHeaps::new(); + let slot = pools.push_heap(h1.unwrap(), true); + assert!(pools.is_l0(slot)); + assert_eq!(pools.len(), 1); + let taken = pools.take_heap(slot); + assert!(taken.is_some()); + assert!(!pools.is_l0(slot), "reclaimed slot must clear is_l0"); + assert_eq!(pools.len(), 0); + let reused = pools.push_heap(h2.unwrap(), false); + assert_eq!(reused, slot, "freed slot is reused"); + assert!(!pools.is_l0(reused), "reused slot must reflect new l0 flag"); + + // Verify sampled-only L0 texture heap and sparse buffer L0 heap creation on hardware D3D12. + if !matches!(crate::gpu::recomp::runner::wave32_supported(), Ok(true)) { + crate::gpu::recomp::runner::skip_test("no hardware GPU for L0 heap creation"); + return; + } + let mut l0_tex_desc = texture_pool_heap_desc(true); + l0_tex_desc.SizeInBytes = PAGE as u64; + let mut l0_tex_heap: Option = None; + if let Err(e) = unsafe { dev.CreateHeap(&l0_tex_desc, &mut l0_tex_heap) } { + crate::gpu::recomp::runner::skip_test(&format!("adapter declined L0 texture heap: {e}")); + return; + } + assert!(l0_tex_heap.is_some()); + + let mut l0_buf_desc = l0_tex_desc; + l0_buf_desc.Flags = D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; + let mut l0_buf_heap: Option = None; + if let Err(e) = unsafe { dev.CreateHeap(&l0_buf_desc, &mut l0_buf_heap) } { + crate::gpu::recomp::runner::skip_test(&format!("adapter declined L0 buffer heap: {e}")); + return; + } + assert!(l0_buf_heap.is_some()); + } + + #[test] + fn l0_page_promotes_in_place_to_local_when_target_binds_same_va() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if !matches!(crate::gpu::recomp::runner::wave32_supported(), Ok(true)) { + crate::gpu::recomp::runner::skip_test("no hardware GPU"); + return; + } + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return; + } + let dev = dev.unwrap(); + let Some(mut pages) = (unsafe { Pages::new(&dev) }) else { + crate::gpu::recomp::runner::skip_test("no Tier 2 tiled resources"); + return; + }; + + // Seed an evictable L0 pool heap so the sampled texture binds into L0. + let mut l0_heap: Option = None; + if let Err(e) = unsafe { dev.CreateHeap(&texture_pool_heap_desc(true), &mut l0_heap) } { + crate::gpu::recomp::runner::skip_test(&format!("adapter declined L0 texture heap: {e}")); + return; + } + let l0_slot = pages.pools.push_heap(l0_heap.unwrap(), true); + pages.pool.add_heap_at(l0_slot, POOL_PAGES, true); + + let make_reserved = |flags: D3D12_RESOURCE_FLAGS| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: flags, + ..Default::default() + }; + let mut res: Option = None; + unsafe { + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res) + .expect("CreateReservedResource"); + } + res.unwrap() + }; + + let sampled = make_reserved(D3D12_RESOURCE_FLAG_NONE); + let rt = make_reserved(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let mut total = 0u32; + unsafe { dev.GetResourceTiling(&sampled, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); } + assert!(total > 0); + let va = 0x3000_0000usize; + let console_bytes = Some(total as u64 * PAGE as u64); + + unsafe { + // Helper to upload a solid RGBA32 pixel to a 256x256 texture or read back pixel (0,0) on `pages.queue`. + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.Close().unwrap(); + let row_pitch = 256u32 * 4; + let buf_bytes = (row_pitch * 256) as u64; + let make_buf = |heap_type: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| -> ID3D12Resource { + let hp = D3D12_HEAP_PROPERTIES { Type: heap_type, ..Default::default() }; + let bd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: buf_bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &bd, state, None, &mut r).unwrap(); + r.unwrap() + }; + let upload_buf = make_buf(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let readback_buf = make_buf(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + let fence_ev = windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap(); + let run_copy = |pages: &mut Pages, dst_tex: Option<&ID3D12Resource>, src_tex: Option<&ID3D12Resource>| { + alloc.Reset().unwrap(); + list.Reset(&alloc, None).unwrap(); + let fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + Width: 256, + Height: 256, + Depth: 1, + RowPitch: row_pitch, + }, + }; + if let Some(tex) = dst_tex { + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::ManuallyDrop::new(Some(tex.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::ManuallyDrop::new(Some(upload_buf.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + let _ = std::mem::ManuallyDrop::into_inner(dst.pResource); + let _ = std::mem::ManuallyDrop::into_inner(src.pResource); + } else if let Some(tex) = src_tex { + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::ManuallyDrop::new(Some(readback_buf.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::ManuallyDrop::new(Some(tex.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + let _ = std::mem::ManuallyDrop::into_inner(dst.pResource); + let _ = std::mem::ManuallyDrop::into_inner(src.pResource); + } + list.Close().unwrap(); + let cmd: ID3D12CommandList = list.clone().into(); + pages.queue.ExecuteCommandLists(&[Some(cmd)]); + pages.value += 1; + let v = pages.value; + assert!(super::super::real::native_queue_signal(&pages.queue, &pages.fence, v).is_ok()); + if super::super::real::fence_completed(&pages.fence) < v { + pages.fence.SetEventOnCompletion(v, fence_ev).unwrap(); + windows::Win32::System::Threading::WaitForSingleObject(fence_ev, 5000); + } + }; + let fill_upload = |pixel: [u8; 4]| { + let mut ptr = std::ptr::null_mut(); + upload_buf.Map(0, None, Some(&mut ptr)).unwrap(); + let slice = std::slice::from_raw_parts_mut(ptr as *mut u8, buf_bytes as usize); + for px in slice.chunks_exact_mut(4) { px.copy_from_slice(&pixel); } + upload_buf.Unmap(0, None); + }; + let read_pixel0 = || -> [u8; 4] { + let mut ptr = std::ptr::null_mut(); + readback_buf.Map(0, None, Some(&mut ptr)).unwrap(); + let px = *(ptr as *const [u8; 4]); + readback_buf.Unmap(0, None); + px + }; + + // 1. Sampled texture binds onto the L0 pool and receives uploaded texels. + let (used1, extra1) = pages + .bind_range(&dev, &sampled, va, console_bytes, total, 0, 0..total as usize, true) + .expect("bind sampled on L0"); + assert_eq!(used1.len(), total as usize); + assert!(extra1.is_empty()); + let old_l0_tiles: Vec = used1.iter().map(|a| pages.pages[a].tile).collect(); + assert!(old_l0_tiles.iter().all(|&(h, _)| h == l0_slot && pages.pools.is_l0(h))); + pages.targets.insert( + sampled.as_raw() as usize, + Target { va, console_bytes, total, mapped: true, used: used1.clone(), used_extra: extra1, levels: None, texels: None, recycle: None }, + ); + fill_upload([0x12, 0x34, 0x56, 0x78]); + run_copy(&mut pages, Some(&sampled), None); + + // Also stage a pending HeldUnmap referencing `used1` (initially mapped to L0) to verify + // `stale_mapping` gets set on promotion and cancelling it remaps onto the promoted tiles. + let held_tex = make_reserved(D3D12_RESOURCE_FLAG_NONE); + pages.map(&held_tex, 0, &old_l0_tiles); + pages.targets.insert( + held_tex.as_raw() as usize, + Target { va, console_bytes, total, mapped: false, used: Vec::new(), used_extra: Vec::new(), levels: None, texels: None, recycle: None }, + ); + pages.held_unmaps.push(HeldUnmap { + res: held_tex.clone(), + total, + used: used1.clone(), + used_extra: Vec::new(), + level_tiles: Vec::new(), + marks: Vec::new(), + immediate_cool: false, + stale_mapping: false, + }); + + // 2. Render target binds the exact same VA: must promote pages in-place to local VRAM, + // copy the uploaded texels across, remap the live sampled alias, and flag HeldUnmap. + let (used2, extra2) = pages + .bind_range(&dev, &rt, va, console_bytes, total, 0, 0..total as usize, false) + .expect("bind RT at same VA promotes L0 pages to local"); + assert_eq!(used2, used1, "RT and sampled alias must share the exact same page keys"); + assert!(extra2.is_empty() && pages.extra_pages.is_empty(), "must promote in place without splitting"); + for a in &used2 { + let p = &pages.pages[a]; + assert!(!pages.pools.is_l0(p.tile.0), "promoted page must live in local VRAM"); + assert_eq!(p.users, 2, "both sampled texture and RT must share the promoted page"); + } + assert!(pages.held_unmaps[0].stale_mapping, "pending HeldUnmap on promoted page must be marked stale"); + assert_eq!(pages.pool.cooling.len(), total as usize, "old L0 tiles must be cooled"); + for old in &old_l0_tiles { + assert!(pages.pool.cooling.iter().any(|(t, _)| t == old)); + } + + // 3. Verify uploaded texels survived L0 -> local promotion on BOTH RT and sampled alias. + run_copy(&mut pages, None, Some(&rt)); + assert_eq!(read_pixel0(), [0x12, 0x34, 0x56, 0x78], "RT must observe promoted texels"); + run_copy(&mut pages, None, Some(&sampled)); + assert_eq!(read_pixel0(), [0x12, 0x34, 0x56, 0x78], "sampled alias must observe promoted texels"); + + // 4. Write new texels into RT and verify the remapped sampled alias reads them live. + fill_upload([0xAA, 0xBB, 0xCC, 0xDD]); + run_copy(&mut pages, Some(&rt), None); + run_copy(&mut pages, None, Some(&sampled)); + assert_eq!(read_pixel0(), [0xAA, 0xBB, 0xCC, 0xDD], "sampled alias must share live writes from RT"); + + // 5. Cancel the stale HeldUnmap via `remap_if_unmapped` and verify it reads live RT texels + // (proving it was remapped from the old L0 tile onto the promoted local tile). + let dev_key = dev.as_raw() as usize; + let prev_pages = PAGES.lock().unwrap().insert(dev_key, Some(pages)); + assert!(remap_if_unmapped(&held_tex), "cancelling stale HeldUnmap must succeed"); + let mut pages = PAGES.lock().unwrap().remove(&dev_key).flatten().unwrap(); + if let Some(prev) = prev_pages { + PAGES.lock().unwrap().insert(dev_key, prev); + } + assert!(pages.held_unmaps.is_empty()); + run_copy(&mut pages, None, Some(&held_tex)); + assert_eq!(read_pixel0(), [0xAA, 0xBB, 0xCC, 0xDD], "cancelled HeldUnmap must remap to promoted local tile"); + + let _ = windows::Win32::Foundation::CloseHandle(fence_ev); + assert!(dev.GetDeviceRemovedReason().is_ok(), "device healthy after promotion, copy, and remap"); + } + } }