Streaming, copy queue, texture pools and a shader cache that survives rebuilds
Textures and staging cut from 64 MB blocks; a kept view per page section and page lists read again until the title has filled them in; the GPU side told when streamed bytes land; results fetched over the copy queue (VICTORY_RELAY_COPY=1); the write-watch journal behind a reader-writer lock; the shader cache keyed by the translator's sources and `victory shaders`; helper lanes as in upstream 1733 (VICTORY_HELPER_OWN). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
7f166af4f3
commit
9fea7434cd
20 files changed
+1629
-232
No files matched your search
@@ -0,0 +1,456 @@
|
||||
//! 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, 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;
|
||||
/// 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)>,
|
||||
}
|
||||
|
||||
impl<B: Clone> Pool<B> {
|
||||
const fn new() -> Pool<B> {
|
||||
Pool { blocks: Vec::new(), resting: VecDeque::new() }
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
if any {
|
||||
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 > SPARE {
|
||||
*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 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(SPARE));
|
||||
// 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user