Skip to content
Draft
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
87 changes: 87 additions & 0 deletions runtime/d3d12/buffer_import_guest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<Place>(device.Get(),44);
auto reg=method<Register>(device.Get(),74);
auto unreg=method<Unregister>(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<Allocate>(GetProcAddress(module,"XMemAllocatePhysicalPages"));
auto map=reinterpret_cast<Map>(GetProcAddress(module,"XMemMapPhysicalPages"));
auto free_pages=reinterpret_cast<Free>(GetProcAddress(module,"XMemFreePhysicalPages"));
auto reserve=reinterpret_cast<Reserve>(GetProcAddress(module,"XMemVirtualAlloc"));
if(!allocate||!map||!free_pages||!reserve)throw std::runtime_error("xmem exports");
std::array<UINT64,pages> tokens{};
SIZE_T count=pages;
if(!allocate(0x20400000,&count,tokens.data())||count!=pages)
throw std::runtime_error("allocate physical pages");
auto guest=static_cast<UINT*>(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<shadow_words;++i)guest[i]=0x12340000u+i;
auto address=reinterpret_cast<UINT64>(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<ID3D12Resource> 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<ID3D12CommandQueue> queue;
check(device->CreateCommandQueue(&queue_desc,IID_PPV_ARGS(&queue)),"shadow queue");
ComPtr<ID3D12Fence> 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<ID3D12CommandAllocator> allocator;
check(device->CreateCommandAllocator(queue_desc.Type,IID_PPV_ARGS(&allocator)),"shadow allocator");
ComPtr<ID3D12GraphicsCommandList> list;
const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT,0,1,0};
check(method<CreateList>(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<const UINT*>(ptr);
UINT good=0;
for(UINT i=0;i<shadow_words;++i)good+=actual[i]==guest[i];
readback->Unmap(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;i<shadow_words;++i)guest[i]=0x98760000u+i*7u;
UINT second=observe(1);
imported.Reset();
if(token)unreg(device.Get(),token);
if(free_pages)free_pages(pages,tokens.data());
if(first!=shadow_words||second!=shadow_words)
throw std::runtime_error("shadow readback differs: "+std::to_string(first)+"/"+std::to_string(second));
char receipt[160];
std::snprintf(receipt,sizeof(receipt),"d3d12-buffer-shadow PASS pci=%04x:%04x words=%u/%u passes=2",
selected.VendorId,selected.DeviceId,shadow_words,shadow_words);
return receipt;
}

}
int wmain(int argc,wchar_t** argv){
if(argc>1 && !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"))
Expand Down
99 changes: 69 additions & 30 deletions runtime/d3d12/src/device/heap/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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<u8>,
/// What the guest held when the shadow was last synchronised.
guest: GuestState,
block_digests: Vec<Digest>,
}

/// 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<u64>,
}

impl GuestState {
fn new(size: usize) -> Result<Self> {
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::<u64>()
}

/// 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
Expand Down Expand Up @@ -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,
}

Expand Down Expand Up @@ -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() {
Expand All @@ -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::<Digest>()) as u64;
let shadow_base = guard.0;
guard.0 = 0;
Ok(Arc::new(Self {
Expand All @@ -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),
}))
}

Expand All @@ -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(),
}
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion runtime/d3d12/src/device/placement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
10 changes: 6 additions & 4 deletions runtime/d3d12/src/device/placement/check_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand All @@ -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);
Expand All @@ -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();
Expand Down Expand Up @@ -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<Vec<upload::Change>> {
if textures.is_empty() {
return Ok(Vec::new());
Expand Down
26 changes: 26 additions & 0 deletions runtime/d3d12/src/device/placement/digest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading