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
113 changes: 110 additions & 3 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ impl Host {
}

/// Runs closed lists and waits for them.
pub(crate) fn execute(&self, runs: &[&HostList]) {
pub(crate) fn execute(&self, runs: &[&HostList]) -> bool {
// One submission at a time from preparation to copy-back: snapshots
// and the ranges shaders write are per host copy, not per submission.
let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
Expand Down Expand Up @@ -616,6 +616,7 @@ impl Host {
};
#[cfg(not(feature = "diagnostics"))]
let groups = [&lists[..]];
let mut completed = true;
for (i, group) in groups.iter().enumerate() {
*submitted += 1;
let started = std::time::Instant::now();
Expand All @@ -639,11 +640,14 @@ impl Host {
match waited {
#[cfg(windows)]
Ok(()) => {
WaitForSingleObject(self.event, INFINITE);
completed &= WaitForSingleObject(self.event, INFINITE).0 == 0;
}
#[cfg(not(windows))]
Ok(()) => {}
Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
Err(e) => {
completed = false;
tracing::warn!(error = %e, "host submission not waited for");
}
}
}
#[cfg(feature = "diagnostics")]
Expand Down Expand Up @@ -711,6 +715,7 @@ impl Host {
}
}
self.log_messages();
completed
}

/// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
Expand Down Expand Up @@ -1582,6 +1587,78 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us
}

impl Host {
/// Imports a fresh, private upload allocation. The one-time readback
/// detects drivers that substitute their own memory after an import fails.
///
/// # Safety
/// `data` is an exclusive, writable allocation of `size` bytes. The
/// caller must keep it allocated until the returned heap is destroyed.
#[cfg(not(windows))]
pub(crate) unsafe fn import_upload(
&self,
data: *mut u8,
size: usize,
) -> Option<(ID3D12Heap, ID3D12Resource)> {
const ALIGN: usize = 64 << 10;
const MARKER: u64 = 0x5892_0436_28b0_b54a;
if size == 0 || !size.is_multiple_of(ALIGN) || !data.addr().is_multiple_of(ALIGN) {
return None;
}
let device = self.device.cast::<ID3D12Device13>().ok()?;
// SAFETY: the caller owns this aligned and accessible allocation.
let heap: ID3D12Heap = unsafe { device.OpenExistingHeapFromAddress1(data.cast(), size) }.ok()?;
// SAFETY: plain query on a live heap.
if (unsafe { heap.GetDesc() }.Flags & D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER) == D3D12_HEAP_FLAG_NONE {
return None;
}
let mut buffer = None;
// SAFETY: this buffer fits in the imported heap from offset zero.
unsafe {
self.device.CreatePlacedResource(
&heap,
0,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size as u64,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER,
..Default::default()
},
D3D12_RESOURCE_STATE_GENERIC_READ,
None,
&mut buffer,
)
}.ok()?;
let buffer = buffer?;
let readback = self.readback_buffer(8)?;
let list = self.new_list().ok()?;
// SAFETY: the backing data is private and both buffers are live.
let saved = unsafe {
let saved = data.cast::<u64>().read();
data.cast::<u64>().write(MARKER);
list.list.CopyBufferRegion(&readback, 0, &buffer, 0, 8);
saved
};
list.close();
if !self.execute(&[&list]) {
fail(format_args!("could not wait for the imported upload heap check"));
}
let mut mapped = std::ptr::null_mut();
// SAFETY: the list has finished and the readback holds one u64.
let observed = unsafe {
data.cast::<u64>().write(saved);
readback.Map(0, None, Some(&mut mapped)).ok()?;
let value = mapped.cast::<u64>().read();
readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }));
value
};
(observed == MARKER).then_some((heap, buffer))
}

/// A buffer in the upload heap, mapped for writing.
pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
let heap = D3D12_HEAP_PROPERTIES {
Expand Down Expand Up @@ -1627,6 +1704,36 @@ impl Host {
}
}
}

/// A buffer that the CPU can read after its host submission completes.
#[cfg(not(windows))]
pub(crate) fn readback_buffer(&self, size: u64) -> Option<ID3D12Resource> {
let mut buffer = None;
// SAFETY: a valid buffer description and an out pointer for its resource.
unsafe {
self.device.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_READBACK,
..Default::default()
},
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size.max(8),
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
},
D3D12_RESOURCE_STATE_COPY_DEST,
None,
&mut buffer,
)
}.ok()?;
buffer
}
}

