diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 5aac724..24d0ac3 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -140,6 +140,42 @@ pub(crate) fn levels_changed(start: u64) { RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start); } +/// [`levels_changed`] once the submissions begun so far (that of the list +/// whose step calls this among them) have run. +pub(crate) fn levels_changed_after(start: u64) { + let after = crate::host::submissions().0; + RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()).push((after, start)); +} + +static RESHOWN_AFTER: Mutex> = Mutex::new(Vec::new()); + +/// Slots that show a placed texture from another level than the title's view +/// in them says now, and are made from that view when the upload it needs +/// has run ([`HostHeap::texture_slot_flip`]). +struct Flip { + /// The submission to wait for. + after: u64, + /// The heap (its address), the slot, where its record is and which + /// record it was. + heap: usize, + index: u32, + handle: u64, + key: u64, +} + +static FLIPS: Mutex> = Mutex::new(Vec::new()); + +/// Since the start: slots made from their new view after its upload had run, +/// and those the title had written again by then. +pub(crate) static FLIPPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The key of the record at `handle`, a view's descriptor slot; 0: none. +fn record_key(handle: u64) -> u64 { + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + if tag == VIEW_TAG { u64::from(generation) << 32 | u64::from(i) } else { 0 } +} + /// Levels on demand (`crate::tiles`): where the placed textures start /// whose last upload left a held level without tiles (the card had no /// room, or no heap could be had), and when (`crate::host::moment`). A @@ -210,8 +246,9 @@ pub(crate) struct Spans { rule: Rule, by_start: std::collections::BTreeMap)>, by_slot: std::collections::HashMap, - /// The level each slot's view starts at ([`Spans::shows`]). - first: std::collections::HashMap, + /// The level each slot's view starts at, and where what it is read from + /// ends ([`Spans::shows`]). + first: std::collections::HashMap, /// The bytes a placed texture takes, by resource description: worked /// out once for each (a title writes the views of a few thousand /// descriptions, thousands of times a frame). @@ -329,14 +366,20 @@ impl Spans { stale } - /// The view in slot `index` starts at level `first` of its texture. - fn shows(&mut self, index: u32, first: u32) { - self.first.insert(index, first); + /// The view in slot `index` starts at level `first` of its texture; the + /// memory of that and the smaller levels ends at `end`. + fn shows(&mut self, index: u32, first: u32, end: u64) { + self.first.insert(index, (first, end)); + } + + /// Whether slot `index`'s view is read from memory at or past `start`. + fn reaches(&self, index: u32, start: u64) -> bool { + self.first.get(&index).is_none_or(|&(_, end)| end > start) } /// The lowest level a view of the texture at `start` starts at. fn first_viewed(&self, start: u64) -> Option { - self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied() + self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).map(|&(first, _)| first).min() } /// The first span that starts inside `[start, end)` past the first @@ -370,6 +413,7 @@ impl Spans { .iter() .filter_map(|at| self.by_start.get(at)) .flat_map(|span| span.1.iter().copied()) + .filter(|&slot| self.reaches(slot, start)) .collect() } @@ -391,6 +435,7 @@ impl Spans { .into_iter() .chain(self.by_start.range(start..end).map(|(_, span)| span)) .flat_map(|span| span.1.iter().copied()) + .filter(|&slot| self.reaches(slot, start)) .collect() } } @@ -1525,6 +1570,19 @@ impl HostHeap { if self.sampler { return 0; } + { + let mut after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()); + if !after.is_empty() { + let finished = crate::host::submissions().1; + let mut now = RESHOWN.lock().unwrap_or_else(|e| e.into_inner()); + after.retain(|&(at, start)| { + if at <= finished { + now.push(start); + } + at > finished + }); + } + } let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner())); if starts.is_empty() { return 0; @@ -1594,6 +1652,75 @@ impl HostHeap { true } + /// Whether host slot `index` shows the placed texture the title's record + /// at `handle` views, by an earlier view of it. + pub(crate) fn texture_slot_shows_other(&self, index: u32, handle: u64) -> bool { + let key = record_key(handle); + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some(&shown) = made.get(index as usize) else { + return false; + }; + if key == 0 || shown == 0 || shown == key { + return false; + } + let view = |key: u64| view_at(key as u32, (key >> 32) as u32); + matches!((view(shown), view(key)), (Some(a), Some(b)) if same_placed_texture(&a, &b)) + } + + /// Slot `index` is made from the record at `handle` (what it is now) + /// when `list`, which holds the upload of what that view shows, has run: + /// until then it shows what it showed. (Made at once, the frames on the + /// card read the new view before its levels were filled.) + pub(crate) fn texture_slot_flip(&self, list: &crate::host::HostList, index: u32, handle: u64) { + let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + list.defer_host(move || { + let after = crate::host::submissions().0; + let flip = Flip { after, heap, index, handle, key }; + FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); + }); + } + + /// Makes the slots whose new view's upload has run + /// ([`HostHeap::texture_slot_flip`]); returns how many. + pub(crate) fn texture_slots_flip(&self) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let finished = crate::host::submissions().1; + let ready: Vec = { + let mut flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + if flips.is_empty() { + return 0; + } + let own = std::ptr::from_ref(self) as usize; + let (ready, wait): (Vec, Vec) = + flips.drain(..).partition(|f| f.after <= finished && f.heap == own); + *flips = wait; + ready + }; + let mut flipped = 0; + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + for f in ready { + let Some(shown) = made.get_mut(f.index as usize) else { + continue; + }; + if *shown == f.key { + continue; + } + // Written again since, or made null: that write is in the queue. + let view = view_at(f.key as u32, (f.key >> 32) as u32); + let (true, true, Some(view)) = (f.key != 0 && record_key(f.handle) == f.key, *shown != 0, view) else { + FLIPPED[1].fetch_add(1, Relaxed); + continue; + }; + if let Some(kept) = make(&view, self.cpu(f.index)) { + *shown = f.key; + self.keep(f.index, kept); + flipped += 1; + } + } + FLIPPED[0].fetch_add(flipped as u64, Relaxed); + flipped + } + /// The memory of the texture title slot `index` views is there (again): /// see [`HostHeap::texture_slot_gone`]. pub(crate) fn texture_slot_here(&self, index: u32) { @@ -1761,23 +1888,25 @@ impl HostHeap { // (And the level the view starts at: word 4 of a texture // view's description, after format, dimension, mapping // and a pad.) - Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4])) + let at = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let held = crate::resource::placed_bytes_from(resource, crate::resource::first_mip(desc)); + Some((resource, at, desc[4], held.map_or(u64::MAX, |held| at.saturating_add(held)))) } _ => None, }; let stale = { use std::sync::atomic::Ordering::Relaxed; let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); - let span = placed_view.and_then(|(resource, start, first)| { - Some((start, start.saturating_add(placed.bytes(resource)?), first)) + let span = placed_view.and_then(|(resource, start, first, held)| { + Some((start, start.saturating_add(placed.bytes(resource)?), first, held)) }); match span { - Some((start, end, first)) => { + Some((start, end, first, held)) => { SPANNED[0].fetch_min(start, Relaxed); SPANNED[1].fetch_max(end, Relaxed); placed.rule = stale_rule(); let stale = placed.note(index, start, end, !seen); - placed.shows(index, first); + placed.shows(index, first, held); stale } None => { @@ -2786,7 +2915,8 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } View::Shader(resource, desc) => { let resource = *resource as crate::object::This; - if let Some(texture) = crate::resource::host_resource(resource) { + if let Some(copy) = crate::resource::host_copy(resource) { + let texture = ©.texture; // The title's views of textures with a stencil plane, as it // describes them (format, dimension, component mapping, a // pad, then first level, levels, plane): each distinct one @@ -2841,6 +2971,11 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { }; crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels)); } + if copy.base > 0 + && let Some(desc) = &mut desc + { + from_base(desc, copy.base); + } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateShaderResourceView( @@ -2975,6 +3110,23 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } } +/// The view `desc` of a texture, of a host copy of its levels from `base` +/// on (`crate::resource::held_only`). What it shows of larger ones, if any, +/// is left out. +fn from_base(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, base: u32) { + if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D { + return; + } + // SAFETY: the member its dimension says. + let t = unsafe { &mut desc.Anonymous.Texture2D }; + let lost = base.saturating_sub(t.MostDetailedMip); + t.MostDetailedMip = t.MostDetailedMip.saturating_sub(base); + if t.MipLevels != u32::MAX { + t.MipLevels = t.MipLevels.saturating_sub(lost).max(1); + } + t.ResourceMinLODClamp = (t.ResourceMinLODClamp - base as f32).max(0.0); +} + /// Writes of a slot with another view of the placed texture it showed, /// since the start: the slot kept showing the old view. pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -2993,7 +3145,10 @@ fn keep_views() -> bool { fn same_placed_texture(a: &View, b: &View) -> bool { match (a, b) { (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => { - resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12] + // (Words 1 and 13 are the filler of the description's layout, not + // part of what a texture is: `crate::resource::texture_at`.) + let same = |from: usize, to: usize| resource[from..to] == other[from..to]; + resource[0] != 1 && resource[0] == other[0] && same(2, 13) && desc[10..12] == other_desc[10..12] } _ => false, } @@ -3011,6 +3166,7 @@ pub(crate) fn placed_texture(view: &View) -> Option { } let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let texture = crate::resource::texture_at(address, resource)?; + crate::resource::want_level(texture, crate::resource::first_mip(desc)); Some(View::Shader(texture as usize, desc[..10].try_into().ok())) } @@ -3186,6 +3342,40 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// A view of a host copy that begins at a later level shows the same + /// levels of it. + #[test] + fn views_count_from_the_first_level_of_the_host_copy() { + let view = |first, levels, clamp| { + let mut desc = srv_desc(&[98, 4, 5768, 0, first, levels, 0, 0, 0, 0]); + desc.Anonymous.Texture2D.ResourceMinLODClamp = clamp; + from_base(&mut desc, 3); + // SAFETY: the member its dimension says. + let t = unsafe { desc.Anonymous.Texture2D }; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) + }; + assert_eq!(view(3, 4, 0.0), (0, 4, 0.0)); + assert_eq!(view(5, u32::MAX, 5.5), (2, u32::MAX, 2.5)); + // (Two levels the copy has not.) + assert_eq!(view(1, 4, 0.0), (0, 2, 0.0)); + } + + /// Memory past the levels a slot's view shows is not its texture's. + #[test] + fn a_view_of_smaller_levels_is_not_told_of_memory_past_them() { + let mut spans = Spans::default(); + spans.note(1, 0x10000, 0x50000, true); + spans.shows(1, 3, 0x12000); + spans.note(2, 0x10000, 0x50000, true); + spans.shows(2, 0, 0x50000); + assert_eq!(spans.slots_holding(0x11000, 0x11800), vec![1, 2]); + assert_eq!(spans.slots_holding(0x20000, 0x21000), vec![2]); + assert_eq!(spans.slots_in(0x20000, 0x21000), vec![2]); + spans.forget(2); + assert!(spans.slots_in(0x20000, 0x21000).is_empty()); + assert_eq!(spans.slots_in(0x0, 0x10001), vec![1]); + } + /// A texture filled with less than was mapped is looked at again, but /// not for ever: memory that is shown and cannot be read ends it, and a /// filling that got everything starts the count anew. @@ -3235,9 +3425,9 @@ mod tests { // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1, // and the next one 0x6000 after it (run 188). spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true); - spans.shows(1, 3); + spans.shows(1, 3, u64::MAX); spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true); - spans.shows(2, 1); + spans.shows(2, 1, u64::MAX); spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true); assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000)); assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..e7a474a 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -95,6 +95,26 @@ fn early_budgets() -> (u64, u64) { }) } +/// Whether a draw of the title's bake finds the textures it picks by index +/// as title memory has them at that moment (`VICTORY_BAKE_EXACT=0`: as the +/// pass leaves them, as before). The pass looks at a slot whose memory was +/// written or mapped a frame or two later, by when the rest of it has +/// landed, and at one uploaded whole a few frames later again, for a title +/// that fills memory unnoticed: a bake in between took the bytes from before +/// (another texture's), and what it bakes stays: coloured specks all over +/// the waitress's face for the whole diner scene (run n01), none in other +/// runs. So the pass ahead of a bake takes those slots too, and its uploads +/// wait for title memory that is being remapped (`crate::texture` `BAKING`). +fn bake_exact() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BAKE_EXACT").is_none_or(|v| v != "0")) +} + +/// Frames ahead the pass before a bake takes slots from that are due only +/// then ([`bake_exact`]): those of notices (1 and 2), and the first looks +/// again ([`RECHECK_FRAMES`]). +const BAKE_AHEAD: u64 = 12; + /// The pixel shaders of the title's decoration bake (the title: /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the /// frame listings print it. They draw into a 256x256 corner of 2048x2048 @@ -601,6 +621,7 @@ fn heap_recheck() -> bool { } /// Times a placed texture's slot was passed over because its memory is not /// mapped. +pub(crate) static HEAP_TEXTURES_SAME: AtomicU64 = AtomicU64::new(0); pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0); /// Slots the pass found up to date already: their texture is uploaded by /// the draws that read it through a table (it has a staging buffer). @@ -1820,7 +1841,9 @@ impl State { } let began = std::time::Instant::now(); PASS_BUDGET.set(Some(budget)); + crate::texture::BAKING.set(bake && bake_exact()); self.heap_textures(list, heap, host); + crate::texture::BAKING.set(false); PASS_BUDGET.set(None); if bake { BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); @@ -1970,15 +1993,23 @@ impl State { // wrote since the last pass are due again. host.texture_slots_remapped(frame); host.texture_slots_short(frame); - // Levels on demand: the slots of textures whose first level with - // memory changed since the last pass are made again from it. + // The slots of textures whose first level with memory (levels on + // demand), or whose host copy for one with more levels, changed since + // the last pass are made again from it; those whose new view's upload + // has run are made from that. host.texture_views_remade(); + host.texture_slots_flip(); // And with room, the textures whose upload left a held level // without the card's memory are uploaded again. if room { host.texture_slots_waiting(frame); } - let (due, census) = host.texture_slots_due(frame, 4096); + let baking = crate::texture::BAKING.get(); + let (due, census) = if baking { + host.texture_slots_due(frame + BAKE_AHEAD, 1 << 16) + } else { + host.texture_slots_due(frame, 4096) + }; HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { count.store(now, Ordering::Relaxed); @@ -2068,7 +2099,16 @@ impl State { } let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed); if n < 200 || n.is_multiple_of(1000) { + // Whether its pages are the title's at other addresses + // too: what is written there is told of there alone. + let elsewhere = crate::inplace::shown_elsewhere(at as usize & !0xffff, (at + len) as usize); + let first = heap.handle(index).and_then(crate::descriptor::view).map_or(0, |view| match view { + View::Placed(false, _, desc) => crate::resource::first_mip(&desc), + _ => 0, + }); tracing::warn!( + first_level = first, + blocks_shown_elsewhere = elsewhere.len(), slot = index, address = format_args!("{at:#x}"), bytes = len, @@ -2082,7 +2122,8 @@ impl State { let mut partly = None; if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; - let len = crate::resource::placed_bytes(&resource).unwrap_or(1); + let first = crate::resource::first_mip(&desc); + let len = crate::resource::placed_bytes_from(&resource, first).unwrap_or(1); let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); if mapped == 0 { HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); @@ -2155,7 +2196,15 @@ impl State { ); } } - let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); + // A slot that shows the texture by an earlier view of it (one + // from another level) goes on doing so until the upload of what + // the new one shows has run. + let shows_other = !baking + && crate::resource::held_only() + && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle)); + let view = heap.handle(index).and_then(|handle| { + if shows_other { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } + }); let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); let resource = match placed.as_ref().or(view.as_ref()) { Some(&View::Shader(resource, _)) => resource as This, @@ -2174,9 +2223,34 @@ impl State { // through a table: they upload it, and check it at every // submission that samples it. let tabled = crate::texture::is_staged(resource); + // The host copy holds these very bytes: nothing to upload. + let first = match (&placed, &view) { + (Some(_), Some(View::Placed(_, _, desc))) => crate::resource::first_mip(desc), + _ => 0, + }; + let same = !tabled && crate::texture::unchanged(resource, first); + if same { + HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); + if shows_other && let Some(handle) = heap.handle(index) { + let _ = host.mirror(index, handle, true); + } + let again = partly.map(|mapped| (frame + 1, mapped)); + let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; + match memory { + Some((at, len)) => { + let print = crate::texture::fingerprint(at, len); + host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame); + } + None => host.texture_slot_done(index, write, again), + } + continue; + } if let Some(view) = &view { readable(list, sampled.kind, view); } + if shows_other && let Some(handle) = heap.handle(index) { + host.texture_slot_flip(list, index, handle); + } // A texture view the host refuses removes the device: name it. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !GONE.load(Ordering::Relaxed) @@ -3529,7 +3603,12 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { && let Some(t) = crate::resource::host_resource(*resource as This) && crate::texture::title_written(t) { - crate::texture::upload(list, *resource as This, t); + // Of a texture the title placed, the levels the view shows. + let first = match (&placed, view) { + (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc), + _ => 0, + }; + crate::texture::upload_from(list, *resource as This, first); } // A depth texture shaders also write: what they wrote, first. list.twin_use(*resource as This, false, false); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e24be3b..d1f2c5e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -117,6 +117,34 @@ pub(crate) fn available_physical_ram() -> Option { ok.then_some(m.ullAvailPhys) } +/// How long host copies of textures the title fills must have been idle to +/// be let go, in milliseconds, and how many bytes of them go at most (the +/// longest idle first): none but those of ten minutes while what is in use +/// of the card (`used`: without what our own blocks have free, with what is +/// kept free for others) is under 88 % of its budget, else enough to come +/// down to 85 %. `VICTORY_TEXTURE_KEEP=0`: [`vram_idle_ms`]' older rule, +/// all that are idle; `=1`: that rule with its two longer times. +/// +/// (By those times everything idle for 2.5 s went from 75 % of the budget +/// on: 61,000 of them in the first 300 s of session play-1125-0203, at 78 to +/// 80 %, of which 13,000 were made and uploaded again.) +pub(crate) fn vram_keep(budget: u64, used: u64) -> (u64, u64) { + const KEPT_MS: u64 = 600_000; + const IDLE_MS: u64 = 5_000; + const SHORT_MS: u64 = 1_500; + if budget == 0 { + return (IDLE_MS, u64::MAX); + } + let share = |percent: u64| budget / 100 * percent; + if used < share(88) { + (KEPT_MS, u64::MAX) + } else if used < share(95) { + (IDLE_MS, used - share(85)) + } else { + (SHORT_MS, used - share(85)) + } +} + /// Effective idle timeout (in milliseconds) for VRAM-backed host textures, /// scaled down under VRAM pressure. Never returns less than 1,000 ms so /// handles not yet recorded into a list or slot remain protected. @@ -221,6 +249,12 @@ fn sweep() { crate::resource::let_go_idle(); } +/// The number of the newest submission begun, and of the newest of which all +/// before it have finished too. +pub(crate) fn submissions() -> (u64, u64) { + (STARTED.load(Ordering::Acquire), FINISHED.load(Ordering::Acquire)) +} + /// Drops `object` once every submission running now has finished: at once /// if none is. pub(crate) fn retire(object: T) { @@ -5530,8 +5564,10 @@ impl HostList { resource: crate::object::This, wanted: u32, ) -> Option<(&'static ID3D12Resource, u32)> { - let texture = crate::resource::host_resource(resource)?; let copy = crate::resource::host_copy(resource)?; + // SAFETY: as in `crate::resource::host_resource`; the list's states + // hold the copy from here on. + let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(©.texture) }; let wanted = legal_state(texture, wanted); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); match states.entry(std::sync::Arc::as_ptr(©) as usize) { @@ -7408,6 +7444,20 @@ impl Meter { crate::descriptor::host::STALE[4].load(Ordering::Relaxed) ); } + if crate::resource::held_only() { + let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed)); + let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed)); + tracing::info!( + "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \ + levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \ + {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \ + out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free", + bytes >> 20, + whole >> 20, + crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed), + crate::pool::texture_room() >> 20 + ); + } { let mode = crate::watch::page_writes(); let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); @@ -8904,6 +8954,18 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000); } + #[test] + fn textures_are_kept_while_the_card_has_room() { + use super::vram_keep; + let gib = 1 << 30; + assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000); + // Past it: the longest idle ones, enough to come down to 85 %. + let (ms, bytes) = vram_keep(100 * gib, 90 * gib); + assert_eq!((ms, bytes), (5_000, 5 * gib)); + assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib)); + assert_eq!(vram_keep(0, 7).0, 5_000); + } + #[test] fn ram_idle_ms_scales_with_pressure() { use super::ram_idle_ms; diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 32b3bfb..f05d963 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeMap, VecDeque}; use std::ffi::c_void; use std::sync::Mutex; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{GUID, HRESULT, IUnknown, Interface}; @@ -199,6 +199,15 @@ fn lock(m: &'static Mutex) -> std::sync::MutexGuard<'static, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } +/// Bytes of the pieces textures hold now. +static HELD: AtomicU64 = AtomicU64::new(0); + +/// Bytes of the texture blocks no texture holds: the card's memory in use +/// by us that new textures take first. +pub(crate) fn texture_room() -> u64 { + (lock(&TEXTURES).blocks() as u64 * BLOCK).saturating_sub(HELD.load(Ordering::Relaxed)) +} + /// For the memory line: blocks of textures and of staging buffers, in MiB. #[cfg(feature = "diagnostics")] pub(crate) fn memory() -> [u64; 2] { @@ -282,6 +291,7 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; if left == 0 { let gone = Box::from_raw(this.cast::()); + HELD.fetch_sub(gone.piece.len, Ordering::Relaxed); lock(&TEXTURES).give(gone.piece, now()); } left @@ -351,6 +361,7 @@ pub(crate) unsafe fn texture( let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) }; match (result, made) { (Ok(()), Some(made)) => { + HELD.fetch_add(piece.len, Ordering::Relaxed); give_back_with(&made, piece); Some(made) } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index db3621e..dc3de0d 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -98,6 +98,20 @@ pub(crate) struct ResourceDesc { flags: u32, } +#[cfg(windows)] +impl ResourceDesc { + /// The texture of this one's levels from `base` on. + fn from_level(&self, base: u32) -> ResourceDesc { + let mut d = *self; + if base > 0 { + d.width = (d.width >> base).max(1); + d.height = (d.height >> base).max(1); + d.mip_levels -= base as u16; + } + d + } +} + #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct AllocationInfo { @@ -1137,8 +1151,27 @@ pub(crate) struct HostTexture { /// levels have been given. Its `bytes` are 0: what it holds of the card /// is counted there. pub(crate) tiled: Option, + /// The title's level its level 0 is ([`held_only`]): larger levels have + /// no place in it. + pub(crate) base: u32, + /// Tells host copies apart that one texture had one after the other. + pub(crate) serial: u64, + /// Made in place of one with fewer levels: the slots that show that one + /// are made again once this one was filled whole. + pub(crate) grown: std::sync::atomic::AtomicBool, + /// What the last submitted upload put in it. + pub(crate) holds: std::sync::Arc, } +/// What a host copy was filled with last: the first level of it and the +/// hash of the title memory it was read from. +#[cfg(windows)] +pub(crate) type Holds = std::sync::Mutex>; + +/// [`HostTexture::serial`] of the last one made. +#[cfg(windows)] +static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// What a title texture has on the host: its host copy and, for a depth /// texture shaders also write, the colour twin. #[cfg(windows)] @@ -1167,6 +1200,149 @@ struct Hosted { gone: std::sync::atomic::AtomicBool, /// A texture of [`PLACED_TEXTURES`]. placed: std::sync::atomic::AtomicBool, + /// The lowest level a view asked for since it had no host copy + /// ([`want_level`]; `u32::MAX`: none said). + wanted: std::sync::atomic::AtomicU32, + /// The next host copy takes the place of one with fewer levels. + grown: std::sync::atomic::AtomicBool, +} + +/// Whether a texture the title places in memory is read, kept and uploaded +/// from the first level its views show on (`VICTORY_HELD_LEVELS=0`: whole, +/// as before). Such a title describes every level of a texture and views it +/// from the first one it holds; the memory of the larger ones is the next +/// texture's, or nothing. Of two recorded world frames the levels some slot +/// shows are 1.2 and 1.6 GB of the 6.3 and 6.7 GB of such host copies, and +/// most of what was found "changed" and uploaded again was other textures' +/// bytes. +#[cfg(windows)] +pub(crate) fn held_only() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + std::env::var_os("VICTORY_HELD_LEVELS").is_none_or(|v| v != "0") && !crate::tiles::wanted() + }) +} + +/// The first level a placed texture's view shows: of views of one 2D +/// texture (the others show whole textures). After victory-amd 4436f8f1. +pub(crate) fn first_mip(view: &[u32]) -> u32 { + const TEXTURE_2D_VIEW: u32 = 4; + match *view { + [_, TEXTURE_2D_VIEW, _, _, first, ..] => first.min(15), + _ => 0, + } +} + +/// The level from which on a texture of layout `layout` is read for a view +/// that starts at `first`: the smallest levels share a block and are read +/// together; 0 where the larger ones lie between the smaller ones. +pub(crate) fn read_from(layout: &victory_formats::texture::Layout, first: u32) -> u32 { + if layout.slices != 1 || layout.mips.is_empty() { + return 0; + } + let first = first.min(layout.first_tail_mip).min(layout.mips.len() as u32 - 1); + if layout.bytes_from(first) < layout.size { first } else { 0 } +} + +/// The level a host copy begins at for views that start at `first`: one the +/// host can have as a texture's level 0 ([`read_from`]; block-compressed +/// formats in whole blocks). +#[cfg(windows)] +fn base_level(desc: &ResourceDesc, first: u32) -> u32 { + const TEXTURE_2D: u32 = 3; + if first == 0 + || !fills(desc) + || desc.dimension != TEXTURE_2D + || desc.depth_or_array_size != 1 + || desc.mip_levels <= 1 + || desc.sample_count > 1 + { + return 0; + } + let Some(t) = texture_layout(desc).filter(|t| t.planes.len() == 1) else { + return 0; + }; + let layout = &t.planes[0].layout; + if layout.desc.swizzle.xor() { + return 0; + } + let block = u64::from(layout.desc.block.max(1)); + let mut base = read_from(layout, first).min(u32::from(desc.mip_levels) - 1); + let whole = |side: u64| side != 0 && side.is_multiple_of(block); + while base > 0 && !(whole(desc.width >> base) && whole(u64::from(desc.height) >> base)) { + base -= 1; + } + base +} + +/// The bytes of title memory a placed texture with the resource description +/// `desc` is read from for a view that starts at level `first`; `None` as +/// [`placed_bytes`]. Remembered: asked for every slot that is looked at. +#[cfg(windows)] +pub(crate) fn placed_bytes_from(desc: &[u32; 14], first: u32) -> Option { + if first == 0 || !held_only() { + return placed_bytes(desc); + } + type Known = std::collections::HashMap<([u32; 14], u32), Option>; + thread_local! { + static KNOWN: std::cell::RefCell = std::cell::RefCell::default(); + } + KNOWN.with(|known| { + *known.borrow_mut().entry((*desc, first)).or_insert_with(|| { + let whole = placed_bytes(desc)?; + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + let Some(t) = texture_layout(&d).filter(|t| t.planes.len() == 1) else { + return Some(whole); + }; + let layout = &t.planes[0].layout; + Some(layout.bytes_from(read_from(layout, first)).min(whole)) + }) + }) +} + +/// Host copies replaced by ones with more levels, for as long as a thread +/// that asked for one may still be about to record its use +/// ([`host_resource`]): when, and the copy. +#[cfg(windows)] +static REPLACED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Since the start: host copies made with a first level other than the +/// title's, and their bytes; host copies replaced by one with more levels; +/// bytes of title memory such copies' textures take whole. +#[cfg(windows)] +pub(crate) static HELD: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// A view of the placed texture `this` that starts at level `first` is made +/// or brought up to date: a host copy without that level is replaced by one +/// with it (made and filled at the next use; the slots that show the old +/// one go on showing it until that is done). +#[cfg(windows)] +pub(crate) fn want_level(this: This, first: u32) { + use std::sync::atomic::Ordering::Relaxed; + if this.is_null() || !held_only() { + return; + } + let r = resource(this); + if r.desc.dimension == BUFFER || !r.host.placed.load(Relaxed) { + return; + } + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some((host, _)) = made.as_ref() else { + r.host.wanted.fetch_min(first, Relaxed); + return; + }; + if host.base == 0 || host.base <= base_level(&r.desc, first) { + return; + } + r.host.wanted.store(first, Relaxed); + // Under the lock, as in `let_go_idle`. + crate::texture::unstage(this); + r.host.grown.store(true, Relaxed); + HELD[2].fetch_add(1, Relaxed); + if let Some(old) = made.take() { + REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old)); + } } /// Counts for the memory line: host copies of textures the title fills @@ -1353,9 +1529,20 @@ fn hosted(this: This, make: bool) -> Option { texture = reserved; } } + // The levels views show ([`held_only`]), those of the slots shaders + // pick by index among them. + let mut base = 0; + if shape_fits && r.host.placed.load(Relaxed) && held_only() && alias_of(this).is_none() { + let wanted = r.host.wanted.load(Relaxed); + let viewed = crate::descriptor::host::first_viewed(r.data() as u64).unwrap_or(u32::MAX); + let first = wanted.min(viewed); + if first != u32::MAX { + base = base_level(&r.desc, first); + } + } let texture = match texture { Some(texture) => Some(texture), - None => host_texture(&r.desc, r.host.state, clear), + None => host_texture(&r.desc.from_level(base), r.host.state, clear), }; let Some(texture) = texture else { r.host.refused.store(true, Relaxed); @@ -1378,6 +1565,13 @@ fn hosted(this: This, make: bool) -> Option { Some(tiled) => HostTexture::new_tiled(texture, state, tiled), None => HostTexture::new(texture, state), }; + host.base = base; + host.grown.store(r.host.grown.swap(false, Relaxed), Relaxed); + if base > 0 { + HELD[0].fetch_add(1, Relaxed); + HELD[1].fetch_add(host.bytes, Relaxed); + HELD[3].fetch_add(footprint(&r.desc).map_or(0, |f| f.size), Relaxed); + } host.filled = fills(&r.desc); if host.filled { KINDS[0].fetch_add(1, Relaxed); @@ -1455,7 +1649,8 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { // world makes in its first frame ([`targets_room_kept`]) counts as // used. Some([budget, used, ..]) => { - used + crate::shadow::card_room_kept() + targets_room_kept() < budget / 100 * room_percent() + used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept() + < budget / 100 * room_percent() } None => filled < WITHOUT_BUDGET, } @@ -1777,12 +1972,52 @@ pub(crate) fn let_go_idle() { if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { return; } - let idle_ms = crate::host::vram_idle_ms(crate::host::host().and_then(|h| h.video_memory())); + // Copies replaced by ones with more levels, as any let go. + { + let mut replaced = REPLACED.lock().unwrap_or_else(|e| e.into_inner()); + let (gone, keep): (Vec<_>, Vec<_>) = + replaced.drain(..).partition(|(at, _)| crate::host::long_ago(*at, 1000, IDLE_FRAMES)); + *replaced = keep; + drop(replaced); + for (_, made) in gone { + crate::host::retire(made); + } + } + let memory = crate::host::host().and_then(|h| h.video_memory()); + static KEEP: std::sync::OnceLock = std::sync::OnceLock::new(); + let keep = *KEEP + .get_or_init(|| !matches!(std::env::var("VICTORY_TEXTURE_KEEP").as_deref(), Ok("0") | Ok("1"))); + let (idle_ms, most) = match memory { + Some([budget, used, ..]) if keep => { + let used = used.saturating_sub(crate::pool::texture_room()) + + crate::shadow::card_room_kept() + + targets_room_kept(); + crate::host::vram_keep(budget, used) + } + _ => (crate::host::vram_idle_ms(memory), u64::MAX), + }; // For the trail (`crate::host::trail`): how many went, their bytes, // and the first one. let (mut went, mut bytes, mut first) = (0u64, 0u64, None); let all = textures(); - for &at in all.iter() { + // With a limit, the longest idle first. + let mut by_age: Vec<(u64, usize)> = Vec::new(); + if most != u64::MAX { + for &at in all.iter() { + // SAFETY: as below. + let r = unsafe { &*(at as *const Resource) }; + let used = r.host.used.load(Relaxed); + if used != 0 && fills(&r.desc) && crate::host::long_ago(used, idle_ms, IDLE_FRAMES) { + by_age.push((used & 0xffff_ffff, at)); + } + } + by_age.sort_unstable(); + } + let every = all.iter().copied().filter(|_| most == u64::MAX); + for at in every.chain(by_age.iter().map(|&(_, at)| at)) { + if bytes >= most { + break; + } // SAFETY: a texture leaves the table before it is freed, under the // lock held here (`Drop for Resource`). let r = unsafe { &*(at as *const Resource) }; @@ -1800,6 +2035,7 @@ pub(crate) fn let_go_idle() { // Under the lock: the next use must not find the staging // state of the texture let go (it says "uploaded"). crate::texture::unstage(at as This); + r.host.wanted.store(u32::MAX, Relaxed); made.take() } else { None @@ -1973,6 +2209,10 @@ impl HostTexture { bytes, filled: false, tiled: None, + base: 0, + serial: SERIAL.fetch_add(1, Relaxed) + 1, + grown: Default::default(), + holds: Default::default(), } } @@ -1990,6 +2230,10 @@ impl HostTexture { bytes: 0, filled: false, tiled: Some(tiled), + base: 0, + serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1, + grown: Default::default(), + holds: Default::default(), } } } @@ -2054,6 +2298,15 @@ pub(crate) fn host_copy(this: This) -> Option> { hosted(this, true).map(|made| made.0) } +/// A title texture's host copy if it is made; not made here. +#[cfg(windows)] +pub(crate) fn made_copy(this: This) -> Option> { + if this.is_null() { + return None; + } + hosted(this, false).map(|made| made.0) +} + /// A host texture like the title's: same description, in GPU memory, /// without the console's layout and flags. #[cfg(windows)] @@ -2330,6 +2583,8 @@ fn hand_out_resource( refused: std::sync::atomic::AtomicBool::new(false), gone: std::sync::atomic::AtomicBool::new(false), placed: std::sync::atomic::AtomicBool::new(false), + wanted: std::sync::atomic::AtomicU32::new(u32::MAX), + grown: std::sync::atomic::AtomicBool::new(false), }, }); // The host copy waits for the texture's first use ([`Hosted`]). @@ -4140,4 +4395,37 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!(texture_floor_bytes(Some(24 * GIB)), 2 * GIB); assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB); } + + /// A placed texture viewed from a later level has a host copy of that + /// and the smaller levels; a view from an earlier one gets another. + #[cfg(windows)] + #[test] + fn a_placed_texture_is_kept_from_the_level_viewed() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + if crate::host::host().is_none() || !held_only() { + return; + } + // 256x256 BC7, nine levels, 4 KiB blocks. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap(); + let part = placed_bytes_from(&desc, 2).unwrap(); + assert!(part * 8 < whole, "{part} of {whole}"); + assert_eq!(placed_bytes_from(&desc, 0), Some(whole)); + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + let texture = texture_at(at as u64, &desc).unwrap(); + want_level(texture, 2); + let copy = host_copy(texture).unwrap(); + // SAFETY: a live texture. + let d = unsafe { copy.texture.GetDesc() }; + assert_eq!((copy.base, d.Width, d.Height, d.MipLevels), (2, 64, 64, 7)); + want_level(texture, 5); + assert_eq!(host_copy(texture).unwrap().serial, copy.serial); + want_level(texture, 0); + let more = host_copy(texture).unwrap(); + // SAFETY: as above. + let d = unsafe { more.texture.GetDesc() }; + assert_eq!((more.base, d.Width, d.MipLevels), (0, 256, 9)); + assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed)); + } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index f3c2a8d..f970f70 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -46,8 +46,20 @@ pub(crate) struct Staging { footprints: Vec, rows: Vec, layout: victory_formats::texture::Layout, - /// Mips per array slice. + /// Mips per array slice, of the title's texture. mips: u32, + /// The first of them that is read and uploaded + /// (`crate::resource::held_only`), the one the host copy begins at, and + /// the bytes of title memory read. + first: u32, + level0: u32, + read: usize, + /// Which host copy it uploads into, and what that is told to hold. + serial: u64, + holds: Arc, + /// Title memory being remapped is waited for whatever [`no_wait`] says: + /// a list that bakes from the texture now recorded the upload. + waits: std::sync::atomic::AtomicBool, /// The staging buffer's bytes (counted in `STAGED` while it lives). bytes: u64, memory: *const u8, @@ -160,6 +172,8 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8; const COPY_DEST: u32 = 0x400; const COPY_SOURCE: u32 = 0x800; + // (All of its levels: the copy is level by level.) + crate::resource::want_level(placed, 0); let (Some(to), Some(from)) = ( crate::resource::host_resource(placed), crate::resource::host_resource(source), @@ -629,7 +643,21 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { /// its host copy, and the detiling that refreshes the staging buffer at /// submission if the memory changed. Leaves the texture in the copy /// destination state. -pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { +pub(crate) fn upload(list: &HostList, resource: This, _texture: &ID3D12Resource) { + upload_from(list, resource, 0); +} + +thread_local! { + /// The thread records uploads for a draw that bakes from them + /// ([`Staging::waits`]). + pub(crate) static BAKING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// [`upload`] of the levels from `first` on, the ones a view shows: of a +/// texture the title placed there may be no memory of the larger ones, and +/// what lies there is another texture's. (After victory-amd 4436f8f1.) +pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { + let first = if crate::resource::held_only() { first } else { 0 }; let host_written = HOST_WRITTEN .lock() .unwrap_or_else(|e| e.into_inner()) @@ -637,13 +665,28 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) .is_some_and(|set| set.contains(&(resource as usize))); // shortcut: a texture the host copied into keeps the host's contents // even if the title later writes its memory too. - if host_written || !list.first_use(resource as usize) { + if host_written { return; } - let Some(staging) = staging(resource, texture) else { + // Once a list for each first level; not again for one that the list's + // upload of larger ones held too. + if !list.first_use(1 << 63 | (resource as usize) << 4 | first as usize & 15) { + return; + } + if !list.first_use(resource as usize) && staged_from(resource) <= first { + return; + } + let Some(copy) = crate::resource::host_copy(resource) else { + return; + }; + let texture = ©.texture; + let Some(staging) = staging(resource, ©, first) else { return; }; use std::sync::atomic::Ordering::Relaxed; + if BAKING.get() { + staging.waits.store(true, Relaxed); + } staging.used.store(crate::host::moment(), Relaxed); // Levels on demand: a view of the texture now starts at another // level, or another texture now starts inside its span, with no byte @@ -684,7 +727,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); if no_wait() && fill_unlocked() { - let there = mapped_bytes(staging.memory, staging.layout.size as usize); + let there = mapped_bytes(staging.memory, staging.read); staging.expected.store(there, Relaxed); } const COPY_DEST: u32 = 0x400; @@ -741,7 +784,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) pResource: unsafe { std::mem::transmute_copy(texture) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: i as u32, + SubresourceIndex: staging.first - staging.level0 + i as u32, }, }; let from = D3D12_TEXTURE_COPY_LOCATION { @@ -768,6 +811,13 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) staging.dirty.store(false, Relaxed); }); } + // A host copy that took the place of one with fewer levels: the slots + // that show that one are made again once this upload has run. + if staging.first == staging.level0 && copy.grown.swap(false, Relaxed) { + let start = staging.memory as u64; + list.defer_host(move || crate::descriptor::host::levels_changed_after(start)); + } + let noted = staging.clone(); // Levels on demand (`crate::tiles`): after the check below, in the // order of this list's steps, and before the list is executed, the // levels the staging buffer holds as the title's are given the card's @@ -778,6 +828,8 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) let Some(on_demand) = on_demand else { // Once per submission however many of its lists sample the texture. list.defer_texture(staging); + // Then what the list's copy puts in the host copy is known. + list.defer_host(move || noted.note_held()); return; }; list.defer_texture(staging.clone()); @@ -971,7 +1023,21 @@ impl Staging { /// The title memory the texture is read from: address and bytes. pub(crate) fn memory(&self) -> (usize, usize) { - (self.memory as usize, self.layout.size as usize) + (self.memory as usize, self.read) + } + + /// The title's level and the array slice of the staging buffer's part + /// `i`. + fn part(&self, i: usize) -> (u32, u32) { + let mips = self.mips - self.first; + (self.first + i as u32 % mips, i as u32 / mips) + } + + /// The host copy holds what the staging buffer was filled from + /// ([`unchanged`]). + fn note_held(&self) { + let hash = self.last.lock().unwrap_or_else(|e| e.into_inner()).hash; + *self.holds.lock().unwrap_or_else(|e| e.into_inner()) = hash.map(|hash| (self.first, hash)); } /// Detiles the texture memory into the staging buffer if it changed @@ -994,7 +1060,7 @@ impl Staging { } fn refresh_timed(&self) -> usize { - let size = self.layout.size as usize; + let size = self.read; let start = self.memory as usize; let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; @@ -1061,7 +1127,7 @@ impl Staging { // stays mapped (see `crate::watch::title_memory_reading`; without // it a page went between the asking and the read in runs 71 and // 74). - let _mapped = if no_wait() { + let _mapped = if no_wait() && !self.waits.load(std::sync::atomic::Ordering::Relaxed) { // Not waited for: while the runtime remaps title memory the // texture is read through the kernel instead, whole or not at // all (`no_wait`). @@ -1240,7 +1306,7 @@ impl Staging { ); } for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { - let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + let (mip, slice) = self.part(i); let f = footprint.Footprint; let pitch = f.RowPitch as usize; // The last row of the last subresource is not padded to its pitch @@ -1330,6 +1396,59 @@ pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> { Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed))) } +/// The first level a title texture's staging buffer holds; `u32::MAX` +/// without one. +fn staged_from(resource: This) -> u32 { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref() + .and_then(|map| map.get(&(resource as usize))) + .map_or(u32::MAX, |s| s.first) +} + +/// Whether the levels from `first` on of `resource`'s host copy were filled +/// from the bytes title memory holds now: an upload would bring nothing new. +/// (Of 787 repeated uploads of a frame that streams 398 were equal in every +/// byte, and a texture uploaded again costs a staging buffer, a detiling and +/// a copy more than this look.) `VICTORY_TEXTURE_SAME=0`: not asked. +pub(crate) fn unchanged(resource: This, first: u32) -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SAME").is_none_or(|v| v != "0")) { + return false; + } + let Some(copy) = crate::resource::made_copy(resource) else { + return false; + }; + let Some((from, held)) = *copy.holds.lock().unwrap_or_else(|e| e.into_inner()) else { + return false; + }; + let Some((memory, desc)) = crate::resource::texture_memory(resource) else { + return false; + }; + let Some(layout) = crate::resource::texture_layout(&desc) else { + return false; + }; + let layout = &layout.planes[0].layout; + if from > crate::resource::read_from(layout, first).max(copy.base) { + return false; + } + let size = layout.bytes_from(from) as usize; + with_read(size, |read| { + if crate::host::read_there(memory, read) == 0 { + return false; + } + blake3::hash(read) == held + }) +} + +/// Where the levels from `first` on of a title texture are: address and +/// bytes. +pub(crate) fn title_span(resource: This, first: u32) -> Option<(u64, u64)> { + let (memory, desc) = crate::resource::texture_memory(resource)?; + let layout = crate::resource::texture_layout(&desc)?; + let layout = &layout.planes[0].layout; + Some((memory as u64, layout.bytes_from(crate::resource::read_from(layout, first)))) +} + pub(crate) fn is_staged(resource: This) -> bool { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize))) @@ -1342,8 +1461,7 @@ pub(crate) fn staged(resource: This) -> Option<(u64, bool)> { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref()?.get(&(resource as usize))?.clone() }; - let size = s.layout.size as usize; - Some((size as u64, committed(s.memory, size))) + Some((s.read as u64, committed(s.memory, s.read))) } /// Whether `[at, at + len)` is committed memory (streamed textures may be @@ -1509,13 +1627,17 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { } /// The staging state of a title texture, made on first use. -fn staging(resource: This, texture: &ID3D12Resource) -> Option> { +fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> Option> { + let texture = ©.texture; // Asked before the table is locked: the sweep lets go of a staging // buffer with its texture's host side locked, in that order. let on_demand = crate::resource::host_tiled(resource).is_some(); let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let map = map.get_or_insert_with(HashMap::new); - if let Some(s) = map.get(&(resource as usize)) { + if let Some(s) = map.get(&(resource as usize)) + && s.first <= first.max(copy.base) + && s.serial == copy.serial + { return Some(s.clone()); } let (memory, desc) = crate::resource::texture_memory(resource)?; @@ -1534,10 +1656,14 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { let host = host()?; // SAFETY: a live resource. let d = unsafe { texture.GetDesc() }; + let level0 = copy.base; + let mips = level0 + u32::from(d.MipLevels); + let first = crate::resource::read_from(&layout, first).max(level0).min(mips - 1); + let read = layout.bytes_from(first) as usize; let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { - u32::from(d.MipLevels) + mips - first } else { - u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize) + (mips - first) * u32::from(d.DepthOrArraySize) }; let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; let mut rows = vec![0u32; count as usize]; @@ -1546,7 +1672,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { unsafe { host.device.GetCopyableFootprints( &d, - 0, + first - level0, count, 0, Some(footprints.as_mut_ptr()), @@ -1581,7 +1707,13 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { footprints, rows, layout, - mips: u32::from(d.MipLevels), + mips, + first, + level0, + read, + serial: copy.serial, + holds: copy.holds.clone(), + waits: std::sync::atomic::AtomicBool::new(false), bytes: total, memory, last: Mutex::default(), @@ -1800,6 +1932,65 @@ mod allocation_costs { } } + /// What a texture met for the first time costs, by step, in + /// milliseconds a megabyte on one thread: for whether a store of + /// detiled copies on disk could be worth it (its key is a hash of the + /// title's bytes, so reading and hashing them stay; `VICTORY_BENCH_FILE` + /// is a big file to read past the system's cache). + #[test] + #[ignore = "a measurement, not a check"] + fn cold_texture_costs() { + let Some(host) = crate::host::host() else { return }; + let desc = [3u32, 0, 0, 0, 1024, 0, 1024, 0xb_0001, 98, 1, 0, 0x105, 0, 0]; + // SAFETY: 56 bytes in the description's layout. + let desc = unsafe { desc.as_ptr().cast::().read_unaligned() }; + let layout = crate::resource::texture_layout(&desc).unwrap().planes[0].layout.clone(); + let size = layout.size as usize; + let title: Vec = (0..size).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect(); + let (_buffer, up) = host.upload_buffer(2 * layout.size).unwrap(); + // SAFETY: the mapping. + let up = unsafe { std::slice::from_raw_parts_mut(up, 2 * size) }; + let mut read = vec![0u8; size]; + const N: u32 = 200; + let per_mb = |t: std::time::Duration| t.as_secs_f64() * 1e3 / (f64::from(N) * size as f64 / 1e6); + let timed = |what: &str, f: &mut dyn FnMut()| { + f(); + let started = std::time::Instant::now(); + (0..N).for_each(|_| f()); + println!("{what}: {:.3} ms/MB", per_mb(started.elapsed())); + }; + timed("read through the kernel or a safe copy", &mut || { + std::hint::black_box(crate::host::read_into(title.as_ptr(), &mut read)); + }); + timed("blake3", &mut || { + std::hint::black_box(blake3::hash(&title)); + }); + timed("detiled into upload memory", &mut || { + let mut at = 0; + for (mip, m) in layout.mips.iter().enumerate() { + let pitch = (m.width as usize * 16).next_multiple_of(256); + let len = pitch * m.height as usize; + layout.detile(&title, mip as u32, 0, &mut up[at..at + len], pitch, len).unwrap(); + at += len.next_multiple_of(512); + } + }); + timed("copied into upload memory", &mut || up[..size].copy_from_slice(&title)); + if let Some(file) = std::env::var_os("VICTORY_BENCH_FILE") { + use std::os::windows::fs::{FileExt, OpenOptionsExt}; + const NO_BUFFERING: u32 = 0x2000_0000; + let file = std::fs::OpenOptions::new().read(true).custom_flags(NO_BUFFERING).open(file).unwrap(); + let len = file.metadata().unwrap().len(); + let mut block = vec![0u8; size + 4096]; + let skew = block.as_ptr().align_offset(4096); + let n = size / 4096 * 4096; + let mut at = 0u64; + timed("read from the disk, one request at a time", &mut || { + at = (at + 7919 * 4096 * 64) % (len - n as u64) / 4096 * 4096; + file.seek_read(&mut block[skew..skew + n], at).unwrap(); + }); + } + } + #[test] #[ignore = "a measurement, not a check"] fn allocation_costs() {