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
25 changes: 25 additions & 0 deletions runtime/d3d12/src/commands/page_mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,12 +335,37 @@ impl Registry {
}
}

pub(crate) fn retire_range(&self, address: u64, bytes: u64) {
let Some(end) = address.checked_add(bytes) else {
return;
};
if end == address {
return;
}
let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
let retired: Vec<usize> = state
.imports
.iter()
.filter(|(_, (import, _))| import.start < end && address < import.end)
.map(|(&key, _)| key)
.collect();
for key in retired {
if let Some((_, live)) = state.imports.remove(&key) {
live.store(false, Ordering::Release);
}
}
}

fn apply(&self, mappings: &Mappings) -> Result<()> {
let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
mappings.apply(&mut state.imports)
}
}

pub(crate) unsafe extern "system" fn retire_from_xmem(address: u64, bytes: u64) {
GPU_APERTURE.retire_range(address, bytes);
}

struct Job {
mappings: Mappings,
pending: Arc<Pending>,
Expand Down
64 changes: 61 additions & 3 deletions runtime/d3d12/src/device/heap.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! Device memory heaps and resources sharing their native GPU allocation.
mod backing;
pub(in super::super) mod backing;
mod import;
mod shadow;
mod virtual_place;
Expand Down Expand Up @@ -46,6 +46,63 @@ fn strict_buffer_import() -> bool {
}

const IMPORTED_HEAP: GUID = GUID::from_u128(0xc2a3c751_1d00_470c_8efd_5da145efd165);
const IMPORTED_BACKING: GUID = GUID::from_u128(0x8e4b912c_7a3f_4d9e_b512_6c8a0f3d2e19);

struct BackingGuard {
_shadow: Option<Arc<shadow::ShadowPages>>,
_backing: Option<backing::Hold>,
}

impl BackingGuard {
fn new(
shadow: Option<Arc<shadow::ShadowPages>>,
backing: Option<backing::Hold>,
) -> Option<Arc<Self>> {
if shadow.is_none() && backing.is_none() {
return None;
}
Some(Arc::new(Self { _shadow: shadow, _backing: backing }))
}
}

unsafe extern "system" fn unknown_query<N, S>(
this: *mut Proxy<N, S>,
iid: *const GUID,
out: *mut *mut c_void,
) -> HRESULT {
if out.is_null() {
return E_POINTER;
}
unsafe { out.write(core::ptr::null_mut()) };
if iid.is_null() {
return E_POINTER;
}
if unsafe { iid.read_unaligned() } != windows::core::IUnknown::IID {
return windows::Win32::Foundation::E_NOINTERFACE;
}
unsafe {
crate::proxy::add_ref(this);
out.write(this.cast());
}
windows::Win32::Foundation::S_OK
}

fn attach_heap_guard(
heap: &ID3D12Heap,
guard: &Arc<BackingGuard>,
) -> windows::core::Result<()> {
static GUARD_SLOTS: Slots<3> = [
crate::slot!(unknown_query::<(), Arc<BackingGuard>>),
crate::slot!(crate::proxy::add_ref::<(), Arc<BackingGuard>>),
crate::slot!(crate::proxy::release::<(), Arc<BackingGuard>>),
];
let mut out = core::ptr::null_mut();
unsafe {
crate::proxy::allocate(&GUARD_SLOTS, &[], (), None, guard.clone(), &mut out).ok()?;
let marker = windows::core::IUnknown::from_raw(out);
heap.SetPrivateDataInterface(&IMPORTED_BACKING, &marker)
}
}

fn attach_import(resource: &ID3D12Resource, heap: &Arc<ImportedHeap>) -> windows::core::Result<()> {
static MARKER: Slots<8> = child_slots::<ID3D12Heap, Arc<ImportedHeap>, 8>();
Expand Down Expand Up @@ -486,11 +543,12 @@ unsafe fn place_gpu_target(
crate::diagnostics::watch("device-memory image", address, allocation.SizeInBytes, || format!(
"{}x{}x{} format={} flags={:#x}", desc.Width, desc.Height, desc.DepthOrArraySize, desc.Format.0, desc.Flags.0));
let footprint = address.checked_add(allocation.SizeInBytes).ok_or(E_INVALIDARG)?;
if validate_shared_range(address, footprint).is_err() {
if validate_shared_range(address, footprint).is_err() && !backing::is_backed_range(address, footprint) {
let base = address & !0xffff;
let end = footprint.saturating_add(0xffff) & !0xffff;
if !commit_guest_pages(base, end.saturating_sub(base))
|| validate_shared_range(address, footprint).is_err() {
|| (validate_shared_range(address, footprint).is_err()
&& !backing::is_backed_range(address, footprint)) {
static RESERVED: std::sync::Once = std::sync::Once::new();
crate::diagnostics::log_once(&RESERVED, || format!(
"placed GPU image at {address:#x} is not committed guest memory; keeping a device image"));
Expand Down
151 changes: 147 additions & 4 deletions runtime/d3d12/src/device/heap/backing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@
//! failure fails the import.
use std::sync::OnceLock;
use windows::Win32::Foundation::{
E_INVALIDARG, E_OUTOFMEMORY, ERROR_INSUFFICIENT_BUFFER, ERROR_MORE_DATA, ERROR_NOT_FOUND,
ERROR_NOT_SUPPORTED, GetLastError,
E_FAIL, E_INVALIDARG, E_OUTOFMEMORY, ERROR_INSUFFICIENT_BUFFER, ERROR_MORE_DATA,
ERROR_NOT_FOUND, ERROR_NOT_SUPPORTED, GetLastError,
};
use windows::Win32::System::Diagnostics::Debug::{ReadProcessMemory, WriteProcessMemory};
use windows::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
use windows::Win32::System::Threading::GetCurrentProcess;
use windows::core::{HRESULT, Result, s, w};

const INLINE_RUNS: usize = 16;
Expand All @@ -51,23 +53,27 @@ 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);
type IsBacked = unsafe extern "system" fn(u64, u64) -> i32;
type SetInvalidationCallback =
unsafe extern "system" fn(Option<unsafe extern "system" fn(u64, u64)>);

#[derive(Clone, Copy)]
pub(super) struct Exports {
acquire: Acquire,
acquire_runs: Option<AcquireRuns>,
release: Release,
is_backed: Option<IsBacked>,
}

impl Exports {
#[cfg(test)]
pub(super) fn new(acquire: Acquire, release: Release) -> Self {
Self { acquire, acquire_runs: None, release }
Self { acquire, acquire_runs: None, release, is_backed: None }
}

#[cfg(test)]
pub(super) fn with_runs(acquire: Acquire, acquire_runs: AcquireRuns, release: Release) -> Self {
Self { acquire, acquire_runs: Some(acquire_runs), release }
Self { acquire, acquire_runs: Some(acquire_runs), release, is_backed: None }
}
}

Expand All @@ -80,10 +86,21 @@ fn lookup() -> Option<Exports> {
|symbol| core::mem::transmute::<unsafe extern "system" fn() -> isize, AcquireRuns>(symbol),
);
let release = GetProcAddress(module, s!("TuxBoxReleasePhysicalBacking"))?;
let is_backed = GetProcAddress(module, s!("TuxBoxIsPhysicalBacked")).map(
|symbol| core::mem::transmute::<unsafe extern "system" fn() -> isize, IsBacked>(symbol),
);
if let Some(register) = GetProcAddress(module, s!("TuxBoxSetBackingInvalidationCallback")) {
let set_cb: SetInvalidationCallback = core::mem::transmute::<
unsafe extern "system" fn() -> isize,
SetInvalidationCallback,
>(register);
set_cb(Some(crate::commands::page_mapping::retire_from_xmem));
}
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),
is_backed,
})
}
}
Expand Down Expand Up @@ -246,6 +263,132 @@ pub(super) fn acquire(base: u64, size: u64) -> Result<Backing> {
}
}

