Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 88 additions & 30 deletions runtime/d3d12/src/device/allocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand All @@ -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(&region),
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<T>(
device: &ID3D12Device,
slot: &std::sync::Mutex<Option<InitTransition>>,
op: impl FnOnce(&mut InitTransition) -> windows::core::Result<T>,
) -> windows::core::Result<T> {
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,
Expand All @@ -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<Option<InitTransition>>,
resource: &ID3D12Resource,
runs: &[(ID3D12Heap, u32)],
) -> windows::core::Result<()> {
with_init_transition(device, slot, |runner| runner.map_tiles(resource, runs))
}

pub(super) fn packed_requirements(
Expand Down
185 changes: 156 additions & 29 deletions runtime/d3d12/src/device/heap/backing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AcquireRuns>,
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<Exports> {
// 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::<unsafe extern "system" fn() -> isize, AcquireRuns>(symbol),
);
let release = GetProcAddress(module, s!("TuxBoxReleasePhysicalBacking"))?;
Some(Exports {
acquire: core::mem::transmute::<unsafe extern "system" fn() -> isize, Acquire>(acquire),
acquire_runs,
release: core::mem::transmute::<unsafe extern "system" fn() -> isize, Release>(release),
})
}
Expand Down Expand Up @@ -93,30 +120,130 @@ pub(super) struct Backing {
pub(super) hold: Option<Hold>,
}

/// Resolve `base..base + size` to the host memory the GPU must import.
pub(super) fn acquire(base: u64, size: u64) -> Result<Backing> {
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<BackingRun>,
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<Option<AcquiredBacking>> {
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<AcquiredBacking> {
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<Backing> {
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)]
Expand Down
Loading
Loading