/// The swap chain formats a presented texture can be copied into: its own
Expand Down
158 changes: 157 additions & 1 deletion crates/victory-gpu/src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,36 @@ pub(crate) struct Memory {
/// Set when the memory came from the title's allocator, with these
/// allocation attributes (it goes back there).
attributes: Option<u64>,
#[cfg(not(windows))]
owner: Option<std::sync::Arc<ImportedAllocation>>,
}

#[cfg(not(windows))]
struct ImportedAllocation {
ptr: NonNull<u8>,
layout: Layout,
}

// SAFETY: this type owns the allocation. Access to its bytes is through the
// runtime's raw guest pointers, and freeing does not require guest TLS.
#[cfg(not(windows))]
unsafe impl Send for ImportedAllocation {}
// SAFETY: both fields only describe the owned allocation.
#[cfg(not(windows))]
unsafe impl Sync for ImportedAllocation {}

#[cfg(not(windows))]
impl Drop for ImportedAllocation {
fn drop(&mut self) {
// SAFETY: this is the last owner of the allocation from Memory::new.
unsafe { dealloc(self.ptr.as_ptr(), self.layout) };
}
}

#[cfg(not(windows))]
#[windows_core::implement]
struct ImportedHeapKeepalive {
_allocation: std::sync::Arc<ImportedAllocation>,
}

pub type AllocRoutine = extern "win64" fn(usize, u64) -> *mut c_void;
Expand Down Expand Up @@ -624,6 +654,8 @@ impl Memory {
ptr,
layout,
attributes: Some(attributes),
#[cfg(not(windows))]
owner: None,
})
}

Expand All @@ -649,12 +681,43 @@ impl Memory {
ptr,
layout,
attributes: None,
#[cfg(not(windows))]
owner: None,
})
}

#[cfg(not(windows))]
fn import_upload(&mut self) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
use windows::core::{GUID, IUnknown};

const KEEPALIVE: GUID = GUID::from_u128(0x340535d6_2bc0_42a9_a30f_d9430b7b275c);
if self.attributes.is_some() || self.owner.is_some() {
return None;
}
// SAFETY: this is a fresh renderer allocation. We retain it below
// on the host heap, which the returned placed buffer retains.
let (heap, buffer) = unsafe {
crate::host::host()?.import_upload(self.ptr.as_ptr(), self.layout.size())?
};
let allocation = self.owner.insert(std::sync::Arc::new(ImportedAllocation {
ptr: self.ptr,
layout: self.layout,
}));
let keepalive: IUnknown = ImportedHeapKeepalive { _allocation: allocation.clone() }.into();
// SAFETY: a live heap and interface. vkd3d-proton frees its imported
// VkDeviceMemory before releasing the heap's private interfaces.
unsafe { heap.SetPrivateDataInterface(&KEEPALIVE, &keepalive) }.ok()?;
tracing::info!(bytes = self.layout.size(), "imported a Linux native upload heap");
Some(buffer)
}
}