fn acquired_runs(base: u64, size: u64) -> Result<Option<(Vec<BackingRun>, Hold)>> {
match acquire_backing(base, size)? {
AcquiredBacking::Contiguous(Backing { hold: None, .. }) => Ok(None),
AcquiredBacking::Contiguous(Backing { address, hold: Some(hold) }) => {
Ok(Some((vec![BackingRun { address, bytes: size }], hold)))
}
AcquiredBacking::Scattered { runs, hold } => Ok(Some((runs, hold))),
}
}

fn visit_xmem_runs(
address: u64,
bytes: usize,
mut f: impl FnMut(u64, usize, usize) -> Result<()>,
) -> Option<Result<()>> {
if bytes == 0 {
return Some(Ok(()));
}
let Some(end) = address.checked_add(bytes as u64) else {
return Some(Err(E_INVALIDARG.into()));
};
let page_start = address & !0xffff;
let Some(page_end) = end.checked_next_multiple_of(65536) else {
return Some(Err(E_INVALIDARG.into()));
};
let (runs, _hold) = match acquired_runs(page_start, page_end - page_start) {
Ok(Some(ok)) => ok,
Ok(None) => return None,
Err(error) => return Some(Err(error)),
};
let mut guest_cursor = page_start;
for run in runs {
let Some(guest_next) = guest_cursor.checked_add(run.bytes) else {
return Some(Err(E_INVALIDARG.into()));
};
let copy_lo = guest_cursor.max(address);
let copy_hi = guest_next.min(end);
if copy_lo < copy_hi {
let len = (copy_hi - copy_lo) as usize;
let buf_off = (copy_lo - address) as usize;
let host_addr = run.address + (copy_lo - guest_cursor);
if let Err(err) = f(host_addr, buf_off, len) {
return Some(Err(err));
}
}
guest_cursor = guest_next;
}
Some(Ok(()))
}

