| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488 |
- //! Host memory for the textures the title fills, and for their staging
- //! buffers, cut from blocks made once.
- //!
- //! Each such texture had an allocation of its own and its staging buffer
- //! another. On an RX 7900 XTX an allocation takes about 310 microseconds
- //! whatever its size, on one thread (`texture::allocation_costs`), and a
- //! texture cut from a block 6: the pass that makes the textures shaders
- //! pick by index (`draw.rs` `heap_textures`) got through 350-500 of the
- //! 24,000 queued when the world loads in each of its 250 ms turns, some
- //! forty seconds of a world without its textures.
- //! `VICTORY_TEXTURE_POOL=0` makes every one an allocation of its own again.
- //!
- //! A piece given back is used again only two seconds later (nothing the card
- //! was told before that is still running: Windows resets a card that takes
- //! that long over one submission), and by then no list names it (the owners' rule, as for allocations of their own): a
- //! texture's piece comes back when the last reference to the host texture
- //! goes (an object of ours the texture holds says so), a staging buffer's
- //! when the last list that recorded its copy is reset.
- use std::collections::{BTreeMap, VecDeque};
- use std::ffi::c_void;
- use std::sync::Mutex;
- use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
- use windows::Win32::Graphics::Direct3D12::*;
- use windows::core::{GUID, HRESULT, IUnknown, Interface};
- /// Bytes of a block; pieces of more than half of one are not pooled.
- const BLOCK: u64 = 64 << 20;
- /// Blocks with nothing in them that are kept.
- const SPARE: usize = 2;
- /// The same while the card has room ([`room`]): 4 GiB of them.
- const SPARE_KEPT: usize = 64;
- /// How many are kept now.
- static SPARES: AtomicUsize = AtomicUsize::new(SPARE);
- /// Sets how many empty blocks stay, by the card's memory (budget and use):
- /// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`].
- /// Asked once a second.
- pub(crate) fn room(memory: Option<[u64; 4]>) {
- SPARES.store(spares(memory, crate::host::keep_freed()), Ordering::Relaxed);
- }
- fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize {
- match memory {
- Some([budget, used, ..]) if keep && u128::from(used) * 100 < u128::from(budget) * 85 => SPARE_KEPT,
- _ => SPARE,
- }
- }
- /// Milliseconds until a piece given back is used again. (It was three
- /// frames, a tenth of a second while the title shows a loading screen at 30
- /// a second, with up to 18 submissions in the air.)
- const REST: u64 = 2500;
- fn now() -> u64 {
- crate::host::now_ms()
- }
- pub(crate) fn on() -> bool {
- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_POOL").is_none_or(|v| v != "0"))
- }
- /// The free ranges of a block: start and length, never two that touch.
- struct Ranges(BTreeMap<u64, u64>);
- impl Ranges {
- fn new(size: u64) -> Ranges {
- Ranges(BTreeMap::from([(0, size)]))
- }
- /// The lowest place for `len` bytes at a multiple of `align`.
- fn take(&mut self, len: u64, align: u64) -> Option<u64> {
- let (start, size, at) = self.0.iter().find_map(|(&start, &size)| {
- let at = start.next_multiple_of(align);
- (at + len <= start + size).then_some((start, size, at))
- })?;
- self.0.remove(&start);
- if at > start {
- self.0.insert(start, at - start);
- }
- if at + len < start + size {
- self.0.insert(at + len, start + size - at - len);
- }
- Some(at)
- }
- fn give(&mut self, mut start: u64, mut len: u64) {
- if let Some((&before, &size)) = self.0.range(..start).next_back()
- && before + size == start
- {
- self.0.remove(&before);
- (start, len) = (before, len + size);
- }
- if let Some(size) = self.0.remove(&(start + len)) {
- len += size;
- }
- self.0.insert(start, len);
- }
- fn whole(&self, size: u64) -> bool {
- self.0.get(&0) == Some(&size)
- }
- }
- /// A part of a block.
- #[derive(Clone, Copy, Debug, PartialEq)]
- pub(crate) struct Piece {
- block: usize,
- start: u64,
- len: u64,
- }
- struct Block<B> {
- memory: B,
- free: Ranges,
- /// The end of the highest piece ever taken: above it the memory is as
- /// it was made (zeros).
- used_to: u64,
- }
- struct Pool<B> {
- /// `None`: a block let go, its place to be used again.
- blocks: Vec<Option<Block<B>>>,
- /// Pieces given back, and when each may be used again.
- resting: VecDeque<(u64, Piece)>,
- /// The empty blocks it was last told to keep.
- spare: usize,
- }
- impl<B: Clone> Pool<B> {
- const fn new() -> Pool<B> {
- Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0 }
- }
- /// A piece of `len` bytes and the memory it lies in, and whether that
- /// part was ever used before; `make` makes a block when none has room.
- fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnOnce() -> Option<B>) -> Option<(Piece, B, bool)> {
- if len == 0 || len > BLOCK / 2 {
- return None;
- }
- self.rested(now);
- let mut found = None;
- for (i, block) in self.blocks.iter_mut().enumerate() {
- if let Some(block) = block
- && let Some(start) = block.free.take(len, align)
- {
- found = Some((i, start));
- break;
- }
- }
- let (i, start) = match found {
- Some(found) => found,
- None => {
- let mut block = Block { memory: make()?, free: Ranges::new(BLOCK), used_to: 0 };
- let start = block.free.take(len, align)?;
- let i = match self.blocks.iter().position(Option::is_none) {
- Some(i) => i,
- None => {
- self.blocks.push(None);
- self.blocks.len() - 1
- }
- };
- self.blocks[i] = Some(block);
- (i, start)
- }
- };
- let block = self.blocks[i].as_mut()?;
- let again = start < block.used_to;
- block.used_to = block.used_to.max(start + len);
- Some((Piece { block: i, start, len }, block.memory.clone(), again))
- }
- fn give(&mut self, piece: Piece, now: u64) {
- self.resting.push_back((now + REST, piece));
- }
- /// Makes the pieces that rested long enough free, and lets go of empty
- /// blocks past [`SPARE`].
- fn rested(&mut self, now: u64) {
- let mut any = false;
- while let Some(&(ready, piece)) = self.resting.front()
- && ready <= now
- {
- self.resting.pop_front();
- if let Some(block) = self.blocks[piece.block].as_mut() {
- block.free.give(piece.start, piece.len);
- any |= block.free.whole(BLOCK);
- }
- }
- // (Without a piece given back too, once there is less room.)
- let most = SPARES.load(Ordering::Relaxed);
- if any || most < self.spare {
- self.spare = most;
- let mut spare = 0;
- for block in &mut self.blocks {
- if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) {
- spare += 1;
- if spare > most {
- *block = None;
- }
- }
- }
- }
- }
- fn blocks(&self) -> usize {
- self.blocks.iter().flatten().count()
- }
- }
- /// A mapped upload buffer's memory.
- #[derive(Clone)]
- struct Upload(ID3D12Resource, *mut u8);
- // SAFETY: the mapping is written by the owners of its pieces, each its own.
- unsafe impl Send for Upload {}
- static TEXTURES: Mutex<Pool<ID3D12Heap>> = Mutex::new(Pool::new());
- static STAGING: Mutex<Pool<Upload>> = Mutex::new(Pool::new());
- fn lock<T>(m: &'static Mutex<T>) -> std::sync::MutexGuard<'static, T> {
- m.lock().unwrap_or_else(|e| e.into_inner())
- }
- /// For the memory line: blocks of textures and of staging buffers, in MiB.
- #[cfg(feature = "diagnostics")]
- pub(crate) fn memory() -> [u64; 2] {
- [lock(&TEXTURES).blocks() as u64 * (BLOCK >> 20), lock(&STAGING).blocks() as u64 * (BLOCK >> 20)]
- }
- /// Part of a block of mapped upload memory, back in the pool when dropped.
- pub(crate) struct StagingPiece(Piece);
- impl Drop for StagingPiece {
- fn drop(&mut self) {
- lock(&STAGING).give(self.0, now());
- }
- }
- /// `bytes` of upload memory, all zeros: the buffer it lies in, where in
- /// that buffer, and its mapping. `None`: not pooled.
- pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8)> {
- if !on() {
- return None;
- }
- // Copies from a buffer begin at multiples of 512.
- let bytes = bytes.next_multiple_of(512);
- let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
- let (buffer, data) = host.upload_buffer(BLOCK)?;
- crate::host::name(&buffer, || "staging of textures (a block)".into());
- Some(Upload(buffer, data))
- })?;
- let owned = StagingPiece(piece);
- // SAFETY: the piece lies in the block's mapping.
- let data = unsafe { memory.1.add(piece.start as usize) };
- if again {
- // What is not detiled into it (an unmapped texture) uploads zeros,
- // as from a buffer of its own.
- // SAFETY: the piece is ours alone.
- unsafe { std::ptr::write_bytes(data, 0, bytes as usize) };
- }
- Some((owned, memory.0, piece.start, data))
- }
- /// An object the host texture holds and releases when it goes: its piece
- /// is free then.
- #[repr(C)]
- struct Reclaim {
- methods: &'static [*const (); 3],
- references: AtomicU32,
- piece: Piece,
- }
- struct Methods([*const (); 3]);
- // SAFETY: function addresses only.
- unsafe impl Sync for Methods {}
- static RECLAIM: Methods = Methods([query as *const (), add_ref as *const (), release as *const ()]);
- unsafe extern "system" fn query(this: *mut c_void, iid: *const GUID, out: *mut *mut c_void) -> HRESULT {
- const E_NOINTERFACE: HRESULT = HRESULT(0x8000_4002_u32 as i32);
- // SAFETY: COM's arguments.
- unsafe {
- if out.is_null() {
- return HRESULT(0x8000_4003_u32 as i32);
- }
- if iid.as_ref().is_some_and(|iid| *iid == IUnknown::IID) {
- add_ref(this);
- *out = this;
- return HRESULT(0);
- }
- *out = std::ptr::null_mut();
- }
- E_NOINTERFACE
- }
- unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 {
- // SAFETY: one of ours, alive while a reference to it is.
- unsafe { (*this.cast::<Reclaim>()).references.fetch_add(1, Ordering::Relaxed) + 1 }
- }
- unsafe extern "system" fn release(this: *mut c_void) -> u32 {
- // SAFETY: as above; the last reference frees the box it was made as.
- unsafe {
- let left = (*this.cast::<Reclaim>()).references.fetch_sub(1, Ordering::AcqRel) - 1;
- if left == 0 {
- let gone = Box::from_raw(this.cast::<Reclaim>());
- lock(&TEXTURES).give(gone.piece, now());
- }
- left
- }
- }
- /// Makes `texture` give `piece` back when the last reference to it goes.
- fn give_back_with(texture: &ID3D12Resource, piece: Piece) {
- const KEY: GUID = GUID::from_u128(0x6f0e2f0c_5a59_4b1e_9a3f_7f4d2c9be713);
- let made = Box::into_raw(Box::new(Reclaim { methods: &RECLAIM.0, references: AtomicU32::new(1), piece }));
- // SAFETY: a COM object of ours with one reference, which this takes and
- // drops at the end; the texture takes its own.
- unsafe {
- let object = IUnknown::from_raw(made.cast());
- if texture.SetPrivateDataInterface(&KEY, &object).is_err() {
- // Never given back: the piece stays taken, nothing is reused
- // under a texture that may be alive.
- std::mem::forget(object);
- }
- }
- }
- /// A texture of `desc` (no target, depth or unordered access) in a block;
- /// `None`: not pooled, or the host refused.
- ///
- /// # Safety
- /// `desc` is a valid description.
- pub(crate) unsafe fn texture(
- device: &ID3D12Device,
- desc: *const D3D12_RESOURCE_DESC,
- state: D3D12_RESOURCE_STATES,
- ) -> Option<ID3D12Resource> {
- if !on() {
- return None;
- }
- // Small textures lie at multiples of 4 KiB where the host allows it
- // (the top mip is 64 KiB at most): 64 KiB each otherwise.
- // SAFETY: the caller's description.
- let mut d = unsafe { *desc };
- d.Alignment = u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT);
- // SAFETY: plain queries.
- let mut info = unsafe { device.GetResourceAllocationInfo(0, &[d]) };
- if info.SizeInBytes == u64::MAX || info.Alignment != d.Alignment {
- d.Alignment = 0;
- info = unsafe { device.GetResourceAllocationInfo(0, &[d]) };
- }
- if info.SizeInBytes == u64::MAX {
- return None;
- }
- let (piece, heap, _) = lock(&TEXTURES).take(info.SizeInBytes, info.Alignment.max(1), now(), || {
- let desc = D3D12_HEAP_DESC {
- SizeInBytes: BLOCK,
- Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
- Alignment: 0,
- Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,
- };
- let mut heap: Option<ID3D12Heap> = None;
- // SAFETY: plain creation.
- if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } {
- tracing::warn!(error = %e, "no block of texture memory");
- }
- heap
- })?;
- let mut made: Option<ID3D12Resource> = None;
- // SAFETY: the piece is no one else's; the heap lives while a piece of
- // it is taken.
- let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) };
- match (result, made) {
- (Ok(()), Some(made)) => {
- give_back_with(&made, piece);
- Some(made)
- }
- _ => {
- lock(&TEXTURES).give(piece, now());
- None
- }
- }
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn ranges_are_cut_aligned_and_join_again() {
- let mut r = Ranges::new(1024);
- assert_eq!(r.take(100, 64), Some(0));
- assert_eq!(r.take(100, 64), Some(128));
- assert_eq!(r.take(28, 4), Some(100));
- assert_eq!(r.take(2000, 4), None);
- r.give(128, 100);
- r.give(0, 100);
- assert!(!r.whole(1024));
- r.give(100, 28);
- assert!(r.whole(1024));
- }
- #[test]
- fn empty_blocks_stay_while_the_card_has_room() {
- assert_eq!(spares(Some([100, 84, 0, 0]), true), SPARE_KEPT);
- assert_eq!(spares(Some([100, 85, 0, 0]), true), SPARE);
- assert_eq!(spares(Some([100, 10, 0, 0]), false), SPARE);
- assert_eq!(spares(None, true), SPARE);
- }
- #[test]
- fn pieces_never_overlap_and_rest_before_they_are_used_again() {
- let mut pool: Pool<u32> = Pool::new();
- let made = std::cell::Cell::new(0);
- let make = || {
- made.set(made.get() + 1);
- Some(made.get())
- };
- let mut taken: Vec<Piece> = Vec::new();
- for i in 0..500u64 {
- let (p, _, again) = pool.take(65536 * (1 + i % 7), 65536, 0, make).unwrap();
- assert!(!again);
- assert!(taken.iter().all(|q| q.block != p.block || p.start + p.len <= q.start || q.start + q.len <= p.start));
- taken.push(p);
- }
- let blocks = pool.blocks();
- assert!(blocks >= 2);
- // Given back at 10: not used again before 10 + REST.
- let first = taken[0];
- pool.give(first, 10);
- let (p, _, _) = pool.take(first.len, 65536, 10 + REST - 1, make).unwrap();
- assert_ne!((p.block, p.start), (first.block, first.start));
- let (q, _, again) = pool.take(first.len, 65536, 10 + REST, make).unwrap();
- assert_eq!((q.block, q.start, again), (first.block, first.start, true));
- // Everything back: the empty blocks past the spare ones go.
- for p in taken.drain(1..).chain([p, q]) {
- pool.give(p, 20);
- }
- pool.rested(20 + REST);
- assert_eq!(pool.blocks(), blocks.min(SPARES.load(Ordering::Relaxed)));
- // Too big for a block, and a block that cannot be made.
- assert!(pool.take(BLOCK, 65536, 30, make).is_none());
- let mut none: Pool<u32> = Pool::new();
- assert!(none.take(65536, 65536, 0, || None).is_none());
- }
- /// A pooled texture's piece comes back when its last reference goes, not
- /// before; its staging piece begins as zeros.
- #[test]
- fn a_texture_gives_its_piece_back_when_it_goes() {
- let Some(host) = crate::host::host() else { return };
- 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 },
- ..Default::default()
- };
- // SAFETY: a valid description.
- let Some(t) = (unsafe { texture(&host.device, &desc, D3D12_RESOURCE_STATE_COMMON) }) else { return };
- assert_eq!(crate::host::references(&t), 1, "what the texture holds is no reference to it");
- let resting = || lock(&TEXTURES).resting.len();
- let before = resting();
- let other = t.clone();
- drop(t);
- assert_eq!(resting(), before);
- drop(other);
- assert_eq!(resting(), before + 1);
- // SAFETY: the piece's mapping, 4096 bytes of it ours.
- unsafe {
- let (piece, _, at, data) = staging(host, 4096).unwrap();
- assert!(at.is_multiple_of(512));
- std::ptr::write_bytes(data, 0xAB, 4096);
- drop(piece);
- lock(&STAGING).rested(u64::MAX);
- let (_piece, _, _, data) = staging(host, 4096).unwrap();
- assert!((0..4096).all(|i| *data.add(i) == 0));
- // SAFETY: plain query.
- assert!(host.device.GetDeviceRemovedReason().is_ok());
- }
- }
- }
|