From dfbbd92fef632ca917e1fc6306cc3c81951f749d Mon Sep 17 00:00:00 2001 From: PrivacyOnion Date: Wed, 25 Nov 2026 08:53:33 +0100 Subject: [PATCH] gpu, docs: keep placed texture views in step with title memory Placed texture views (host copies made for a texture the title placed in its own memory) now follow that memory: - A remap or unmap cancels a view still being created, so a creation that finishes late can no longer reinsert a stale entry. - Expired views are reaped during normal submissions instead of only at the next invalidation. - A read-only view waits for at least one mapped page. - A slot whose view cannot be made now gets a null view, with no second attempt under the descriptor lock. - A slot already made over a placed view's texture keeps it when a racing mirror finds no texture there because another thread is still making one (texture_lookup reports that case apart). Before, that mirror wrote a null view over the good one until the slot was made again. With no mapped page or a failed creation, the slot still follows the memory and is made null. - A failed rebuild still records the alias change, as before, so it is not tried again on every lookup. The frame report gives host texture count and MiB by creation origin (committed, heap offset, address, placed view, external) and the placed-view cache counts. --- crates/xtp-gpu/src/descriptor/host.rs | 145 +++++++++- crates/xtp-gpu/src/device.rs | 1 + crates/xtp-gpu/src/host.rs | 1 + crates/xtp-gpu/src/resource.rs | 393 +++++++++++++++++++++----- crates/xtp-gpu/src/resource/alias.rs | 13 +- crates/xtp-gpu/src/resource/format.rs | 27 +- docs/analysis/vram.md | 6 + 7 files changed, 500 insertions(+), 86 deletions(-) diff --git a/crates/xtp-gpu/src/descriptor/host.rs b/crates/xtp-gpu/src/descriptor/host.rs index d8e5c0a2..81928a1f 100644 --- a/crates/xtp-gpu/src/descriptor/host.rs +++ b/crates/xtp-gpu/src/descriptor/host.rs @@ -1870,11 +1870,12 @@ impl HostHeap { // record stays the same, so the slot is made again when the host // texture changes. Resolved before the lock, since making the // resource can wait. - let placed = match &view { + let (placed, building) = match &view { Some(v @ View::Placed(_, resource, _)) if for_draw && resource[0] != 1 => { - Some(placed_texture(v)) + let (made, building) = placed_texture_or_building(v); + (Some(made), building) } - _ => None, + _ => (None, false), }; // A texture object's host copy is there for the GPU only once it is // resident, which may be after the title wrote its views: the slot, @@ -1948,7 +1949,17 @@ impl HostHeap { return Ok(None); }; let mut old = None; - if stale(&made) { + // No host texture for a placed view now. While another thread is + // still making it, a slot already made for this record over a + // texture keeps it: a mirror racing the maker would otherwise leave + // the slot null until it is made again. With no mapped page or a + // failed creation, the slot follows the memory and is made null. + let pending = matches!(placed, Some(None)); + let holds = |made: &Made| { + made.keys[index as usize] == key + && made.textures.get(&index).is_some_and(|&(_, r)| r != 0) + }; + if stale(&made) && !(pending && building && holds(&made)) { let view = placed.as_ref().and_then(Option::as_ref).unwrap_or(&view); let later = !for_draw && view.is_buffer(); made.keys[index as usize] = if later { 0 } else { key }; @@ -1966,7 +1977,7 @@ impl HostHeap { _ => made.textures.remove(&index), }; let mut viewed = None; - let kept = if later { + let kept = if later || pending { None } else { let wanted = (self.strides.is_some() || picking).then_some(&mut viewed); @@ -4016,21 +4027,33 @@ fn copy_range(view: &View) -> Option<(u64, u64)> { /// mirrored as shader views are, and their writes stay in the host copy /// that later views of that memory share (`alias`). pub(crate) fn placed_texture(view: &View) -> Option { + placed_texture_or_building(view).0 +} + +/// [`placed_texture`], and whether there is none only because another +/// thread is still making the resource for that memory. +pub(crate) fn placed_texture_or_building(view: &View) -> (Option, bool) { + use crate::resource::PlacedLookup; const BUFFER: u32 = 1; let &View::Placed(unordered, ref resource, ref desc) = view else { - return None; + return (None, false); }; if resource[0] == BUFFER { - return None; + return (None, false); } let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; - let texture = crate::resource::texture_at(address, resource)? as usize; + let texture = match crate::resource::texture_lookup(address, resource) { + PlacedLookup::Ready(r) => r as usize, + PlacedLookup::Building => return (None, true), + PlacedLookup::Absent => return (None, false), + }; let desc = desc[..10].try_into().ok(); - Some(if unordered { + let made = if unordered { View::Unordered(texture, 0, desc) } else { View::Shader(texture, desc) - }) + }; + (Some(made), false) } /// A null view of the kind `view` is, for a slot whose view the host @@ -4950,6 +4973,108 @@ mod tests { drop(std::mem::ManuallyDrop::into_inner(memory)); } + /// A slot made over a placed view's texture keeps it when another + /// mirror finds no texture there because a thread is still making one: + /// it does not write a null view over the good one. + #[test] + fn a_placed_slot_keeps_its_view_while_another_is_made() { + use crate::resource::tests_support::{target, while_placed_building}; + let test = "descriptor::host::tests::a_placed_slot_keeps_its_view_while_another_is_made"; + let Some(_gpu) = crate::testgpu::device(test) else { + return; + }; + const KIB_64: u64 = 1 << 16; + let memory = + std::mem::ManuallyDrop::new(crate::resource::Memory::zeroed(KIB_64, KIB_64).unwrap()); + let address = memory.address(); + let drawn = target(16, 16, 28); + // SAFETY: a description is 56 bytes, 14 words. + let mut resource: [u32; 14] = unsafe { std::mem::transmute_copy(&drawn) }; + resource[12] = 0; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + let heap = crate::descriptor::TestHeap::views(4); + let host = crate::descriptor::heap(heap.0).host().expect("a host heap"); + let handle = crate::descriptor::heap(heap.0).start + 32; + crate::descriptor::create_placed_srv(std::ptr::null(), &resource, &view, handle); + let kept = |h: &HostHeap| { + h.kept.lock().unwrap_or_else(|e| e.into_inner())[1] + .as_ref() + .map(|t| t.as_raw() as usize) + }; + assert!(matches!( + host.mirror(1, handle, true), + Some(View::Shader(..)) + )); + let made = kept(host); + assert!(made.is_some(), "the slot views the placed texture"); + while_placed_building(address, &resource, || { + host.mirror(1, handle, true); + }); + assert_eq!(kept(host), made, "the slot kept its view"); + drop(heap); + crate::resource::memory_remapped(address as usize, KIB_64 as usize); + drop(std::mem::ManuallyDrop::into_inner(memory)); + } + + /// A slot made over a placed view's texture follows its memory when the + /// memory is unmapped: the next mirror finds no texture there, and no + /// thread making one, so the slot is made null. + #[test] + fn a_placed_slot_follows_its_memory_when_unmapped() { + use crate::resource::tests_support::target; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, + VirtualFree, + }; + let test = "descriptor::host::tests::a_placed_slot_follows_its_memory_when_unmapped"; + let Some(_gpu) = crate::testgpu::device(test) else { + return; + }; + const KIB_64: usize = 1 << 16; + // SAFETY: reserve and commit an OS-selected 64 KiB range. + let base = unsafe { + VirtualAlloc( + std::ptr::null(), + KIB_64, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + }; + assert!(!base.is_null()); + let address = base as u64; + let drawn = target(16, 16, 28); + // SAFETY: a description is 56 bytes, 14 words. + let mut resource: [u32; 14] = unsafe { std::mem::transmute_copy(&drawn) }; + resource[12] = 0; + let mut view = [0u32; 16]; + view[..6].copy_from_slice(&[28, 4, 0x1688, 0, 0, 1]); + (view[10], view[11]) = (address as u32, (address >> 32) as u32); + let heap = crate::descriptor::TestHeap::views(4); + let host = crate::descriptor::heap(heap.0).host().expect("a host heap"); + let handle = crate::descriptor::heap(heap.0).start + 32; + crate::descriptor::create_placed_srv(std::ptr::null(), &resource, &view, handle); + let kept = |h: &HostHeap| { + h.kept.lock().unwrap_or_else(|e| e.into_inner())[1] + .as_ref() + .map(|t| t.as_raw() as usize) + }; + assert!(matches!( + host.mirror(1, handle, true), + Some(View::Shader(..)) + )); + assert!(kept(host).is_some(), "the slot views the placed texture"); + // SAFETY: the range was committed above and nothing else uses it. + assert_ne!(unsafe { VirtualFree(base, KIB_64, MEM_DECOMMIT) }, 0); + crate::resource::memory_remapped(address as usize, KIB_64); + host.mirror(1, handle, true); + assert_eq!(kept(host), None, "the slot no longer shows unmapped memory"); + drop(heap); + // SAFETY: release the reservation once no view is placed in it. + assert_ne!(unsafe { VirtualFree(base, 0, MEM_RELEASE) }, 0); + } + /// An unordered access view of a texture the title placed itself is /// made, for a draw, over the resource made for that memory, as shader /// views are (it was null: its writes were lost); a shader view placed diff --git a/crates/xtp-gpu/src/device.rs b/crates/xtp-gpu/src/device.rs index 8cbc74f5..de8d9b86 100644 --- a/crates/xtp-gpu/src/device.rs +++ b/crates/xtp-gpu/src/device.rs @@ -582,6 +582,7 @@ pub(crate) fn log_frame() { line.push_str(&part); } tracing::info!("{line}"); + resource::log_placed_views(); } /// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the diff --git a/crates/xtp-gpu/src/host.rs b/crates/xtp-gpu/src/host.rs index a1fff8eb..41a10244 100644 --- a/crates/xtp-gpu/src/host.rs +++ b/crates/xtp-gpu/src/host.rs @@ -1371,6 +1371,7 @@ impl Host { /// Runs a title submission (the lists of one `ExecuteCommandLists`), /// counted for the frame-rate line once it has finished. pub(crate) fn submit(&self, runs: &[&HostList]) { + crate::resource::reap_placed_views(); #[cfg(feature = "diagnostics")] crate::passdump::submitted(runs); #[cfg(feature = "diagnostics")] diff --git a/crates/xtp-gpu/src/resource.rs b/crates/xtp-gpu/src/resource.rs index 106fd79e..0a9f6881 100644 --- a/crates/xtp-gpu/src/resource.rs +++ b/crates/xtp-gpu/src/resource.rs @@ -874,6 +874,9 @@ pub(crate) struct HostTexture { pub(crate) bytes: u64, /// Of them, what its stand-in format takes beyond the title's. extra: u64, + /// Which title creation path allocated this copy. Shared views do not + /// allocate another copy. + origin: TextureOrigin, /// Whether its memory is resident yet (its own, or its pool heap's): /// until then nothing hands it to the GPU ([`HostTexture::ready`]). residency: Arc, @@ -895,7 +898,13 @@ impl HostTexture { #[cfg(windows)] impl Drop for HostTexture { fn drop(&mut self) { - format::note_texture(false, self.bytes, self.extra, self.slot.is_some()); + format::note_texture( + false, + self.bytes, + self.extra, + self.slot.is_some(), + self.origin, + ); } } @@ -1126,7 +1135,12 @@ pub(crate) fn host_desc( /// creations are logged before and after the call with their size and the /// video memory budget, so a stall names its texture. #[cfg(windows)] -fn host_texture(desc: &ResourceDesc, state: u32, clear: Option<[u32; 5]>) -> Option { +fn host_texture( + desc: &ResourceDesc, + state: u32, + clear: Option<[u32; 5]>, + origin: TextureOrigin, +) -> Option { use windows::Win32::Graphics::Direct3D12::*; if desc.dimension == BUFFER { return None; @@ -1197,7 +1211,7 @@ fn host_texture(desc: &ResourceDesc, state: u32, clear: Option<[u32; 5]>) -> Opt if slot.is_some() { " pooled" } else { "" } ) }); - format::note_texture(true, bytes, extra, slot.is_some()); + format::note_texture(true, bytes, extra, slot.is_some(), origin); let state = crate::host::legal_state(&texture, crate::host::texture_state(state)); Some(HostTexture { texture, @@ -1210,6 +1224,7 @@ fn host_texture(desc: &ResourceDesc, state: u32, clear: Option<[u32; 5]>) -> Opt content: decode::revision().into(), bytes, extra, + origin, residency, slot, }) @@ -1516,6 +1531,16 @@ fn resource<'a>(this: This) -> &'a Resource { unsafe { &*this.cast::() } } +#[cfg(windows)] +#[derive(Clone, Copy)] +enum TextureOrigin { + Committed, + HeapOffset, + Address, + PlacedView, + External, +} + // The creation methods' own arguments, passed on, and how the resource is // made (for the alias log). #[allow(clippy::too_many_arguments)] @@ -1553,7 +1578,16 @@ fn hand_out_resource( // SAFETY: the title passes a whole clear value. unsafe { clear.cast::<[u32; 5]>().read_unaligned() } }); - (host_texture(&desc, state, clear).map(Arc::new), false) + let origin = match &backing { + Backing::Committed(_) => TextureOrigin::Committed, + Backing::Placed { .. } => TextureOrigin::HeapOffset, + Backing::Address(_) if how == PLACED_VIEW => TextureOrigin::PlacedView, + Backing::Address(_) => TextureOrigin::Address, + }; + ( + host_texture(&desc, state, clear, origin).map(Arc::new), + false, + ) } }; let resource = Box::new(Resource { @@ -1895,13 +1929,15 @@ static PLACED_TEXTURES: std::sync::Mutex = type PlacedTextures = std::collections::BTreeMap<(u64, [u32; 14]), PlacedView>; /// A placed view's resource, the alias count it was last matched at and -/// the bytes it covers. +/// the bytes it covers. New entries can be invalidated while being made. #[cfg(windows)] #[derive(Debug, Clone, Copy)] struct PlacedView { - resource: usize, + resource: Option, changes: u64, len: u64, + /// Nonzero while a thread is making a copy outside the map lock. + building: u64, } /// The most bytes a placed view's texture has covered: how far before a @@ -1914,6 +1950,13 @@ static LONGEST_PLACED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU #[cfg(windows)] const PLACED_VIEW: &str = "placed view"; +#[cfg(windows)] +static NEXT_PLACEMENT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); +#[cfg(windows)] +static UNMAPPED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +#[cfg(windows)] +static INVALIDATED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// Resources of placed views no longer in [`PLACED_TEXTURES`], with when /// they left it: released [`GRACE`] later, as a caller of `texture_at` may /// still be using one it was just given (lists keep only their address, and @@ -1929,18 +1972,16 @@ const GRACE: std::time::Duration = std::time::Duration::from_secs(2); /// those waiting for longer. #[cfg(windows)] fn release_later(resources: Vec) { + let mut waiting = RELEASED.lock().unwrap_or_else(|e| e.into_inner()); let now = std::time::Instant::now(); - RELEASED - .lock() - .unwrap_or_else(|e| e.into_inner()) - .extend(resources.into_iter().map(|r| (now, r))); - release_waiting(GRACE); + waiting.extend(resources.into_iter().map(|r| (now, r))); + drop(waiting); + release_waiting(now, GRACE); } /// Releases the resources that have waited `grace` or more. #[cfg(windows)] -fn release_waiting(grace: std::time::Duration) { - let now = std::time::Instant::now(); +fn release_waiting(now: std::time::Instant, grace: std::time::Duration) { let mut waiting = RELEASED.lock().unwrap_or_else(|e| e.into_inner()); let due = waiting .iter() @@ -1953,6 +1994,29 @@ fn release_waiting(grace: std::time::Duration) { } } +/// Give back expired placed views even if streaming stops remapping memory. +#[cfg(windows)] +pub(crate) fn reap_placed_views() { + release_waiting(std::time::Instant::now(), GRACE); +} + +#[cfg(windows)] +pub(crate) fn log_placed_views() { + use std::sync::atomic::Ordering::Relaxed; + let cached = placed_textures().len(); + let retiring = RELEASED.lock().unwrap_or_else(|e| e.into_inner()).len(); + let (same_address, shared) = alias::counts(); + tracing::info!( + cached, + retiring, + unmapped = UNMAPPED_VIEWS.load(Relaxed), + invalidated = INVALIDATED_VIEWS.load(Relaxed), + same_address, + shared, + "placed texture views" + ); +} + #[cfg(windows)] fn placed_textures() -> std::sync::MutexGuard<'static, PlacedTextures> { PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()) @@ -1965,10 +2029,13 @@ fn placed_textures() -> std::sync::MutexGuard<'static, PlacedTextures> { /// run). #[cfg(windows)] pub(crate) fn memory_remapped(at: usize, len: usize) { + if len == 0 { + return; + } let (start, end) = (at as u64, (at as u64).saturating_add(len as u64)); - let from = start.saturating_sub(LONGEST_PLACED.load(std::sync::atomic::Ordering::Relaxed)); let gone: Vec = { let mut map = placed_textures(); + let from = start.saturating_sub(LONGEST_PLACED.load(std::sync::atomic::Ordering::Relaxed)); let keys: Vec<_> = map .range((from, [0; 14])..(end, [0; 14])) .filter(|((address, _), view)| address.saturating_add(view.len.max(1)) > start) @@ -1976,10 +2043,11 @@ pub(crate) fn memory_remapped(at: usize, len: usize) { .collect(); keys.iter() .filter_map(|k| map.remove(k)) - .map(|view| view.resource) + .filter_map(|view| view.resource) .collect() }; if !gone.is_empty() { + INVALIDATED_VIEWS.fetch_add(gone.len() as u64, std::sync::atomic::Ordering::Relaxed); tracing::debug!( at = format_args!("{at:#x}"), len, @@ -2002,14 +2070,16 @@ fn forget_shared_views(address: u64) { let keys: Vec<_> = map .range((address, [0; 14])..=(address, [u32::MAX; 14])) .filter(|(_, view)| { - let r = resource(view.resource as This); - r.shared && alias::current(address, &r.desc).is_none() + view.resource.is_some_and(|made| { + let r = resource(made as This); + r.shared && alias::current(address, &r.desc).is_none() + }) }) .map(|(k, _)| *k) .collect(); keys.iter() .filter_map(|k| map.remove(k)) - .map(|view| view.resource) + .filter_map(|view| view.resource) .collect() }; if !gone.is_empty() { @@ -2035,75 +2105,156 @@ fn forget_shared_views(address: u64) { /// again). #[cfg(windows)] pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { + texture_lookup(address, desc).ready() +} + +/// What [`texture_lookup`] found for a placed view. +#[cfg(windows)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PlacedLookup { + /// The resource made for that memory, its host copy resident. + Ready(This), + /// None yet: another thread is still making the first one. + Building, + /// None: no mapped page, a failed creation, or a host copy not + /// resident yet. + Absent, +} + +#[cfg(windows)] +impl PlacedLookup { + pub(crate) fn ready(self) -> Option { + match self { + PlacedLookup::Ready(r) => Some(r), + _ => None, + } + } +} + +/// [`texture_at`], telling a view another thread is still making from one +/// there is none for. +#[cfg(windows)] +pub(crate) fn texture_lookup(address: u64, desc: &[u32; 14]) -> PlacedLookup { + texture_lookup_with(address, desc, |d| { + let mut out = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + (at_address(address, d, std::ptr::null(), iid, &mut out, PLACED_VIEW) == S_OK) + .then_some(out) + }) +} + +#[cfg(all(test, windows))] +fn texture_at_with( + address: u64, + desc: &[u32; 14], + make: impl FnOnce(ResourceDesc) -> Option, +) -> Option { + texture_lookup_with(address, desc, make).ready() +} + +#[cfg(windows)] +fn texture_lookup_with( + address: u64, + desc: &[u32; 14], + make: impl FnOnce(ResourceDesc) -> Option, +) -> PlacedLookup { + use std::sync::atomic::Ordering::Relaxed; + let found = |r: Option| r.map_or(PlacedLookup::Absent, PlacedLookup::Ready); + if address == 0 { + return PlacedLookup::Absent; + } let desc = canonical_resource_desc(*desc); // SAFETY: 56 bytes in the description's layout. let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; if d.dimension == BUFFER { - return None; + return PlacedLookup::Absent; } let key = (address, desc); - let usable = |r: This| ready_host(r).is_some().then_some(r); + let usable = |r: usize| { + let r = r as This; + ready_host(r).is_some().then_some(r) + }; let changes = alias::changes(); - // The resource made so far, if it is still the one to use. - let before = { + let (ticket, len) = { let mut map = placed_textures(); - match map.get_mut(&key) { - Some(view) => { - let made = view.resource as This; - let current = resource(made).host.clone(); + if let Some(view) = map.get_mut(&key) { + if view.building != 0 { + return view + .resource + .and_then(usable) + .map_or(PlacedLookup::Building, PlacedLookup::Ready); + } + if let Some(made) = view.resource { let stale = view.changes != changes - && alias::current(address, &d) - .is_some_and(|now| !current.as_ref().is_some_and(|c| Arc::ptr_eq(c, &now))); - view.changes = changes; + && alias::current(address, &d).is_some_and(|now| { + !resource(made as This) + .host + .as_ref() + .is_some_and(|c| Arc::ptr_eq(c, &now)) + }); if !stale { - return usable(made); + view.changes = changes; + return found(usable(made)); } - Some(made) } - None => None, } + // Publish the range before dropping the lock. A remap can now + // cancel this creation even while the driver is allocating it. + let len = footprint(&d).map_or(1, |info| info.size); + LONGEST_PLACED.fetch_max(len, Relaxed); + let ticket = NEXT_PLACEMENT.fetch_add(1, Relaxed); + let view = map.entry(key).or_insert(PlacedView { + resource: None, + changes, + len, + building: 0, + }); + view.building = ticket; + (ticket, len) + }; + // The indexed upload pass already defers views of unmapped pages. + // Table draws and later descriptor checks also reach this path. + // Keep GPU-writeable copies and aliases of live GPU sources eligible. + let out = if host_flags(d.flags) & alias::WRITABLE != 0 + || alias::has_sources(address) + || crate::texture::any_committed(address as *const u8, len as usize) + { + make(d) + } else { + UNMAPPED_VIEWS.fetch_add(1, Relaxed); + None }; - let mut out = std::ptr::null(); - let iid = &RESOURCE_IIDS[0]; - let made = at_address(address, d, std::ptr::null(), iid, &mut out, PLACED_VIEW) == S_OK; let mut map = placed_textures(); - if !made { - // `before` may be released by now (its memory remapped while this - // one was made): only what the map holds now is handed out. - return map.get(&key).and_then(|view| usable(view.resource as This)); - } - let len = footprint(&d).map_or(0, |info| info.size); - LONGEST_PLACED.fetch_max(len, std::sync::atomic::Ordering::Relaxed); - match map.get_mut(&key) { - // Another thread made or replaced it meanwhile: theirs stays, ours - // was never handed out. - Some(view) if Some(view.resource as This) != before => { - let theirs = usable(view.resource as This); - drop(map); + let Some(view) = map.get_mut(&key).filter(|v| v.building == ticket) else { + let current = match map.get(&key) { + Some(v) => match v.resource.and_then(usable) { + Some(r) => PlacedLookup::Ready(r), + None if v.building != 0 => PlacedLookup::Building, + None => PlacedLookup::Absent, + }, + None => PlacedLookup::Absent, + }; + drop(map); + if let Some(out) = out { resource_release(out); - theirs - } - Some(view) => { - let replaced = std::mem::replace(&mut view.resource, out as usize); - view.changes = changes; - view.len = len; - let ours = usable(out); - drop(map); - release_later(vec![replaced]); - ours - } - None => { - map.insert( - key, - PlacedView { - resource: out as usize, - changes, - len, - }, - ); - usable(out) } - } + return current; + }; + view.building = 0; + // Recorded even when the creation failed, as before a creation was made + // outside the lock: a failed rebuild is not tried again on every lookup + // (a slow creation on the title's thread), only at the next change. + view.changes = changes; + let replaced = out.and_then(|out| view.resource.replace(out as usize)); + let current = view.resource.and_then(usable); + if view.resource.is_none() { + map.remove(&key); + } + drop(map); + if let Some(replaced) = replaced { + release_later(vec![replaced]); + } + found(current) } /// The buffer a GPU-written texture's texels go through into a texture of @@ -2890,7 +3041,8 @@ fn own_texture( texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32, ) -> HostTexture { - format::note_texture(true, 0, 0, false); + let origin = TextureOrigin::External; + format::note_texture(true, 0, 0, false, origin); HostTexture { texture, state: state.into(), @@ -2900,6 +3052,7 @@ fn own_texture( content: decode::revision().into(), bytes: 0, extra: 0, + origin, residency: Arc::new(residency::Residency::resident()), slot: None, } @@ -3326,6 +3479,29 @@ pub(crate) mod tests_support { use super::*; use windows::Win32::Graphics::Direct3D12::*; + /// Runs `f` while the placed view of `desc` at `address` looks as if + /// another thread were still making its first copy: [`texture_at`] + /// finds none there. The entry as it was comes back after. + pub(crate) fn while_placed_building(address: u64, desc: &[u32; 14], f: impl FnOnce()) { + let key = (address, canonical_resource_desc(*desc)); + let saved = placed_textures().remove(&key); + placed_textures().insert( + key, + PlacedView { + resource: None, + changes: alias::changes(), + len: 1, + building: u64::MAX, + }, + ); + f(); + let mut map = placed_textures(); + map.remove(&key); + if let Some(saved) = saved { + map.insert(key, saved); + } + } + /// A `width` x `height` depth texture in `format` that the title also /// asks unordered access for (it gets a colour twin). pub(crate) fn depth_unordered(width: u64, height: u32, format: u32) -> ResourceDesc { @@ -4280,7 +4456,7 @@ mod tests { return view; } let key = (address, canonical_resource_desc(*desc)); - let view = placed_textures()[&key].resource as This; + let view = placed_textures()[&key].resource.expect("a published view") as This; resident(view); texture_at(address, desc).unwrap() } @@ -4664,7 +4840,13 @@ mod tests { // SAFETY: this test owns the view and has not used it yet. WARP normally // keeps format 67. Give it the same host copy used on RTX hardware. let view = unsafe { &mut *stand_in.cast_mut().cast::() }; - view.host = host_texture(&texture(16, 16, RGBA16F, 1), 0, None).map(Arc::new); + view.host = host_texture( + &texture(16, 16, RGBA16F, 1), + 0, + None, + TextureOrigin::Address, + ) + .map(Arc::new); resident(stand_in); let to = host_copy(stand_in).unwrap(); let elsewhere = fresh_memory(&mut held); @@ -4807,6 +4989,71 @@ mod tests { release_views_at(address); } + #[cfg(windows)] + #[test] + fn a_read_only_placed_view_waits_for_its_first_mapped_page() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + + let test = "resource::tests::a_read_only_placed_view_waits_for_its_first_mapped_page"; + let Some(_gpu) = crate::testgpu::device(test) else { + return; + }; + let desc = texture(256, 256, 28, 1); + let len = footprint(&desc).unwrap().size as usize; + let view = words(&desc, [0, 0]); + // SAFETY: reserve an OS-selected range and commit one page inside it. + let base = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE, PAGE_READWRITE) }; + assert!(!base.is_null() && len > 4096); + let address = base as u64; + assert!(texture_at_with(address, &view, |_| panic!("no host allocation")).is_none()); + assert!(!placed_textures().contains_key(&(address, view))); + // SAFETY: the second page is within the reservation. + let page = unsafe { VirtualAlloc(base.add(4096), 4096, MEM_COMMIT, PAGE_READWRITE) }; + assert!(!page.is_null()); + assert!(texture_at(address, &view).is_some()); + memory_remapped(address as usize, len); + release_views_at(address); + // SAFETY: release the original reservation once the view is gone. + assert_ne!(unsafe { VirtualFree(base, 0, MEM_RELEASE) }, 0); + } + + #[cfg(windows)] + #[test] + fn a_remap_cancels_a_placed_view_still_being_created() { + let test = "resource::tests::a_remap_cancels_a_placed_view_still_being_created"; + let Some(_gpu) = crate::testgpu::device(test) else { + return; + }; + let mut held = Vec::new(); + let memory = fresh_memory(&mut held); + let address = memory.address(); + let view = words(&texture(16, 16, 28, 1), [0, 0]); + let mut old = None; + let stale = texture_at_with(address, &view, |d| { + assert!(texture_at_with(address, &view, |_| panic!("already building")).is_none()); + let mut out = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + assert_eq!( + at_address(address, d, std::ptr::null(), iid, &mut out, PLACED_VIEW), + S_OK + ); + old = resource(out).host.clone(); + memory_remapped(address as usize, KIB_64 as usize); + Some(out) + }); + assert!(stale.is_none()); + assert_eq!( + Arc::strong_count(&old.unwrap()), + 1, + "unpublished copy released" + ); + assert!(texture_at(address, &view).is_some()); + memory_remapped(address as usize, KIB_64 as usize); + release_views_at(address); + } + /// A remapped range that starts inside a placed view's texture takes it /// too (it shows that memory), not only those starting in the range. #[cfg(windows)] diff --git a/crates/xtp-gpu/src/resource/alias.rs b/crates/xtp-gpu/src/resource/alias.rs index 3216136a..3a0b0312 100644 --- a/crates/xtp-gpu/src/resource/alias.rs +++ b/crates/xtp-gpu/src/resource/alias.rs @@ -212,11 +212,21 @@ pub(super) fn written_beside( }) } +static SEEN: AtomicU64 = AtomicU64::new(0); +static SHARED: AtomicU64 = AtomicU64::new(0); + +pub(super) fn counts() -> (u64, u64) { + let shared = SHARED.load(Ordering::Relaxed); + (SEEN.load(Ordering::Relaxed), shared) +} + /// Logs the first aliases met over a GPU-written texture (then every /// power of two), shared or not and why. fn note(address: u64, want: &ResourceDesc, how: &str, with: Option, why: &str, on: bool) { - static SEEN: AtomicU64 = AtomicU64::new(0); let n = SEEN.fetch_add(1, Ordering::Relaxed) + 1; + if on && with.is_some() { + SHARED.fetch_add(1, Ordering::Relaxed); + } if n > 64 && !n.is_power_of_two() { return; } @@ -299,7 +309,6 @@ pub(super) fn unregister(address: u64, resource: usize) { } } -#[cfg(test)] pub(super) fn has_sources(address: u64) -> bool { sources().contains_key(&address) } diff --git a/crates/xtp-gpu/src/resource/format.rs b/crates/xtp-gpu/src/resource/format.rs index 1febca93..4318c236 100644 --- a/crates/xtp-gpu/src/resource/format.rs +++ b/crates/xtp-gpu/src/resource/format.rs @@ -872,14 +872,28 @@ pub(crate) fn note_stand_in(title: u32, host: u32) { static LIVE: [std::sync::atomic::AtomicI64; 5] = [const { std::sync::atomic::AtomicI64::new(0) }; 5]; +#[cfg(windows)] +static BY_ORIGIN: [[std::sync::atomic::AtomicI64; 2]; 5] = + [const { [const { std::sync::atomic::AtomicI64::new(0) }; 2] }; 5]; + /// Counts a host texture of `bytes` made (`alive`) or freed: `extra` of /// them for its stand-in format, `pooled` if placed in the texture pool. -pub(crate) fn note_texture(alive: bool, bytes: u64, extra: u64, pooled: bool) { +#[cfg(windows)] +pub(super) fn note_texture( + alive: bool, + bytes: u64, + extra: u64, + pooled: bool, + origin: super::TextureOrigin, +) { use std::sync::atomic::Ordering::Relaxed; let sign = if alive { 1 } else { -1 }; LIVE[0].fetch_add(sign, Relaxed); LIVE[1].fetch_add(sign * bytes as i64, Relaxed); LIVE[2].fetch_add(sign * extra as i64, Relaxed); + let [count, size] = &BY_ORIGIN[origin as usize]; + count.fetch_add(sign, Relaxed); + size.fetch_add(sign * bytes as i64, Relaxed); if pooled { LIVE[3].fetch_add(sign, Relaxed); LIVE[4].fetch_add(sign * bytes as i64, Relaxed); @@ -918,6 +932,17 @@ pub(crate) fn report() -> Option { (bytes - pooled_bytes) >> 20, extra >> 20 ); + #[cfg(windows)] + let pool = { + let [committed, offset, address, view, external] = + BY_ORIGIN.each_ref().map(|[count, size]| { + format!("{} / {} MiB", count.load(Relaxed), size.load(Relaxed) >> 20) + }); + format!( + "{pool}; by title creation: committed {committed}, heap offset {offset}, \ + address {address}, placed view {view}, external {external}" + ) + }; let stood_in: Vec = counts .stood_in .iter() diff --git a/docs/analysis/vram.md b/docs/analysis/vram.md index d79058f8..ae6ef789 100644 --- a/docs/analysis/vram.md +++ b/docs/analysis/vram.md @@ -124,6 +124,12 @@ far ...`. Stand-ins (67 → RGBA16F, 85/86/115 → RGBA8, 116/117 → RGBA16F, 189 → RGBA16_SNORM, 190 → RG8) take twice the title's bytes: the `+S MiB` is that half. +The frame report gives live count and MiB by the title creation path that +allocated each copy. The placed-view line gives current cached and retiring +views, cumulative deferrals for unmapped memory and remap invalidations, +and how many same-address lookups found a GPU-written source or shared it. +Descriptor and command-list references can outlive a cache entry. + ## 3. Measurements ### 3.1 Micro-benchmark (WARP)