diff --git a/runtime/d3d12/buffer_import_guest.cpp b/runtime/d3d12/buffer_import_guest.cpp index 5dde2a80..85d7601e 100644 --- a/runtime/d3d12/buffer_import_guest.cpp +++ b/runtime/d3d12/buffer_import_guest.cpp @@ -373,8 +373,95 @@ std::string unmap_mode(const wchar_t* requested, bool release_first) { return receipt; } +// Read a page the host cannot import directly. The provider then mirrors the +// page into a copy of its own, and that copy has to follow the guest's writes +// before every submission. +std::string shadow_mode(const wchar_t* requested, bool) { + DXGI_ADAPTER_DESC1 selected{}; + // A megabyte of guest pages, so the copy the provider makes shows in the + // memory ledger. + constexpr UINT pages=16; + constexpr UINT shadow_words=pages*page/4; + auto device=create_device(requested,selected); + auto place=method(device.Get(),44); + auto reg=method(device.Get(),74); + auto unreg=method(device.Get(),75); + auto module=LoadLibraryW(L"xmem.dll"); + if(!module)throw std::runtime_error("load xmem"); + using Allocate=BOOL(WINAPI*)(UINT64,SIZE_T*,UINT64*); + using Map=void*(WINAPI*)(void*,SIZE_T,const UINT64*); + using Free=BOOL(WINAPI*)(SIZE_T,const UINT64*); + using Reserve=void*(WINAPI*)(void*,SIZE_T,DWORD,DWORD,DWORD); + auto allocate=reinterpret_cast(GetProcAddress(module,"XMemAllocatePhysicalPages")); + auto map=reinterpret_cast(GetProcAddress(module,"XMemMapPhysicalPages")); + auto free_pages=reinterpret_cast(GetProcAddress(module,"XMemFreePhysicalPages")); + auto reserve=reinterpret_cast(GetProcAddress(module,"XMemVirtualAlloc")); + if(!allocate||!map||!free_pages||!reserve)throw std::runtime_error("xmem exports"); + std::array tokens{}; + SIZE_T count=pages; + if(!allocate(0x20400000,&count,tokens.data())||count!=pages) + throw std::runtime_error("allocate physical pages"); + auto guest=static_cast(reserve(nullptr,pages*page,0x20402000,0x23,0x2404)); + if(!guest)throw std::runtime_error("reserve guest pages"); + if(map(guest,pages,tokens.data())!=guest)throw std::runtime_error("map guest pages"); + for(UINT i=0;i(guest); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width=pages*page; + desc.Height=desc.DepthOrArraySize=desc.MipLevels=1; + desc.SampleDesc.Count=1; + desc.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + SIZE_T token=0; + check(reg(device.Get(),address,pages,&token),"shadow register"); + ComPtr imported; + check(place(device.Get(),address,&desc,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&imported)),"shadow place"); + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr queue; + check(device->CreateCommandQueue(&queue_desc,IID_PPV_ARGS(&queue)),"shadow queue"); + ComPtr fence; + check(device->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&fence)),"shadow fence"); + auto readback=compute_fixture::buffer(device.Get(),D3D12_HEAP_TYPE_READBACK,shadow_words*4,D3D12_RESOURCE_STATE_COPY_DEST); + auto observe=[&](UINT pass){ + ComPtr allocator; + check(device->CreateCommandAllocator(queue_desc.Type,IID_PPV_ARGS(&allocator)),"shadow allocator"); + ComPtr list; + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT,0,1,0}; + check(method(device.Get(),73)(device.Get(),list_desc,allocator.Get(),nullptr,IID_PPV_ARGS(&list)),"shadow list"); + list->CopyBufferRegion(readback.Get(),0,imported.Get(),0,shadow_words*4); + check(list->Close(),"shadow close"); + ID3D12CommandList* batch[]={list.Get()}; + queue->ExecuteCommandLists(1,batch); + check(queue->Signal(fence.Get(),pass+1),"shadow signal"); + compute_fixture::wait_for_fence(fence.Get(),pass+1); + D3D12_RANGE range{0,shadow_words*4},empty{}; + void* ptr{}; + check(readback->Map(0,&range,&ptr),"shadow readback"); + auto actual=static_cast(ptr); + UINT good=0; + for(UINT i=0;iUnmap(0,&empty); + return good; + }; + UINT first=observe(0); + // The CPU changes the page. A copy the provider made has to follow it. + for(UINT i=0;i1 && !std::wcscmp(argv[1],L"--shadow")) + return tuxbox_test::frame_main(argc-1,argv+1,"d3d12-buffer-shadow",false,shadow_mode); if(argc>1 && !std::wcscmp(argv[1],L"--remap")) return tuxbox_test::frame_main(argc-1,argv+1,"d3d12-buffer-remap",false,remap); if(argc>1 && !std::wcscmp(argv[1],L"--unmap-alive")) diff --git a/runtime/d3d12/src/device/heap/shadow.rs b/runtime/d3d12/src/device/heap/shadow.rs index f96083c2..5ac1a27e 100644 --- a/runtime/d3d12/src/device/heap/shadow.rs +++ b/runtime/d3d12/src/device/heap/shadow.rs @@ -4,10 +4,13 @@ //! CPU writes are copied in before each submission. GPU writes stay in the copy: //! the CPU and other addresses of the same pages do not see them. //! +//! What the guest held is kept as digests rather than as a copy of it, because +//! a copy would cost as much memory again as the shadow itself. +//! //! From pull request #200 by DrArroway. use super::{ImportedHeap, trace_import_failure}; use crate::commands::page_mapping::ImportPin; -use crate::device::placement::{Digest, Hasher, guarded_copy_available, guarded_copy_read}; +use crate::device::placement::{Digest, Hasher, digest64, guarded_copy_available, guarded_copy_read}; use core::ffi::c_void; use std::cell::UnsafeCell; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; @@ -21,17 +24,49 @@ use windows::Win32::System::Memory::{ use windows::core::Result; const MAX_SHADOW_BYTES: usize = 1 << 30; -const PAGE_STEP: usize = 4096; const CHUNK_BYTES: usize = 64; const BLOCK_BYTES: usize = 65536; const STRIPE_BLOCKS: usize = 8; const PARALLEL_THRESHOLD_BLOCKS: usize = 16; struct ShadowState { - baseline: Vec, + /// What the guest held when the shadow was last synchronised. + guest: GuestState, block_digests: Vec, } +/// The guest's bytes as of the last synchronisation, kept as digests. +/// +/// The shadow has to know which bytes the CPU changed, so that the bytes the +/// GPU wrote in the same range stay. A copy of the range would cost as much +/// memory again as the shadow itself, so each 64-byte chunk is kept as a +/// digest instead. +struct GuestState { + /// The digest of each 64-byte chunk of the guest. + chunks: Vec, +} + +impl GuestState { + fn new(size: usize) -> Result { + let mut chunks = Vec::new(); + chunks.try_reserve_exact(size.div_ceil(CHUNK_BYTES)).map_err(|_| E_OUTOFMEMORY)?; + chunks.resize(size.div_ceil(CHUNK_BYTES), 0); + Ok(Self { chunks }) + } + + /// The bytes these digests stand for. + fn bytes(&self) -> usize { + self.chunks.len() * size_of::() + } + + /// Record the guest's current content, which the shadow now holds. + fn record(&mut self, guest: &[u8]) { + for (digest, chunk) in self.chunks.iter_mut().zip(guest.chunks(CHUNK_BYTES)) { + *digest = digest64(chunk); + } + } +} + /// Private anonymous host copy of committed section-backed guest pages. /// On drivers such as RADV that restrict `VK_EXT_external_memory_host` to /// anonymous userptr pages, `OpenExistingHeapFromAddress*` imports this buffer @@ -60,7 +95,7 @@ struct ShadowTarget { guest_base: u64, shadow_base: usize, size: usize, - baseline_ptr: *mut u8, + chunks_ptr: *mut u64, digests_ptr: *mut Digest, } @@ -103,11 +138,10 @@ impl ShadowPages { if size == 0 || size > MAX_SHADOW_BYTES { return Err(E_INVALIDARG.into()); } - let mut baseline = Vec::new(); - baseline.try_reserve_exact(size).map_err(|_| E_OUTOFMEMORY)?; let block_count = size.div_ceil(BLOCK_BYTES); let mut block_digests = Vec::new(); block_digests.try_reserve_exact(block_count).map_err(|_| E_OUTOFMEMORY)?; + let mut guest = GuestState::new(size)?; // SAFETY: `None` base asks the OS for an anonymous private region of `size` bytes. let shadow_ptr = unsafe { VirtualAlloc(None, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; if shadow_ptr.is_null() { @@ -119,11 +153,15 @@ impl ShadowPages { } // SAFETY: `is_guest_readable` confirmed `guest_base..guest_base + size` is committed and // readable, and `shadow_ptr` holds `size` writable bytes. - let guest = unsafe { core::slice::from_raw_parts(guest_base as *const u8, size) }; - baseline.extend_from_slice(guest); - // SAFETY: `shadow_ptr` holds `size` writable bytes, and `baseline` was just filled with `size` bytes. - unsafe { core::ptr::copy_nonoverlapping(baseline.as_ptr(), shadow_ptr.cast(), size) }; - block_digests.extend(baseline.chunks(BLOCK_BYTES).map(Digest::of)); + let content = unsafe { core::slice::from_raw_parts(guest_base as *const u8, size) }; + // SAFETY: as above; the shadow starts as a copy of the guest. + unsafe { core::ptr::copy_nonoverlapping(content.as_ptr(), shadow_ptr.cast(), size) }; + guest.record(content); + block_digests.extend(content.chunks(BLOCK_BYTES).map(Digest::of)); + // The shadow's copy of the range, and the digests that say what the + // guest held. The copy is what the GPU reads; the digests are what + // tells the CPU's changes from the GPU's. + let held = size as u64 + guest.bytes() as u64 + (block_count * size_of::()) as u64; let shadow_base = guard.0; guard.0 = 0; Ok(Arc::new(Self { @@ -132,8 +170,8 @@ impl ShadowPages { size, pin_live, retired: AtomicBool::new(false), - state: UnsafeCell::new(ShadowState { baseline, block_digests }), - _charge: crate::device::charges::host(crate::device::charges::Category::Shadow, 2 * size as u64), + state: UnsafeCell::new(ShadowState { guest, block_digests }), + _charge: crate::device::charges::host(crate::device::charges::Category::Shadow, held), })) } @@ -157,7 +195,7 @@ impl ShadowPages { guest_base: self.guest_base, shadow_base: self.shadow_base, size: self.size, - baseline_ptr: state.baseline.as_mut_ptr(), + chunks_ptr: state.guest.chunks.as_mut_ptr(), digests_ptr: state.block_digests.as_mut_ptr(), } } @@ -184,10 +222,12 @@ impl ShadowTarget { let block_digest = unsafe { &mut *self.digests_ptr.add(b) }; let copy_and_update = |guest: &[u8], block_digest: &mut Digest| { // SAFETY: `[start..end)` is within `0..self.size` and exclusive to block `b`. - let baseline = unsafe { core::slice::from_raw_parts_mut(self.baseline_ptr.add(start), len) }; + let chunks = unsafe { + core::slice::from_raw_parts_mut(self.chunks_ptr.add(start / CHUNK_BYTES), len.div_ceil(CHUNK_BYTES)) + }; // SAFETY: `start..start + len` lies in the shadow's `size` bytes and belongs to block `b` alone. let shadow = unsafe { core::slice::from_raw_parts_mut((self.shadow_base + start) as *mut u8, len) }; - diff_copy_chunks(guest, baseline, shadow); + diff_copy_chunks(guest, chunks, shadow); *block_digest = Digest::of(guest); }; if guarded { @@ -279,21 +319,20 @@ pub(in crate::device) fn is_guest_readable(address: u64, size: usize) -> bool { true } -/// Skip unchanged 4 KiB pages, then sync only 64-byte chunks where CPU memory -/// diverged from `baseline`, leaving any GPU-written chunks in `shadow` intact. -fn diff_copy_chunks(guest: &[u8], baseline: &mut [u8], shadow: &mut [u8]) -> usize { +/// Sync the 64-byte chunks where CPU memory diverged from the guest as it +/// was, leaving any GPU-written chunks in `shadow` intact. +/// +/// `chunks` holds the digest of each 64-byte chunk of the guest as of the +/// last synchronisation, and is updated here, so the next call sees the guest +/// as it is now. +fn diff_copy_chunks(guest: &[u8], chunks: &mut [u64], shadow: &mut [u8]) -> usize { let mut copied = 0usize; - for ((gp, bp), sp) in guest.chunks(PAGE_STEP).zip(baseline.chunks_mut(PAGE_STEP)).zip(shadow.chunks_mut(PAGE_STEP)) - { - if gp == &*bp { - continue; - } - for ((g, b), s) in gp.chunks(CHUNK_BYTES).zip(bp.chunks_mut(CHUNK_BYTES)).zip(sp.chunks_mut(CHUNK_BYTES)) { - if g != &*b { - s.copy_from_slice(g); - b.copy_from_slice(g); - copied += g.len(); - } + for ((digest, g), s) in chunks.iter_mut().zip(guest.chunks(CHUNK_BYTES)).zip(shadow.chunks_mut(CHUNK_BYTES)) { + let value = digest64(g); + if value != *digest { + s.copy_from_slice(g); + *digest = value; + copied += g.len(); } } copied diff --git a/runtime/d3d12/src/device/placement.rs b/runtime/d3d12/src/device/placement.rs index bb0c1a0c..86a451f7 100644 --- a/runtime/d3d12/src/device/placement.rs +++ b/runtime/d3d12/src/device/placement.rs @@ -36,7 +36,7 @@ mod upload; mod waits; mod writeback; pub(crate) use descriptors::{DescriptorMap, DescriptorRange, HeapViews, PlacedView, Views}; -pub(in crate::device) use digest::{Digest, Hasher}; +pub(in crate::device) use digest::{Digest, Hasher, digest64}; pub(crate) use guarded_copy::recover as recover_guarded_copy; pub(in crate::device) use guarded_copy::{available as guarded_copy_available, read as guarded_copy_read}; pub(super) use planes::{color_plane, console_layout, nv12_pitch}; diff --git a/runtime/d3d12/src/device/placement/check_pool.rs b/runtime/d3d12/src/device/placement/check_pool.rs index 4841ac19..78884a4b 100644 --- a/runtime/d3d12/src/device/placement/check_pool.rs +++ b/runtime/d3d12/src/device/placement/check_pool.rs @@ -65,7 +65,9 @@ impl CheckPool { fn worker_loop(&self) { let mut seen_gen = 0u64; - let mut spares = upload::ByteSpares::default(); + // The workers share one pool of spare buffers, so that the memory they + // hold does not grow with the number of them. + let spares = upload::ByteSpares::shared(); loop { let (items_ptr, len, profile_on) = { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); @@ -78,7 +80,7 @@ impl CheckPool { }; // SAFETY: `check_chunk` keeps `prepared` alive until `remaining == 0`. let items = unsafe { core::slice::from_raw_parts(items_ptr as *const guest_read::PreparedInPlace, len) }; - let result = self.run_worker(items, profile_on, &mut spares); + let result = self.run_worker(items, profile_on, &spares); let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); let job = state.active.as_mut().expect("active job until remaining hits zero"); job.results.push(result); @@ -93,7 +95,7 @@ impl CheckPool { &self, items: &[guest_read::PreparedInPlace], profile_on: bool, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, ) -> WorkerResult { let mut tally = if profile_on { Tally::on() } else { Tally::default() }; let mut changes = Vec::new(); @@ -122,7 +124,7 @@ pub(super) fn check_chunk( gpu: u64, tally: &mut Tally, scratch: &mut guest_read::Scratch, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, ) -> Result> { if textures.is_empty() { return Ok(Vec::new()); diff --git a/runtime/d3d12/src/device/placement/digest.rs b/runtime/d3d12/src/device/placement/digest.rs index 511dacdd..59488d8c 100644 --- a/runtime/d3d12/src/device/placement/digest.rs +++ b/runtime/d3d12/src/device/placement/digest.rs @@ -31,6 +31,32 @@ impl Digest { } } +/// A digest of a short run of bytes, for noticing that it changed. +/// +/// The lanes of [`Digest`] each mix only a quarter of the words, so one of +/// them on its own would miss a change in the others. This mixes every word +/// into one value, and costs less than a [`Digest`] of the same bytes, which +/// matters when a shadow keeps one of these for every 64 bytes it holds. +pub(in crate::device) fn digest64(bytes: &[u8]) -> u64 { + const SECOND: u64 = 0xff51_afd7_ed55_8ccd; + let mut hash = 0x9e37_79b9_7f4a_7c15u64 ^ (bytes.len() as u64); + let mut words = bytes.chunks_exact(8); + for word in &mut words { + let value = u64::from_le_bytes(word.try_into().expect("eight bytes")); + hash = (hash ^ value).wrapping_mul(SECOND).rotate_left(31); + } + let rest = words.remainder(); + if !rest.is_empty() { + let mut last = [0u8; 8]; + last[..rest.len()].copy_from_slice(rest); + hash = (hash ^ u64::from_le_bytes(last)).wrapping_mul(SECOND).rotate_left(31); + } + // A final mix, so that the last word reaches every bit of the result. + hash ^= hash >> 33; + hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53); + hash ^ (hash >> 29) +} + /// Builds the same digest as [`Digest::of`] from pieces, so that a mip which /// spans several host runs is digested where it lies, without joining it. pub(in crate::device) struct Hasher { diff --git a/runtime/d3d12/src/device/placement/guest_read.rs b/runtime/d3d12/src/device/placement/guest_read.rs index f7d35bb5..6aec3f80 100644 --- a/runtime/d3d12/src/device/placement/guest_read.rs +++ b/runtime/d3d12/src/device/placement/guest_read.rs @@ -329,7 +329,7 @@ impl Texture { hit_count: Count, changes: &mut Vec, unmapped: &mut Vec, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, tally: &mut Tally, ) -> Result> { let mut digest_batch = DigestBatch::start(tally); @@ -387,7 +387,7 @@ impl Texture { start_level: usize, hit_count: Count, changes: &mut Vec, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, tally: &mut Tally, ) -> Result> { let mut unmapped = Vec::new(); @@ -446,7 +446,7 @@ impl Texture { fallback: Count, changes: &mut Vec, scratch: &mut Scratch, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, tally: &mut Tally, ) -> Result { let mut all_read = true; @@ -481,7 +481,7 @@ impl Texture { self: &Arc, changes: &mut Vec, scratch: &mut Scratch, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, gpu: u64, tally: &mut Tally, ) -> Result> { @@ -580,7 +580,7 @@ impl Texture { self: &Arc, changes: &mut Vec, scratch: &mut Scratch, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, gpu: u64, tally: &mut Tally, ) -> Result<()> { @@ -591,7 +591,7 @@ impl Texture { self: &Arc, changes: &mut Vec, scratch: &mut Scratch, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, gpu: u64, tally: &mut Tally, allow_cache: bool, @@ -840,7 +840,7 @@ impl PreparedInPlace { pub(super) fn check_in_place( &self, changes: &mut Vec, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, tally: &mut Tally, ) -> Result<()> { let held = self.texture.residency.first() as usize; @@ -1006,7 +1006,7 @@ impl PreparedInPlace { &self, changes: &mut Vec, scratch: &mut Scratch, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, gpu: u64, tally: &mut Tally, ) -> Result<()> { diff --git a/runtime/d3d12/src/device/placement/remapped.rs b/runtime/d3d12/src/device/placement/remapped.rs index 42fb7b0b..c564cd84 100644 --- a/runtime/d3d12/src/device/placement/remapped.rs +++ b/runtime/d3d12/src/device/placement/remapped.rs @@ -65,7 +65,7 @@ impl Texture { pub(super) fn check_gpu_pages( self: &Arc, changes: &mut Vec, - spares: &mut upload::ByteSpares, + spares: &upload::ByteSpares, tally: &mut Tally, ) -> Result { let Some(pages) = self.mapped_pages() else { return Ok(false) }; diff --git a/runtime/d3d12/src/device/placement/spares.rs b/runtime/d3d12/src/device/placement/spares.rs index d197a6e4..d49ee3e7 100644 --- a/runtime/d3d12/src/device/placement/spares.rs +++ b/runtime/d3d12/src/device/placement/spares.rs @@ -4,15 +4,55 @@ //! as the rest of the publication's recording. On an RTX 5090 (620.70, GE-Proton //! 11-14) creating a 925 MiB one with its allocator and list took 52-67 ms, and //! the title's largest publications are that size. -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; /// How long an unused spare is kept. pub(super) const RETAIN: Duration = Duration::from_secs(2); -/// The most bytes kept in spares for one queue. Idle readback buffers sit in -/// system memory beside the in-flight ones (`flight`); ProjectScarlett's -/// queues kept gigabytes of them at the loading screen. +/// The most bytes the pools keep for reuse, over all of them. Idle readback +/// buffers sit in system memory beside the in-flight ones (`flight`); +/// ProjectScarlett's queues kept gigabytes of them at the loading screen. pub(super) const RETAIN_BYTES: u64 = 256 << 20; + +/// What the pools may keep for reuse, and what they keep now. +/// +/// The pools of every queue share one budget, because a title that has many +/// queues would otherwise keep a budget's worth of buffers for each of them. +pub(super) struct Budget { + kept: AtomicU64, + limit: u64, +} + +impl Budget { + /// The budget the pools share. + pub(super) fn shared() -> Arc { + static SHARED: OnceLock> = OnceLock::new(); + Arc::clone(SHARED.get_or_init(|| Arc::new(Budget { kept: AtomicU64::new(0), limit: RETAIN_BYTES }))) + } + + /// A budget of its own, for a pool that must not share one. + #[cfg(test)] + pub(super) fn own(limit: u64) -> Arc { + Arc::new(Budget { kept: AtomicU64::new(0), limit }) + } + + /// The bytes the pools keep now. + fn kept(&self) -> u64 { + self.kept.load(Ordering::Relaxed) + } + + /// Record bytes the pools keep. + fn kept_by(&self, bytes: u64) { + self.kept.fetch_add(bytes, Ordering::Relaxed); + } + + /// Record bytes the pools gave back. + fn freed(&self, bytes: u64) { + self.kept.fetch_sub(bytes, Ordering::Relaxed); + } +} + /// Sizes are rounded up to an eighth of their power of two so that /// publications of similar size share spares. pub(super) fn rounded(size: u64) -> Option { @@ -26,20 +66,29 @@ fn fits(spare: u64, size: u64) -> bool { spare >= size && spare <= size.saturating_mul(2).max(size.saturating_add(4 << 20)) } -pub(super) struct Spares(Mutex>); +pub(super) struct Spares { + items: Mutex>, + budget: Arc, +} impl Default for Spares { fn default() -> Self { - Self(Mutex::new(Vec::new())) + Self { items: Mutex::new(Vec::new()), budget: Budget::shared() } } } impl Spares { + /// A pool with a budget of its own. + #[cfg(test)] + pub(super) fn with_budget(budget: Arc) -> Self { + Self { items: Mutex::new(Vec::new()), budget } + } + /// The smallest spare that fits `size`, and its size. pub(super) fn take(&self, size: u64, now: Instant) -> Option<(T, u64)> { let (taken, expired) = { - let mut spares = super::lock(&self.0); - let expired = Self::expire(&mut spares, now); + let mut spares = super::lock(&self.items); + let expired = self.expire(&mut spares, now); let best = spares .iter() .enumerate() @@ -48,6 +97,9 @@ impl Spares { .map(|(index, _)| index); (best.map(|index| spares.swap_remove(index)), expired) }; + if let Some((_, size, _)) = taken { + self.budget.freed(size); + } // Released outside the lock: freeing a large buffer takes a while. drop(expired); taken.map(|(item, size, _)| (item, size)) @@ -55,33 +107,34 @@ impl Spares { pub(super) fn put(&self, item: T, size: u64, now: Instant) { let released = { - let mut spares = super::lock(&self.0); - let mut released = Self::expire(&mut spares, now); - // Newest first: keep the newest spares within the budget. + let mut spares = super::lock(&self.items); + let released = self.expire(&mut spares, now); + // Newest first: the newest spares are the ones a queue asks for. spares.insert(0, (item, size, now)); - let mut kept = 0u64; - let mut index = 0; - while index < spares.len() { - let total = kept.saturating_add(spares[index].1); - if total > RETAIN_BYTES { - released.push(spares.remove(index)); - } else { - kept = total; - index += 1; - } + self.budget.kept_by(size); + // The oldest go when all the pools together hold too much. + while self.budget.kept() > self.budget.limit { + let Some(index) = spares.len().checked_sub(1) else { break }; + let (_, size, _) = spares.remove(index); + self.budget.freed(size); } released }; drop(released); } - fn expire(spares: &mut Vec<(T, u64, Instant)>, now: Instant) -> Vec<(T, u64, Instant)> { - spares.extract_if(.., |(_, _, at)| now.saturating_duration_since(*at) >= RETAIN).collect() + fn expire(&self, spares: &mut Vec<(T, u64, Instant)>, now: Instant) -> Vec<(T, u64, Instant)> { + let expired = + spares.extract_if(.., |(_, _, at)| now.saturating_duration_since(*at) >= RETAIN).collect::>(); + for (_, size, _) in &expired { + self.budget.freed(*size); + } + expired } #[cfg(test)] pub(super) fn sizes(&self) -> Vec { - let mut sizes: Vec<_> = super::lock(&self.0).iter().map(|(_, size, _)| *size).collect(); + let mut sizes: Vec<_> = super::lock(&self.items).iter().map(|(_, size, _)| *size).collect(); sizes.sort_unstable(); sizes } @@ -94,70 +147,79 @@ impl Spares { /// Without this a queue had a buffer for every batch submitted and not yet /// published. The worker is slower than the title's submissions when it lags, /// and nothing bounded their number. -pub(super) struct Live(Mutex, u64, Instant)>>); +pub(super) struct Live { + items: Mutex, u64, Instant)>>, + budget: Arc, +} impl Default for Live { fn default() -> Self { - Self(Mutex::new(Vec::new())) + Self { items: Mutex::new(Vec::new()), budget: Budget::shared() } } } impl Live { + /// A pool with a budget of its own. + #[cfg(test)] + pub(super) fn with_budget(budget: Arc) -> Self { + Self { items: Mutex::new(Vec::new()), budget } + } + /// The smallest buffer that fits `size`, in use or not, and its size. pub(super) fn share(&self, size: u64, now: Instant) -> Option<(Arc, u64)> { let (found, expired) = { - let mut live = super::lock(&self.0); + let mut live = super::lock(&self.items); let found = live.iter_mut().filter(|(_, held, _)| fits(*held, size)).min_by_key(|(_, held, _)| *held).map( |entry| { entry.2 = now; (entry.0.clone(), entry.1) }, ); - (found, Self::expire(&mut live, now)) + (found, self.expire(&mut live, now)) }; drop(expired); found } pub(super) fn add(&self, buffer: &Arc, size: u64, now: Instant) { - super::lock(&self.0).push((buffer.clone(), size, now)); + super::lock(&self.items).push((buffer.clone(), size, now)); + self.budget.kept_by(size); } /// A publication has finished with `buffer`. pub(super) fn done(&self, buffer: Arc, now: Instant) { let expired = { - let mut live = super::lock(&self.0); + let mut live = super::lock(&self.items); if let Some(entry) = live.iter_mut().find(|entry| Arc::ptr_eq(&entry.0, &buffer)) { entry.2 = now; } drop(buffer); - Self::expire(&mut live, now) + self.expire(&mut live, now) }; drop(expired); } /// Takes out the buffers that no publication uses and that are too old or /// over the budget, newest kept first. - fn expire(live: &mut Vec<(Arc, u64, Instant)>, now: Instant) -> Vec<(Arc, u64, Instant)> { + fn expire(&self, live: &mut Vec<(Arc, u64, Instant)>, now: Instant) -> Vec<(Arc, u64, Instant)> { live.sort_by_key(|entry| std::cmp::Reverse(entry.2)); - let mut kept = 0u64; - live.extract_if(.., |(buffer, size, at)| { - if Arc::strong_count(buffer) > 1 { - return false; - } - let total = kept.saturating_add(*size); - if now.saturating_duration_since(*at) >= RETAIN || total > RETAIN_BYTES { - return true; - } - kept = total; - false - }) - .collect() + let expired = live + .extract_if(.., |(buffer, _size, at)| { + if Arc::strong_count(buffer) > 1 { + return false; + } + now.saturating_duration_since(*at) >= RETAIN || self.budget.kept() > self.budget.limit + }) + .collect::>(); + for (_, size, _) in &expired { + self.budget.freed(*size); + } + expired } #[cfg(test)] pub(super) fn sizes(&self) -> Vec { - let mut sizes: Vec<_> = super::lock(&self.0).iter().map(|(_, size, _)| *size).collect(); + let mut sizes: Vec<_> = super::lock(&self.items).iter().map(|(_, size, _)| *size).collect(); sizes.sort_unstable(); sizes } diff --git a/runtime/d3d12/src/device/placement/upload.rs b/runtime/d3d12/src/device/placement/upload.rs index 2dca44fb..f6899702 100644 --- a/runtime/d3d12/src/device/placement/upload.rs +++ b/runtime/d3d12/src/device/placement/upload.rs @@ -4,8 +4,9 @@ use super::residency::Held; use super::{Digest, Texture, committed_in, lock}; use crate::submit_profile::{Step, Tally}; use core::mem::ManuallyDrop; +use std::collections::VecDeque; use std::sync::atomic::{AtomicU64, Ordering}; -use std::{collections::VecDeque, sync::Arc}; +use std::sync::{Arc, Mutex, OnceLock}; use windows::Win32::Foundation::{E_FAIL, E_INVALIDARG, E_OUTOFMEMORY, HANDLE}; use windows::Win32::Graphics::{Direct3D12::*, Dxgi::Common::DXGI_SAMPLE_DESC}; use windows::core::{HRESULT, Interface, Result}; @@ -35,9 +36,12 @@ pub(super) struct Upload { /// Staging bytes of uploads the transfer queue has not released. static IN_FLIGHT: AtomicU64 = AtomicU64::new(0); +/// Staging bytes kept for reuse after their copies finished. +static IDLE: AtomicU64 = AtomicU64::new(0); +/// The bytes the upload buffers hold, in flight and kept for reuse. pub(super) fn staging_in_flight() -> u64 { - IN_FLIGHT.load(Ordering::Relaxed) + IN_FLIGHT.load(Ordering::Relaxed) + IDLE.load(Ordering::Relaxed) } impl Upload { @@ -64,7 +68,10 @@ pub(super) enum Pending { /// Completed uploads kept for reuse, by their buffers' total size. The /// first flush can queue gigabytes; only this much stays allocated after it. -const IDLE_BYTES: u64 = 256 << 20; +/// The bytes the completed uploads keep for reuse. +fn idle_bytes() -> u64 { + IDLE_BYTES +} /// Buffer sizes are rounded up so that later batches of similar size fit. fn upload_capacity(size: u64) -> Option { @@ -73,45 +80,90 @@ fn upload_capacity(size: u64) -> Option { /// The most bytes, and buffers, kept from uploaded changes for later ones. const SPARE_BYTES: usize = 64 << 20; +/// The bytes the completed uploads keep for reuse. +const IDLE_BYTES: u64 = 256 << 20; const SPARE_BUFFERS: usize = 64; /// Buffers that held a change's bytes, oldest first, for the next change. -#[derive(Default)] -pub(super) struct ByteSpares(Vec>); +/// +/// The pool is behind a lock, so that everything that reads title bytes can +/// share one budget of buffers. A worker that holds a buffer has taken it out +/// of the pool, so the lock is only held while one is taken or given back. +pub(super) struct ByteSpares { + pool: Arc>, +} + +struct Pool { + buffers: Vec>, + /// The most bytes the pool keeps. + cap: usize, +} + +/// The pool every reader shares, so that the memory it holds does not grow +/// with the number of workers. +static SHARED: OnceLock = OnceLock::new(); + +impl Default for ByteSpares { + fn default() -> Self { + Self::with_cap(SPARE_BYTES) + } +} impl ByteSpares { + /// A pool of its own, keeping at most `cap` bytes. + pub(super) fn with_cap(cap: usize) -> Self { + Self { pool: Arc::new(Mutex::new(Pool { buffers: Vec::new(), cap })) } + } + + /// The pool every reader shares. + pub(super) fn shared() -> Self { + Self { pool: Arc::clone(&SHARED.get_or_init(|| ByteSpares::with_cap(SPARE_BYTES)).pool) } + } + /// An empty buffer that holds `bytes` without growing: the smallest spare /// that is not much larger, or a new one. - pub(super) fn take(&mut self, bytes: usize) -> Result> { + pub(super) fn take(&self, bytes: usize) -> Result> { let most = bytes.saturating_mul(2).max(bytes.saturating_add(64 << 10)); - let fits = (0..self.0.len()) - .filter(|&i| (bytes..=most).contains(&self.0[i].capacity())) - .min_by_key(|&i| self.0[i].capacity()); + let mut pool = self.pool.lock().unwrap_or_else(|e| e.into_inner()); + let fits = (0..pool.buffers.len()) + .filter(|&i| (bytes..=most).contains(&pool.buffers[i].capacity())) + .min_by_key(|&i| pool.buffers[i].capacity()); if let Some(index) = fits { - return Ok(self.0.remove(index)); + return Ok(pool.buffers.remove(index)); } let mut buffer = Vec::new(); buffer.try_reserve_exact(bytes).map_err(|_| E_OUTOFMEMORY)?; Ok(buffer) } - pub(super) fn put(&mut self, mut buffer: Vec) { + pub(super) fn put(&self, mut buffer: Vec) { buffer.clear(); - if buffer.capacity() > SPARE_BYTES || self.0.try_reserve(1).is_err() { + let mut pool = self.pool.lock().unwrap_or_else(|e| e.into_inner()); + if buffer.capacity() > pool.cap || pool.buffers.try_reserve(1).is_err() { return; } - self.0.push(buffer); - while self.kept() > SPARE_BYTES || self.count() > SPARE_BUFFERS { - self.0.remove(0); + pool.buffers.push(buffer); + while pool.kept() > pool.cap || pool.buffers.len() > SPARE_BUFFERS { + pool.buffers.remove(0); } } - fn kept(&self) -> usize { - self.0.iter().map(Vec::capacity).sum() + /// The bytes the pool holds. + #[cfg(test)] + pub(super) fn kept(&self) -> usize { + self.pool.lock().unwrap_or_else(|e| e.into_inner()).kept() } - fn count(&self) -> usize { - self.0.len() + /// The buffers the pool holds. + #[cfg(test)] + pub(super) fn count(&self) -> usize { + self.pool.lock().unwrap_or_else(|e| e.into_inner()).buffers.len() + } +} + +impl Pool { + fn kept(&self) -> usize { + self.buffers.iter().map(Vec::capacity).sum() } } @@ -158,7 +210,8 @@ impl Transfer { meter: None, changes: Vec::new(), check_queue: Vec::new(), - spares: ByteSpares::default(), + // One pool of spare buffers, shared with the workers that read title bytes. + spares: ByteSpares::shared(), offsets: Vec::new(), reader_waits: Vec::new(), #[cfg(test)] @@ -222,8 +275,7 @@ impl Transfer { let parallel = false; if parallel { for chunk in check_queue.chunks(1024) { - let chunk_changes = - super::check_pool::check_chunk(chunk, gpu, tally, &mut self.scratch, &mut self.spares)?; + let chunk_changes = super::check_pool::check_chunk(chunk, gpu, tally, &mut self.scratch, &self.spares)?; bytes += chunk_changes.iter().map(|c| c.bytes.len()).sum::(); changes.extend(chunk_changes); // All of a texture's mips stay in one upload. @@ -235,7 +287,7 @@ impl Transfer { } else { for texture in &check_queue { let found = changes.len(); - texture.changed(&mut changes, &mut self.scratch, &mut self.spares, gpu, tally)?; + texture.changed(&mut changes, &mut self.scratch, &self.spares, gpu, tally)?; bytes += changes[found..].iter().map(|change: &Change| change.bytes.len()).sum::(); // All of a texture's mips stay in one upload. if bytes >= BATCH_BYTES { @@ -331,19 +383,23 @@ impl Transfer { Ok(()) } - /// Keeps a completed upload for reuse, up to `IDLE_BYTES` of buffers. + /// Keeps a completed upload for reuse, up to what the host can spare. fn recycle(&mut self, mut upload: Upload) { upload.release(); if self.idle.try_reserve(1).is_err() { return; } + let capacity = upload.capacity; self.idle.push(upload); + IDLE.fetch_add(capacity, Ordering::Relaxed); let mut idle: u64 = self.idle.iter().map(|u| u.capacity).sum(); - while idle > IDLE_BYTES { + while idle > idle_bytes() { let Some(largest) = (0..self.idle.len()).max_by_key(|&i| self.idle[i].capacity) else { break; }; - idle -= self.idle.swap_remove(largest).capacity; + let capacity = self.idle.swap_remove(largest).capacity; + idle -= capacity; + IDLE.fetch_sub(capacity, Ordering::Relaxed); } } @@ -404,6 +460,8 @@ impl Transfer { impl Drop for Transfer { fn drop(&mut self) { + // The buffers kept for reuse go with the transfer. + IDLE.fetch_sub(self.idle.iter().map(|upload| upload.capacity).sum::(), Ordering::Relaxed); if let Some((tick, _)) = self.pending.back() { // Resignal in case the original signal failed after ExecuteCommandLists. // SAFETY: the queue and fence are this transfer's own and live; the calls read a value and take diff --git a/runtime/d3d12/src/tests/device/heap_shadow.rs b/runtime/d3d12/src/tests/device/heap_shadow.rs index 8410f459..5c5f1bb0 100644 --- a/runtime/d3d12/src/tests/device/heap_shadow.rs +++ b/runtime/d3d12/src/tests/device/heap_shadow.rs @@ -49,8 +49,10 @@ impl Drop for MappedPage { #[test] fn diff_copy_chunks_preserves_untouched_gpu_bytes() { let mut guest = vec![0u8; 8192]; - let mut baseline = vec![0u8; 8192]; let mut shadow = vec![0u8; 8192]; + // The shadow holds the guest as it was, so nothing is out of date yet. + let mut state = GuestState::new(guest.len()).expect("state"); + state.record(&guest); // Page 0 [0..4096] stays clean on CPU while holding GPU writes. // Page 1 [4096..8192] sees CPU writes in chunk 2 [4224..4288], keeping chunk 1 [4160..4224] GPU writes. @@ -58,13 +60,34 @@ fn diff_copy_chunks_preserves_untouched_gpu_bytes() { shadow[4160..4224].fill(0xAA); guest[4224..4288].fill(0x55); - let copied = diff_copy_chunks(&guest, &mut baseline, &mut shadow); + let copied = diff_copy_chunks(&guest, &mut state.chunks, &mut shadow); assert_eq!(copied, 64); assert!(shadow[0..64].iter().all(|&b| b == 0)); assert!(shadow[64..128].iter().all(|&b| b == 0x99)); assert!(shadow[4160..4224].iter().all(|&b| b == 0xAA)); assert!(shadow[4224..4288].iter().all(|&b| b == 0x55)); - assert!(baseline[4224..4288].iter().all(|&b| b == 0x55)); + + // A second pass finds nothing new to copy: the guest has not changed since. + let copied = diff_copy_chunks(&guest, &mut state.chunks, &mut shadow); + assert_eq!(copied, 0); +} + +#[test] +fn diff_copy_chunks_copies_again_after_the_guest_returns_to_an_earlier_value() { + let mut guest = vec![0u8; 8192]; + let mut shadow = vec![0u8; 8192]; + let mut state = GuestState::new(guest.len()).expect("state"); + state.record(&guest); + + guest[64..128].fill(0x55); + assert_eq!(diff_copy_chunks(&guest, &mut state.chunks, &mut shadow), 64); + assert!(shadow[64..128].iter().all(|&b| b == 0x55)); + + // The guest returns to an earlier value, which is a change again, so the + // chunk is copied over what the shadow holds. + guest[64..128].fill(0); + assert_eq!(diff_copy_chunks(&guest, &mut state.chunks, &mut shadow), 64); + assert!(shadow[64..128].iter().all(|&b| b == 0)); } #[test] diff --git a/runtime/d3d12/src/tests/device/placement/check_pool.rs b/runtime/d3d12/src/tests/device/placement/check_pool.rs index ebceed72..75f783a7 100644 --- a/runtime/d3d12/src/tests/device/placement/check_pool.rs +++ b/runtime/d3d12/src/tests/device/placement/check_pool.rs @@ -39,8 +39,8 @@ fn check_chunk_collects_all_changes_and_merges_profile() { (0..count).map(|i| Texture::new(&device, &images, first + i as u64 * stride, &desc, None).unwrap()).collect(); let mut tally = Tally::on(); let mut scratch = guest_read::Scratch::default(); - let mut spares = upload::ByteSpares::default(); - let changes = check_chunk(&textures, 0, &mut tally, &mut scratch, &mut spares).unwrap(); + let spares = upload::ByteSpares::default(); + let changes = check_chunk(&textures, 0, &mut tally, &mut scratch, &spares).unwrap(); assert_eq!(changes.len(), count); assert_eq!(tally.units(Step::Digest).0, count as u64); unsafe { VirtualFree(mem, 0, MEM_RELEASE) }.unwrap(); @@ -142,8 +142,8 @@ fn check_chunk_runs_xmem_access_only_on_caller_thread() { let mut tally = Tally::on(); let mut scratch = guest_read::Scratch::default(); - let mut spares = upload::ByteSpares::default(); - let changes = check_chunk(&textures, 0, &mut tally, &mut scratch, &mut spares).unwrap(); + let spares = upload::ByteSpares::default(); + let changes = check_chunk(&textures, 0, &mut tally, &mut scratch, &spares).unwrap(); assert_eq!(changes.len(), count); assert_eq!(ACCESS_CALLS.load(Ordering::Acquire), count); assert_eq!(RELEASE_CALLS.load(Ordering::Acquire), count); @@ -250,8 +250,8 @@ fn check_chunk_reuses_cached_runs_and_retries_active_mapping_state() { let _ = texture.unwritten(0, &mut tally); } let mut scratch = guest_read::Scratch::default(); - let mut spares = upload::ByteSpares::default(); - let initial = check_chunk(&textures, 0, &mut tally, &mut scratch, &mut spares).unwrap(); + let spares = upload::ByteSpares::default(); + let initial = check_chunk(&textures, 0, &mut tally, &mut scratch, &spares).unwrap(); assert_eq!(initial.len(), count); assert_eq!(ACCESS_CALLS.load(Ordering::Acquire), count); assert_eq!(RELEASE_CALLS.load(Ordering::Acquire), count); @@ -259,13 +259,13 @@ fn check_chunk_reuses_cached_runs_and_retries_active_mapping_state() { super::super::lock(&change.texture.contents).previous[change.level] = Some(change.digest); } - let cached = check_chunk(&textures, 0, &mut tally, &mut scratch, &mut spares).unwrap(); + let cached = check_chunk(&textures, 0, &mut tally, &mut scratch, &spares).unwrap(); assert_eq!(cached.len(), 0); assert_eq!(ACCESS_CALLS.load(Ordering::Acquire), count, "second parallel chunk skips XMem access"); assert_eq!(RELEASE_CALLS.load(Ordering::Acquire), count, "second parallel chunk skips XMem release"); unsafe { *(first as *mut u8) ^= 0x55 }; - let changed = check_chunk(&textures, 0, &mut tally, &mut scratch, &mut spares).unwrap(); + let changed = check_chunk(&textures, 0, &mut tally, &mut scratch, &spares).unwrap(); assert_eq!(changed.len(), 1); assert_eq!(ACCESS_CALLS.load(Ordering::Acquire), count, "mutation found on cached workers without XMem"); for change in &changed { @@ -273,7 +273,7 @@ fn check_chunk_reuses_cached_runs_and_retries_active_mapping_state() { } TEST_STATE.store(1, Ordering::Release); - let retried = check_chunk(&textures, 0, &mut tally, &mut scratch, &mut spares).unwrap(); + let retried = check_chunk(&textures, 0, &mut tally, &mut scratch, &spares).unwrap(); assert_eq!(retried.len(), 0); assert_eq!(ACCESS_CALLS.load(Ordering::Acquire), 2 * count, "active mapping state retries sequentially on caller"); assert_eq!(WRONG_THREAD_ACCESS.load(Ordering::Acquire), 0); diff --git a/runtime/d3d12/src/tests/device/placement/spares.rs b/runtime/d3d12/src/tests/device/placement/spares.rs index 32c759ef..ca1798c0 100644 --- a/runtime/d3d12/src/tests/device/placement/spares.rs +++ b/runtime/d3d12/src/tests/device/placement/spares.rs @@ -4,7 +4,7 @@ const MIB: u64 = 1 << 20; #[test] fn a_returned_spare_serves_the_next_publication_of_its_size() { - let spares = Spares::default(); + let spares = Spares::with_budget(Budget::own(RETAIN_BYTES)); let now = Instant::now(); assert!(spares.take(225 * MIB, now).is_none()); spares.put("large", rounded(225 * MIB).unwrap(), now); @@ -15,7 +15,7 @@ fn a_returned_spare_serves_the_next_publication_of_its_size() { #[test] fn the_smallest_fitting_spare_is_taken_and_a_small_publication_leaves_a_large_one() { - let spares = Spares::default(); + let spares = Spares::with_budget(Budget::own(RETAIN_BYTES)); let now = Instant::now(); for size in [128 * MIB, MIB, 2 * MIB] { spares.put(size, size, now); @@ -28,7 +28,7 @@ fn the_smallest_fitting_spare_is_taken_and_a_small_publication_leaves_a_large_on #[test] fn unused_spares_are_released_and_the_budget_is_kept() { - let spares = Spares::default(); + let spares = Spares::with_budget(Budget::own(RETAIN_BYTES)); let start = Instant::now(); spares.put(0, 64 * MIB, start); spares.put(1, 4 * MIB, start + RETAIN / 2); @@ -54,7 +54,7 @@ fn sizes_are_rounded_to_an_eighth_of_their_power_of_two() { #[test] fn a_buffer_in_use_is_shared_and_idle_ones_are_released() { - let live = Live::default(); + let live = Live::with_budget(Budget::own(RETAIN_BYTES)); let start = Instant::now(); assert!(live.share(128 * MIB, start).is_none()); let first = Arc::new("large"); diff --git a/runtime/d3d12/src/tests/device/placement/upload.rs b/runtime/d3d12/src/tests/device/placement/upload.rs index e4e18612..c059ec96 100644 --- a/runtime/d3d12/src/tests/device/placement/upload.rs +++ b/runtime/d3d12/src/tests/device/placement/upload.rs @@ -173,7 +173,7 @@ fn completed_uploads_lend_their_buffer_to_the_next_change() { #[test] fn a_changes_bytes_are_lent_to_the_next_change() { const MIP: usize = 8 << 20; - let mut spares = super::ByteSpares::default(); + let spares = super::ByteSpares::default(); let first = spares.take(MIP).unwrap(); assert!(first.is_empty() && first.capacity() >= MIP); let at = first.as_ptr(); diff --git a/tools/check_d3d12_regressions.py b/tools/check_d3d12_regressions.py index 605b595c..29871872 100644 --- a/tools/check_d3d12_regressions.py +++ b/tools/check_d3d12_regressions.py @@ -44,6 +44,7 @@ "indirect": ("d3d12-indirect", (), "d3d12-indirect", ("list=59", "words=64/64")), "indirect-scarlett": ("d3d12-indirect", ("--scarlett",), "d3d12-indirect", ("list=61", "words=64/64")), "buffer-remap": ("d3d12-buffer-import", ("--remap",), "d3d12-buffer-remap", ("words=1024/1024", "identical=1", "replacement=1", "cpu-reserved=1")), + "buffer-shadow": ("d3d12-buffer-import", ("--shadow",), "d3d12-buffer-shadow", ("words=262144/262144", "passes=2")), "buffer-layout": ("d3d12-buffer-import", ("--layout",), "d3d12-buffer-layout", ("slot=133", "words=512/512", "VA-offsets=0,4")), "buffer-import": ("d3d12-buffer-import", (), "d3d12-buffer-import", ("pages=2", "words=1536/1536", "passes=2", "aliases=2")), "buffer-import-reject": ("d3d12-buffer-import", ("--reject",), "d3d12-buffer-import-reject", ("rejected=1",)), @@ -56,7 +57,7 @@ # These measure what a host's drivers do with views at 16-byte offsets. They # run only when named: `tuxbox.py check` leaves them out. MEASURED = ("cbv-views", "root-cbv-graphics", "root-cbv-mesh") -DEFAULT = tuple(name for name in CASES if name not in MEASURED and name not in ("root-cbv-window", "root-cbv-offsets", "alias-deferred", "copy-resource", "indirect-scarlett", "mesh", "buffer-import", "buffer-import-reject", "buffer-layout", "buffer-remap", "buffer-unmap-alive", "buffer-unmap-released")) +DEFAULT = tuple(name for name in CASES if name not in MEASURED and name not in ("root-cbv-window", "root-cbv-offsets", "alias-deferred", "copy-resource", "indirect-scarlett", "mesh", "buffer-import", "buffer-import-reject", "buffer-layout", "buffer-remap", "buffer-shadow", "buffer-unmap-alive", "buffer-unmap-released")) # These run with the constant-buffer settings `tuxbox.py run` gives a game. The # other cases keep vkd3d-proton's defaults. LAUNCHER_CBV = ("root-cbv-offsets", "root-cbv-graphics", "root-cbv-mesh") @@ -217,7 +218,7 @@ def main(argv=None): "dxil.dll":a.compiler_dir/"dxil.dll", "wine":wine,"wineserver":files/"bin/wineserver"} artifacts.update({CASES[c][0]+".exe":a.build_dir/(CASES[c][0]+".exe") for c in selected}) - if "buffer-remap" in selected: + if "buffer-remap" in selected or "buffer-shadow" in selected: if not a.xmem: ap.error("buffer-remap needs --xmem") artifacts["xmem.dll"]=a.xmem