From 58815f7c3f3c0e17df5cb70f80b33c9ac9a6a319 Mon Sep 17 00:00:00 2001 From: BBareth <179921368+BBareth@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:32:00 +0100 Subject: [PATCH] D3D12.X: reuse the command objects and readback buffers of texture downloads Texture download preparation repeatedly creates the same D3D12 objects during streaming. Reuse each allocator, command list and private fence by device and queue type. Reuse committed readback buffers separately by device and 64 KiB-rounded size. Return objects only after their private fence confirms GPU completion. Cap idle storage at 1,024 command sets and 1 GiB of readback buffers. Each idle entry owns a device reference, so its raw device address cannot be reused while the entry is cached. Assisted-by: Codex (GPT-6) --- crates/xcl/src/hle/d3d12x/real.rs | 16 ++ crates/xcl/src/hle/d3d12x/title_textures.rs | 285 +++++++++++++++++--- 2 files changed, 260 insertions(+), 41 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e70e3d9e85..b20e8b6b5b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4811,6 +4811,22 @@ unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { } creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]); +/// Download fences only notify XCL that a copy is done. Their owners manage their lifetime. +pub(super) unsafe fn create_download_fence(dev: &ID3D12Device) -> windows::core::Result { + let raw = dev.as_raw(); + if !is_ext(vt(raw) as usize) { + return dev.CreateFence(0, D3D12_FENCE_FLAG_NONE); + } + // Skip the title fence registry, which holds another reference until process exit. + let mut out = std::ptr::null_mut(); + let iid = pc_iid(Kind::Fence); + windows::core::HRESULT(dev_create_fence_pc(raw, 0, D3D12_FENCE_FLAG_NONE.0 as usize, &iid, &mut out)).ok()?; + if out.is_null() { + return Err(windows::core::Error::from_hresult(windows::core::HRESULT(crate::util::E_FAIL))); + } + Ok(ID3D12Fence::from_raw(out)) +} + /// fences created through the device (AddRef'd: they are released at the end only) /// (a read-write lock: `is_fence` reads it on every queue call, and `end_title` reads it with /// the title's threads suspended – a reader that holds it then blocks no other reader) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..4da8a1022c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -3652,13 +3652,98 @@ fn validate_download_layout( Ok((out, total)) } +const DOWNLOAD_POOL_SETS: usize = 1024; +const DOWNLOAD_POOL_BYTES: u64 = 1 << 30; + +fn download_buffer_size(bytes: usize) -> Option { + (bytes as u64).max(1).checked_next_multiple_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64) +} + +struct DownloadCommands { + graphics: ID3D12GraphicsCommandList, + allocator: ID3D12CommandAllocator, + fence: ID3D12Fence, + fence_value: u64, +} + +/// Idle command sets, keyed by device and queue type, and readbacks, keyed by device and size. +struct DownloadPool { + sets: Vec<((usize, i32), S)>, + buffers: BTreeMap<(usize, u64), Vec>, + buffer_bytes: u64, +} + +impl DownloadPool { + const fn new() -> Self { + Self { sets: Vec::new(), buffers: BTreeMap::new(), buffer_bytes: 0 } + } + + fn take(&mut self, device: usize, queue_type: i32, size: u64) -> (Option, Option) { + let set = self.sets.iter().rposition(|(key, _)| *key == (device, queue_type)) + .map(|i| self.sets.swap_remove(i).1); + let buffer = if let std::collections::btree_map::Entry::Occupied(mut bucket) = self.buffers.entry((device, size)) { + let buffer = bucket.get_mut().pop(); + if bucket.get().is_empty() { + bucket.remove(); + } + self.buffer_bytes -= size; + buffer + } else { + None + }; + (set, buffer) + } + + // Return rejected entries to the caller for destruction outside the pool lock. + /// Every idle readback buffer, for the caller to release outside the pool's lock. + fn drain_buffers(&mut self) -> Vec { + self.buffer_bytes = 0; + std::mem::take(&mut self.buffers).into_values().flatten().collect() + } + + fn put(&mut self, device: usize, queue_type: i32, size: u64, mut set: Option, buffer: B) + -> (Option, Option) + { + if self.sets.len() < DOWNLOAD_POOL_SETS { + if let Some(set) = set.take() { + self.sets.push(((device, queue_type), set)); + } + } + if size <= DOWNLOAD_POOL_BYTES - self.buffer_bytes { + self.buffers.entry((device, size)).or_default().push(buffer); + self.buffer_bytes += size; + (set, None) + } else { + (set, Some(buffer)) + } + } +} + +// Each entry owns a device reference so its address cannot be reused while the entry is idle. +/// Runs `create`; when it fails for lack of memory, `reclaim` runs and `create` gets one more try. +/// The pool's idle readback buffers can be the memory a buffer of another size needs. +fn retry_after_reclaim(mut create: impl FnMut() -> Result, out_of_memory: impl Fn(&E) -> bool, reclaim: impl FnOnce()) -> Result { + match create() { + Err(e) if out_of_memory(&e) => { + reclaim(); + create() + } + result => result, + } +} + +static DOWNLOAD_POOL: Mutex> = + Mutex::new(DownloadPool::new()); + struct DownloadObjects { _source: ID3D12Resource, readback: ID3D12Resource, - _allocator: ID3D12CommandAllocator, + readback_size: u64, + commands: DownloadCommands, list: ID3D12CommandList, _queue: ID3D12CommandQueue, - _fence_hold: ID3D12Fence, + device: ID3D12Device, + queue_type: i32, } /// A closed command list and every object it may reference. The caller must hold its state/order @@ -3671,9 +3756,9 @@ pub(super) struct TextureDownloadPlan { tex: Arc, source: ID3D12Resource, readback: ID3D12Resource, - allocator: ID3D12CommandAllocator, + readback_size: u64, + commands: DownloadCommands, list: ID3D12CommandList, - fence: ID3D12Fence, footprints: Vec, bytes: usize, } @@ -3698,15 +3783,22 @@ pub(super) struct PendingDownload { impl Drop for PendingDownload { fn drop(&mut self) { - let done = self.fence_value.is_some_and(|v| { - let got = unsafe { super::real::native_fence_completed(&self.fence) }; - got != u64::MAX && got >= v - }); - if !done { - if let Some(objects) = self.objects.take() { - std::mem::forget(objects); - } + let Some(objects) = self.objects.take() else { return }; + if !self.is_complete() { + std::mem::forget(objects); + return; } + + let DownloadObjects { readback, readback_size, mut commands, device, queue_type, .. } = objects; + let key = device.as_raw() as usize; + // MAX is the device-removal sentinel. Retire a fence before it would signal that value. + let next_value = commands.fence_value.checked_add(1).filter(|&v| v < u64::MAX); + let set = next_value.map(|value| { + commands.fence_value = value; + (commands, device.clone()) + }); + let rejected = DOWNLOAD_POOL.lock().unwrap().put(key, queue_type, readback_size, set, (readback, device)); + drop(rejected); } } @@ -3761,25 +3853,29 @@ impl TextureDownloadPlan { { return Err("texture download queue type or source device differs from its plan".into()); } + let fence_value = self.commands.fence_value; + let fence = self.commands.fence.clone(); let mut pending = PendingDownload { tex: self.tex, objects: Some(DownloadObjects { _source: self.source, readback: self.readback, - _allocator: self.allocator, + readback_size: self.readback_size, + commands: self.commands, list: self.list, _queue: queue.clone(), - _fence_hold: self.fence.clone(), + device: self.device, + queue_type: self.queue_type.0, }), - fence: self.fence, + fence, fence_value: None, footprints: self.footprints, bytes: self.bytes, }; let list = pending.objects.as_ref().unwrap().list.clone(); super::real::native_queue_execute(queue, &list); - let signal_error = match super::real::native_queue_signal(queue, &pending.fence, 1) { - Ok(()) => { pending.fence_value = Some(1); None } + let signal_error = match super::real::native_queue_signal(queue, &pending.fence, fence_value) { + Ok(()) => { pending.fence_value = Some(fence_value); None } Err(e) => Some(e.to_string()), }; Ok(SubmittedDownload { ticket: pending, signal_error }) @@ -4204,7 +4300,7 @@ fn download_queue_type_supported(ty: D3D12_COMMAND_LIST_TYPE) -> bool { matches!(ty, D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE) } -/// Build but do not submit a download. Preparation performs no global lookup or queue operation. +/// Build but do not submit a download. The pool lock is released before D3D12 calls. #[allow(dead_code)] pub(super) unsafe fn prepare_texture_download( dev: &ID3D12Device, @@ -4240,27 +4336,60 @@ pub(super) unsafe fn prepare_texture_download( .ok_or("driver footprint overflow")?; } let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?; - let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; - let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; - let mut readback = None; - dev.CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, - D3D12_HEAP_FLAG_NONE, - &D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: bytes as u64, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - ..Default::default() - }, - D3D12_RESOURCE_STATE_COPY_DEST, - None, - &mut readback, - ).map_err(|e| e.to_string())?; - let readback = readback.ok_or("no readback resource")?; + let readback_size = download_buffer_size(bytes).ok_or("readback buffer size overflow")?; + let (pooled_set, pooled_buffer) = DOWNLOAD_POOL.lock().unwrap().take(dev.as_raw() as usize, queue_type.0, readback_size); + let (commands, readback) = own_work(|| { + let reset = pooled_set.and_then(|(commands, _)| { + (commands.allocator.Reset().is_ok() && commands.graphics.Reset(&commands.allocator, None).is_ok()) + .then_some(commands) + }); + let commands = match reset { + Some(commands) => commands, + None => { + let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; + let graphics = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; + let fence = super::real::create_download_fence(dev).map_err(|e| e.to_string())?; + DownloadCommands { graphics, allocator, fence, fence_value: 1 } + } + }; + let readback = match pooled_buffer { + Some((readback, _)) => readback, + None => { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: readback_size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let create = || { + let mut readback: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .map(|()| readback) + }; + // The idle buffers are dropped after the pool's lock is released. + let reclaim = || { + let idle = DOWNLOAD_POOL.lock().unwrap().drain_buffers(); + drop(idle); + }; + retry_after_reclaim(create, |e: &windows::core::Error| e.code() == windows::Win32::Foundation::E_OUTOFMEMORY, reclaim) + .map_err(|e| e.to_string())? + .ok_or("no readback resource")? + } + }; + Ok::<_, String>((commands, readback)) + })?; + let graphics = &commands.graphics; let barrier = |subresource, before, after| D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -4284,8 +4413,7 @@ pub(super) unsafe fn prepare_texture_download( } graphics.Close().map_err(|e| e.to_string())?; let list: ID3D12CommandList = graphics.cast().map_err(|e| e.to_string())?; - let fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; - Ok(TextureDownloadPlan { device: dev.clone(), queue_type, tex, source: source.clone(), readback, allocator, list, fence, footprints, bytes }) + Ok(TextureDownloadPlan { device: dev.clone(), queue_type, tex, source: source.clone(), readback, readback_size, commands, list, footprints, bytes }) } @@ -5942,6 +6070,81 @@ pub(super) mod tests { .collect() } + #[test] + fn download_pool_rounds_readback_sizes() { + assert_eq!(download_buffer_size(0), Some(0x10000)); + assert_eq!(download_buffer_size(1), Some(0x10000)); + assert_eq!(download_buffer_size(0x10000), Some(0x10000)); + assert_eq!(download_buffer_size(0x10001), Some(0x20000)); + assert_eq!(download_buffer_size(usize::MAX), None); + } + + #[test] + fn download_pool_keys_sets_by_queue_type_and_buffers_by_size() { + let mut pool = DownloadPool::new(); + let direct = D3D12_COMMAND_LIST_TYPE_DIRECT.0; + let compute = D3D12_COMMAND_LIST_TYPE_COMPUTE.0; + assert_eq!(pool.put(1, direct, 0x10000, Some(10), 20), (None, None)); + assert_eq!(pool.put(2, compute, 0x20000, Some(11), 21), (None, None)); + + assert_eq!(pool.take(1, compute, 0x20000), (None, None)); + assert_eq!(pool.take(1, compute, 0x10000), (None, Some(20))); + assert_eq!(pool.take(1, direct, 0x10000), (Some(10), None)); + assert_eq!(pool.take(2, compute, 0x20000), (Some(11), Some(21))); + assert_eq!(pool.buffer_bytes, 0); + assert!(pool.buffers.is_empty()); + } + + #[test] + fn download_pool_caps_idle_sets_and_readback_bytes_independently() { + let mut pool = DownloadPool::new(); + let size = 0x10000; + assert_eq!(pool.put(1, 0, DOWNLOAD_POOL_BYTES, None, 1), (None, None)); + for set in 0..DOWNLOAD_POOL_SETS { + assert_eq!(pool.put(1, 0, size, Some(set), 2), (None, Some(2))); + } + assert_eq!(pool.put(2, 0, size, Some(0), 3), (Some(0), Some(3))); + assert_eq!(pool.take(2, 0, size), (None, None)); + assert_eq!(pool.take(1, 0, DOWNLOAD_POOL_BYTES), (Some(DOWNLOAD_POOL_SETS - 1), Some(1))); + assert_eq!(pool.put(2, 0, size, Some(1), 3), (None, None)); + assert_eq!(pool.put(2, 0, size, Some(2), 4), (Some(2), None)); + assert_eq!(pool.buffer_bytes, 2 * size); + } + + #[test] + fn download_pool_gives_up_its_idle_buffers_for_one_retry_after_out_of_memory() { + let mut pool = DownloadPool::::new(); + assert_eq!(pool.put(1, 0, 0x10000, None, 20), (None, None)); + assert_eq!(pool.put(1, 0, 0x20000, None, 21), (None, None)); + let pool = Mutex::new(pool); + // Out of memory while the pool still holds buffers: they are released, then one retry. + let mut tries = 0; + let created = retry_after_reclaim( + || { + tries += 1; + if pool.lock().unwrap().buffer_bytes == 0 { Ok(7) } else { Err("out of memory") } + }, + |e| *e == "out of memory", + || { + let idle = pool.lock().unwrap().drain_buffers(); + assert!(pool.try_lock().is_ok(), "the buffers are released outside the lock"); + assert_eq!(idle, vec![20, 21]); + }, + ); + assert_eq!((created, tries), (Ok(7), 2)); + assert!(pool.lock().unwrap().buffers.is_empty()); + // Another error is returned as it is: nothing reclaimed, no retry. + assert_eq!(pool.lock().unwrap().put(1, 0, 0x10000, None, 22), (None, None)); + let mut tries = 0; + let failed: Result = retry_after_reclaim(|| { tries += 1; Err("device removed") }, |e| *e == "out of memory", || panic!("reclaimed")); + assert_eq!((failed, tries), (Err("device removed"), 1)); + assert_eq!(pool.lock().unwrap().buffer_bytes, 0x10000); + // Out of memory twice: the second error comes back. + let mut tries = 0; + let failed: Result = retry_after_reclaim(|| { tries += 1; Err("out of memory") }, |e| *e == "out of memory", || {}); + assert_eq!((failed, tries), (Err("out of memory"), 2)); + } + #[test] fn download_plans_use_writer_capable_queue_types() { assert!(download_queue_type_supported(D3D12_COMMAND_LIST_TYPE_DIRECT));