From f9b630db07ef6e77bcd80dec1d0f3db09d42a945 Mon Sep 17 00:00:00 2001 From: DrArroway Date: Thu, 26 Nov 2026 18:19:43 +0100 Subject: [PATCH] d3d12: import non-contiguous XMem backings through a reserved buffer --- runtime/d3d12/src/device/allocation.rs | 118 ++++++-- runtime/d3d12/src/device/heap/backing.rs | 185 +++++++++++-- runtime/d3d12/src/device/heap/import.rs | 138 ++++++++- .../d3d12/src/tests/device/heap_backing.rs | 262 +++++++++++++++++- 4 files changed, 631 insertions(+), 72 deletions(-) diff --git a/runtime/d3d12/src/device/allocation.rs b/runtime/d3d12/src/device/allocation.rs index c0399811..f516f7d8 100644 --- a/runtime/d3d12/src/device/allocation.rs +++ b/runtime/d3d12/src/device/allocation.rs @@ -194,13 +194,30 @@ impl InitTransition { Ok(Self { queue, allocator, list, fence, value: 0 }) } + fn wait_for_queue(&mut self) -> windows::core::Result<()> { + use windows::Win32::Foundation::CloseHandle; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + unsafe { + self.value += 1; + self.queue.Signal(&self.fence, self.value)?; + if self.fence.GetCompletedValue() < self.value { + let event = CreateEventW(None, false, false, None)?; + let set = self.fence.SetEventOnCompletion(self.value, event); + if set.is_ok() { + WaitForSingleObject(event, INFINITE); + } + let _ = CloseHandle(event); + set?; + } + } + Ok(()) + } + fn apply( &mut self, resource: &ID3D12Resource, target: D3D12_RESOURCE_STATES, ) -> windows::core::Result<()> { - use windows::Win32::Foundation::CloseHandle; - use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; unsafe { self.allocator.Reset()?; self.list.Reset(&self.allocator, None)?; @@ -225,22 +242,67 @@ impl InitTransition { self.list.Close()?; let command_list: ID3D12CommandList = self.list.clone().into(); self.queue.ExecuteCommandLists(&[Some(command_list)]); - self.value += 1; - self.queue.Signal(&self.fence, self.value)?; - if self.fence.GetCompletedValue() < self.value { - let event = CreateEventW(None, false, false, None)?; - let set = self.fence.SetEventOnCompletion(self.value, event); - if set.is_ok() { - WaitForSingleObject(event, INFINITE); - } - let _ = CloseHandle(event); - set?; + } + self.wait_for_queue() + } + + fn map_tiles( + &mut self, + resource: &ID3D12Resource, + runs: &[(ID3D12Heap, u32)], + ) -> windows::core::Result<()> { + let mut tile_offset = 0u32; + for (heap, tiles) in runs { + let coordinate = D3D12_TILED_RESOURCE_COORDINATE { + X: tile_offset, + Y: 0, + Z: 0, + Subresource: 0, + }; + let region = D3D12_TILE_REGION_SIZE { + NumTiles: *tiles, + ..Default::default() + }; + let range_start = 0u32; + unsafe { + self.queue.UpdateTileMappings( + resource, + 1, + Some(&coordinate), + Some(®ion), + Some(heap), + 1, + Some(&D3D12_TILE_RANGE_FLAG_NONE), + Some(&range_start), + Some(tiles), + D3D12_TILE_MAPPING_FLAG_NONE, + ); } + tile_offset = tile_offset + .checked_add(*tiles) + .ok_or(windows::Win32::Foundation::E_INVALIDARG)?; } - Ok(()) + self.wait_for_queue() } } +fn with_init_transition( + device: &ID3D12Device, + slot: &std::sync::Mutex>, + op: impl FnOnce(&mut InitTransition) -> windows::core::Result, +) -> windows::core::Result { + let mut slot = slot.lock().unwrap_or_else(|e| e.into_inner()); + let runner = match slot.as_mut() { + Some(runner) => runner, + None => slot.insert(InitTransition::new(device)?), + }; + let result = op(runner); + if result.is_err() { + *slot = None; + } + result +} + pub(super) fn transition_initial_state( device: &Device, resource: &ID3D12Resource, @@ -252,23 +314,19 @@ pub(super) fn transition_initial_state( { return Ok(()); } - let mut slot = device - .state - .init_transition - .lock() - .unwrap_or_else(|e| e.into_inner()); - let runner = match slot.as_mut() { - Some(runner) => runner, - None => match InitTransition::new(&device.native) { - Ok(runner) => slot.insert(runner), - Err(error) => return Err(error.code()), - }, - }; - if let Err(error) = runner.apply(resource, target) { - *slot = None; - return Err(error.code()); - } - Ok(()) + with_init_transition(&device.native, &device.state.init_transition, |runner| { + runner.apply(resource, target) + }) + .map_err(|error| error.code()) +} + +pub(super) fn map_reserved_tiles( + device: &ID3D12Device, + slot: &std::sync::Mutex>, + resource: &ID3D12Resource, + runs: &[(ID3D12Heap, u32)], +) -> windows::core::Result<()> { + with_init_transition(device, slot, |runner| runner.map_tiles(resource, runs)) } pub(super) fn packed_requirements( diff --git a/runtime/d3d12/src/device/heap/backing.rs b/runtime/d3d12/src/device/heap/backing.rs index 3669fd7c..29bc20ba 100644 --- a/runtime/d3d12/src/device/heap/backing.rs +++ b/runtime/d3d12/src/device/heap/backing.rs @@ -18,44 +18,71 @@ //! void TuxBoxReleasePhysicalBacking(UINT64 hold); //! ``` //! -//! For a 64 KiB-aligned range, acquire writes the start of the contiguous host -//! range that holds the same bytes, which may equal `address`, and a hold. While -//! the hold lives, XMem keeps that host range mapped to private memory, even if -//! the title unmaps, remaps or frees the pages. What it contains after a remap -//! does not matter: the queue retires imports of remapped pages. Acquire fails -//! with `ERROR_NOT_FOUND` when the range holds no XMem physical page; the -//! importer then uses the address itself, as it does without the exports. Any -//! other failure, such as pages whose backings are not contiguous, fails the -//! import. +//! For a 64 KiB-aligned range, `TuxBoxAcquirePhysicalBacking` writes the start +//! of the contiguous host range that holds the same bytes, which may equal +//! `address`, and a hold. When a range spans pages whose backings are not +//! contiguous, `TuxBoxAcquirePhysicalBackingRuns` (when exported) returns one +//! hold covering an ordered list of 64 KiB-aligned piece runs that can be bound +//! together via a reserved buffer and `UpdateTileMappings`. While a hold lives, +//! XMem keeps those host ranges mapped to private memory, even if the title +//! unmaps, remaps or frees the pages. What it contains after a remap does not +//! matter: the queue retires imports of remapped pages. Acquire fails with +//! `ERROR_NOT_FOUND` when the range holds no XMem physical page; the importer +//! then uses the address itself, as it does without the exports. Any other +//! failure fails the import. use std::sync::OnceLock; -use windows::Win32::Foundation::{E_INVALIDARG, ERROR_NOT_FOUND, GetLastError}; +use windows::Win32::Foundation::{ + E_INVALIDARG, E_OUTOFMEMORY, ERROR_INSUFFICIENT_BUFFER, ERROR_MORE_DATA, ERROR_NOT_FOUND, + ERROR_NOT_SUPPORTED, GetLastError, +}; use windows::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; use windows::core::{HRESULT, Result, s, w}; +const INLINE_RUNS: usize = 16; + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct BackingRun { + pub(super) address: u64, + pub(super) bytes: u64, +} + type Acquire = unsafe extern "system" fn(u64, u64, *mut u64, *mut u64) -> i32; +type AcquireRuns = + unsafe extern "system" fn(u64, u64, *mut BackingRun, *mut u32, *mut u64) -> i32; type Release = unsafe extern "system" fn(u64); #[derive(Clone, Copy)] pub(super) struct Exports { acquire: Acquire, + acquire_runs: Option, release: Release, } impl Exports { #[cfg(test)] pub(super) fn new(acquire: Acquire, release: Release) -> Self { - Self { acquire, release } + Self { acquire, acquire_runs: None, release } + } + + #[cfg(test)] + pub(super) fn with_runs(acquire: Acquire, acquire_runs: AcquireRuns, release: Release) -> Self { + Self { acquire, acquire_runs: Some(acquire_runs), release } } } fn lookup() -> Option { - // SAFETY: both names are XMem exports with the signatures above. + // SAFETY: names match the XMem physical-backing exports documented above. unsafe { let module = GetModuleHandleW(w!("xmem.dll")).ok()?; let acquire = GetProcAddress(module, s!("TuxBoxAcquirePhysicalBacking"))?; + let acquire_runs = GetProcAddress(module, s!("TuxBoxAcquirePhysicalBackingRuns")).map( + |symbol| core::mem::transmute:: isize, AcquireRuns>(symbol), + ); let release = GetProcAddress(module, s!("TuxBoxReleasePhysicalBacking"))?; Some(Exports { acquire: core::mem::transmute:: isize, Acquire>(acquire), + acquire_runs, release: core::mem::transmute:: isize, Release>(release), }) } @@ -93,30 +120,130 @@ pub(super) struct Backing { pub(super) hold: Option, } -/// Resolve `base..base + size` to the host memory the GPU must import. -pub(super) fn acquire(base: u64, size: u64) -> Result { - let identity = || Backing { address: base, hold: None }; - let Some(exports) = exports() else { return Ok(identity()) }; - let (mut address, mut cookie) = (0u64, 0u64); - // SAFETY: both outputs are writable locals. - if unsafe { (exports.acquire)(base, size, &mut address, &mut cookie) } == 0 { +/// Contiguous or piece-wise private host backing behind a guest range. +pub(super) enum AcquiredBacking { + Contiguous(Backing), + Scattered { + runs: Vec, + hold: Hold, + }, +} + +fn log_redirect(base: u64, address: u64) { + if address != base { + static REDIRECTED: std::sync::Once = std::sync::Once::new(); + crate::diagnostics::log_once(&REDIRECTED, || { + "game memory is imported through its XMem backing".into() + }); + } +} + +fn acquire_runs_list( + acquire_runs: AcquireRuns, + release: Release, + base: u64, + size: u64, +) -> Result> { + let mut inline = [BackingRun { address: 0, bytes: 0 }; INLINE_RUNS]; + let mut overflow = Vec::new(); + let mut count = inline.len() as u32; + let mut cookie = 0u64; + // SAFETY: `inline` has `count` writable `BackingRun` slots. + let slice = if unsafe { (acquire_runs)(base, size, inline.as_mut_ptr(), &mut count, &mut cookie) } != 0 { + &inline[..] + } else { let error = unsafe { GetLastError() }; if error == ERROR_NOT_FOUND { - return Ok(identity()); + return Ok(None); + } + if !matches!(error, ERROR_MORE_DATA | ERROR_INSUFFICIENT_BUFFER) || count <= inline.len() as u32 { + return Err(HRESULT::from_win32(error.0).into()); + } + if u64::from(count) > size / 65536 { + return Err(E_INVALIDARG.into()); } - return Err(HRESULT::from_win32(error.0).into()); + overflow.try_reserve_exact(count as usize).map_err(|_| E_OUTOFMEMORY)?; + overflow.resize(count as usize, BackingRun { address: 0, bytes: 0 }); + // SAFETY: `overflow` has `count` writable `BackingRun` slots. + if unsafe { (acquire_runs)(base, size, overflow.as_mut_ptr(), &mut count, &mut cookie) } == 0 { + let retry_error = unsafe { GetLastError() }; + return if retry_error == ERROR_NOT_FOUND { + Ok(None) + } else { + Err(HRESULT::from_win32(retry_error.0).into()) + }; + } + &overflow[..] + }; + let hold = Hold { release, cookie }; + let used = count as usize; + if used == 0 || used > slice.len() { + return Err(E_INVALIDARG.into()); + } + let slice = &slice[..used]; + let mut total = 0u64; + for run in slice { + if run.address == 0 + || !run.address.is_multiple_of(65536) + || run.bytes == 0 + || !run.bytes.is_multiple_of(65536) + || run.address.checked_add(run.bytes).is_none() + { + return Err(E_INVALIDARG.into()); + } + total = total.checked_add(run.bytes).ok_or(E_INVALIDARG)?; } - let hold = Hold { release: exports.release, cookie }; - if address == 0 || !address.is_multiple_of(65536) { + if total != size { return Err(E_INVALIDARG.into()); } - if address != base { - static REDIRECTED: std::sync::Once = std::sync::Once::new(); - crate::diagnostics::log_once(&REDIRECTED, || { - "game memory is imported through its XMem backing".into() - }); + if slice.len() == 1 { + let address = slice[0].address; + log_redirect(base, address); + return Ok(Some(AcquiredBacking::Contiguous(Backing { address, hold: Some(hold) }))); + } + let mut runs = Vec::new(); + runs.try_reserve_exact(slice.len()).map_err(|_| E_OUTOFMEMORY)?; + runs.extend_from_slice(slice); + static SCATTERED: std::sync::Once = std::sync::Once::new(); + crate::diagnostics::log_once(&SCATTERED, || { + "game memory is imported through non-contiguous XMem backings".into() + }); + Ok(Some(AcquiredBacking::Scattered { runs, hold })) +} + +/// Resolve `base..base + size` to contiguous or piece-wise host memory for the GPU. +pub(super) fn acquire_backing(base: u64, size: u64) -> Result { + let identity = || AcquiredBacking::Contiguous(Backing { address: base, hold: None }); + let Some(exports) = exports() else { return Ok(identity()) }; + let (mut address, mut cookie) = (0u64, 0u64); + // SAFETY: both outputs are writable locals. + if unsafe { (exports.acquire)(base, size, &mut address, &mut cookie) } != 0 { + let hold = Hold { release: exports.release, cookie }; + if address == 0 || !address.is_multiple_of(65536) { + return Err(E_INVALIDARG.into()); + } + log_redirect(base, address); + return Ok(AcquiredBacking::Contiguous(Backing { address, hold: Some(hold) })); + } + let error = unsafe { GetLastError() }; + if error == ERROR_NOT_FOUND { + return Ok(identity()); + } + if error == ERROR_NOT_SUPPORTED + && let Some(acquire_runs) = exports.acquire_runs + { + return acquire_runs_list(acquire_runs, exports.release, base, size).map(|found| found.unwrap_or_else(identity)); + } + Err(HRESULT::from_win32(error.0).into()) +} + +/// Resolve `base..base + size` to a single contiguous host backing range. +#[cfg(test)] +pub(super) fn acquire(base: u64, size: u64) -> Result { + match acquire_backing(base, size)? { + AcquiredBacking::Contiguous(backing) => Ok(backing), + AcquiredBacking::Scattered { .. } => Err(windows::Win32::Foundation::E_NOTIMPL.into()), } - Ok(Backing { address, hold: Some(hold) }) } #[cfg(test)] diff --git a/runtime/d3d12/src/device/heap/import.rs b/runtime/d3d12/src/device/heap/import.rs index 2949beb7..ec765036 100644 --- a/runtime/d3d12/src/device/heap/import.rs +++ b/runtime/d3d12/src/device/heap/import.rs @@ -23,10 +23,11 @@ pub(super) fn trace_import_failure(source: &'static str, api: &'static str, size // This holder is also the key for the weak single-page import cache. Its // last native resource releases both the heap reference and the VA pin. -// Field order is load-bearing: `native` must drop before `_shadow` unmaps -// and before `_backing` lets XMem unmap the imported memory. +// Field order is load-bearing: `native` and `extra_heaps` must drop before +// `_shadow` unmaps and before `_backing` lets XMem unmap the imported memory. pub(in super::super) struct ImportedHeap { pub(super) native: ID3D12Heap, + extra_heaps: Vec, pub(super) _pin: ImportPin, _shadow: Option>, _backing: Option, @@ -36,21 +37,123 @@ pub(in super::super) struct ImportedHeap { impl ImportedHeap { pub(super) fn direct(native: ID3D12Heap, pin: ImportPin, backing: super::backing::Backing) -> Self { - Self { native, _pin: pin, _shadow: None, _backing: backing.hold, memory: backing.address } + Self { native, extra_heaps: Vec::new(), _pin: pin, _shadow: None, _backing: backing.hold, memory: backing.address } } pub(super) fn shadowed(native: ID3D12Heap, pin: ImportPin, shadow: Arc, backing: super::backing::Backing) -> Self { - Self { native, _pin: pin, _shadow: Some(shadow), _backing: backing.hold, memory: backing.address } + Self { native, extra_heaps: Vec::new(), _pin: pin, _shadow: Some(shadow), _backing: backing.hold, memory: backing.address } + } + + pub(super) fn scattered( + native: ID3D12Heap, + extra_heaps: Vec, + pin: ImportPin, + hold: super::backing::Hold, + ) -> Self { + Self { + native, + extra_heaps, + _pin: pin, + _shadow: None, + _backing: Some(hold), + memory: 0, + } } /// Whether a later import of the same guest pages, now backed by /// `memory`, can reuse this heap. pub(super) fn reusable_for(&self, memory: u64) -> bool { - self.is_live() && self.memory == memory + self.extra_heaps.is_empty() && self.is_live() && self.memory == memory } } +/// Import a 64 KiB-aligned buffer whose XMem backings span multiple discrete +/// host runs by mapping each piece heap into a `CreateReservedResource` buffer. +#[allow(clippy::too_many_arguments)] +pub(super) fn import_scattered_buffer( + native_device: &ID3D12Device, + init_transition: &std::sync::Mutex>, + offset: u64, + desc: &D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, + runs: Vec, + hold: super::backing::Hold, + pin: ImportPin, + source: &'static str, + check_mirror: bool, +) -> windows::core::Result<(ID3D12Resource, Arc)> { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; + // Declare `_hold` before `heaps` and `resource` so error drops release + // `resource`, then `heaps`, and `_hold` last. + let _hold = hold; + let granularity = u64::from(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT); + if offset != 0 + || runs.len() < 2 + || desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER + || desc.Width == 0 + { + return Err(E_NOTIMPL.into()); + } + let sized: ID3D12Device13 = native_device.cast().map_err(|_| E_NOTIMPL)?; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if unsafe { + native_device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + } + .is_err() + || options.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_1.0 + { + return Err(E_NOTIMPL.into()); + } + let mut heaps = Vec::new(); + heaps.try_reserve_exact(runs.len()).map_err(|_| E_OUTOFMEMORY)?; + for run in &runs { + let end = run.address.checked_add(run.bytes).ok_or(E_INVALIDARG)?; + validate_shared_range(run.address, end)?; + if check_mirror && super::shadow::contains_mapped_pages(run.address, run.bytes) { + return Err(E_NOTIMPL.into()); + } + let native = unsafe { sized.OpenExistingHeapFromAddress1(run.address as _, run.bytes as usize) } + .map_err(|error| { + trace_import_failure(source, "scattered-sized", run.bytes, error.code()); + error + })?; + let tiles = u32::try_from(run.bytes / granularity).map_err(|_| E_INVALIDARG)?; + heaps.push((native, tiles)); + } + let reserved_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: desc.Width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAGS(desc.Flags.0 & super::super::format::HOST_FLAGS), + }; + let mut resource = None; + unsafe { native_device.CreateReservedResource(&reserved_desc, state, None, &mut resource)? }; + let resource: ID3D12Resource = resource.ok_or(E_POINTER)?; + super::super::allocation::map_reserved_tiles(native_device, init_transition, &resource, &heaps)?; + let mut iter = heaps.into_iter().map(|(heap, _)| heap); + let primary = iter.next().expect("scattered runs validated >= 2"); + let extra_heaps: Vec = iter.collect(); + let heap = Arc::new(ImportedHeap::scattered(primary, extra_heaps, pin, _hold)); + if let Err(error) = attach_import(&resource, &heap) { + drop(resource); + return Err(error); + } + static SCATTERED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + trace_buffer_path("imported_scattered", &SCATTERED, source, desc.Width); + Ok((resource, heap)) +} + // Slot 44 places a tiled resource at a title-selected virtual address. An // unrelated allocation would lose texture contents and subsequent page remaps. pub(in super::super) fn import_buffer_with_heap( @@ -85,7 +188,27 @@ pub(in super::super) fn import_buffer_with_heap( // Import the memory behind these pages: the address may be one of several // GPU aliases of it (see `backing`). Without XMem's backing exports this // is the address itself. - let backing = super::backing::acquire(base, size)?; + let backing = match super::backing::acquire_backing(base, size)? { + super::backing::AcquiredBacking::Contiguous(backing) => backing, + super::backing::AcquiredBacking::Scattered { runs, hold } => { + super::super::host_profile::report(device); + let check_mirror = super::super::host_profile::needs_mirror( + super::super::host_profile::section_import(device), + ); + return import_scattered_buffer( + &device.native, + &device.state.init_transition, + offset, + desc, + state, + runs, + hold, + pin, + source, + check_mirror, + ); + } + }; let memory = backing.address; validate_shared_range(memory, memory.checked_add(size).ok_or(E_INVALIDARG)?)?; super::super::host_profile::report(device); @@ -216,6 +339,9 @@ impl ImportedHeap { pub(in super::super) fn buffer_alias(self: &Arc, device: &ID3D12Device, offset: u64, width: u64, stride: u32, flags: D3D12_RESOURCE_FLAGS, ) -> windows::core::Result<(ID3D12Resource, u64)> { + if !self.extra_heaps.is_empty() { + return Err(E_NOTIMPL.into()); + } let mut desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: width, Height: 1, DepthOrArraySize: 1, MipLevels: 1, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, diff --git a/runtime/d3d12/src/tests/device/heap_backing.rs b/runtime/d3d12/src/tests/device/heap_backing.rs index 32bdd604..e3e0c6e2 100644 --- a/runtime/d3d12/src/tests/device/heap_backing.rs +++ b/runtime/d3d12/src/tests/device/heap_backing.rs @@ -4,7 +4,8 @@ use crate::commands::page_mapping::GPU_APERTURE; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use windows::Win32::Foundation::{ - ERROR_NOT_FOUND, ERROR_NOT_SUPPORTED, SetLastError, WAIT_OBJECT_0, + E_INVALIDARG, E_NOTIMPL, ERROR_MORE_DATA, ERROR_NOT_FOUND, ERROR_NOT_SUPPORTED, SetLastError, + WAIT_OBJECT_0, }; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; use windows::Win32::Graphics::Direct3D12::*; @@ -22,6 +23,7 @@ const PAGE: u64 = 65536; static SERIAL: Mutex<()> = Mutex::new(()); // (guest page, backing) pairs the fake resolves; anything else is not XMem's. static MAP: Mutex> = Mutex::new(Vec::new()); +static RUNS_MAP: Mutex)>> = Mutex::new(Vec::new()); static FAIL_WITH: AtomicU64 = AtomicU64::new(0); static ACQUIRED: AtomicU64 = AtomicU64::new(0); static RELEASED: AtomicU64 = AtomicU64::new(0); @@ -33,16 +35,54 @@ unsafe extern "system" fn fake_acquire(address: u64, bytes: u64, backing: *mut u return 0; } let map = MAP.lock().unwrap(); - let Some(&(_, start)) = map.iter().find(|(guest, _)| *guest == address) else { + if let Some(&(_, start)) = map.iter().find(|(guest, _)| *guest == address) { + assert_eq!(bytes % PAGE, 0); + let cookie = ACQUIRED.fetch_add(1, Ordering::AcqRel) + 1; + unsafe { + backing.write(start); + hold.write(cookie); + } + return 1; + } + drop(map); + let runs_map = RUNS_MAP.lock().unwrap(); + if runs_map.iter().any(|(guest, _)| *guest == address) { + unsafe { SetLastError(ERROR_NOT_SUPPORTED) }; + return 0; + } + unsafe { SetLastError(ERROR_NOT_FOUND) }; + 0 +} + +unsafe extern "system" fn fake_acquire_runs( + address: u64, + bytes: u64, + out_runs: *mut BackingRun, + count: *mut u32, + hold: *mut u64, +) -> i32 { + let fail = FAIL_WITH.load(Ordering::Acquire); + if fail != 0 { + unsafe { SetLastError(windows::Win32::Foundation::WIN32_ERROR(fail as u32)) }; + return 0; + } + let runs_map = RUNS_MAP.lock().unwrap(); + let Some((_, runs)) = runs_map.iter().find(|(guest, _)| *guest == address) else { unsafe { SetLastError(ERROR_NOT_FOUND) }; return 0; }; assert_eq!(bytes % PAGE, 0); - let cookie = ACQUIRED.fetch_add(1, Ordering::AcqRel) + 1; - unsafe { - backing.write(start); - hold.write(cookie); + let capacity = unsafe { count.read() } as usize; + unsafe { count.write(runs.len() as u32) }; + if capacity < runs.len() { + unsafe { SetLastError(ERROR_MORE_DATA) }; + return 0; + } + for (i, run) in runs.iter().enumerate() { + unsafe { out_runs.add(i).write(*run) }; } + let cookie = ACQUIRED.fetch_add(1, Ordering::AcqRel) + 1; + unsafe { hold.write(cookie) }; 1 } @@ -53,21 +93,35 @@ unsafe extern "system" fn fake_release(_hold: u64) { struct FakeXmem(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>); impl FakeXmem { - fn install(map: &[(u64, u64)]) -> Self { + fn reset_state(map: &[(u64, u64)], runs: &[(u64, Vec)]) -> std::sync::MutexGuard<'static, ()> { let guard = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); *MAP.lock().unwrap() = map.to_vec(); + *RUNS_MAP.lock().unwrap() = runs.to_vec(); FAIL_WITH.store(0, Ordering::Release); ACQUIRED.store(0, Ordering::Release); RELEASED.store(0, Ordering::Release); + guard + } + + fn install(map: &[(u64, u64)]) -> Self { + let guard = Self::reset_state(map, &[]); *TEST_EXPORTS.lock().unwrap() = Some(Exports::new(fake_acquire, fake_release)); Self(guard) } + + fn install_runs(runs: &[(u64, Vec)]) -> Self { + let guard = Self::reset_state(&[], runs); + *TEST_EXPORTS.lock().unwrap() = + Some(Exports::with_runs(fake_acquire, fake_acquire_runs, fake_release)); + Self(guard) + } } impl Drop for FakeXmem { fn drop(&mut self) { *TEST_EXPORTS.lock().unwrap() = None; MAP.lock().unwrap().clear(); + RUNS_MAP.lock().unwrap().clear(); } } @@ -296,3 +350,197 @@ fn a_moved_backing_is_imported_again() { assert_eq!(RELEASED.load(Ordering::Acquire), ACQUIRED.load(Ordering::Acquire)); drop(xmem); } + +#[test] +fn scattered_backing_runs_are_acquired_and_released_once() { + let expected = vec![ + BackingRun { address: 0x7_0100_0000, bytes: PAGE }, + BackingRun { address: 0x7_0300_0000, bytes: 2 * PAGE }, + ]; + let _xmem = FakeXmem::install_runs(&[(0x7_0004_0000, expected.clone())]); + let acquired = acquire_backing(0x7_0004_0000, 3 * PAGE).unwrap(); + let AcquiredBacking::Scattered { runs, hold } = acquired else { + panic!("expected scattered backing"); + }; + assert_eq!(runs, expected); + assert_eq!((ACQUIRED.load(Ordering::Acquire), RELEASED.load(Ordering::Acquire)), (1, 0)); + drop(hold); + assert_eq!(RELEASED.load(Ordering::Acquire), 1); +} + +#[test] +fn scattered_backing_retries_when_runs_exceed_inline_capacity() { + let expected: Vec = (0..20u64) + .map(|i| BackingRun { address: 0x7_1000_0000 + i * (2 * PAGE), bytes: PAGE }) + .collect(); + let _xmem = FakeXmem::install_runs(&[(0x7_0005_0000, expected.clone())]); + let AcquiredBacking::Scattered { runs, hold } = acquire_backing(0x7_0005_0000, 20 * PAGE).unwrap() else { + panic!("expected scattered backing after retry"); + }; + assert_eq!(runs, expected); + assert_eq!((ACQUIRED.load(Ordering::Acquire), RELEASED.load(Ordering::Acquire)), (1, 0)); + drop(hold); + assert_eq!(RELEASED.load(Ordering::Acquire), 1); +} + +#[test] +fn scattered_backing_invalid_runs_release_hold_and_fail() { + let unaligned = vec![ + BackingRun { address: 0x7_0100_1000, bytes: PAGE }, + BackingRun { address: 0x7_0200_0000, bytes: PAGE }, + ]; + let wrong_total = vec![ + BackingRun { address: 0x7_0100_0000, bytes: PAGE }, + BackingRun { address: 0x7_0200_0000, bytes: 2 * PAGE }, + ]; + let _xmem = FakeXmem::install_runs(&[ + (0x7_0006_0000, unaligned), + (0x7_0007_0000, wrong_total), + ]); + let err1 = acquire_backing(0x7_0006_0000, 2 * PAGE).err().expect("unaligned run must fail"); + let err2 = acquire_backing(0x7_0007_0000, 2 * PAGE).err().expect("mismatched run total must fail"); + assert_eq!(err1.code(), E_INVALIDARG); + assert_eq!(err2.code(), E_INVALIDARG); + assert_eq!((ACQUIRED.load(Ordering::Acquire), RELEASED.load(Ordering::Acquire)), (2, 2)); +} + +#[test] +fn scattered_backing_single_run_collapses_to_contiguous() { + let single = vec![BackingRun { address: 0x7_0400_0000, bytes: 2 * PAGE }]; + let _xmem = FakeXmem::install_runs(&[(0x7_0008_0000, single)]); + let AcquiredBacking::Contiguous(backing) = acquire_backing(0x7_0008_0000, 2 * PAGE).unwrap() else { + panic!("single-run scattered response should collapse to contiguous"); + }; + assert_eq!(backing.address, 0x7_0400_0000); + assert!(backing.hold.is_some()); + drop(backing); + assert_eq!((ACQUIRED.load(Ordering::Acquire), RELEASED.load(Ordering::Acquire)), (1, 1)); +} + +#[test] +fn scattered_alias_imports_through_reserved_buffer_and_aliases_cpu_and_gpu() { + let Some(device) = hardware_device() else { return }; + let native: ID3D12Device = device.cast().unwrap(); + let a = Region::private(PAGE as usize); + let b = Region::private(PAGE as usize); + let c = Region::private(PAGE as usize); + let alias_abc = Region::reserved((3 * PAGE) as usize); + let alias_bc = Region::reserved((2 * PAGE) as usize); + + a.words(4).copy_from_slice(&[0xaaaa_0001, 0xaaaa_0002, 0xaaaa_0003, 0xaaaa_0004]); + b.words(4).copy_from_slice(&[0xbbbb_0001, 0xbbbb_0002, 0xbbbb_0003, 0xbbbb_0004]); + c.words(4).copy_from_slice(&[0xcccc_0001, 0xcccc_0002, 0xcccc_0003, 0xcccc_0004]); + + let xmem = FakeXmem::install_runs(&[ + ( + alias_abc.address(), + vec![ + BackingRun { address: c.address(), bytes: PAGE }, + BackingRun { address: a.address(), bytes: PAGE }, + BackingRun { address: b.address(), bytes: PAGE }, + ], + ), + ( + alias_bc.address(), + vec![ + BackingRun { address: b.address(), bytes: PAGE }, + BackingRun { address: c.address(), bytes: PAGE }, + ], + ), + ]); + let init_transition = Mutex::new(None); + let import = |guest: &Region, offset: u64, width: u64| { + let size = (offset + width).next_multiple_of(PAGE); + let AcquiredBacking::Scattered { runs, hold } = acquire_backing(guest.address(), size).unwrap() else { + panic!("expected scattered backing"); + }; + let pin = GPU_APERTURE.pin(guest.address(), size).unwrap(); + let desc = D3D12_RESOURCE_DESC { + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..buffer_desc(width) + }; + super::super::import::import_scattered_buffer( + &native, + &init_transition, + offset, + &desc, + D3D12_RESOURCE_STATE_COMMON, + runs, + hold, + pin, + "test", + false, + ) + }; + + // Sub-page offsets fail cleanly and still release the acquired hold. + let offset_err = import(&alias_abc, 256, 2 * PAGE + 256) + .err() + .expect("non-zero offset must return E_NOTIMPL"); + assert_eq!(offset_err.code(), E_NOTIMPL); + assert_eq!((ACQUIRED.load(Ordering::Acquire), RELEASED.load(Ordering::Acquire)), (1, 1)); + + // Non-64KiB-multiple width spanning all 3 discrete backing runs `[c, a, b]`. + let (res_abc, heap_abc) = import(&alias_abc, 0, 2 * PAGE + 1024).unwrap(); + let (res_bc, heap_bc) = import(&alias_bc, 0, 2 * PAGE).unwrap(); + assert!(!heap_abc.reusable_for(0)); + assert_eq!( + heap_abc.buffer_alias(&native, 256, 256, 16, D3D12_RESOURCE_FLAG_NONE).err().unwrap().code(), + E_NOTIMPL + ); + + let upload = committed(&device, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let readback = committed(&device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + let mut mapped = core::ptr::null_mut(); + unsafe { upload.Map(0, None, Some(&mut mapped)) }.unwrap(); + let write_c: [u32; 4] = [0x1111_0001, 0x1111_0002, 0x1111_0003, 0x1111_0004]; + let write_a: [u32; 4] = [0x2222_0001, 0x2222_0002, 0x2222_0003, 0x2222_0004]; + let write_b: [u32; 4] = [0x3333_0001, 0x3333_0002, 0x3333_0003, 0x3333_0004]; + unsafe { + core::ptr::copy_nonoverlapping(write_c.as_ptr(), mapped.cast::(), 4); + core::ptr::copy_nonoverlapping(write_a.as_ptr(), mapped.cast::().add(4), 4); + core::ptr::copy_nonoverlapping(write_b.as_ptr(), mapped.cast::().add(8), 4); + } + + submit(&device, |list| unsafe { + // Read initial CPU markers across all 3 tiles: tile 0=c, tile 1=a, tile 2=b. + list.CopyBufferRegion(&readback, 0, &res_abc, 0, 16); + list.CopyBufferRegion(&readback, 16, &res_abc, PAGE, 16); + list.CopyBufferRegion(&readback, 32, &res_abc, 2 * PAGE, 16); + // Write into all 3 tiles (including tail tile 2 < width=2*PAGE+1024) via res_abc. + list.CopyBufferRegion(&res_abc, 64, &upload, 0, 16); + list.CopyBufferRegion(&res_abc, PAGE + 64, &upload, 16, 16); + list.CopyBufferRegion(&res_abc, 2 * PAGE + 64, &upload, 32, 16); + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + ..Default::default() + }; + list.ResourceBarrier(&[barrier]); + // Read GPU writes back via the second alias `[b, c]`. + list.CopyBufferRegion(&readback, 64, &res_bc, 64, 16); + list.CopyBufferRegion(&readback, 80, &res_bc, PAGE + 64, 16); + }); + + let mut out = core::ptr::null_mut(); + unsafe { readback.Map(0, None, Some(&mut out)) }.unwrap(); + let seen = unsafe { core::slice::from_raw_parts(out.cast::(), 24) }; + assert_eq!(&seen[0..4], &[0xcccc_0001, 0xcccc_0002, 0xcccc_0003, 0xcccc_0004]); + assert_eq!(&seen[4..8], &[0xaaaa_0001, 0xaaaa_0002, 0xaaaa_0003, 0xaaaa_0004]); + assert_eq!(&seen[8..12], &[0xbbbb_0001, 0xbbbb_0002, 0xbbbb_0003, 0xbbbb_0004]); + assert_eq!(&seen[16..20], &write_b); + assert_eq!(&seen[20..24], &write_c); + assert_eq!(&c.words(20)[16..20], &write_c); + assert_eq!(&a.words(20)[16..20], &write_a); + assert_eq!(&b.words(20)[16..20], &write_b); + + drop((res_abc, heap_abc)); + drop((res_bc, heap_bc)); + assert_eq!(RELEASED.load(Ordering::Acquire), ACQUIRED.load(Ordering::Acquire)); + + // Releasing scattered regions and holds must not leave dangling VMAs that poison later submits. + drop((a, b, c)); + submit(&device, |list| unsafe { + list.CopyBufferRegion(&readback, 0, &upload, 0, 16); + }); + drop(xmem); +}