diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index a04e35327..30065b3b8 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -177,7 +177,10 @@ the runtime made. unified memory a `Managed` buffer has two copies, as on a Mac with a discrete GPU (`did_modify_range` and a blit's `synchronize_resource` move the bytes), and a `Shared` resource lies in host-cached system memory (announced once, `shared-in-system-memory`). -- **New resources** read what plain Metal's measured answer is: a new buffer reads zero. +- **New resources** read what plain Metal's measured answer is: a new buffer reads zero. A + host-visible buffer longer than 32 MiB lies, where the device imports host pointers, in fresh + anonymous pages imported by their pointer, zero as mapped, so that nothing writes its zeros; a + recycled one is set to zero on the host. - **The Metal address space.** Every buffer and heap has a `gpu_address`, and textures, samplers, pipeline states and indirect command buffers a `gpu_resource_id`. Translated shaders read both from argument buffers, as on Metal 3. A consumer may pin either (`AddressPlacement`, @@ -208,8 +211,9 @@ the runtime made. between commands whose bytes are apart, as it does between untracked uses Metal leaves to the program; no order of either changes a result. - **Textures over buffers** share the buffer's bytes. The runtime keeps a copy and announces it - (`shadowed-texture`) over a no-copy buffer's host pages (an image bound to them would start - `UNDEFINED`, and its first move may rewrite any byte bound to it), where the device's linear + (`shadowed-texture`) over a no-copy buffer's host pages or such a long buffer's fresh pages (an + image bound to them would start `UNDEFINED`, and its first move may rewrite any byte bound to + it), where the device's linear images cannot hold Metal's layout, and where the rows lie with bytes between them. ## Runtime extensions diff --git a/crates/metal2vulkan-runtime/examples/host_ab/main.rs b/crates/metal2vulkan-runtime/examples/host_ab/main.rs index 35639bb80..fee67da19 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/main.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/main.rs @@ -276,6 +276,7 @@ fn child(side: &str, options: &Options) { "runtime work counts: queue_submissions {} command_buffers_submitted {} \ pipeline_barriers {} draws {} dispatches {} variant_pipelines_made {} \ device_memory_allocated {} host_pointer_imports_made {} \ + fresh_page_buffers_made {} fresh_page_bytes {} new_buffer_bytes_cleared {} \ requirement_images_made {} arena_pools_made {} owned_descriptor_pools {} \ draws_settled {} stage_tables_read {} graphics_pipelines_looked_up {} \ draws_pushing_set_zero {} set_zero_writes_pushed {} set_zero_sets_reused {} \ @@ -291,6 +292,9 @@ fn child(side: &str, options: &Options) { c.variant_pipelines_made, c.device_memory_allocated, c.host_pointer_imports_made, + c.fresh_page_buffers_made, + c.fresh_page_bytes, + c.new_buffer_bytes_cleared, c.requirement_images_made, c.arena_pools_made, c.owned_descriptor_pools, diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 05f7d19b9..929254519 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -28,6 +28,7 @@ use super::degradation::Degradation; use super::device::{lock, DeviceShared}; use super::error::{internal, invalid, nil, vulkan, Error, Problem}; use super::exit_guard; +use super::fresh_pages; use super::generated_commands::PREPROCESS_BUFFER; use super::heap::{Heap, HeapType}; use super::host_aliases::Alias; @@ -1869,8 +1870,12 @@ impl Device { of_heap: bool, placement: impl Into, ) -> Result { - let buffer = + let (buffer, bytes) = self.placed_new_buffer(call, length, modes, class, of_heap, placement.into())?; + // Fresh pages read zero as mapped (`fresh_pages.rs`): nothing is written. + if bytes == NewBytes::Zero { + return Ok(buffer); + } // Dropping `buffer` on failure releases it. buffer.clear_first()?; Ok(buffer) @@ -1902,18 +1907,20 @@ impl Device { if length == 0 || length > self.properties().max_buffer_length { return Err(nil(CALL, Problem::BufferLength { length })); } - self.placed_new_buffer( + let (buffer, _) = self.placed_new_buffer( CALL, length, modes, class, false, AddressPlacement::Outside.into(), - ) + )?; + Ok(buffer) } - /// [`zeroed_buffer`](Device::zeroed_buffer)'s buffer before its bytes are set to zero: its - /// bytes are its memory's as placed. A buffer not of a heap is a parked one of the same making + /// [`zeroed_buffer`](Device::zeroed_buffer)'s buffer before its bytes are set to zero, and + /// what they hold: its memory's bytes as placed, or zero where it lies in fresh pages it + /// imported (`fresh_pages.rs`). A buffer not of a heap is a parked one of the same making /// where the recycler holds one, and is noted as one it may park as it goes (`recycle.rs`). fn placed_new_buffer( &self, @@ -1923,7 +1930,7 @@ impl Device { class: MemoryClass, of_heap: bool, placement: Place, - ) -> Result { + ) -> Result<(Buffer, NewBytes), Error> { if self.is_lost() { return Err(Error::DeviceLost); } @@ -1949,23 +1956,55 @@ impl Device { .size(size) .usage(usage(false)), ); - // A heap's own buffer lies where its textures can too, and is never parked. - let making = (!of_heap).then_some(BufferMaking { size, class }); - let taken = making.and_then(|making| self.recycled_buffer(&making)); - let made = match taken { - Some((raw, memory)) => { - // Its range of the address space is a new one, as a new buffer's. - let address = lock(&shared.addresses).place(placement, length); - match address { - Ok(address) => Ok((raw, (memory, address))), - Err(error) => { - lock(&shared.recycled_buffers).forget(raw); - recycle::destroy(raw_device, &mut lock(&shared.memory), [(raw, memory)]); - Err(error) - } + // A heap's own buffer lies where its textures can too, and is never parked. A long + // host-visible one of the runtime's own lies in fresh pages where the device takes them. + let wants_fresh = + !of_heap && fresh_pages::takes_fresh_pages(size, class) && shared.host_import.is_ok(); + let making = (!of_heap).then_some(BufferMaking { + size, + class, + fresh_pages: wants_fresh, + }); + let mut taken = making.and_then(|making| self.recycled_buffer(&making)); + let fresh = match (&taken, wants_fresh) { + (None, true) => self.fresh_page_buffer(size, class)?, + _ => None, + }; + // Where the device took no fresh pages, a parked buffer of its own memory, made so as the + // buffer is made below. + if let (None, None, Some(making)) = (&taken, &fresh, making.filter(|_| wants_fresh)) { + let making = BufferMaking { + fresh_pages: false, + ..making + }; + taken = self.recycled_buffer(&making); + } + let bytes = match fresh { + Some(_) => NewBytes::Zero, + None => NewBytes::AsPlaced, + }; + // Its range of the address space is a new one, as a new buffer's; the buffer and its + // memory go again where none is left. + let place_address = |raw, memory: Placement| { + let address = lock(&shared.addresses).place(placement, length); + match address { + Ok(address) => Ok((raw, (memory, address))), + Err(error) => { + lock(&shared.recycled_buffers).forget(raw); + recycle::destroy(raw_device, &mut lock(&shared.memory), [(raw, memory)]); + Err(error) } } - None => (|| { + }; + let made = match (taken, fresh) { + (Some((raw, memory)), _) => place_address(raw, memory), + (None, Some((raw, memory))) => { + if let Some(making) = making { + lock(&shared.recycled_buffers).made(raw, making); + } + place_address(raw, memory) + } + (None, None) => (|| { // SAFETY: the device is live and `info` valid. let raw = unsafe { raw_device.create_buffer(&info, None) }.map_err(vulkan)?; shared.counts.buffer_made(info.usage); @@ -1976,7 +2015,12 @@ impl Device { }; match placed { Ok(placed) => { + // Not in fresh pages, whatever was asked: the device took none. if let Some(making) = making { + let making = BufferMaking { + fresh_pages: false, + ..making + }; lock(&shared.recycled_buffers).made(raw, making); } Ok((raw, placed)) @@ -1991,7 +2035,7 @@ impl Device { }; // On failure the host copy, unused, goes with `mirror` (`Mirror`'s drop). let (raw, (placement, (address, reserved))) = made?; - Ok(self.buffer_of(BufferParts { + let buffer = self.buffer_of(BufferParts { raw, memory: placement, offset: 0, @@ -2007,7 +2051,8 @@ impl Device { mirror, #[cfg(unix)] again: None, - })) + }); + Ok((buffer, bytes)) } /// A parked buffer of `making` (`recycle.rs`), now live, where the recycler holds one. @@ -2439,6 +2484,15 @@ impl Device { } } +/// What a new buffer's bytes hold as [`Device::placed_new_buffer`] makes it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum NewBytes { + /// Its memory's bytes as placed: undefined, or a parked buffer's last owner's. + AsPlaced, + /// Zero: fresh pages it imported (`fresh_pages.rs`). + Zero, +} + /// The memory class of a buffer of `modes`' storage and CPU cache modes, for `call`: refused for /// `Memoryless`, which is no buffer's. `Shared` storage is `MemoryClass::WriteCombined` in the /// write-combined CPU cache mode, which the host does not read. @@ -2484,6 +2538,18 @@ impl Heap { } impl Buffer { + /// Whether the buffer lies in fresh pages it imported (`fresh_pages.rs`), to which no image + /// is bound: false for a no-copy buffer, a heap's and one over the caller's `VkBuffer`. + pub(super) fn in_fresh_pages(&self) -> bool { + match &self.0.bytes { + Bytes::Own(OwnBytes { + lie: Lie::Fixed(fixed), + .. + }) => fixed.pages.memory.placement.over_own_pages(), + Bytes::Own(_) | Bytes::Heap(_) => false, + } + } + /// Whether the buffer's own pages, of the runtime's memory, lie in device-local memory; `None` /// for a heap's buffer, whose bytes are its heap's. A buffer's pages are its for good. pub(super) fn own_pages_device_local(&self) -> Option { @@ -2557,6 +2623,7 @@ impl Buffer { // SAFETY: as in `clear`: the buffer's host-coherent bytes, which nothing else uses // yet. unsafe { std::ptr::write_bytes(contents.as_ptr(), 0, size as usize) }; + self.0.device.shared().counts.new_buffer_cleared(size); if self.mirror().is_none() { return Ok(()); } diff --git a/crates/metal2vulkan-runtime/src/fresh_pages.rs b/crates/metal2vulkan-runtime/src/fresh_pages.rs new file mode 100644 index 000000000..d97c37c21 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/fresh_pages.rs @@ -0,0 +1,198 @@ +//! Large new buffers in fresh pages: a host-visible buffer of the runtime's own longer than half a +//! pooled block lies in anonymous pages the runtime maps for it and imports by their pointer +//! (`VK_EXT_external_memory_host`), not in memory the device allocates, so nothing writes its +//! zeros. +//! +//! - **Why.** A new Metal buffer reads zero (`Device::new_buffer`). Memory the device allocates +//! holds undefined bytes, so the runtime sets a new buffer's to zero on the host +//! (`Buffer::clear_first`), and in memory no buffer used before that write is the CPU's first +//! touch of each page. Measured on an M3 Max under MoltenVK 1.4.1, for 64 MiB, it took 2.1 to +//! 2.3 ms, on top of the allocation's 1.1 to 1.3 ms (MoltenVK's heap and its residency set's +//! commit). A memset of pages already touched took 0.29 ms. Metal made the buffer in 6 us and +//! paid for its pages at their first touch. Anonymous pages are zero when mapped. Apple's +//! mmap(2) says "MAP_ANON Map zero-filled anonymous memory not associated with any specific +//! file", and Linux's says of `MAP_ANONYMOUS` "its contents are initialized to zero". An import +//! of them is that memory (`VkImportMemoryHostPointerInfoEXT`). So the buffer reads zero with +//! nothing written, and the first touch is paid where the program makes it, as on Metal. The +//! import costs what the allocation it replaces costs (the same commit, 1.0 to 1.2 ms for +//! 64 MiB). +//! - **Which.** A buffer that takes a block of its own (`memory.rs`'s `place`): longer than half a +//! pooled block ([`FRESH_PAGES_PAST`]), not of a heap, whose bytes the host maps in memory of +//! its class (`Shared`, write-combined, `Managed` with unified memory). The device must import +//! host pointers (`host_memory.rs`'s `Importer`), and the class's best memory type for the buffer +//! must take the pages: else the buffer lies where it would have, made as ever. A shorter one +//! lies in a pooled block. There the bytes a buffer used before are set to zero by a memset of +//! pages already touched (about 4.5 us per MiB), which is cheaper than an import of fresh ones +//! (16 us per MiB). An import also costs 17 to 43 us whatever its size, against a pooled +//! placement's none. +//! - **Recycled.** A parked buffer of the same making (`recycle.rs`) is still taken first, and its +//! bytes set to zero on the host (0.29 ms for 64 MiB), since its pages hold its last owner's. +//! Only a buffer made here reads zero unwritten. +//! - **Textures over it** take the shadow (`shadow.rs`). An image bound to imported memory starts +//! `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), and its first move may write any byte +//! bound to it. Counted: `WorkCounts::shadows_over_fresh_pages`. +//! - **Freed.** The pages are unmapped once the memory imported from them is freed, since the +//! import requires them mapped for its whole life. That happens with the buffer's block, or +//! after it where freed memory waits for the batches in flight (`freed_memory.rs`). +//! - **Counted**: `WorkCounts::fresh_page_buffers_made` and `fresh_page_bytes`. + +use super::buffer::usage; +use super::device::lock; +use super::error::{vulkan, Error}; +use super::memory::{self, MemoryClass, Placement, BLOCK_BYTES}; +use crate::release; +use crate::Device; +use ash::vk; +use std::ptr::NonNull; + +/// The length past which a host-visible buffer of the runtime's own lies in fresh pages: half a +/// pooled block, past which it takes a block of its own (the module docs). +pub(super) const FRESH_PAGES_PAST: u64 = BLOCK_BYTES / 2; + +/// Whether a buffer of `size` bytes (its padded length) in memory of `class` lies in fresh pages +/// where the device takes them (the module docs): `class` is the buffer's after a `Managed` +/// buffer on a device without unified memory took `Private` memory and a host copy. +pub(super) fn takes_fresh_pages(size: u64, class: MemoryClass) -> bool { + let host_visible = matches!( + class, + MemoryClass::Shared | MemoryClass::WriteCombined | MemoryClass::Managed + ); + host_visible && size > FRESH_PAGES_PAST && cfg!(unix) +} + +/// Anonymous private pages the runtime mapped for a buffer of its own, read-write and zero, and +/// unmapped as this goes: after the memory imported from them is freed (`memory.rs`'s `Block`). +#[derive(Debug)] +pub(crate) struct OwnPages { + pointer: NonNull, + length: u64, +} + +// SAFETY: the pages are the runtime's alone; who writes them is the resource API's contract +// (Metal's `contents`), and unmapping them is this value's alone. +unsafe impl Send for OwnPages {} +// SAFETY: as above; a shared `OwnPages` answers its pointer and length alone. +unsafe impl Sync for OwnPages {} + +impl OwnPages { + /// `length` bytes of new anonymous private pages, read-write, at a host page; `None` where + /// the system maps none. + #[cfg(unix)] + fn map(length: u64) -> Option { + let bytes = usize::try_from(length).ok()?; + // SAFETY: a new private anonymous mapping, at an address the kernel picks. + let pointer = unsafe { + libc::mmap( + std::ptr::null_mut(), + bytes, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_ANON | libc::MAP_PRIVATE, + -1, + 0, + ) + }; + if pointer == libc::MAP_FAILED { + return None; + } + let pointer = NonNull::new(pointer.cast::())?; + Some(OwnPages { pointer, length }) + } + + /// No pages are mapped on this system. + #[cfg(not(unix))] + fn map(_length: u64) -> Option { + None + } + + /// Where the pages start. + pub(super) fn pointer(&self) -> NonNull { + self.pointer + } + + /// Their bytes. + pub(super) fn length(&self) -> u64 { + self.length + } +} + +impl Drop for OwnPages { + fn drop(&mut self) { + #[cfg(unix)] + // SAFETY: the mapping is this value's, and nothing reads it any more: the memory + // imported from it was freed first (`memory.rs`'s `Block`). + unsafe { + libc::munmap(self.pointer.as_ptr().cast(), self.length as usize); + } + } +} + +impl Device { + /// A `VkBuffer` of `size` bytes, made for host allocations with every usage of a buffer of + /// its own and the device-address usage where the device enables it (its address is its own, + /// as no block's buffer of addresses lies in the pages), bound in fresh pages imported as + /// memory of `class`: the buffer and its placement, its bytes zero (the module docs). `None` + /// where the device takes no such pages: it imports no host pointer, the system maps none, + /// the class's best memory type for the buffer is not among those the pages allow, or the + /// driver refuses them. Refused where the buffer cannot be made at all. + pub(super) fn fresh_page_buffer( + &self, + size: u64, + class: MemoryClass, + ) -> Result, Error> { + let shared = self.shared(); + let Ok(importer) = &shared.host_import else { + return Ok(None); + }; + let raw_device = shared.vk(); + let mut external = vk::ExternalMemoryBufferCreateInfo::default() + .handle_types(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT); + let info = shared.sharing().buffer( + vk::BufferCreateInfo::default() + .size(size) + .usage(usage(shared.device_address)) + .push_next(&mut external), + ); + // SAFETY: the device is live and `info` and its chain valid. + let raw = unsafe { raw_device.create_buffer(&info, None) }.map_err(vulkan)?; + shared.counts.buffer_made(info.usage); + // SAFETY: `raw` is a live buffer of this device. + let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; + // Whole units of the host page and the import alignment, as the import requires of the + // pointer and the length, and room for the buffer's requirements. + let unit = (importer.page) + .max(importer.alignment) + .max(requirements.alignment); + let placed = (requirements.size.max(size)) + .checked_next_multiple_of(unit) + .and_then(OwnPages::map) + .and_then(|pages| { + // SAFETY: the pages are host memory of this process at a multiple of the unit, + // which the import alignment divides (both are powers of two). + let types = unsafe { importer.memory_types(raw_device, pages.pointer()) }.ok()?; + // The memory type the buffer would take without the pages: the pages take it, or + // the buffer lies there as ever. + let best = lock(&shared.memory).best_type(requirements.memory_type_bits, class)?; + if types & 1 << best == 0 { + return None; + } + memory::import_own_pages(&shared.memory, raw_device, pages, best).ok() + }); + let Some(placement) = placed else { + // SAFETY: the buffer is unused. + unsafe { release::object(raw_device, raw) }; + return Ok(None); + }; + // SAFETY: the placement is the pages' memory, at least the buffer's size and of a type it + // takes, at offset 0, which every alignment divides; the buffer is unbound. + if let Err(error) = + unsafe { raw_device.bind_buffer_memory(raw, placement.memory, placement.offset) } + { + // SAFETY: the buffer is unused. + unsafe { release::object(raw_device, raw) }; + lock(&shared.memory).free(raw_device, &placement); + return Err(vulkan(error)); + } + shared.counts.fresh_page_buffer_made(placement.size()); + Ok(Some((raw, placement))) + } +} diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index b7feb6085..698c0e8b1 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -102,6 +102,7 @@ mod fill_value; mod fragment_imageblock; mod framebuffer_fetch; mod freed_memory; +mod fresh_pages; mod fresh_unwritten; mod function_table; #[doc(hidden)] diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 17dfbca68..23139f857 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -16,7 +16,9 @@ //! [`MemoryClass`]; [`Memory::free`] with the placement it gave. Buffers use it in step 1; //! textures and heaps add their classes and callers in their own steps. Imported host memory //! has its own entry, [`Memory::import_host`]: one dedicated block per import, never -//! pooled, freed through the same [`Memory::free`]. A dma-buf's import +//! pooled, freed through the same [`Memory::free`]. So has a buffer's fresh pages +//! ([`import_own_pages`], `fresh_pages.rs`): a dedicated block that unmaps them once its +//! memory is freed. A dma-buf's import //! (`Memory::import_dma_buf`) is in no block: the placement in it keeps it, and frees it as it //! goes (`dma_buf.rs`'s `DmaBufPages`). //! @@ -47,6 +49,7 @@ use super::device::lock; use super::dma_buf::DmaBufPages; use super::error::{internal, vulkan, Error, MemoryKind}; use super::freed_memory::{Parked, Parking}; +use super::fresh_pages::OwnPages; use super::memory_log::{self, MemoryLog}; use super::range::RangeAllocator; use super::sharing::Sharing; @@ -546,6 +549,9 @@ pub(super) struct Block { addresses: Option, /// It is the caller's host memory, imported ([`Memory::import_host`]). imported: bool, + /// The pages its memory was imported from, where the runtime mapped them for it + /// ([`import_own_pages`]): unmapped once the memory is freed. + pages: Option, /// Its memory type. type_index: u32, } @@ -567,25 +573,34 @@ impl Block { /// Nothing is placed in the block any more, and no command that reads it is pending. unsafe fn release(self, device: &ash::Device) { // SAFETY: the caller's contract. - let memory = unsafe { self.release_addresses(device) }; + let (memory, pages) = unsafe { self.release_addresses(device) }; // SAFETY: the caller's contract; freeing unmaps it. unsafe { release::object(device, memory) }; + // The pages it was imported from go after it (`VkImportMemoryHostPointerInfoEXT`). + drop(pages); } - /// Destroy the block's buffer of addresses: its memory, to free. + /// Destroy the block's buffer of addresses: its memory, to free, and the pages it was + /// imported from where the runtime mapped them, to unmap once it is freed. /// /// # Safety /// /// Nothing is placed in the block any more, and no command that reads the buffer is pending. - unsafe fn release_addresses(self, device: &ash::Device) -> vk::DeviceMemory { + unsafe fn release_addresses( + self, + device: &ash::Device, + ) -> (vk::DeviceMemory, Option) { let Block { - memory, addresses, .. + memory, + addresses, + pages, + .. } = self; if let Some(addresses) = addresses { // SAFETY: the caller's contract. unsafe { release::object(device, addresses.raw) }; } - memory + (memory, pages) } } @@ -651,6 +666,8 @@ pub(super) struct Placement { /// asked for one ([`allocate_addressed`]) on a device that enables /// `bufferDeviceAddress`. pub(super) address: Option, + /// It lies in pages the runtime mapped and imported ([`import_own_pages`]). + own_pages: bool, /// The imports of the caller's dma-bufs the placement lies in, with the source that made them /// (`dma_buf.rs`), which no block of the runtime's holds: kept until the placement goes, and /// freed, the source dropped, when their last holder goes. @@ -678,6 +695,7 @@ impl Placement { offset, mapped: mapped.map(Mapped), address: None, + own_pages: false, #[cfg(unix)] dma_buf: None, } @@ -706,6 +724,7 @@ impl Placement { offset: 0, mapped: Some(Mapped(mapped)), address: None, + own_pages: false, dma_buf: Some(pages), } } @@ -733,6 +752,12 @@ impl Placement { } } + /// Whether the placement lies in pages the runtime mapped and imported + /// ([`import_own_pages`]), to which no image is bound (`fresh_pages.rs`). + pub(super) fn over_own_pages(&self) -> bool { + self.own_pages + } + /// The imports of the caller's dma-bufs the placement lies in, with their source /// (`dma_buf.rs`); `None` for any other placement. #[cfg(unix)] @@ -765,6 +790,7 @@ impl Placement { offset: self.offset, mapped: self.mapped, address: self.address, + own_pages: self.own_pages, #[cfg(unix)] dma_buf: self.dma_buf.clone(), } @@ -1106,6 +1132,7 @@ impl Memory { .as_ref() .filter(|_| addressed) .map(|addresses| addresses.address + offset), + own_pages: payload.pages.is_some(), #[cfg(unix)] dma_buf: None, } @@ -1219,8 +1246,14 @@ impl Memory { // Out of the driver's list first, with no submission inside its `vkQueueSubmit`, whose // encoding may list it (`freed_memory.rs`), then the batches that may list it noted. // SAFETY: the caller's. - let (memory, noted) = + let ((memory, pages), noted) = parking.note_destroying(|| unsafe { block.release_addresses(device) }); + // The pages the memory was imported from go after it, with what goes once it is freed. + let after = match (pages, after) { + (None, after) => after, + (Some(pages), None) => Some(Box::new(pages) as Box), + (Some(pages), Some(after)) => Some(Box::new((pages, after)) as Box), + }; if !parking.reached(¬ed) { parking.waits(); // Checked again once counted: a waiter that published a value before the count did @@ -1274,43 +1307,38 @@ impl Memory { allowed: u32, class: MemoryClass, ) -> Result { - let mut failure = ImportFailure::NoMemoryType; - for type_index in candidates(&self.types, allowed, class, self.unified) { - let mut import = vk::ImportMemoryHostPointerInfoEXT::default() - .handle_type(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT) - .host_pointer(pointer.as_ptr().cast()); - let mut flags = vk::MemoryAllocateFlagsInfo::default() - .flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); - let mut info = vk::MemoryAllocateInfo::default() - .allocation_size(size) - .memory_type_index(type_index) - .push_next(&mut import); - if self.device_address { - info = info.push_next(&mut flags); - } - // SAFETY: `info` and its chain live for the call; the type index is the device's and - // allows the pointer; the caller's contract keeps the memory mapped. - match unsafe { device.allocate_memory(&info, None) } { - Ok(memory) => { - let block = Block { - memory, - size, - mapped: Some(Mapped(pointer)), - addresses: None, - imported: true, - type_index, - }; - let host = pointer.as_ptr() as usize; - self.say_block(&format!("imported host memory 0x{host:x}"), &block); - let index = self - .pool(Holds::Buffers, type_index) - .add(size, true, block, size); - return Ok(self.placement((Holds::Buffers, type_index), index, 0, size, false)); - } - Err(error) => failure = ImportFailure::Vulkan(error), - } - } - Err(failure) + let types = candidates(&self.types, allowed, class, self.unified); + // SAFETY: the caller's contract. + let (memory, type_index) = + unsafe { import_pointer(device, pointer, size, &types, self.device_address) }?; + let block = Block { + memory, + size, + mapped: Some(Mapped(pointer)), + addresses: None, + imported: true, + pages: None, + type_index, + }; + let host = pointer.as_ptr() as usize; + self.say_block(&format!("imported host memory 0x{host:x}"), &block); + Ok(self.add_import(block, type_index, size)) + } + + /// The best memory type of `class` among `allowed`, where it has one. + pub(super) fn best_type(&self, allowed: u32, class: MemoryClass) -> Option { + candidates(&self.types, allowed, class, self.unified) + .first() + .copied() + } + + /// `block`, `size` bytes of memory type `type_index` just imported, added to its pool as a + /// dedicated block: its placement at offset 0. + fn add_import(&mut self, block: Block, type_index: u32, size: u64) -> Placement { + let index = self + .pool(Holds::Buffers, type_index) + .add(size, true, block, size); + self.placement((Holds::Buffers, type_index), index, 0, size, false) } /// Import the dma-buf `fd`, `size` bytes, as memory of the best type of `class` among @@ -1526,6 +1554,7 @@ impl BlockMaker { mapped, addresses, imported: false, + pages: None, type_index, }) } @@ -1581,6 +1610,77 @@ fn color_image_types(device: &ash::Device, sharing: Sharing<'_>) -> Result, + device: &ash::Device, + pages: OwnPages, + type_index: u32, +) -> Result { + let device_address = lock(memory).device_address; + let (pointer, size) = (pages.pointer(), pages.length()); + // SAFETY: the pages stay mapped until the block that takes them is freed, and their pointer + // and length are multiples of the import alignment (`Device::fresh_page_buffer`). + let (raw, type_index) = + unsafe { import_pointer(device, pointer, size, &[type_index], device_address) }?; + let block = Block { + memory: raw, + size, + mapped: Some(Mapped(pointer)), + addresses: None, + imported: false, + pages: Some(pages), + type_index, + }; + let mut memory = lock(memory); + memory.say_block("imported fresh pages for a buffer", &block); + Ok(memory.add_import(block, type_index, size)) +} + +/// The memory of `size` bytes of host memory at `pointer`, imported as the first of `types` the +/// driver takes, with the device-address flag where `device_address`, and its type. Refused when +/// `types` is empty, else with the failure of the last type tried. +/// +/// # Safety +/// +/// The `size` bytes at `pointer` are host memory of this process that stays mapped until the +/// memory is freed, both multiples of the device's import alignment, and each of `types` allows +/// the pointer. +unsafe fn import_pointer( + device: &ash::Device, + pointer: NonNull, + size: u64, + types: &[u32], + device_address: bool, +) -> Result<(vk::DeviceMemory, u32), ImportFailure> { + let mut failure = ImportFailure::NoMemoryType; + for &type_index in types { + let mut import = vk::ImportMemoryHostPointerInfoEXT::default() + .handle_type(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT) + .host_pointer(pointer.as_ptr().cast()); + let mut flags = + vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); + let mut info = vk::MemoryAllocateInfo::default() + .allocation_size(size) + .memory_type_index(type_index) + .push_next(&mut import); + if device_address { + info = info.push_next(&mut flags); + } + // SAFETY: `info` and its chain live for the call; the type index is the device's and + // allows the pointer; the caller's contract keeps the memory mapped. + match unsafe { device.allocate_memory(&info, None) } { + Ok(memory) => return Ok((memory, type_index)), + Err(error) => failure = ImportFailure::Vulkan(error), + } + } + Err(failure) +} + /// Place memory meeting a buffer's `requirements` of `class` in `memory`: in a pooled block with /// room, else in a new block (dedicated when larger than half a block), trying the class's /// memory types best first ([`place`]). diff --git a/crates/metal2vulkan-runtime/src/recycle.rs b/crates/metal2vulkan-runtime/src/recycle.rs index e30097262..0e449f1a3 100644 --- a/crates/metal2vulkan-runtime/src/recycle.rs +++ b/crates/metal2vulkan-runtime/src/recycle.rs @@ -15,8 +15,9 @@ //! parked buffer its Metal buffer, resident. //! - **The same making.** An image is taken only for a making of the same plan (format, extent, //! levels, layers, samples, usage, flags, view formats: `ImagePlan`), texture type, memory class -//! and sharing ([`ImageMaking`]); a buffer only for one of the same size and memory class -//! ([`BufferMaking`]; every such buffer has the same usage and the device's sharing): its +//! and sharing ([`ImageMaking`]); a buffer only for one of the same size, memory class and +//! pages, the device's or fresh ones it imported ([`BufferMaking`]; every such buffer has the +//! same usage and the device's sharing): its //! `vkCreateImage` or `vkCreateBuffer` parameters and its placement's memory are what a new //! one's would be. //! - **What a new owner sees.** Nothing of the last one's. An image is handed over as a new one @@ -25,7 +26,8 @@ //! the current layout"), and its maker's first move writes what a new texture reads: zero, or //! the copies in of a shadow, as for an image just made (`texture/first_move.rs`). A buffer's //! maker sets its bytes to zero as it does a new buffer's, on the host or by the device's next -//! submission (`Buffer::clear_first`), at the same cost; a scratch buffer's bytes hold no value +//! submission (`Buffer::clear_first`), at the same cost, fresh pages it imported among them +//! (`fresh_pages.rs`), which hold the last owner's bytes; a scratch buffer's bytes hold no value //! before the GPU writes them, recycled or new. A buffer takes a range of the Metal address //! space as a new one does (`address.rs`): its Vulkan device address, which the recycled //! `VkBuffer` keeps, is never shown. An image made to start as its memory lies starts as the @@ -102,12 +104,14 @@ pub(crate) struct ImageMaking { pub(crate) families: Vec, } -/// What fixes a buffer's making (`Device::placed_new_buffer`): its size (padded) and the memory -/// class it lies in. +/// What fixes a buffer's making (`Device::placed_new_buffer`): its size (padded), the memory +/// class it lies in, and whether it lies in fresh pages it imported (`fresh_pages.rs`), its +/// `VkBuffer` made for host allocations. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) struct BufferMaking { pub(crate) size: u64, pub(crate) class: MemoryClass, + pub(crate) fresh_pages: bool, } /// A parked object. diff --git a/crates/metal2vulkan-runtime/src/tests/fresh_pages.rs b/crates/metal2vulkan-runtime/src/tests/fresh_pages.rs new file mode 100644 index 000000000..a354ff7fd --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/fresh_pages.rs @@ -0,0 +1,370 @@ +//! Long new buffers in fresh pages (`fresh_pages.rs`), on the device the GPU cfg selects. +//! +//! - **A long new buffer reads zero, nothing written.** A `Shared` buffer, a write-combined one +//! and a `Managed` one (with unified memory), each longer than half a pooled block: each lies in +//! fresh pages (`WorkCounts::fresh_page_buffers_made`), the host set none of its bytes to zero +//! (`new_buffer_bytes_cleared` unchanged), and it reads zero through `contents` and through a +//! blit out of it. Without the fresh pages each would be a memset of its length. A shorter one, +//! a `Private` one and a heap's are made as before: a pooled or device placement, cleared. +//! - **Right after a filled one of its length.** A buffer filled by the GPU and released, then one +//! of the same length: it takes the parked one (`buffers_recycled`), whose bytes the host sets +//! to zero (`new_buffer_bytes_cleared` grows by its padded length), and it reads zero. Past the +//! recycler's bytes (`recycle::BUFFERS`) nothing is parked: the next buffer lies in fresh pages +//! again and reads zero, nothing written. +//! - **A copy of bytes.** `new_buffer_with_bytes` of a long pattern lies in fresh pages and reads +//! the pattern, through `contents` and a blit. +//! - **A texture over a long buffer** is a shadow of its bytes +//! (`WorkCounts::shadows_over_fresh_pages`): a blit out of it reads the bytes the CPU wrote, and +//! a render pass's clear through it reaches them once the command buffer completed. +//! +//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). + +use super::blit_holds::{Scratch, WAIT}; +use crate::fresh_pages::FRESH_PAGES_PAST; +use crate::{ + BlitOption, Buffer, ClearColor, CommandBufferStatus, CommandQueue, CpuCacheMode, Device, + DeviceKind, DeviceOptions, HazardTrackingMode, HeapDescriptor, HeapType, LoadAction, Origin, + RenderPassDescriptor, ResourceOptions, ShaderCacheOptions, Size, StorageMode, StoreAction, + TextureDescriptor, WorkCounts, +}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use std::path::Path; + +/// A long buffer's length: past half a pooled block, and not a multiple of 16, so its padding is +/// read too. +const LONG: u64 = FRESH_PAGES_PAST + 4100; + +/// The device the cfg selects, its shader cache in `cache`. +fn device(cache: &Path) -> Device { + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + shader_cache: ShaderCacheOptions { + directory: Some(cache.to_owned()), + ..ShaderCacheOptions::default() + }, + ..DeviceOptions::default() + }; + Device::system_default_with(&options).unwrap() +} + +/// Whether the device takes fresh pages: it imports host pointers. +fn takes_fresh_pages(device: &Device) -> bool { + device.shared().host_import.is_ok() +} + +/// Fill `buffer` with `value` on the GPU, waited for. +fn fill(queue: &CommandQueue, buffer: &Buffer, value: u8) { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(buffer, 0..buffer.length(), value).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert!(command_buffer.wait_until_completed_for(WAIT).is_ok()); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +/// The bytes of `buffer`, blitted into `out` (`Shared`, at least as long, its bytes set to 0xcd +/// first so that the copy shows), waited for. +fn read_on_gpu(queue: &CommandQueue, buffer: &Buffer, out: &Buffer) -> Vec { + let length = buffer.length(); + let contents = out.contents().unwrap(); + // SAFETY: the shared buffer's bytes, which no command uses now. + unsafe { std::ptr::write_bytes(contents.as_ptr(), 0xcd, length as usize) }; + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_buffer(buffer, 0, out, 0, length) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert!(command_buffer.wait_until_completed_for(WAIT).is_ok()); + // SAFETY: as above; the copy completed. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), length as usize) }.to_vec() +} + +/// The bytes of a host-visible `buffer` through its `contents`. +fn read_on_cpu(buffer: &Buffer) -> Vec { + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's bytes, which no command uses now. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }.to_vec() +} + +/// Whether every byte of `bytes` is zero, and else where the first that is not lies. +fn first_nonzero(bytes: &[u8]) -> Option { + bytes.iter().position(|&b| b != 0) +} + +/// Wait until the device parked `count` buffers in all. +fn buffers_parked_at_least(device: &Device, count: u64) { + let until = std::time::Instant::now() + WAIT; + while device.work_counts().object_churn.buffers_parked < count { + assert!(std::time::Instant::now() < until, "the buffers were parked"); + std::thread::yield_now(); + } +} + +/// The counts that tell where a new buffer's zeros came from: buffers made in fresh pages, and +/// bytes the host cleared. +fn zeros(counts: &WorkCounts) -> (u64, u64) { + ( + counts.fresh_page_buffers_made, + counts.new_buffer_bytes_cleared, + ) +} + +#[test] +fn a_long_new_buffer_reads_zero_with_nothing_written() { + let scratch = Scratch::new("fresh-pages-new"); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let fresh = takes_fresh_pages(&device); + let out = device.new_buffer(LONG, ResourceOptions::shared()).unwrap(); + let write_combined = ResourceOptions::new( + StorageMode::Shared, + CpuCacheMode::WriteCombined, + HazardTrackingMode::Default, + ); + let managed = ResourceOptions::new( + StorageMode::Managed, + CpuCacheMode::DefaultCache, + HazardTrackingMode::Default, + ); + let mut legs = vec![ + ("shared", ResourceOptions::shared()), + ("write-combined", write_combined), + ]; + if device.properties().has_unified_memory { + legs.push(("managed", managed)); + } + // Each kept, so that none is parked for the next. + let mut kept = Vec::new(); + for (what, options) in legs { + let before = zeros(&device.work_counts()); + let buffer = device.new_buffer(LONG, options).unwrap(); + let after = zeros(&device.work_counts()); + let padded = LONG.next_multiple_of(16); + match fresh { + true => assert_eq!( + (after.0 - before.0, after.1 - before.1), + (1, 0), + "{what}: the buffer lies in fresh pages, no byte of it written" + ), + false => assert_eq!( + (after.0 - before.0, after.1 - before.1), + (0, padded), + "{what}: the device takes no fresh pages: the host clears the buffer" + ), + } + assert_eq!(buffer.in_fresh_pages(), fresh, "{what}"); + assert_eq!( + first_nonzero(&read_on_cpu(&buffer)), + None, + "{what}: contents" + ); + assert_eq!( + first_nonzero(&read_on_gpu(&queue, &buffer, &out)), + None, + "{what}: a blit out of it" + ); + kept.push(buffer); + } + + // Made as before: a shorter one, a `Private` one, and a heap's own buffer. + let before = zeros(&device.work_counts()); + let short = device + .new_buffer(FRESH_PAGES_PAST, ResourceOptions::shared()) + .unwrap(); + let after = zeros(&device.work_counts()); + assert_eq!( + (after.0 - before.0, after.1 - before.1), + (0, FRESH_PAGES_PAST), + "half a block lies in a pooled block, cleared" + ); + assert!(!short.in_fresh_pages()); + assert_eq!(first_nonzero(&read_on_cpu(&short)), None); + let before = zeros(&device.work_counts()); + let private = device.new_buffer(LONG, ResourceOptions::private()).unwrap(); + assert_eq!(zeros(&device.work_counts()), before, "a Private buffer"); + assert!(!private.in_fresh_pages()); + assert_eq!(first_nonzero(&read_on_gpu(&queue, &private, &out)), None); + let descriptor = HeapDescriptor::new(HeapType::Automatic, LONG, ResourceOptions::shared()); + let before = zeros(&device.work_counts()); + let heap = device.new_heap(&descriptor).unwrap(); + assert_eq!( + zeros(&device.work_counts()).0, + before.0, + "a heap's own buffer lies where its textures can" + ); + let placed = heap + .new_buffer(FRESH_PAGES_PAST + 256, ResourceOptions::shared()) + .unwrap(); + assert!(!placed.in_fresh_pages()); + assert_eq!( + first_nonzero(&read_on_cpu(&placed)), + None, + "a new heap's buffer" + ); +} + +#[test] +fn a_long_buffer_made_right_after_a_filled_one_reads_zero() { + let scratch = Scratch::new("fresh-pages-after"); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let fresh = takes_fresh_pages(&device); + // Past the recycler's bytes: never parked. + let past = 80 << 20; + let out = device.new_buffer(past, ResourceOptions::shared()).unwrap(); + for length in [LONG, past] { + let first = device + .new_buffer(length, ResourceOptions::shared()) + .unwrap(); + fill(&queue, &first, 0xab); + assert!(read_on_cpu(&first).iter().all(|&b| b == 0xab), "the fill"); + let before = device.work_counts(); + drop(first); + let parks = length <= 64 << 20; + if parks { + buffers_parked_at_least(&device, before.object_churn.buffers_parked + 1); + } + let second = device + .new_buffer(length, ResourceOptions::shared()) + .unwrap(); + let after = device.work_counts(); + let recycled = after.object_churn.buffers_recycled - before.object_churn.buffers_recycled; + let made = after.fresh_page_buffers_made - before.fresh_page_buffers_made; + let cleared = after.new_buffer_bytes_cleared - before.new_buffer_bytes_cleared; + let padded = length.next_multiple_of(16); + match (parks, fresh) { + // The parked buffer, its last owner's bytes set to zero on the host. + (true, _) => assert_eq!((recycled, made, cleared), (1, 0, padded), "{length}"), + (false, true) => assert_eq!((recycled, made, cleared), (0, 1, 0), "{length}"), + (false, false) => assert_eq!((recycled, made, cleared), (0, 0, padded), "{length}"), + } + assert_eq!( + first_nonzero(&read_on_cpu(&second)), + None, + "{length}: contents read zero, not the old bytes" + ); + assert_eq!( + first_nonzero(&read_on_gpu(&queue, &second, &out)), + None, + "{length}: a blit reads zero, not the old bytes" + ); + } +} + +#[test] +fn a_long_buffer_with_bytes_reads_them() { + let scratch = Scratch::new("fresh-pages-bytes"); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let bytes: Vec = (0..LONG).map(|i| (i % 251) as u8).collect(); + let before = device.work_counts().fresh_page_buffers_made; + let buffer = device + .new_buffer_with_bytes(&bytes, ResourceOptions::shared()) + .unwrap(); + let made = device.work_counts().fresh_page_buffers_made - before; + assert_eq!(made, u64::from(takes_fresh_pages(&device))); + assert!(read_on_cpu(&buffer) == bytes, "contents read the bytes"); + let out = device.new_buffer(LONG, ResourceOptions::shared()).unwrap(); + assert!( + read_on_gpu(&queue, &buffer, &out) == bytes, + "a blit reads the bytes" + ); +} + +#[test] +fn a_texture_over_a_long_buffer_is_its_bytes_through_a_shadow() { + const SIDE: u64 = 64; + const ROW: u64 = 512; + let scratch = Scratch::new("fresh-pages-texture"); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let buffer = device.new_buffer(LONG, ResourceOptions::shared()).unwrap(); + let contents = buffer.contents().unwrap(); + let span = (ROW * SIDE) as usize; + let pattern: Vec = (0..span).map(|i| (i % 253) as u8).collect(); + // SAFETY: the buffer's first bytes, which no command uses now. + unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), contents.as_ptr(), span) }; + let before = device.work_counts(); + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + descriptor.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&descriptor, 0, ROW).unwrap(); + let after = device.work_counts(); + let over_fresh = after.shadows_over_fresh_pages - before.shadows_over_fresh_pages; + assert_eq!(over_fresh, u64::from(buffer.in_fresh_pages())); + if buffer.in_fresh_pages() { + assert_eq!(after.shadowed_textures - before.shadowed_textures, 1); + } + + // A blit out of the texture reads the bytes the CPU wrote, row by row. + let out = device + .new_buffer(SIDE * SIDE * 4, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(SIDE, SIDE, 1), + &out, + 0, + SIDE * 4, + SIDE * SIDE * 4, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert!(command_buffer.wait_until_completed_for(WAIT).is_ok()); + let read = read_on_cpu(&out); + for y in 0..SIDE as usize { + let row = &read[y * SIDE as usize * 4..(y + 1) * SIDE as usize * 4]; + let wrote = &pattern[y * ROW as usize..][..SIDE as usize * 4]; + assert_eq!( + row, wrote, + "row {y} of the texture reads the buffer's bytes" + ); + } + + // A clear through the texture reaches the buffer's bytes, and only its texels'. + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(texture.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(1.0, 0.0, 1.0, 0.0); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .render_command_encoder(&pass) + .unwrap() + .end_encoding() + .unwrap(); + command_buffer.commit().unwrap(); + assert!(command_buffer.wait_until_completed_for(WAIT).is_ok()); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let now = read_on_cpu(&buffer); + for y in 0..SIDE as usize { + let row = &now[y * ROW as usize..(y + 1) * ROW as usize]; + let texels = &row[..SIDE as usize * 4]; + assert!( + texels.chunks(4).all(|texel| texel == [255, 0, 255, 0]), + "row {y}: the clear reached the buffer" + ); + assert_eq!( + &row[SIDE as usize * 4..], + &pattern[y * ROW as usize + SIDE as usize * 4..(y + 1) * ROW as usize], + "row {y}: the bytes between the rows kept the CPU's" + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 1771c7655..0aed1ff33 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -67,6 +67,8 @@ mod fitted_variant_notice; mod framebuffer_fetch; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod freed_memory; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod fresh_pages; mod fresh_unwritten; mod function_table; mod gate; diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index b8fbf26e7..3e36ee25e 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -2115,6 +2115,9 @@ impl Device { // Metal's contract leaves no moment the CPU may not write them. The shadow's copies // address its texels alone, through the buffer. let host = texels.buffer.caller_memory() == Some(CallerMemory::HostPages); + // Nor over fresh pages the runtime imported for a long buffer of its own + // (`fresh_pages.rs`), for the same reason. + let fresh = texels.buffer.in_fresh_pages(); // The plans a linear image aliasing the bytes is tried with, the first the device makes: // with the feedback loop usage a draw takes that reads the texture its own pass renders // through a snapshot (`feedback_candidate`, `texture/attached_reads.rs`), which costs a @@ -2144,6 +2147,12 @@ impl Device { UNDEFINED, whose first move Vulkan lets read and write every byte it is bound to, \ where Metal keeps every CPU write" .to_owned() + } else if fresh { + self.shared().counts.shadow_over_fresh_pages(); + "the buffer's bytes lie in fresh host pages imported for it, which an image could alias \ + only from UNDEFINED, whose first move Vulkan lets read and write every byte it is \ + bound to, where Metal keeps every CPU write" + .to_owned() } else { let over = (&*texels, &holds); for &wider in &plans[..plans.len() - 1] { diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 6f363b337..e9b5950d9 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -235,6 +235,10 @@ pub(crate) struct Counters { modifier_feature_queries: AtomicU64, shadowed_textures: AtomicU64, shadows_zeroed: AtomicU64, + shadows_over_fresh_pages: AtomicU64, + fresh_page_buffers_made: AtomicU64, + fresh_page_bytes: AtomicU64, + new_buffer_bytes_cleared: AtomicU64, shadow_copies: AtomicU64, shadow_texels_copied_in: AtomicU64, shadow_texels_first_copied_in: AtomicU64, @@ -1675,6 +1679,24 @@ impl Counters { } } + /// A texture over a buffer's bytes is a shadow of them because they lie in fresh pages the + /// buffer imported (`fresh_pages.rs`). + pub(crate) fn shadow_over_fresh_pages(&self) { + (self.shadows_over_fresh_pages).fetch_add(1, Ordering::Relaxed); + } + + /// A buffer was made in `bytes` of fresh pages it imported, which read zero unwritten + /// (`fresh_pages.rs`). + pub(crate) fn fresh_page_buffer_made(&self, bytes: u64) { + (self.fresh_page_buffers_made).fetch_add(1, Ordering::Relaxed); + (self.fresh_page_bytes).fetch_add(bytes, Ordering::Relaxed); + } + + /// The host set `bytes` of a new buffer to zero as it was made (`Buffer::clear_first`). + pub(crate) fn new_buffer_cleared(&self, bytes: u64) { + (self.new_buffer_bytes_cleared).fetch_add(bytes, Ordering::Relaxed); + } + /// An encoder planned `n` copies between shadowed textures' truths and their shadows /// (`shadow.rs`), whose copies in and back of buffers' textures' images move `texels_in` and /// `texels_back` texels. @@ -3238,6 +3260,21 @@ pub struct WorkCounts { /// Every other shadow's copy in writes each texel before any command reads it, so its image /// starts as its memory lies. pub shadows_zeroed: u64, + /// Of `shadowed_textures`, those over a buffer that lies in fresh pages it imported + /// (`fresh_page_buffers_made`): an image bound to imported memory starts `UNDEFINED`, and its + /// first move may write any byte bound to it. + pub shadows_over_fresh_pages: u64, + /// Buffers of the runtime's own made in fresh anonymous pages imported by their pointer + /// (`VK_EXT_external_memory_host`), which read zero with nothing written: host-visible ones + /// longer than half a pooled block, not of a heap, where the device takes such pages. A + /// parked one taken again is not counted. + pub fresh_page_buffers_made: u64, + /// Their pages' bytes: whole units of the host page and the import alignment. + pub fresh_page_bytes: u64, + /// The bytes of new buffers the host set to zero as they were made: the `Shared` and + /// `Managed` ones' (a `Managed` buffer's host copy too, without unified memory), but those + /// made in fresh pages. + pub new_buffer_bytes_cleared: u64, /// Copies between a shadowed texture's truth and its shadow that encoders planned /// (`shadow.rs`): copies in before a command, copies back after one or as the encoder ends, /// and the keeps and merges of a command that writes the bytes two ways or writes through a @@ -3919,6 +3956,10 @@ impl Device { dma_buf_image_fallbacks: counters.dma_buf_image_fallbacks.load(Ordering::Relaxed), modifier_feature_queries: counters.modifier_feature_queries.load(Ordering::Relaxed), shadowed_textures: counters.shadowed_textures.load(Ordering::Relaxed), + shadows_over_fresh_pages: counters.shadows_over_fresh_pages.load(Ordering::Relaxed), + fresh_page_buffers_made: counters.fresh_page_buffers_made.load(Ordering::Relaxed), + fresh_page_bytes: counters.fresh_page_bytes.load(Ordering::Relaxed), + new_buffer_bytes_cleared: counters.new_buffer_bytes_cleared.load(Ordering::Relaxed), views_through_swizzle: counters.views_through_swizzle.load(Ordering::Relaxed), view_shadows: counters.view_shadows.load(Ordering::Relaxed), attachment_reads_through_copies: counters diff --git a/docs/API.md b/docs/API.md index 7058bd99d..4be8cfcb7 100644 --- a/docs/API.md +++ b/docs/API.md @@ -184,13 +184,16 @@ the device refuses (`HostMemory::with_dma_buf`), `VK_EXT_external_memory_dma_buf `VK_EXT_queue_family_foreign` beside them, wherever a device lists them. A texture over a no-copy buffer's host pages (imported by their pointer or as dma-bufs) is a shadow -(`shadowed-texture`): an optimal image of the runtime's own memory, whose texels the encoders copy -in from the pages before a use and back (merged back: only the bytes the commands changed) after a -write. No image is bound to the pages: an image bound to imported memory starts in -`VK_IMAGE_LAYOUT_UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), and its first move, like any -layout transition, may read and write every byte bound to it, where Metal keeps every CPU write to -bytes a command buffer does not write. `Texture::vk_image` gives `None` for such a texture. A -texture placed in a heap over dma-buf pages is an image over a dma-buf of its own pages, which its +(`shadowed-texture`), as is one over a host-visible buffer of the runtime's own longer than 32 MiB +where the device imports host pointers: that buffer lies in fresh anonymous pages imported by their +pointer, zero as mapped, so that nothing writes its zeros (`WorkCounts::fresh_page_buffers_made`, +`shadows_over_fresh_pages`). Such a shadow is an optimal image of the runtime's own memory, whose +texels the encoders copy in from the pages before a use and back (merged back: only the bytes the +commands changed) after a write. No image is bound to the pages: an image bound to imported memory +starts in `VK_IMAGE_LAYOUT_UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), and its first move, +like any layout transition, may read and write every byte bound to it, where Metal keeps every CPU +write to bytes a command buffer does not write. `Texture::vk_image` gives `None` for such a texture. +A texture placed in a heap over dma-buf pages is an image over a dma-buf of its own pages, which its first submission acquires from `VK_QUEUE_FAMILY_FOREIGN_EXT`; a linear image over a buffer of the runtime's own memory starts `VK_IMAGE_LAYOUT_PREINITIALIZED`, and its move from there keeps its bytes. FAST-PATHS.md's costs and known gaps state what this costs and differs from Metal in. @@ -964,7 +967,8 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. - `metal2vulkan-degrade-shadowed-texture` (performance). `ShadowedTexture`: A 2D texture over a buffer is a shadow image: the buffer is over host pages (a no-copy buffer's, imported by their - pointer or as dma-bufs), where an image bound to them would start `UNDEFINED` and Vulkan lets its + pointer or as dma-bufs, or the fresh pages a host-visible buffer of the runtime's own longer than + 32 MiB lies in), where an image bound to them would start `UNDEFINED` and Vulkan lets its layout transitions (its first move among them) read and write any byte bound to it, where Metal keeps every CPU write; or its rows (or an array's slices) lie with the buffer's bytes between them, which an image over them would hold in its subresource, where Vulkan lets the image's diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index f9cd0348c..cb222dbff 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -155,25 +155,31 @@ recorded here. sign strip (two copies and a dispatch, or a draw per layer when multisampled) follows a pass with depth writes where no stand-in runs (`texture/signed_depth.rs`). A texture never switched on pays a flag read per pass. -- **A texture over a no-copy buffer's host pages, or over a buffer whose rows lie with bytes - between them,** is a shadow on every device, whatever its usage (`shadowed-texture`): its texels - copied in before each use and merged back after each write (only those inside the draws' - scissors for a pass that takes it as a loaded attachment alone). An image bound to host pages - starts `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), and its first move may read and write - every byte bound to it, which the host could keep only by undoing a CPU write made meanwhile, - where Metal keeps it; an image over padded rows holds the bytes between them, which a render - pass's load and store operations may rewrite too. On the UHD 770 (ANV) a 1080p `BGRA8Unorm` - surface's pass that loads, draws and stores (`guest_frame_costs`) took 1.9 ms from commit to - completion, 1.4 ms of it the copies (copy in 0.21 ms, keep 0.60, merge 0.60), against 0.4 ms - into a `Private` texture; a linear image over the pages took 2.6-3.1 ms, its draws slow in host - memory. Twelve such passes in one command buffer took 21 ms against the linear image's 27.5 ms, - and 0.4-0.5 ms more of the process's CPU a frame (1.2 ms against 0.7): about 20 µs a pass on the - encoding thread, 10 µs on the queue's waiter and 10 µs on the recorder and reaper together. On - ANV making a 1307x512 tile took about 135 µs as a shadow against 41 µs as an image; a frame - sampling four `BGRA8Unorm` tiles over no-copy pages - (`surface_texture_costs::read_only_padded_costs`) took 3.2-5.3 ms with the textures made once - and 3.4-7.1 ms with new ones each frame, where images over the rows took 3.0-6.1 and 4.6-8.6 - ms. An ordinary buffer's packed rows avoid it. +- **A texture over a no-copy buffer's host pages, over a host-visible buffer longer than 32 MiB, or + over a buffer whose rows lie with bytes between them,** is a shadow on every device, whatever its + usage (`shadowed-texture`): its texels copied in before each use and merged back after each write + (only those inside the draws' scissors for a pass that takes it as a loaded attachment alone). An + image bound to host pages starts `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), and its first + move may read and write every byte bound to it, which the host could keep only by undoing a CPU + write made meanwhile, where Metal keeps it; an image over padded rows holds the bytes between + them, which a render pass's load and store operations may rewrite too. A host-visible buffer + longer than half a pooled block (32 MiB) lies in fresh anonymous pages imported by their pointer + where the device imports them (`fresh_pages.rs`), which read zero as mapped, so its creation + writes none of its bytes, and the CPU's first touch of its pages is paid where the program makes + it, as on Metal (host_ab on the M3 Max, 64 MiB: made in 0.01-2.2 ms against 3.2-4.7 ms of + allocation and memset, its first CPU write 2.4-6.5 ms against 0.7-1.4 ms, Metal's 3.7-7.4 ms): + such a buffer's textures are shadows for the same reason (`WorkCounts::shadows_over_fresh_pages`). + On the UHD 770 (ANV) a 1080p `BGRA8Unorm` surface's pass + that loads, draws and stores (`guest_frame_costs`) took 1.9 ms from commit to completion, 1.4 ms + of it the copies (copy in 0.21 ms, keep 0.60, merge 0.60), against 0.4 ms into a `Private` + texture; a linear image over the pages took 2.6-3.1 ms, its draws slow in host memory. Twelve such + passes in one command buffer took 21 ms against the linear image's 27.5 ms, and 0.4-0.5 ms more of + the process's CPU a frame (1.2 ms against 0.7): about 20 µs a pass on the encoding thread, 10 µs + on the queue's waiter and 10 µs on the recorder and reaper together. On ANV making a 1307x512 tile + took about 135 µs as a shadow against 41 µs as an image; a frame sampling four `BGRA8Unorm` tiles + over no-copy pages (`surface_texture_costs::read_only_padded_costs`) took 3.2-5.3 ms with the + textures made once and 3.4-7.1 ms with new ones each frame, where images over the rows took + 3.0-6.1 and 4.6-8.6 ms. An ordinary buffer's packed rows avoid it. - **On MoltenVK, a texture over a buffer that renders or that blits write keeps a shadow.** MoltenVK 1.4.1 reports a format's linear-tiling attachment and blit-destination features from uninitialized memory, so no MoltenVK description states them