pub(in super::super) fn is_backed_range(start: u64, end: u64) -> bool {
if end <= start {
return false;
}
let page_start = start & !0xffff;
let Some(page_end) = end.checked_next_multiple_of(65536) else {
return false;
};
let Some(exports) = exports() else {
return false;
};
if let Some(is_backed) = exports.is_backed {
return unsafe { is_backed(page_start, page_end - page_start) != 0 };
}
matches!(acquired_runs(page_start, page_end - page_start), Ok(Some(_)))
}

pub(in super::super) fn try_read_xmem_bytes(address: u64, dst: &mut [u8]) -> Option<bool> {
visit_xmem_runs(address, dst.len(), |host_addr, buf_off, len| {
let mut got = 0usize;
unsafe {
ReadProcessMemory(
GetCurrentProcess(),
host_addr as *const _,
dst[buf_off..buf_off + len].as_mut_ptr().cast(),
len,
Some(&mut got),
)
}?;
if got != len {
return Err(E_FAIL.into());
}
Ok(())
})
.map(|res| res.is_ok())
}

pub(in super::super) fn read_guest_bytes(address: u64, dst: &mut [u8]) -> bool {
if let Some(ok) = try_read_xmem_bytes(address, dst) {
return ok;
}
if dst.is_empty() {
return true;
}
let mut got = 0usize;
let res = unsafe {
ReadProcessMemory(
GetCurrentProcess(),
address as *const _,
dst.as_mut_ptr().cast(),
dst.len(),
Some(&mut got),
)
};
res.is_ok() && got == dst.len()
}

pub(in super::super) fn try_write_xmem_bytes(address: u64, src: &[u8]) -> Option<Result<()>> {
visit_xmem_runs(address, src.len(), |host_addr, buf_off, len| {
let mut written = 0usize;
unsafe {
WriteProcessMemory(
GetCurrentProcess(),
host_addr as *const _,
src[buf_off..buf_off + len].as_ptr().cast(),
len,
Some(&mut written),
)
}?;
if written != len {
return Err(E_FAIL.into());
}
Ok(())
})
}

#[cfg(test)]
#[path = "../../tests/device/heap_backing.rs"]
mod tests;
Loading
Loading