impl Drop for Memory {
fn drop(&mut self) {
#[cfg(not(windows))]
if self.owner.is_some() {
return;
}
match (self.attributes, ALLOCATOR.get()) {
(Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes),
// SAFETY: allocated in `new` with this layout.
Expand All @@ -668,6 +731,8 @@ struct Heap {
object: Object,
desc: HeapDesc,
memory: Memory,
#[cfg(not(windows))]
imported: Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource>,
}

pub(crate) extern "win64" fn create_heap(
Expand Down Expand Up @@ -697,10 +762,26 @@ pub(crate) extern "win64" fn create_heap(
Ok(memory) => memory,
Err(hr) => return hr,
};
#[cfg(not(windows))]
let (memory, imported) = {
const UPLOAD_HEAP: u32 = 2;
static IMPORT_UPLOADS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let mut memory = memory;
let imported = if desc.properties.kind == UPLOAD_HEAP
&& *IMPORT_UPLOADS.get_or_init(|| std::env::var_os("VICTORY_IMPORT_UPLOADS").is_some_and(|v| v == "1"))
{
memory.import_upload()
} else {
None
};
(memory, imported)
};
let heap = Box::new(Heap {
object: Object::new(&HEAP_FUNCTIONS),
desc,
memory,
#[cfg(not(windows))]
imported,
});
object::hand_out(HEAP, heap, iid, &HEAP_IIDS, out)
}
Expand Down Expand Up @@ -900,6 +981,21 @@ impl Resource {
Backing::Address(at) => at,
}
}

fn register_buffer(&self, resource: usize) {
let start = self.data() as u64;
#[cfg(not(windows))]
if let Backing::Placed { heap, offset } = self.backing
&& self.desc.flags & 0x4 == 0 // D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
{
// SAFETY: a placed resource holds a reference to its heap.
if let Some(buffer) = unsafe { &*heap.cast::<Heap>() }.imported.as_ref() {
crate::shadow::register_upload(resource, start, self.desc.width, buffer, offset);
return;
}
}
crate::shadow::register(resource, start, self.desc.width);
}
}

fn resource<'a>(this: This) -> &'a Resource {
Expand Down Expand Up @@ -936,7 +1032,7 @@ fn hand_out_resource(
});
if desc.dimension == BUFFER {
let at = std::ptr::from_ref::<Resource>(&resource) as usize;
crate::shadow::register(at, resource.data() as u64, desc.width);
resource.register_buffer(at);
}
object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out)
}
Expand Down Expand Up @@ -1368,6 +1464,66 @@ mod tests {
}
}

#[cfg(not(windows))]
#[test]
#[ignore = "needs a D3D12 device and explicit upload-import test settings"]
fn placed_upload_reads_the_guest_bytes() {
use windows::Win32::Graphics::Direct3D12::D3D12_RANGE;

const BYTES: usize = 256;
let direct = std::env::var_os("VICTORY_EXPECT_DIRECT_UPLOAD").is_some_and(|v| v == "1");
let host = crate::host::host().expect("D3D12 device");
let null = std::ptr::null();
let mut heap = null;
let desc = HeapDesc {
size: 2 * KIB_64,
properties: HeapProperties { kind: 2, ..PROPERTIES },
alignment: KIB_64,
flags: 0,
};
assert_eq!(create_heap(null, &desc, &HEAP_IIDS[0], &mut heap), S_OK);
// SAFETY: create_heap returned a live guest heap.
let owned = unsafe { &*heap.cast::<Heap>() }.memory.owner.as_ref().map(std::sync::Arc::downgrade);
assert_eq!(owned.is_some(), direct);

let mut placed = null;
assert_eq!(
create_placed(null, heap, KIB_64, &buffer(KIB_64), 0, null.cast(), &RESOURCE_IIDS[0], &mut placed),
S_OK
);
let address = resource(placed).data();
let shadow = crate::shadow::find(address as u64, BYTES as u64).unwrap();
assert_eq!(shadow.offset(address as u64), if direct { KIB_64 } else { 0 });

let list = host.new_list().unwrap();
let readback = host.readback_buffer(BYTES as u64).unwrap();
shadow.refresh(&list, address as u64, BYTES as u64);
// SAFETY: the placed allocation is live and the copy fits both buffers.
unsafe {
address.write_bytes(57, BYTES);
list.list.CopyBufferRegion(&readback, 0, &shadow.buffer, shadow.offset(address as u64), BYTES as u64);
}
drop(shadow);
list.close();
if direct {
assert_eq!(resource_release(placed), 0);
assert_eq!(heap_release(heap), 0);
assert!(owned.unwrap().upgrade().is_some());
}
assert!(host.execute(&[&list]));
let mut mapped = std::ptr::null_mut();
// SAFETY: readback contains the finished copy and the CPU only reads it.
unsafe {
readback.Map(0, None, Some(&mut mapped)).unwrap();
assert_eq!(std::slice::from_raw_parts(mapped.cast::<u8>(), BYTES), &[57; BYTES]);
readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 }));
}
if !direct {
assert_eq!(resource_release(placed), 0);
assert_eq!(heap_release(heap), 0);
}
}

fn texture(width: u64, height: u32, format: u32, mips: u16) -> ResourceDesc {
ResourceDesc {
dimension: 3,
Expand Down
Loading