diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 46cf638c057..570d22d50f7 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -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()); @@ -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(); @@ -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")] @@ -711,6 +715,7 @@ impl Host { } } self.log_messages(); + completed } /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations @@ -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::().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::().read(); + data.cast::().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::().write(saved); + readback.Map(0, None, Some(&mut mapped)).ok()?; + let value = mapped.cast::().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 { @@ -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 { + 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 diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 583781830aa..57e9112e82d 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -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, + #[cfg(not(windows))] + owner: Option>, +} + +#[cfg(not(windows))] +struct ImportedAllocation { + ptr: NonNull, + 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, } pub type AllocRoutine = extern "win64" fn(usize, u64) -> *mut c_void; @@ -624,6 +654,8 @@ impl Memory { ptr, layout, attributes: Some(attributes), + #[cfg(not(windows))] + owner: None, }) } @@ -649,12 +681,43 @@ impl Memory { ptr, layout, attributes: None, + #[cfg(not(windows))] + owner: None, }) } + + #[cfg(not(windows))] + fn import_upload(&mut self) -> Option { + 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. @@ -668,6 +731,8 @@ struct Heap { object: Object, desc: HeapDesc, memory: Memory, + #[cfg(not(windows))] + imported: Option, } pub(crate) extern "win64" fn create_heap( @@ -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 = 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) } @@ -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::() }.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 { @@ -936,7 +1032,7 @@ fn hand_out_resource( }); if desc.dimension == BUFFER { let at = std::ptr::from_ref::(&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) } @@ -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::() }.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::(), 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, diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index c7b390b1d83..814c4112cc2 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -29,6 +29,8 @@ pub(crate) struct Shadow { pub(crate) buffer: ID3D12Resource, data: *mut u8, gpu: u64, + /// Offset in an imported upload heap, whose bytes already belong to the title. + imported_offset: Option, /// Where the title buffer starts and how long it is. start: u64, len: u64, @@ -96,22 +98,38 @@ impl Shadow { /// Offset of a title address from the buffer's start. pub(crate) fn offset(&self, address: u64) -> u64 { - address - self.start + self.imported_offset.unwrap_or(0) + (address - self.start) } /// Brings `len` bytes at `address` up to date when `list` is submitted, /// and keeps the copy alive until the list is reset. pub(crate) fn refresh(self: &Arc, list: &HostList, address: u64, len: u64) { + if self.imported_offset.is_some() { + list.keep(&self.buffer); + return; + } let len = len.min(self.start + self.len - address); list.defer_refresh(self, address as usize, len as usize); } - fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow { - let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; + fn new( + buffer: ID3D12Resource, + data: *mut u8, + gpu: u64, + start: u64, + len: u64, + imported_offset: Option, + ) -> Shadow { + let pages = if imported_offset.is_some() { + 0 + } else { + (start + len).div_ceil(PAGE as u64) - start / PAGE as u64 + }; Shadow { buffer, data, gpu, + imported_offset, start, len, copied: Mutex::new(vec![0; pages as usize]), @@ -138,6 +156,9 @@ impl Shadow { /// before the submission (a copy per declared range and submission); /// a GPU-side dirty mask would save that if big ranges make it slow. pub(crate) fn gpu_writes(self: &Arc, list: &HostList, address: u64, len: u64) { + if self.imported_offset.is_some() { + return; // Upload heaps only have host GPU read views. + } let len = len.min(self.left(address)); list.defer_gpu_write(self, address as usize, len as usize); } @@ -263,6 +284,9 @@ impl Shadow { /// since it was last copied (all of it if the memory is not /// write-watched). Returns the bytes copied. pub(crate) fn update(&self, address: usize, len: usize) -> usize { + if self.imported_offset.is_some() { + return 0; + } let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (address.max(start), (address + len).min(end)); if from >= to { @@ -379,11 +403,30 @@ fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> { /// A title buffer exists at `start` (`len` bytes). pub(crate) fn register(resource: usize, start: u64, len: u64) { + register_shadow(resource, start, len, None); +} + +/// A placed upload buffer shares the host resource of its whole guest heap. +#[cfg(not(windows))] +pub(crate) fn register_upload( + resource: usize, + start: u64, + len: u64, + buffer: &ID3D12Resource, + offset: u64, +) { + // SAFETY: a live buffer covering the complete upload heap. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + offset; + let shadow = Arc::new(Shadow::new(buffer.clone(), std::ptr::null_mut(), gpu, start, len, Some(offset))); + register_shadow(resource, start, len, Some(shadow)); +} + +fn register_shadow(resource: usize, start: u64, len: u64, shadow: Option>) { buffers().insert( (start, resource), Entry { end: start + len, - shadow: None, + shadow, }, ); } @@ -430,7 +473,7 @@ pub(crate) fn find(address: u64, len: u64) -> Option> { "buffer copied to the host" ); } - entry.shadow = Some(Arc::new(Shadow::new(buffer, data, gpu, key.0, len))); + entry.shadow = Some(Arc::new(Shadow::new(buffer, data, gpu, key.0, len, None))); } entry.shadow.clone() } @@ -461,7 +504,7 @@ fn loose(address: u64, end: u64) -> Option> { len, "loose memory copied to the host" ); - let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len)); + let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len, None)); map.insert((start, len), shadow.clone()); Some(shadow) }