diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 0d3d0440b..c43c5213b 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -178,10 +178,13 @@ the runtime made. `IdPlacement`, `Device::reserve_resource_ids`); a pin the space cannot honour is `Error::PlacementConflict`. - **Host memory without a copy.** `unsafe Device::new_buffer_with_bytes_no_copy` imports host - memory through `VK_EXT_external_memory_host`; memory the device cannot import exactly is refused. - `unsafe Device::new_heap_with_bytes_no_copy` is its heap twin. `Buffer::rebind_bytes_no_copy` - and `Heap::rebind_bytes_no_copy` move either to another range, keeping the objects, addresses and - IDs. `CommandBuffer::used_resources` lists what a command buffer uses until it completes, so a + memory, given as a `HostMemory`, through `VK_EXT_external_memory_host`; memory the device cannot + import exactly is refused. `unsafe Device::new_heap_with_bytes_no_copy` is its heap twin. + `Buffer::rebind_bytes_no_copy` and `Heap::rebind_bytes_no_copy` move either to another range, + keeping the objects, addresses and IDs. Where a driver refuses the pointer (RADV refuses shared + mappings, a `memfd`'s among them), memory made with `HostMemory::with_dma_buf` is imported from + dma-bufs of its pages instead ([HOWTO](../../docs/HOWTO.md#6-host-memory-a-driver-refuses)). + `CommandBuffer::used_resources` lists what a command buffer uses until it completes, so a program knows when it may take memory away. - **Hazards** are tracked as Metal tracks them. A heap's resources are untracked by default, so encoders that share them order themselves with fences. Commands that reach a resource through an @@ -212,6 +215,8 @@ Calls Metal does not have, for a consumer that emulates a Metal device: its sampler's. - Resource ID reservations, placements and counts (`Device::reserve_resource_ids`, `IdPlacement`, `Device::sampler_ids_live`), and the private getters of indirect commands. +- `HostMemory::with_dma_buf` and its `DmaBufSource`: dma-bufs of a no-copy object's pages, for a + device that refuses their pointer. [docs/API.md section 10](../../docs/API.md#10-accepted-differences) lists where the runtime answers otherwise than Metal on purpose. diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 1776e089a..7969bcc76 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -266,6 +266,8 @@ pub(super) struct Detached { /// The index of the memory type of the pages it was detached from: a texture made over the /// bytes meanwhile takes the route it would over them (`texture/heap.rs`). type_index: u32, + /// Whether the pages it was detached from were imported as dma-bufs, for the same. + over_dma_buf: bool, } impl Detached { @@ -301,6 +303,7 @@ impl Detached { _stand_in: stand_in, pages, type_index: from.type_index(), + over_dma_buf: from.over_dma_buf(), }) } } @@ -506,6 +509,23 @@ impl HostPages { self.import.pages.memory.placement.type_index() } + /// Whether they were imported as dma-bufs (`dma_buf.rs`), not by their pointer. + pub(super) fn over_dma_buf(&self) -> bool { + self.import.pages.memory.placement.over_dma_buf() + } + + /// Where they lie as dma-bufs (`dma_buf.rs`): the imports, with the caller's source; the host + /// address where their bytes start (from which an image over them reckons its texels'); and + /// the imports' memory type. `None` for pages imported by their pointer. + #[cfg(unix)] + pub(super) fn dma_buf(&self) -> Option<(&Arc, u64, u32)> { + let pages = &self.import.pages; + let placement = &pages.memory.placement; + let imports = placement.dma_buf_pages()?; + let start = (placement.mapped?.as_ptr() as u64).checked_add(pages.offset)?; + Some((imports, start, placement.type_index())) + } + /// Release the pages to `release` when they go. pub(super) fn release_to(&self, release: Release) { // A refused set leaves the deallocator unrun, as a refused call does: never reached, @@ -600,10 +620,13 @@ impl Drop for HostImport { return; }; let shared = self.device.shared(); + // A submission that used the pages waited for their sparse binding: waited for here + // where none did. + self.pages.memory.placement.settle(); // SAFETY: no pending command buffer uses the pages: one whose commands used them holds // them until it completed (`rebind.rs`), one that may read a texture's image over them // holds the image, which holds the import (`heap_sets.rs`), and every buffer over them - // let go of them. + // let go of them; their binding completed. unsafe { release::object(shared.vk(), self.pages.raw) }; lock(&shared.memory).free(shared.vk(), &self.pages.memory.placement); drop(busy); @@ -1956,6 +1979,13 @@ impl Buffer { } } + /// The host pages the buffer's bytes lie in now ([`Buffer::pages_cell`]): a no-copy + /// buffer's, or a no-copy heap's for a buffer of the heap; `None` for any other buffer, and + /// while they are detached. + pub(super) fn host_pages(&self) -> Option> { + self.pages_cell()?.current() + } + /// Where the bytes of the host pages the buffer lies in ([`Buffer::pages_cell`]) start in /// their memory, which an aliasing image's place in them is reckoned from. Refused (an /// internal error) for a buffer over no host pages. @@ -2021,6 +2051,17 @@ impl Buffer { } } + /// Whether the host pages the buffer's bytes lie in (a no-copy buffer's, or for a heap's + /// buffer its heap's), or lay in while they are detached, were imported as dma-bufs + /// (`dma_buf.rs`); false for a buffer over no host pages. + pub(super) fn over_dma_buf(&self) -> bool { + match self.pages_cell().map(|cell| cell.lying()) { + Some(Lying::In(pages)) => pages.over_dma_buf(), + Some(Lying::Detached(detached)) => detached.over_dma_buf, + None => false, + } + } + /// `device`. pub fn device(&self) -> &Device { &self.0.device diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index 637763899..902a821c8 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -17,12 +17,13 @@ use super::error::{internal, invalid, nil, vulkan, Error, Problem, RuntimeGap}; use super::heap::{Heap, HeapProblem}; use super::host_memory::{ based_size, binds_in, buffer_base, import_refused, import_window, not_importable, - refuse_unwritable, Deallocator, HostMemory, HostRelease, ImportWindow, Importer, KeepAlive, - WindowRefusal, + refuse_unwritable, refused, Deallocator, HostMemory, HostRelease, ImportWindow, Importer, + KeepAlive, Source, }; use super::memory::{ImportFailure, MemoryClass, Placement}; use super::rebind::RebindProblem; use super::texture::stand_in::TextureImages; +use super::texture::Remade; use super::values::{ResourceOptions, StorageMode}; use super::Device; use crate::release; @@ -217,7 +218,8 @@ impl Device { } self.buffer_with_bytes(CALL, bytes, resource_options, place) } - // SAFETY: `HostMemory::new`'s caller vouched for `length` bytes at the pointer. + // SAFETY: the `HostMemory` constructor's caller vouched for `length` bytes at the + // pointer. BufferContents::NoCopy { memory, deallocator, @@ -258,33 +260,38 @@ impl Device { Ok(self.visible(buffer)) } - /// `newBufferWithBytesNoCopy:length:options:deallocator:`: a buffer whose bytes are the - /// caller's `length` bytes at `bytes` (module docs of `host_memory.rs`). `deallocator` - /// runs once, with `bytes` and `length`, when the buffer's last reference goes: on a runtime - /// thread when that is a command buffer completing. A refused call never runs it. + /// `newBufferWithBytesNoCopy:length:options:deallocator:`, its pointer wrapped in `memory` + /// ([`HostMemory`]): a buffer whose bytes are the caller's `length` bytes at + /// `memory.pointer()` (module docs of `host_memory.rs`). `deallocator` runs once, with the + /// pointer and `length`, when the buffer's last reference goes: on a runtime thread when that + /// is a command buffer completing. A refused call never runs it. /// /// The pages are imported here, as Metal wires them when it makes the buffer: the GPU uses - /// the pages mapped at `bytes` now, and memory the device cannot import is refused here, as - /// Metal answers nil. The import costs work per page here (on macOS about 11 to 20 ms per GiB - /// measured on an M4 and an M3 Max), where Metal makes the buffer at once and pays at the - /// first command using it (24 to 88 ms per GiB). + /// the pages mapped at the pointer now, and memory the device cannot import is refused here, + /// as Metal answers nil. The import costs work per page here (on macOS about 11 to 20 ms per + /// GiB measured on an M4 and an M3 Max), where Metal makes the buffer at once and pays at the + /// first command using it (24 to 88 ms per GiB). Where the device refuses the pointer and + /// `memory` carries a dma-buf source ([`HostMemory::with_dma_buf`]), the dma-bufs it makes of + /// the pages are imported instead. /// /// Refused: a length of 0 or past `max_buffer_length` (`Nil`, as plain Metal answers nil, EV /// TTG-nil10-m4); `Private` or `Memoryless` storage, as Metal stops them, and an undefined /// option (`Invalid`); a device /// without `VK_EXT_external_memory_host` (`Unsupported`, naming it); memory this device - /// cannot import exactly (`Unsupported`, `HostMemory`), among it on Linux a page this process - /// cannot write ([`HostMemory::new`]); pages past the device's allocation size - /// (`OutOfMemory`). Pages not mapped, or mapped without access, which Metal makes no buffer - /// over (nil), are refused here too, typed as the check or the import answers, though such - /// memory breaks [`HostMemory::new`]'s contract. + /// cannot import exactly, by its pointer or by its dma-bufs (`Unsupported`, `HostMemory`), + /// among it on Linux a page this process cannot write ([`HostMemory::new`]); dma-bufs that + /// break the source's contract (`Invalid`, `Problem::DmaBuf`); pages past the + /// device's allocation size (`OutOfMemory`). Pages not mapped, or mapped without access, which + /// Metal makes no buffer over (nil), are refused here too, typed as the check or the import + /// answers, though such memory breaks [`HostMemory::new`]'s contract. /// /// # Safety /// - /// The `length` bytes at `bytes` meet [`HostMemory::new`]'s contract. + /// `memory` meets the contract of the [`HostMemory`] constructor that made it + /// ([`HostMemory::new`], [`HostMemory::with_dma_buf`]) for `length` bytes. pub unsafe fn new_buffer_with_bytes_no_copy( &self, - bytes: NonNull, + memory: HostMemory, length: u64, options: ResourceOptions, deallocator: Option, @@ -295,7 +302,7 @@ impl Device { let buffer = unsafe { self.buffer_over_host_memory( CALL, - HostMemory::new(bytes), + memory, length, options, HostRelease { @@ -425,18 +432,9 @@ impl Device { .host_import .as_ref() .map_err(|unsupported| Error::Unsupported(unsupported.clone()))?; - let pointer = memory.pointer(); - let window = import_window( - pointer.as_ptr() as u64, - length, - importer.page, - importer.alignment, - ) - .map_err(|refusal| match refusal { - // Memory past the address space's end is not mapped: Metal makes no buffer over it. - WindowRefusal::Overflow => nil(call, Problem::BufferLength { length }), - WindowRefusal::BeyondPages | WindowRefusal::Binding => not_importable(), - })?; + let (pointer, source) = memory.into_parts(); + let host = host_window(call, importer, pointer, length, source)?; + let window = host.window; if of_heap && window.offset != 0 { let alignment = importer.page.max(importer.alignment); let problem = HeapProblem::HostMemoryAlignment { alignment }; @@ -444,7 +442,8 @@ impl Device { } refuse_unwritable(&window)?; // A buffer over the bytes a live no-copy buffer was made over, of its memory class, lies - // in its import (`host_aliases.rs`); a heap's own buffer imports its own. + // in its import (`host_aliases.rs`), its dma-buf source dropped uncalled; a heap's own + // buffer imports its own. let made_over = (pointer.as_ptr() as u64, length); let release = release.of(pointer, length); let shares = (!of_heap) @@ -460,19 +459,21 @@ impl Device { shared.aliases.place(buffer.identity().key, made_over); return Ok(buffer); } - let buffer = self.host_buffer(&window, length)?; - // The window starts `window.offset` bytes before the pointer, in the pages it touches. - let start = pointer.as_ptr().wrapping_sub(window.offset as usize); // SAFETY: the window lies in the pages of the caller's bytes, which stay mapped - // (`HostMemory::new`), and the buffer is a new one of this device. - let placed = unsafe { - self.import_pages(importer, &buffer, start, &window, class, placement, length) - }; - let (memory, (address, reserved)) = match placed { - Ok(placed) => placed, + // (`HostMemory::new`), and the source's pieces hold them (`HostMemory::with_dma_buf`). No + // lock of the runtime's is held. + let (buffer, memory) = + match unsafe { self.import_by_pointer(importer, pointer, length, host, class) }? { + Ok(made) => made, + // SAFETY: as above. + Err(source) => unsafe { + self.import_from_source(call, importer, pointer, length, &window, source, class) + }?, + }; + let (address, reserved) = match self.place_window(placement, &window, length) { + Ok(held) => held, Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(shared.vk(), buffer.raw) }; + self.discard_import(buffer, memory); return Err(error); } }; @@ -548,18 +549,9 @@ impl Device { .host_import .as_ref() .map_err(|unsupported| Error::Unsupported(unsupported.clone()))?; - let pointer = memory.pointer(); - let window = import_window( - pointer.as_ptr() as u64, - length, - importer.page, - importer.alignment, - ) - .map_err(|refusal| match refusal { - // Memory past the address space's end is not mapped: Metal makes no buffer over it. - WindowRefusal::Overflow => nil(call, Problem::BufferLength { length }), - WindowRefusal::BeyondPages | WindowRefusal::Binding => not_importable(), - })?; + let (pointer, source) = memory.into_parts(); + let host = host_window(call, importer, pointer, length, source)?; + let window = host.window; if heap.is_some() && window.offset != 0 { let alignment = importer.page.max(importer.alignment); let problem = HeapProblem::HostMemoryAlignment { alignment }; @@ -577,25 +569,48 @@ impl Device { refuse_unwritable(&window)?; // Detached bytes are given pages with no texture being made over them, and none is // made until the textures that presented stand-ins present their own images again. - let settled = match cell.detached() { - true => Some( - cell.settled() - .ok_or(Error::NotImplemented(RuntimeGap::DetachTextures))?, - ), + let detached_textures = || Error::NotImplemented(RuntimeGap::DetachTextures); + let mut settled = match cell.detached() { + true => Some(cell.settled().ok_or_else(detached_textures)?), false => None, }; - let host = self.host_buffer(&window, length)?; - // The window starts `window.offset` bytes before the pointer, in the pages it touches. - let start = pointer.as_ptr().wrapping_sub(window.offset as usize); // SAFETY: the window lies in the pages of the caller's bytes, which stay mapped - // (`HostMemory::new`), and the buffer is a new one of this device. - let placed = unsafe { self.import_backing(importer, &host, start, &window, class) }; - let placement = match placed { - Ok(placement) => placement, - Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(shared.vk(), host.raw) }; - return Err(error); + // (`HostMemory::new`, `HostMemory::with_dma_buf`). + let (host, placement, remade) = match unsafe { + self.import_by_pointer(importer, pointer, length, host, class) + }? { + Ok((host, placement)) => (host, placement, Remade::default()), + // The source is called with no lock of the runtime's held (`dma_buf.rs`): the + // textures over detached bytes are let go of meanwhile, and must be settled again + // after it. + Err(source) => { + let was_settled = settled.take().is_some(); + // SAFETY: as above, and the source's pieces hold the pages + // (`HostMemory::with_dma_buf`). + let (host, placement) = unsafe { + self.import_from_source(call, importer, pointer, length, &window, source, class) + }?; + // The aliasing images of the textures over the bytes, made over dma-bufs of their + // own pages, each of which the source makes: still with no lock held. + let again = self.dma_buf_images_again(&aliases, heap, &placement, pointer); + let remade = match again { + Ok(remade) => remade, + Err(error) => { + self.discard_import(host, placement); + return Err(error); + } + }; + if was_settled { + match cell.settled() { + Some(again) => settled = Some(again), + None => { + drop(remade); + self.discard_import(host, placement); + return Err(detached_textures()); + } + } + } + (host, placement, remade) } }; let pages = self.host_pages( @@ -607,13 +622,14 @@ impl Device { ); // The heap's images bound to its bytes, made again over the new pages. A refusal drops // them and the new pages unreleased: the deallocator goes unrun. + let mut remade = remade; let mut swaps = match heap { - Some(heap) => self.rebound_heap_images(heap, &pages)?, + Some(heap) => self.rebound_heap_images(heap, &pages, &mut remade)?, None => Vec::new(), }; // The aliasing images of the textures over the bytes, made again over the new pages. if !aliases.is_empty() { - swaps.extend(self.rebound_alias_images(&aliases, &pages)?); + swaps.extend(self.rebound_alias_images(&aliases, &pages, remade)?); } let (old, again) = shared .rebinds @@ -747,39 +763,103 @@ impl Device { Ok(buffer) } - /// Import the window's pages at `start`, bind `buffer` in them, `buffer.base` bytes below - /// the window's offset, and hold bytes of the address space for the buffer's `length` bytes - /// at `address`: the placement, and the buffer's address and held bytes. A range the runtime - /// picks keeps the pointer's offset in its page, as Metal's address does. Everything is - /// released again on failure but the buffer. + /// The pointer's import of `host`'s window ([`Device::import_pointer`]), where the device's + /// import alignment covers it, exactly as ever; and where the device refuses it ([`refused`]: + /// no window, a buffer that does not fit it, no memory type, a driver refusal) and the caller + /// gave a dma-buf source the device can use, the source, uncalled (`Err`), for the caller to + /// call with no lock of the runtime's held (`Device::import_from_source`, `dma_buf.rs`). A + /// refusal without such a source is the pointer's. /// /// # Safety /// - /// The window's `size` bytes at `start` are host memory of this process that stays mapped - /// until the buffer is dropped; `buffer` is an unbound buffer of this device made for host - /// allocations. - unsafe fn import_pages( + /// The window's pages are host memory of this process that stays mapped until the + /// placement is freed (`HostMemory::new`). + unsafe fn import_by_pointer( &self, importer: &Importer, - buffer: &HostBuffer, - start: *mut u8, + pointer: NonNull, + length: u64, + host: HostWindow, + class: MemoryClass, + ) -> Result, Error> { + let HostWindow { + window, + by_pointer, + source, + } = host; + let refusal = match by_pointer { + // SAFETY: the caller's. + true => match unsafe { self.import_pointer(importer, pointer, length, &window, class) } + { + Ok(imported) => return Ok(Ok(imported)), + Err(error) if refused(&error) => error, + Err(error) => return Err(error), + }, + false => not_importable(), + }; + source.map(Err).ok_or(refusal) + } + + /// The `VkBuffer` of a no-copy buffer of `length` bytes at `pointer`, made for host + /// allocations and bound in the import of the window's pages at their pointer + /// (`VK_EXT_external_memory_host`), `buffer.base` bytes below the window's offset, as memory + /// of `class`: the buffer and the placement. Released again on failure. + /// + /// # Safety + /// + /// The window's `size` bytes are host memory of this process that stays mapped until the + /// placement is freed. + unsafe fn import_pointer( + &self, + importer: &Importer, + pointer: NonNull, + length: u64, window: &ImportWindow, class: MemoryClass, - address: Place, - length: u64, - ) -> Result<(Placement, (GpuAddress, Held)), Error> { - let shared = self.shared(); - // SAFETY: the caller's. - let placement = unsafe { self.import_backing(importer, buffer, start, window, class) }?; - match self.place_window(address, window, length) { - Ok(held) => Ok((placement, held)), + ) -> Result<(HostBuffer, Placement), Error> { + let buffer = self.host_buffer(window, length)?; + // The window starts `window.offset` bytes before the pointer, in the pages it touches. + let start = pointer.as_ptr().wrapping_sub(window.offset as usize); + // SAFETY: the caller's, and the buffer is a new one of this device. + match unsafe { self.import_backing(importer, &buffer, start, window, class) } { + Ok(placement) => Ok((buffer, placement)), Err(error) => { - lock(&shared.memory).free(shared.vk(), &placement); + // SAFETY: the buffer is unused. + unsafe { release::object(self.shared().vk(), buffer.raw) }; Err(error) } } } + /// No dma-buf is imported on this system: there is no source to call. + /// + /// # Safety + /// + /// None: it does nothing. + #[cfg(not(unix))] + unsafe fn import_from_source( + &self, + _call: &'static str, + _importer: &Importer, + _pointer: NonNull, + _length: u64, + _window: &ImportWindow, + source: Source, + _class: MemoryClass, + ) -> Result<(HostBuffer, Placement), Error> { + match source {} + } + + /// Release `buffer` and its `placement`, an import made for a buffer or rebind that is not + /// made after all: the `VkBuffer` first, once its sparse binding completed. + fn discard_import(&self, buffer: HostBuffer, placement: Placement) { + let shared = self.shared(); + placement.settle(); + // SAFETY: the buffer is unused, and its binding completed. + unsafe { release::object(shared.vk(), buffer.raw) }; + lock(&shared.memory).free(shared.vk(), &placement); + } + /// The Metal addresses of a no-copy buffer of `length` bytes `window.offset` bytes into /// `window`, placed as `address` asks: the window's pages where the program names no address, /// so that the buffer's address keeps its pointer's offset in its page. @@ -836,7 +916,9 @@ impl Device { /// /// # Safety /// - /// As [`Device::import_pages`]'s. + /// The window's `size` bytes at `start` are host memory of this process that stays mapped + /// until the placement is freed; `buffer` is an unbound buffer of this device made for host + /// allocations. unsafe fn import_backing( &self, importer: &Importer, @@ -911,11 +993,51 @@ impl Device { } } +/// The host pages a no-copy buffer (or a heap's own buffer) of some length imports +/// ([`host_window`]). +struct HostWindow { + /// The pages: the range rounded out to the host page. + window: ImportWindow, + /// Whether the device's import alignment covers them, so that their pointer is imported + /// first (`VK_EXT_external_memory_host`). + by_pointer: bool, + /// The caller's dma-buf source, where it gave one and the device imports dma-bufs. + source: Option, +} + +/// The host pages a no-copy object of `length` bytes at `pointer` imports on the device of +/// `importer`, for `call`: the pages the range touches ([`import_window`]), imported by their +/// pointer where the device's import alignment covers them, else only as a dma-buf where the +/// caller gave a source the device can use. A source the device cannot use is dropped uncalled. +/// Refused: memory past the address space's end (`Nil`, as Metal makes no buffer over it); a +/// range the import alignment cannot cover, with no usable source (`Unsupported`, `HostMemory`). +fn host_window( + call: &'static str, + importer: &Importer, + pointer: NonNull, + length: u64, + source: Option, +) -> Result { + let source = source.filter(|_| importer.imports_dma_bufs()); + let at = pointer.as_ptr() as u64; + let window = import_window(at, length, importer.page, 1) + .map_err(|_| nil(call, Problem::BufferLength { length }))?; + let by_pointer = import_window(at, length, importer.page, importer.alignment).is_ok(); + if !by_pointer && source.is_none() { + return Err(not_importable()); + } + Ok(HostWindow { + window, + by_pointer, + source, + }) +} + /// A no-copy buffer's unbound `VkBuffer` (`Device::host_buffer`): `size` bytes, its bytes from /// `base`, with its memory requirements. -struct HostBuffer { - raw: vk::Buffer, - base: u64, - size: u64, - requirements: vk::MemoryRequirements, +pub(super) struct HostBuffer { + pub(super) raw: vk::Buffer, + pub(super) base: u64, + pub(super) size: u64, + pub(super) requirements: vk::MemoryRequirements, } diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index b3228069f..7fd5f28f0 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -930,19 +930,22 @@ impl Texels { } /// The attachment twin of `pixel_format` kept with the texels (a texture buffer's, or a - /// rotated texture's), made by `make` at the first pass that needs it. + /// rotated texture's), made by `make` at the first pass that needs it, with the twins' + /// lock not held: a twin over dma-buf pages calls the program's source (`dma_buf.rs`). Where + /// another pass made one meanwhile, that one is kept and `make`'s goes, with no lock held. pub(super) fn twin( &self, pixel_format: PixelFormat, make: impl FnOnce() -> Result, ) -> Result { - let mut twins = lock(&self.twins); - if let Some(twin) = twins.get(&pixel_format) { + if let Some(twin) = lock(&self.twins).get(&pixel_format) { return Ok(twin.clone()); } - let twin = make()?; - twins.insert(pixel_format, twin.clone()); - Ok(twin) + let made = make()?; + let kept = (lock(&self.twins).entry(pixel_format)) + .or_insert_with(|| made.clone()) + .clone(); + Ok(kept) } /// The copies of a rotated texture's image of its pass's frame (`image` of `identity`, of diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 30a438e9c..687d27375 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -402,6 +402,13 @@ impl CommandBufferShared { wait_values.push(value); wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); } + // And the last binding of a no-copy buffer's dma-bufs, on every `VkQueue`, the first + // too (a binding is ordered with no later submission), until it completed. + if let Some((timeline, value)) = device.binding_wait() { + wait_semaphores.push(timeline); + wait_values.push(value); + wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); + } // The first work waits for what the batch's commands wait for (a heap's fill another // queue did comes before a move of an image placed in it; an event the program waits // for before reusing a heap's memory), but a binary semaphore, which one wait consumes; diff --git a/crates/metal2vulkan-runtime/src/creation.rs b/crates/metal2vulkan-runtime/src/creation.rs index 8b5a8e280..91827bf14 100644 --- a/crates/metal2vulkan-runtime/src/creation.rs +++ b/crates/metal2vulkan-runtime/src/creation.rs @@ -39,6 +39,27 @@ pub(crate) unsafe fn image( unsafe { device.create_image(info, None) }.map_err(vulkan) } +/// A `VkImage` of `info`, made by `device`, or the driver's refusal of it: an image whose making +/// the driver may refuse for its parameters alone (one of a DRM format modifier's explicit +/// layout, `dma_buf.rs`), whose caller takes another way then. A lost device is +/// `Error::DeviceLost`; refused in a host step. +/// +/// # Safety +/// +/// As `vkCreateImage`'s: `device` is live, and `info` and its chain are valid for it. +pub(crate) unsafe fn image_or_refusal( + device: &ash::Device, + info: &vk::ImageCreateInfo<'_>, +) -> Result, Error> { + outside_host_step(HostStepObject::Image)?; + // SAFETY: the caller's. + match unsafe { device.create_image(info, None) } { + Ok(raw) => Ok(Ok(raw)), + Err(vk::Result::ERROR_DEVICE_LOST) => Err(Error::DeviceLost), + Err(refusal) => Ok(Err(refusal)), + } +} + /// A `VkRenderPass` of `info`, made by `device`; refused in a host step. /// /// # Safety diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 0805528e2..e0f5f067e 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -222,9 +222,10 @@ degradations! { /// A 2D texture over a buffer is a shadow image: no linear image of the device lays its /// texels out as Metal does in the buffer's memory (over a no-copy buffer's imported /// host memory, no linear image made for host allocations does), or the buffer is over - /// the caller's `VkBuffer`, whose memory backs no image of the runtime's. Also a heap's - /// depth or stencil texture on a device whose driver lays - /// such images apart from their memory + /// the caller's `VkBuffer`, whose memory backs no image of the runtime's, or over host + /// pages imported as dma-bufs (`HostMemory::with_dma_buf`) where the device makes no image + /// over a dma-buf of the texture's own pages (the notice names why). Also a heap's depth + /// or stencil texture on a device whose driver lays such images apart from their memory /// ([`metal2vulkan::device::DriverFact::DepthStencilImagesLieApart`]): its image is a /// shadow of the heap's bytes in its range. Also a heap's 2D texture of one level of /// `RGB10A8_2P_XR10` or its sRGB twin: its image is a shadow of its two planes in the diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs index 25b72baa8..73f84ba40 100644 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ b/crates/metal2vulkan-runtime/src/device/adopt.rs @@ -50,7 +50,10 @@ pub struct RawDevice { /// buffer a Metal texture over the buffer's imported memory, without a copy; /// `VK_NV_linear_color_attachment`, with its `linearColorAttachment` feature enabled beside /// it (and, below Vulkan 1.3, `VK_KHR_format_feature_flags2`, which it requires there), makes - /// a texture over a buffer's memory render into its linear image in place. + /// a texture over a buffer's memory render into its linear image in place; + /// `VK_KHR_external_memory_fd` with `VK_EXT_external_memory_dma_buf` serve + /// `HostMemory::with_dma_buf`, and with them `VK_EXT_image_drm_format_modifier` with + /// `VK_EXT_queue_family_foreign` make textures over its pages images rather than shadows. pub device_extensions: Vec, /// Where the device keeps translated shaders: by default, the platform's per-user cache /// directory. @@ -219,6 +222,9 @@ impl Device { // `VK_KHR_pipeline_library` with its feature, and the device's properties say whether it // links fast, as a made device takes it. let listed: BTreeSet = raw.device_extensions.iter().cloned().collect(); + // Nor whether the dma-buf route's were (`dma_buf.rs`): the consumer lists them. + let dma_buf = super::create::dma_buf_names(&listed).is_some(); + let dma_buf_images = super::create::dma_buf_image_names(&listed).is_some(); let graphics_pipeline_library = super::create::graphics_pipeline_library(&listed, || { // SAFETY: the consumer's physical device of its instance, which lists the // extension (the consumer enabled it), at Vulkan 1.2 or later. @@ -254,6 +260,8 @@ impl Device { .device_extensions .iter() .any(|name| name.as_c_str() == ash::ext::pipeline_creation_feedback::NAME), + dma_buf, + dma_buf_images, calibration: gpu_time::Extension::among(&raw.device_extensions.into_iter().collect()), gpu_times_from_host: raw.gpu_times_from_host, // An adopted device keeps no execution record: validation makes its own devices. diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index 6e312653e..76a0d07e5 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -742,6 +742,34 @@ pub(crate) fn enable_set(description: &DeviceDescription, options: &DeviceOption set } +/// The extensions of the dma-buf route (`dma_buf.rs`) of a device listing `listed`: +/// `VK_KHR_external_memory_fd` and the `VK_EXT_external_memory_dma_buf` that requires it, where the +/// device lists both. The runtime's own need, outside the vocabulary, so outside the enable set, +/// the compile profile and its fingerprint (the shader cache's key). +pub(crate) fn dma_buf_names(listed: &BTreeSet) -> Option<[&'static CStr; 2]> { + let names = [ + ash::khr::external_memory_fd::NAME, + ash::ext::external_memory_dma_buf::NAME, + ]; + names + .iter() + .all(|name| listed.contains(*name)) + .then_some(names) +} + +/// The extensions of the images of textures over the dma-buf route's pages (`dma_buf.rs`) of a +/// device listing `listed`: `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign`, +/// where the device lists both and the route's two ([`dma_buf_names`]). Outside the vocabulary as +/// the route's are; what they require is core at the runtime's Vulkan 1.2 floor. +pub(crate) fn dma_buf_image_names(listed: &BTreeSet) -> Option<[&'static CStr; 2]> { + let names = [ + ash::ext::image_drm_format_modifier::NAME, + ash::ext::queue_family_foreign::NAME, + ]; + (dma_buf_names(listed).is_some() && names.iter().all(|name| listed.contains(*name))) + .then_some(names) +} + /// Whether a device of `description` the runtime creates under `options` enables /// `VK_EXT_device_generated_commands`: where the description states it (the extension and its /// `deviceGeneratedCommands`), `options` do not withhold it, and `set` enables @@ -1076,6 +1104,9 @@ fn create_on( .device_extensions .iter() .any(|name| name.as_c_str() == feedback_name); + // The runtime's own needs, outside the vocabulary, where listed (`dma_buf.rs`). + let dma_buf = dma_buf_names(&listed); + let dma_buf_images = dma_buf_image_names(&listed); let extra: Vec = options .device_extensions .iter() @@ -1083,6 +1114,8 @@ fn create_on( .chain(calibration.map(|extension| extension.name().to_owned())) .chain((metal_objects && !metal_asked).then(|| metal_name.to_owned())) .chain((creation_feedback && !feedback_asked).then(|| feedback_name.to_owned())) + .chain(dma_buf.into_iter().flatten().map(CStr::to_owned)) + .chain(dma_buf_images.into_iter().flatten().map(CStr::to_owned)) .collect(); let mut enables = Enables::of(&set, api, &listed, &extra)?; // The features of the caller's extensions whose structures the runtime knows, as the device @@ -1222,6 +1255,8 @@ fn create_on( graphics_pipeline_library, metal_objects: metal_objects || metal_asked, creation_feedback: creation_feedback || feedback_asked, + dma_buf: dma_buf.is_some(), + dma_buf_images: dma_buf_images.is_some(), sparse_features, owned: true, cache: cache.clone(), diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 346bb5e0a..d539bb0b8 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -222,6 +222,10 @@ pub(super) struct DeviceShared { /// a dispatch of the state that made it (`function_table.rs`). pub(super) function_tables: Mutex>>, internal: Mutex>, + /// The last sparse binding of a no-copy buffer's dma-bufs (`dma_buf.rs`) the host has not + /// seen complete: the internal timeline and the value it signals, which every later + /// submission that may use the buffer waits for (`submit.rs`). + bound_at: Mutex>, /// The queue reserved for staging copies, where the device has one (`staging.rs`). staging: Option, pub(super) scheduler: Scheduler, @@ -767,6 +771,11 @@ pub(super) struct Parts { /// vocabulary, wherever listed: each making of a program's pipeline reads whether its cache /// held the pipeline (`shader_cache/mod.rs`). pub(super) creation_feedback: bool, + /// It enables the dma-buf route's extensions (`create.rs`'s `dma_buf_names`), outside + /// `enabled`'s vocabulary (`dma_buf.rs`). + pub(super) dma_buf: bool, + /// It enables the route's image extensions (`create.rs`'s `dma_buf_image_names`), likewise. + pub(super) dma_buf_images: bool, /// The sparse members of the core features it enables, outside `enabled`'s vocabulary /// (`sparse/device.rs`). pub(super) sparse_features: vk::PhysicalDeviceFeatures, @@ -810,6 +819,8 @@ impl Device { graphics_pipeline_library, metal_objects, creation_feedback, + dma_buf, + dma_buf_images, sparse_features, owned, cache, @@ -1012,6 +1023,8 @@ impl Device { &loader_word, metal_objects, instance.sink().is_some(), + dma_buf, + dma_buf_images, ) }; // SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back. @@ -1202,6 +1215,7 @@ impl Device { heap_nan_residue: NanResidue::default(), function_tables: Mutex::default(), internal: Mutex::new(None), + bound_at: Mutex::new(None), staging, scheduler, completion, diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs index 0ba552237..222b1e0a1 100644 --- a/crates/metal2vulkan-runtime/src/device/submit.rs +++ b/crates/metal2vulkan-runtime/src/device/submit.rs @@ -6,10 +6,16 @@ //! work that waits (`texture/first_move.rs`), after the batches on other `VkQueue`s that did such //! work: no new resource waits for one, so making one waits for no GPU work. That work goes in a //! submission of its own just before the work's. +//! +//! The one submission no one waits for is a no-copy buffer's sparse binding of its dma-bufs +//! (`dma_buf.rs`), on the same queue and timeline: it would wait behind the queue's work in +//! flight. Every submission after it, on every `VkQueue`, waits for it until the host saw it +//! complete, and the buffer's release waits for it. use super::relay::By; use super::{lock, Device}; use crate::error::{vulkan, Error}; +use crate::exit_guard::{self, Call}; use crate::release; use crate::resource::ResourceKey; use ash::vk; @@ -170,10 +176,13 @@ impl Device { // SAFETY: the fence is unsignaled or signaled and not pending. unsafe { raw.reset_fences(&[objects.fence]) }.map_err(vulkan)?; let buffers = [objects.buffer]; - let wait_semaphores: Vec = (waits.iter()) - .map(|point| shared.queues[point.queue].timeline) + // And the last binding of a no-copy buffer's dma-bufs, until it completed. + let waits: Vec<(vk::Semaphore, u64)> = (waits.iter()) + .map(|point| (shared.queues[point.queue].timeline, point.value)) + .chain(self.binding_wait()) .collect(); - let wait_values: Vec = waits.iter().map(|point| point.value).collect(); + let wait_semaphores: Vec = waits.iter().map(|wait| wait.0).collect(); + let wait_values: Vec = waits.iter().map(|wait| wait.1).collect(); let wait_stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; waits.len()]; // It signals its own timeline, which a batch on another `VkQueue` waits for where it did // first work. @@ -261,6 +270,70 @@ impl Device { } } + /// Bind `binds` to `buffer`, a sparse buffer no command has used, with one + /// `vkQueueBindSparse` on the device's first `VkQueue` that signals the internal timeline, + /// and return without waiting for it: every submission made after it, on every `VkQueue`, + /// waits for it until the host saw it complete ([`Device::binding_wait`]). The timeline and + /// the value it signals, which the buffer's release waits for. + pub(crate) fn bind_sparse_buffer( + &self, + buffer: vk::Buffer, + binds: &[vk::SparseMemoryBind], + ) -> Result<(vk::Semaphore, u64), Error> { + if self.is_lost() { + return Err(Error::DeviceLost); + } + let shared = self.shared(); + let raw = shared.vk(); + let mut internal = lock(&shared.internal); + if internal.is_none() { + *internal = Some(Internal::new(self)?); + } + let Some(objects) = internal.as_mut() else { + unreachable!("made above"); + }; + let buffer_binds = [vk::SparseBufferMemoryBindInfo::default() + .buffer(buffer) + .binds(binds)]; + let value = objects.signalled + 1; + let signal_semaphores = [objects.timeline]; + let signal_values = [value]; + let mut timeline = + vk::TimelineSemaphoreSubmitInfo::default().signal_semaphore_values(&signal_values); + let info = vk::BindSparseInfo::default() + .buffer_binds(&buffer_binds) + .signal_semaphores(&signal_semaphores) + .push_next(&mut timeline); + // SAFETY: the buffer is live, made with `SPARSE_BINDING`, unused; every bind lies in it + // and in its memory at its alignment, of a type it takes (`dma_buf.rs`); the queue's + // family binds sparse memory, and the queue is used under its lock; the signal is above + // the timeline's value (the internal lock is held). + let bound = shared.use_queue(0, By::Runtime, |queue| unsafe { + raw.queue_bind_sparse(queue, &[info], vk::Fence::null()) + }); + exit_guard::called(Call::QueueBindSparse); + bound.map_err(|error| self.failed(error))?; + objects.signalled = value; + *lock(&shared.bound_at) = Some((objects.timeline, value)); + Ok((objects.timeline, value)) + } + + /// The last binding of a no-copy buffer's dma-bufs ([`Device::bind_sparse_buffer`]) while + /// the host has not seen it complete: what a submission waits for, as the buffer may be + /// among what it uses. + pub(crate) fn binding_wait(&self) -> Option<(vk::Semaphore, u64)> { + let shared = self.shared(); + let mut bound_at = lock(&shared.bound_at); + let (timeline, value) = (*bound_at)?; + // SAFETY: the timeline is the device's, live while the device is. + let reached = unsafe { shared.vk().get_semaphore_counter_value(timeline) }; + if reached.is_ok_and(|reached| reached >= value) { + *bound_at = None; + return None; + } + Some((timeline, value)) + } + /// The error of a failed submission or wait, recording a lost device. pub(crate) fn failed(&self, error: vk::Result) -> Error { if error == vk::Result::ERROR_DEVICE_LOST { diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs new file mode 100644 index 000000000..f1341101a --- /dev/null +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -0,0 +1,1123 @@ +//! Dma-bufs of host pages (a runtime extension: Metal has none), the last resort of a no-copy +//! import (`host_memory.rs`) on a device that refuses the pages' pointer, as RADV refuses any +//! shared mapping (a `memfd`'s among them). A device that lists `VK_EXT_external_memory_dma_buf` +//! and `VK_KHR_external_memory_fd` enables both, outside the vocabulary +//! (`device::create::dma_buf_names`), and has a dma-buf importer; one that imports the pointer +//! never calls a source. The caller's contract is [`DmaBufSource`]'s, [`DmaBufRequest`]'s and +//! `HostMemory::with_dma_buf`'s; this is how the runtime keeps it. +//! +//! - **The imports.** Each chunk is its own memory, of the best type of the buffer's memory class +//! (`memory.rs`'s `candidates`: host-visible and coherent, never a device-coherent type of +//! `VK_AMD_device_coherent_memory`, which the runtime does not enable) among those +//! `vkGetMemoryFdPropertiesKHR` and the buffer take. A source that was called is kept with the +//! imports ([`DmaBufPages`]) and dropped with them. +//! - **The buffer** is a `VkBuffer` made for dma-bufs over the pages from their first byte, so its +//! bytes lie at their offset in their first page whatever the chunks, and a rebind between one +//! chunk and several keeps their place in it. **One chunk** gives a plain buffer bound at the +//! import's start. **Several chunks** give a sparse one (`SPARSE_BINDING`), each chunk bound at +//! its offset from the request's start by one `vkQueueBindSparse` on the device's first queue +//! (`device/submit.rs`): the call does not wait for it, which would wait behind that queue's +//! work in flight; every later submission on every queue waits for it until it completed, and +//! the buffer's release does where none did. The granule is the alignment of such a buffer +//! where the device has `sparseBinding`, its queue family binds sparse memory and it imports +//! dma-bufs for such a buffer (64 KiB on RADV of Mesa 26.2.4, 4 KiB on 26.0.8); elsewhere the +//! request's length, so that exactly one chunk is taken (NVIDIA's sparse buffers take no type +//! its dma-bufs import as; it imports the pointer anyway). The padding past the pages lies +//! inside the `VkBuffer` but past the bytes a copy or a binding reaches. +//! - **The bytes.** The runtime never maps a dma-buf: `contents` stays the caller's pointer, and +//! the CPU's writes through it and the GPU's through the imports meet in the same pages with no +//! flush or invalidate (the types are host-coherent). +//! - **Textures** over such pages (a no-copy buffer's texture and its views, or a texture placed in +//! such a heap), where the device also lists `VK_EXT_image_drm_format_modifier` and +//! `VK_EXT_queue_family_foreign` (enabled beside the route, `create.rs`'s `dma_buf_image_names`), +//! are each an image of `DRM_FORMAT_MOD_LINEAR` made for dma-bufs and bound to a dedicated import +//! (`VkMemoryDedicatedAllocateInfo`) of the one dma-buf the source makes of the pages its memory +//! requirements cover ([`Device::dma_buf_image`]). Its one plane starts at the texels' offset in +//! their first page; its rows are the texture's (`bytesPerRow`) over a buffer, and the driver's +//! own (`VkImageDrmFormatModifierListCreateInfoEXT`) in a heap, where a texture over pages +//! imported by their pointer is the driver's linear image. Its features are the modifier's +//! (64-bit where the device has `format_feature_flags2`: `modifier_features`), checked as a +//! linear image's are against the optimal tiling's for the texture's usage, and its limits the +//! format query's for that modifier and dma-bufs. RADV (Mesa 26.2.4 and 26.0.8) lays a plane only +//! at an offset that is a multiple of 256 bytes and rows a multiple of 256 apart, and refuses any +//! other layout (`VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT`): the runtime asks the +//! driver and takes its answer, never a rule of its own. The source is called only once the image +//! is made and checked; the import keeps it, and goes after the image. Counted: +//! `WorkCounts::dma_buf_images`. +//! - **Their layouts.** The image is made `UNDEFINED`, as Vulkan makes an image of external +//! memory (`VUID-VkImageCreateInfo-pNext-01443`), and the first submission that uses it acquires +//! it from `VK_QUEUE_FAMILY_FOREIGN_EXT` into `GENERAL` (`texture/first_move.rs`), from +//! `GENERAL`, which keeps its contents: Vulkan leaves undefined the contents of an exclusive +//! resource first used without its ownership transferred from the foreign family. It rests in +//! `GENERAL` from then on, with no acquire or release around later submissions: the pages are +//! the caller's host memory, which only the CPU (through `contents`) and this device touch, and +//! the CPU's writes there are host writes to host-coherent memory, which a submission orders +//! after them, as for the buffer's import; a `DRM_FORMAT_MOD_LINEAR` image keeps no metadata a +//! foreign write could leave stale. Measured on RADV of both versions: a CPU write between two +//! submissions, with no acquire between, is what the second reads; the GPU's writes reach the +//! pages at the texels' places and leave the rows' padding. +//! - **Their hazards.** The image takes the identity of the bytes it lies over (the buffer's, or +//! the heap's), so hazard tracking orders its uses against the buffer's and the heap's other +//! resources' over the same pages, as for any aliasing image, though its import is its own. +//! - **Where none is made** (for the reasons [`Device::dma_buf_image`] lists), the texture takes +//! the way it took before such images: a shadow of the bytes, counted +//! (`WorkCounts::dma_buf_image_fallbacks`) and announced (`shadowed-texture`, naming why). +//! - **Rebinds** onto pages imported as dma-bufs make each texture's image again over its own new +//! pages before the rebind settles (`rebind.rs`), and are refused +//! (`NotImplemented(RebindTextures)`) where one is not made. +//! - **Refused** (the pointer's refusal: `Unsupported`, `HostMemory`): a source that fails, chunks +//! the device imports as no type the buffer takes, a driver that refuses a chunk, and a sparse +//! buffer whose alignment misses the granule asked. Counted: `WorkCounts::dma_buf_imports` (each +//! chunk) and `WorkCounts::dma_buf_sparse_buffers`. + +use super::buffer::usage; +use super::buffer_descriptor::HostBuffer; +use super::device::lock; +use super::error::{invalid, vulkan, Error, Problem}; +use super::exit_guard::{self, Call}; +use super::host_memory::{based_size, import_refused, not_importable, ImportWindow, Importer}; +use super::image_plan::{ImageFacts, ImagePlan}; +use super::linear_plan::{check_linear_limits, tiling_lack, viewed_formats, LinearLack}; +use super::memory::{ImportFailure, MemoryClass, Placement}; +use super::Device; +use crate::release; +use ash::vk; +use metal2vulkan::vk::{Format, FormatFeatureFlags2, ImageCreateFlags, SampleCountFlags}; +use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; +use std::ptr::NonNull; +use std::sync::Arc; +use std::time::Duration; + +/// A runtime extension (Metal has none): makes dma-bufs of the host pages a no-copy import +/// covers, for a device that refuses the pages' pointer +/// ([`HostMemory::with_dma_buf`](crate::HostMemory::with_dma_buf)). +/// +/// Called on the thread making the object, with no lock of the runtime's held: for a buffer or +/// heap (or its rebind), only where the device refuses the pointer and imports dma-bufs for it; +/// then once for each image the runtime makes over a texture's own pages in them (over the +/// buffer, placed in the heap, a view of one, or remade by a rebind). A source the runtime never +/// calls is dropped with the call; one it called is kept with the imports it made, until they go. +/// +/// It returns dma-bufs of the pages asked for ([`DmaBufRequest`]) in chunks ([`DmaBufChunk`]), in +/// order: each chunk's length a positive multiple of the host page, at most its dma-buf's size, +/// and every boundary between two chunks, as an offset from the request's `start`, a multiple of +/// its `granule`. The descriptors are the runtime's from then on: Vulkan's once imported, closed +/// otherwise. An `Err` keeps the pointer's refusal (`Unsupported`, `HostMemory`), or makes a +/// texture a shadow of the bytes instead (announced `shadowed-texture`); chunks that break these +/// rules or the request's, or a descriptor that is no dma-buf, are refused as misuse (`Invalid`, +/// `Problem::DmaBuf`). +pub type DmaBufSource = + Arc std::io::Result> + Send + Sync + 'static>; + +/// What a [`DmaBufSource`] is asked for: `length` bytes of host pages from `start`, both multiples +/// of the host page, to be returned as chunks split only at multiples of `granule` from `start`. +/// +/// A buffer's or heap's request is the caller's range rounded out to the host page, whatever the +/// device's import alignment for host pointers (a dma-buf has none). A texture's starts at the page +/// its texels start in and runs through the pages its image's memory covers, inside an import's +/// pages; its `granule` is its `length`, and the image is bound to its one chunk's import alone. +/// +/// One chunk holds the `length` bytes, or them rounded up to `granule`. Several hold exactly that +/// rounding (Vulkan binds a sparse buffer's memory in whole granules, +/// `VUID-VkSparseMemoryBind-resourceOffset-09491`): the last chunk's pages past `length` are +/// padding, which the buffer's bytes never reach and the GPU reaches only through an access past +/// the buffer's pages. Pad with a scratch page of the caller's own, repeated, not pages of other +/// memory. Chunks that total otherwise are refused (`Invalid`, `Problem::DmaBuf`). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DmaBufRequest { + /// The first byte of the first page. + pub start: NonNull, + /// The bytes of the pages. + pub length: u64, + /// The multiple of which every boundary between two chunks lies from `start`: the alignment + /// of a sparse buffer made for dma-bufs, where the device binds one in several chunks + /// (a multiple of the host page); `length` where it does not, so that exactly one chunk is + /// taken. + pub granule: u64, +} + +// SAFETY: a request is an address and two lengths, plain data: nothing is reached through the +// address by having the request. +unsafe impl Send for DmaBufRequest {} +// SAFETY: as above. +unsafe impl Sync for DmaBufRequest {} + +/// One chunk of a [`DmaBufSource`]'s answer: a dma-buf whose bytes `0..length` are the requested +/// pages from where the chunks before it end. +#[derive(Debug)] +pub struct DmaBufChunk { + /// The dma-buf. + pub fd: OwnedFd, + /// The bytes of the chunk, a multiple of the host page. + pub length: u64, +} + +/// The imports of the chunks a no-copy buffer's host pages lie in, and the source that made them: +/// held by the pages' placement (`memory.rs`), so by the buffers and images over them, and freed, +/// the source dropped, once the last of those goes. Every `VkBuffer` bound to them is destroyed +/// first (`buffer.rs`'s `HostImport`). +/// +/// The last holder may go on a runtime thread (a command buffer's completion lets go of the +/// buffer): the imports are freed inside a section of the exit guard, as every Vulkan call there +/// is, and the source, the program's code, is dropped after it as the program's +/// (`exit_guard::program`), its panic caught. While the process exits both are left to its end. +pub(super) struct DmaBufPages { + device: Device, + memories: Vec, + /// The caller's source; taken only as the pages drop. + source: Option, + /// The host address of the first page, and the bytes of the pages: what the source made the + /// imports of. + start: u64, + length: u64, + /// The sparse binding of the buffer over several imports, which nothing waited for: the + /// internal timeline and the value it signals (`Device::bind_sparse_buffer`). + bound: Option<(vk::Semaphore, u64)>, +} + +impl Drop for DmaBufPages { + fn drop(&mut self) { + // The Vulkan teardown is a section of the exit guard. + let Some(busy) = exit_guard::enter() else { + // The process is exiting: the imports stay to its end, and the source with them. + if let Some(source) = self.source.take() { + std::mem::forget(source); + } + return; + }; + let raw_device = self.device.shared().vk(); + for &memory in &self.memories { + // SAFETY: nothing is bound to the imports any more and no command reads them (the + // struct's docs). + unsafe { release::object(raw_device, memory) }; + } + drop(busy); + if let Some(source) = self.source.take() { + exit_guard::program(move || drop(source)); + } + } +} + +impl DmaBufPages { + /// The imports `source` made of the pages `request` asked for, none imported yet. + fn new(device: &Device, source: DmaBufSource, request: DmaBufRequest) -> DmaBufPages { + DmaBufPages { + device: device.clone(), + memories: Vec::new(), + source: Some(source), + start: request.start.as_ptr() as u64, + length: request.length, + bound: None, + } + } + + /// Wait until the sparse binding of the buffer over the imports completed, where it may not + /// have: before the buffer is destroyed (`buffer.rs`'s `HostImport`, or a buffer not made + /// after all). A submission that used the buffer waited for it, so this waits only for a + /// buffer let go of before any did, behind the first queue's work submitted before it. A lost + /// device ends the wait: its work counts as complete. + pub(super) fn settle(&self) { + let Some((timeline, value)) = self.bound else { + return; + }; + let raw_device = self.device.shared().vk(); + let semaphores = [timeline]; + let values = [value]; + let info = vk::SemaphoreWaitInfo::default() + .semaphores(&semaphores) + .values(&values); + loop { + // SAFETY: the timeline is the device's, live while the device is. + let waited = unsafe { raw_device.wait_semaphores(&info, WAIT_SLICE.as_nanos() as u64) }; + exit_guard::called(Call::WaitSemaphores); + if waited != Err(vk::Result::TIMEOUT) { + return; + } + } + } + + /// Whether the pages hold the `length` bytes from host address `start`. + fn holds(&self, start: u64, length: u64) -> bool { + let end = start.checked_add(length); + start >= self.start && end.is_some_and(|end| end <= self.start + self.length) + } +} + +impl std::fmt::Debug for DmaBufPages { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DmaBufPages") + .field("memories", &self.memories) + .finish_non_exhaustive() + } +} + +/// Whether chunks of `lengths` bytes, in order, answer `request` as the [`DmaBufSource`] contract +/// allows on a host of `page`-byte pages: at least one, each a positive multiple of the page; +/// every boundary between two a multiple of the granule from the request's start; together the +/// request's length rounded up to the granule, or, one chunk, the length itself. +pub(super) fn chunks_cover(lengths: &[u64], request: &DmaBufRequest, page: u64) -> bool { + let page = page.max(1); + let granule = request.granule.max(1); + let Some(rounded) = request.length.checked_next_multiple_of(granule) else { + return false; + }; + let mut end = 0u64; + for &length in lengths { + if !end.is_multiple_of(granule) || length == 0 || !length.is_multiple_of(page) { + return false; + } + end = match end.checked_add(length) { + Some(end) => end, + None => return false, + }; + } + match lengths.len() { + 0 => false, + 1 => end == request.length || end == rounded, + _ => end == rounded, + } +} + +/// Whether `chunks` answer `request` as the [`DmaBufSource`] contract allows on a host of +/// `page`-byte pages ([`chunks_cover`]), each a dma-buf of at least its length. +fn answers(chunks: &[DmaBufChunk], request: &DmaBufRequest, page: u64) -> bool { + let lengths: Vec = chunks.iter().map(|chunk| chunk.length).collect(); + let held = |chunk: &DmaBufChunk| { + dma_buf_length(chunk.fd.as_fd()).is_some_and(|bytes| chunk.length <= bytes) + }; + chunks_cover(&lengths, request, page) && chunks.iter().all(held) +} + +/// The bytes of the dma-buf `fd`; `None` where it is no dma-buf (its file is not on the kernel's +/// dma-buf file system). +#[cfg(target_os = "linux")] +fn dma_buf_length(fd: BorrowedFd<'_>) -> Option { + use std::os::fd::AsRawFd; + /// `DMA_BUF_MAGIC` of Linux's `include/uapi/linux/magic.h`. + const DMA_BUF_MAGIC: u64 = 0x444d_4142; + let mut stat = std::mem::MaybeUninit::::uninit(); + // SAFETY: the descriptor is open for the call, and `fstatfs` writes the structure. + if unsafe { libc::fstatfs(fd.as_raw_fd(), stat.as_mut_ptr()) } != 0 { + return None; + } + // SAFETY: the call succeeded, so it wrote the structure. + let stat = unsafe { stat.assume_init() }; + // The field's type differs between architectures and C libraries. + if i128::from(stat.f_type) != i128::from(DMA_BUF_MAGIC) { + return None; + } + // SAFETY: a dma-buf answers `SEEK_END` with its size (`dma_buf_llseek`), and nothing reads + // through its file position. + let end = unsafe { libc::lseek(fd.as_raw_fd(), 0, libc::SEEK_END) }; + u64::try_from(end).ok() +} + +/// No file is a dma-buf on this system. +#[cfg(not(target_os = "linux"))] +fn dma_buf_length(_fd: BorrowedFd<'_>) -> Option { + None +} + +/// How long one wait for the sparse binding lasts before it is asked again. +const WAIT_SLICE: Duration = Duration::from_millis(100); + +/// The handle type of every import of a dma-buf, and of every buffer and image made for one. +const DMA_BUF: vk::ExternalMemoryHandleTypeFlags = vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT; + +impl Device { + /// The `VkBuffer` of a no-copy buffer of `length` bytes at `pointer`, made for dma-bufs and + /// bound in the imports of the chunks `source` makes of `window`'s pages, as memory of + /// `class`, for `call`: the buffer and its placement, which keeps the imports and the source. + /// The source is asked once the device is known to import dma-bufs for such a buffer, with + /// no lock of the runtime's held, and never again here. Refused, everything made released, + /// as the module says. + /// + /// # Safety + /// + /// The window's pages are host memory of this process that stays mapped until the placement + /// is freed (`HostMemory::new`), and the chunks the source returns hold exactly those pages + /// (`HostMemory::with_dma_buf`). + pub(super) unsafe fn import_from_source( + &self, + call: &'static str, + importer: &Importer, + pointer: NonNull, + length: u64, + window: &ImportWindow, + source: DmaBufSource, + class: MemoryClass, + ) -> Result<(HostBuffer, Placement), Error> { + if !self.imports_dma_buf_buffers(vk::BufferCreateFlags::empty()) { + return Err(not_importable()); + } + // The window starts `window.offset` bytes before the pointer, in the pages it touches. + let start = NonNull::new(pointer.as_ptr().wrapping_sub(window.offset as usize)) + .ok_or_else(not_importable)?; + let granule = match self.sparse_granule(importer) { + Some(granule) if granule < window.size => granule, + _ => window.size, + }; + let request = DmaBufRequest { + start, + length: window.size, + granule, + }; + let chunks = source(request).map_err(|_| not_importable())?; + if !answers(&chunks, &request, importer.page) { + return Err(invalid(call, Problem::DmaBuf)); + } + let mut pages = DmaBufPages::new(self, source, request); + // SAFETY: the caller's. + let (buffer, memory, type_index) = + unsafe { self.chunks_buffer(importer, chunks, &mut pages, length, window, class) }?; + let counts = &self.shared().counts; + counts.dma_buf_imported(pages.memories.len()); + if pages.bound.is_some() { + counts.dma_buf_sparse_buffer_made(); + } + let placement = Placement::dma_buf(Arc::new(pages), memory, type_index, window.size, start); + Ok((buffer, placement)) + } + + /// The `VkBuffer` of a no-copy buffer of `length` bytes over `window`'s pages from their + /// first byte, its bytes `window.offset` bytes into it whatever the chunks, made for + /// dma-bufs, each of `chunks` imported (noted in `pages`) as memory of `class` and bound at + /// its offset from the window's start: one chunk by `vkBindBufferMemory` to a plain buffer, + /// several by a sparse binding of a `SPARSE_BINDING` one (`Device::bind_sparse_buffer`, noted + /// in `pages`). The buffer, its one import (`VK_NULL_HANDLE` for several) and the first + /// import's type. Refused, the buffer released, where the bytes padded to 16 run past the + /// chunks, the buffer's memory does not fit them or its alignment misses their boundaries, a + /// chunk's types take none of the class's the buffer takes, the driver refuses a chunk, or + /// the binding fails. + /// + /// # Safety + /// + /// As [`Device::import_from_source`]'s; `chunks` meet [`chunks_cover`]. + unsafe fn chunks_buffer( + &self, + importer: &Importer, + chunks: Vec, + pages: &mut DmaBufPages, + length: u64, + window: &ImportWindow, + class: MemoryClass, + ) -> Result<(HostBuffer, vk::DeviceMemory, u32), Error> { + let shared = self.shared(); + let raw_device = shared.vk(); + let lengths: Vec = chunks.iter().map(|chunk| chunk.length).collect(); + let size: u64 = lengths.iter().sum(); + // A range the binding layer pads to 16 bytes from the bytes stays inside the buffer, as + // a pointer's import holds it (`based_size`). + if based_size(window.offset, length).is_none_or(|padded| padded > size) { + return Err(not_importable()); + } + let sparse = lengths.len() > 1; + let flags = match sparse { + true => vk::BufferCreateFlags::SPARSE_BINDING, + false => vk::BufferCreateFlags::empty(), + }; + let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(DMA_BUF); + let info = shared.sharing().buffer( + vk::BufferCreateInfo::default() + .flags(flags) + .size(size) + .usage(usage(shared.device_address)) + .push_next(&mut external), + ); + // SAFETY: the device is live and `info` and its chain valid; a sparse one has + // `sparseBinding` (`Device::sparse_granule`). + 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) }; + let bound = (|| { + let alignment = requirements.alignment.max(1); + let fits = match sparse { + // Each chunk binds whole at its offset, which the alignment must divide, as it + // must divide each chunk's length. + true => lengths + .iter() + .all(|length| length.is_multiple_of(alignment)), + false => requirements.size <= size, + }; + if !fits { + return Err(not_importable()); + } + let memories = self.import_chunks(importer, chunks, pages, &requirements, class)?; + if !sparse { + // SAFETY: the buffer is unbound, made for dma-bufs; the memory is of a type it + // takes and holds its requirements from 0. + unsafe { raw_device.bind_buffer_memory(raw, memories[0].0, 0) }.map_err(vulkan)?; + return Ok(memories[0]); + } + let mut offset = 0; + let binds: Vec = (memories.iter().zip(&lengths)) + .map(|(&(memory, _), &length)| { + let bind = vk::SparseMemoryBind::default() + .resource_offset(offset) + .size(length) + .memory(memory) + .memory_offset(0); + offset += length; + bind + }) + .collect(); + pages.bound = Some(self.bind_sparse_buffer(raw, &binds)?); + Ok((vk::DeviceMemory::null(), memories[0].1)) + })(); + match bound { + // The bytes lie `window.offset` bytes into the buffer, which is bound from the + // window's first byte; it holds the pages, and its padding past them is no one's. + Ok((memory, type_index)) => { + let buffer = HostBuffer { + raw, + base: window.offset, + size: window.size, + requirements, + }; + Ok((buffer, memory, type_index)) + } + Err(error) => { + // SAFETY: no command uses the buffer; a failed binding left nothing pending. + unsafe { release::object(raw_device, raw) }; + Err(error) + } + } + } + + /// Each of `chunks` imported as memory of `class` of a type both it and a buffer of + /// `requirements` take, in order, noted in `pages` (which frees them), with its type. + /// Refused (`Unsupported`, `HostMemory`) where a chunk's types take none of the class's the + /// buffer takes, or the driver refuses it; the descriptors not yet imported are closed then. + fn import_chunks( + &self, + importer: &Importer, + chunks: Vec, + pages: &mut DmaBufPages, + requirements: &vk::MemoryRequirements, + class: MemoryClass, + ) -> Result, Error> { + let shared = self.shared(); + let raw_device = shared.vk(); + let mut imported = Vec::with_capacity(chunks.len()); + for DmaBufChunk { fd, length } in chunks { + // SAFETY: the importer is this device's, and the descriptor a dma-buf. + let types = unsafe { importer.dma_buf_types(raw_device, fd.as_fd()) } + .map_err(import_refused)?; + let allowed = types & requirements.memory_type_bits; + let (memory, type_index) = lock(&shared.memory) + .import_dma_buf(raw_device, fd, length, (allowed, class), None) + .map_err(|failure| match failure { + ImportFailure::NoMemoryType => not_importable(), + ImportFailure::Vulkan(error) => import_refused(error), + })?; + pages.memories.push(memory); + imported.push((memory, type_index)); + } + Ok(imported) + } + + /// The granule a dma-buf source's chunks split at, where the device assembles a buffer of + /// several: it has `sparseBinding`, its queue family binds sparse memory, and it imports + /// dma-bufs for a sparse buffer without a dedicated allocation; then the alignment of such a + /// buffer (of the host page), rounded up to the host page. `None` elsewhere. Asked of the + /// device once ([`Importer::sparse_granule`]). + fn sparse_granule(&self, importer: &Importer) -> Option { + *importer.sparse_granule.get_or_init(|| { + let shared = self.shared(); + let flags = vk::BufferCreateFlags::SPARSE_BINDING; + if !shared.sparse.binds() || !self.imports_dma_buf_buffers(flags) { + return None; + } + let raw_device = shared.vk(); + let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(DMA_BUF); + let info = shared.sharing().buffer( + vk::BufferCreateInfo::default() + .flags(flags) + .size(importer.page) + .usage(usage(shared.device_address)) + .push_next(&mut external), + ); + // SAFETY: the device is live, has `sparseBinding`, and `info` and its chain are valid. + let raw = unsafe { raw_device.create_buffer(&info, None) }.ok()?; + shared.counts.buffer_made(info.usage); + // SAFETY: `raw` is a live buffer of this device. + let alignment = unsafe { raw_device.get_buffer_memory_requirements(raw) }.alignment; + // SAFETY: the buffer is unused. + unsafe { release::object(raw_device, raw) }; + alignment + .max(1) + .checked_next_multiple_of(importer.page) + .filter(|granule| granule.is_multiple_of(alignment.max(1))) + }) + } + + /// Whether the device imports a dma-buf for a no-copy buffer's `VkBuffer` made with `flags` + /// without a dedicated allocation (`vkGetPhysicalDeviceExternalBufferProperties`), as it must + /// import host allocations for one (`Importer::new`). + fn imports_dma_buf_buffers(&self, flags: vk::BufferCreateFlags) -> bool { + let shared = self.shared(); + let info = vk::PhysicalDeviceExternalBufferInfo::default() + .flags(flags) + .usage(usage(shared.device_address)) + .handle_type(DMA_BUF); + let mut external = vk::ExternalBufferProperties::default(); + // SAFETY: the physical device is the instance's; the query is core in Vulkan 1.1. + unsafe { + shared + .instance + .raw + .get_physical_device_external_buffer_properties( + shared.physical, + &info, + &mut external, + ) + }; + let features = external.external_memory_properties.external_memory_features; + features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE) + && !features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY) + } +} + +/// `DRM_FORMAT_MOD_LINEAR` of Linux's `drm_fourcc.h`: one plane of rows one after another, each +/// the plane's pitch from the last. +const DRM_FORMAT_MOD_LINEAR: u64 = 0; + +/// Where a texture's texels lie in dma-buf pages, for its image over them +/// ([`Device::dma_buf_image`]). +pub(super) struct DmaBufTexels<'a> { + /// The imports of the pages (a no-copy buffer's or heap's), with the caller's source. + pub(super) pages: &'a DmaBufPages, + /// Their memory type, which the image's import takes too. + pub(super) type_index: u32, + /// The host address of the texels' first byte. + pub(super) at: u64, + /// The bytes from a row's first texel to the next row's. + pub(super) row_pitch: u64, + /// The bytes from a slice's first texel to the next slice's, for a plan of several layers. + pub(super) slice_pitch: u64, +} + +/// A texture's image over dma-buf pages, made and bound ([`Device::dma_buf_image`]): its +/// `VkImage`, which the caller destroys, and the import of its pages, which it drops after. +pub(super) struct DmaBufImage { + pub(super) raw: vk::Image, + pub(super) import: Arc, +} + +/// The layout the driver gives a `DRM_FORMAT_MOD_LINEAR` image of its own choosing +/// ([`Device::dma_buf_natural_layout`]): its plane's row and array pitches, and its memory's +/// bytes and alignment, from the plane's first byte. +pub(super) struct NaturalLayout { + pub(super) row_pitch: u64, + pub(super) slice_pitch: u64, + pub(super) size: u64, + pub(super) alignment: u64, +} + +/// The one memory plane of an image of `DRM_FORMAT_MOD_LINEAR`, whose layout Vulkan reports +/// (`VUID-vkGetImageSubresourceLayout-tiling-09433`). +fn memory_plane_0() -> vk::ImageSubresource { + vk::ImageSubresource { + aspect_mask: vk::ImageAspectFlags::MEMORY_PLANE_0_EXT, + mip_level: 0, + array_layer: 0, + } +} + +/// An image over dma-buf pages made and not yet bound: its requirements, and the request for +/// its pages. +struct Unbound { + raw: vk::Image, + requirements: vk::MemoryRequirements, + request: DmaBufRequest, +} + +impl Device { + /// The image of the first of `plans` the device makes one of (a texture's plans, each viewed + /// as `facts` says), and its index, over `texels`, where the texels lie in the caller's + /// dma-buf pages: a `DRM_FORMAT_MOD_LINEAR` image + /// (`VK_EXT_image_drm_format_modifier`) whose one plane starts at the texels' offset in their + /// first page, rows `row_pitch` apart (slices `slice_pitch`), made for dma-bufs, and bound to + /// a dedicated import (`VkMemoryDedicatedAllocateInfo`) of the one dma-buf the caller's source + /// makes of exactly the pages its memory requirements cover (`DmaBufRequest { granule: + /// length }`), of the pages' imports' memory type; counted (`WorkCounts::dma_buf_images`). It + /// starts `UNDEFINED`, as Vulkan makes an image of external memory, for its first move to + /// acquire from `VK_QUEUE_FAMILY_FOREIGN_EXT` (`FirstMove::acquired`). + /// + /// Why not, for the notice of the path taken instead (`shadowed-texture`), where the device + /// makes none: it does not enable the extensions; the plan has several levels, depth or + /// samples, or a mutable format with no list of its views; the modifier's tiling lacks a + /// feature the plan's optimal tiling has for its usage; the format query refuses such an + /// image, or the plan passes its limits; the driver refuses the plane layout or lays it out + /// otherwise; the image's memory runs past the pages or takes no memory of their type; the + /// source fails or answers against its contract; the driver refuses the import. The reason is + /// the last plan's; everything made is released then. The source is called at most once, for + /// the first plan the device makes an image of before asking it, with no lock of the + /// runtime's held (the caller holds none). + pub(super) fn dma_buf_image( + &self, + plans: &[&ImagePlan], + facts: &ImageFacts<'_>, + texels: &DmaBufTexels<'_>, + ) -> Result, Error> { + let mut why = "no plan".to_owned(); + for (index, plan) in plans.iter().enumerate() { + match self.dma_buf_image_unbound(plan, facts, texels)? { + Ok(unbound) => { + let made = self.bind_dma_buf_image(unbound, texels)?; + return Ok(made.map(|image| (index, image))); + } + Err(reason) => why = reason, + } + } + Ok(Err(why)) + } + + /// The queue family the first move of an image over dma-buf pages acquires it for: the + /// device's one family, or `VK_QUEUE_FAMILY_IGNORED` where its images are concurrent among + /// several (`sharing.rs`), as Vulkan has an acquire of such an image name it. + pub(super) fn foreign_acquirer(&self) -> u32 { + match &self.shared().queue_families[..] { + [family] => *family, + _ => vk::QUEUE_FAMILY_IGNORED, + } + } + + /// [`Device::dma_buf_image`]'s image made and checked, unbound, with the request for its + /// pages; why not where the device makes none before the source is asked. + fn dma_buf_image_unbound( + &self, + plan: &ImagePlan, + facts: &ImageFacts<'_>, + texels: &DmaBufTexels<'_>, + ) -> Result, Error> { + let shared = self.shared(); + let raw_device = shared.vk(); + let (page, view_formats) = match self.dma_buf_image_checks(plan, facts)? { + Ok(checked) => checked, + Err(why) => return Ok(Err(why)), + }; + let offset = texels.at % page; + let array_pitch = if plan.layers > 1 { + texels.slice_pitch + } else { + 0 + }; + let planes = [vk::SubresourceLayout { + offset, + size: 0, + row_pitch: texels.row_pitch, + array_pitch, + depth_pitch: 0, + }]; + let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default() + .drm_format_modifier(DRM_FORMAT_MOD_LINEAR) + .plane_layouts(&planes); + let raw = match self.drm_linear_image(plan, &view_formats, &mut explicit)? { + Ok(raw) => raw, + Err(error) => { + return Ok(Err(format!( + "the driver refuses a DRM_FORMAT_MOD_LINEAR plane at offset {offset} of its \ + first page with rows {} bytes apart ({error:?})", + texels.row_pitch + ))) + } + }; + let refuse = |why: String| { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { release::object(raw_device, raw) }; + Ok(Err(why)) + }; + // Bound to a dedicated import, whether or not the driver asks one. + // SAFETY: `raw` is a live image of this device. + let requirements = unsafe { raw_device.get_image_memory_requirements(raw) }; + // SAFETY: `raw` is a live image of a DRM format modifier's tiling, whose one memory plane + // is plane 0 (`VUID-vkGetImageSubresourceLayout-tiling-09433`). + let report = unsafe { raw_device.get_image_subresource_layout(raw, memory_plane_0()) }; + if report.offset != offset + || report.row_pitch != texels.row_pitch + || (plan.layers > 1 && report.array_pitch != array_pitch) + { + return refuse(format!( + "the driver lays the plane out at offset {}, rows {} and slices {} bytes apart, \ + where the texels lie at offset {offset}, rows {} and slices {array_pitch} apart", + report.offset, report.row_pitch, report.array_pitch, texels.row_pitch + )); + } + // The pages from the texels' first, through the image's memory. + let first = texels.at - offset; + let length = match requirements.size.checked_next_multiple_of(page) { + Some(length) if texels.pages.holds(first, length) => length, + _ => { + return refuse(format!( + "its image's memory, {} bytes from the first page of its texels, runs past \ + the pages the buffer's range touches", + requirements.size + )) + } + }; + if requirements.memory_type_bits & (1 << texels.type_index) == 0 { + return refuse(format!( + "its image takes none of the pages' memory type {}", + texels.type_index + )); + } + let Some(start) = NonNull::new(first as *mut u8) else { + return refuse("its texels lie in the null page".to_owned()); + }; + Ok(Ok(Unbound { + raw, + requirements, + request: DmaBufRequest { + start, + length, + granule: length, + }, + })) + } + + /// `unbound`'s image bound to a dedicated import of the dma-buf the caller's source makes of + /// its pages, of `texels`' memory type, and counted; why not, the image released, where the + /// source fails or answers against its contract or the driver refuses the import or binding. + fn bind_dma_buf_image( + &self, + unbound: Unbound, + texels: &DmaBufTexels<'_>, + ) -> Result, Error> { + let Unbound { + raw, + requirements, + request, + } = unbound; + let shared = self.shared(); + let raw_device = shared.vk(); + let refuse = |why: String| { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { release::object(raw_device, raw) }; + Ok(Err(why)) + }; + let (Ok(importer), Some(source)) = (shared.host_import.as_ref(), &texels.pages.source) + else { + return refuse("the pages keep no source of dma-bufs".to_owned()); + }; + // The source is the program's code, called with no lock of the runtime's held. + let chunks = match source(request) { + Ok(chunks) => chunks, + Err(error) => { + return refuse(format!( + "the caller's source made no dma-buf of its {} bytes of pages: {error}", + request.length + )) + } + }; + // A request whose granule is its length takes one chunk (`chunks_cover`). + let answered = answers(&chunks, &request, importer.page); + let (true, Ok([chunk])) = (answered, <[DmaBufChunk; 1]>::try_from(chunks)) else { + return refuse( + "the caller's source answered other than one dma-buf of the pages asked".to_owned(), + ); + }; + // SAFETY: the importer is this device's, and the descriptor a dma-buf. + let types = match unsafe { importer.dma_buf_types(raw_device, chunk.fd.as_fd()) } { + Ok(types) => types, + Err(error) => return refuse(format!("the driver refuses the dma-buf ({error:?})")), + }; + // The pages' type (host-visible and coherent, as every class of theirs is), dedicated to + // the image at its requirements' size exactly + // (`VUID-VkMemoryDedicatedAllocateInfo-image-01433`), within the dma-buf's pages. + let allowed = (types & (1 << texels.type_index), MemoryClass::Shared); + let imported = lock(&shared.memory).import_dma_buf( + raw_device, + chunk.fd, + requirements.size, + allowed, + Some(raw), + ); + let memory = match imported { + Ok((memory, _)) => memory, + Err(ImportFailure::NoMemoryType) => { + return refuse(format!( + "the driver imports the dma-buf as none of the pages' memory type {}", + texels.type_index + )) + } + Err(ImportFailure::Vulkan(vk::Result::ERROR_DEVICE_LOST)) => { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { release::object(raw_device, raw) }; + return Err(Error::DeviceLost); + } + Err(ImportFailure::Vulkan(error)) => { + return refuse(format!("the driver refuses the import ({error:?})")) + } + }; + // SAFETY: the image is unbound; the memory is its dedicated allocation, of its size. + if let Err(error) = unsafe { raw_device.bind_image_memory(raw, memory, 0) } { + // SAFETY: nothing is bound to the memory, and no command uses it. + unsafe { release::object(raw_device, memory) }; + return refuse(format!("the driver refuses to bind the import ({error:?})")); + } + shared.counts.dma_buf_image_made(); + let mut import = DmaBufPages::new(self, Arc::clone(source), request); + import.memories.push(memory); + Ok(Ok(DmaBufImage { + raw, + import: Arc::new(import), + })) + } + + /// What a `DRM_FORMAT_MOD_LINEAR` image of `plan` for dma-bufs takes before its plane is laid + /// out: the host's page, which its import starts at, and the formats it lists for its views; + /// why not where the device makes none (the reasons of [`Device::dma_buf_image`] before the + /// plane's). + fn dma_buf_image_checks( + &self, + plan: &ImagePlan, + facts: &ImageFacts<'_>, + ) -> Result), String>, Error> { + let page = match self.shared().host_import.as_ref() { + Ok(importer) if importer.makes_dma_buf_images() => importer.page, + _ => { + return Ok(Err( + "the device enables no VK_EXT_image_drm_format_modifier and \ + VK_EXT_queue_family_foreign beside its dma-buf imports" + .to_owned(), + )) + } + }; + if plan.levels != 1 || plan.extent[2] != 1 || plan.samples != SampleCountFlags::COUNT_1 { + return Ok(Err(format!( + "its image has {} levels, a depth of {} and {:?} samples, where a \ + DRM_FORMAT_MOD_LINEAR image over the pages has one of each", + plan.levels, plan.extent[2], plan.samples + ))); + } + // A DRM format modifier's mutable image lists its views' formats + // (`VUID-VkImageCreateInfo-tiling-02353`): a plan whose views take any compatible format + // lists each the runtime views a texture as (`linear_plan::viewed_formats`), its own + // format first. + let mutable = plan.flags.contains(ImageCreateFlags::MUTABLE_FORMAT); + let formats: Vec = match mutable && plan.view_formats.is_empty() { + true => std::iter::once(plan.format) + .chain(viewed_formats(plan, facts)) + .collect(), + false => plan.view_formats.clone(), + }; + if let Some(LinearLack { format, features }) = + tiling_lack(plan, facts, |format| self.modifier_features(format)) + { + return Ok(Err(format!( + "the DRM_FORMAT_MOD_LINEAR tiling of {format:?} lacks {features:?}, which its \ + optimal tiling has for the texture's usage" + ))); + } + let view_formats: Vec = formats.iter().map(|&format| format.into()).collect(); + let limits = match self.dma_buf_image_limits(plan, &view_formats) { + Ok(limits) => limits, + Err(why) => return Ok(Err(why)), + }; + if let Err(need) = check_linear_limits(plan, &limits) { + return Ok(Err(format!( + "its image passes the device's limits for a DRM_FORMAT_MOD_LINEAR image of \ + {:?} for dma-bufs: {need:?}", + plan.format + ))); + } + Ok(Ok((page, view_formats))) + } + + /// The layout the driver gives a `DRM_FORMAT_MOD_LINEAR` image of `plan` for dma-bufs where it + /// chooses it (`VkImageDrmFormatModifierListCreateInfoEXT`), its plane at offset 0: what a + /// heap's texture over dma-buf pages lays its texels out as (`texture/heap.rs`), as the + /// driver's linear image lays out one over pages imported by their pointer. Why not where the + /// device makes none (the reasons of [`Device::dma_buf_image`] before the plane's, or the + /// driver refuses such an image). + pub(super) fn dma_buf_natural_layout( + &self, + plan: &ImagePlan, + facts: &ImageFacts<'_>, + ) -> Result, Error> { + let raw_device = self.shared().vk(); + let view_formats = match self.dma_buf_image_checks(plan, facts)? { + Ok((_, view_formats)) => view_formats, + Err(why) => return Ok(Err(why)), + }; + let modifiers = [DRM_FORMAT_MOD_LINEAR]; + let mut chosen = + vk::ImageDrmFormatModifierListCreateInfoEXT::default().drm_format_modifiers(&modifiers); + let raw = match self.drm_linear_image(plan, &view_formats, &mut chosen)? { + Ok(raw) => raw, + Err(error) => { + return Ok(Err(format!( + "the driver refuses a DRM_FORMAT_MOD_LINEAR image of its own layout \ + ({error:?})" + ))) + } + }; + // SAFETY: `raw` is a live image of a DRM format modifier's tiling, whose one memory plane + // is plane 0; it is destroyed right after the queries, with no memory bound. + let (report, requirements) = unsafe { + let report = raw_device.get_image_subresource_layout(raw, memory_plane_0()); + let requirements = raw_device.get_image_memory_requirements(raw); + release::object(raw_device, raw); + (report, requirements) + }; + Ok(Ok(NaturalLayout { + row_pitch: report.row_pitch, + slice_pitch: report.array_pitch, + size: requirements.size, + alignment: requirements.alignment, + })) + } + + /// A `DRM_FORMAT_MOD_LINEAR` image of `plan` for dma-bufs, viewed as `view_formats`, its + /// plane laid out as `modifier` says (an explicit layout, or the modifier listed for the driver + /// to lay out), made `UNDEFINED` as Vulkan makes an image of external memory; or the driver's + /// refusal of it. + fn drm_linear_image( + &self, + plan: &ImagePlan, + view_formats: &[vk::Format], + modifier: &mut impl vk::ExtendsImageCreateInfo, + ) -> Result, Error> { + let shared = self.shared(); + let mut external = vk::ExternalMemoryImageCreateInfo::default().handle_types(DMA_BUF); + let mut list = vk::ImageFormatListCreateInfo::default(); + let info = plan + .create_info(shared.sharing(), view_formats, &mut list) + .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) + .initial_layout(vk::ImageLayout::UNDEFINED) + .push_next(&mut external) + .push_next(modifier); + // SAFETY: the device is live and enables the extension; `info` and its chain are valid + // and within the device's limits for such an image (`dma_buf_image_limits`), its one + // plane the modifier's one (`modifier_features`), made `UNDEFINED` for external memory. + unsafe { crate::creation::image_or_refusal(shared.vk(), &info) } + } + + /// The features of `format`'s `DRM_FORMAT_MOD_LINEAR` tiling where the device lists that + /// modifier for it with one plane; none elsewhere. The 64-bit list + /// (`VkDrmFormatModifierPropertiesList2EXT`) where the device has `format_feature_flags2`, as + /// the optimal tiling's features come from it: the 32-bit list cannot carry the storage bits + /// above bit 31 (`STORAGE_READ_WITHOUT_FORMAT` and `STORAGE_WRITE_WITHOUT_FORMAT`), so a + /// writable texture would always lack them. + fn modifier_features(&self, format: Format) -> FormatFeatureFlags2 { + let shared = self.shared(); + let format: vk::Format = format.into(); + let query = |list: &mut dyn vk::ExtendsFormatProperties2| { + let mut properties = vk::FormatProperties2::default().push_next(list); + // SAFETY: the physical device is the instance's, whose device enables the extension; + // a list without entries asks the count alone, and one with entries holds as many as + // its count for the driver to write. + unsafe { + shared.instance.raw.get_physical_device_format_properties2( + shared.physical, + format, + &mut properties, + ) + } + }; + let linear = |modifier: u64, planes: u32| modifier == DRM_FORMAT_MOD_LINEAR && planes == 1; + let features = if self.properties().description.has_format_feature_flags2() { + let mut list = vk::DrmFormatModifierPropertiesList2EXT::default(); + query(&mut list); + let count = list.drm_format_modifier_count as usize; + let mut modifiers = vec![vk::DrmFormatModifierProperties2EXT::default(); count]; + let mut list = vk::DrmFormatModifierPropertiesList2EXT::default() + .drm_format_modifier_properties(&mut modifiers); + query(&mut list); + let written = list.drm_format_modifier_count as usize; + modifiers.iter().take(written).find_map(|modifier| { + linear( + modifier.drm_format_modifier, + modifier.drm_format_modifier_plane_count, + ) + .then_some(modifier.drm_format_modifier_tiling_features.as_raw()) + }) + } else { + let mut list = vk::DrmFormatModifierPropertiesListEXT::default(); + query(&mut list); + let count = list.drm_format_modifier_count as usize; + let mut modifiers = vec![vk::DrmFormatModifierPropertiesEXT::default(); count]; + let mut list = vk::DrmFormatModifierPropertiesListEXT::default() + .drm_format_modifier_properties(&mut modifiers); + query(&mut list); + let written = list.drm_format_modifier_count as usize; + modifiers.iter().take(written).find_map(|modifier| { + linear( + modifier.drm_format_modifier, + modifier.drm_format_modifier_plane_count, + ) + .then_some(u64::from( + modifier.drm_format_modifier_tiling_features.as_raw(), + )) + }) + }; + features.map_or(FormatFeatureFlags2::empty(), FormatFeatureFlags2::from_raw) + } + + /// The device's limits for a `DRM_FORMAT_MOD_LINEAR` image of `plan` for dma-bufs, viewed as + /// `view_formats`; why not where its format query refuses such an image or it imports no + /// dma-buf for one. + fn dma_buf_image_limits( + &self, + plan: &ImagePlan, + view_formats: &[vk::Format], + ) -> Result { + let shared = self.shared(); + let families = &shared.queue_families; + let mut modifier = vk::PhysicalDeviceImageDrmFormatModifierInfoEXT::default() + .drm_format_modifier(DRM_FORMAT_MOD_LINEAR); + modifier = match families.len() > 1 { + true => modifier + .sharing_mode(vk::SharingMode::CONCURRENT) + .queue_family_indices(families), + false => modifier.sharing_mode(vk::SharingMode::EXCLUSIVE), + }; + let mut external = + vk::PhysicalDeviceExternalImageFormatInfo::default().handle_type(DMA_BUF); + let mut list = vk::ImageFormatListCreateInfo::default().view_formats(view_formats); + let mut query = vk::PhysicalDeviceImageFormatInfo2::default() + .format(plan.format.into()) + .ty(plan.image_type.into()) + .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) + .usage(plan.usage.into()) + .flags(plan.flags.into()) + .push_next(&mut external) + .push_next(&mut modifier); + if !view_formats.is_empty() { + query = query.push_next(&mut list); + } + let mut imported = vk::ExternalImageFormatProperties::default(); + let mut properties = vk::ImageFormatProperties2::default().push_next(&mut imported); + // SAFETY: the physical device is the instance's, whose device enables the extensions; + // `query` and `properties` and their chains live for the call. + let queried = unsafe { + shared + .instance + .raw + .get_physical_device_image_format_properties2( + shared.physical, + &query, + &mut properties, + ) + }; + if let Err(error) = queried { + return Err(format!( + "the device's image format query reports no DRM_FORMAT_MOD_LINEAR image of {:?}, \ + usage {:?}, flags {:?} for dma-bufs ({error:?})", + plan.format, plan.usage, plan.flags + )); + } + let limits = properties.image_format_properties; + let features = imported.external_memory_properties.external_memory_features; + if !features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE) { + return Err(format!( + "it imports no dma-buf for a DRM_FORMAT_MOD_LINEAR image of {:?}", + plan.format + )); + } + Ok(limits) + } +} diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index e313dc780..5dd93ed95 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -499,6 +499,11 @@ pub enum Problem { AlreadyCommitted, /// An object made by another device. ForeignObject, + /// Dma-bufs a `DmaBufSource` returned (a runtime extension: Metal has none, + /// `HostMemory::with_dma_buf`) that break its contract: chunks that do not cover the pages + /// asked for, split off the granule, or of lengths off the host page, and a descriptor that + /// is no dma-buf or holds fewer bytes than its chunk. + DmaBuf, /// An image the caller made that cannot be wrapped as a texture of the descriptor /// (`new_texture_with_vk_image`). WrappedImage(WrappedImageProblem), @@ -1294,7 +1299,15 @@ pub enum RuntimeGap { OverlappingTextureCopies, /// `Buffer::rebind_bytes_no_copy` of a no-copy buffer with a live texture over its bytes, /// given memory at another offset in its page than the old: the texture's copies and texel - /// views are planned at the bytes' offset in their `VkBuffer` (`rebind.rs`). + /// views are planned at the bytes' offset in their `VkBuffer` (`rebind.rs`). Also a rebind + /// of a no-copy buffer or heap with a texture whose image is bound to its bytes, where the + /// device makes no such image over the new memory: over memory it imports by its pointer, one + /// that takes the import's type and lies where the texture's texels do, its rows (and slices) + /// as far apart as the old image's, and never for a heap's texture whose image lay over + /// dma-bufs, whose rows the driver's `DRM_FORMAT_MOD_LINEAR` layout spaces; over memory it + /// imports as dma-bufs (`HostMemory::with_dma_buf`), an image of `DRM_FORMAT_MOD_LINEAR` over + /// a dma-buf of the texture's own new pages, which needs `VK_EXT_image_drm_format_modifier` + /// and `VK_EXT_queue_family_foreign`, a layout the driver takes and the source's dma-buf. RebindTextures, /// A PVRTC texture's blocks in a Metal block order the runtime does not lay out: /// `replaceRegion` and `getBytes` of a region other than a whole level, which Metal's API diff --git a/crates/metal2vulkan-runtime/src/heap.rs b/crates/metal2vulkan-runtime/src/heap.rs index ac5512b33..fd3ac60af 100644 --- a/crates/metal2vulkan-runtime/src/heap.rs +++ b/crates/metal2vulkan-runtime/src/heap.rs @@ -67,7 +67,6 @@ use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMo use super::Device; use metal2vulkan::device::AllocationLimits; use std::collections::HashMap; -use std::ptr::NonNull; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; @@ -482,24 +481,27 @@ impl Device { } /// A heap over the caller's host memory (a runtime extension, the heap twin of - /// [`Device::new_buffer_with_bytes_no_copy`]): an automatic or placement heap of the - /// descriptor's size rounded up to 16 KiB whose bytes are the caller's, from `bytes`. Its - /// buffers and textures alias at their offsets as in any heap of its type, and the CPU's - /// writes through `bytes` are what its resources' commands read. `deallocator` runs once, - /// with `bytes` and the heap's size, when the heap's last reference goes (its resources hold - /// it): on a runtime thread when that is a command buffer completing. A refused call never - /// runs it. `keep_alive` ([`KeepAlive`]) is dropped once the device's import of the memory is - /// freed: with one, `deallocator` runs at the heap's release, though a command buffer submitted - /// before a texture placed in the heap was released may hold the import until it completes; - /// with none, `deallocator` waits for the import (`host-deallocator-delayed`). + /// [`Device::new_buffer_with_bytes_no_copy`]), its pointer wrapped in `memory` + /// ([`HostMemory`]): an automatic or placement heap of the descriptor's size rounded up to 16 + /// KiB whose bytes are the caller's, from `memory.pointer()`. Its buffers and textures alias at + /// their offsets as in any heap of its type, and the CPU's writes through the pointer are what + /// its resources' commands read. `deallocator` runs once, with the pointer and the heap's size, + /// when the heap's last reference goes (its resources hold it): on a runtime thread when that + /// is a command buffer completing. A refused call never runs it. `keep_alive` ([`KeepAlive`]) + /// is dropped once the device's import of the memory is freed: with one, `deallocator` runs at + /// the heap's release, though a command buffer submitted before a texture placed in the heap + /// was released may hold the import until it completes; with none, `deallocator` waits for the + /// import (`host-deallocator-delayed`). /// - /// The memory is imported here, as a no-copy buffer's is (`host_memory.rs`). A buffer - /// placed in the heap is its bytes; a texture is an image bound to them where the device - /// binds such an image to imported host memory (its optimal image, else a linear one), else - /// an image of its own whose texels the encoders copy from the heap's bytes and back, laid - /// out by level and layer from the texture's offset, which the device announces once - /// (`shadowed-texture`; `texture/heap.rs`). Its purgeable state answers as a no-copy - /// buffer's: non-volatile, and emptying it keeps the caller's bytes. + /// The memory is imported here, as a no-copy buffer's is (`host_memory.rs`): by its pointer, or + /// where the device refuses that and `memory` carries a dma-buf source + /// ([`HostMemory::with_dma_buf`]), by the dma-bufs it makes of the pages. A buffer placed in + /// the heap is its bytes; a texture is an image bound to them where the device binds such an + /// image to imported host memory (its optimal image, else a linear one; over dma-bufs, an + /// image over a dma-buf of its own pages), else an image of its own whose texels the encoders copy from + /// the heap's bytes and back, laid out by level and layer from the texture's offset, which the + /// device announces once (`shadowed-texture`; `texture/heap.rs`). Its purgeable state answers + /// as a no-copy buffer's: non-volatile, and emptying it keeps the caller's bytes. /// /// Refused: a size of 0 (`Nil`, as [`Device::new_heap`] answers it); storage other than /// `Shared`, a sparse heap, an undefined option (`Invalid`); memory whose first byte is not a multiple of the import's unit @@ -512,10 +514,11 @@ impl Device { /// /// # Safety /// - /// The heap's [`size`](Heap::size) bytes at `bytes` meet [`HostMemory::new`]'s contract. + /// `memory` meets the contract of the [`HostMemory`] constructor that made it + /// ([`HostMemory::new`], [`HostMemory::with_dma_buf`]) for the heap's [`size`](Heap::size). pub unsafe fn new_heap_with_bytes_no_copy( &self, - bytes: NonNull, + memory: HostMemory, descriptor: &HeapDescriptor, deallocator: Option, keep_alive: Option, @@ -525,7 +528,7 @@ impl Device { keep_alive, }; // SAFETY: the caller's contract. - unsafe { self.no_copy_heap_with_token(bytes, descriptor, release, None) } + unsafe { self.no_copy_heap_with_token(memory, descriptor, release, None) } } /// [`Device::new_heap_with_bytes_no_copy`] with `token` (a runtime extension), dropped once @@ -537,7 +540,7 @@ impl Device { /// As [`Device::new_heap_with_bytes_no_copy`]'s. pub unsafe fn new_heap_with_bytes_no_copy_and_range_token( &self, - bytes: NonNull, + memory: HostMemory, descriptor: &HeapDescriptor, deallocator: Option, keep_alive: Option, @@ -548,7 +551,7 @@ impl Device { keep_alive, }; // SAFETY: the caller's contract. - unsafe { self.no_copy_heap_with_token(bytes, descriptor, release, Some(token)) } + unsafe { self.no_copy_heap_with_token(memory, descriptor, release, Some(token)) } } /// [`Device::new_heap_with_bytes_no_copy`], given back to `release`, the heap's own bytes @@ -559,7 +562,7 @@ impl Device { /// As [`Device::new_heap_with_bytes_no_copy`]'s. unsafe fn no_copy_heap_with_token( &self, - bytes: NonNull, + memory: HostMemory, descriptor: &HeapDescriptor, release: HostRelease, token: Option, @@ -578,7 +581,7 @@ impl Device { let bytes = unsafe { self.buffer_over_host_memory( CALL, - HostMemory::new(bytes), + memory, size, options, release, diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index d26974830..100a531c3 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -1,5 +1,6 @@ //! Buffers over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`), through -//! `VK_EXT_external_memory_host`. +//! `VK_EXT_external_memory_host`, or, where the device refuses the pointer, dma-buf memory of the +//! pages the caller imports (`VK_EXT_external_memory_dma_buf`, [`DmaBufSource`], `dma_buf.rs`). //! //! - **What Metal takes** (measured on an Apple M3 Max and an M4, plain and under API validation): //! any pointer and any length but 0; the buffer covers the whole host pages its range touches @@ -29,9 +30,16 @@ //! there the rule refuses a little more than the driver would. On macOS, MoltenVK hands the //! range to Metal, which reads read-only pages, so there is no check. //! - **What drivers answered**. Private anonymous memory was imported on every venue measured. RADV -//! refused shared memory (anonymous shared, or a mapping of a shared memory object) typed: Mesa -//! 26.2.4 answers `VK_ERROR_INVALID_EXTERNAL_HANDLE`, 26.0.8 `VK_ERROR_UNKNOWN`, and both are -//! refusals ([`import_refused`]). +//! refused shared memory typed: anonymous shared memory, and any mapping of a file, a shared +//! memory object or a `memfd` among them (QEMU's `memory-backend-memfd,share=on` guest RAM). It +//! imports a host pointer through amdgpu's userptr, which the kernel takes only over anonymous +//! pages. Mesa 26.2.4 answers `VK_ERROR_INVALID_EXTERNAL_HANDLE`, 26.0.8 `VK_ERROR_UNKNOWN`, and +//! both are refusals ([`import_refused`]). NVIDIA and lavapipe imported the same shared memory. +//! - **Dma-bufs of the pages** ([`HostMemory::with_dma_buf`]), the last resort before that +//! refusal: where the device refuses the pointer ([`refused`]: the import window, the buffer's +//! binding in it, the memory types, or the driver) and imports dma-bufs, the buffer is bound in +//! imports of the source's dma-bufs of the pages instead (`dma_buf.rs`). Every import the device +//! takes by its pointer is made exactly as before, with no call more. //! - **When**. The pages are imported when the buffer is made, on every platform, as Metal wires //! them then: the GPU uses the pages mapped at the pointer when the buffer was made, whatever is //! mapped there later, and memory the device cannot import is refused by the call that makes the @@ -58,6 +66,8 @@ //! contract keeps mapped: its deallocator runs at its release either way. use super::device::lock; +#[cfg(unix)] +use super::dma_buf::DmaBufSource; use super::error::{vulkan, Error}; use super::exit_guard; use super::loader_word::LoaderWord; @@ -68,17 +78,41 @@ use std::ffi::c_void; use std::ptr::NonNull; use std::sync::Mutex; -/// Host memory a buffer wraps without a copy: a pointer whose bytes the caller vouches for (the -/// `pointer` of `newBufferWithBytesNoCopy:length:options:deallocator:`). -#[derive(Debug)] -pub struct HostMemory(NonNull); +/// Host memory a buffer or heap wraps without a copy: a pointer whose bytes the caller vouches for +/// (the `pointer` of `newBufferWithBytesNoCopy:length:options:deallocator:`), and, as a runtime +/// extension, a source of dma-bufs of its pages for a device that refuses the pointer itself +/// ([`HostMemory::with_dma_buf`]). +pub struct HostMemory { + pointer: NonNull, + source: Option, +} -// SAFETY: a `HostMemory` is an address and the caller's guarantee for it (`HostMemory::new`); the -// runtime touches the bytes only as a buffer of them, under that guarantee. +/// What a [`HostMemory`] may carry besides its pointer: a [`DmaBufSource`] where the system has +/// file descriptors, nothing elsewhere. +#[cfg(unix)] +pub(super) type Source = DmaBufSource; + +/// What a [`HostMemory`] may carry besides its pointer: nothing on this system. +#[cfg(not(unix))] +pub(super) type Source = std::convert::Infallible; + +// SAFETY: a `HostMemory` is an address and the caller's guarantee for it (`HostMemory::new`), +// and a source that is `Send`; the runtime touches the bytes only as a buffer of them, under that +// guarantee. unsafe impl Send for HostMemory {} -// SAFETY: as above. +// SAFETY: as above; a shared `HostMemory` answers its pointer alone, and its source is reached +// only by value ([`HostMemory::into_parts`]). unsafe impl Sync for HostMemory {} +impl std::fmt::Debug for HostMemory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HostMemory") + .field("pointer", &self.pointer) + .field("dma_buf", &self.source.is_some()) + .finish() + } +} + impl HostMemory { /// The host memory at `pointer`, for a buffer of some length `length` made from it. /// @@ -101,14 +135,53 @@ impl HostMemory { /// (`Unsupported`, `HostMemory`), though Metal reads such pages: Linux drivers pin imported /// pages for writing, and one (ANV) imported a read-only page and then lost the device at the /// GPU's first read. Some drivers also refuse shared memory (RADV refused anonymous shared - /// memory and mappings of shared memory objects); private memory imports everywhere measured. + /// memory and mappings of shared memory objects, `memfd` mappings among them); private memory + /// imports everywhere measured. [`HostMemory::with_dma_buf`] imports such memory where the + /// device imports dma-bufs. pub unsafe fn new(pointer: NonNull) -> HostMemory { - HostMemory(pointer) + HostMemory { + pointer, + source: None, + } + } + + /// As [`HostMemory::new`], plus a source of dma-bufs of the pages for a device that refuses + /// the pointer (a runtime extension, [`DmaBufSource`]). The runtime first imports the pointer + /// exactly as [`HostMemory::new`]'s; only where the device refuses it (a driver refusal, or a + /// range its import alignment cannot cover) and enables `VK_EXT_external_memory_dma_buf`, it + /// imports the source's chunks instead: one chunk binds a plain buffer, several a sparse one. + /// A texture over such pages (over the buffer, placed in the heap, or a view of one) is an + /// image over a dma-buf of its own pages where the device lists + /// `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign`, else a shadow of the + /// bytes (announced `shadowed-texture`). Refused as [`HostMemory::new`]'s memory is + /// (`Unsupported`, `HostMemory`) where the device imports no chunk or the source fails; chunks + /// that break the source's contract are misuse (`Invalid`, `Problem::DmaBuf`). Measured: RADV + /// refuses the pointer of `memfd` and other shared mappings and imports `udmabuf`s of their + /// pages; NVIDIA and lavapipe import the pointer and never call the source. + /// + /// # Safety + /// + /// [`HostMemory::new`]'s contract for the bytes at `pointer`, holding while the chunks are + /// imported as while the pointer is; and the chunks `source` returns hold exactly the pages it + /// is asked for, in order (then padding, [`DmaBufRequest`](crate::DmaBufRequest)), the same + /// pieces of the same files for every request over the same pages, so that the GPU's bytes, + /// the buffer's and its textures', are the CPU's. + #[cfg(unix)] + pub unsafe fn with_dma_buf(pointer: NonNull, source: DmaBufSource) -> HostMemory { + HostMemory { + pointer, + source: Some(source), + } } /// The pointer. pub fn pointer(&self) -> NonNull { - self.0 + self.pointer + } + + /// The pointer, and the dma-buf source where the caller gave one. + pub(super) fn into_parts(self) -> (NonNull, Option) { + (self.pointer, self.source) } } @@ -172,7 +245,8 @@ pub(super) enum WindowRefusal { /// The import of `length` bytes at `pointer` on a host of `page`-byte pages and a device that /// imports at multiples of `alignment`: the range rounded out to the larger of the two. Refused -/// when the rounding would take pages the range does not touch. +/// when the rounding would take pages the range does not touch, so a window made is always the +/// pages the range touches, the one an `alignment` of 1 makes (a dma-buf's, which has none). pub(super) fn import_window( pointer: u64, length: u64, @@ -255,6 +329,13 @@ pub(super) fn not_importable() -> Error { Error::Unsupported(Unsupported::not_representable(Feature::HostMemory)) } +/// Whether `error` is the refusal of host memory this device cannot import exactly +/// ([`not_importable`]): the window, the buffer's binding in it, the memory types or the driver +/// refused the pointer, which a dma-buf of its pages may serve ([`DmaBufSource`]). +pub(super) fn refused(error: &Error) -> bool { + *error == not_importable() +} + /// The error of a failed import call (`vkGetMemoryHostPointerPropertiesEXT` or the allocation): a /// driver that refuses the memory is a device gap, anything else a Vulkan failure. Refusing /// drivers answer `VK_ERROR_INVALID_EXTERNAL_HANDLE`, but RADV of Mesa 26.0.8 answers @@ -427,6 +508,16 @@ pub(super) struct Importer { /// instance reports through `VK_EXT_debug_utils`: an image made of a Metal texture is named /// [`METAL_TEXTURE_IMAGE`] for the layers' messages. names: Option, + /// `vkGetMemoryFdPropertiesKHR`, where the device enables the dma-buf route (`dma_buf.rs`). + dma_buf: Option, + /// Whether the device also enables the route's image extensions (`create.rs`'s + /// `dma_buf_image_names`), for images of textures over dma-buf pages (`dma_buf.rs`). + dma_buf_images: bool, + /// The granule a dma-buf source's chunks split at, where the device assembles a buffer of + /// several (`dma_buf.rs`): the alignment of a sparse buffer made for dma-bufs. Asked once, + /// the first time a pointer is refused and a source called; `None` where the device makes no + /// such buffer. + pub(super) sparse_granule: std::sync::OnceLock>, } /// The debug name of an image the runtime made of a Metal texture over an import's `MTLBuffer` @@ -445,7 +536,8 @@ impl Importer { /// # Safety /// /// `device` is a live device of `physical`, made from `instance` with `enabled` enabled, and - /// `loader_word` is its loader word. + /// `loader_word` is its loader word; made with the dma-buf route's extensions where `dma_buf`, + /// and its image extensions where `dma_buf_images` (`create.rs`). pub(super) unsafe fn new( instance: &ash::Instance, physical: vk::PhysicalDevice, @@ -455,6 +547,8 @@ impl Importer { loader_word: &LoaderWord, metal_objects: bool, debug_names: bool, + dma_buf: bool, + dma_buf_images: bool, ) -> Result { if !enabled .extensions @@ -499,15 +593,63 @@ impl Importer { let metal = metal_objects.then(|| ash::ext::metal_objects::DeviceFn::load(load)); let names = (metal_objects && debug_names).then(|| ash::ext::debug_utils::DeviceFn::load(load)); + let dma_buf = dma_buf.then(|| ash::khr::external_memory_fd::DeviceFn::load(load)); + let dma_buf_images = dma_buf.is_some() && dma_buf_images; Ok(Importer { functions, page, alignment, metal, names, + dma_buf, + dma_buf_images, + sparse_granule: std::sync::OnceLock::new(), }) } + /// Whether the device imports dma-bufs (`VK_EXT_external_memory_dma_buf`), which a no-copy + /// buffer's pages may come as where it refuses their pointer ([`DmaBufSource`]). + pub(super) fn imports_dma_bufs(&self) -> bool { + self.dma_buf.is_some() + } + + /// Whether the device makes images over dma-bufs of host pages (`dma_buf.rs`): it imports + /// dma-bufs and enables `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign`. + pub(super) fn makes_dma_buf_images(&self) -> bool { + self.dma_buf_images + } + + /// The memory types the dma-buf `fd` can be imported into (`vkGetMemoryFdPropertiesKHR`); + /// `ERROR_FEATURE_NOT_PRESENT` where the device imports no dma-bufs. + /// + /// # Safety + /// + /// `device` is the importer's device. + #[cfg(unix)] + pub(super) unsafe fn dma_buf_types( + &self, + device: &ash::Device, + fd: std::os::fd::BorrowedFd<'_>, + ) -> Result { + use std::os::fd::AsRawFd; + let functions = self + .dma_buf + .as_ref() + .ok_or(vk::Result::ERROR_FEATURE_NOT_PRESENT)?; + let mut properties = vk::MemoryFdPropertiesKHR::default(); + // SAFETY: the caller's contract; the function was loaded for this device, and the + // descriptor is open for the call (the query does not take it). + let result = unsafe { + (functions.get_memory_fd_properties_khr)( + device.handle(), + vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT, + fd.as_raw_fd(), + &mut properties, + ) + }; + result.result_with_success(properties.memory_type_bits) + } + /// Whether the device's imports are allocated for export of their `MTLBuffer` /// (`VK_EXT_metal_objects`). pub(super) fn exports_metal(&self) -> bool { diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 8eb94e39d..71ef2bdd7 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -66,6 +66,8 @@ mod depth_stencil_scratch; mod descriptor_arena; mod detach; mod device; +#[cfg(unix)] +mod dma_buf; mod draw_source; mod driver_defects; mod driver_facts; @@ -215,6 +217,8 @@ pub use device::{ DebugMessage, Device, DeviceHandles, DeviceKind, DeviceOptions, LayerSetting, LayerSettingValue, MessageKind, MessageSeverity, MessageSink, RawDevice, }; +#[cfg(unix)] +pub use dma_buf::{DmaBufChunk, DmaBufRequest, DmaBufSource}; pub use dynamic_library::DynamicLibrary; pub use error::DynamicLibraryError; pub use error::ExtensionFeature; diff --git a/crates/metal2vulkan-runtime/src/linear_plan.rs b/crates/metal2vulkan-runtime/src/linear_plan.rs index cb75799cb..dc06cc670 100644 --- a/crates/metal2vulkan-runtime/src/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/linear_plan.rs @@ -590,6 +590,18 @@ pub(super) struct LinearLack { /// none of the features of a usage that format does not take, so only those it takes are asked of /// its linear tiling. `None` where the linear image lacks nothing. pub(super) fn linear_lack(plan: &ImagePlan, facts: &ImageFacts) -> Option { + tiling_lack(plan, facts, |format| facts.linear(format)) +} + +/// What an image of `plan` in another tiling than optimal, whose features in a format are +/// `tiling`'s answer, lacks of all its optimal image can do, as [`linear_lack`] asks it of linear +/// tiling: a `DRM_FORMAT_MOD_LINEAR` image's features are its modifier's (`dma_buf.rs`). `None` +/// where it lacks nothing. +pub(super) fn tiling_lack( + plan: &ImagePlan, + facts: &ImageFacts, + tiling: impl Fn(Format) -> FormatFeatureFlags2, +) -> Option { let needed = USAGE_FEATURES .iter() .filter(|(usage, _)| plan.usage.contains(*usage)) @@ -604,7 +616,7 @@ pub(super) fn linear_lack(plan: &ImagePlan, facts: &ImageFacts) -> Option Option Vec { +pub(super) fn viewed_formats(plan: &ImagePlan, facts: &ImageFacts) -> Vec { if !plan.flags.contains(ImageCreateFlags::MUTABLE_FORMAT) || !plan.view_formats.is_empty() { return plan.view_formats.clone(); } diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index f81dd9eca..88af8a6f3 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -12,7 +12,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`]. +//! pooled, freed through the same [`Memory::free`]. 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`). //! //! - **Addresses** ([`allocate_addressed`]). A buffer placed for a device address gets it from its //! block: a block that holds such a buffer has one buffer over its whole memory with the @@ -33,6 +35,8 @@ use super::buffer::usage; use super::device::lock; +#[cfg(unix)] +use super::dma_buf::DmaBufPages; use super::error::{internal, vulkan, Error, MemoryKind}; use super::range::RangeAllocator; use super::sharing::Sharing; @@ -40,6 +44,8 @@ use super::work_counts::Counters; use crate::release; use ash::vk; use std::ptr::NonNull; +#[cfg(unix)] +use std::sync::Arc; use std::sync::Mutex; /// The size of a pooled block, at most the device's `maxMemoryAllocationSize`. @@ -469,6 +475,11 @@ pub(super) struct Placement { /// asked for one ([`allocate_addressed`]) on a device that enables /// `bufferDeviceAddress`. pub(super) address: Option, + /// 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. + #[cfg(unix)] + dma_buf: Option>, } impl Placement { @@ -491,6 +502,35 @@ impl Placement { offset, mapped: mapped.map(Mapped), address: None, + #[cfg(unix)] + dma_buf: None, + } + } + + /// The placement of a no-copy buffer's `size` bytes of host pages in the imports of the + /// caller's dma-bufs of them, `pages`: at offset 0 of `memory`, of type `type_index`, where + /// they are one import, or no memory (`VK_NULL_HANDLE`) where they are several bound to a + /// sparse buffer; their host address is `mapped`, the pages' pointer (the runtime never maps + /// a dma-buf). No block of the runtime's, so freeing it returns nothing; it keeps the imports + /// until it goes. + #[cfg(unix)] + pub(super) fn dma_buf( + pages: Arc, + memory: vk::DeviceMemory, + type_index: u32, + size: u64, + mapped: NonNull, + ) -> Placement { + Placement { + type_index, + holds: Holds::Buffers, + block: None, + size, + memory, + offset: 0, + mapped: Some(Mapped(mapped)), + address: None, + dma_buf: Some(pages), } } @@ -504,6 +544,36 @@ impl Placement { self.size } + /// Whether the placement lies in imports of the caller's dma-bufs (`dma_buf.rs`), to which no + /// image is bound (an image over them is bound to a dma-buf of its own pages). + pub(super) fn over_dma_buf(&self) -> bool { + #[cfg(unix)] + { + self.dma_buf.is_some() + } + #[cfg(not(unix))] + { + false + } + } + + /// 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)] + pub(super) fn dma_buf_pages(&self) -> Option<&Arc> { + self.dma_buf.as_ref() + } + + /// Wait until the sparse binding of the buffer over the placement's dma-bufs completed, + /// where it may not have (`dma_buf.rs`'s `DmaBufPages::settle`): before that buffer is + /// destroyed. Any other placement has nothing to wait for. + pub(super) fn settle(&self) { + #[cfg(unix)] + if let Some(pages) = &self.dma_buf { + pages.settle(); + } + } + /// The same placement, for another owner to free from now on: an image's first memory, which /// goes with its first `VkImage` once the image takes its storage form /// (`texture/storage_form.rs`). The image frees its storage form's memory instead, never @@ -518,6 +588,8 @@ impl Placement { offset: self.offset, mapped: self.mapped, address: self.address, + #[cfg(unix)] + dma_buf: self.dma_buf.clone(), } } } @@ -767,6 +839,8 @@ impl Memory { .as_ref() .filter(|_| addressed) .map(|addresses| addresses.address + offset), + #[cfg(unix)] + dma_buf: None, } } @@ -881,6 +955,58 @@ impl Memory { Err(failure) } + /// Import the dma-buf `fd`, `size` bytes, as memory of the best type of `class` among + /// `allowed` (the types both the dma-buf and what is bound in it take): the memory and its + /// type, the caller's to free (`dma_buf.rs`'s `DmaBufPages`), in no block and never mapped. + /// For a buffer, allocated with the device-address flag where the device enables + /// `bufferDeviceAddress`; for `image`, its dedicated allocation (`size` its requirements'). + /// Refused when no type of `class` is among `allowed`, else with the failure of the last type + /// tried; the descriptor is Vulkan's once imported, and closed on failure. + #[cfg(unix)] + pub(super) fn import_dma_buf( + &self, + device: &ash::Device, + fd: std::os::fd::OwnedFd, + size: u64, + (allowed, class): (u32, MemoryClass), + image: Option, + ) -> Result<(vk::DeviceMemory, u32), ImportFailure> { + use std::os::fd::{AsRawFd, IntoRawFd}; + let mut failure = ImportFailure::NoMemoryType; + for type_index in candidates(&self.types, allowed, class, self.unified) { + let mut import = vk::ImportMemoryFdInfoKHR::default() + .handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) + .fd(fd.as_raw_fd()); + let mut flags = vk::MemoryAllocateFlagsInfo::default() + .flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); + let mut dedicated = vk::MemoryDedicatedAllocateInfo::default(); + let mut info = vk::MemoryAllocateInfo::default() + .allocation_size(size) + .memory_type_index(type_index) + .push_next(&mut import); + match image { + Some(image) => { + dedicated = dedicated.image(image); + info = info.push_next(&mut dedicated); + } + None if self.device_address => info = info.push_next(&mut flags), + None => {} + } + // SAFETY: `info` and its chain live for the call; the type index is the device's and + // allows the dma-buf (and the image, unbound and made for dma-bufs, whose size this + // is). A failed import leaves the descriptor open, the caller's. + match unsafe { device.allocate_memory(&info, None) } { + Ok(memory) => { + // A successful import owns the descriptor: Vulkan closes it with the memory. + let _ = fd.into_raw_fd(); + return Ok((memory, type_index)); + } + Err(error) => failure = ImportFailure::Vulkan(error), + } + } + Err(failure) + } + /// The property flags of memory type `index`, where the device has it. pub(super) fn type_flags(&self, index: u32) -> Option { self.types diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index 555b0d2d0..2bce8e61e 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -47,7 +47,9 @@ //! a heap's rebind keeps (its first byte at the import's unit); a no-copy buffer with a texture //! over it is rebound only to memory at the same offset in its page //! (`NotImplemented(RebindTextures)` else), as is one whose aliasing image the device cannot make -//! again over the new pages (their memory type is not one it takes). +//! again over the new pages (their memory type is not one it takes). Over new pages imported as +//! dma-bufs, each such image is made again over a dma-buf of its own new pages before the rebind +//! settles (`Device::dma_buf_images_again`, `dma_buf.rs`), and refused likewise where it is not. use super::buffer::{Buffer, Detached, HostCell, HostPages, Lying, WeakBuffer}; use super::command_buffer::CommandBufferShared; @@ -60,7 +62,6 @@ use super::Device; use metal2vulkan::bind::ResidentRange; use std::any::Any; use std::collections::{BTreeSet, HashMap}; -use std::ptr::NonNull; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak}; @@ -691,23 +692,23 @@ impl Drop for Holds { impl Buffer { /// Give the no-copy buffer other host memory of its length from now on (a runtime extension; - /// the module docs of `rebind.rs` state the rule): `bytes`, under [`HostMemory::new`]'s - /// contract for the buffer's [`length`](Buffer::length), imported as + /// the module docs of `rebind.rs` state the rule): `memory` ([`HostMemory`]), under its + /// constructor's contract for the buffer's [`length`](Buffer::length), imported as /// [`Device::new_buffer_with_bytes_no_copy`] imports memory. The buffer, its `gpu_address` and - /// its options stay; `contents` answers `bytes` from now on. Command buffers first submitted - /// before the call keep the old memory until they complete; one committed before it and first - /// submitted after reaches the new memory through what it made resident and what its commands - /// reach unnamed, and through what its compute, blit and render encoders named, which this call - /// encodes again; it fails `CommandBufferError::EncodedUseRebound` where an encoder this call - /// cannot encode again named the buffer (one of a command buffer that used command predication, - /// among others); commands encoded after it use the new. The old memory's deallocator runs once - /// every command buffer submitted before the call that used it completed (in the call, where - /// none holds it); `deallocator` runs for `bytes` at the next rebind's turn, or when the buffer - /// goes. A refused call runs neither and changes nothing. `keep_alive` ([`KeepAlive`]) is - /// dropped once the device's import of `bytes` is freed: with one, `deallocator` runs at that - /// turn though something still holds the import (a command buffer submitted before a texture - /// over the bytes was released); with none, `deallocator` waits for the import - /// (`host-deallocator-delayed`). + /// its options stay; `contents` answers `memory.pointer()` from now on. Command buffers first + /// submitted before the call keep the old memory until they complete; one committed before it + /// and first submitted after reaches the new memory through what it made resident and what its + /// commands reach unnamed, and through what its compute, blit and render encoders named, which + /// this call encodes again; it fails `CommandBufferError::EncodedUseRebound` where an encoder + /// this call cannot encode again named the buffer (one of a command buffer that used command + /// predication, among others); commands encoded after it use the new. The old memory's + /// deallocator runs once every command buffer submitted before the call that used it completed + /// (in the call, where none holds it); `deallocator` runs for the new memory at the next + /// rebind's turn, or when the buffer goes. A refused call runs neither and changes nothing. + /// `keep_alive` ([`KeepAlive`]) is dropped once the device's import of the new memory is freed: + /// with one, `deallocator` runs at that turn though something still holds the import (a command + /// buffer submitted before a texture over the bytes was released); with none, `deallocator` + /// waits for the import (`host-deallocator-delayed`). /// /// A texture over the buffer (a shadow of its bytes, or a texture buffer) reads the new /// memory from its next use, and one whose linear image aliases its bytes has its image made @@ -719,18 +720,20 @@ impl Buffer { /// memory at another offset in its page than the old where a texture over the buffer lives /// (`NotImplemented(RebindTextures)`: the texture's copies, views and aliasing image are /// planned at that offset), or where the device cannot make a texture's aliasing image again - /// over the new memory (`NotImplemented(RebindTextures)`); memory the device cannot import - /// exactly, as `new_buffer_with_bytes_no_copy` refuses it; a lost device. + /// over the new memory (`NotImplemented(RebindTextures)`, which says when); memory the device + /// cannot import exactly, as `new_buffer_with_bytes_no_copy` refuses it; a lost device. /// /// # Safety /// - /// `bytes` meets [`HostMemory::new`]'s contract for the buffer's length. The old memory stays - /// mapped until its keep-alive is dropped, else until its deallocator runs, or with neither - /// until every command buffer first submitted before the call completed. No command that uses the buffer is encoded, and no command - /// buffer that uses it committed, on another thread during the call. + /// `memory` meets the contract of the [`HostMemory`] constructor that made it + /// ([`HostMemory::new`], [`HostMemory::with_dma_buf`]) for the buffer's length. The old memory + /// stays mapped until its keep-alive is dropped, else until its deallocator runs, or with + /// neither until every command buffer first submitted before the call completed. No command + /// that uses the buffer is encoded, and no command buffer that uses it committed, on another + /// thread during the call. pub unsafe fn rebind_bytes_no_copy( &self, - bytes: NonNull, + memory: HostMemory, deallocator: Option, keep_alive: Option, ) -> Result<(), Error> { @@ -744,7 +747,7 @@ impl Buffer { CALL, self, cell, - HostMemory::new(bytes), + memory, HostRelease { deallocator, keep_alive, @@ -758,14 +761,15 @@ impl Buffer { impl Heap { /// Give the heap over the caller's host memory (`Device::new_heap_with_bytes_no_copy`) other /// host memory of its size from now on (a runtime extension), as - /// [`Buffer::rebind_bytes_no_copy`] gives a no-copy buffer: `bytes`, its first byte at a - /// multiple of the import's unit as the heap's was. Every buffer and texture placed in the - /// heap stays, at its offset, with its `gpu_address` and resource ID; a buffer's `contents` - /// answers its offset in `bytes` from now on. A texture bound to the heap's bytes has its - /// image made again over the new memory, at its offset, before the call returns, as has a - /// texture over one of the heap's buffers whose linear image aliases its bytes; a texture - /// held as a shadow of the heap's bytes, a texture buffer and a shadowed texture over one of - /// the heap's buffers read them from their next use. Nothing of the old contents is copied. + /// [`Buffer::rebind_bytes_no_copy`] gives a no-copy buffer: `memory` ([`HostMemory`]), its + /// first byte at a multiple of the import's unit as the heap's was. Every buffer and texture + /// placed in the heap stays, at its offset, with its `gpu_address` and resource ID; a buffer's + /// `contents` answers its offset from `memory.pointer()` from now on. A texture bound to the + /// heap's bytes has its image made again over the new memory, at its offset, before the call + /// returns, as has a texture over one of the heap's buffers whose linear image aliases its + /// bytes; a texture held as a shadow of the heap's bytes, a texture buffer and a shadowed + /// texture over one of the heap's buffers read them from their next use. Nothing of the old + /// contents is copied. /// /// Refused: a heap not over the caller's host memory (`Invalid`, /// [`RebindProblem::NotHostMemory`]); a command buffer not yet committed whose commands used @@ -781,7 +785,7 @@ impl Heap { /// of the heap and its resources. pub unsafe fn rebind_bytes_no_copy( &self, - bytes: NonNull, + memory: HostMemory, deallocator: Option, keep_alive: Option, ) -> Result<(), Error> { @@ -798,7 +802,7 @@ impl Heap { CALL, own, cell, - HostMemory::new(bytes), + memory, HostRelease { deallocator, keep_alive, diff --git a/crates/metal2vulkan-runtime/src/tests/detach_lost.rs b/crates/metal2vulkan-runtime/src/tests/detach_lost.rs index 0ba28d7b1..4ffa98703 100644 --- a/crates/metal2vulkan-runtime/src/tests/detach_lost.rs +++ b/crates/metal2vulkan-runtime/src/tests/detach_lost.rs @@ -8,7 +8,9 @@ //! `m2v_cpu_icd`), on the kind of device the cfg selects. use crate::error::Error; -use crate::{Device, DeviceKind, DeviceOptions, EventRef, ResourceOptions, ShaderCacheOptions}; +use crate::{ + Device, DeviceKind, DeviceOptions, EventRef, HostMemory, ResourceOptions, ShaderCacheOptions, +}; use std::alloc::Layout; use std::path::{Path, PathBuf}; use std::ptr::NonNull; @@ -91,7 +93,12 @@ fn a_detach_waiting_for_a_submitted_command_buffer_settles_on_a_lost_device() { // SAFETY: the memory outlives the device (dropped after it, below), and nothing else uses // it meanwhile. let made = unsafe { - device.new_buffer_with_bytes_no_copy(host.0, BYTES as u64, ResourceOptions::default(), None) + device.new_buffer_with_bytes_no_copy( + HostMemory::new(host.0), + BYTES as u64, + ResourceOptions::default(), + None, + ) }; let buffer = match made { Ok(buffer) => buffer, diff --git a/crates/metal2vulkan-runtime/src/tests/device.rs b/crates/metal2vulkan-runtime/src/tests/device.rs index f612ca0d6..6e44ea4c5 100644 --- a/crates/metal2vulkan-runtime/src/tests/device.rs +++ b/crates/metal2vulkan-runtime/src/tests/device.rs @@ -16,14 +16,15 @@ fn the_registry_id_folds_the_uuid_and_is_never_zero() { } use crate::device::create::{ - default_loaders, enable_set, host_image_copy, instance_version, layer_settings, - linear_color_attachment, open_loader, queue_plan, setting_values, timeline_difference, - QueuePlan, + default_loaders, dma_buf_image_names, dma_buf_names, enable_set, host_image_copy, + instance_version, layer_settings, linear_color_attachment, open_loader, queue_plan, + setting_values, timeline_difference, QueuePlan, }; use crate::enables::host_image_copy_names; use crate::{DeviceOptions, Error, InstanceApiVersion, LayerSetting, LayerSettingValue}; use ash::vk; use metal2vulkan::device::{ApiVersion, DeviceDescription, VkExtension, VkFeature}; +use std::collections::BTreeSet; use std::ffi::{CStr, CString}; /// Every committed profile's description at the runtime's Vulkan 1.2 instance, as `(file, @@ -48,6 +49,75 @@ fn descriptions() -> Vec<(std::path::PathBuf, DeviceDescription)> { out } +/// The dma-buf route's extensions: `VK_KHR_external_memory_fd` and +/// `VK_EXT_external_memory_dma_buf`. +const DMA_BUF: [&CStr; 2] = [ + c"VK_KHR_external_memory_fd", + c"VK_EXT_external_memory_dma_buf", +]; + +/// The extensions of the images of textures over the route's pages: +/// `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign`. +const DMA_BUF_IMAGES: [&CStr; 2] = [ + c"VK_EXT_image_drm_format_modifier", + c"VK_EXT_queue_family_foreign", +]; + +/// The dma-buf route of a no-copy buffer (`dma_buf.rs`), the last resort where a device refuses +/// the pointer, takes its two extensions on every committed profile that lists both (RADV's, +/// NVIDIA's, lavapipe's and ANV's among them), on no profile that lacks either, and outside the +/// vocabulary; the images of textures over its pages take theirs +/// (`VK_EXT_image_drm_format_modifier`, `VK_EXT_queue_family_foreign`) on every profile that +/// lists those two and the route's, and on no other. Every profile's enable set is the +/// recommendation and `VK_EXT_external_memory_host` where listed, as before the route, so no +/// compile profile or fingerprint (the shader cache's key) moves with them. +#[test] +fn the_dma_buf_route_is_enabled_wherever_listed_outside_the_profile() { + let (mut lists_both, mut lists_all) = (0, 0); + for (path, description) in descriptions() { + let text = std::fs::read_to_string(&path).unwrap(); + let listed: BTreeSet = DMA_BUF + .iter() + .chain(&DMA_BUF_IMAGES) + .filter(|name| text.contains(&format!("\"{}\"", name.to_str().unwrap()))) + .map(|name| (*name).to_owned()) + .collect(); + let lists = DMA_BUF.iter().all(|name| listed.contains(*name)); + let lists_images = DMA_BUF_IMAGES.iter().all(|name| listed.contains(*name)); + assert_eq!(dma_buf_names(&listed).is_some(), lists, "{path:?}"); + assert_eq!( + dma_buf_image_names(&listed).is_some(), + lists && lists_images, + "{path:?}" + ); + for name in DMA_BUF.iter().chain(&DMA_BUF_IMAGES) { + let mut one_short = listed.clone(); + one_short.remove(*name); + assert_eq!(dma_buf_image_names(&one_short), None, "{path:?}"); + if DMA_BUF.contains(name) { + assert_eq!(dma_buf_names(&one_short), None, "{path:?}"); + } + } + lists_both += usize::from(lists); + lists_all += usize::from(lists && lists_images); + let options = DeviceOptions::default(); + let mut before = description.recommended_enables(&options.policy); + let host_memory = VkExtension::ExtExternalMemoryHost; + if description.extensions.contains(&host_memory) { + before.extensions.insert(host_memory); + } + assert_eq!(enable_set(&description, &options), before, "{path:?}"); + } + assert!( + lists_both > 1, + "fewer than two committed profiles list both" + ); + assert!( + lists_all > 1, + "fewer than two committed profiles list all four" + ); +} + /// The robustness features. const ROBUSTNESS: [VkFeature; 4] = [ VkFeature::RobustBufferAccess, @@ -416,7 +486,6 @@ fn equivalent_queue_families_are_all_taken_in_turn() { #[test] fn host_image_copy_is_enabled_wherever_the_device_has_it() { use std::cell::Cell; - use std::collections::BTreeSet; let names = host_image_copy_names(ApiVersion::V1_2); assert_eq!(names.len(), 3); let listed: BTreeSet = names.iter().map(|&name| name.to_owned()).collect(); @@ -443,7 +512,6 @@ fn host_image_copy_is_enabled_wherever_the_device_has_it() { #[test] fn linear_color_attachment_is_enabled_where_the_device_has_it_at_vulkan_1_3() { use std::cell::Cell; - use std::collections::BTreeSet; let listed: BTreeSet = [c"VK_NV_linear_color_attachment".to_owned()].into(); let asked = Cell::new(false); assert!(linear_color_attachment(ApiVersion::V1_3, &listed, || { diff --git a/crates/metal2vulkan-runtime/src/tests/host_memory.rs b/crates/metal2vulkan-runtime/src/tests/host_memory.rs index 3f02c6bb0..ed133ff23 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_memory.rs @@ -2,8 +2,8 @@ //! binds in them, the memory types an import may use, and the host's page. use crate::host_memory::{ - based_size, binds_in, buffer_base, host_page, import_refused, import_window, ImportWindow, - WindowRefusal, + based_size, binds_in, buffer_base, host_page, import_refused, import_window, refused, + ImportWindow, WindowRefusal, }; use crate::memory::{candidates, MemoryClass}; use crate::{Error, MemoryKind, VkResultCode}; @@ -490,3 +490,111 @@ fn a_driver_s_refused_import_is_a_device_gap_and_other_failures_are_vulkan_s() { )) ); } + +/// The refusals a dma-buf of the pages may serve are exactly the device's refusal of the memory +/// (`not_importable`): a Vulkan failure, running out of memory, a refusal of another feature or +/// of another kind, and a nil answer are final. +#[test] +fn only_the_device_s_refusal_of_the_memory_falls_back_to_a_dma_buf() { + assert!(refused(&Error::Unsupported( + Unsupported::not_representable(Feature::HostMemory) + ))); + assert!(refused(&import_refused( + vk::Result::ERROR_INVALID_EXTERNAL_HANDLE + ))); + assert!(refused(&import_refused(vk::Result::ERROR_UNKNOWN))); + for error in [ + import_refused(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY), + import_refused(vk::Result::ERROR_INITIALIZATION_FAILED), + Error::Unsupported(Unsupported::not_implemented(Feature::HostMemory)), + Error::Unsupported(Unsupported::not_representable(Feature::GpuTimes)), + Error::DeviceLost, + ] { + assert!(!refused(&error), "{error:?}"); + } +} + +/// A dma-buf's window is the range rounded out to the host page alone (`import_window` at an +/// alignment of 1): where the device's import alignment for host pointers refuses a range +/// (`BeyondPages`), it still covers exactly the pages the range touches, and where the alignment +/// takes one, the two windows agree (`host_window` keeps one). +#[test] +fn a_dma_buf_window_is_the_pages_the_range_touches() { + let (page, unit, at) = (4096, 64 << 10, 0x7f00_0000_0000); + assert_eq!( + import_window(at, unit, page, unit), + import_window(at, unit, page, 1) + ); + assert_eq!( + import_window(at + page + 100, page, page, unit), + Err(WindowRefusal::BeyondPages) + ); + assert_eq!( + import_window(at + page + 100, page, page, 1), + Ok(ImportWindow { + start: at + page, + size: 2 * page, + offset: 100, + }) + ); +} + +/// A source's chunks must cover the request, each a whole number of host pages, every boundary at +/// a multiple of the granule; several chunks cover the request rounded up to the granule (the +/// last one padded past the pages, as a sparse buffer binds whole granules), one chunk the request +/// or that rounding; one chunk is the only answer where the granule is the length. +#[cfg(unix)] +#[test] +fn a_source_s_chunks_cover_the_request_at_its_granule() { + use crate::dma_buf::{chunks_cover, DmaBufRequest}; + let page = 4096; + let start = std::ptr::NonNull::::dangling(); + let request = |length, granule| DmaBufRequest { + start, + length, + granule, + }; + let one = request(8 * page, 8 * page); + assert!(chunks_cover(&[8 * page], &one, page)); + assert!(!chunks_cover(&[], &one, page)); + assert!(!chunks_cover(&[4 * page, 4 * page], &one, page)); + assert!(!chunks_cover(&[7 * page], &one, page)); + assert!(!chunks_cover(&[9 * page], &one, page)); + let paged = request(8 * page, page); + assert!(chunks_cover(&[3 * page, page, 4 * page], &paged, page)); + assert!(!chunks_cover(&[3 * page, 0, 5 * page], &paged, page)); + assert!(!chunks_cover( + &[3 * page + 512, 5 * page - 512], + &paged, + page + )); + let coarse = request(8 * page, 2 * page); + assert!(chunks_cover(&[2 * page, 6 * page], &coarse, page)); + assert!(!chunks_cover(&[3 * page, 5 * page], &coarse, page)); + // Several chunks end at the request rounded up to the granule: the last one is padded. + let ragged = request(5 * page, 2 * page); + assert!(chunks_cover(&[4 * page, 2 * page], &ragged, page)); + assert!(chunks_cover(&[2 * page, 2 * page, 2 * page], &ragged, page)); + assert!(!chunks_cover(&[4 * page, page], &ragged, page)); + assert!(!chunks_cover(&[4 * page, 4 * page], &ragged, page)); + // One chunk is the pages, or the pages padded to the granule. + assert!(chunks_cover(&[5 * page], &ragged, page)); + assert!(chunks_cover(&[6 * page], &ragged, page)); + assert!(!chunks_cover(&[7 * page], &ragged, page)); + assert!(!chunks_cover( + &[u64::MAX - page + 1, 2 * page], + &ragged, + page + )); + // A 64 KiB granule on 4 KiB pages, as RADV of Mesa 26.2.4 binds sparse buffers. + let granule = 64 << 10; + let window = request(16_201 * page, granule); + let rounded = (16_201 * page).next_multiple_of(granule); + let mut lengths = vec![4 << 20; 15]; + lengths.push(rounded - 15 * (4 << 20)); + assert!(chunks_cover(&lengths, &window, page)); + assert!(chunks_cover(&[16_201 * page], &window, page)); + lengths.pop(); + lengths.push(16_201 * page - 15 * (4 << 20)); + assert!(!chunks_cover(&lengths, &window, page)); +} diff --git a/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs b/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs index ea3e9f49b..e99de9ddc 100644 --- a/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs +++ b/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs @@ -16,7 +16,7 @@ use crate::pipeline::pool::held; use crate::{ BlitOption, Buffer, ClearColor, CommandBufferStatus, Device, DeviceKind, DeviceOptions, - LoadAction, Origin, PipelineOptions, RenderPassDescriptor, RenderPipelineState, + HostMemory, LoadAction, Origin, PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, ShaderCacheOptions, Size, StoreAction, Texture, TextureDescriptor, }; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; @@ -122,7 +122,7 @@ fn no_copy_texture(device: &Device, freed: &Arc) -> (Buffer, Texture // deallocator unrun, and the memory then leaks. let buffer = unsafe { device.new_buffer_with_bytes_no_copy( - memory, + HostMemory::new(memory), NO_COPY as u64, ResourceOptions::shared(), Some(Box::new(move |pointer, _| { diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 634149730..25c52f27a 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -134,6 +134,7 @@ use stand_in::StandIn; use std::any::Any; use std::collections::{BTreeSet, HashMap}; use std::ops::Range; +use std::ptr::NonNull; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, Weak}; use wrapped::WrappedImage; @@ -448,7 +449,8 @@ struct Image { /// It was made with host-transfer usage, moved to `GENERAL` and zeroed on the host, so its /// CPU copies may run there (`texture/host_copy.rs`). host_copies: bool, - /// Its `VkImage` has linear tiling: a texture over a buffer's memory (`alias_image`), or a + /// Its `VkImage` has linear tiling, or `DRM_FORMAT_MOD_LINEAR`'s, whose rows lie as a linear + /// image's: a texture over a buffer's memory (`alias_image`, `dma_buf_alias_image`), or a /// heap's linear image (`texture/heap.rs`). Not a Metal texture over a buffer /// (`metal_alias_image`), which renders where Metal's textures do. linear: bool, @@ -484,17 +486,61 @@ enum RawGoes { } /// An image's `VkImage`: its own for good, but for a texture bound to the bytes of a heap over -/// host pages, whose image a rebind re-makes over the new pages ([`Image::swap_in`]). -struct Raw(AtomicU64); +/// host pages, whose image a rebind re-makes over the new pages ([`Image::swap_in`]). With it, the +/// dedicated import its `VkImage` is bound to, for an image over dma-buf pages (`dma_buf.rs`), +/// which goes with that `VkImage`, after it. +struct Raw { + image: AtomicU64, + import: Mutex>, +} + +/// The dedicated import of the pages a texture's image over dma-buf pages is bound to +/// (`dma_buf.rs`), freed after the image is destroyed. +#[cfg(unix)] +pub(super) type ImageImport = Arc; + +/// No image is made over dma-buf pages on this system. +#[cfg(not(unix))] +pub(super) type ImageImport = std::convert::Infallible; impl Raw { fn new(raw: vk::Image) -> Raw { - Raw(AtomicU64::new(raw.as_raw())) + Raw { + image: AtomicU64::new(raw.as_raw()), + import: Mutex::new(None), + } + } + + /// `raw`, bound to `import`, its dedicated import. + #[cfg(unix)] + fn imported(raw: vk::Image, import: ImageImport) -> Raw { + Raw { + image: AtomicU64::new(raw.as_raw()), + import: Mutex::new(Some(import)), + } + } + + /// Whether the `VkImage` now is bound to a dedicated import of its own pages. + fn dedicated(&self) -> bool { + lock(&self.import).is_some() } /// The `VkImage` now. fn get(&self) -> vk::Image { - vk::Image::from_raw(self.0.load(Ordering::Acquire)) + vk::Image::from_raw(self.image.load(Ordering::Acquire)) + } + + /// Hold `raw`, bound to `import` where it has a dedicated one, from now on: the `VkImage` it + /// held and that one's import. + fn swap( + &self, + raw: vk::Image, + import: Option, + ) -> (vk::Image, Option) { + let mut held = lock(&self.import); + let old = self.image.swap(raw.as_raw(), Ordering::AcqRel); + let old_import = std::mem::replace(&mut *held, import); + (vk::Image::from_raw(old), old_import) } } @@ -507,6 +553,9 @@ pub(super) struct ImageObjects { views: Vec, /// What becomes of `raw` as this goes. raw_goes: RawGoes, + /// The dedicated import `raw` is bound to, an image over dma-buf pages (`dma_buf.rs`): freed + /// as this goes, after `raw` is destroyed. + import: Option, } impl Drop for ImageObjects { @@ -640,19 +689,50 @@ fn first_color_subresource() -> vk::ImageSubresource { /// (`shadowed-texture`) names. type Aliased = Result, String>; -/// A linear image aliasing the host pages of a no-copy buffer (or of a no-copy heap, for a -/// texture over one of its buffers), noted in the pages' hold (`buffer.rs`'s `HostCell`) so that -/// a rebind makes it again over the new pages ([`Device::rebound_alias_images`]): the image, and -/// where it is bound, in bytes from where the pages' bytes start in their memory. +/// An image aliasing the host pages of a no-copy buffer (or of a no-copy heap, for a texture over +/// one of its buffers), noted in the pages' hold (`buffer.rs`'s `HostCell`) so that a rebind makes +/// it again over the new pages ([`Device::rebound_alias_images`]): the image, and where its texels +/// lie, in bytes from where the pages' bytes start (in their memory, and in the host addresses +/// they lie at). #[derive(Clone)] pub(super) struct AliasWatch { image: Weak, from_base: u64, /// The texture's type: a 2D texture or array. texture_type: TextureType, - /// The Metal texture over the import's `MTLBuffer` the image is made of, where it is one - /// (`metal_texture.rs`); else a linear image made for host allocations. - metal: Option, + /// What the image is made as. + kind: AliasKind, +} + +/// What an aliasing image over host pages is made as ([`AliasWatch`]). +#[derive(Clone)] +pub(super) enum AliasKind { + /// A linear image, its rows (and slices) the texels' pitches apart: over pages imported by + /// their pointer, one made for host allocations and bound in the pages' import + /// ([`Device::alias_image`]); over pages imported as dma-bufs, a `DRM_FORMAT_MOD_LINEAR` image + /// bound to a dedicated import of a dma-buf of its own pages + /// ([`Device::dma_buf_alias_image`]). A rebind makes the kind its new pages take. + Linear { row_pitch: u64, slice_pitch: u64 }, + /// A Metal texture over the import's `MTLBuffer` (`metal_texture.rs`). + Metal(MetalOver), +} + +/// The images a rebind made for the textures over the bytes it gives pages it imported as +/// dma-bufs ([`Device::dma_buf_images_again`]), before it settled: each texture's image with its +/// new `VkImage`, bound to a dedicated import of its own pages (`dma_buf.rs`). Dropped unused, +/// they go. +#[derive(Default)] +pub(super) struct Remade(Vec<(Arc, ImageObjects)>); + +impl Remade { + /// The objects made for `image`, where some were. + fn take(&mut self, image: &Arc) -> Option { + let at = self + .0 + .iter() + .position(|(made, _)| Arc::ptr_eq(made, image))?; + Some(self.0.swap_remove(at).1) + } } impl AliasWatch { @@ -670,6 +750,20 @@ impl ImageObjects { raw, views: Vec::new(), raw_goes: RawGoes::Destroyed, + import: None, + } + } + + /// `raw`, a new image of `device`'s bound to `import`, its dedicated import of dma-buf pages + /// (`dma_buf.rs`), with no views yet. + #[cfg(unix)] + fn imported(device: &Device, raw: vk::Image, import: ImageImport) -> ImageObjects { + ImageObjects { + device: device.clone(), + raw, + views: Vec::new(), + raw_goes: RawGoes::Destroyed, + import: Some(import), } } @@ -702,6 +796,22 @@ impl ImageSwap { } } + /// `objects`, a new image for `image` over `pages`, dma-buf pages, bound to a dedicated import + /// of them (`dma_buf.rs`) and made `UNDEFINED`, to swap in: its first move acquires it from + /// `VK_QUEUE_FAMILY_FOREIGN_EXT` for `family` (`Device::foreign_acquirer`). + fn acquired( + image: Arc, + objects: ImageObjects, + pages: &HostPages, + family: u32, + ) -> ImageSwap { + let swap = ImageSwap::new(image, objects, vk::ImageLayout::UNDEFINED, pages); + ImageSwap { + first: swap.first.acquired(family), + ..swap + } + } + /// Whether the swap is `image`'s. fn is_of(&self, image: &Arc) -> bool { Arc::ptr_eq(&self.image, image) @@ -798,8 +908,9 @@ impl Image { fn swap_in(&self, objects: &mut ImageObjects) { let mut views = lock(&self.views); self.views_go(); - let old = self.raw.0.swap(objects.raw.as_raw(), Ordering::AcqRel); - objects.raw = vk::Image::from_raw(old); + let (old, import) = self.raw.swap(objects.raw, objects.import.take()); + objects.raw = old; + objects.import = import; objects.views.extend(views.drain().map(|(_, view)| view)); // A stand-in's read image swapped out goes as the stand-in's (an image in memory of its // own swaps its own back instead, `present_own`). @@ -894,7 +1005,9 @@ impl Image { return None; } self.views_go(); - let old = vk::Image::from_raw(self.raw.0.swap(stand_in.read().as_raw(), Ordering::AcqRel)); + let (old, import) = self.raw.swap(stand_in.read(), None); + // An image in memory of its own keeps its `VkImage`, which no dedicated import is bound + // to (only an image over dma-buf pages has one). let own = self.own_memory().then_some(old); // An image bound to the detached pages lets go of their memory: its `VkImage` goes with // the pages. @@ -906,11 +1019,13 @@ impl Image { None => RawGoes::Destroyed, }; *detached = Some(DetachedImage { stand_in, own }); + // A dedicated import of dma-buf pages goes with the `VkImage` bound to it. Some(ImageObjects { device: self.device.clone(), raw: old, views: views.drain().map(|(_, view)| view).collect(), raw_goes, + import, }) } @@ -925,12 +1040,13 @@ impl Image { let own = detached.as_ref()?.own?; let stand_in = detached.take()?.stand_in; self.views_go(); - let old = vk::Image::from_raw(self.raw.0.swap(own.as_raw(), Ordering::AcqRel)); + let (old, import) = self.raw.swap(own, None); Some(ImageObjects { device: self.device.clone(), raw: old, views: views.drain().map(|(_, view)| view).collect(), raw_goes: RawGoes::WithStandIn(stand_in), + import, }) } @@ -1815,20 +1931,35 @@ impl Device { // Over bytes detached from their pages (`detach.rs`) no image aliases them: the texture // is their shadow, which presents a stand-in until they lie in pages again. let detached = texels.buffer.detached(); - if wider != plan && !detached { - if let Ok(image) = self.alias_image(wider, layout, descriptor, &texels, &facts)? { - return Ok(Storage::Alias { image, texels }); - } - } + let dma_buf = texels.buffer.over_dma_buf(); // Where no image aliases the bytes, the reason the plan's attempt gives is the notice's. - let why = match detached { - true => "the buffer's bytes were detached from their pages (detach_backing) as the \ - texture was made" - .to_owned(), - false => match self.alias_image(plan.clone(), layout, descriptor, &texels, &facts)? { + let why = if detached { + "the buffer's bytes were detached from their pages (detach_backing) as the texture \ + was made" + .to_owned() + } else if dma_buf { + // Over dma-buf pages, one image of the two plans at most, its pages' source called + // once (`dma_buf.rs`). + let plans = [&wider, &plan]; + let plans = if wider != plan { + &plans[..] + } else { + &plans[1..] + }; + match self.dma_buf_alias_image(plans, layout, descriptor, &texels, &facts)? { Ok(image) => return Ok(Storage::Alias { image, texels }), Err(why) => why, - }, + } + } else { + if wider != plan { + if let Ok(image) = self.alias_image(wider, layout, descriptor, &texels, &facts)? { + return Ok(Storage::Alias { image, texels }); + } + } + match self.alias_image(plan.clone(), layout, descriptor, &texels, &facts)? { + Ok(image) => return Ok(Storage::Alias { image, texels }), + Err(why) => why, + } }; let plan = self.with_undeclared_usage(plan, layout, usage, false, &facts)?; if !plan @@ -2028,7 +2159,8 @@ impl Device { /// makes it again over ([`Device::rebound_alias_images`]); on a device whose imports give /// their `MTLBuffer`s it is instead made of a Metal texture over the import's `MTLBuffer` /// ([`Device::metal_alias_image`]), which renders where the driver's linear images do not. - /// The image's hazard tracking is the buffer's. + /// Pages the runtime imported as dma-buf memory take [`Device::dma_buf_alias_image`]'s image + /// instead. The image's hazard tracking is the buffer's. fn alias_image( &self, plan: ImagePlan, @@ -2158,7 +2290,10 @@ impl Device { image: Arc::downgrade(&image), from_base: memory_offset - base, texture_type: layout.texture_type, - metal: None, + kind: AliasKind::Linear { + row_pitch: texels.layout.row_pitch, + slice_pitch: texels.layout.slice_pitch, + }, }); } Ok(Ok(image)) @@ -2239,11 +2374,140 @@ impl Device { image: Arc::downgrade(&image), from_base: memory_offset - base, texture_type: layout.texture_type, - metal: Some(over), + kind: AliasKind::Metal(over), }); Ok(Ok(image)) } + /// The image of the first of `plans` the device makes over `texels`, whose bytes lie in host + /// pages the runtime imported as dma-buf memory (`dma_buf.rs`): a `DRM_FORMAT_MOD_LINEAR` + /// image bound to a dedicated import of a dma-buf of its own pages, which the pages' source + /// makes (called once), its rows the texels' rows; noted in the pages' hold, which a rebind + /// makes it again over ([`Device::rebound_alias_images`]). Its first move acquires it from + /// `VK_QUEUE_FAMILY_FOREIGN_EXT` into `GENERAL`, keeping the bytes. It aliases the buffer's + /// bytes through another import of the same pages, so its hazard tracking is the buffer's (its + /// key), as every image aliasing a buffer's bytes is: a write through the one orders before a + /// read through the other in a command buffer, by the tracker's memory barriers. Where the + /// device makes none, why, the fallback counted (`WorkCounts::dma_buf_image_fallbacks`): the + /// texture takes the way a texture over memory no image aliases takes. + #[cfg(unix)] + fn dma_buf_alias_image( + &self, + plans: &[&ImagePlan], + layout: &TextureLayout, + descriptor: &TextureDescriptor, + texels: &Texels, + facts: &ImageFacts<'_>, + ) -> Result { + let pages = texels.buffer.host_pages(); + let over = pages.as_deref().and_then(HostPages::dma_buf); + let Some((imports, start, type_index)) = over else { + return Err(internal( + "a texture over dma-buf pages the buffer does not lie in", + )); + }; + let base = texels.buffer.pages_base()?; + let (_, buffer_offset, _) = texels.buffer.memory(); + let from_base = buffer_offset + texels.layout.offset - base; + let (row_pitch, slice_pitch) = (texels.layout.row_pitch, texels.layout.slice_pitch); + let place = crate::dma_buf::DmaBufTexels { + pages: imports, + type_index, + at: start + from_base, + row_pitch, + slice_pitch, + }; + let made = match self.dma_buf_image(plans, facts, &place)? { + Ok(made) => made, + Err(why) => { + self.shared().counts.dma_buf_image_fell_back(); + return Ok(Err(format!( + "the buffer's host pages are imported as dma-buf memory, and {why}" + ))); + } + }; + let (index, made) = made; + let owner = Owner::Buffer { + memory: Mutex::new(texels.buffer.memory_hold()), + }; + let image = self.dma_buf_texture_image( + made, + plans[index].clone(), + owner, + (texels.options(), descriptor.allow_gpu_optimized_contents), + // The buffer's bytes, tracked as the texture is. + Identity { + tracked: texels.tracked(), + ..texels.buffer.identity() + }, + ); + let image = image.shared(); + texels.buffer.watch_alias(AliasWatch { + image: Arc::downgrade(&image), + from_base, + texture_type: layout.texture_type, + kind: AliasKind::Linear { + row_pitch, + slice_pitch, + }, + }); + Ok(Ok(image)) + } + + /// The image of a texture over dma-buf pages (over a buffer, or placed in a heap), `made` of + /// `plan` (`dma_buf.rs`), with its `owner`, its options and whether it allows GPU-optimized + /// contents, and the `identity` of its bytes: a `DRM_FORMAT_MOD_LINEAR` image, whose rows are a + /// linear image's (a write of its bytes is a write of its texels), its first move acquiring + /// it from `VK_QUEUE_FAMILY_FOREIGN_EXT` into `GENERAL`, keeping the bytes. + #[cfg(unix)] + fn dma_buf_texture_image( + &self, + made: crate::dma_buf::DmaBufImage, + plan: ImagePlan, + owner: Owner, + (options, allow_gpu_optimized_contents): (ResourceOptions, bool), + identity: Identity, + ) -> Image { + let crate::dma_buf::DmaBufImage { raw, import } = made; + let image = Image { + device: self.clone(), + raw: Raw::imported(raw, import), + owner, + plan, + options, + allow_gpu_optimized_contents, + identity, + views: Mutex::new(HashMap::new()), + twin: None, + decoded: None, + form: Default::default(), + kept_outside: AtomicBool::new(false), + detached: Mutex::new(None), + first_move: Mutex::new(None), + host_copies: false, + linear: true, + staging_copies: false, + objects: ObjectsToken::default(), + }; + let first = FirstMove::new(raw, image.plan().format, vk::ImageLayout::UNDEFINED, true) + .acquired(self.foreign_acquirer()); + *lock(&image.first_move) = Some(first); + image + } + + /// No host pages are imported as dma-bufs on this system. + #[cfg(not(unix))] + fn dma_buf_alias_image( + &self, + _plans: &[&ImagePlan], + _layout: &TextureLayout, + _descriptor: &TextureDescriptor, + _texels: &Texels, + _facts: &ImageFacts<'_>, + ) -> Result { + Err(internal("a texture over dma-buf pages on a system of none")) + } + /// A `VkImage` of `plan` (of Metal's `texture_type`), made of the Metal texture `over` /// describes over the `MTLBuffer` of `memory`, an import allocated for its export, from /// `offset`: treated as bound (`VkImportMetalTextureInfoEXT`). Where none is made, why (for @@ -2395,16 +2659,25 @@ impl Device { /// The aliasing images of `watches`, over a no-copy buffer's (or a no-copy heap's) host /// pages, made again over a rebind's new `pages` (`rebind.rs`): each of the same plan, made - /// for host allocations as [`alias_image`](Self::alias_image) made it, bound as far from the - /// new pages' first byte as it was from the old's; swapped in once the rebind is made, the - /// device's next submission that names it moving it to `GENERAL`. Refused - /// (`NotImplemented(RebindTextures)`) where the device makes no such image there: the new - /// import's memory type is not one the image takes, or the image's alignment misses its place. + /// as the new pages take it, its texels as far from the new pages' first byte as they were + /// from the old's; swapped in once the rebind is made, the device's next submission that + /// names it moving it to `GENERAL`. Over pages imported by their pointer, an image made for + /// host allocations as [`alias_image`](Self::alias_image) made it, bound in their import (or + /// a Metal texture over its `MTLBuffer`, as [`metal_alias_image`](Self::metal_alias_image) + /// made it); over pages imported as dma-bufs (`dma_buf.rs`), the `DRM_FORMAT_MOD_LINEAR` + /// image `remade` holds for it, made before the rebind settled + /// ([`dma_buf_images_again`](Self::dma_buf_images_again)), which its first move acquires + /// from `VK_QUEUE_FAMILY_FOREIGN_EXT`. Refused (`NotImplemented(RebindTextures)`) where the + /// device makes no such image there: the new import's memory type is not one the image + /// takes, the image's alignment misses its place, `remade` holds none for it, or a Metal + /// texture's pages are imported as dma-bufs. pub(super) fn rebound_alias_images( &self, watches: &[AliasWatch], pages: &HostPages, + mut remade: Remade, ) -> Result, Error> { + let dma_buf = pages.over_dma_buf(); let (memory, base) = pages.memory(); let type_index = pages.type_index(); let raw_device = self.shared().vk(); @@ -2414,32 +2687,59 @@ impl Device { continue; }; let at = base + watch.from_base; - if let Some(over) = &watch.metal { - let made = self.metal_image(image.plan(), over, watch.texture_type, memory, at)?; - let Ok(raw) = made else { + if dma_buf { + let objects = match &watch.kind { + AliasKind::Linear { .. } => remade.take(&image), + AliasKind::Metal(_) => None, + }; + let Some(objects) = objects else { return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); }; + let family = self.foreign_acquirer(); // Dropped on a later failure, the images made so far go. - swaps.push(ImageSwap::new( - Arc::clone(&image), - ImageObjects::new(self, raw), - vk::ImageLayout::UNDEFINED, - pages, - )); + swaps.push(ImageSwap::acquired(image, objects, pages, family)); continue; } + let (row_pitch, slice_pitch) = match &watch.kind { + AliasKind::Linear { + row_pitch, + slice_pitch, + } => (*row_pitch, *slice_pitch), + AliasKind::Metal(over) => { + let made = + self.metal_image(image.plan(), over, watch.texture_type, memory, at)?; + let Ok(raw) = made else { + return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); + }; + // Dropped on a later failure, the images made so far go. + swaps.push(ImageSwap::new( + Arc::clone(&image), + ImageObjects::new(self, raw), + vk::ImageLayout::UNDEFINED, + pages, + )); + continue; + } + }; let made = self.host_linear_image(image.plan())?; let Ok(LinearMade { raw, requirements, + report, initial, - .. }) = made else { return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); }; + // Its rows (and slices) must lie as the old image's did: a `DRM_FORMAT_MOD_LINEAR` + // image's are the texture's, which the driver's linear image may not take. + let plan = image.plan(); + let slices = plan.layers.max(plan.extent[2]); if requirements.memory_type_bits & (1 << type_index) == 0 || !at.is_multiple_of(requirements.alignment.max(1)) + || report.offset != 0 + || report.row_pitch != row_pitch + || (slices > 1 && report.array_pitch != slice_pitch) { // SAFETY: the image is live and unbound, and no command uses it. unsafe { release::object(raw_device, raw) }; @@ -2464,6 +2764,76 @@ impl Device { Ok(swaps) } + /// The images of the textures over a no-copy buffer's (or a no-copy heap's) bytes, made for a + /// rebind's new pages, which it imported as dma-bufs (`placement`), the bytes at `pointer`: + /// for each linear one `watches` note, a `DRM_FORMAT_MOD_LINEAR` image of its plan over the + /// one dma-buf the pages' source makes of its own pages ([`Device::dma_buf_image`]), its + /// texels as far from the new bytes' first as they were from the old's, and its rows as far + /// apart; and for each of `heap`'s textures bound to its bytes, one in the driver's layout at + /// its offset (`texture/heap.rs`). Made before the rebind settles, with no lock of the + /// runtime's held: the source is called once for each. Nothing for pages imported by their + /// pointer. Refused (`NotImplemented(RebindTextures)`), what was made released, where the + /// device makes no such image of one (`dma_buf_image`'s reasons). + #[cfg(unix)] + pub(super) fn dma_buf_images_again( + &self, + watches: &[AliasWatch], + heap: Option<&Heap>, + placement: &Placement, + pointer: NonNull, + ) -> Result { + let mut remade = Remade::default(); + let Some(imports) = placement.dma_buf_pages() else { + return Ok(remade); + }; + if let Some(heap) = heap { + let type_index = placement.type_index(); + self.dma_buf_heap_images_again(heap, imports, type_index, pointer, &mut remade)?; + } + let facts = self + .shared() + .textures + .facts(self.compile_device().profile()); + for watch in watches { + let Some(image) = watch.image.upgrade() else { + continue; + }; + // A Metal texture's rebind to dma-buf pages is refused as the swaps are made. + let AliasKind::Linear { + row_pitch, + slice_pitch, + } = watch.kind + else { + continue; + }; + let texels = crate::dma_buf::DmaBufTexels { + pages: imports, + type_index: placement.type_index(), + at: pointer.as_ptr() as u64 + watch.from_base, + row_pitch, + slice_pitch, + }; + let Ok((_, made)) = self.dma_buf_image(&[image.plan()], &facts, &texels)? else { + return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); + }; + let objects = ImageObjects::imported(self, made.raw, made.import); + remade.0.push((image, objects)); + } + Ok(remade) + } + + /// No pages are imported as dma-bufs on this system: nothing is made. + #[cfg(not(unix))] + pub(super) fn dma_buf_images_again( + &self, + _watches: &[AliasWatch], + _heap: Option<&Heap>, + _placement: &Placement, + _pointer: NonNull, + ) -> Result { + Ok(Remade::default()) + } + /// The image of `plan` for a texture of `layout` made with `descriptor` (and its hazard /// tracking mode `hazard`), checked against the device's limits for it, placed, and in the /// `GENERAL` layout. diff --git a/crates/metal2vulkan-runtime/src/texture/first_move.rs b/crates/metal2vulkan-runtime/src/texture/first_move.rs index a90b65b39..2a08bbe21 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -17,7 +17,12 @@ //! too; its image of a format a clear writes is cleared ([`FirstMove::cleared`]) rather than //! copied over, single- or multisampled. An image that takes a rebind's new `VkImage` notes that //! one's (`rebind.rs`). The image (or stand-in) is registered weakly once it is shared -//! ([`FirstMoves::register`]). A new buffer whose bytes the host cannot write (`Private`, and a +//! ([`FirstMoves::register`]). An image over a dma-buf of its own pages (`dma_buf.rs`) starts +//! `UNDEFINED` too, and its move is an acquire from `VK_QUEUE_FAMILY_FOREIGN_EXT` for the +//! device's queue family (`VK_QUEUE_FAMILY_IGNORED` where its images are concurrent among +//! several), from `GENERAL` (which keeps its bytes, as Vulkan's foreign images keep theirs only +//! through such an acquire) to `GENERAL` ([`FirstMove::acquired`]); it rests there. +//! A new buffer whose bytes the host cannot write (`Private`, and a //! `Managed` buffer's device copy) notes its fill with zeros ([`FirstFill`]) the same way //! (`Buffer::clear_first`), and a new `Private` buffer made with bytes then the copy of a staging //! buffer's (`Buffer::fill_first_from`). So do a sparse texture's image (its move; an emulated @@ -97,6 +102,9 @@ pub(crate) struct FirstMove { /// Metal's pattern over the image's first levels, which the zeros then leave /// ([`FirstMove::patterned`]). pattern: Option, + /// The queue family the move acquires the image for from `VK_QUEUE_FAMILY_FOREIGN_EXT`, an + /// image over dma-buf pages the CPU writes ([`FirstMove::acquired`]). + acquire: Option, } /// How a first move writes Metal's pattern into the first `levels` levels of its image, of @@ -208,9 +216,23 @@ impl FirstMove { zero: None, rebindable, pattern: None, + acquire: None, } } + /// The move, an acquire of the image from `VK_QUEUE_FAMILY_FOREIGN_EXT` for `family` (the + /// device's one queue family, or `VK_QUEUE_FAMILY_IGNORED` for an image concurrent among + /// several, `sharing.rs`): an image over dma-buf pages (`dma_buf.rs`), made `UNDEFINED` as + /// Vulkan makes an image of external memory, whose bytes the CPU wrote outside Vulkan. It + /// moves from `GENERAL`, the layout of the bytes as they lie, which an acquire keeps; a move + /// from `UNDEFINED` may discard them, and so may a queue family that takes an exclusive + /// image without one. + pub(crate) fn acquired(mut self, family: u32) -> FirstMove { + self.old = vk::ImageLayout::GENERAL; + self.acquire = Some(family); + self + } + /// The move, which also writes every texel `copies` reach (`zero_copies`) with zero bytes /// from `zeros`. pub(crate) fn zeroed(mut self, zeros: vk::Buffer, copies: &[ImageRegion]) -> FirstMove { @@ -486,15 +508,19 @@ impl FirstMove { exit_guard::called(Call::CmdPipelineBarrier); } - /// The barrier of the move. + /// The barrier of the move: an acquire from `VK_QUEUE_FAMILY_FOREIGN_EXT` where it is one. fn barrier(&self) -> vk::ImageMemoryBarrier<'static> { + let (source, target) = match self.acquire { + Some(family) => (vk::QUEUE_FAMILY_FOREIGN_EXT, family), + None => (vk::QUEUE_FAMILY_IGNORED, vk::QUEUE_FAMILY_IGNORED), + }; vk::ImageMemoryBarrier::default() .src_access_mask(vk::AccessFlags::MEMORY_WRITE) .dst_access_mask(vk::AccessFlags::MEMORY_READ | vk::AccessFlags::MEMORY_WRITE) .old_layout(self.old) .new_layout(vk::ImageLayout::GENERAL) - .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) - .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) + .src_queue_family_index(source) + .dst_queue_family_index(target) .image(self.image) .subresource_range(self.whole()) } diff --git a/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs b/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs index e1fdeaa4b..ce822f49b 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs @@ -20,8 +20,8 @@ use super::{Image, Owner, Storage, Texture}; use crate::buffer::MemoryHold; use crate::device::lock; use crate::{ - Device, DeviceKind, DeviceOptions, HeapDescriptor, HeapType, Region, ResourceOptions, - ShaderCacheOptions, TextureDescriptor, + Device, DeviceKind, DeviceOptions, HeapDescriptor, HeapType, HostMemory, Region, + ResourceOptions, ShaderCacheOptions, TextureDescriptor, }; use metal2vulkan::metal::PixelFormat; use std::alloc::Layout; @@ -139,7 +139,12 @@ fn a_waiting_move_of_an_image_a_detach_let_go_of_is_dropped() { let device = device(&scratch.0); // SAFETY: the memory outlives the device (dropped after it), and nothing else uses it. let made = unsafe { - device.new_buffer_with_bytes_no_copy(host.0, BYTES as u64, ResourceOptions::shared(), None) + device.new_buffer_with_bytes_no_copy( + HostMemory::new(host.0), + BYTES as u64, + ResourceOptions::shared(), + None, + ) }; let Ok(buffer) = made else { eprintln!( @@ -184,7 +189,9 @@ fn a_host_copy_makes_the_waiting_move_of_an_image_over_host_pages() { let heap_descriptor = HeapDescriptor::new(HeapType::Automatic, BYTES as u64, ResourceOptions::shared()); // SAFETY: the memory outlives the device (dropped after it), and nothing else uses it. - let made = unsafe { device.new_heap_with_bytes_no_copy(host.0, &heap_descriptor, None, None) }; + let made = unsafe { + device.new_heap_with_bytes_no_copy(HostMemory::new(host.0), &heap_descriptor, None, None) + }; let Ok(heap) = made else { eprintln!( "first move lifetimes: no heap over host memory on {}", diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index 8f6e8d919..7976f761c 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -143,7 +143,7 @@ use super::heap_two_planes::{HeapPlaneCopies, TwoPlaneHeapLayout}; use super::stand_in::StandIn; use super::{ copy_units, image_aspects, image_error, DetachedImage, IdUse, Image, ImageObjects, - ImagePlacement, ImageSwap, Owner, Raw, Storage, Texture, TextureDescriptor, ViewRecord, + ImagePlacement, ImageSwap, Owner, Raw, Remade, Storage, Texture, TextureDescriptor, ViewRecord, }; use crate::address::ObjectsToken; use crate::buffer::{ @@ -750,6 +750,12 @@ fn initial_layout(tiling: vk::ImageTiling) -> vk::ImageLayout { } } +/// Whether a heap texture's image of `tiling` lays its rows out linearly (`Image::linear`): linear +/// tiling, or `DRM_FORMAT_MOD_LINEAR`'s, the one modifier a heap's image takes (`dma_buf.rs`). +fn linear_tiling(tiling: vk::ImageTiling) -> bool { + tiling == vk::ImageTiling::LINEAR || tiling == vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT +} + /// Metal's answer for a texture buffer of `layout` in a heap (CRF heap probe 1, an M3 Max and an /// M4 alike): its row of texels exactly, at a multiple of 16 bytes /// (`minimumTextureBufferAlignmentForPixelFormat:`, `LINEAR_ALIGNMENT`) for every format and @@ -1682,6 +1688,12 @@ impl Device { /// buffer), or ask a dedicated allocation (RADV). Elsewhere, and for a texture with a depth /// twin, `NotImplemented(HeapTextureMemory)`. /// + /// Over pages imported as dma-bufs (`dma_buf.rs`, where the device refused their pointer), + /// where the linear image would be: an image of the driver's `DRM_FORMAT_MOD_LINEAR` layout at + /// the texture's offset, bound to a dedicated import of a dma-buf of its own pages, where its + /// bytes and alignment fit the answer ([`dma_buf_heap_plan`](Self::dma_buf_heap_plan)); else, + /// and where it is not made after all as the texture is, the shadow, counted and announced. + /// /// A texture of a plain format Metal lays out tiled (`HeapLayout::Tiled`) is a shadow of its /// elements tiled in the heap's bytes (`AliasRoute::Tiled`, `heap_tiled.rs`), where its optimal /// image takes copies and the moves fit the device; elsewhere it takes the routes above, @@ -1744,7 +1756,6 @@ impl Device { .shared() .textures .facts(self.compile_device().profile()); - let texture_type = p.layout.texture_type; let (linear, _) = plan_texture_images(&p.layout, descriptor.image_usage(), false, &facts) .map_err(|refusal| image_error(call, refusal))?; let SizeAndAlign { size, align } = p.size_and_align; @@ -1752,6 +1763,15 @@ impl Device { // one over it (MoltenVK: Metal makes no depth texture over a buffer). let driver = &self.properties().driver_facts; let apart = !colour(&linear) && driver.contains(&DriverFact::DepthStencilImagesLieApart); + // Over pages imported as dma-buf memory (`dma_buf.rs`), an image of the driver's + // `DRM_FORMAT_MOD_LINEAR` layout, bound to a dedicated import of a dma-buf of its own + // pages as the texture is made (`heap_texture_at`), where it fits the answer; else the + // shadow below, counted and announced. + let dma_buf = bytes.over_dma_buf(); + if !apart && dma_buf { + let image = self.dma_buf_heap_plan(linear, &p, &facts)?; + return Ok(HeapPlan { image, ..p }); + } if !apart && linear_lack(&linear, &facts).is_none() { let tiling = vk::ImageTiling::LINEAR; if let Some(requirements) = self.host_image_requirements(&linear)? { @@ -1769,17 +1789,177 @@ impl Device { } } } - let optimal = self.with_free_usage(linear, texture_type)?; - if !shadowable(&optimal, size) { + let image = self.memory_shadow(linear, &p)?; + Ok(HeapPlan { image, ..p }) + } + + /// The image of a texture of plan `p` in a heap over pages imported as dma-buf memory + /// (`dma_buf.rs`), `linear` its plan: an image of the driver's `DRM_FORMAT_MOD_LINEAR` layout + /// ([`Device::dma_buf_natural_layout`]) at the texture's offset, made and bound to a dedicated + /// import of a dma-buf of its own pages as the texture is made (`heap_texture_at`), where the + /// device makes one of the plan and its bytes and alignment fit the heap's answer; else a + /// shadow of the heap's bytes ([`dma_buf_heap_shadow`](Self::dma_buf_heap_shadow)). + #[cfg(unix)] + fn dma_buf_heap_plan( + &self, + linear: ImagePlan, + p: &HeapPlan, + facts: &crate::image_plan::ImageFacts<'_>, + ) -> Result { + let SizeAndAlign { size, align } = p.size_and_align; + let why = match self.dma_buf_natural_layout(&linear, facts)? { + Ok(natural) if natural.size <= size && natural.alignment <= align => { + return Ok(HeapImage { + plan: linear, + tiling: vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT, + // The optimal image's, which its shadow takes where none is made. + requirements: p.image.requirements, + route: AliasRoute::Direct, + }); + } + Ok(natural) => format!( + "the driver's DRM_FORMAT_MOD_LINEAR image of it takes {} bytes at an alignment \ + of {}, past the {size} at {align} the heap answers", + natural.size, natural.alignment + ), + Err(why) => why, + }; + self.dma_buf_heap_shadow(linear, p, why) + } + + /// No pages are imported as dma-bufs on this system: the shadow, as before. + #[cfg(not(unix))] + fn dma_buf_heap_plan( + &self, + linear: ImagePlan, + p: &HeapPlan, + _facts: &crate::image_plan::ImageFacts<'_>, + ) -> Result { + self.memory_shadow(linear, p) + } + + /// The image of a texture of plan `p` whose route is a `DRM_FORMAT_MOD_LINEAR` image over + /// dma-buf pages ([`dma_buf_heap_plan`](Self::dma_buf_heap_plan)), at `offset` of the heap + /// whose buffer is `bytes`: made in the driver's layout and bound to a dedicated import of + /// the dma-buf the pages' source makes of its own pages ([`Device::dma_buf_image`]), with no + /// lock of the runtime's held. Where none is made, `p` takes the shadow of the heap's bytes + /// instead ([`dma_buf_heap_shadow`](Self::dma_buf_heap_shadow)), and nothing is answered. + #[cfg(unix)] + fn made_dma_buf_heap_image( + &self, + bytes: &Buffer, + p: &mut HeapPlan, + offset: u64, + ) -> Result, Error> { + let pages = bytes.host_pages(); + let facts = self + .shared() + .textures + .facts(self.compile_device().profile()); + let made = match pages.as_deref().and_then(HostPages::dma_buf) { + None => Err("the heap's bytes lie in no dma-buf pages".to_owned()), + Some((imports, start, type_index)) => { + let pages = (&**imports, type_index, start + offset); + let size = p.size_and_align.size; + self.dma_buf_heap_image(&p.image.plan, &facts, pages, size)? + } + }; + let why = match made { + Ok(made) => return Ok(Some(made)), + Err(why) => why, + }; + p.image = self.dma_buf_heap_shadow(p.image.plan.clone(), p, why)?; + Ok(None) + } + + /// The image of a heap texture of `plan` (viewed as `facts` says) in the driver's + /// `DRM_FORMAT_MOD_LINEAR` layout ([`Device::dma_buf_natural_layout`]), where it takes no more + /// than the texture's `size` bytes, over the one dma-buf the pages' source makes of its own + /// pages ([`Device::dma_buf_image`]): `pages` are the heap's imports, their memory type and + /// the host address of the texture's first byte. Why not, where none is made. + #[cfg(unix)] + fn dma_buf_heap_image( + &self, + plan: &ImagePlan, + facts: &crate::image_plan::ImageFacts<'_>, + (pages, type_index, at): (&crate::dma_buf::DmaBufPages, u32, u64), + size: u64, + ) -> Result, Error> { + let natural = match self.dma_buf_natural_layout(plan, facts)? { + Ok(natural) if natural.size <= size => natural, + Ok(natural) => { + let taken = natural.size; + let why = format!("the driver's image of it takes {taken} bytes, past its {size}"); + return Ok(Err(why)); + } + Err(why) => return Ok(Err(why)), + }; + let texels = crate::dma_buf::DmaBufTexels { + pages, + type_index, + at, + row_pitch: natural.row_pitch, + slice_pitch: natural.slice_pitch, + }; + Ok((self.dma_buf_image(&[plan], facts, &texels)?).map(|(_, made)| made)) + } + + /// No pages are imported as dma-bufs on this system: never reached. + #[cfg(not(unix))] + fn made_dma_buf_heap_image( + &self, + _bytes: &Buffer, + _p: &mut HeapPlan, + _offset: u64, + ) -> Result, Error> { + Err(internal( + "a heap texture over dma-buf pages on a system of none", + )) + } + + /// The image of a texture of plan `p` in a heap over host pages that is a shadow of the heap's + /// bytes in memory of its own (`AliasRoute::MemoryShadow`): `linear`'s plan as an optimal + /// image with the runtime's free usage, where Vulkan copies it to and from the bytes (one + /// sample) and its planes fit the answered size; else `NotImplemented(HeapTextureMemory)`. + fn memory_shadow(&self, linear: ImagePlan, p: &HeapPlan) -> Result { + let optimal = self.with_free_usage(linear, p.layout.texture_type)?; + if !shadowable(&optimal, p.size_and_align.size) { return Err(Error::NotImplemented(RuntimeGap::HeapTextureMemory)); } - let image = HeapImage { + Ok(HeapImage { plan: optimal, tiling: vk::ImageTiling::OPTIMAL, requirements: p.image.requirements, route: AliasRoute::MemoryShadow, - }; - Ok(HeapPlan { image, ..p }) + }) + } + + /// [`memory_shadow`](Self::memory_shadow)'s image for a texture of plan `p` in a heap over + /// pages imported as dma-buf memory, of which no image over a dma-buf of its own pages is made + /// for `why` (`dma_buf.rs`): counted (`WorkCounts::dma_buf_image_fallbacks`) and announced + /// once per device (`shadowed-texture`). + fn dma_buf_heap_shadow( + &self, + linear: ImagePlan, + p: &HeapPlan, + why: String, + ) -> Result { + let image = self.memory_shadow(linear, p)?; + self.shared().counts.dma_buf_image_fell_back(); + let layout = &p.layout; + self.degrade(Degradation::ShadowedTexture, || { + let [width, height, depth] = layout.extent; + let object = format!( + "a {:?} {:?} texture of {width}x{height}x{depth} in a heap", + layout.pixel_format, layout.texture_type + ); + let why = format!( + "the heap's host pages are imported as dma-buf memory, and {why}: its image is \ + a shadow of the heap's bytes" + ); + (object, why) + }); + Ok(image) } /// The image of a texture of plan `p` laid out as `tiled` in a heap over host pages @@ -1874,7 +2054,7 @@ impl Device { size: u64, owner: Owner, ) -> Result { - let (raw, initial) = self.heap_raw_image( + let made = self.heap_raw_image( &image.plan, image.tiling, binding.host, @@ -1882,6 +2062,9 @@ impl Device { at, size, )?; + let (raw, initial) = made.ok_or_else(|| { + internal("a heap texture's image does not lie where its plan placed it") + })?; let made = Image { device: self.clone(), raw: Raw::new(raw), @@ -1898,7 +2081,7 @@ impl Device { detached: Mutex::new(None), first_move: Mutex::new(None), host_copies: false, - linear: image.tiling == vk::ImageTiling::LINEAR, + linear: linear_tiling(image.tiling), staging_copies: false, objects: ObjectsToken::default(), }; @@ -1937,7 +2120,7 @@ impl Device { })), first_move: Mutex::new(None), host_copies: false, - linear: image.tiling == vk::ImageTiling::LINEAR, + linear: linear_tiling(image.tiling), staging_copies: false, objects: ObjectsToken::default(), } @@ -1945,7 +2128,8 @@ impl Device { /// A `VkImage` of `plan` and `tiling` (made for host allocations where `host`) bound at `at` /// of `memory`, whose requirements hold at most `size` bytes there, with the layout it - /// starts in, for its caller to move to `GENERAL`. + /// starts in, for its caller to move to `GENERAL`; `None`, nothing made, where its + /// requirements do not (its alignment misses `at`, or it takes more bytes). fn heap_raw_image( &self, plan: &ImagePlan, @@ -1954,7 +2138,7 @@ impl Device { memory: vk::DeviceMemory, at: u64, size: u64, - ) -> Result<(vk::Image, vk::ImageLayout), Error> { + ) -> Result, Error> { let raw_device = self.shared().vk(); let view_formats = plan.ash_view_formats(); let mut list = vk::ImageFormatListCreateInfo::default(); @@ -1983,9 +2167,7 @@ impl Device { if !at.is_multiple_of(requirements.alignment.max(1)) || requirements.size > size { // SAFETY: the image is live and unbound, and no command uses it. unsafe { release::object(raw_device, raw) }; - return Err(internal( - "a heap texture's image does not lie where its plan placed it", - )); + return Ok(None); } // SAFETY: the image is live and unbound; the memory is the heap's, which the texture // holds, of a type the image takes (`new_heap_texture`, `host_heap_plan`), at an offset @@ -1995,22 +2177,29 @@ impl Device { unsafe { release::object(raw_device, raw) }; return Err(vulkan(error)); } - Ok((raw, initial)) + Ok(Some((raw, initial))) } /// The images of `heap`'s live textures bound to its bytes, re-made over a rebind's new - /// pages, `pages` (`rebind.rs`): each - /// the same plan, linear and made for host allocations as `host_heap_plan` made it, bound at - /// the texture's offset; swapped in once the rebind is made, the device's next submission - /// that names it moving it to `GENERAL`. A texture held as a shadow of the heap's bytes, or a - /// texture buffer, takes none: the one's copies and the other's views read the heap's buffer as - /// they are recorded or made. + /// pages, `pages` (`rebind.rs`): each the same plan, bound at the texture's offset; swapped in + /// once the rebind is made, the device's next submission that names it moving it to + /// `GENERAL`. Over pages imported by their pointer, linear and made for host allocations as + /// `host_heap_plan` made it; over pages imported as dma-bufs (`dma_buf.rs`), the + /// `DRM_FORMAT_MOD_LINEAR` image `remade` holds for it, made before the rebind settled + /// ([`Device::dma_buf_images_again`]), which its first move acquires from + /// `VK_QUEUE_FAMILY_FOREIGN_EXT`. A texture held as a shadow of the heap's bytes, or a texture + /// buffer, takes none: the one's copies and the other's views read the heap's buffer as they + /// are recorded or made. Refused (`NotImplemented(RebindTextures)`) where no such image is made + /// for a texture bound to the bytes: `remade` holds none for it, or the image made for host + /// allocations does not lie in its place (one made over dma-buf pages before). pub(crate) fn rebound_heap_images( &self, heap: &Heap, pages: &HostPages, + remade: &mut Remade, ) -> Result, Error> { let (memory, base) = pages.memory(); + let dma_buf = pages.over_dma_buf(); let (textures, _) = heap.textures_from(0); let mut swaps: Vec = Vec::new(); for texture in &textures { @@ -2023,7 +2212,26 @@ impl Device { if swaps.iter().any(|swap| swap.is_of(image)) { continue; } - let (raw, initial) = self.heap_raw_image( + if dma_buf { + let Some(objects) = remade.take(image) else { + return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); + }; + let family = self.foreign_acquirer(); + // Dropped on a later failure, the images made so far go. + swaps.push(ImageSwap::acquired( + Arc::clone(image), + objects, + pages, + family, + )); + continue; + } + // An image over dma-buf pages lies in the layout the driver gives a + // `DRM_FORMAT_MOD_LINEAR` image, which its linear image need not keep. + if image.raw.dedicated() { + return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); + } + let made = self.heap_raw_image( image.plan(), vk::ImageTiling::LINEAR, true, @@ -2031,6 +2239,9 @@ impl Device { base + place.offset, place.size, )?; + let Some((raw, initial)) = made else { + return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); + }; // Dropped on a later failure, the images made so far go. swaps.push(ImageSwap::new( Arc::clone(image), @@ -2042,6 +2253,46 @@ impl Device { Ok(swaps) } + /// The images of `heap`'s live textures bound to its bytes, made for a rebind's new pages, + /// which it imported as dma-bufs (`imports`, of memory type `type_index`), the heap's bytes at + /// `pointer`, into `remade`: for each, a `DRM_FORMAT_MOD_LINEAR` image of its plan in the + /// driver's layout ([`Device::dma_buf_natural_layout`]) at its offset, over the one dma-buf the + /// pages' source makes of its own pages ([`Device::dma_buf_image`]). With no lock of the + /// runtime's held, as the source is called once for each. Refused + /// (`NotImplemented(RebindTextures)`) where the device makes no such image of one. + #[cfg(unix)] + pub(super) fn dma_buf_heap_images_again( + &self, + heap: &Heap, + imports: &crate::dma_buf::DmaBufPages, + type_index: u32, + pointer: NonNull, + remade: &mut Remade, + ) -> Result<(), Error> { + let facts = self + .shared() + .textures + .facts(self.compile_device().profile()); + let (textures, _) = heap.textures_from(0); + for texture in &textures { + let Storage::Image(image) = &texture.0.storage else { + continue; + }; + let Owner::Heap(place) = &image.owner else { + continue; + }; + if remade.0.iter().any(|(made, _)| Arc::ptr_eq(made, image)) { + continue; + } + let pages = (imports, type_index, pointer.as_ptr() as u64 + place.offset); + let made = self.dma_buf_heap_image(image.plan(), &facts, pages, place.size)?; + let made = made.map_err(|_| Error::NotImplemented(RuntimeGap::RebindTextures))?; + let objects = ImageObjects::imported(self, made.raw, made.import); + remade.0.push((Arc::clone(image), objects)); + } + Ok(()) + } + /// The texture of plan `p` bound at `place` of its heap, whose buffer is `bytes`, with /// `options` (the heap's), in the `GENERAL` layout and holding what its bytes held; its depth /// twin, where it has one, inside the same range. @@ -2072,6 +2323,16 @@ impl Device { identity: bytes.identity(), host: bytes.caller_memory() == Some(CallerMemory::HostPages), }; + // Over dma-buf pages the image of the driver's `DRM_FORMAT_MOD_LINEAR` layout is made + // here, its pages' source called once; where none is, the texture is a shadow of the + // heap's bytes, as it was before such images. + let mut p = p; + let dma_buf_image = match p.image.tiling == vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT { + true if stand_in.is_none() => { + self.made_dma_buf_heap_image(bytes, &mut p, place.offset)? + } + _ => None, + }; let twin = p.twin; let route = p.image.route; let twin_route = twin.as_ref().map(|(twin, _)| twin.route); @@ -2118,11 +2379,19 @@ impl Device { *lock(&place.memory) = bytes.memory_hold(); let owner = Owner::Heap(Box::new(place)); let image_size = twin.as_ref().map_or(size, |&(_, offset)| offset); - let mut image = match &stand_in { - Some(stand_in) => { + let mut image = match (&stand_in, dma_buf_image) { + (Some(stand_in), _) => { self.detached_heap_image(&binding, p.image, owner, Arc::clone(stand_in)) } - None => self.bind_heap_image(&binding, p.image, at, image_size, owner)?, + #[cfg(unix)] + (None, Some(made)) => self.dma_buf_texture_image( + made, + p.image.plan, + owner, + (binding.options, binding.allow_gpu_optimized_contents), + binding.identity, + ), + _ => self.bind_heap_image(&binding, p.image, at, image_size, owner)?, }; if let Some((twin, offset)) = twin { let twin_size = size - offset; diff --git a/crates/metal2vulkan-runtime/src/texture/storage_form.rs b/crates/metal2vulkan-runtime/src/texture/storage_form.rs index 8a74a15aa..7dfc58cd0 100644 --- a/crates/metal2vulkan-runtime/src/texture/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/texture/storage_form.rs @@ -78,7 +78,6 @@ use crate::tracker::Access; use crate::values::StorageMode; use crate::Device; use ash::vk; -use ash::vk::Handle; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, Weak}; use std::time::{Duration, Instant}; @@ -446,11 +445,10 @@ impl Prepared { return None; } image.views_go(); - let first = image - .raw - .0 - .swap(swapped.objects.raw.as_raw(), Ordering::AcqRel); - swapped.objects.raw = vk::Image::from_raw(first); + let objects = &mut swapped.objects; + let (first, import) = image.raw.swap(objects.raw, objects.import.take()); + objects.raw = first; + objects.import = import; swapped .objects .views diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index a304496a1..9d940b0eb 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -79,6 +79,10 @@ pub(crate) struct Counters { linear_passes_through_copies: AtomicU64, draw_states_recorded: AtomicU64, host_deallocators_delayed: AtomicU64, + dma_buf_imports: AtomicU64, + dma_buf_sparse_buffers: AtomicU64, + dma_buf_images: AtomicU64, + dma_buf_image_fallbacks: AtomicU64, replay_logs_kept: AtomicU64, replay_log_bytes: AtomicU64, encoders_reencoded: AtomicU64, @@ -415,6 +419,31 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// `chunks` chunks of host pages a caller's source made were imported as dma-buf memory, and + /// a buffer bound in them, where the device refused the pages' pointer (`dma_buf.rs`). + pub(crate) fn dma_buf_imported(&self, chunks: usize) { + self.dma_buf_imports + .fetch_add(chunks as u64, Ordering::Relaxed); + } + + /// A no-copy buffer's (or heap's, or rebind's) `VkBuffer` was assembled from several chunks' + /// imports as a sparse buffer (`dma_buf.rs`). + pub(crate) fn dma_buf_sparse_buffer_made(&self) { + self.dma_buf_sparse_buffers.fetch_add(1, Ordering::Relaxed); + } + + /// A texture's image over dma-buf pages was made and bound to a dedicated import of a dma-buf + /// of its own pages (`dma_buf.rs`). + pub(crate) fn dma_buf_image_made(&self) { + self.dma_buf_images.fetch_add(1, Ordering::Relaxed); + } + + /// A texture over dma-buf pages that such an image would alias took the path of a texture + /// over memory no image aliases instead: the device made no such image of it (`dma_buf.rs`). + pub(crate) fn dma_buf_image_fell_back(&self) { + self.dma_buf_image_fallbacks.fetch_add(1, Ordering::Relaxed); + } + /// A command buffer kept an ended encoder's log of `bytes` bytes (`replay.rs`). pub(crate) fn replay_log_kept(&self, bytes: usize) { self.replay_logs_kept.fetch_add(1, Ordering::Relaxed); @@ -737,6 +766,23 @@ pub struct WorkCounts { /// it runs once the import is freed (`host-deallocator-delayed`). With a keep-alive the /// deallocator runs at the release, and none is counted. pub host_deallocators_delayed: u64, + /// Chunks of host pages imported as dma-buf memory from a caller's source + /// (`HostMemory::with_dma_buf`), where the device refused the pages' pointer: no-copy + /// buffers', heaps' and rebinds' alike, one per chunk. None where every pointer was imported. + pub dma_buf_imports: u64, + /// Of those buffers, heaps and rebinds, the ones whose `VkBuffer` is a sparse buffer + /// assembled from several chunks. + pub dma_buf_sparse_buffers: u64, + /// Images of textures over such dma-buf memory (over a no-copy buffer, placed in a no-copy + /// heap, a view of either), each a `DRM_FORMAT_MOD_LINEAR` image bound to a dedicated import + /// of a dma-buf of its own pages from the caller's source, aliasing the buffer's bytes: one per + /// image made, a rebind's too. Not counted in `dma_buf_imports`. + pub dma_buf_images: u64, + /// Textures over such dma-buf memory that such an image would alias but the device made none + /// (the source failed, the format, usage, extent or plane layout is not supported, or the + /// driver refused the import): each takes the path of a texture over memory no image aliases + /// (`shadowed-texture`). + pub dma_buf_image_fallbacks: u64, /// Ended compute and blit encoders whose logs their command buffers kept, as a rebind before /// the first submission may encode them again (`replay.rs`), and the bytes of those logs. pub replay_logs_kept: u64, @@ -865,6 +911,10 @@ impl Device { .load(Ordering::Relaxed), draw_states_recorded: counters.draw_states_recorded.load(Ordering::Relaxed), host_deallocators_delayed: counters.host_deallocators_delayed.load(Ordering::Relaxed), + dma_buf_imports: counters.dma_buf_imports.load(Ordering::Relaxed), + dma_buf_sparse_buffers: counters.dma_buf_sparse_buffers.load(Ordering::Relaxed), + dma_buf_images: counters.dma_buf_images.load(Ordering::Relaxed), + dma_buf_image_fallbacks: counters.dma_buf_image_fallbacks.load(Ordering::Relaxed), replay_logs_kept: counters.replay_logs_kept.load(Ordering::Relaxed), replay_log_bytes: counters.replay_log_bytes.load(Ordering::Relaxed), encoders_reencoded: counters.encoders_reencoded.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index f322d2f2f..7f610f11c 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -6d54d007da67eae179542f08d224b2b404eb7835fd4d5414689bb9a93b15fbc9 +291c83b9334b98ab0a1078a1b5048196afc2ce23fe0062ee8949a8d89b1179b3 diff --git a/crates/metal2vulkan-validation/src/parity/sequences/runtime.rs b/crates/metal2vulkan-validation/src/parity/sequences/runtime.rs index 66c353de3..d6faad5bb 100644 --- a/crates/metal2vulkan-validation/src/parity/sequences/runtime.rs +++ b/crates/metal2vulkan-validation/src/parity/sequences/runtime.rs @@ -24,9 +24,9 @@ use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ BlitCommandEncoder, BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus, CommandQueue, ComputeCommandEncoder, ComputePipelineState, DebugMessage, Device, EventRef, - Fence, Heap, HeapDescriptor, HeapType, Library, LoadAction, Origin, PipelineOptions, - RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, ResourceOptions, SharedEvent, - Size, StoreAction, Texture, TextureDescriptor, + Fence, Heap, HeapDescriptor, HeapType, HostMemory, Library, LoadAction, Origin, + PipelineOptions, RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, + ResourceOptions, SharedEvent, Size, StoreAction, Texture, TextureDescriptor, }; use std::cell::{Cell, RefCell}; use std::collections::BTreeSet; @@ -202,7 +202,7 @@ impl SeqApi for RuntimeSeq { // SAFETY: the caller's contract, `HostMemory::new`'s. unsafe { self.device - .new_buffer_with_bytes_no_copy(bytes, length, options, None) + .new_buffer_with_bytes_no_copy(HostMemory::new(bytes), length, options, None) } .map_err(refused) } diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index e20e6c89c..4ba21f0e9 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -231,6 +231,8 @@ mod device_lockstep; mod discard_counts; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod discard_hoist; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] +mod dma_buf_imports; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod dont_care_stores; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index 3df4799e4..a5bd59dee 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -205,7 +205,7 @@ use metal2vulkan::Budget; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ BlitOption, CpuCacheMode, DebugMessage, Degradation, DegradationCategory, Device, - DeviceOptions, DriverSetting, Error, HazardTrackingMode, HeapDescriptor, HeapType, + DeviceOptions, DriverSetting, Error, HazardTrackingMode, HeapDescriptor, HeapType, HostMemory, LayerSetting, LayerSettingValue, LoadAction, MessageSeverity, MetalLevel, MultisampleStencilResolveFilter, Origin, PipelineOptions, RenderPassDescriptor, ResourceOptions, RuntimeGap, Size, StorageMode, StoreAction, TextureDescriptor, @@ -753,7 +753,12 @@ fn the_private_option_bit_is_ignored_once() { let memory = Mapping::anonymous(GUEST_PAGE); // SAFETY: the mapping outlives the buffer, which is dropped first. let no_copy = unsafe { - device.new_buffer_with_bytes_no_copy(memory.pointer(), GUEST_PAGE as u64, shared, None) + device.new_buffer_with_bytes_no_copy( + HostMemory::new(memory.pointer()), + GUEST_PAGE as u64, + shared, + None, + ) }; match no_copy { Err(error) if not_importable(&error) => {} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/detach.rs b/crates/metal2vulkan-validation/src/runtime_lane/detach.rs index 37133f38c..cb3cb936a 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/detach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/detach.rs @@ -41,9 +41,9 @@ use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ Buffer, ClearColor, CommandBuffer, CommandBufferError, CommandBufferStatus, CommandQueue, - Degradation, Device, Error, EventRef, Heap, HeapDescriptor, HeapType, Invalid, LoadAction, - PipelineOptions, Problem, RebindProblem, Region, RenderPassDescriptor, ResourceOptions, - SharedEvent, StoreAction, TextureDescriptor, + Degradation, Device, Error, EventRef, Heap, HeapDescriptor, HeapType, HostMemory, Invalid, + LoadAction, PipelineOptions, Problem, RebindProblem, Region, RenderPassDescriptor, + ResourceOptions, SharedEvent, StoreAction, TextureDescriptor, }; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -535,7 +535,7 @@ fn large_heap(device: &Device) -> Option<(Heap, Buffer)> { // SAFETY: the deallocator releases the mapping once the heap's pages go. let made = unsafe { device.new_heap_with_bytes_no_copy( - pointer, + HostMemory::new(pointer), &descriptor, Some(recording(&seen, mapping)), None, @@ -573,7 +573,7 @@ fn a_detach_of_a_large_heap_allocates_no_device_memory() { // SAFETY: the deallocator releases the mapping once the buffer's pages go. let large = unsafe { device.new_buffer_with_bytes_no_copy( - pointer, + HostMemory::new(pointer), LARGE as u64, ResourceOptions::default(), Some(recording(&seen, mapping)), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs new file mode 100644 index 000000000..993054ae0 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs @@ -0,0 +1,1791 @@ +//! Device tests of no-copy imports whose pointer the device refuses, made through dma-bufs of +//! their pages (`HostMemory::with_dma_buf`), on the device the cfg selects, under the validation +//! layer (each test fails on any message the layer reports). +//! +//! The memory is guest RAM as QEMU's `memory-backend-memfd,share=on` makes it: a `memfd` sealed +//! against growing and shrinking (`F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL`) and mapped shared, +//! with views that map pieces of the file contiguously, as a consumer gathers a guest object's +//! pages. The CPU writes and reads through the file's own whole mapping, the GPU through the +//! buffer over a view. Each test makes its dma-bufs itself, `udmabuf`s of the file pieces behind +//! the pages the runtime asks for (`/dev/udmabuf`, `UDMABUF_CREATE_LIST`), split where the request +//! allows to keep each within the host's udmabuf limits, which the tests read and never change, +//! and padded, where several chunks are made, with a scratch page of the file's that no view maps, +//! as a consumer does: the runtime runs no udmabuf code. +//! +//! RADV refuses the pointer of such memory and imports the chunks, which the runtime counts +//! (`WorkCounts::dma_buf_imports`, and `dma_buf_sparse_buffers` for a buffer of several), and +//! makes each texture over them an image of `DRM_FORMAT_MOD_LINEAR` over a dma-buf of its own +//! pages, which it asks the source for too (`dma_buf_images`), or its shadow where it makes none +//! (`dma_buf_image_fallbacks`); NVIDIA and lavapipe import the pointer, never call the source and +//! count nothing. A driver not measured has its answers printed. Where `/dev/udmabuf` cannot be +//! opened each test says so and passes without running. + +use super::first_use::{read_mark, release, scheduled, Busy, ENDED}; +use super::host_memory::{ + counting, gpu_fill, gpu_read, host_page, not_importable, on_device, run, Mapping, +}; +use super::no_copy_heaps::{ + blit_into, blit_texels, encode_texels_in, encode_texels_out, shared, staged, +}; +use super::{read_buffer, validated_device, Messages, ScratchCache}; +use crate::gpu::TEST_DEVICE; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan::vk::DriverId; +use metal2vulkan_runtime::{ + BlitOption, Buffer, CommandBuffer, CommandQueue, Degradation, Device, DmaBufChunk, + DmaBufRequest, DmaBufSource, Error, EventRef, Heap, HeapDescriptor, HeapType, HostMemory, + Origin, Problem, ResourceOptions, RuntimeGap, Size, TextureDescriptor, +}; +use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd}; +use std::ptr::NonNull; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// `struct udmabuf_create_item` of Linux's `include/uapi/linux/udmabuf.h`. +#[repr(C)] +struct CreateItem { + memfd: u32, + pad: u32, + offset: u64, + size: u64, +} + +/// `struct udmabuf_create_list` of the same header, its items following it. +#[repr(C)] +struct CreateList { + flags: u32, + count: u32, +} + +const _: () = assert!(size_of::() == 24 && size_of::() == 8); + +/// `UDMABUF_FLAGS_CLOEXEC`. +const UDMABUF_FLAGS_CLOEXEC: u32 = 0x01; + +/// `UDMABUF_CREATE_LIST`, `_IOW('u', 0x43, struct udmabuf_create_list)` in the generic ioctl +/// encoding. +const UDMABUF_CREATE_LIST: u64 = + (1 << 30) | ((size_of::() as u64) << 16) | ((b'u' as u64) << 8) | 0x43; + +/// The udmabuf device. +const UDMABUF: &str = "/dev/udmabuf"; + +/// Where the kernel states udmabuf's limits. +const PARAMETERS: &str = "/sys/module/udmabuf/parameters"; + +/// udmabuf's limits on this host, read (never changed): the most items one list takes +/// (`list_limit`, 1024 by default) and the most bytes one dma-buf holds (`size_limit_mb`, 64 MiB +/// by default). The defaults where the module states none. +#[derive(Clone, Copy, Debug)] +struct Limits { + items: usize, + bytes: u64, +} + +impl Limits { + fn of_host() -> Limits { + let read = |name: &str| -> Option { + std::fs::read_to_string(format!("{PARAMETERS}/{name}")) + .ok()? + .trim() + .parse() + .ok() + }; + Limits { + items: read("list_limit").map_or(1024, |items| items as usize), + bytes: read("size_limit_mb").unwrap_or(64) << 20, + } + } +} + +/// A dma-buf of the pieces `(offset, size)` of `memfd`, in order (`UDMABUF_CREATE_LIST`). +fn udmabuf(memfd: BorrowedFd<'_>, pieces: &[(u64, u64)]) -> std::io::Result { + let device = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(UDMABUF)?; + let count = u32::try_from(pieces.len()).map_err(std::io::Error::other)?; + let memfd = u32::try_from(memfd.as_raw_fd()).map_err(std::io::Error::other)?; + // The list's head, then its items, in words aligned for both. + let mut words = vec![0u64; 1 + 3 * pieces.len()]; + // SAFETY: `words` holds the head and `count` items, each at an 8-byte-aligned word. + unsafe { + let head = words.as_mut_ptr().cast::(); + head.write(CreateList { + flags: UDMABUF_FLAGS_CLOEXEC, + count, + }); + let items = words.as_mut_ptr().add(1).cast::(); + for (index, &(offset, size)) in pieces.iter().enumerate() { + items.add(index).write(CreateItem { + memfd, + pad: 0, + offset, + size, + }); + } + } + // SAFETY: the list lives for the call, and the kernel reads its head and `count` items. + let fd = unsafe { libc::ioctl(device.as_raw_fd(), UDMABUF_CREATE_LIST as _, words.as_ptr()) }; + if fd < 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: the ioctl returned a new descriptor, this caller's. + Ok(unsafe { OwnedFd::from_raw_fd(fd) }) +} + +/// Whether this process can make a udmabuf; printed, as the test's skip, where it cannot. +fn udmabuf_openable(test: &str) -> bool { + match std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(UDMABUF) + { + Ok(_) => true, + Err(error) => { + eprintln!("{test}: SKIPPED: {UDMABUF} cannot be opened ({error})"); + false + } + } +} + +/// Guest RAM: a sealed `memfd` of `len` bytes and one scratch page past them, which no view maps +/// and which pads a source's last chunk where it makes several; and the file's own whole shared +/// mapping of the `len` bytes. +struct Memfd { + fd: OwnedFd, + len: usize, + whole: View, +} + +/// What a test's source saw: each request, with the number of chunks it answered (0 for an +/// `Err`). +type Calls = Arc>>; + +impl Memfd { + fn new(len: usize) -> Memfd { + // SAFETY: a new anonymous file, owned at once. + let fd = unsafe { + let fd = libc::memfd_create( + c"m2v-guest-ram".as_ptr(), + libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING, + ); + assert!(fd >= 0, "memfd_create: {}", std::io::Error::last_os_error()); + OwnedFd::from_raw_fd(fd) + }; + let file = len + host_page(); + // SAFETY: the descriptor is this object's. + unsafe { + assert_eq!(libc::ftruncate(fd.as_raw_fd(), file as libc::off_t), 0); + let seals = libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL; + assert_eq!(libc::fcntl(fd.as_raw_fd(), libc::F_ADD_SEALS, seals), 0); + } + let whole = View::new(fd.as_fd(), &[(0, len)]); + Memfd { fd, len, whole } + } + + /// A view of the file's `pieces` `(offset, size)`, mapped contiguously in that order. + fn view(&self, pieces: &[(usize, usize)]) -> View { + assert!(pieces + .iter() + .all(|&(offset, size)| offset + size <= self.len)); + View::new(self.fd.as_fd(), pieces) + } + + /// A source of dma-bufs of `view`'s pages, as a consumer makes them: the file pieces behind + /// the request, split at multiples of its granule into as few chunks as keep each within the + /// host's udmabuf limits (an `Err` where one granule alone exceeds them), the last of several + /// padded with the scratch page. It records each request in `calls`. + fn source(&self, view: &View, calls: &Calls) -> DmaBufSource { + self.source_split(view, calls, false) + } + + /// As [`Memfd::source`], but one chunk per granule wherever the request allows several. + fn granules(&self, view: &View, calls: &Calls) -> DmaBufSource { + self.source_split(view, calls, true) + } + + /// [`Memfd::source`], or [`Memfd::granules`] where `per_granule`. + fn source_split(&self, view: &View, calls: &Calls, per_granule: bool) -> DmaBufSource { + let fd = Arc::new(self.fd.try_clone().unwrap()); + let base = view.at.as_ptr() as usize; + let pieces = view.pieces.clone(); + let calls = Arc::clone(calls); + let scratch = self.len as u64; + let limits = Limits::of_host(); + Arc::new(move |request: DmaBufRequest| { + let made = (|| { + let at = (request.start.as_ptr() as usize) + .checked_sub(base) + .ok_or_else(|| std::io::Error::other("pages before the view"))?; + let limits = match per_granule { + true => Limits { + bytes: limits.bytes.min(request.granule), + ..limits + }, + false => limits, + }; + let plan = chunk_plan(&pieces, at, &request, limits, scratch)?; + plan.into_iter() + .map(|(items, length)| { + Ok(DmaBufChunk { + fd: udmabuf(fd.as_fd(), &items)?, + length, + }) + }) + .collect::>>() + })(); + let chunks = made.as_ref().map_or(0, Vec::len); + calls.lock().unwrap().push((request, chunks)); + made + }) + } +} + +/// One chunk a consumer plans: its file pieces `(offset, size)` and its length. +type PlannedChunk = (Vec<(u64, u64)>, u64); + +/// The chunks a consumer answers `request` with over a view of `pieces` whose first byte the +/// request starts `at`: each its file pieces and its length, split only at multiples of the +/// request's granule, as few as keep each within `limits`; where there are several, the last is +/// padded to a multiple of the granule with the page at file offset `scratch`, repeated. An `Err` +/// where one granule's pages alone exceed the limits, or lie past the view. +fn chunk_plan( + pieces: &[(usize, usize)], + at: usize, + request: &DmaBufRequest, + limits: Limits, + scratch: u64, +) -> std::io::Result> { + let (length, granule) = (request.length, request.granule.max(1)); + let mut chunks: Vec = Vec::new(); + let mut current: PlannedChunk = (Vec::new(), 0); + let mut from = 0u64; + let too_big = |unit: u64, items: usize| { + std::io::Error::other(format!( + "a granule of {unit} bytes in {items} pieces exceeds udmabuf's limits {limits:?}" + )) + }; + while from < length { + let unit = granule.min(length - from); + let items = file_pieces(pieces, at + from as usize, unit as usize) + .ok_or_else(|| std::io::Error::other("pages past the view"))?; + let mut joined = current.0.clone(); + for &(offset, size) in &items { + match joined.last_mut() { + Some((last, last_size)) if *last + *last_size == offset => *last_size += size, + _ => joined.push((offset, size)), + } + } + if joined.len() <= limits.items && current.1 + unit <= limits.bytes { + current = (joined, current.1 + unit); + } else if current.0.is_empty() || items.len() > limits.items || unit > limits.bytes { + return Err(too_big(unit, items.len())); + } else { + chunks.push(std::mem::replace(&mut current, (items, unit))); + } + from += unit; + } + chunks.push(current); + if chunks.len() > 1 { + let page = host_page() as u64; + let last = chunks.last_mut().expect("several"); + while !last.1.is_multiple_of(granule) { + last.0.push((scratch, page)); + last.1 += page; + } + if last.0.len() > limits.items || last.1 > limits.bytes { + return Err(too_big(last.1, last.0.len())); + } + } + Ok(chunks) +} + +/// The file pieces behind `len` bytes from `at` of a view of `pieces` (in view order), adjacent +/// ones merged; `None` past the view. +fn file_pieces(pieces: &[(usize, usize)], at: usize, len: usize) -> Option> { + let mut out: Vec<(u64, u64)> = Vec::new(); + let (mut from, end) = (at, at.checked_add(len)?); + let mut piece_start = 0; + for &(offset, size) in pieces { + let piece_end = piece_start + size; + if from < piece_end && from < end { + let take = piece_end.min(end) - from; + let file = (offset + from - piece_start) as u64; + match out.last_mut() { + Some((last, last_size)) if *last + *last_size == file => *last_size += take as u64, + _ => out.push((file, take as u64)), + } + from += take; + } + piece_start = piece_end; + } + (from == end).then_some(out) +} + +/// Pieces of a file mapped shared and contiguously at one address, unmapped when dropped. +struct View { + at: NonNull, + len: usize, + pieces: Vec<(usize, usize)>, +} + +// SAFETY: the view is plain memory of this process; each test orders the CPU's and the GPU's +// accesses. +unsafe impl Send for View {} + +impl View { + fn new(fd: BorrowedFd<'_>, pieces: &[(usize, usize)]) -> View { + let len: usize = pieces.iter().map(|&(_, size)| size).sum(); + // SAFETY: a fresh reservation, then fixed shared mappings of the file inside it. + unsafe { + let reservation = libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_NONE, + libc::MAP_PRIVATE | libc::MAP_ANON, + -1, + 0, + ); + assert_ne!(reservation, libc::MAP_FAILED, "mmap reservation"); + let mut at = 0; + for &(offset, size) in pieces { + let wanted = reservation.cast::().add(at).cast(); + let mapped = libc::mmap( + wanted, + size, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED | libc::MAP_FIXED, + fd.as_raw_fd(), + offset as libc::off_t, + ); + assert_eq!( + mapped, + wanted, + "mmap of a piece: {}", + std::io::Error::last_os_error() + ); + at += size; + } + View { + at: NonNull::new(reservation.cast()).unwrap(), + len, + pieces: pieces.to_vec(), + } + } + } + + /// The view's address `offset` bytes in. + fn pointer(&self, offset: usize) -> NonNull { + assert!(offset < self.len); + // SAFETY: inside the view. + unsafe { NonNull::new_unchecked(self.at.as_ptr().add(offset)) } + } + + /// A copy of the view's bytes `range`. + fn read(&self, range: std::ops::Range) -> Vec { + assert!(range.start <= range.end && range.end <= self.len); + // SAFETY: the range lies in the view; each test orders the accesses. + unsafe { + std::slice::from_raw_parts(self.at.as_ptr().add(range.start), range.len()).to_vec() + } + } + + /// Write `bytes` into the view at `offset`. + fn write(&self, offset: usize, bytes: &[u8]) { + assert!(offset + bytes.len() <= self.len); + // SAFETY: as in `read`. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.at.as_ptr().add(offset), bytes.len()) + }; + } +} + +impl Drop for View { + fn drop(&mut self) { + // SAFETY: the mappings are this view's, and no buffer uses them any more (each test drops + // its buffers first). + unsafe { libc::munmap(self.at.as_ptr().cast(), self.len) }; + } +} + +/// What `device` does with a memfd's pages: `Some(true)` where it refuses their pointer and +/// imports dma-bufs (RADV), `Some(false)` where it imports the pointer (NVIDIA, lavapipe); `None` +/// for a driver not measured, whose answers are printed only. +fn imports_dma_buf(device: &Device) -> Option { + let driver = device.properties().description.driver_id; + if driver == Some(DriverId::MESA_RADV) { + Some(true) + } else if driver == Some(DriverId::NVIDIA_PROPRIETARY) + || driver == Some(DriverId::MESA_LLVMPIPE) + { + Some(false) + } else { + None + } +} + +/// The device's counts of chunks imported and of sparse buffers assembled so far. +fn dma_buf_counts(device: &Device) -> (u64, u64) { + let counts = device.work_counts(); + (counts.dma_buf_imports, counts.dma_buf_sparse_buffers) +} + +/// Whether `error` refuses dma-bufs that break the source's contract (`Invalid`, `DmaBuf`). +fn misuse(error: &Error) -> bool { + matches!(error, Error::Invalid(invalid) if invalid.problem == Problem::DmaBuf) +} + +/// Check what making a no-copy object over a memfd view with a source did, against the device's +/// expected answer: where it imports dma-bufs, the source asked once for `pages` (the first byte +/// and length of the pages) at a granule that is their length or a multiple of the host page +/// below it, and each chunk it answered imported and counted, a buffer of several counted as +/// assembled, and `chunks` of them where given; else no call and no count. `before` is the +/// counts before the call. The chunks answered. +fn check_route( + test: &str, + device: &Device, + calls: &Calls, + pages: (NonNull, u64), + before: (u64, u64), + chunks: Option, +) -> usize { + let calls = calls.lock().unwrap().clone(); + let (imports, sparse) = dma_buf_counts(device); + let counted = (imports - before.0, sparse - before.1); + let answered = calls.first().map_or(0, |&(_, chunks)| chunks); + match imports_dma_buf(device) { + Some(true) => { + assert_eq!(calls.len(), 1, "{test}: the source's calls: {calls:?}"); + let (request, _) = calls[0]; + assert_eq!( + (request.start, request.length), + pages, + "{test}: {request:?}" + ); + let page = host_page() as u64; + assert!( + request.granule == request.length + || (request.granule < request.length && request.granule.is_multiple_of(page)), + "{test}: {request:?}" + ); + if let Some(chunks) = chunks { + assert_eq!(answered, chunks, "{test}: chunks answered"); + } + let assembled = u64::from(answered > 1); + assert_eq!(counted, (answered as u64, assembled), "{test}: counted"); + } + Some(false) => { + assert!(calls.is_empty(), "{test}: the source was called: {calls:?}"); + assert_eq!(counted, (0, 0), "{test}: counted"); + } + None => {} + } + let name = device.name(); + eprintln!("{test}: on {name}: chunks and sparse buffers {counted:?}, source calls {calls:?}"); + answered +} + +/// A no-copy buffer over `length` bytes of `view` from `offset`, with `source`. +fn no_copy( + device: &Device, + view: &View, + offset: usize, + length: usize, + source: DmaBufSource, +) -> Result { + // SAFETY: each test's view outlives its buffers, and the source makes dma-bufs of its pages. + unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::with_dma_buf(view.pointer(offset), source), + length as u64, + ResourceOptions::default(), + None, + ) + } +} + +/// A no-copy buffer over a scattered memfd view, two discontiguous file pieces mapped contiguously +/// in the other order (file pages 5 and 6, then 1 and 2), as a consumer gathers a guest object, at +/// a pointer and a length that are not page-aligned: where the device refuses the pointer (RADV), +/// the source is called once with the pages the range touches (no import-alignment rounding), its +/// one chunk's list holding both pieces in view order, imported and counted; elsewhere the pointer +/// is imported and the source dropped uncalled. Either way `contents` is the pointer, the GPU reads +/// the CPU's writes through the file's own mapping, a GPU fill across the seam lands at the right +/// file offsets on either side, and the CPU's later writes reach the GPU, with no map, flush or +/// invalidate. +#[test] +fn a_scattered_view_is_imported_across_its_pieces() { + const TEST: &str = "dma-buf scattered view"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let page = host_page(); + let queue = device.new_command_queue().unwrap(); + let ram = Memfd::new(8 * page); + let pieces = [(5 * page, 2 * page), (page, 2 * page)]; + assert_eq!( + file_pieces(&pieces, 0, 4 * page), + Some(vec![ + (5 * page as u64, 2 * page as u64), + (page as u64, 2 * page as u64) + ]) + ); + let view = ram.view(&pieces); + // The CPU writes the view's bytes `bytes` through the file's own mapping. + let write = |bytes: &[u8]| { + ram.whole.write(5 * page, &bytes[..2 * page]); + ram.whole.write(page, &bytes[2 * page..]); + }; + let earlier = counting(4 * page, 3); + write(&earlier); + // From 100 bytes into the view to 64 bytes before its end. + let (offset, length) = (100, 4 * page - 164); + let calls = Calls::default(); + let before = dma_buf_counts(device); + let buffer = no_copy(device, &view, offset, length, ram.source(&view, &calls)).unwrap(); + let pages = (view.at, 4 * page as u64); + check_route(TEST, device, &calls, pages, before, Some(1)); + assert_eq!(buffer.contents(), Some(view.pointer(offset))); + let read = gpu_read(&queue, &buffer, 0..length as u64); + assert!( + read == earlier[offset..offset + length], + "{TEST}: the GPU's read" + ); + // A fill of 100 bytes either side of the seam. + let seam = 2 * page; + let fill = (seam - offset - 100) as u64..(seam - offset + 100) as u64; + gpu_fill(&queue, &buffer, fill, 0xc3); + let end_of_first = ram.whole.read(7 * page - 100..7 * page); + let start_of_second = ram.whole.read(page..page + 100); + assert!(end_of_first.iter().all(|&byte| byte == 0xc3)); + assert!(start_of_second.iter().all(|&byte| byte == 0xc3)); + assert_eq!( + ram.whole.read(7 * page - 101..7 * page - 100), + [earlier[seam - 101]] + ); + assert_eq!( + ram.whole.read(page + 100..page + 101), + [earlier[seam + 100]] + ); + assert_eq!(view.read(seam - 100..seam + 100), vec![0xc3; 200]); + // And the CPU's later writes reach the GPU without a flush. + let later = counting(4 * page, 97); + write(&later); + let read = gpu_read(&queue, &buffer, 0..length as u64); + assert!( + read == later[offset..offset + length], + "{TEST}: the CPU's later bytes" + ); + drop(buffer); + }); +} + +/// `runs` single pages of a new memfd, every other page of the file so that no two are adjacent, +/// mapped as one view, each page's bytes counting from its run: the memfd, the view and its bytes. +fn every_other_page(runs: usize) -> (Memfd, View, Vec) { + let page = host_page(); + let ram = Memfd::new(2 * runs * page); + let pieces: Vec<(usize, usize)> = (0..runs).map(|run| (2 * run * page, page)).collect(); + let view = ram.view(&pieces); + let mut bytes = Vec::with_capacity(runs * page); + for run in 0..runs { + let run_bytes = counting(page, run); + ram.whole.write(2 * run * page, &run_bytes); + bytes.extend(run_bytes); + } + (ram, view, bytes) +} + +/// [`every_other_page`]'s `runs` pages; a no-copy buffer over all but the view's first 64 and +/// last 64 bytes, made through `source`, read and filled by the GPU and checked at every page's +/// file offset, and the page after each run left alone. The making's refusal, where it is refused. +fn check_runs(test: &str, device: &Device, runs: usize) -> Result<(), Error> { + let page = host_page(); + let queue = device.new_command_queue().unwrap(); + let (ram, view, expected) = every_other_page(runs); + let (offset, length) = (64, runs * page - 128); + let calls = Calls::default(); + let before = dma_buf_counts(device); + let buffer = no_copy(device, &view, offset, length, ram.source(&view, &calls))?; + check_route( + test, + device, + &calls, + (view.at, (runs * page) as u64), + before, + None, + ); + assert!( + gpu_read(&queue, &buffer, 0..length as u64) == expected[offset..offset + length], + "{test}: the GPU's read" + ); + gpu_fill(&queue, &buffer, 0..length as u64, 0x6e); + for run in 0..runs { + let file = ram.whole.read(2 * run * page..2 * run * page + page); + let (from, to) = match run { + 0 => (offset, page), + _ if run == runs - 1 => (0, page - 64), + _ => (0, page), + }; + assert!( + file[from..to].iter().all(|&byte| byte == 0x6e), + "{test}: run {run}" + ); + assert_eq!( + file[..from], + expected[run * page..run * page + from], + "{test}: run {run}" + ); + let skipped = ram + .whole + .read((2 * run + 1) * page..(2 * run + 1) * page + 1); + assert_eq!(skipped, [0], "{test}: the page after run {run}"); + } + drop(buffer); + Ok(()) +} + +/// A view of more discontiguous runs than one udmabuf takes on this host (its `list_limit`, 1024 +/// by default, read and never changed): `list_limit + 76` single pages. Where the device refuses +/// the pointer and binds sparse buffers of dma-bufs (RADV), the runtime asks for chunks at its +/// granule, the source answers two (the second padded with its scratch page to the granule), and +/// the buffer is assembled from them, counted; the GPU and the CPU see each other's bytes at +/// every page's file offset. Elsewhere the pointer is imported, the source uncalled. +#[test] +fn a_view_past_one_udmabuf_s_limits_is_assembled_from_chunks() { + const TEST: &str = "dma-buf many runs"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let runs = Limits::of_host().items + 76; + match (imports_dma_buf(device), check_runs(TEST, device, runs)) { + (_, Ok(())) => {} + (None, Err(error)) => eprintln!("{TEST}: on {}: {error:?}", device.name()), + (Some(_), Err(error)) => panic!("{TEST}: {error:?}"), + } + }); +} + +/// The refusals: memfd memory with no source is refused typed where the device refuses its +/// pointer (RADV), as before; a source that fails keeps that refusal, called once; chunks that do +/// not cover the pages, and a chunk whose descriptor is no dma-buf (the memfd itself), are the +/// caller's misuse (`Invalid`, `DmaBuf`), their descriptors closed. Nothing is counted for any of +/// them. Where the device imports the pointer, each is made and no source is called. +#[test] +fn shared_memory_is_refused_without_a_working_source() { + const TEST: &str = "dma-buf refusals"; + on_device(|device| { + let page = host_page(); + let ram = Memfd::new(4 * page); + let view = ram.view(&[(page, 2 * page)]); + let before = dma_buf_counts(device); + let refuses = imports_dma_buf(device); + let check = + |what: &str, made: Result, expected: fn(&Error) -> bool| match made { + Ok(_) => assert_ne!(refuses, Some(true), "{TEST}: {what} was made"), + Err(error) => { + assert_ne!(refuses, Some(false), "{TEST}: {what}: {error:?}"); + assert!(expected(&error), "{TEST}: {what}: {error:?}"); + } + }; + // SAFETY: the view outlives the buffer. + let plain = unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::new(view.pointer(0)), + 2 * page as u64, + ResourceOptions::default(), + None, + ) + }; + check("no source", plain, not_importable); + let calls = Arc::new(Mutex::new(0usize)); + let counted = Arc::clone(&calls); + let failing: DmaBufSource = Arc::new(move |_| { + *counted.lock().unwrap() += 1; + Err(std::io::Error::other("no dma-buf")) + }); + let failed = no_copy(device, &view, 0, 2 * page, failing); + check("a failing source", failed, not_importable); + let expected_calls = usize::from(refuses == Some(true)); + if refuses.is_some() { + assert_eq!(*calls.lock().unwrap(), expected_calls, "{TEST}: calls"); + } + if udmabuf_openable(TEST) { + // One page of the two asked for. + let fd = Arc::new(ram.fd.try_clone().unwrap()); + let short: DmaBufSource = Arc::new(move |_| { + Ok(vec![DmaBufChunk { + fd: udmabuf(fd.as_fd(), &[(page as u64, page as u64)])?, + length: page as u64, + }]) + }); + let made = no_copy(device, &view, 0, 2 * page, short); + check("a chunk short of the pages", made, misuse); + } + // The memfd itself, which is no dma-buf. + let fd = Arc::new(ram.fd.try_clone().unwrap()); + let file: DmaBufSource = Arc::new(move |request| { + Ok(vec![DmaBufChunk { + fd: fd.try_clone()?, + length: request.length, + }]) + }); + let made = no_copy(device, &view, 0, 2 * page, file); + check("a chunk that is no dma-buf", made, misuse); + assert_eq!(dma_buf_counts(device), before, "{TEST}: counted"); + }); +} + +/// The source runs with no lock of the runtime's held: one that makes a buffer of the device's +/// own and a no-copy buffer of private memory before it answers, for a no-copy buffer, a texture +/// over it and a view of that texture in another format (each texture's image over a dma-buf of +/// its own pages), and for a rebind of one onto memfd memory, returns, and each is made over its +/// chunks (RADV) or over the pointer, the source uncalled (elsewhere). The rebound buffer's bytes +/// are then the view's. +#[test] +fn the_source_runs_with_no_runtime_lock_held() { + const TEST: &str = "dma-buf source calls the runtime"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let page = host_page(); + let queue = device.new_command_queue().unwrap(); + let ram = Memfd::new(8 * page); + let view = ram.view(&[(4 * page, 2 * page)]); + let reentrant = |calls: &Calls| -> DmaBufSource { + let inner = ram.source(&view, calls); + let device = device.clone(); + Arc::new(move |request| { + let own = device.new_buffer(4096, ResourceOptions::default()).unwrap(); + let private = Mapping::anonymous(page); + // SAFETY: the mapping outlives the buffer, dropped first. + let over = unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::new(private.pointer()), + page as u64, + ResourceOptions::default(), + None, + ) + }; + drop((own, over.unwrap())); + drop(private); + inner(request) + }) + }; + let calls = Calls::default(); + let before = dma_buf_counts(device); + let buffer = no_copy(device, &view, 0, 2 * page, reentrant(&calls)).unwrap(); + check_route( + TEST, + device, + &calls, + (view.at, 2 * page as u64), + before, + Some(1), + ); + // A texture over it, and a view of another format: each image's call (RADV) too. + let counted = image_counts(device); + let texture = buffer + .new_texture(&read_only(PixelFormat::BGRA8Unorm, 64, 8), 0, 256) + .unwrap(); + let viewed = texture.new_texture_view(PixelFormat::RGBA8Unorm).unwrap(); + check_images(TEST, device, counted, 2, 0); + drop((viewed, texture)); + drop(buffer); + // A rebind of a buffer over private memory onto the view. + let private = Mapping::anonymous(2 * page); + // SAFETY: the mapping outlives the buffer. + let buffer = unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::new(private.pointer()), + 2 * page as u64, + ResourceOptions::default(), + None, + ) + } + .unwrap(); + let written = counting(2 * page, 41); + ram.whole.write(4 * page, &written); + let calls = Calls::default(); + let before = dma_buf_counts(device); + // SAFETY: the view outlives the buffer, and no other thread encodes or commits. + unsafe { + buffer.rebind_bytes_no_copy( + HostMemory::with_dma_buf(view.pointer(0), reentrant(&calls)), + None, + None, + ) + } + .unwrap(); + check_route( + TEST, + device, + &calls, + (view.at, 2 * page as u64), + before, + Some(1), + ); + assert_eq!(buffer.contents(), Some(view.pointer(0))); + assert_eq!(gpu_read(&queue, &buffer, 0..2 * page as u64), written); + drop(buffer); + drop(private); + }); +} + +/// How long a test waits for a command buffer. +const WAIT: Duration = Duration::from_secs(60); + +/// Commit a command buffer on `queue` that waits for `event` to reach 1 and then copies +/// `length` bytes into a new shared buffer with `copy`; run `release` once it is committed, then +/// signal the event and wait: the command buffer's completion, on one of the device's handler +/// threads, lets go of what it held last. The bytes copied. +fn copied_after_release( + queue: &CommandQueue, + length: u64, + copy: impl FnOnce(&mut metal2vulkan_runtime::BlitCommandEncoder, &Buffer), + release: impl FnOnce(), +) -> Vec { + let device = queue.device(); + let event = device.new_shared_event().unwrap(); + let out = device + .new_buffer(length, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::from(&event), 1) + .unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + copy(&mut blit, &out); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + release(); + event.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + read_buffer(&out, 0, length).unwrap() +} + +/// Where a source went: the thread that dropped it, once it went. +type DroppedOn = Arc>>; + +/// Notes, as it goes, the thread it goes on. +struct DropMark(DroppedOn); + +impl Drop for DropMark { + fn drop(&mut self) { + *self.0.lock().unwrap() = Some(std::thread::current()); + } +} + +/// `source`, noting in `on` the thread that drops it: the runtime drops a source with the import +/// it retained it with. +fn marked(source: DmaBufSource, on: &DroppedOn) -> DmaBufSource { + let mark = DropMark(Arc::clone(on)); + Arc::new(move |request| { + let _ = &mark; + source(request) + }) +} + +/// Where the device imports dma-bufs, wait for the source noted in `on` to go, and check it went +/// on a thread of the runtime's, not this test's: the import `what` was freed as a command buffer +/// that held it last completed. +fn went_off_thread(test: &str, device: &Device, on: &DroppedOn, what: &str) { + if imports_dma_buf(device) != Some(true) { + return; + } + let deadline = Instant::now() + WAIT; + let thread = loop { + if let Some(thread) = on.lock().unwrap().clone() { + break thread; + } + assert!(Instant::now() < deadline, "{test}: {what}: never freed"); + std::thread::sleep(Duration::from_millis(1)); + }; + assert_ne!( + thread.id(), + std::thread::current().id(), + "{test}: {what}: freed on the test's thread" + ); + eprintln!( + "{test}: {what}: freed on the runtime's thread {:?}", + thread.name() + ); +} + +/// What a command buffer holds of dma-buf pages goes on a thread of the runtime's as it completes, +/// inside an exit-guard section (the runtime's debug builds end the process on a Vulkan call +/// outside one): a 64 x 64 `BGRA8Unorm` texture over a no-copy buffer of memfd memory, rows 256 +/// bytes apart, released with the buffer while a blit out of the texture waits on an event (the +/// consumer's display-path surface textures); a buffer assembled from several chunks, released +/// so; and a buffer's old pages, rebound away while a command buffer first submitted before the +/// rebind, which copies out of them, spins on the GPU (one that waits on an event is first +/// submitted after the rebind, and reaches the new pages). Each blit reads the bytes the CPU +/// wrote, and each source, retained with its import, goes on a thread other than the test's. +/// Where the device imports the pointer the same holds of its import, and the source goes uncalled +/// as the buffer is made. +#[test] +fn dma_buf_pages_go_on_a_handler_thread_as_a_command_buffer_completes() { + const TEST: &str = "dma-buf pages released at completion"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let page = host_page(); + let queue = device.new_command_queue().unwrap(); + // A texture over the buffer, both released before the blit runs. + let length = 64 * 256; + let ram = Memfd::new(length + 2 * page); + let view = ram.view(&[(page, length)]); + let written = counting(length, 7); + ram.whole.write(page, &written); + let calls = Calls::default(); + let before = dma_buf_counts(device); + let dropped = DroppedOn::default(); + let source = marked(ram.source(&view, &calls), &dropped); + let buffer = no_copy(device, &view, 0, length, source).unwrap(); + check_route( + TEST, + device, + &calls, + (view.at, length as u64), + before, + Some(1), + ); + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, 64, 64, false); + descriptor.usage = TextureUsage::SHADER_READ; + let texture = buffer.new_texture(&descriptor, 0, 256).unwrap(); + let held = Mutex::new(Some((texture, buffer))); + let read = copied_after_release( + &queue, + length as u64, + |blit, out| { + let guard = held.lock().unwrap(); + let (texture, _) = guard.as_ref().unwrap(); + blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(64, 64, 1), + out, + 0, + 256, + length as u64, + BlitOption::None, + ) + .unwrap(); + }, + || drop(held.lock().unwrap().take()), + ); + assert!(read == written, "{TEST}: the texture's texels"); + went_off_thread(TEST, device, &dropped, "the texture's pages"); + // A buffer of several chunks, released before the copy runs. + let runs = Limits::of_host().items + 76; + let (ram, view, expected) = every_other_page(runs); + let length = runs * page; + let calls = Calls::default(); + let before = dma_buf_counts(device); + let dropped = DroppedOn::default(); + let source = marked(ram.source(&view, &calls), &dropped); + let buffer = no_copy(device, &view, 0, length, source).unwrap(); + check_route(TEST, device, &calls, (view.at, length as u64), before, None); + let held = Mutex::new(Some(buffer)); + let read = copied_after_release( + &queue, + length as u64, + |blit, out| { + let guard = held.lock().unwrap(); + let buffer = guard.as_ref().unwrap(); + blit.copy_from_buffer_to_buffer(buffer, 0, out, 0, length as u64) + .unwrap(); + }, + || drop(held.lock().unwrap().take()), + ); + assert!(read == expected, "{TEST}: the assembled buffer's bytes"); + went_off_thread(TEST, device, &dropped, "the assembled buffer's chunks"); + // A buffer's old pages, rebound away while a command buffer that copies out of them, + // first submitted before the rebind, spins on the GPU. + let busy = Busy::new(device, &queue); + let length = 2 * page; + let ram = Memfd::new(8 * page); + let old = ram.view(&[(page, length)]); + let new = ram.view(&[(4 * page, length)]); + let written = counting(length, 3); + ram.whole.write(page, &written); + let calls = Calls::default(); + let before = dma_buf_counts(device); + let dropped = DroppedOn::default(); + let source = marked(ram.source(&old, &calls), &dropped); + let buffer = no_copy(device, &old, 0, length, source).unwrap(); + check_route( + TEST, + device, + &calls, + (old.at, length as u64), + before, + Some(1), + ); + let out = device + .new_buffer(length as u64, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let words = busy.encode(device, &command_buffer); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_buffer(&buffer, 0, &out, 0, length as u64) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + scheduled(&command_buffer); + // SAFETY: both views outlive the buffer, and no other thread encodes or commits. + unsafe { + buffer.rebind_bytes_no_copy( + HostMemory::with_dma_buf(new.pointer(0), ram.source(&new, &Calls::default())), + None, + None, + ) + } + .unwrap(); + assert_ne!( + read_mark(&words), + ENDED, + "{TEST}: the busy work ended before the rebind" + ); + if imports_dma_buf(device) == Some(true) { + assert!( + dropped.lock().unwrap().is_none(), + "{TEST}: the old pages were freed while a command buffer in flight held them" + ); + } + release(&words); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + assert_eq!(read_mark(&words), ENDED, "{TEST}: the busy work's end mark"); + let read = read_buffer(&out, 0, length as u64).unwrap(); + assert!(read == written, "{TEST}: the old pages' bytes"); + went_off_thread(TEST, device, &dropped, "the old pages"); + drop(buffer); + }); +} + +/// A no-copy buffer assembled from several chunks (a sparse buffer, RADV) made while a command +/// buffer spins on the device's first `VkQueue` until the test releases it: the call returns while +/// the work still spins (its binding waits for no GPU work in flight), and once it is released the +/// GPU reads the buffer's bytes. The busy work gives up after about 2 s, so a call that waits for +/// it fails the test rather than hangs it. Elsewhere the pointer is imported, which waits for +/// nothing either. +#[test] +fn a_sparse_buffer_s_binding_waits_for_no_gpu_work() { + const TEST: &str = "dma-buf binding behind GPU work"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + // The first queue made on a new device submits to its first `VkQueue`. + let queue = device.new_command_queue().unwrap(); + let busy = Busy::new(device, &queue); + // Past RADV's largest sparse granule measured (64 KiB), so a split at it is several. + let span = 3 << 16; + let ram = Memfd::new(span); + let view = ram.view(&[(0, span)]); + let written = counting(span, 23); + ram.whole.write(0, &written); + let calls = Calls::default(); + let before = dma_buf_counts(device); + let (busy_work, mark) = busy.commit(device, &queue); + scheduled(&busy_work); + assert_eq!(read_mark(&mark), 0, "{TEST}: the busy work ended first"); + let at = Instant::now(); + let made = no_copy(device, &view, 0, span, ram.granules(&view, &calls)); + let took = at.elapsed(); + let spinning = read_mark(&mark) == 0; + release(&mark); + busy_work.wait_until_completed_for(WAIT).unwrap(); + let buffer = made.unwrap(); + eprintln!("{TEST}: on {}: the call took {took:?}", device.name()); + assert!(spinning, "{TEST}: the call returned after the busy work"); + let chunks = check_route(TEST, device, &calls, (view.at, span as u64), before, None); + if imports_dma_buf(device) == Some(true) { + assert!(chunks > 1, "{TEST}: {chunks} chunks answered"); + } + assert!( + gpu_read(&queue, &buffer, 0..span as u64) == written, + "{TEST}: the GPU's read" + ); + drop(buffer); + }); +} + +/// The device's counts of textures' images made over dma-bufs of their own pages, and of textures +/// over dma-buf pages that took the path such a texture took before (a shadow of the bytes). +fn image_counts(device: &Device) -> (u64, u64) { + let counts = device.work_counts(); + (counts.dma_buf_images, counts.dma_buf_image_fallbacks) +} + +/// Check what making textures over dma-buf pages counted since `before`: `images` images and +/// `fallbacks` fallbacks where the device imports dma-bufs (RADV, whose list holds +/// `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign`); none where it imports +/// the pointer (NVIDIA, lavapipe), whose textures take the path they took before. +fn check_images(test: &str, device: &Device, before: (u64, u64), images: u64, fallbacks: u64) { + let now = image_counts(device); + let counted = (now.0 - before.0, now.1 - before.1); + match imports_dma_buf(device) { + Some(true) => assert_eq!(counted, (images, fallbacks), "{test}: images, fallbacks"), + Some(false) => assert_eq!(counted, (0, 0), "{test}: counted"), + None => eprintln!("{test}: on {}: counted {counted:?}", device.name()), + } +} + +/// The `height` rows of `row` bytes at `offset` of `bytes`, `pitch` apart, packed. +fn packed(bytes: &[u8], offset: usize, pitch: usize, row: usize, height: usize) -> Vec { + (0..height) + .flat_map(|r| &bytes[offset + r * pitch..offset + r * pitch + row]) + .copied() + .collect() +} + +/// A `width` x `height` 2D texture of `pf` that shaders only read. +fn read_only(pf: PixelFormat, width: u64, height: u64) -> TextureDescriptor { + let mut descriptor = TextureDescriptor::texture_2d(pf, width, height, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor +} + +/// Check the source's requests `asked`, made as a texture whose `texels` are `(pitch, row, rows)` +/// (rows `pitch` bytes apart, `row` bytes each) was made at `offset` of a view starting `at`: +/// where the device made its image over a dma-buf of its own pages (`image`, on RADV), one request, +/// for the page its texels start in and the pages from there its image's memory covers, in one +/// chunk (its granule its length), one chunk answered; none where it took its shadow, or where the +/// device imports the pointer. +fn check_texture_request( + test: &str, + device: &Device, + asked: &[(DmaBufRequest, usize)], + at: NonNull, + offset: usize, + texels: (usize, usize, usize), + image: bool, +) { + let page = host_page(); + let (pitch, row, rows) = texels; + match (imports_dma_buf(device), image) { + (Some(true), true) => { + assert_eq!(asked.len(), 1, "{test}: the source's calls: {asked:?}"); + let (request, chunks) = asked[0]; + let first = offset / page * page; + let needed = (offset % page + pitch * (rows - 1) + row) as u64; + // SAFETY: inside the view. + let start = unsafe { NonNull::new_unchecked(at.as_ptr().add(first)) }; + assert_eq!(request.start, start, "{test}: {request:?}"); + assert!( + request.length >= needed + && request.length.is_multiple_of(page as u64) + && request.length < needed + page as u64, + "{test}: {request:?} for {needed} bytes" + ); + assert_eq!(request.granule, request.length, "{test}: {request:?}"); + assert_eq!(chunks, 1, "{test}: chunks answered"); + } + (Some(_), _) => assert!(asked.is_empty(), "{test}: the source's calls: {asked:?}"), + (None, _) => eprintln!("{test}: on {}: the source's calls {asked:?}", device.name()), + } +} + +/// Textures over a no-copy buffer of memfd memory (the consumer's display-path surfaces), rows 256 +/// bytes apart: where the device imports the buffer's pages as dma-bufs (RADV), each is an image of +/// `DRM_FORMAT_MOD_LINEAR` bound to a dedicated import of a dma-buf of its own pages, which the +/// source is asked for once, counted, its plane at the texels' offset in their first page: over one +/// page; over three, a page into the buffer; 256 bytes into a page; one a shader writes, whose +/// modifier's storage features above bit 31 the device reports only in the 64-bit list +/// (`STORAGE_*_WITHOUT_FORMAT`, which the optimal tiling has). One 64 bytes into a page, at which +/// RADV lays no plane (Mesa 26.2.4 and 26.0.8 took plane offsets that are multiples of 256 and +/// refused 4 to 128 and 4032), takes its shadow instead, the source not called, counted as a +/// fallback. Each reads the bytes the CPU wrote; the CPU's later writes, with no call between, are +/// what the next command buffer reads (the image rests in `GENERAL` after its one acquire from the +/// foreign queue family); a blit's write into it lands in the file's pages at the texels' places, +/// the padding past each row keeping the CPU's bytes. The one over three pages, `BGRA8Unorm` made +/// without `PixelFormatView` usage, is read and written through a view in `RGBA8Unorm` +/// (`texture/view_shadow.rs`), an image over a dma-buf of its own pages too, counted, whose write +/// the texture then reads. Where the device imports the pointer (NVIDIA, lavapipe) the textures +/// take the path they took before: the source uncalled, nothing counted. +#[test] +fn a_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() { + const TEST: &str = "dma-buf texture"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let page = host_page(); + let queue = device.new_command_queue().unwrap(); + let length = 8 * page; + let ram = Memfd::new(10 * page); + let pages = ram.view(&[(2 * page, length)]); + let at = pages.at; + ram.whole.write(2 * page, &counting(length, 13)); + let calls = Calls::default(); + let before = dma_buf_counts(device); + let buffer = no_copy(device, &pages, 0, length, ram.source(&pages, &calls)).unwrap(); + check_route(TEST, device, &calls, (at, length as u64), before, Some(1)); + let pitch = 256; + // What, its descriptor, offset, whether RADV makes its image over a dma-buf of its own + // pages, and whether it is used through a view. + let writable = |pf, width, height| { + let mut descriptor = read_only(pf, width, height); + descriptor.usage |= TextureUsage::SHADER_WRITE; + descriptor + }; + let cases = [ + ( + "one page", + read_only(PixelFormat::RGBA8Unorm, 60, 16), + 0, + true, + false, + ), + ( + "three pages", + read_only(PixelFormat::BGRA8Unorm, 64, 40), + page, + true, + true, + ), + ( + "256 bytes in", + read_only(PixelFormat::RGBA8Unorm, 64, 20), + 5 * page + 256, + true, + false, + ), + ( + "64 bytes in", + read_only(PixelFormat::RGBA8Unorm, 16, 8), + 7 * page + 64, + false, + false, + ), + ( + "shader write", + writable(PixelFormat::RGBA8Unorm, 64, 16), + 0, + true, + false, + ), + ]; + for (k, case) in cases.into_iter().enumerate() { + let (what, descriptor, offset, image, view) = case; + let test = format!("{TEST}: {what}"); + let size = (descriptor.width, descriptor.height); + let (row, rows) = (4 * size.0 as usize, size.1 as usize); + let asked_before = calls.lock().unwrap().len(); + let counted = image_counts(device); + let earlier = counting(pitch * rows, 20 + k); + ram.whole.write(2 * page + offset, &earlier); + let texture = buffer + .new_texture(&descriptor, offset as u64, pitch as u64) + .unwrap(); + check_images(&test, device, counted, u64::from(image), u64::from(!image)); + let asked = calls.lock().unwrap()[asked_before..].to_vec(); + let texels = (pitch, row, rows); + check_texture_request(&test, device, &asked, at, offset, texels, image); + let target = match view { + true => { + let counted = image_counts(device); + let viewed = texture.new_texture_view(PixelFormat::RGBA8Unorm).unwrap(); + check_images(&test, device, counted, 1, 0); + viewed + } + false => texture.clone(), + }; + assert!( + blit_texels(&queue, &target, size, 4) == packed(&earlier, 0, pitch, row, rows), + "{test}: the CPU's bytes" + ); + // The CPU's later bytes, with no call between. + let later = counting(pitch * rows, 60 + k); + ram.whole.write(2 * page + offset, &later); + assert!( + blit_texels(&queue, &target, size, 4) == packed(&later, 0, pitch, row, rows), + "{test}: the CPU's later bytes" + ); + // A blit's write lands at the texels' places; the padding keeps the CPU's bytes. + let written = counting(row * rows, 100 + k); + blit_into(&queue, &target, size, 4, &written); + assert!( + blit_texels(&queue, &texture, size, 4) == written, + "{test}: the texture reads the write" + ); + let file = ram + .whole + .read(2 * page + offset..2 * page + offset + pitch * rows); + for r in 0..rows { + let at = r * pitch; + assert!( + file[at..at + row] == written[r * row..(r + 1) * row], + "{test}: row {r} of the blit's texels" + ); + assert!( + file[at + row..at + pitch] == later[at + row..at + pitch], + "{test}: row {r}'s padding" + ); + } + drop((target, texture)); + eprintln!( + "{test}: on {}: {}", + device.name(), + match image_counts(device).0 - counted.0 { + 0 => "the path taken before", + _ => "an image over a dma-buf of its own pages", + } + ); + } + drop(buffer); + }); +} + +/// A texture's image over a dma-buf of its own pages and its buffer's import of the same pages +/// are one resource to hazard tracking (the texture's image takes the buffer's identity): in one +/// command buffer, a blit's write of the buffer is what the next encoder's copy out of the texture +/// reads, and a copy into the texture is what the next encoder's copy out of the buffer reads; +/// and so across two command buffers on one queue. Where the device imports the pointer the +/// texture is what it was before, and the same holds. +#[test] +fn a_buffer_and_its_texture_over_dma_buf_pages_order_their_writes() { + const TEST: &str = "dma-buf texture and buffer"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let page = host_page(); + let queue = device.new_command_queue().unwrap(); + let length = 4 * page; + let ram = Memfd::new(6 * page); + let view = ram.view(&[(page, length)]); + ram.whole.write(page, &counting(length, 5)); + let calls = Calls::default(); + let buffer = no_copy(device, &view, 0, length, ram.source(&view, &calls)).unwrap(); + let counted = image_counts(device); + let size = (64, 16); + let bytes = (4 * size.0 * size.1) as usize; + let texture = buffer + .new_texture(&read_only(PixelFormat::RGBA8Unorm, size.0, size.1), 0, 256) + .unwrap(); + check_images(TEST, device, counted, 1, 0); + let out = device + .new_buffer(bytes as u64, ResourceOptions::shared()) + .unwrap(); + let copy = |command_buffer: &CommandBuffer, from: &Buffer, to: &Buffer| { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_buffer(from, 0, to, 0, bytes as u64) + .unwrap(); + blit.end_encoding().unwrap(); + }; + // A write through one, then a read through the other: in one command buffer, and in two + // committed in order. + let mut texels = Vec::new(); + for (two, into_texture, salt) in [ + (false, false, 5), + (false, true, 77), + (true, false, 101), + (true, true, 151), + ] { + texels = counting(bytes, salt); + let from = staged(device, &texels); + let first = queue.command_buffer().unwrap(); + match into_texture { + true => encode_texels_in(&first, &from, size, 4, &texture), + false => copy(&first, &from, &buffer), + } + let second = two.then(|| { + first.commit().unwrap(); + queue.command_buffer().unwrap() + }); + let reader = second.as_ref().unwrap_or(&first); + match into_texture { + true => copy(reader, &buffer, &out), + false => encode_texels_out(reader, &texture, size, 4, &out), + } + run(reader); + assert_eq!(first.error(), None); + assert!( + read_buffer(&out, 0, bytes as u64).unwrap() == texels, + "{TEST}: two command buffers {two}, written into the texture {into_texture}" + ); + } + assert!( + ram.whole.read(page..page + bytes) == texels, + "{TEST}: the file's pages" + ); + drop(texture); + drop(buffer); + }); +} + +/// Where the source fails for a texture's pages (it answers the buffer's request, then none), the +/// texture over dma-buf pages takes the path it took before: a shadow of the bytes, counted as a +/// fallback and announced once (`shadowed-texture`, naming the dma-buf pages and the source's +/// failure); the source asked once for it. The shadow reads the CPU's bytes, and a blit's write +/// through it reaches them. Where the device imports the pointer, nothing is asked or counted. +#[test] +fn a_texture_over_dma_buf_pages_takes_its_shadow_where_the_source_fails() { + const TEST: &str = "dma-buf texture fallback"; + if !udmabuf_openable(TEST) { + return; + } + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let page = host_page(); + let queue = device.new_command_queue().unwrap(); + let length = 2 * page; + let ram = Memfd::new(4 * page); + let view = ram.view(&[(page, length)]); + let earlier = counting(length, 17); + ram.whole.write(page, &earlier); + let calls = Calls::default(); + let inner = ram.source(&view, &calls); + let answered = Arc::new(Mutex::new(0usize)); + let asked = Arc::clone(&answered); + let once: DmaBufSource = Arc::new(move |request| { + let mut asked = asked.lock().unwrap(); + *asked += 1; + match *asked { + 1 => inner(request), + _ => Err(std::io::Error::other("no dma-buf for a texture")), + } + }); + let buffer = no_copy(&device, &view, 0, length, once).unwrap(); + let counted = image_counts(&device); + let size = (64, 32); + let bytes = (4 * size.0 * size.1) as usize; + let texture = buffer + .new_texture(&read_only(PixelFormat::RGBA8Unorm, size.0, size.1), 0, 256) + .unwrap(); + check_images(TEST, &device, counted, 0, 1); + let notices: Vec<_> = messages + .take_notices() + .into_iter() + .filter_map(|message| message.degradation) + .filter(|notice| notice.degradation == Degradation::ShadowedTexture) + .collect(); + match imports_dma_buf(&device) { + Some(true) => { + assert_eq!(*answered.lock().unwrap(), 2, "{TEST}: the source's calls"); + assert_eq!(notices.len(), 1, "{TEST}: {notices:?}"); + let reason = ¬ices[0].reason; + assert!( + reason.contains("dma-buf") && reason.contains("no dma-buf for a texture"), + "{TEST}: {reason}" + ); + eprintln!("{TEST}: on {}: shadowed-texture: {reason}", device.name()); + } + Some(false) => assert_eq!(*answered.lock().unwrap(), 0, "{TEST}: called"), + None => eprintln!("{TEST}: on {}: notices {notices:?}", device.name()), + } + assert!( + blit_texels(&queue, &texture, size, 4) == earlier[..bytes], + "{TEST}: the CPU's bytes" + ); + let texels = counting(bytes, 61); + blit_into(&queue, &texture, size, 4, &texels); + assert!( + ram.whole.read(page..page + bytes) == texels, + "{TEST}: the blit's write" + ); + drop((texture, buffer)); + } + let failing = messages.take(); + assert!( + failing.is_empty(), + "{TEST}: the validation layer reported: {failing:#?}" + ); +} + +/// A placement heap of `view`'s length over its pages of `ram`, with `ram`'s source noting in +/// `calls`. +fn heap_over(device: &Device, ram: &Memfd, view: &View, calls: &Calls) -> Heap { + let descriptor = HeapDescriptor::new(HeapType::Placement, view.len as u64, shared()); + // SAFETY: the view outlives the heap, and the source makes dma-bufs of its pages. + unsafe { + device.new_heap_with_bytes_no_copy( + HostMemory::with_dma_buf(view.pointer(0), ram.source(view, calls)), + &descriptor, + None, + None, + ) + } + .unwrap() +} + +/// A no-copy heap over a memfd view (whose pages its size covers exactly): where the device +/// refuses the pointer (RADV), the heap's bytes are the source's chunks, and a buffer placed in it +/// reads the CPU's bytes at its offset and its GPU fill lands at the file's offsets. The heap +/// places a texture Metal may keep losslessly compressed (a 64 x 64 `RGBA8Unorm` texture only +/// read, `heap-texture-lossless-layout`), which a heap over pages imported by their pointer binds +/// as a linear image to its memory: where the heap's pages are imported as dma-bufs (RADV), the +/// texture is an image of the driver's `DRM_FORMAT_MOD_LINEAR` layout at its offset, over a +/// dma-buf of its own pages, counted, the source asked once for it; a blit's write into it reads +/// back, and lands in the heap's pages at the texture's offset (rows 256 bytes apart, the driver's +/// pitch for the image). Elsewhere the pointer is imported, nothing is counted or asked, and the +/// write reads back too. +#[test] +fn a_no_copy_heap_s_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() { + const TEST: &str = "dma-buf heap texture"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let page = host_page(); + let size = 1 << 20; + let queue = device.new_command_queue().unwrap(); + let ram = Memfd::new(size + 2 * page); + let view = ram.view(&[(2 * page, size)]); + let held = counting(size, 29); + ram.whole.write(2 * page, &held); + let calls = Calls::default(); + let before = dma_buf_counts(device); + let heap = heap_over(device, &ram, &view, &calls); + check_route(TEST, device, &calls, (view.at, size as u64), before, None); + let placed = 2 * page as u64; + let buffer = heap + .new_buffer_at_offset(placed, shared(), page as u64) + .unwrap(); + assert_eq!(buffer.contents(), Some(view.pointer(page))); + assert_eq!(gpu_read(&queue, &buffer, 0..placed), held[page..3 * page]); + gpu_fill(&queue, &buffer, 0..placed, 0x3c); + let file = ram.whole.read(3 * page..5 * page); + assert!(file.iter().all(|&byte| byte == 0x3c), "{TEST}: the fill"); + drop(buffer); + let extent = (64, 64); + let mut descriptor = read_only(PixelFormat::RGBA8Unorm, extent.0, extent.1); + descriptor.resource_options = shared(); + let answer = device.heap_texture_size_and_align(&descriptor).unwrap(); + let offset = answer.align.max(page as u64) * 3; + let asked_before = calls.lock().unwrap().len(); + let counted = image_counts(device); + let texture = heap.new_texture_at_offset(&descriptor, offset).unwrap(); + check_images(TEST, device, counted, 1, 0); + let asked = calls.lock().unwrap()[asked_before..].to_vec(); + let texels = (256, 256, 64); + check_texture_request(TEST, device, &asked, view.at, offset as usize, texels, true); + let bytes = (4 * extent.0 * extent.1) as usize; + let written = counting(bytes, 71); + blit_into(&queue, &texture, extent, 4, &written); + assert!( + blit_texels(&queue, &texture, extent, 4) == written, + "{TEST}: the blit's write reads back" + ); + let at = 2 * page + offset as usize; + let file = ram.whole.read(at..at + bytes); + match imports_dma_buf(device) { + Some(true) => assert!(file == written, "{TEST}: the heap's pages"), + _ => eprintln!( + "{TEST}: on {}: the heap's pages hold the texels row by row: {}", + device.name(), + file == written + ), + } + drop(texture); + drop(heap); + }); +} + +/// A rebind of bytes over dma-buf pages to other such pages makes each texture's image again over +/// a dma-buf of its own new pages (RADV), counted, the new source asked once for the bytes and +/// once for each texture: a no-copy buffer's texture, and a no-copy heap's. Each then reads the +/// new pages' bytes, and a blit's write through it lands there, the old pages keeping theirs. +/// Elsewhere the textures are made again as before, nothing counted or asked. +#[test] +fn a_rebind_makes_textures_over_dma_buf_pages_again_over_the_new_pages() { + const TEST: &str = "dma-buf texture rebind"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let page = host_page(); + let queue = device.new_command_queue().unwrap(); + let radv = imports_dma_buf(device) == Some(true); + // A no-copy buffer's texture. + let length = 2 * page; + let ram = Memfd::new(8 * page); + let old = ram.view(&[(page, length)]); + let new = ram.view(&[(5 * page, length)]); + let (before, after) = (counting(length, 3), counting(length, 101)); + ram.whole.write(page, &before); + ram.whole.write(5 * page, &after); + let source = ram.source(&old, &Calls::default()); + let buffer = no_copy(device, &old, 0, length, source).unwrap(); + let size = (64, 32); + let bytes = (4 * size.0 * size.1) as usize; + let texture = buffer + .new_texture(&read_only(PixelFormat::RGBA8Unorm, size.0, size.1), 0, 256) + .unwrap(); + assert!(blit_texels(&queue, &texture, size, 4) == before[..bytes]); + let calls = Calls::default(); + let counted = image_counts(device); + // SAFETY: both views outlive the buffer, and no other thread encodes or commits. + unsafe { + buffer.rebind_bytes_no_copy( + HostMemory::with_dma_buf(new.pointer(0), ram.source(&new, &calls)), + None, + None, + ) + } + .unwrap(); + check_images(TEST, device, counted, 1, 0); + let expected = if radv { 2 } else { 0 }; + let asked = calls.lock().unwrap().len(); + assert_eq!(asked, expected, "{TEST}: the new source's calls"); + assert!( + blit_texels(&queue, &texture, size, 4) == after[..bytes], + "{TEST}: the texture reads the new pages" + ); + let texels = counting(bytes, 55); + blit_into(&queue, &texture, size, 4, &texels); + assert!( + ram.whole.read(5 * page..5 * page + bytes) == texels, + "{TEST}: the new pages" + ); + assert!( + ram.whole.read(page..page + length) == before, + "{TEST}: the old pages" + ); + drop((texture, buffer)); + // A no-copy heap's texture. + let heap_size = 1 << 20; + let ram = Memfd::new(2 * heap_size); + let old = ram.view(&[(0, heap_size)]); + let new = ram.view(&[(heap_size, heap_size)]); + let heap = heap_over(device, &ram, &old, &Calls::default()); + let extent = (64, 64); + let mut descriptor = read_only(PixelFormat::RGBA8Unorm, extent.0, extent.1); + descriptor.resource_options = shared(); + let texture = heap.new_texture_at_offset(&descriptor, 0).unwrap(); + let heap_bytes = (4 * extent.0 * extent.1) as usize; + let written = counting(heap_bytes, 7); + blit_into(&queue, &texture, extent, 4, &written); + let calls = Calls::default(); + let counted = image_counts(device); + // SAFETY: both views outlive the heap, and no other thread encodes or commits. + unsafe { + heap.rebind_bytes_no_copy( + HostMemory::with_dma_buf(new.pointer(0), ram.source(&new, &calls)), + None, + None, + ) + } + .unwrap(); + check_images(TEST, device, counted, 1, 0); + let asked = calls.lock().unwrap().len(); + assert_eq!(asked, expected, "{TEST}: the heap's new source's calls"); + let texels = counting(heap_bytes, 131); + blit_into(&queue, &texture, extent, 4, &texels); + assert!( + blit_texels(&queue, &texture, extent, 4) == texels, + "{TEST}: the heap's texture over the new pages" + ); + if radv { + assert!( + ram.whole.read(heap_size..heap_size + heap_bytes) == texels, + "{TEST}: the heap's new pages" + ); + assert!( + ram.whole.read(0..heap_bytes) == written, + "{TEST}: the heap's old pages" + ); + } + drop(texture); + drop(heap); + }); +} + +/// A rebind between pages a source answers in one chunk and pages it answers a chunk per granule +/// (a sparse buffer, RADV), both ways, of a no-copy buffer 80 bytes into its page with a texture +/// over it whose rows are 240 bytes apart: RADV lays no `DRM_FORMAT_MOD_LINEAR` plane there, so +/// the texture is a shadow of the bytes, its copies planned at the bytes' offset in their +/// `VkBuffer`. Either buffer holds the bytes at their offset in their page, so each rebind is made +/// and the texture reads each new pages' texels. Elsewhere the pointer is imported each time. Then +/// a rebind onto anonymous memory, whose pointer every device imports: made, the texture reading +/// its texels, or refused (`NotImplemented`, `RebindTextures`) where that import holds the bytes +/// elsewhere in its `VkBuffer`; never made with the texels misplaced. +#[test] +fn a_rebind_between_one_chunk_and_several_keeps_a_texture_s_texels() { + const TEST: &str = "dma-buf rebind between chunkings"; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let queue = device.new_command_queue().unwrap(); + // Past RADV's largest sparse granule measured (64 KiB), so a split at it is several. + let span = 3 << 16; + let ram = Memfd::new(3 * span); + let views: Vec = (0..3).map(|at| ram.view(&[(at * span, span)])).collect(); + let fills: Vec> = (0..3) + .map(|at| { + let fill = counting(span, 11 + 40 * at); + ram.whole.write(at * span, &fill); + fill + }) + .collect(); + let (offset, length) = (80, span - 160); + let size = (60, 64); + let pitch = 4 * size.0; + let bytes = (pitch * size.1) as usize; + let source = ram.source(&views[0], &Calls::default()); + let buffer = no_copy(device, &views[0], offset, length, source).unwrap(); + let counted = image_counts(device); + let descriptor = read_only(PixelFormat::RGBA8Unorm, size.0, size.1); + let texture = buffer.new_texture(&descriptor, 0, pitch).unwrap(); + check_images(TEST, device, counted, 0, 1); + assert!(blit_texels(&queue, &texture, size, 4) == fills[0][offset..offset + bytes]); + for (at, several) in [(1, true), (2, false)] { + let calls = Calls::default(); + let source = match several { + true => ram.granules(&views[at], &calls), + false => ram.source(&views[at], &calls), + }; + let before = dma_buf_counts(device); + // SAFETY: the views outlive the buffer, and no other thread encodes or commits. + unsafe { + buffer.rebind_bytes_no_copy( + HostMemory::with_dma_buf(views[at].pointer(offset), source), + None, + None, + ) + } + .unwrap(); + let assembled = dma_buf_counts(device).1 - before.1; + if imports_dma_buf(device) == Some(true) { + assert_eq!(assembled, u64::from(several), "{TEST}: view {at}"); + } + assert!( + blit_texels(&queue, &texture, size, 4) == fills[at][offset..offset + bytes], + "{TEST}: the texture over view {at}" + ); + } + let anonymous = Mapping::anonymous(span); + let fill = counting(span, 151); + anonymous.write(0, &fill); + let pointer = NonNull::new(anonymous.pointer().as_ptr().wrapping_add(offset)).unwrap(); + // SAFETY: the mapping outlives the buffer, and no other thread encodes or commits. + let rebound = unsafe { buffer.rebind_bytes_no_copy(HostMemory::new(pointer), None, None) }; + match rebound { + Ok(()) => assert!( + blit_texels(&queue, &texture, size, 4) == fill[offset..offset + bytes], + "{TEST}: the texture over anonymous memory" + ), + Err(Error::NotImplemented(RuntimeGap::RebindTextures)) => {} + Err(error) => panic!("{TEST}: the rebind onto anonymous memory: {error:?}"), + } + eprintln!( + "{TEST}: on {}: the rebind onto anonymous memory: {rebound:?}", + device.name() + ); + drop((texture, buffer)); + }); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/exits.rs b/crates/metal2vulkan-validation/src/runtime_lane/exits.rs index deb03587e..8654ddabf 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/exits.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/exits.rs @@ -25,7 +25,7 @@ use super::{validated_device, Messages, ScratchCache}; use crate::gpu::{DeviceType, TEST_DEVICE}; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Deallocator, Device, DeviceKind, - EventRef, ResourceOptions, SharedEvent, SharedEventListener, + EventRef, HostMemory, ResourceOptions, SharedEvent, SharedEventListener, }; use std::io::Read; use std::path::PathBuf; @@ -322,7 +322,7 @@ fn child() { // SAFETY: the pages stay mapped for the life of the process. let made = unsafe { device.new_buffer_with_bytes_no_copy( - memory, + HostMemory::new(memory), page as u64, ResourceOptions::default(), Some(deallocator), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs index 76285917b..570b9a955 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs @@ -178,10 +178,18 @@ impl Busy { /// word after the spin's flag, ordered after the spin by the buffer both use. The command /// buffer, and the buffer of the mark. pub(super) fn commit(&self, device: &Device, queue: &CommandQueue) -> (CommandBuffer, Buffer) { + let command_buffer = queue.command_buffer().unwrap(); + let words = self.encode(device, &command_buffer); + command_buffer.commit().unwrap(); + (command_buffer, words) + } + + /// Encode the busy work into `command_buffer`, as [`commit`](Busy::commit) commits it: the + /// spin and the end mark's blit. The buffer of the mark. + pub(super) fn encode(&self, device: &Device, command_buffer: &CommandBuffer) -> Buffer { let ticket = buffer_with(device, &1u32.to_le_bytes()).unwrap(); let words = buffer_with(device, &[0; 8]).unwrap(); let cap = buffer_with(device, &self.cap.to_le_bytes()).unwrap(); - let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.compute_command_encoder().unwrap(); encoder.set_compute_pipeline_state(&self.state).unwrap(); encoder.set_buffer(Some(&ticket), 0, 0).unwrap(); @@ -193,8 +201,7 @@ impl Busy { let mut blit = command_buffer.blit_command_encoder().unwrap(); blit.fill_buffer(&words, 4..8, 1).unwrap(); blit.end_encoding().unwrap(); - command_buffer.commit().unwrap(); - (command_buffer, words) + words } } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/heap_extended_reads.rs b/crates/metal2vulkan-validation/src/runtime_lane/heap_extended_reads.rs index 07f305a46..4c7e0a37b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/heap_extended_reads.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/heap_extended_reads.rs @@ -57,8 +57,8 @@ use metal2vulkan::pipeline::{ use metal2vulkan::Budget; use metal2vulkan_devtools::llvm_assemble_text; use metal2vulkan_runtime::{ - CommandBufferStatus, ComputePipelineState, Degradation, Device, Error, PipelineOptions, Region, - ResourceOptions, SamplerState, Size, Texture, TextureDescriptor, + CommandBufferStatus, ComputePipelineState, Degradation, Device, Error, HostMemory, + PipelineOptions, Region, ResourceOptions, SamplerState, Size, Texture, TextureDescriptor, }; use std::collections::{BTreeMap, BTreeSet}; use std::time::Duration; @@ -975,7 +975,7 @@ fn a_raw_texture_over_a_buffer_announces_its_shadow_only_where_not_named() { // SAFETY: the mapping outlives the buffer and its view, dropped first. "no-copy" => match unsafe { device.new_buffer_with_bytes_no_copy( - memory.pointer(), + HostMemory::new(memory.pointer()), GUEST_PAGE as u64, ResourceOptions::shared(), None, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs b/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs index bde4da6ad..07d0ad066 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs @@ -43,9 +43,9 @@ use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; use metal2vulkan_devtools::llvm_assemble; use metal2vulkan_runtime::{ BlitOption, ClearColor, CommandQueue, Degradation, Device, DeviceOptions, Error, Heap, - HeapDescriptor, HeapType, LoadAction, MetalLevel, ObjectId, Origin, PipelineOptions, Region, - RenderPassDescriptor, ResourceOptions, RuntimeGap, Size, StoreAction, Texture, - TextureDescriptor, WorkCounts, + HeapDescriptor, HeapType, HostMemory, LoadAction, MetalLevel, ObjectId, Origin, + PipelineOptions, Region, RenderPassDescriptor, ResourceOptions, RuntimeGap, Size, StoreAction, + Texture, TextureDescriptor, WorkCounts, }; use std::path::Path; @@ -189,8 +189,14 @@ fn heap_over(device: &Device, mapping: &Mapping) -> Option { let descriptor = HeapDescriptor::new(HeapType::Placement, HEAP as u64, shared()); // SAFETY: the mapping holds `HEAP` writable bytes and outlives the heap (each test drops the // heap first). - match unsafe { device.new_heap_with_bytes_no_copy(mapping.pointer(), &descriptor, None, None) } - { + match unsafe { + device.new_heap_with_bytes_no_copy( + HostMemory::new(mapping.pointer()), + &descriptor, + None, + None, + ) + } { Ok(heap) => Some(heap), Err(error) if not_importable(&error) => { eprintln!("HEAPLAYOUT: the device imports no host memory: {error:?}"); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/heaps.rs b/crates/metal2vulkan-validation/src/runtime_lane/heaps.rs index 2e32282d9..9f6561a8e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/heaps.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/heaps.rs @@ -25,8 +25,9 @@ use crate::executor_contract::out_of_bounds::{GUARD_FILL, PAD_FILL}; use crate::gpu::TEST_DEVICE; use metal2vulkan_runtime::{ Buffer, CommandBufferStatus, CommandQueue, CpuCacheMode, Degradation, Device, Error, - HazardTrackingMode, Heap, HeapDescriptor, HeapProblem, HeapType, Invalid, MemoryKind, Nil, - Problem, PurgeableState, ResourceOptions, RuntimeGap, SizeAndAlign, StorageMode, + HazardTrackingMode, Heap, HeapDescriptor, HeapProblem, HeapType, HostMemory, Invalid, + MemoryKind, Nil, Problem, PurgeableState, ResourceOptions, RuntimeGap, SizeAndAlign, + StorageMode, }; use std::collections::BTreeMap; use std::time::{Duration, Instant}; @@ -1405,7 +1406,7 @@ fn a_loaded_pointer_reaches_a_rebound_no_copy_buffer_once_a_command_used_it_agai let new = Mapping::anonymous(len); new.write(0, &bytes); // SAFETY: `new` outlives the buffer, which is dropped first, and no other thread uses it. - unsafe { pages.rebind_bytes_no_copy(new.pointer(), None, None) }.unwrap(); + unsafe { pages.rebind_bytes_no_copy(HostMemory::new(new.pointer()), None, None) }.unwrap(); old.write(0, &bytes); let produced = walk_unnamed(device, &queue, &walker, &pages, None); assert!( @@ -1443,7 +1444,7 @@ fn a_loaded_pointer_reaches_a_no_copy_buffer_rebound_before_its_use_once_a_comma let new = Mapping::anonymous(len); new.write(0, &bytes); // SAFETY: `new` outlives the buffer, which is dropped first, and no other thread uses it. - unsafe { pages.rebind_bytes_no_copy(new.pointer(), None, None) }.unwrap(); + unsafe { pages.rebind_bytes_no_copy(HostMemory::new(new.pointer()), None, None) }.unwrap(); let produced = walk_unnamed(device, &queue, &walker, &pages, None); assert!(produced != walker.metal_output, "no command used it"); gpu_read(&queue, &pages, 0..4); @@ -1493,7 +1494,7 @@ fn a_loaded_pointer_reaches_a_rebound_heap_s_buffer_once_a_command_used_the_heap let new = Mapping::anonymous(HEAP); new.write(AT, &bytes); // SAFETY: `new` outlives the heap, which is dropped first, and no other thread uses it. - unsafe { heap.rebind_bytes_no_copy(new.pointer(), None, None) }.unwrap(); + unsafe { heap.rebind_bytes_no_copy(HostMemory::new(new.pointer()), None, None) }.unwrap(); old.write(AT, &bytes); let produced = walk_unnamed(device, &queue, &walker, &placed, None); assert!( @@ -1537,7 +1538,8 @@ fn a_rebind_of_one_of_two_buffers_over_a_memory_ends_only_its_use() { let new = Mapping::anonymous(len); new.write(0, &bytes); // SAFETY: `new` outlives the buffer, which is dropped first, and no other thread uses it. - unsafe { rebound.rebind_bytes_no_copy(new.pointer(), None, None) }.unwrap(); + unsafe { rebound.rebind_bytes_no_copy(HostMemory::new(new.pointer()), None, None) } + .unwrap(); memory.write(0, &bytes); let produced = walk_unnamed(device, &queue, &walker, &rebound, None); assert!( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs index ed52cd6cc..509baec6a 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs @@ -355,7 +355,14 @@ pub(super) unsafe fn no_copy( deallocator: Option, ) -> Result { // SAFETY: the caller's contract. - unsafe { device.new_buffer_with_bytes_no_copy(pointer, len as u64, options, deallocator) } + unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::new(pointer), + len as u64, + options, + deallocator, + ) + } } /// Commit `command_buffer`, wait for it, and check it completed without error. @@ -1878,7 +1885,7 @@ fn refused_no_copy_buffers_never_run_their_deallocator() { // SAFETY: the mapping outlives the call, which makes nothing. let refused = unsafe { device.new_buffer_with_bytes_no_copy( - memory.pointer(), + HostMemory::new(memory.pointer()), length, made, Some(recording(&seen, ())), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/indirect_executions.rs b/crates/metal2vulkan-validation/src/runtime_lane/indirect_executions.rs index 26fc2a36f..cdc8e3f6d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/indirect_executions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/indirect_executions.rs @@ -41,7 +41,7 @@ use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandBufferStatus, ComputeCommandEncoder, ComputePipelineState, DebugMessage, Degradation, Device, DeviceOptions, Error, ExecutedPipeline, Execution, Heap, - HeapDescriptor, HeapType, IndirectCommand, IndirectCommandBuffer, + HeapDescriptor, HeapType, HostMemory, IndirectCommand, IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandBufferProblem, Invalid, PipelineOptions, Problem, Region, RenderPassDescriptor, ResourceOptions, Size, VisibleFunctionTableDescriptor, }; @@ -1386,7 +1386,8 @@ fn commands_reach_a_rebound_no_copy_buffer_once_a_command_used_it_again() { ); // SAFETY: the mapping outlives the buffer, dropped first, and no other thread uses // the buffer. - unsafe { buffer.rebind_bytes_no_copy(memory.pointer(), None, None) }.unwrap(); + unsafe { buffer.rebind_bytes_no_copy(HostMemory::new(memory.pointer()), None, None) } + .unwrap(); new_pages.push(memory); } assert_eq!(output(&case.compute, &buffers), before); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/kept_variants.rs b/crates/metal2vulkan-validation/src/runtime_lane/kept_variants.rs index 6a8fb7121..38f2300ee 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/kept_variants.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/kept_variants.rs @@ -17,9 +17,9 @@ use metal2vulkan::pipeline::{ }; use metal2vulkan_devtools::llvm_assemble; use metal2vulkan_runtime::{ - Buffer, ClearColor, CommandBuffer, CommandBufferStatus, ComputePipelineState, Device, Library, - LoadAction, PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, - StoreAction, Texture, TextureDescriptor, WorkCounts, + Buffer, ClearColor, CommandBuffer, CommandBufferStatus, ComputePipelineState, Device, + HostMemory, Library, LoadAction, PipelineOptions, RenderPassDescriptor, RenderPipelineState, + ResourceOptions, Size, StoreAction, Texture, TextureDescriptor, WorkCounts, }; use std::alloc::Layout; use std::cell::RefCell; @@ -93,7 +93,7 @@ fn no_copy_buffer(device: &Device, freed: &Arc) -> Buffer { // deallocator unrun, and the memory then leaks. unsafe { device.new_buffer_with_bytes_no_copy( - memory, + HostMemory::new(memory), NO_COPY as u64, ResourceOptions::shared(), Some(Box::new(move |pointer, _| { diff --git a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_heaps.rs b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_heaps.rs index 9cd4a8b41..913b9fb10 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_heaps.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_heaps.rs @@ -29,9 +29,10 @@ use crate::gpu::TEST_DEVICE; use metal2vulkan::metal::format::is_depth_stencil; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan_runtime::{ - BlitOption, Buffer, CommandQueue, CpuCacheMode, Deallocator, Degradation, Device, Error, - HazardTrackingMode, Heap, HeapDescriptor, HeapProblem, HeapType, Invalid, Nil, Origin, Problem, - Region, ResourceOptions, RuntimeGap, Size, StorageMode, Texture, TextureDescriptor, + BlitOption, Buffer, CommandBuffer, CommandQueue, CpuCacheMode, Deallocator, Degradation, + Device, Error, HazardTrackingMode, Heap, HeapDescriptor, HeapProblem, HeapType, HostMemory, + Invalid, Nil, Origin, Problem, Region, ResourceOptions, RuntimeGap, Size, StorageMode, Texture, + TextureDescriptor, }; use std::ptr::NonNull; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -97,7 +98,9 @@ pub(super) unsafe fn no_copy_heap( ) -> Option { let descriptor = HeapDescriptor::new(heap_type, HEAP as u64, shared()); // SAFETY: the caller's contract. - match unsafe { device.new_heap_with_bytes_no_copy(pointer, &descriptor, deallocator, None) } { + match unsafe { + device.new_heap_with_bytes_no_copy(HostMemory::new(pointer), &descriptor, deallocator, None) + } { Ok(heap) => Some(heap), Err(error) if not_importable(&error) => { eprintln!("NOCOPYHEAP: the device imports no host memory: {error:?}"); @@ -122,7 +125,7 @@ pub(super) fn band(len: usize, base: u8) -> Vec { } /// A Shared buffer holding `bytes`. -fn staged(device: &Device, bytes: &[u8]) -> Buffer { +pub(super) fn staged(device: &Device, bytes: &[u8]) -> Buffer { let buffer = device .new_buffer(bytes.len() as u64, ResourceOptions::shared()) .unwrap(); @@ -237,54 +240,48 @@ fn a_no_copy_heap_s_buffers_are_the_caller_s_bytes() { assert_eq!(seen.dropped.load(Ordering::SeqCst), 0); } -/// The texels of `texture`'s first level (`side` square, `bytes` a texel), read back through a -/// blit. -pub(super) fn blit_texels( - queue: &CommandQueue, +/// Encode a blit of `texture`'s first level, `size` texels of `bytes` bytes, into `out`, rows +/// packed. +pub(super) fn encode_texels_out( + command_buffer: &CommandBuffer, texture: &Texture, - side: u64, + (width, height): (u64, u64), bytes: u64, -) -> Vec { - let device = queue.device(); - let len = side * side * bytes; - let copy = device.new_buffer(len, ResourceOptions::shared()).unwrap(); - let command_buffer = queue.command_buffer().unwrap(); + out: &Buffer, +) { 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), - ©, + Size::new(width, height, 1), + out, 0, - side * bytes, - len, + width * bytes, + width * height * bytes, BlitOption::None, ) .unwrap(); blit.end_encoding().unwrap(); - run(&command_buffer); - read_buffer(©, 0, len).unwrap() } -/// Blit `texels` (`side` square, `bytes` a texel) into `texture`'s first level. -pub(super) fn blit_into( - queue: &CommandQueue, - texture: &Texture, - side: u64, +/// Encode a blit of `from`'s bytes, rows packed, into `texture`'s first level, `size` texels of +/// `bytes` bytes. +pub(super) fn encode_texels_in( + command_buffer: &CommandBuffer, + from: &Buffer, + (width, height): (u64, u64), bytes: u64, - texels: &[u8], + texture: &Texture, ) { - let source = staged(queue.device(), texels); - let command_buffer = queue.command_buffer().unwrap(); let mut blit = command_buffer.blit_command_encoder().unwrap(); blit.copy_from_buffer_to_texture( - &source, + from, 0, - side * bytes, - side * side * bytes, - Size::new(side, side, 1), + width * bytes, + width * height * bytes, + Size::new(width, height, 1), texture, 0, 0, @@ -293,6 +290,37 @@ pub(super) fn blit_into( ) .unwrap(); blit.end_encoding().unwrap(); +} + +/// The texels of `texture`'s first level (`size` texels, `bytes` a texel), read back through a +/// blit, rows packed. +pub(super) fn blit_texels( + queue: &CommandQueue, + texture: &Texture, + size: (u64, u64), + bytes: u64, +) -> Vec { + let len = size.0 * size.1 * bytes; + let copy = (queue.device()) + .new_buffer(len, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + encode_texels_out(&command_buffer, texture, size, bytes, ©); + run(&command_buffer); + read_buffer(©, 0, len).unwrap() +} + +/// Blit `texels` (`size` texels, `bytes` a texel, rows packed) into `texture`'s first level. +pub(super) fn blit_into( + queue: &CommandQueue, + texture: &Texture, + size: (u64, u64), + bytes: u64, + texels: &[u8], +) { + let source = staged(queue.device(), texels); + let command_buffer = queue.command_buffer().unwrap(); + encode_texels_in(&command_buffer, &source, size, bytes, texture); run(&command_buffer); } @@ -355,8 +383,12 @@ fn texture_round_trip(pf: PixelFormat, side: u64, bytes: u64, offset: u64) -> Op // The GPU writes the texture: the caller's bytes and the buffer's change. mapping.fill(0); let first = band(len, 0x00); - blit_into(&queue, &texture, side, bytes, &first); - assert_eq!(blit_texels(&queue, &texture, side, bytes), first, "{what}"); + blit_into(&queue, &texture, (side, side), bytes, &first); + assert_eq!( + blit_texels(&queue, &texture, (side, side), bytes), + first, + "{what}" + ); let host = mapping.read(range.clone()); let changed = host.iter().filter(|&&byte| byte != 0).count(); assert!( @@ -375,7 +407,7 @@ fn texture_round_trip(pf: PixelFormat, side: u64, bytes: u64, offset: u64) -> Op // The CPU writes the caller's bytes: every texel changes. let second = band(size as usize, 0x80); mapping.write(start, &second); - let read = blit_texels(&queue, &texture, side, bytes); + let read = blit_texels(&queue, &texture, (side, side), bytes); assert_eq!( same_texels(&read, &first, bytes), 0, @@ -384,7 +416,7 @@ fn texture_round_trip(pf: PixelFormat, side: u64, bytes: u64, offset: u64) -> Op // The GPU writes through the buffer: every texel changes again. gpu_fill(&queue, &buffer, 0..size, 0x5A); - let after = blit_texels(&queue, &texture, side, bytes); + let after = blit_texels(&queue, &texture, (side, side), bytes); assert_eq!( same_texels(&after, &read, bytes), 0, @@ -406,7 +438,11 @@ fn texture_round_trip(pf: PixelFormat, side: u64, bytes: u64, offset: u64) -> Op .get_bytes(&mut texels, row, 0, region, 0, 0) .unwrap(); assert_eq!(texels, third, "{what}: getBytes after replaceRegion"); - assert_eq!(blit_texels(&queue, &texture, side, bytes), third, "{what}"); + assert_eq!( + blit_texels(&queue, &texture, (side, side), bytes), + third, + "{what}" + ); laid = if tiled { let n = bytes as usize; (0..side).all(|y| { @@ -474,7 +510,12 @@ fn a_no_copy_heap_is_refused_as_its_rules_say() { let deallocator: Deallocator = Box::new(move |_, _| drop(count)); // SAFETY: the mapping holds every byte asked for and outlives any heap. let made = unsafe { - device.new_heap_with_bytes_no_copy(at, &descriptor, Some(deallocator), None) + device.new_heap_with_bytes_no_copy( + HostMemory::new(at), + &descriptor, + Some(deallocator), + None, + ) }; assert_eq!(seen.runs.load(Ordering::SeqCst), 0); assert_eq!(seen.dropped.load(Ordering::SeqCst), 1, "{descriptor:?}"); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rebinds.rs b/crates/metal2vulkan-validation/src/runtime_lane/rebinds.rs index c8cacb018..815b94a7d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rebinds.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rebinds.rs @@ -45,8 +45,8 @@ use metal2vulkan::metal::TextureType; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Deallocator, Device, Error, EventRef, - Heap, HeapDescriptor, HeapProblem, HeapType, Invalid, Origin, Problem, RebindProblem, - ResourceOptions, RuntimeGap, SharedEvent, Size, Texture, TextureDescriptor, + Heap, HeapDescriptor, HeapProblem, HeapType, HostMemory, Invalid, Origin, Problem, + RebindProblem, ResourceOptions, RuntimeGap, SharedEvent, Size, Texture, TextureDescriptor, }; use std::collections::BTreeMap; use std::ptr::NonNull; @@ -112,14 +112,26 @@ pub(super) fn rebind(buffer: &Buffer, mapping: Mapping, seen: &Arc) -> Res let pointer = mapping.pointer(); // SAFETY: the mapping holds the buffer's length until the deallocator releases it, and no // other thread encodes or commits meanwhile. - unsafe { buffer.rebind_bytes_no_copy(pointer, Some(recording(seen, mapping)), None) } + unsafe { + buffer.rebind_bytes_no_copy( + HostMemory::new(pointer), + Some(recording(seen, mapping)), + None, + ) + } } /// Rebind `heap` to `mapping`, whose deallocator records into `seen` and releases it. pub(super) fn rebind_heap(heap: &Heap, mapping: Mapping, seen: &Arc) -> Result<(), Error> { let pointer = mapping.pointer(); // SAFETY: as `rebind`'s, for the heap's size. - unsafe { heap.rebind_bytes_no_copy(pointer, Some(recording(seen, mapping)), None) } + unsafe { + heap.rebind_bytes_no_copy( + HostMemory::new(pointer), + Some(recording(seen, mapping)), + None, + ) + } } /// Where a deallocator ran. @@ -547,7 +559,8 @@ fn only_the_caller_s_memory_is_rebound() { count.runs.fetch_add(1, Ordering::SeqCst); }); // SAFETY: the mapping holds the heap's size past `off` and outlives any rebind. - let made = unsafe { over.rebind_bytes_no_copy(off, Some(deallocator), None) }; + let made = + unsafe { over.rebind_bytes_no_copy(HostMemory::new(off), Some(deallocator), None) }; let Err(Error::Invalid(invalid)) = &made else { panic!("an unaligned rebind: {made:?}"); }; @@ -603,7 +616,9 @@ fn a_texture_over_a_rebound_buffer_reads_the_new_pages() { "REBIND texture over a no-copy buffer: {}", if aliased { "aliased" } else { "shadowed" } ); - let read = |texture: &Texture| blit_texels(&queue, texture, side as u64, bytes as u64); + let read = |texture: &Texture| { + blit_texels(&queue, texture, (side as u64, side as u64), bytes as u64) + }; assert_eq!(read(&texture), rows(&counting(LEN, 1), side, bytes, pitch)); // Memory 256 bytes into a page. @@ -614,7 +629,8 @@ fn a_texture_over_a_rebound_buffer_reads_the_new_pages() { let count = DropRecord(Arc::clone(&seen)); let deallocator: Deallocator = Box::new(move |_, _| drop(count)); // SAFETY: the mapping holds the length past `off` and outlives any rebind. - let made = unsafe { buffer.rebind_bytes_no_copy(off, Some(deallocator), None) }; + let made = + unsafe { buffer.rebind_bytes_no_copy(HostMemory::new(off), Some(deallocator), None) }; assert_eq!(made, Err(Error::NotImplemented(RuntimeGap::RebindTextures))); assert_eq!(seen.dropped.load(Ordering::SeqCst), 1); drop(off_page); @@ -624,7 +640,13 @@ fn a_texture_over_a_rebound_buffer_reads_the_new_pages() { rebind(&buffer, next, &Arc::default()).unwrap(); assert_eq!(read(&texture), rows(&counting(LEN, 2), side, bytes, pitch)); let written: Vec = (0..side * side * bytes).map(|i| (i % 199) as u8).collect(); - blit_into(&queue, &texture, side as u64, bytes as u64, &written); + blit_into( + &queue, + &texture, + (side as u64, side as u64), + bytes as u64, + &written, + ); // SAFETY: the new mapping lives until the buffer goes; no command writes it now. let now = unsafe { at(pointer, 0..side * pitch) }; assert_eq!(rows(&now, side, bytes, pitch), written); @@ -658,7 +680,9 @@ fn a_texture_over_a_no_copy_heap_s_buffer_follows_a_rebind() { let texture = buffer.new_texture(&descriptor, 0, pitch as u64).unwrap(); // SAFETY: the handle is only compared, while the texture lives. let aliased = unsafe { texture.vk_image() }.is_some(); - let read = |texture: &Texture| blit_texels(&queue, texture, side as u64, bytes as u64); + let read = |texture: &Texture| { + blit_texels(&queue, texture, (side as u64, side as u64), bytes as u64) + }; assert_eq!( read(&texture), rows(&counting(HEAP, 1)[offset..], side, bytes, pitch) @@ -673,7 +697,13 @@ fn a_texture_over_a_no_copy_heap_s_buffer_follows_a_rebind() { "the texels of the new pages" ); let written: Vec = (0..side * side * bytes).map(|i| (i % 199) as u8).collect(); - blit_into(&queue, &texture, side as u64, bytes as u64, &written); + blit_into( + &queue, + &texture, + (side as u64, side as u64), + bytes as u64, + &written, + ); // SAFETY: the new mapping lives until the heap goes; no command writes it now. let now = unsafe { at(next_pointer, offset..offset + side * pitch) }; assert_eq!(rows(&now, side, bytes, pitch), written); @@ -838,7 +868,7 @@ fn a_rebound_heap_keeps_its_resources() { let id = texture.gpu_resource_id(); let len = (side * side * bytes) as usize; let first: Vec = (0..len).map(|i| (i % 251) as u8).collect(); - blit_into(&queue, &texture, side, bytes, &first); + blit_into(&queue, &texture, (side, side), bytes, &first); let size = device .heap_texture_size_and_align(&heap_descriptor(format, side)) .unwrap() @@ -853,7 +883,11 @@ fn a_rebound_heap_keeps_its_resources() { let next_pointer = next.pointer(); // SAFETY: the test keeps the mapping until the heap is gone. unsafe { - heap.rebind_bytes_no_copy(next_pointer, Some(recording(&next_seen, ())), None) + heap.rebind_bytes_no_copy( + HostMemory::new(next_pointer), + Some(recording(&next_seen, ())), + None, + ) } .unwrap_or_else(|error| panic!("{format:?}: {error:?}")); ran( @@ -868,12 +902,12 @@ fn a_rebound_heap_keeps_its_resources() { mappings[old].fill(0); assert_eq!(texture.gpu_resource_id(), id); assert_eq!( - blit_texels(&queue, &texture, side, bytes), + blit_texels(&queue, &texture, (side, side), bytes), first, "{format:?}: the texels of the new pages" ); let second: Vec = (0..len).map(|i| (i % 241) as u8 ^ 0x5a).collect(); - blit_into(&queue, &texture, side, bytes, &second); + blit_into(&queue, &texture, (side, side), bytes, &second); let current = mappings.len() - 1; assert_ne!( mappings[current].read(range.clone()), @@ -891,7 +925,11 @@ fn a_rebound_heap_keeps_its_resources() { let next_seen = Arc::new(Seen::default()); // SAFETY: the test keeps the mapping until the heap is gone. unsafe { - heap.rebind_bytes_no_copy(next.pointer(), Some(recording(&next_seen, ())), None) + heap.rebind_bytes_no_copy( + HostMemory::new(next.pointer()), + Some(recording(&next_seen, ())), + None, + ) } .unwrap(); mappings.push(next); @@ -1025,8 +1063,14 @@ fn a_texture_sampled_before_its_first_submission_reads_its_heap_s_new_pages() { second.write(0, &laid); let before = device.work_counts(); // SAFETY: the test keeps the mapping until the heap is gone. - unsafe { heap.rebind_bytes_no_copy(second.pointer(), Some(recording(&seen[1], ())), None) } - .unwrap(); + unsafe { + heap.rebind_bytes_no_copy( + HostMemory::new(second.pointer()), + Some(recording(&seen[1], ())), + None, + ) + } + .unwrap(); // Its last use, the copy in, completed before the rebind. ran(&seen[0], first.pointer(), HEAP, &laid[..16], Thread::Any); assert_eq!(held.status(), CommandBufferStatus::Committed); @@ -1100,7 +1144,8 @@ fn a_heap_rebind_costs_an_image_per_bound_texture() { let next = Mapping::anonymous(HEAP); let start = Instant::now(); // SAFETY: the test keeps the mapping until the heap is gone. - unsafe { heap.rebind_bytes_no_copy(next.pointer(), None, None) }.unwrap(); + unsafe { heap.rebind_bytes_no_copy(HostMemory::new(next.pointer()), None, None) } + .unwrap(); times.push(format!("{:.0}", start.elapsed().as_secs_f64() * 1e6)); mappings.push(next); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/surface_aliases.rs b/crates/metal2vulkan-validation/src/runtime_lane/surface_aliases.rs index ef8da4547..fb5a72ef4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/surface_aliases.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/surface_aliases.rs @@ -44,8 +44,8 @@ use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; use metal2vulkan_devtools::llvm_assemble_text; use metal2vulkan_runtime::{ BlitOption, Buffer, ClearColor, CommandBuffer, CommandQueue, ComputePipelineState, Device, - EventRef, IoSurfacePlane, LoadAction, Origin, PipelineOptions, RenderPassDescriptor, - ResourceOptions, Size, StoreAction, Texture, TextureDescriptor, + EventRef, HostMemory, IoSurfacePlane, LoadAction, Origin, PipelineOptions, + RenderPassDescriptor, ResourceOptions, Size, StoreAction, Texture, TextureDescriptor, }; /// The consumer's display surface: 1920x1080 `RGBA16Float`, 8 bytes a texel, rows packed. @@ -205,7 +205,10 @@ impl Surface { let second = import(other.pointer()).unwrap(); // SAFETY: the surface's mapping outlives the buffer, and the pages it leaves stay // mapped until the surface goes; no command uses the buffer yet. - unsafe { second.rebind_bytes_no_copy(memory.pointer(), None, None) }.unwrap(); + unsafe { + second.rebind_bytes_no_copy(HostMemory::new(memory.pointer()), None, None) + } + .unwrap(); left = Some(other); second } diff --git a/docs/API.md b/docs/API.md index 12ef6dcad..681ce57d1 100644 --- a/docs/API.md +++ b/docs/API.md @@ -140,6 +140,12 @@ bit-exact `fneg`, `fabs` and `half`-to-`float` widening of NaNs and denormals. U switches it also keeps Metal's canonical NaNs and Metal's operand choice in `fmin`, `fmax`, `min3`, `max3` and `clamp`. +What the runtime enables for itself outside the vocabulary enters no enable set, compile profile +or fingerprint: among it the extensions of its dma-buf fallback for no-copy memory whose pointer +the device refuses (`HostMemory::with_dma_buf`), `VK_EXT_external_memory_dma_buf` with +`VK_KHR_external_memory_fd`, and `VK_EXT_image_drm_format_modifier` with +`VK_EXT_queue_family_foreign` beside them, wherever a device lists them. + ## 2. A library `Library::parse` takes a metallib, a bitcode wrapper or a raw AIR module; `Library::from_air` @@ -680,8 +686,10 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. buffer is a shadow image: no linear image of the device lays its texels out as Metal does in the buffer's memory (over a no-copy buffer's imported host memory, no linear image made for host allocations does), or the buffer is over the caller's `VkBuffer`, whose memory backs no image of - the runtime's. Cost: its texels are copied into an image before each use and back after each - write. + the runtime's, or over host pages imported as dma-bufs (`HostMemory::with_dma_buf`) where the + device makes no image over a dma-buf of the texture's own pages (the notice names why; + `WorkCounts::dma_buf_image_fallbacks` counts it). Cost: its texels are copied into an image before + each use and back after each write. - `metal2vulkan-degrade-staged-texture-buffer` (performance). `StagedTextureBuffer`: A texture buffer is viewed through a staging buffer: its texels start where the device views none (`minTexelBufferOffsetAlignment`). Cost: its texels are copied into a staging buffer before each diff --git a/docs/HOWTO.md b/docs/HOWTO.md index ceb899f19..0db3e74c2 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -1,8 +1,8 @@ # Integrating metal2vulkan The checklist around the library: the tools each piece needs, caching, failures, isolating a -compile and checking an integration. The API itself is [API.md](API.md); the runtime's is -[its README](../crates/metal2vulkan-runtime/README.md). +compile, host memory a driver refuses, and checking an integration. The API itself is +[API.md](API.md); the runtime's is [its README](../crates/metal2vulkan-runtime/README.md). ## 1. Tools @@ -133,7 +133,49 @@ down, or a hard memory ceiling must hold, compile in a child process: The validation crate's worker (`crates/metal2vulkan-validation/src/worker/`) implements this, under 20 seconds and 500 MiB per attempt. -## 6. Check the integration +## 6. Host memory a driver refuses + +`Device::new_buffer_with_bytes_no_copy`, `new_heap_with_bytes_no_copy` and the +`rebind_bytes_no_copy` calls import the caller's pages by their pointer +(`VK_EXT_external_memory_host`). Some drivers refuse the pointer of shared memory: RADV (AMD on +Linux) imports a pointer through amdgpu's userptr, which takes anonymous pages only, so it refuses +`MAP_SHARED` mappings of a `memfd`, a shared memory object or any file (QEMU's +`memory-backend-memfd,share=on` guest RAM among them) with `Unsupported`, `HostMemory`. NVIDIA and +lavapipe import the same memory. + +A consumer whose memory is such a mapping passes `HostMemory::with_dma_buf(pointer, source)` instead +of `HostMemory::new(pointer)`. The runtime still imports the pointer first, exactly as without a +source, and calls the source only where the device refuses it: for dma-bufs of the pages the range +touches, and again once for each texture's image over its own pages in them. The rustdoc of +`HostMemory::with_dma_buf`, `DmaBufSource` and `DmaBufRequest` is the contract: when the source is +called, the chunks it answers, and what is refused. In short, answer each `DmaBufRequest` with +dma-bufs of exactly the pages asked for, in order, split only at multiples of its `granule`. Where +the granule is less than the length (64 KiB on RADV of Mesa 26.2.4, 4 KiB on 26.0.8), several +chunks are bound to one sparse buffer and must total the length rounded up to the granule: pad the +last with a scratch page of your own, repeated. A texture's request takes one chunk, of the same +file pieces the buffer's chunks hold there. + +On Linux, `udmabuf` makes such a dma-buf of the file pieces behind the pages: open `/dev/udmabuf` +(the process needs read and write access to it) and issue `UDMABUF_CREATE_LIST` with one item per +run of contiguous file pages; the `memfd` must be sealed against shrinking (`F_SEAL_SHRINK`, as QEMU +seals it) and not against writing. The consumer knows the pieces behind every byte; the runtime runs +no udmabuf code. Each udmabuf takes at most `list_limit` items and `size_limit_mb` MiB (the module's +parameters under `/sys/module/udmabuf/parameters`, 1024 and 64 by default). Keep each chunk within +the host's limits as they are: read them, never assume them raised. Scattered memory needs many +items: a macOS desktop guest of 14 GiB was measured importing up to 63.3 MiB in one object, in up to +16,201 separate 4 KiB runs, with 19 to 29 of its imports past 1024 runs; at a 64 KiB granule such an +object takes 16 chunks. + +A texture over such memory is an image over a dma-buf of its own pages where the device also lists +`VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign` (RADV does). RADV (Mesa 26.2.4 +and 26.0.8) lays such an image's plane only at an offset in its page that is a multiple of 256 +bytes, with rows a multiple of 256 bytes apart: keep a texture's offset and `bytes_per_row` so (a +4 KiB-aligned surface with 256-byte-aligned rows always is). Elsewhere the texture takes a shadow of +the bytes, announced (`shadowed-texture`, naming why), and a rebind that cannot make the image again +is refused (`NotImplemented(RebindTextures)`). `WorkCounts::dma_buf_imports`, +`dma_buf_sparse_buffers`, `dma_buf_images` and `dma_buf_image_fallbacks` count what the route did. + +## 7. Check the integration `spirv-val` checks structural validity, not agreement with Metal: diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 96fe026bf..e80a744e4 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -14,7 +14,7 @@ Columns: - `none`: no public API path: malformed or non-Metal input, Apple-private calls, or a cap no valid program of ordinary size meets; - `?`: not assessed yet. -Generated at `53fc528b6`. +Generated at `d612d286c`. ## Totals @@ -36,9 +36,9 @@ Generated at `53fc528b6`. | `Stage` | A function stage the model does not cover | - | via a helper: 2: `crates/metal2vulkan-air/src/abi/check.rs:579`, `crates/metal2vulkan/src/error/mod.rs:246` | `none`: a stage outside AIR's public stages | | `AddressSpace` | An LLVM address space the typed model does not define (it defines AIR's `thread` 0 through `threadgroup_imageblock` 4, `object_data` 6 and the... | every device (not implemented) | 2: `crates/metal2vulkan-air/src/ir/types.rs:191`, `crates/metal2vulkan/src/memory/plan.rs:1854` | `none`: Apple's AGX library address spaces | | `ModuleRecord` | A module-level record outside the accepted subset (alias, ifunc, comdat, …) | - | via a helper: 4: `crates/metal2vulkan-air/src/bitcode/module.rs:343`, `crates/metal2vulkan-air/src/bitcode/module.rs:435` (+2) | `none`: LLVM constructs AIR does not emit | -| `Instruction` | An instruction record outside the closed instruction set | - | via a helper: 11: `crates/metal2vulkan-air/src/bitcode/function.rs:1015`, `crates/metal2vulkan-air/src/bitcode/function.rs:1062` (+9) | `none`: LLVM instructions AIR does not emit | +| `Instruction` | An instruction record outside the closed instruction set | - | via a helper: 11: `crates/metal2vulkan-air/src/bitcode/function.rs:1010`, `crates/metal2vulkan-air/src/bitcode/function.rs:1057` (+9) | `none`: LLVM instructions AIR does not emit | | `Type` | A type outside the typed model | - | via a helper: 4: `crates/metal2vulkan-air/src/bitcode/types.rs:184`, `crates/metal2vulkan-air/src/bitcode/types.rs:206` (+2) | `none`: LLVM types AIR does not emit | -| `CallingConvention` | A calling convention other than AIR's | - | via a helper: 3: `crates/metal2vulkan-air/src/bitcode/function.rs:1359`, `crates/metal2vulkan-air/src/bitcode/module.rs:499` (+1) | `none`: LLVM calling conventions AIR does not use | +| `CallingConvention` | A calling convention other than AIR's | - | via a helper: 3: `crates/metal2vulkan-air/src/bitcode/function.rs:1354`, `crates/metal2vulkan-air/src/bitcode/module.rs:499` (+1) | `none`: LLVM calling conventions AIR does not use | | `UnknownIntrinsic` | An intrinsic outside the closed set | every device (not implemented) | 2: `crates/metal2vulkan-air/src/error.rs:621`, `crates/metal2vulkan/src/lower/select.rs:990` | `rare`: AIR from a newer compiler (macOS 27 AIR 2.9) | | `AgxUnmodeled` | An AGX intrinsic whose semantics are not modeled | every device (not implemented) | 1: `crates/metal2vulkan/src/lower/simd/agx.rs:62` | `rare`: Apple's own libraries' AGX intrinsics | | `StaticInitializer` | A static initializer that cannot be evaluated | every device (not implemented) | 1: `crates/metal2vulkan-air/src/error.rs:627` | `none`: LLVM initializers AIR does not emit | @@ -74,7 +74,7 @@ Generated at `53fc528b6`. | `MinLodClamp` | `min_lod_clamp` without `shaderResourceMinLod` | devices without VkFeature::ShaderResourceMinLod; every device (not implemented) | 2: `crates/metal2vulkan/src/lower/sampler/select.rs:1311`, `crates/metal2vulkan/src/lower/sampler/select.rs:891` | `rare`: min_lod_clamp on a device without shaderResourceMinLod | | `TexelOffset` | A texel offset the device cannot apply | devices short of a device limit the site names; every device (no Vulkan mechanism) | 2: `crates/metal2vulkan/src/lower/sampler/select.rs:750`, `crates/metal2vulkan/src/lower/sampler/select.rs:824` | `app`: texel offsets a device cannot apply | | `GatherExtended` | Gather with non-constant offsets or components | - | via a helper: 1: `crates/metal2vulkan/src/lower/sampler/select.rs:782` | `rare`: gathers with dynamic offsets or components | -| `StorageImageMultisample` | Multisampled storage images | - | via a helper: 1: `crates/metal2vulkan/src/lower/texture/slot.rs:1037` | `rare`: writable multisampled textures | +| `StorageImageMultisample` | Multisampled storage images | - | via a helper: 1: `crates/metal2vulkan/src/lower/texture/slot.rs:1046` | `rare`: writable multisampled textures | | `StorageTextureInVertexStage` | Storage images in the vertex stage | - | via a helper: 1: `crates/metal2vulkan/src/lower/texture/slot.rs:666` | `rare`: writable textures in vertex functions | | `CubeArray` | Cube arrays | devices without VkFeature::ImageCubeArray | 2: `crates/metal2vulkan/src/lower/sampler/select.rs:1214`, `crates/metal2vulkan/src/lower/texture/slot.rs:456` | `rare`: cube arrays on a device without imageCubeArray | | `SamplerAnisotropy` | Constexpr sampler anisotropy | devices without VkFeature::SamplerAnisotropy; every device (not implemented) | 3: `crates/metal2vulkan/src/lower/sampler/select.rs:1409`, `crates/metal2vulkan/src/metal/sampler.rs:255` (+1) | `app`: anisotropic constexpr samplers on a device without samplerAnisotropy | @@ -90,10 +90,10 @@ Generated at `53fc528b6`. | `LayeredRendering` | Layered rendering (`render_target_array_index`, `viewport_array_index`) | devices without VkFeature::ImageView2DOn3DImage; devices without VkFeature::ShaderOutputLayer; devices without VkFeature::ShaderOutputViewportIndex | 3: `crates/metal2vulkan-runtime/src/render_pass.rs:1538`, `crates/metal2vulkan/src/lower/mesh/mod.rs:736` (+1) | `rare`: layered rendering on a device without its features | | `ClipDistance` | Clip or cull distances | devices without VkFeature::ShaderClipDistance; devices without VkLimit::MaxClipDistances | 2: `crates/metal2vulkan/src/lower/mesh/mod.rs:892`, `crates/metal2vulkan/src/lower/mesh/mod.rs:900` | `rare`: clip distances on a device without them | | `DualSourceBlending` | Dual-source blending | devices without VkFeature::DualSrcBlend; devices without VkLimit::MaxFragmentDualSrcAttachments | 5: `crates/metal2vulkan-runtime/src/families/formats.rs:398`, `crates/metal2vulkan/src/metal/state.rs:37` (+3) | `rare`: dual-source blending on a device without it | -| `Barycentrics` | Barycentric coordinates | drivers with a defect | 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs:1460` | `rare`: barycentric coordinates | +| `Barycentrics` | Barycentric coordinates | drivers with a defect | 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs:1462` | `rare`: barycentric coordinates | | `StencilExport` | Stencil export | devices without VkExtension::ExtShaderStencilExport; every device (not implemented) | 6: `crates/metal2vulkan-runtime/src/families/features.rs:1091`, `crates/metal2vulkan/src/bind/graphics.rs:2058` (+4) | `rare`: stencil from the shader | | `SampleRateShading` | Per-sample shading | devices without VkFeature::SampleRateShading; devices without a capability the site computes (`needs`); every device (not implemented) | 3: `crates/metal2vulkan/src/pipeline/link/graphics.rs:700`, `crates/metal2vulkan/src/pipeline/link/graphics.rs:702` (+1) | `rare`: per-sample shading | -| `PixelCoverageAtSampleRate` | The pixel's coverage (`[[sample_mask]]` read) in a fragment function that runs once per sample | drivers with a defect; every device (no Vulkan mechanism); every device (not implemented) | 3: `crates/metal2vulkan/src/lower/fragment/coverage.rs:291`, `crates/metal2vulkan/src/lower/simd/mod.rs:735` (+1) | `rare`: coverage read at sample rate | +| `PixelCoverageAtSampleRate` | The pixel's coverage (`[[sample_mask]]` read) in a fragment function that runs once per sample | drivers with a defect; every device (no Vulkan mechanism); every device (not implemented) | 3: `crates/metal2vulkan/src/lower/fragment/coverage.rs:291`, `crates/metal2vulkan/src/lower/simd/mod.rs:739` (+1) | `rare`: coverage read at sample rate | | `InterfaceComponents` | Too many interface components or locations | devices short of a device limit the site names; devices without VkLimit::MaxColorAttachments; devices without VkLimit::MaxVertexInputAttributes | 3: `crates/metal2vulkan/src/pipeline/link/graphics.rs:256`, `crates/metal2vulkan/src/pipeline/link/varyings.rs:343` (+1) | `rare`: too many varyings or attachments for a device | | `UnmatchedVarying` | A fragment input without a vertex producer (a Metal link error) | every device (no Vulkan mechanism) | 3: `crates/metal2vulkan/src/pipeline/link/varyings.rs:253`, `crates/metal2vulkan/src/pipeline/link/varyings.rs:439` (+1) | `none`: a Metal link error | | `KernelStageIn` | Kernel `[[stage_in]]` | every device (not implemented) | 3: `crates/metal2vulkan-runtime/src/indirect_execute.rs:337`, `crates/metal2vulkan/src/bind/dispatch.rs:881` (+1) | `rare`: kernel stage-in combinations Metal leaves unestablished | @@ -104,12 +104,12 @@ Generated at `53fc528b6`. | `RayTracing` | | devices without a capability the site computes (`missing`); every device (no Vulkan mechanism); every device (not implemented) | 12: `crates/metal2vulkan/src/bind/acceleration.rs:202`, `crates/metal2vulkan/src/bind/acceleration.rs:216` (+10) | `rare`: ray tracing (out of scope by ruling) | | `Tensors` | | every device (not implemented) | 2: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs:32`, `crates/metal2vulkan/src/lower/select.rs:887` | `rare`: shader tensors | | `RasterizationRateMap` | | every device (not implemented) | 1: `crates/metal2vulkan/src/lower/fragment/mod.rs:875` | `rare`: rasterization rate maps | -| `GpuEncodedIndirectCommands` | | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism); every device (not implemented) | 11: `crates/metal2vulkan/src/bind/replay.rs:530`, `crates/metal2vulkan/src/bind/replay.rs:770` (+9) | `rare`: indirect command buffers encoded by a kernel | +| `GpuEncodedIndirectCommands` | | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism); every device (not implemented) | 11: `crates/metal2vulkan/src/bind/replay.rs:530`, `crates/metal2vulkan/src/bind/replay.rs:772` (+9) | `rare`: indirect command buffers encoded by a kernel | | `VulkanVersion` | The device's Vulkan version is below the 1.2 floor | devices without ApiVersion::V1_2 | 2: `crates/metal2vulkan/src/ash_interop/query.rs:898`, `crates/metal2vulkan/src/device/derive.rs:101` | `none`: a device below Vulkan 1.2 | | `Constant` | A bitcode constant record outside the typed model (block address, inline asm, `select` and other constant expressions the IR has no form for) | - | via a helper: 3: `crates/metal2vulkan-air/src/bitcode/constants.rs:210`, `crates/metal2vulkan-air/src/bitcode/constants.rs:268` (+1) | `none`: LLVM constant forms AIR does not emit | | `Attribute` | An LLVM attribute kind that changes the calling ABI and that AIR does not use (`inalloca`, `preallocated`, `byref`, `nest`, the `swift*` kinds) | - | via a helper: 2: `crates/metal2vulkan-air/src/bitcode/attrs.rs:493`, `crates/metal2vulkan/src/error/mod.rs:258` | `none`: LLVM ABI attributes AIR does not use | -| `BitcodeRecord` | A bitcode record LLVM defines in `block` that the typed model does not cover and that has no more specific variant (legacy spellings predating... | - | via a helper: 7: `crates/metal2vulkan-air/src/bitcode/attrs.rs:337`, `crates/metal2vulkan-air/src/bitcode/function.rs:577` (+5) | `none`: bitcode records AIR does not emit | -| `SyncScope` | An atomic access or fence in a synchronization scope other than LLVM's built-in `singlethread` and system scopes | - | via a helper: 2: `crates/metal2vulkan-air/src/bitcode/function.rs:1260`, `crates/metal2vulkan/src/error/mod.rs:260` | `none`: synchronization scopes AIR does not use | +| `BitcodeRecord` | A bitcode record LLVM defines in `block` that the typed model does not cover and that has no more specific variant (legacy spellings predating... | - | via a helper: 7: `crates/metal2vulkan-air/src/bitcode/attrs.rs:337`, `crates/metal2vulkan-air/src/bitcode/function.rs:572` (+5) | `none`: bitcode records AIR does not emit | +| `SyncScope` | An atomic access or fence in a synchronization scope other than LLVM's built-in `singlethread` and system scopes | - | via a helper: 2: `crates/metal2vulkan-air/src/bitcode/function.rs:1255`, `crates/metal2vulkan/src/error/mod.rs:260` | `none`: synchronization scopes AIR does not use | | `SubgroupOperations` | Simdgroup operations of a class the stage's subgroups do not support (the stage is not in `subgroupSupportedStages`, or an operation class is... | devices without VkFeature::ShaderQuadControl; devices without VkFeature::ShaderSubgroupExtendedTypes; devices without VkProperty::SubgroupStage | 4: `crates/metal2vulkan-runtime/src/families/features.rs:1643`, `crates/metal2vulkan/src/lower/simd/mod.rs:402` (+2) | `app`: simdgroup functions in a stage a device's subgroups do not support | | `DirectCall` | A call to a defined function the inliner cannot take | every device (not implemented) | 1: `crates/metal2vulkan-air/src/canon/mod.rs:1283` | `rare`: variadic or byval calls the inliner cannot take | | `WideSwitchLiteral` | A switch case literal wider than 32 bits | every device (not implemented) | 1: `crates/metal2vulkan/src/structurize/emit.rs:207` | `rare`: 64-bit switch literals | @@ -131,9 +131,9 @@ Generated at `53fc528b6`. | `TextureSize` | A texture whose extent, array layers, or level count is past what the device takes for its format, type, and usage (`Capability::Limit` names the... | devices short of a device limit the site names | 1: `crates/metal2vulkan-runtime/src/image_plan.rs:1062` | `app`: a texture past a device's image limits | | `TextureSampleCount` | A texture sample count the device does not take for its format, type, and usage | devices short of a Vulkan property the site names; devices without VkFeature::MultisampleArrayImage; every device (no Vulkan mechanism) | 3: `crates/metal2vulkan-runtime/src/image_plan.rs:1110`, `crates/metal2vulkan-runtime/src/image_plan.rs:570` (+1) | `app`: a sample count a device lacks for the texture | | `TextureView` | A texture view Vulkan cannot make exactly on this image | every device (no Vulkan mechanism); every device (not implemented) | 5: `crates/metal2vulkan-runtime/src/binding_view.rs:156`, `crates/metal2vulkan-runtime/src/texture/view_shadow.rs:184` (+3) | `app`: a texture view Vulkan cannot make exactly | -| `TextureSwizzle` | A texture swizzle whose Metal behavior is not measured | devices short of a Vulkan feature the site names; every device (not implemented) | 7: `crates/metal2vulkan-runtime/src/binding_view.rs:167`, `crates/metal2vulkan-runtime/src/texture.rs:775` (+5) | `app`: texture swizzles whose Metal behaviour is unmeasured | +| `TextureSwizzle` | A texture swizzle whose Metal behavior is not measured | devices short of a Vulkan feature the site names; every device (not implemented) | 7: `crates/metal2vulkan-runtime/src/binding_view.rs:167`, `crates/metal2vulkan-runtime/src/texture.rs:885` (+5) | `app`: texture swizzles whose Metal behaviour is unmeasured | | `MipmapGeneration` | `generateMipmapsForTexture:` where the device's filter is not shown to give Metal's answer | devices without VkFeature::ShaderInt64; devices without a format's usage; every device (not implemented) | 7: `crates/metal2vulkan-runtime/src/blit_texture.rs:1689`, `crates/metal2vulkan-runtime/src/mipmap_pick.rs:37` (+5) | `app`: generateMipmapsForTexture: where the device's filter is not Metal's | -| `HostMemory` | A buffer over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`) | devices without VkExtension::ExtExternalMemoryHost; every device (no Vulkan mechanism); every device (not implemented) | 5: `crates/metal2vulkan-runtime/src/host_memory.rs:255`, `crates/metal2vulkan-runtime/src/host_memory.rs:280` (+3) | `system`: newBufferWithBytesNoCopy: where the device cannot import the memory | +| `HostMemory` | A buffer over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`) | devices without VkExtension::ExtExternalMemoryHost; every device (no Vulkan mechanism); every device (not implemented) | 5: `crates/metal2vulkan-runtime/src/host_memory.rs:329`, `crates/metal2vulkan-runtime/src/host_memory.rs:361` (+3) | `system`: newBufferWithBytesNoCopy: where the device cannot import the memory | | `GpuTimes` | A command buffer's GPU times (`GPUStartTime`, `GPUEndTime`) on a device whose queue family writes no timestamps (`timestampValidBits` 0) | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:1830` | `rare`: GPU times on a queue without timestamps | | `CountingVisibility` | A `Counting` visibility result (`MTLVisibilityResultModeCounting`) on a device without `occlusionQueryPrecise` | devices without VkFeature::OcclusionQueryPrecise | 1: `crates/metal2vulkan-runtime/src/visibility.rs:447` | `rare`: counting occlusion queries on a device without precise queries | | `ViewFormatReinterpretation` | A texture view whose format has other components, or components of other widths, than its texture's (`RGBA8Unorm` as `R32Uint`), on a device whose... | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/view_plan.rs:547` | `app`: a view of another component layout on a portability subset (MoltenVK) | @@ -143,7 +143,7 @@ Generated at `53fc528b6`. | `PrivateMemory` | A stage whose private memory (its `thread` variables and arrays, and the constants it holds per thread) takes more Function storage a thread than... | - | via a helper: 1: `crates/metal2vulkan/src/lower/select.rs:1153` | `rare`: very large per-thread arrays | | `SparseTextures` | A sparse heap (`MTLHeapTypeSparse`), or a texture made from one, on a device without what a sparse resident image of it needs, which `missing` names | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/sparse/texture.rs:32` | `rare`: sparse heaps on a device without sparse images | | `SparseMapping` | A sparse texture's mapping update (`updateTextureMapping:` and its array form, or a move of mappings) that covers part of one of the device's... | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/sparse/encoder.rs:466` | `rare`: sparse mappings off the device's blocks | -| `TimelineSemaphores` | Command buffers and events, which the runtime completes and signals through timeline semaphores (core in Vulkan 1.2), on a device whose... | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/device/create.rs:986` | `none`: a device below the runtime's floor | +| `TimelineSemaphores` | Command buffers and events, which the runtime completes and signals through timeline semaphores (core in Vulkan 1.2), on a device whose... | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/device/create.rs:1014` | `none`: a device below the runtime's floor | | `Reflection` | Reflection of an argument whose answer Metal's has not been measured for (`reflection`) | every device (not implemented) | 9: `crates/metal2vulkan/src/bind/argument_buffer.rs:628`, `crates/metal2vulkan/src/reflection/derive.rs:179` (+7) | `rare`: reflection of argument kinds Metal's answer is unmeasured for | | `HeapTextureTiling` | A texture of a heap whose memory the device's optimal images do not take (a `Shared` heap on a device whose optimal images take no host-visible... | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/texture/heap.rs:540` | `app`: textures in Shared heaps on a device whose optimal images take no host memory | | `ViewportDepthRange` | A viewport depth range past `[0, 1]` (`setViewport:`), which Metal takes and the runtime draws natively (`VK_EXT_depth_range_unrestricted`) or... | drivers with a defect | 1: `crates/metal2vulkan-runtime/src/render_state.rs:1035` | `rare`: viewport depth outside [0, 1] | @@ -152,8 +152,8 @@ Generated at `53fc528b6`. | `IndirectRenderState` | A render state a function sets on an indirect render command (`render_command::set_cull_mode`, `set_front_facing_winding`,... | every device (not implemented) | 1: `crates/metal2vulkan/src/lower/access/encode.rs:559` | `rare`: render state set by a kernel on an indirect command | | `GlobalBuiltinInFragment` | A fragment function's read of a Metal 3.1 program-scope built-in variable that Metal does not lower there | every device (not implemented) | 1: `crates/metal2vulkan/src/lower/select.rs:896` | `rare`: Metal 3.1 global built-ins in fragment functions | | `PrivateRenderState` | A private fixed-function property of Metal's pipeline descriptor (Apple SPI, OpenGL on Metal's) set to a value whose effect the translation has... | every device (not implemented) | 4: `crates/metal2vulkan/src/bind/heap.rs:1278`, `crates/metal2vulkan/src/bind/plan/resources.rs:880` (+2) | `none`: Apple-private pipeline fields of OpenGL on Metal (no public header) | -| `ExtendedRangeBlend` | Metal's blend into an extended-range attachment (`BGRA10_XR`, `BGR10_XR`, `RGB10A8_2P_XR10` and their `_sRGB` twins), which the function computes... | every device (not implemented) | 4: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:276`, `crates/metal2vulkan/src/lower/fragment/fetch.rs:1006` (+2) | `system`: the parts of a blend into an extended-range (XR10) attachment the measured model does not hold (second-source factors, the color blend color difference, a one-color-channel mask, float4 and sRGB outside the measured forms); the consumer's guests blend RGB10A8_2P_XR10 attachments | -| `TileReach` | The tiles a render pass's primitives reach, binned on the device ([`tile_reach_module`](crate::bind::tile_reach_module)), on a device without what... | devices short of a Vulkan feature the site names; devices without a capability the site computes (`vec![int64]`); devices without buffer device addresses (`addressed_needs`); every device (not implemented) | 5: `crates/metal2vulkan/src/bind/tile_reach.rs:272`, `crates/metal2vulkan/src/lower/stage_io/plan.rs:1944` (+3) | `app`: the tiles a pass's draws reach, binned on a device without shaderInt64 | +| `ExtendedRangeBlend` | Metal's blend into an extended-range attachment (`BGRA10_XR`, `BGR10_XR`, `RGB10A8_2P_XR10` and their `_sRGB` twins), which the function computes... | every device (not implemented) | 4: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:276`, `crates/metal2vulkan/src/lower/fragment/fetch.rs:1008` (+2) | `system`: the parts of a blend into an extended-range (XR10) attachment the measured model does not hold (second-source factors, the color blend color difference, a one-color-channel mask, float4 and sRGB outside the measured forms); the consumer's guests blend RGB10A8_2P_XR10 attachments | +| `TileReach` | The tiles a render pass's primitives reach, binned on the device ([`tile_reach_module`](crate::bind::tile_reach_module)), on a device without what... | devices short of a Vulkan feature the site names; devices without a capability the site computes (`vec![int64]`); devices without buffer device addresses (`addressed_needs`); every device (not implemented) | 5: `crates/metal2vulkan/src/bind/tile_reach.rs:272`, `crates/metal2vulkan/src/lower/stage_io/plan.rs:1946` (+3) | `app`: the tiles a pass's draws reach, binned on a device without shaderInt64 | | `CommandPredication` | Metal's private command predication (`encodeStartIf:offset:comparison:referenceValue:` and the rest), whose step module... | devices without buffer device addresses (`addressed_needs`) | 1: `crates/metal2vulkan/src/bind/replay/predication.rs:415` | `none`: Apple-private command predication on a device without buffer device addresses | | `ProgramScopeBinding` | A program-scope buffer binding of MSL 3.2 (macOS 15 and later), `constant T* constant p [[buffer(n)]];` in Apple's `!air.global_bindings` list,... | - | via a helper: 2: `crates/metal2vulkan-air/src/abi/module.rs:77`, `crates/metal2vulkan/src/error/mod.rs:268` | `app`: MSL 3.2 program-scope buffer bindings (macOS 15 and later) | | `SeqCstFence` | A sequentially consistent fence (`seq_cst` `atomic_thread_fence`, an LLVM `fence seq_cst`, or a `seq_cst` barrier ordering device memory), whose... | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`) | 2: `crates/metal2vulkan/src/lower/sync/barrier.rs:443`, `crates/metal2vulkan/src/lower/sync/barrier.rs:449` | `rare`: a seq_cst fence on a device without buffer device addresses or the stage's stores | @@ -162,13 +162,13 @@ Generated at `53fc528b6`. | Variant | What it blocks | Where | Sites | Reach | |---|---|---|---|---| -| `Textures` | Textures and texture buffers | every device (runtime piece not built) | 9: `crates/metal2vulkan-runtime/src/blit_texture.rs:159`, `crates/metal2vulkan-runtime/src/buffer_texture.rs:1522` (+7) | `rare`: texture forms the runtime has not built (texture buffers of some forms, X24Stencil8 views) | +| `Textures` | Textures and texture buffers | every device (runtime piece not built) | 9: `crates/metal2vulkan-runtime/src/blit_texture.rs:159`, `crates/metal2vulkan-runtime/src/buffer_texture.rs:1525` (+7) | `rare`: texture forms the runtime has not built (texture buffers of some forms, X24Stencil8 views) | | `ResourceHeap` | The resource-ID heap, descriptor set 1 | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/binding.rs:1358` | `rare`: the resource-ID heap's remaining forms | -| `SparseHeaps` | Sparse heaps and their textures | every device (runtime piece not built) | 3: `crates/metal2vulkan-runtime/src/sparse/encoder.rs:458`, `crates/metal2vulkan-runtime/src/texture.rs:1360` (+1) | `rare`: sparse heaps | +| `SparseHeaps` | Sparse heaps and their textures | every device (runtime piece not built) | 3: `crates/metal2vulkan-runtime/src/sparse/encoder.rs:458`, `crates/metal2vulkan-runtime/src/texture.rs:1476` (+1) | `rare`: sparse heaps | | `SparseTileMaps` | What the runtime's emulation of sparse textures does not build yet | every device (runtime piece not built) | 3: `crates/metal2vulkan-runtime/src/binding.rs:428`, `crates/metal2vulkan-runtime/src/sparse/texture.rs:30` (+1) | `rare`: sparse texture emulation's unbuilt pieces | -| `HeapPastMaxBufferSize` | A heap larger than the device's `maxBufferSize`, which the device can allocate | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/heap.rs:686` | `rare`: a heap past maxBufferSize | -| `HeapTextureAlignment` | A heap texture whose image needs an alignment past the heap memory's base alignment (64 KiB) | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture/heap.rs:1269` | `rare`: a heap texture needing more than 64 KiB alignment | -| `HeapTextureMemory` | A heap texture whose image the heap's memory type does not take | every device (runtime piece not built) | 5: `crates/metal2vulkan-runtime/src/texture/heap.rs:1254`, `crates/metal2vulkan-runtime/src/texture/heap.rs:1261` (+3) | `app`: a heap texture the heap's memory type does not take | +| `HeapPastMaxBufferSize` | A heap larger than the device's `maxBufferSize`, which the device can allocate | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/heap.rs:689` | `rare`: a heap past maxBufferSize | +| `HeapTextureAlignment` | A heap texture whose image needs an alignment past the heap memory's base alignment (64 KiB) | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture/heap.rs:1275` | `rare`: a heap texture needing more than 64 KiB alignment | +| `HeapTextureMemory` | A heap texture whose image the heap's memory type does not take | every device (runtime piece not built) | 5: `crates/metal2vulkan-runtime/src/texture/heap.rs:1260`, `crates/metal2vulkan-runtime/src/texture/heap.rs:1267` (+3) | `app`: a heap texture the heap's memory type does not take | | `FunctionTablePastMaxBufferLength` | A visible-function table of more entries than one buffer of the device's `max_buffer_length` holds words for, or than its size word holds | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/function_table.rs:628` | `none`: a function table past one buffer | | `IndirectCommandBufferPastMaxBufferLength` | An indirect command buffer of more commands than one buffer of the device's `max_buffer_length` holds the records of | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:522` | `none`: an ICB past one buffer | | `IndirectRenderCommands` | What indirect command buffers lack of their render commands | every device (runtime piece not built) | 16: `crates/metal2vulkan-runtime/src/compute.rs:1026`, `crates/metal2vulkan-runtime/src/compute.rs:1076` (+14) | `rare`: indirect render commands' remaining pieces | @@ -207,20 +207,20 @@ Generated at `53fc528b6`. | `LayeredPass` | A layered render pass (`renderTargetArrayLength` 2 or more) that needs a step of one layer | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/color_resolve.rs:517` | `rare`: layered passes needing a per-layer color resolve | | `FunctionOptions` | A function descriptor's options beyond `CompileToBinary` and `StoreFunctionInMetalPipelinesScript` (`Library::new_function_with_descriptor`) | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/library.rs:215` | `rare`: function descriptor options beyond CompileToBinary | | `OverlappingTextureCopies` | A blit copy between overlapping regions of one texture's texels (`copyFromTexture:...` with the source's region meeting the destination's, through... (not scheduled) | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/blit_texture.rs:1201` | `rare`: overlapping texture copies (Metal races) | -| `RebindTextures` | `Buffer::rebind_bytes_no_copy` of a no-copy buffer with a live texture over its bytes, given memory at another offset in its page than the old | every device (runtime piece not built) | 4: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs:575`, `crates/metal2vulkan-runtime/src/texture.rs:2420` (+2) | `none`: a runtime extension's rebind with a live texture | -| `PvrtcBlockOrder` | A PVRTC texture's blocks in a Metal block order the runtime does not lay out | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture.rs:5095` | `rare`: PVRTC regions off whole levels | +| `RebindTextures` | `Buffer::rebind_bytes_no_copy` of a no-copy buffer with a live texture over its bytes, given memory at another offset in its page than the old | every device (runtime piece not built) | 10: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs:567`, `crates/metal2vulkan-runtime/src/texture.rs:2696` (+8) | `none`: a runtime extension's rebind with a live texture | +| `PvrtcBlockOrder` | A PVRTC texture's blocks in a Metal block order the runtime does not lay out | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture.rs:5465` | `rare`: PVRTC regions off whole levels | | `VertexFetchPast4GiB` | A draw (`drawPrimitives:` and its forms, or an indirect command buffer's command) that may read a vertex attribute the pipeline fetches in its... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/render/vertex_reach.rs:72` | `rare`: vertex fetch past 4 GiB of a bind offset | | `StageInFetchPast4GiB` | A dispatch (`dispatchThreads:threadsPerThreadgroup:` and its forms, or an indirect command buffer's command) whose kernel may read a... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/fetch_reach.rs:126` | `rare`: stage-in fetch past 4 GiB of a bind offset | | `MappedTextureSampling` | A command that would sample a texture of an address-mode map (`TextureDescriptor::address_mode_map`) where the runtime cannot map it at bind... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/address_map.rs:158` | `none`: a runtime extension's texture (address_mode_map) sampled where the runtime cannot map it; no Metal API path | | `LibrarySource` | A library compiled from Metal Shading Language source | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/library.rs:107` | `app`: a library compiled from Metal source (newLibraryWithSource:); the runtime takes metallibs and AIR | | `RestartedStrip` | An indexed strip after `set_primitive_restart_enabled` with an index Vulkan does not restart at, which the runtime draws as a list an index... | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/index_rewrite.rs:109`, `crates/metal2vulkan-runtime/src/render.rs:5912` | `none`: a strip after the Apple-private setPrimitiveRestartEnabled:index: whose rewrite pass cannot run as Metal draws | | `RotatedTexture` | A rotated texture (`TextureDescriptor::rotation`) where the runtime does not build what Metal does | every device (runtime piece not built) | 9: `crates/metal2vulkan-runtime/src/blit_texture.rs:1508`, `crates/metal2vulkan-runtime/src/buffer_texture.rs:706` (+7) | `rare`: a rotated drawable's views, blits with images over overlapping rows, rows past its buffer | -| `DetachTextures` | A texture over a no-copy buffer's or heap's bytes (a heap's texture, or a texture over the buffer or over one of the heap's buffers) that no... | every device (runtime piece not built) | 9: `crates/metal2vulkan-runtime/src/buffer.rs:1969`, `crates/metal2vulkan-runtime/src/buffer_descriptor.rs:583` (+7) | `none`: a runtime extension's detach with a texture no stand-in presents exactly | +| `DetachTextures` | A texture over a no-copy buffer's or heap's bytes (a heap's texture, or a texture over the buffer or over one of the heap's buffers) that no... | every device (runtime piece not built) | 9: `crates/metal2vulkan-runtime/src/buffer.rs:1999`, `crates/metal2vulkan-runtime/src/buffer_descriptor.rs:572` (+7) | `none`: a runtime extension's detach with a texture no stand-in presents exactly | | `TextureBufferLevels` | A texture buffer of more than one level (`TextureDescriptor::mipmap_level_count`, up to its width's full chain) from the device's, a heap's or the... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture_descriptor.rs:531` | `rare`: a texture buffer of more than one level (public, unusual) | | `WriteSwizzle` | A texture of `TextureDescriptor::write_swizzle_enabled` whose swizzle is not the default, with `ShaderWrite` or `RenderTarget` usage, from the... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture_descriptor.rs:538` | `none`: Apple-private writeSwizzleEnabled with a swizzle that writes | -| `DetachedTexelAccess` | `Texture::replace_region` or `get_bytes` of a texture whose bytes (a no-copy buffer's or heap's) are detached (`detach_backing`) | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture.rs:4392` | `none`: CPU texel access while a runtime extension detached the bytes | +| `DetachedTexelAccess` | `Texture::replace_region` or `get_bytes` of a texture whose bytes (a no-copy buffer's or heap's) are detached (`detach_backing`) | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture.rs:4762` | `none`: CPU texel access while a runtime extension detached the bytes | | `SurfaceDepthStencil` | A use of a texture of a depth or stencil format (`Depth16Unorm`, `Depth32Float`, `Depth32Float_Stencil8`, `Stencil8`, `X32_Stencil8`) over a plane... | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/blit_texture.rs:232`, `crates/metal2vulkan-runtime/src/texture/surface_depth.rs:56` | `rare`: a blit of the stencil of a Depth32Float_Stencil8 texture over a plane of an IOSurface with planes, or a pass on an X32_Stencil8 one's view as Depth32Float_Stencil8 | -| `HostHeapUncompressedMultisample` | A multisample texture in a heap over host pages (`Device::new_heap_with_bytes_no_copy`) that Metal keeps uncompressed | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture/heap.rs:1707` | `none`: a multisample texture Metal keeps uncompressed in a runtime extension's heap over host pages | +| `HostHeapUncompressedMultisample` | A multisample texture in a heap over host pages (`Device::new_heap_with_bytes_no_copy`) that Metal keeps uncompressed | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture/heap.rs:1719` | `none`: a multisample texture Metal keeps uncompressed in a runtime extension's heap over host pages | | `PredicationUnbalanced` | An unbalanced command-predication record (`ComputeCommandEncoder::encode_end_if` and the other ends, or `encode_start_else`, with no block open;... | every device (runtime piece not built) | 4: `crates/metal2vulkan-runtime/src/predication.rs:354`, `crates/metal2vulkan-runtime/src/predication.rs:386` (+2) | `none`: an unbalanced Apple-private command-predication record, whose dropped work Metal decides by no rule measured | | `PredicationOpenAtUnitEnd` | A command buffer one of whose units of predication ended with an If still open that no misused record killed, refused at `CommandBuffer::commit` | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/predication.rs:279` | `none`: an Apple-private predication If left open, live, where its unit ends | | `PredicationWordPastBuffer` | A predication condition word (`encode_start_if`'s offset, rounded down to a multiple of 4) past its buffer's end | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/predication.rs:139` | `none`: an Apple-private predication condition word past its buffer | @@ -269,7 +269,7 @@ Generated at `53fc528b6`. | `TypeCount` | Types in the bitcode type table | every device (a deterministic cap) | 2: `crates/metal2vulkan-air/src/bitcode/types.rs:159`, `crates/metal2vulkan-air/src/ir/types.rs:239` | `none`: a type table past the cap | | `MetadataNodes` | Metadata nodes | every device (a deterministic cap) | 3: `crates/metal2vulkan-air/src/bitcode/function.rs:334`, `crates/metal2vulkan-air/src/bitcode/metadata.rs:192` (+1) | `none`: metadata past the cap | | `BitstreamNesting` | Bitstream block nesting | every device (a deterministic cap) | 1: `crates/metal2vulkan-air/src/bitstream/mod.rs:267` | `none`: malformed nesting | -| `InstructionCount` | Instructions of the decoded module | every device (a deterministic cap) | 8: `crates/metal2vulkan-air/src/bitcode/function.rs:1467`, `crates/metal2vulkan-air/src/bitcode/function.rs:180` (+6) | `rare`: very large modules | +| `InstructionCount` | Instructions of the decoded module | every device (a deterministic cap) | 8: `crates/metal2vulkan-air/src/bitcode/function.rs:1462`, `crates/metal2vulkan-air/src/bitcode/function.rs:180` (+6) | `rare`: very large modules | | `LayoutNesting` | Nesting depth of `air.struct_type_info` layouts and the argument-buffer members inside them | every device (a deterministic cap) | 3: `crates/metal2vulkan-air/src/abi/structs.rs:147`, `crates/metal2vulkan-air/src/abi/structs.rs:160` (+1) | `none`: argument-buffer layouts nested past the cap | | `ConstructNesting` | Nesting depth of structured constructs the structurizer emits (P8 recurses once per level) | every device (a deterministic cap) | 2: `crates/metal2vulkan/src/structurize/emit.rs:216`, `crates/metal2vulkan/src/structurize/emit/predicate.rs:151` | `none`: control flow nested past the cap | | `PrivateArenaBytes` | Bytes of a function's private arena, whose pointers are `u32` byte offsets | every device (a deterministic cap) | 3: `crates/metal2vulkan/src/lower/access/local.rs:595`, `crates/metal2vulkan/src/memory/plan.rs:1684` (+1) | `none`: a private arena past 4 GiB | @@ -299,9 +299,9 @@ Each refusal's sites, with the function that builds it. - `feature::Stage`: `crates/metal2vulkan-air/src/abi/check.rs:579 (unsupported_stage)`; `crates/metal2vulkan/src/error/mod.rs:246 (from)` - `feature::AddressSpace`: `crates/metal2vulkan-air/src/ir/types.rs:191 (from_raw)`; `crates/metal2vulkan/src/memory/plan.rs:1854 (reprs)` - `feature::ModuleRecord`: `crates/metal2vulkan-air/src/bitcode/module.rs:343 (record)`; `crates/metal2vulkan-air/src/bitcode/module.rs:435 (global)`; `crates/metal2vulkan-air/src/bitcode/module.rs:514 (function)`; `crates/metal2vulkan/src/error/mod.rs:248 (from)` -- `feature::Instruction`: `crates/metal2vulkan-air/src/bitcode/function.rs:1015 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1062 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1083 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1140 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1214 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1222 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1238 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1343 (call)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1385 (call)`; `crates/metal2vulkan-air/src/bitcode/function.rs:828 (record)`; `crates/metal2vulkan/src/error/mod.rs:249 (from)` +- `feature::Instruction`: `crates/metal2vulkan-air/src/bitcode/function.rs:1010 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1057 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1078 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1135 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1209 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1217 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1233 (record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1338 (call)`; `crates/metal2vulkan-air/src/bitcode/function.rs:1380 (call)`; `crates/metal2vulkan-air/src/bitcode/function.rs:823 (record)`; `crates/metal2vulkan/src/error/mod.rs:249 (from)` - `feature::Type`: `crates/metal2vulkan-air/src/bitcode/types.rs:184 (decode)`; `crates/metal2vulkan-air/src/bitcode/types.rs:206 (decode)`; `crates/metal2vulkan-air/src/bitcode/types.rs:232 (decode)`; `crates/metal2vulkan/src/error/mod.rs:250 (from)` -- `feature::CallingConvention`: `crates/metal2vulkan-air/src/bitcode/function.rs:1359 (call)`; `crates/metal2vulkan-air/src/bitcode/module.rs:499 (function)`; `crates/metal2vulkan/src/error/mod.rs:251 (from)` +- `feature::CallingConvention`: `crates/metal2vulkan-air/src/bitcode/function.rs:1354 (call)`; `crates/metal2vulkan-air/src/bitcode/module.rs:499 (function)`; `crates/metal2vulkan/src/error/mod.rs:251 (from)` - `feature::UnknownIntrinsic`: `crates/metal2vulkan-air/src/error.rs:621 (from)`; `crates/metal2vulkan/src/lower/select.rs:990 (route)` - `feature::AgxUnmodeled`: `crates/metal2vulkan/src/lower/simd/agx.rs:62 (unmodeled)` - `feature::StaticInitializer`: `crates/metal2vulkan-air/src/error.rs:627 (from)` @@ -326,18 +326,18 @@ Each refusal's sites, with the function that builds it. - `feature::ThreadgroupMemorySize`: `crates/metal2vulkan/src/bind/plan/compute.rs:710 (plan)`; `crates/metal2vulkan/src/memory/arena.rs:169 (check)`; `crates/metal2vulkan/src/memory/plan.rs:457 (too_large)` - `feature::CoherentMemory`: `crates/metal2vulkan/src/lower/sync/memory_model.rs:152 (check)` - `feature::Int64Atomics`: `crates/metal2vulkan/src/lower/access/atomic.rs:624 (select)`; `crates/metal2vulkan/src/lower/access/atomic.rs:633 (select)` -- `feature::ImageAtomics`: `crates/metal2vulkan-runtime/src/families/formats.rs:476 (atomic_gap)`; `crates/metal2vulkan-runtime/src/families/formats.rs:480 (atomic_gap)`; `crates/metal2vulkan/src/lower/texture/slot.rs:871 (atomic_format)` +- `feature::ImageAtomics`: `crates/metal2vulkan-runtime/src/families/formats.rs:476 (atomic_gap)`; `crates/metal2vulkan-runtime/src/families/formats.rs:480 (atomic_gap)`; `crates/metal2vulkan/src/lower/texture/slot.rs:880 (atomic_format)` - `feature::DescriptorCount`: `crates/metal2vulkan/src/lower/access/mod.rs:1640 (accept_placement)`; `crates/metal2vulkan/src/lower/select.rs:1615 (finish)`; `crates/metal2vulkan/src/pipeline/link.rs:989 (limit_error)` - `feature::BufferRange`: `crates/metal2vulkan-runtime/src/function_table.rs:575 (past_storage_buffer_range)`; `crates/metal2vulkan/src/bind/graphics.rs:2890 (patch_draw)`; `crates/metal2vulkan/src/bind/graphics.rs:2936 (patch_draw)`; `crates/metal2vulkan/src/bind/graphics.rs:2965 (patch_draw)`; `crates/metal2vulkan/src/bind/instantiate.rs:578 (bind_buffers)`; `crates/metal2vulkan/src/lower/access/function_table.rs:226 (select)`; `crates/metal2vulkan/src/lower/access/mod.rs:1155 (place_slots)` - `feature::Int64Arithmetic`: `crates/metal2vulkan/src/lower/arith/legal.rs:582 (check_scalar)`; `crates/metal2vulkan/src/lower/select.rs:1117 (selector_form)` - `feature::Float64Arithmetic`: `crates/metal2vulkan/src/device/metal.rs:230 (unsupported_features)`; `crates/metal2vulkan/src/lower/arith/legal.rs:587 (check_scalar)` -- `feature::Format`: `crates/metal2vulkan-runtime/src/binding_view.rs:146 (binding_view)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:450 (check_formats)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:464 (check_formats)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:521 (pair_unit)`; `crates/metal2vulkan-runtime/src/blit_texture.rs:1980 (through_buffer)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:512 (make_texture_over)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:576 (make_texture_over)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:608 (make_texture_over)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:841 (texture_buffer_texel)`; `crates/metal2vulkan-runtime/src/copy_plan.rs:270 (colour_unit)`; `crates/metal2vulkan-runtime/src/copy_plan.rs:298 (copy_unit)`; `crates/metal2vulkan-runtime/src/copy_plan.rs:344 (copy_unit)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:345 (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:525 (usable_twin)`; `crates/metal2vulkan-runtime/src/families/features.rs:1555 (read_write_tier)`; `crates/metal2vulkan-runtime/src/families/formats.rs:1640 (sparse_missing)`; `crates/metal2vulkan-runtime/src/families/formats.rs:228 (none)`; `crates/metal2vulkan-runtime/src/families/formats.rs:272 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:292 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:307 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:365 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:404 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:486 (atomic_gap)`; `crates/metal2vulkan-runtime/src/families/formats.rs:520 (lacking)`; `crates/metal2vulkan-runtime/src/families/formats.rs:534 (unsupported)`; `crates/metal2vulkan-runtime/src/image_plan.rs:516 (check_own_memory)`; `crates/metal2vulkan-runtime/src/image_plan.rs:628 (plan_held)`; `crates/metal2vulkan-runtime/src/image_plan.rs:713 (plan_held)`; `crates/metal2vulkan-runtime/src/image_plan.rs:826 (plan_held)`; `crates/metal2vulkan-runtime/src/render.rs:5267 (viewing)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1259 (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1578 (target)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1657 (attachment_format)`; `crates/metal2vulkan-runtime/src/render_pass.rs:926 (check_target)`; `crates/metal2vulkan-runtime/src/resolve.rs:387 (unmodelled_resolve)`; `crates/metal2vulkan-runtime/src/sample_copy.rs:176 (checked_twin)`; `crates/metal2vulkan-runtime/src/sample_copy.rs:204 (plan)`; `crates/metal2vulkan-runtime/src/sample_interleave.rs:295 (interleave_merge)`; `crates/metal2vulkan-runtime/src/shadow.rs:352 (unmerged)`; `crates/metal2vulkan-runtime/src/shadow.rs:359 (unmerged)`; `crates/metal2vulkan-runtime/src/texture.rs:1717 (texture_as)`; `crates/metal2vulkan-runtime/src/texture.rs:3269 (two_planes_refused)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1604 (new_heap_texture)`; `crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs:79 (refused)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs:115 (converted_storage)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs:275 (ycbcr_write_shadow)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs:378 (new_render_shadow)`; `crates/metal2vulkan-runtime/src/two_planes.rs:115 (unmeasured)`; `crates/metal2vulkan-runtime/src/view_plan.rs:359 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:372 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:379 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:389 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:399 (check_format)`; `crates/metal2vulkan-runtime/src/ycbcr.rs:271 (refused)`; `crates/metal2vulkan/src/bind/extended_shadow.rs:184 (extended_shadow_module)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1705 (extended_sampler)`; `crates/metal2vulkan/src/bind/plan/resources.rs:192 (require_filter_features)`; `crates/metal2vulkan/src/bind/plan/resources.rs:953 (plain_texture)`; `crates/metal2vulkan/src/bind/sample_interleave.rs:304 (finish)`; `crates/metal2vulkan/src/bind/unused_bits.rs:545 (unused_bits_module)`; `crates/metal2vulkan/src/lower/access/tile.rs:1029 (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs:154 (select_param)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1297 (select_output)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1323 (select_output)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:678 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:699 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:705 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:711 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:736 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:855 (plan)`; `crates/metal2vulkan/src/lower/sampler/select.rs:716 (texel_in)`; `crates/metal2vulkan/src/lower/sampler/select.rs:999 (select_extended)`; `crates/metal2vulkan/src/lower/stage_io/extended_color.rs:77 (plan)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1793 (entry)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:776 (zeroed_output)`; `crates/metal2vulkan/src/lower/texture/mod.rs:2279 (select)`; `crates/metal2vulkan/src/lower/texture/mod.rs:2893 (cross_class)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3065 (select_image)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3235 (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3272 (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3596 (select_write)`; `crates/metal2vulkan/src/lower/texture/slot.rs:1006 (declare_slot)`; `crates/metal2vulkan/src/lower/texture/slot.rs:1018 (declare_slot)`; `crates/metal2vulkan/src/lower/texture/slot.rs:1024 (declare_slot)`; `crates/metal2vulkan/src/lower/texture/slot.rs:727 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:730 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:741 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:755 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:772 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:796 (ulong_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:807 (ulong_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:844 (ulong_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:879 (atomic_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:888 (atomic_format)`; `crates/metal2vulkan/src/metal/format/mod.rs:1500 (vk_format)`; `crates/metal2vulkan/src/metal/format/mod.rs:1502 (vk_format)`; `crates/metal2vulkan/src/metal/format/mod.rs:1545 (candidates)`; `crates/metal2vulkan/src/metal/format/mod.rs:2475 (storage_choice_viewed)`; `crates/metal2vulkan/src/metal/format/mod.rs:2493 (held_storage_choice)`; `crates/metal2vulkan/src/metal/format/mod.rs:2501 (held_storage_choice)`; `crates/metal2vulkan/src/metal/format/mod.rs:2573 (held_storage_choice)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:345 (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:453 (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:830 (reads_alpha_to_coverage)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:847 (reads_alpha_to_coverage)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:956 (extended_write_mask)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs:450 (rotated_blend)` +- `feature::Format`: `crates/metal2vulkan-runtime/src/binding_view.rs:146 (binding_view)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:450 (check_formats)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:464 (check_formats)`; `crates/metal2vulkan-runtime/src/blit_plan.rs:521 (pair_unit)`; `crates/metal2vulkan-runtime/src/blit_texture.rs:1980 (through_buffer)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:512 (make_texture_over)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:576 (make_texture_over)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:608 (make_texture_over)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:841 (texture_buffer_texel)`; `crates/metal2vulkan-runtime/src/copy_plan.rs:270 (colour_unit)`; `crates/metal2vulkan-runtime/src/copy_plan.rs:298 (copy_unit)`; `crates/metal2vulkan-runtime/src/copy_plan.rs:344 (copy_unit)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:345 (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:525 (usable_twin)`; `crates/metal2vulkan-runtime/src/families/features.rs:1555 (read_write_tier)`; `crates/metal2vulkan-runtime/src/families/formats.rs:1640 (sparse_missing)`; `crates/metal2vulkan-runtime/src/families/formats.rs:228 (none)`; `crates/metal2vulkan-runtime/src/families/formats.rs:272 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:292 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:307 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:365 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:404 (answers)`; `crates/metal2vulkan-runtime/src/families/formats.rs:486 (atomic_gap)`; `crates/metal2vulkan-runtime/src/families/formats.rs:520 (lacking)`; `crates/metal2vulkan-runtime/src/families/formats.rs:534 (unsupported)`; `crates/metal2vulkan-runtime/src/image_plan.rs:516 (check_own_memory)`; `crates/metal2vulkan-runtime/src/image_plan.rs:628 (plan_held)`; `crates/metal2vulkan-runtime/src/image_plan.rs:713 (plan_held)`; `crates/metal2vulkan-runtime/src/image_plan.rs:826 (plan_held)`; `crates/metal2vulkan-runtime/src/render.rs:5267 (viewing)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1259 (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1578 (target)`; `crates/metal2vulkan-runtime/src/render_pass.rs:1657 (attachment_format)`; `crates/metal2vulkan-runtime/src/render_pass.rs:926 (check_target)`; `crates/metal2vulkan-runtime/src/resolve.rs:387 (unmodelled_resolve)`; `crates/metal2vulkan-runtime/src/sample_copy.rs:176 (checked_twin)`; `crates/metal2vulkan-runtime/src/sample_copy.rs:204 (plan)`; `crates/metal2vulkan-runtime/src/sample_interleave.rs:295 (interleave_merge)`; `crates/metal2vulkan-runtime/src/shadow.rs:352 (unmerged)`; `crates/metal2vulkan-runtime/src/shadow.rs:359 (unmerged)`; `crates/metal2vulkan-runtime/src/texture.rs:1833 (texture_as)`; `crates/metal2vulkan-runtime/src/texture.rs:3639 (two_planes_refused)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1610 (new_heap_texture)`; `crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs:79 (refused)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs:115 (converted_storage)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs:275 (ycbcr_write_shadow)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs:378 (new_render_shadow)`; `crates/metal2vulkan-runtime/src/two_planes.rs:115 (unmeasured)`; `crates/metal2vulkan-runtime/src/view_plan.rs:359 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:372 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:379 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:389 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:399 (check_format)`; `crates/metal2vulkan-runtime/src/ycbcr.rs:271 (refused)`; `crates/metal2vulkan/src/bind/extended_shadow.rs:184 (extended_shadow_module)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1705 (extended_sampler)`; `crates/metal2vulkan/src/bind/plan/resources.rs:192 (require_filter_features)`; `crates/metal2vulkan/src/bind/plan/resources.rs:953 (plain_texture)`; `crates/metal2vulkan/src/bind/sample_interleave.rs:304 (finish)`; `crates/metal2vulkan/src/bind/unused_bits.rs:545 (unused_bits_module)`; `crates/metal2vulkan/src/lower/access/tile.rs:1029 (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs:154 (select_param)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1299 (select_output)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1325 (select_output)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:680 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:701 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:707 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:713 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:738 (extended_range_blend)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:857 (plan)`; `crates/metal2vulkan/src/lower/sampler/select.rs:716 (texel_in)`; `crates/metal2vulkan/src/lower/sampler/select.rs:999 (select_extended)`; `crates/metal2vulkan/src/lower/stage_io/extended_color.rs:77 (plan)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1795 (entry)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:776 (zeroed_output)`; `crates/metal2vulkan/src/lower/texture/mod.rs:2279 (select)`; `crates/metal2vulkan/src/lower/texture/mod.rs:2893 (cross_class)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3065 (select_image)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3235 (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3272 (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3596 (select_write)`; `crates/metal2vulkan/src/lower/texture/slot.rs:1015 (declare_slot)`; `crates/metal2vulkan/src/lower/texture/slot.rs:1027 (declare_slot)`; `crates/metal2vulkan/src/lower/texture/slot.rs:1033 (declare_slot)`; `crates/metal2vulkan/src/lower/texture/slot.rs:733 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:736 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:747 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:761 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:778 (storage_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:802 (ulong_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:813 (ulong_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:853 (ulong_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:888 (atomic_format)`; `crates/metal2vulkan/src/lower/texture/slot.rs:897 (atomic_format)`; `crates/metal2vulkan/src/metal/format/mod.rs:1500 (vk_format)`; `crates/metal2vulkan/src/metal/format/mod.rs:1502 (vk_format)`; `crates/metal2vulkan/src/metal/format/mod.rs:1545 (candidates)`; `crates/metal2vulkan/src/metal/format/mod.rs:2475 (storage_choice_viewed)`; `crates/metal2vulkan/src/metal/format/mod.rs:2493 (held_storage_choice)`; `crates/metal2vulkan/src/metal/format/mod.rs:2501 (held_storage_choice)`; `crates/metal2vulkan/src/metal/format/mod.rs:2573 (held_storage_choice)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:345 (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:453 (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:830 (reads_alpha_to_coverage)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:847 (reads_alpha_to_coverage)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:956 (extended_write_mask)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs:450 (rotated_blend)` - `feature::DivergentImplicitLod`: `crates/metal2vulkan/src/lower/sampler/select.rs:377 (select_sampling)` - `feature::ImplicitLodOutsideFragment`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs:136 (query_min_level)`; `crates/metal2vulkan/src/lower/sampler/select.rs:254 (query_level_measured)`; `crates/metal2vulkan/src/lower/sampler/select.rs:280 (query_min_level)` - `feature::MinLodClamp`: `crates/metal2vulkan/src/lower/sampler/select.rs:1311 (select_one)`; `crates/metal2vulkan/src/lower/sampler/select.rs:891 (min_lod)` - `feature::TexelOffset`: `crates/metal2vulkan/src/lower/sampler/select.rs:750 (offset)`; `crates/metal2vulkan/src/lower/sampler/select.rs:824 (in_device_range)` - `feature::GatherExtended`: `crates/metal2vulkan/src/lower/sampler/select.rs:782 (dynamic_offset)` -- `feature::StorageImageMultisample`: `crates/metal2vulkan/src/lower/texture/slot.rs:1037 (declare_slot)` +- `feature::StorageImageMultisample`: `crates/metal2vulkan/src/lower/texture/slot.rs:1046 (declare_slot)` - `feature::StorageTextureInVertexStage`: `crates/metal2vulkan/src/lower/texture/slot.rs:666 (stage_stores)` - `feature::CubeArray`: `crates/metal2vulkan/src/lower/sampler/select.rs:1214 (select_one)`; `crates/metal2vulkan/src/lower/texture/slot.rs:456 (declare_heap)` - `feature::SamplerAnisotropy`: `crates/metal2vulkan/src/lower/sampler/select.rs:1409 (select_one)`; `crates/metal2vulkan/src/metal/sampler.rs:255 (check_sampler)`; `crates/metal2vulkan/src/metal/sampler.rs:258 (check_sampler)` @@ -347,36 +347,36 @@ Each refusal's sites, with the function that builds it. - `feature::PixelSamplerCompare`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs:115 (lowered)` - `feature::TexelBuffer`: `crates/metal2vulkan/src/bind/instantiate.rs:731 (texel_ranges)`; `crates/metal2vulkan/src/bind/instantiate.rs:737 (texel_ranges)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1113 (plain_texture)` - `feature::RasterOrderGroups`: `crates/metal2vulkan/src/device/metal.rs:242 (unsupported_features)`; `crates/metal2vulkan/src/lower/fragment/rog.rs:151 (mode)`; `crates/metal2vulkan/src/lower/fragment/rog.rs:172 (mode)` -- `feature::FramebufferFetch`: `crates/metal2vulkan-runtime/src/families/features.rs:1007 (state)`; `crates/metal2vulkan-runtime/src/framebuffer_fetch.rs:354 (ordered)`; `crates/metal2vulkan-runtime/src/render.rs:4359 (next_instance)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:110 (lacks)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:137 (new)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:496 (planes_merge)`; `crates/metal2vulkan/src/bind/extended_shadow.rs:190 (extended_shadow_module)`; `crates/metal2vulkan/src/bind/graphics.rs:1013 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:1050 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:1069 (plan)`; `crates/metal2vulkan/src/bind/sample_planes.rs:431 (finish)`; `crates/metal2vulkan/src/device/metal.rs:255 (unsupported_features)`; `crates/metal2vulkan/src/lower/fragment/color.rs:208 (select_param)`; `crates/metal2vulkan/src/lower/fragment/color.rs:257 (unordered)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:196 (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:271 (depth_test_form)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:317 (stencil_test_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1148 (plan_sample)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:383 (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:591 (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:655 (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:691 (extended_range_blend)`; `crates/metal2vulkan/src/pipeline/link/fetch.rs:159 (storage_attachments)` +- `feature::FramebufferFetch`: `crates/metal2vulkan-runtime/src/families/features.rs:1007 (state)`; `crates/metal2vulkan-runtime/src/framebuffer_fetch.rs:354 (ordered)`; `crates/metal2vulkan-runtime/src/render.rs:4359 (next_instance)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:110 (lacks)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:137 (new)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:496 (planes_merge)`; `crates/metal2vulkan/src/bind/extended_shadow.rs:190 (extended_shadow_module)`; `crates/metal2vulkan/src/bind/graphics.rs:1013 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:1050 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:1069 (plan)`; `crates/metal2vulkan/src/bind/sample_planes.rs:431 (finish)`; `crates/metal2vulkan/src/device/metal.rs:255 (unsupported_features)`; `crates/metal2vulkan/src/lower/fragment/color.rs:208 (select_param)`; `crates/metal2vulkan/src/lower/fragment/color.rs:257 (unordered)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:196 (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:271 (depth_test_form)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:317 (stencil_test_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1150 (plan_sample)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:383 (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:591 (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:657 (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:693 (extended_range_blend)`; `crates/metal2vulkan/src/pipeline/link/fetch.rs:159 (storage_attachments)` - `feature::PrimitiveId`: `crates/metal2vulkan/src/device/metal.rs:264 (unsupported_features)` - `feature::VertexAmplification`: `crates/metal2vulkan/src/bind/graphics.rs:3109 (multiview_instances)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:646 (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:219 (vertex_amplification)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:238 (control_plan)` - `feature::LayeredRendering`: `crates/metal2vulkan-runtime/src/render_pass.rs:1538 (target)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:736 (target_index)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:755 (target_index)` - `feature::ClipDistance`: `crates/metal2vulkan/src/lower/mesh/mod.rs:892 (select)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:900 (select)` - `feature::DualSourceBlending`: `crates/metal2vulkan-runtime/src/families/formats.rs:398 (answers)`; `crates/metal2vulkan/src/metal/state.rs:37 (blend_factor)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:1013 (check_outputs)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs:464 (rotated_blend)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs:539 (rotated_blend)` -- `feature::Barycentrics`: `crates/metal2vulkan/src/lower/stage_io/plan.rs:1460 (input_builtin)` +- `feature::Barycentrics`: `crates/metal2vulkan/src/lower/stage_io/plan.rs:1462 (input_builtin)` - `feature::StencilExport`: `crates/metal2vulkan-runtime/src/families/features.rs:1091 (state)`; `crates/metal2vulkan/src/bind/graphics.rs:2058 (shadow_stencil_words)`; `crates/metal2vulkan/src/lower/fragment/stencil.rs:157 (device_form)`; `crates/metal2vulkan/src/lower/fragment/stencil.rs:168 (not_implemented)`; `crates/metal2vulkan/src/pipeline/link/stencil.rs:55 (shadow_stencil)`; `crates/metal2vulkan/src/pipeline/link/stencil.rs:73 (shadow_stencil)` - `feature::SampleRateShading`: `crates/metal2vulkan/src/pipeline/link/graphics.rs:700 (sample_invocations)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:702 (sample_invocations)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:789 (sample_invocations)` -- `feature::PixelCoverageAtSampleRate`: `crates/metal2vulkan/src/lower/fragment/coverage.rs:291 (finish)`; `crates/metal2vulkan/src/lower/simd/mod.rs:735 (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:735 (sample_invocations)` +- `feature::PixelCoverageAtSampleRate`: `crates/metal2vulkan/src/lower/fragment/coverage.rs:291 (finish)`; `crates/metal2vulkan/src/lower/simd/mod.rs:739 (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:735 (sample_invocations)` - `feature::InterfaceComponents`: `crates/metal2vulkan/src/pipeline/link/graphics.rs:256 (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:343 (assign)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:77 (limit_error)` - `feature::UnmatchedVarying`: `crates/metal2vulkan/src/pipeline/link/varyings.rs:253 (mesh_fragment)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:439 (varyings)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:450 (varyings)` - `feature::KernelStageIn`: `crates/metal2vulkan-runtime/src/indirect_execute.rs:337 (record)`; `crates/metal2vulkan/src/bind/dispatch.rs:881 (instantiate)`; `crates/metal2vulkan/src/lower/stage_io/stage_in.rs:133 (select)` -- `feature::Tessellation`: `crates/metal2vulkan-air/src/canon/mod.rs:1220 (post_check)`; `crates/metal2vulkan-air/src/canon/mod.rs:1311 (post_check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs:519 (select)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1328 (input_builtin)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:710 (param)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:100 (not_implemented)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:432 (plan_entry)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:435 (plan_entry)`; `crates/metal2vulkan/src/metal/vertex.rs:219 (fetch_as)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:222 (control_plan)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:251 (check_fragment)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:275 (push_offset)` +- `feature::Tessellation`: `crates/metal2vulkan-air/src/canon/mod.rs:1220 (post_check)`; `crates/metal2vulkan-air/src/canon/mod.rs:1311 (post_check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs:519 (select)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1330 (input_builtin)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:710 (param)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:100 (not_implemented)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:432 (plan_entry)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:435 (plan_entry)`; `crates/metal2vulkan/src/metal/vertex.rs:219 (fetch_as)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:222 (control_plan)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:251 (check_fragment)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:275 (push_offset)` - `feature::MeshShading`: `crates/metal2vulkan/src/bind/graphics.rs:1096 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:2398 (mesh_limit)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:459 (check_payload)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:496 (plan_entry)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:530 (plan_entry)`; `crates/metal2vulkan/src/memory/plan.rs:1849 (reprs)`; `crates/metal2vulkan/src/pipeline/link/mesh.rs:72 (records)` - `feature::TileShading`: `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs:497 (scratch)`; `crates/metal2vulkan/src/bind/plan/compute.rs:236 (tile_memory)`; `crates/metal2vulkan/src/lower/access/tile.rs:151 (not_implemented)`; `crates/metal2vulkan/src/lower/sync/barrier.rs:275 (tile_shading)`; `crates/metal2vulkan/src/pipeline/compile/api.rs:607 (tile_pipeline)` - `feature::Imageblocks`: `crates/metal2vulkan/src/lower/access/imageblock.rs:98 (imageblocks)`; `crates/metal2vulkan/src/lower/access/mod.rs:879 (select_param)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs:103 (require)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs:85 (not_implemented)`; `crates/metal2vulkan/src/lower/texture/mod.rs:2289 (select)`; `crates/metal2vulkan/src/lower/texture/slice.rs:127 (imageblocks)`; `crates/metal2vulkan/src/pipeline/link/imageblock.rs:46 (fragment_imageblock)` - `feature::RayTracing`: `crates/metal2vulkan/src/bind/acceleration.rs:202 (instance_record)`; `crates/metal2vulkan/src/bind/acceleration.rs:216 (instance_record)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1087 (primitive_data_read)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1202 (instance_count)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1245 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1257 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1282 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1297 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:1312 (intersect)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:344 (slot_of)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:385 (select_param)`; `crates/metal2vulkan/src/lower/select.rs:883 (route_air)` - `feature::Tensors`: `crates/metal2vulkan-air/src/canon/matmul2d/synth.rs:32 (refuse)`; `crates/metal2vulkan/src/lower/select.rs:887 (route_air)` - `feature::RasterizationRateMap`: `crates/metal2vulkan/src/lower/fragment/mod.rs:875 (select)` -- `feature::GpuEncodedIndirectCommands`: `crates/metal2vulkan/src/bind/replay.rs:530 (preprocess)`; `crates/metal2vulkan/src/bind/replay.rs:770 (replay_preprocess_module)`; `crates/metal2vulkan/src/bind/replay/flat.rs:247 (flat_dispatch_module)`; `crates/metal2vulkan/src/lower/access/encode.rs:390 (needs)`; `crates/metal2vulkan/src/lower/access/encode.rs:406 (needs)`; `crates/metal2vulkan/src/lower/access/encode.rs:518 (select_command)`; `crates/metal2vulkan/src/lower/access/mod.rs:1509 (plan_replay)`; `crates/metal2vulkan/src/lower/access/mod.rs:1522 (plan_replay)`; `crates/metal2vulkan/src/lower/access/mod.rs:1525 (plan_replay)`; `crates/metal2vulkan/src/pipeline/compile.rs:1888 (plan_one)`; `crates/metal2vulkan/src/pipeline/compile.rs:1893 (plan_one)` +- `feature::GpuEncodedIndirectCommands`: `crates/metal2vulkan/src/bind/replay.rs:530 (preprocess)`; `crates/metal2vulkan/src/bind/replay.rs:772 (replay_preprocess_module)`; `crates/metal2vulkan/src/bind/replay/flat.rs:247 (flat_dispatch_module)`; `crates/metal2vulkan/src/lower/access/encode.rs:390 (needs)`; `crates/metal2vulkan/src/lower/access/encode.rs:406 (needs)`; `crates/metal2vulkan/src/lower/access/encode.rs:518 (select_command)`; `crates/metal2vulkan/src/lower/access/mod.rs:1509 (plan_replay)`; `crates/metal2vulkan/src/lower/access/mod.rs:1522 (plan_replay)`; `crates/metal2vulkan/src/lower/access/mod.rs:1525 (plan_replay)`; `crates/metal2vulkan/src/pipeline/compile.rs:1888 (plan_one)`; `crates/metal2vulkan/src/pipeline/compile.rs:1893 (plan_one)` - `feature::VulkanVersion`: `crates/metal2vulkan/src/ash_interop/query.rs:898 (query)`; `crates/metal2vulkan/src/device/derive.rs:101 (with_deviations)` - `feature::Constant`: `crates/metal2vulkan-air/src/bitcode/constants.rs:210 (record)`; `crates/metal2vulkan-air/src/bitcode/constants.rs:268 (record)`; `crates/metal2vulkan/src/error/mod.rs:257 (from)` - `feature::Attribute`: `crates/metal2vulkan-air/src/bitcode/attrs.rs:493 (known)`; `crates/metal2vulkan/src/error/mod.rs:258 (from)` -- `feature::BitcodeRecord`: `crates/metal2vulkan-air/src/bitcode/attrs.rs:337 (decode_lists)`; `crates/metal2vulkan-air/src/bitcode/function.rs:577 (symtab)`; `crates/metal2vulkan-air/src/bitcode/metadata.rs:130 (decode)`; `crates/metal2vulkan-air/src/bitcode/metadata.rs:157 (decode)`; `crates/metal2vulkan-air/src/bitcode/module.rs:727 (check_bodies)`; `crates/metal2vulkan-air/src/bitcode/module.rs:872 (symtab)`; `crates/metal2vulkan/src/error/mod.rs:259 (from)` -- `feature::SyncScope`: `crates/metal2vulkan-air/src/bitcode/function.rs:1260 (atomic)`; `crates/metal2vulkan/src/error/mod.rs:260 (from)` -- `feature::SubgroupOperations`: `crates/metal2vulkan-runtime/src/families/features.rs:1643 (simd)`; `crates/metal2vulkan/src/lower/simd/mod.rs:402 (finish)`; `crates/metal2vulkan/src/lower/simd/mod.rs:448 (full_quads)`; `crates/metal2vulkan/src/lower/simd/mod.rs:971 (select_group)` +- `feature::BitcodeRecord`: `crates/metal2vulkan-air/src/bitcode/attrs.rs:337 (decode_lists)`; `crates/metal2vulkan-air/src/bitcode/function.rs:572 (symtab)`; `crates/metal2vulkan-air/src/bitcode/metadata.rs:130 (decode)`; `crates/metal2vulkan-air/src/bitcode/metadata.rs:157 (decode)`; `crates/metal2vulkan-air/src/bitcode/module.rs:727 (check_bodies)`; `crates/metal2vulkan-air/src/bitcode/module.rs:872 (symtab)`; `crates/metal2vulkan/src/error/mod.rs:259 (from)` +- `feature::SyncScope`: `crates/metal2vulkan-air/src/bitcode/function.rs:1255 (atomic)`; `crates/metal2vulkan/src/error/mod.rs:260 (from)` +- `feature::SubgroupOperations`: `crates/metal2vulkan-runtime/src/families/features.rs:1643 (simd)`; `crates/metal2vulkan/src/lower/simd/mod.rs:402 (finish)`; `crates/metal2vulkan/src/lower/simd/mod.rs:448 (full_quads)`; `crates/metal2vulkan/src/lower/simd/mod.rs:975 (select_group)` - `feature::DirectCall`: `crates/metal2vulkan-air/src/canon/mod.rs:1283 (post_check)` - `feature::WideSwitchLiteral`: `crates/metal2vulkan/src/structurize/emit.rs:207 (check_tree)` -- `feature::Lowering`: `crates/metal2vulkan/src/bind/plan/resources.rs:755 (level_views)`; `crates/metal2vulkan/src/lower/access/handle.rs:1062 (texture_target)`; `crates/metal2vulkan/src/lower/access/handle.rs:1073 (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs:318 (domain_kind)`; `crates/metal2vulkan/src/lower/access/imageblock.rs:175 (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs:571 (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs:76 (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs:53 (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs:113 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs:144 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs:653 (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs:111 (not_lowered)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:144 (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:126 (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs:207 (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs:30 (refuse)`; `crates/metal2vulkan/src/lower/select.rs:813 (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs:902 (route_air)`; `crates/metal2vulkan/src/lower/simd/mod.rs:136 (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs:728 (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs:353 (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs:96 (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs:134 (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs:72 (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs:212 (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs:249 (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:96 (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs:178 (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3565 (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs:46 (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs:183 (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs:453 (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs:662 (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:92 (patch_fetch_projection)` +- `feature::Lowering`: `crates/metal2vulkan/src/bind/plan/resources.rs:755 (level_views)`; `crates/metal2vulkan/src/lower/access/handle.rs:1062 (texture_target)`; `crates/metal2vulkan/src/lower/access/handle.rs:1073 (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs:318 (domain_kind)`; `crates/metal2vulkan/src/lower/access/imageblock.rs:175 (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs:571 (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs:76 (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs:53 (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs:113 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs:144 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs:653 (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs:111 (not_lowered)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:144 (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:126 (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs:207 (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs:30 (refuse)`; `crates/metal2vulkan/src/lower/select.rs:813 (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs:902 (route_air)`; `crates/metal2vulkan/src/lower/simd/mod.rs:136 (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs:732 (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs:353 (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs:96 (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs:134 (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs:72 (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs:212 (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs:249 (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:96 (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs:178 (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3565 (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs:46 (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs:183 (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs:453 (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs:662 (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:92 (patch_fetch_projection)` - `feature::SamplerAddressMode`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs:176`; `crates/metal2vulkan/src/metal/sampler.rs:248 (check_sampler)` - `feature::AlphaToOne`: `crates/metal2vulkan/src/pipeline/link/graphics.rs:243 (graphics_state)` - `feature::StageStoresAndAtomics`: `crates/metal2vulkan/src/lower/access/tile_memory.rs:73 (written)` @@ -394,9 +394,9 @@ Each refusal's sites, with the function that builds it. - `feature::TextureSize`: `crates/metal2vulkan-runtime/src/image_plan.rs:1062 (check_image_limits)` - `feature::TextureSampleCount`: `crates/metal2vulkan-runtime/src/image_plan.rs:1110 (check_image_limits)`; `crates/metal2vulkan-runtime/src/image_plan.rs:570 (plan_held)`; `crates/metal2vulkan-runtime/src/image_plan.rs:580 (plan_held)` - `feature::TextureView`: `crates/metal2vulkan-runtime/src/binding_view.rs:156 (binding_view)`; `crates/metal2vulkan-runtime/src/texture/view_shadow.rs:184 (apart_refusal)`; `crates/metal2vulkan-runtime/src/view_plan.rs:411 (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs:461 (check_view)`; `crates/metal2vulkan-runtime/src/view_plan.rs:483 (check_view)` -- `feature::TextureSwizzle`: `crates/metal2vulkan-runtime/src/binding_view.rs:167 (binding_view)`; `crates/metal2vulkan-runtime/src/texture.rs:775 (view)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1088 (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs:2275 (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3300 (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3637 (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs:294 (select)` +- `feature::TextureSwizzle`: `crates/metal2vulkan-runtime/src/binding_view.rs:167 (binding_view)`; `crates/metal2vulkan-runtime/src/texture.rs:885 (view)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1088 (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs:2275 (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3300 (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3637 (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs:294 (select)` - `feature::MipmapGeneration`: `crates/metal2vulkan-runtime/src/blit_texture.rs:1689 (generate_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_pick.rs:37 (pick_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:264 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:272 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:277 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:306 (plan_mipmaps)`; `crates/metal2vulkan/src/bind/mipmap_filter.rs:915 (mipmap_filter_module)` -- `feature::HostMemory`: `crates/metal2vulkan-runtime/src/host_memory.rs:255 (not_importable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:280 (refuse_unwritable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:463 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:468 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:486 (new)` +- `feature::HostMemory`: `crates/metal2vulkan-runtime/src/host_memory.rs:329 (not_importable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:361 (refuse_unwritable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:557 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:562 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:580 (new)` - `feature::GpuTimes`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:1830 (gpu_times)` - `feature::CountingVisibility`: `crates/metal2vulkan-runtime/src/visibility.rs:447 (check_mode)` - `feature::ViewFormatReinterpretation`: `crates/metal2vulkan-runtime/src/view_plan.rs:547 (reinterpretation_refused)` @@ -406,7 +406,7 @@ Each refusal's sites, with the function that builds it. - `feature::PrivateMemory`: `crates/metal2vulkan/src/lower/select.rs:1153 (function_storage)` - `feature::SparseTextures`: `crates/metal2vulkan-runtime/src/sparse/texture.rs:32 (sparse_refusal)` - `feature::SparseMapping`: `crates/metal2vulkan-runtime/src/sparse/encoder.rs:466 (splits_a_unit)` -- `feature::TimelineSemaphores`: `crates/metal2vulkan-runtime/src/device/create.rs:986 (timeline_difference)` +- `feature::TimelineSemaphores`: `crates/metal2vulkan-runtime/src/device/create.rs:1014 (timeline_difference)` - `feature::Reflection`: `crates/metal2vulkan/src/bind/argument_buffer.rs:628 (unmeasured)`; `crates/metal2vulkan/src/reflection/derive.rs:179 (specialized_reads)`; `crates/metal2vulkan/src/reflection/derive.rs:213 (read_attributes)`; `crates/metal2vulkan/src/reflection/derive.rs:240 (gap_at)`; `crates/metal2vulkan/src/reflection/function.rs:172 (unmeasured)`; `crates/metal2vulkan/src/reflection/function.rs:366 (attribute)`; `crates/metal2vulkan/src/reflection/function.rs:437 (module_constants)`; `crates/metal2vulkan/src/reflection/linked.rs:127 (function)`; `crates/metal2vulkan/src/reflection/mod.rs:249 (stage)` - `feature::HeapTextureTiling`: `crates/metal2vulkan-runtime/src/texture/heap.rs:540 (tiling_refusal)` - `feature::ViewportDepthRange`: `crates/metal2vulkan-runtime/src/render_state.rs:1035 (depth_ranges_refused)` @@ -415,18 +415,18 @@ Each refusal's sites, with the function that builds it. - `feature::IndirectRenderState`: `crates/metal2vulkan/src/lower/access/encode.rs:559 (select_command)` - `feature::GlobalBuiltinInFragment`: `crates/metal2vulkan/src/lower/select.rs:896 (route_air)` - `feature::PrivateRenderState`: `crates/metal2vulkan/src/bind/heap.rs:1278 (array)`; `crates/metal2vulkan/src/bind/plan/resources.rs:880 (write_rounding)`; `crates/metal2vulkan/src/lower/texture/mod.rs:2811 (mode_rounded_write)`; `crates/metal2vulkan/src/pipeline/private_state.rs:47 (refused)` -- `feature::ExtendedRangeBlend`: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:276 (refused)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1006 (plan)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1009 (plan)`; `crates/metal2vulkan/src/lower/fragment/input_blend.rs:154 (plan)` -- `feature::TileReach`: `crates/metal2vulkan/src/bind/tile_reach.rs:272 (tile_reach_module)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1944 (capture)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1970 (capture)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:2012 (refuse_unaddressed)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:447 (param)` +- `feature::ExtendedRangeBlend`: `crates/metal2vulkan/src/lower/arith/extended_range/blend.rs:276 (refused)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1008 (plan)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1011 (plan)`; `crates/metal2vulkan/src/lower/fragment/input_blend.rs:154 (plan)` +- `feature::TileReach`: `crates/metal2vulkan/src/bind/tile_reach.rs:272 (tile_reach_module)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1946 (capture)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1972 (capture)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:2014 (refuse_unaddressed)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:447 (param)` - `feature::CommandPredication`: `crates/metal2vulkan/src/bind/replay/predication.rs:415 (predication_step_module)` - `feature::ProgramScopeBinding`: `crates/metal2vulkan-air/src/abi/module.rs:77 (decode)`; `crates/metal2vulkan/src/error/mod.rs:268 (from)` - `feature::SeqCstFence`: `crates/metal2vulkan/src/lower/sync/barrier.rs:443 (require_seq_cst)`; `crates/metal2vulkan/src/lower/sync/barrier.rs:449 (require_seq_cst)` -- `gap::Textures`: `crates/metal2vulkan-runtime/src/blit_texture.rs:159 (check_depth_view)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:1522 (view_usage)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs:1406 (compile_error)`; `crates/metal2vulkan-runtime/src/texture.rs:1176 (image_error)`; `crates/metal2vulkan-runtime/src/texture.rs:1838 (storage_over_buffer)`; `crates/metal2vulkan-runtime/src/texture.rs:2741 (new_image_starting)`; `crates/metal2vulkan-runtime/src/texture.rs:3750 (image)`; `crates/metal2vulkan-runtime/src/texture.rs:5025 (host_copy)`; `crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs:206 (new_surface_planes_texture)` +- `gap::Textures`: `crates/metal2vulkan-runtime/src/blit_texture.rs:159 (check_depth_view)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:1525 (view_usage)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs:1406 (compile_error)`; `crates/metal2vulkan-runtime/src/texture.rs:1292 (image_error)`; `crates/metal2vulkan-runtime/src/texture.rs:1969 (storage_over_buffer)`; `crates/metal2vulkan-runtime/src/texture.rs:3111 (new_image_starting)`; `crates/metal2vulkan-runtime/src/texture.rs:4120 (image)`; `crates/metal2vulkan-runtime/src/texture.rs:5395 (host_copy)`; `crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs:206 (new_surface_planes_texture)` - `gap::ResourceHeap`: `crates/metal2vulkan-runtime/src/binding.rs:1358 (descriptor)` -- `gap::SparseHeaps`: `crates/metal2vulkan-runtime/src/sparse/encoder.rs:458 (first_slice)`; `crates/metal2vulkan-runtime/src/texture.rs:1360 (plan_sparse_texture)`; `crates/metal2vulkan-runtime/src/texture.rs:4322 (make_aliasable)` -- `gap::SparseTileMaps`: `crates/metal2vulkan-runtime/src/binding.rs:428 (slot_tile_map)`; `crates/metal2vulkan-runtime/src/sparse/texture.rs:30 (sparse_refusal)`; `crates/metal2vulkan-runtime/src/texture.rs:1385 (plan_sparse_texture)` -- `gap::HeapPastMaxBufferSize`: `crates/metal2vulkan-runtime/src/heap.rs:686 (heap_size)` -- `gap::HeapTextureAlignment`: `crates/metal2vulkan-runtime/src/texture/heap.rs:1269 (heap_plan)` -- `gap::HeapTextureMemory`: `crates/metal2vulkan-runtime/src/texture/heap.rs:1254 (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1261 (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1702 (host_heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1774 (host_heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:467 (memory_refusal)` +- `gap::SparseHeaps`: `crates/metal2vulkan-runtime/src/sparse/encoder.rs:458 (first_slice)`; `crates/metal2vulkan-runtime/src/texture.rs:1476 (plan_sparse_texture)`; `crates/metal2vulkan-runtime/src/texture.rs:4692 (make_aliasable)` +- `gap::SparseTileMaps`: `crates/metal2vulkan-runtime/src/binding.rs:428 (slot_tile_map)`; `crates/metal2vulkan-runtime/src/sparse/texture.rs:30 (sparse_refusal)`; `crates/metal2vulkan-runtime/src/texture.rs:1501 (plan_sparse_texture)` +- `gap::HeapPastMaxBufferSize`: `crates/metal2vulkan-runtime/src/heap.rs:689 (heap_size)` +- `gap::HeapTextureAlignment`: `crates/metal2vulkan-runtime/src/texture/heap.rs:1275 (heap_plan)` +- `gap::HeapTextureMemory`: `crates/metal2vulkan-runtime/src/texture/heap.rs:1260 (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1267 (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1714 (host_heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1927 (memory_shadow)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:467 (memory_refusal)` - `gap::FunctionTablePastMaxBufferLength`: `crates/metal2vulkan-runtime/src/function_table.rs:628 (past_limit)` - `gap::IndirectCommandBufferPastMaxBufferLength`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:522 (new_indirect_command_buffer)` - `gap::IndirectRenderCommands`: `crates/metal2vulkan-runtime/src/compute.rs:1026 (execute_commands_in_buffer)`; `crates/metal2vulkan-runtime/src/compute.rs:1076 (execute_commands_in_buffer_indirect)`; `crates/metal2vulkan-runtime/src/depth_stencil.rs:85 (gpu_resource_id)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:3495 (render_state)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:517 (new_indirect_command_buffer)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs:1413 (compile_error)`; `crates/metal2vulkan-runtime/src/render.rs:5737 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:6027 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:6306 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:6668 (draw_resident)`; `crates/metal2vulkan-runtime/src/render/executions.rs:1773 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2438 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:361 (execute_commands_in_buffer)`; `crates/metal2vulkan-runtime/src/render/executions.rs:419 (execute_commands_in_buffer_indirect)`; `crates/metal2vulkan-runtime/src/render/executions.rs:432 (execute_commands_in_buffer_indirect)`; `crates/metal2vulkan-runtime/src/render/executions.rs:876 (back_memoryless)` @@ -465,20 +465,20 @@ Each refusal's sites, with the function that builds it. - `gap::LayeredPass`: `crates/metal2vulkan-runtime/src/color_resolve.rs:517 (plan)` - `gap::FunctionOptions`: `crates/metal2vulkan-runtime/src/library.rs:215 (new_function_with_descriptor)` - `gap::OverlappingTextureCopies`: `crates/metal2vulkan-runtime/src/blit_texture.rs:1201 (texture_copies_of_bytes)` -- `gap::RebindTextures`: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs:575 (rebind_host_pages)`; `crates/metal2vulkan-runtime/src/texture.rs:2420 (rebound_alias_images)`; `crates/metal2vulkan-runtime/src/texture.rs:2439 (rebound_alias_images)`; `crates/metal2vulkan-runtime/src/texture.rs:2446 (rebound_alias_images)` -- `gap::PvrtcBlockOrder`: `crates/metal2vulkan-runtime/src/texture.rs:5095 (host_copy)` +- `gap::RebindTextures`: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs:567 (rebind_host_pages)`; `crates/metal2vulkan-runtime/src/texture.rs:2696 (rebound_alias_images)`; `crates/metal2vulkan-runtime/src/texture.rs:2712 (rebound_alias_images)`; `crates/metal2vulkan-runtime/src/texture.rs:2732 (rebound_alias_images)`; `crates/metal2vulkan-runtime/src/texture.rs:2746 (rebound_alias_images)`; `crates/metal2vulkan-runtime/src/texture.rs:2817 (dma_buf_images_again)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:2217 (rebound_heap_images)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:2232 (rebound_heap_images)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:2243 (rebound_heap_images)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:2289 (dma_buf_heap_images_again)` +- `gap::PvrtcBlockOrder`: `crates/metal2vulkan-runtime/src/texture.rs:5465 (host_copy)` - `gap::VertexFetchPast4GiB`: `crates/metal2vulkan-runtime/src/render/vertex_reach.rs:72 (check_vertex_reach)` - `gap::StageInFetchPast4GiB`: `crates/metal2vulkan-runtime/src/fetch_reach.rs:126 (check_stage_in_reach)` - `gap::MappedTextureSampling`: `crates/metal2vulkan-runtime/src/address_map.rs:158 (resolve)` - `gap::LibrarySource`: `crates/metal2vulkan-runtime/src/library.rs:107 (new_library_with_source)` - `gap::RestartedStrip`: `crates/metal2vulkan-runtime/src/index_rewrite.rs:109 (new)`; `crates/metal2vulkan-runtime/src/render.rs:5912 (draw_resident)` -- `gap::RotatedTexture`: `crates/metal2vulkan-runtime/src/blit_texture.rs:1508 (texel_copies)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:706 (turned_plane)`; `crates/metal2vulkan-runtime/src/rotated.rs:184 (new)`; `crates/metal2vulkan-runtime/src/rotated.rs:200 (new)`; `crates/metal2vulkan-runtime/src/shadow.rs:346 (unmerged)`; `crates/metal2vulkan-runtime/src/texture.rs:4562 (view)`; `crates/metal2vulkan-runtime/src/texture/rotation.rs:102 (check_rotated_reach)`; `crates/metal2vulkan-runtime/src/texture/rotation.rs:317 (copied_image)`; `crates/metal2vulkan-runtime/src/texture/usage_shadow.rs:188 (new_usage_shadow)` -- `gap::DetachTextures`: `crates/metal2vulkan-runtime/src/buffer.rs:1969 (pages_base)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs:583 (rebind_host_pages)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:616 (make_texture_over)`; `crates/metal2vulkan-runtime/src/detach.rs:144 (detach_host_pages)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:2152 (heap_texture_at)`; `crates/metal2vulkan-runtime/src/texture/stand_in.rs:143 (new_stand_in)`; `crates/metal2vulkan-runtime/src/texture/stand_in.rs:248 (stand_in_while_detached)`; `crates/metal2vulkan-runtime/src/texture/stand_in.rs:297 (stand_ins)`; `crates/metal2vulkan-runtime/src/texture/stand_in.rs:303 (stand_ins)` +- `gap::RotatedTexture`: `crates/metal2vulkan-runtime/src/blit_texture.rs:1508 (texel_copies)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:706 (turned_plane)`; `crates/metal2vulkan-runtime/src/rotated.rs:184 (new)`; `crates/metal2vulkan-runtime/src/rotated.rs:200 (new)`; `crates/metal2vulkan-runtime/src/shadow.rs:346 (unmerged)`; `crates/metal2vulkan-runtime/src/texture.rs:4932 (view)`; `crates/metal2vulkan-runtime/src/texture/rotation.rs:102 (check_rotated_reach)`; `crates/metal2vulkan-runtime/src/texture/rotation.rs:317 (copied_image)`; `crates/metal2vulkan-runtime/src/texture/usage_shadow.rs:188 (new_usage_shadow)` +- `gap::DetachTextures`: `crates/metal2vulkan-runtime/src/buffer.rs:1999 (pages_base)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs:572 (rebind_host_pages)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs:616 (make_texture_over)`; `crates/metal2vulkan-runtime/src/detach.rs:144 (detach_host_pages)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:2421 (heap_texture_at)`; `crates/metal2vulkan-runtime/src/texture/stand_in.rs:143 (new_stand_in)`; `crates/metal2vulkan-runtime/src/texture/stand_in.rs:248 (stand_in_while_detached)`; `crates/metal2vulkan-runtime/src/texture/stand_in.rs:297 (stand_ins)`; `crates/metal2vulkan-runtime/src/texture/stand_in.rs:303 (stand_ins)` - `gap::TextureBufferLevels`: `crates/metal2vulkan-runtime/src/texture_descriptor.rs:531 (check_made)` - `gap::WriteSwizzle`: `crates/metal2vulkan-runtime/src/texture_descriptor.rs:538 (check_made)` -- `gap::DetachedTexelAccess`: `crates/metal2vulkan-runtime/src/texture.rs:4392 (refuse_detached_texels)` +- `gap::DetachedTexelAccess`: `crates/metal2vulkan-runtime/src/texture.rs:4762 (refuse_detached_texels)` - `gap::SurfaceDepthStencil`: `crates/metal2vulkan-runtime/src/blit_texture.rs:232 (unit)`; `crates/metal2vulkan-runtime/src/texture/surface_depth.rs:56 (surface_depth_twin)` -- `gap::HostHeapUncompressedMultisample`: `crates/metal2vulkan-runtime/src/texture/heap.rs:1707 (host_heap_plan)` +- `gap::HostHeapUncompressedMultisample`: `crates/metal2vulkan-runtime/src/texture/heap.rs:1719 (host_heap_plan)` - `gap::PredicationUnbalanced`: `crates/metal2vulkan-runtime/src/predication.rs:354 (nil)`; `crates/metal2vulkan-runtime/src/predication.rs:386 (start_else)`; `crates/metal2vulkan-runtime/src/predication.rs:438 (end_if)`; `crates/metal2vulkan-runtime/src/predication.rs:558 (end_loop)` - `gap::PredicationOpenAtUnitEnd`: `crates/metal2vulkan-runtime/src/predication.rs:279 (commit)` - `gap::PredicationWordPastBuffer`: `crates/metal2vulkan-runtime/src/predication.rs:139 (new)` @@ -512,7 +512,7 @@ Each refusal's sites, with the function that builds it. - `limit::TypeCount`: `crates/metal2vulkan-air/src/bitcode/types.rs:159 (decode)`; `crates/metal2vulkan-air/src/ir/types.rs:239 (intern)` - `limit::MetadataNodes`: `crates/metal2vulkan-air/src/bitcode/function.rs:334 (metadata)`; `crates/metal2vulkan-air/src/bitcode/metadata.rs:192 (push)`; `crates/metal2vulkan-air/src/bitcode/metadata.rs:221 (strings)` - `limit::BitstreamNesting`: `crates/metal2vulkan-air/src/bitstream/mod.rs:267 (enter_block)` -- `limit::InstructionCount`: `crates/metal2vulkan-air/src/bitcode/function.rs:1467 (call)`; `crates/metal2vulkan-air/src/bitcode/function.rs:180 (decode)`; `crates/metal2vulkan-air/src/bitcode/function.rs:320 (constants)`; `crates/metal2vulkan-air/src/bitcode/function.rs:595 (forward)`; `crates/metal2vulkan-air/src/bitcode/function.rs:686 (push)`; `crates/metal2vulkan-air/src/bitcode/function.rs:697 (push)`; `crates/metal2vulkan-air/src/bitcode/function.rs:727 (count_record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:731 (count_record)` +- `limit::InstructionCount`: `crates/metal2vulkan-air/src/bitcode/function.rs:1462 (call)`; `crates/metal2vulkan-air/src/bitcode/function.rs:180 (decode)`; `crates/metal2vulkan-air/src/bitcode/function.rs:320 (constants)`; `crates/metal2vulkan-air/src/bitcode/function.rs:590 (forward)`; `crates/metal2vulkan-air/src/bitcode/function.rs:681 (push)`; `crates/metal2vulkan-air/src/bitcode/function.rs:692 (push)`; `crates/metal2vulkan-air/src/bitcode/function.rs:722 (count_record)`; `crates/metal2vulkan-air/src/bitcode/function.rs:726 (count_record)` - `limit::LayoutNesting`: `crates/metal2vulkan-air/src/abi/structs.rs:147 (open)`; `crates/metal2vulkan-air/src/abi/structs.rs:160 (finish)`; `crates/metal2vulkan/src/bind/argument_buffer.rs:715 (layout)` - `limit::ConstructNesting`: `crates/metal2vulkan/src/structurize/emit.rs:216 (check_tree)`; `crates/metal2vulkan/src/structurize/emit/predicate.rs:151 (facts)` - `limit::PrivateArenaBytes`: `crates/metal2vulkan/src/lower/access/local.rs:595 (use_arena)`; `crates/metal2vulkan/src/memory/plan.rs:1684 (place_allocas)`; `crates/metal2vulkan/src/memory/plan.rs:1691 (place_allocas)` diff --git a/docs/RUNTIME-PORTING.md b/docs/RUNTIME-PORTING.md index fa47c1bd4..7143091cf 100644 --- a/docs/RUNTIME-PORTING.md +++ b/docs/RUNTIME-PORTING.md @@ -244,7 +244,7 @@ narrow refusal that the call's rustdoc describes. | Item | Metal | Runtime | |---|---|---| | `heap_texture_size_and_align` | `heapTextureSizeAndAlignWithDescriptor:` | `Device::heap_texture_size_and_align`: the device's own requirement | -| `new_buffer_over_host_memory` | `newBufferWithBytesNoCopy:length:options:deallocator:` | `unsafe Device::new_buffer_with_bytes_no_copy` (`VK_EXT_external_memory_host`) *(partial)* | +| `new_buffer_over_host_memory` | `newBufferWithBytesNoCopy:length:options:deallocator:` | `unsafe Device::new_buffer_with_bytes_no_copy` over a `HostMemory` (`VK_EXT_external_memory_host`; where the device refuses the pointer, the dma-bufs of `HostMemory::with_dma_buf`'s source, `VK_EXT_external_memory_dma_buf`) *(partial)* | | `new_buffer_of_length` | `newBufferWithLength:options:` | `Device::new_buffer` | | `new_command_queue` | `newCommandQueue` | `Device::new_command_queue` | | `new_compute_pipeline_state` | `newComputePipelineStateWithDescriptor:options:reflection:error:` | `Device::new_compute_pipeline_state` | @@ -266,8 +266,8 @@ narrow refusal that the call's rustdoc describes. | `new_buffer` | `newBufferWithDescriptor:` (SPI) | `Device::new_buffer_with_descriptor` (`BufferDescriptor` by value, with host contents and an `AddressPlacement`) | | `new_heap` | `newHeapWithDescriptor:` | `Device::new_heap` (`HeapDescriptor::placement` pins its address range) | | `reserve_address_pool` | (none: a runtime extension; Metal's own pools of buffers shorter than a page) | `Device::reserve_address_pool` -> `AddressPool`, holding a pin's span; `BufferDescriptor::with_pool_slot(&pool, offset)` places a buffer at the pool's address plus a 256-byte-aligned offset, holding its length rounded up to 256 bytes | -| `new_heap_over_host_memory` | (none: a runtime extension) | `unsafe Device::new_heap_with_bytes_no_copy`: a heap over the caller's page-aligned memory (`VK_EXT_external_memory_host`), the heap twin of `new_buffer_with_bytes_no_copy` | -| `rebind_host_memory` | (none: a runtime extension) | `unsafe Buffer::rebind_bytes_no_copy`, `unsafe Heap::rebind_bytes_no_copy`: another range of the same length under the same objects and GPU addresses, in commit order (`RebindProblem::EncodedUses` while uncommitted work used them) | +| `new_heap_over_host_memory` | (none: a runtime extension) | `unsafe Device::new_heap_with_bytes_no_copy`: a heap over the caller's page-aligned memory, a `HostMemory` (`VK_EXT_external_memory_host`, or dma-bufs as for a buffer), the heap twin of `new_buffer_with_bytes_no_copy` | +| `rebind_host_memory` | (none: a runtime extension) | `unsafe Buffer::rebind_bytes_no_copy`, `unsafe Heap::rebind_bytes_no_copy`: another range of the same length, a `HostMemory`, under the same objects and GPU addresses, in commit order (`RebindProblem::EncodedUses` while uncommitted work used them) | | `new_sampler_state` | `newSamplerStateWithDescriptor:` | `Device::new_sampler_state`, or `Device::new_sampler_state_with_options` (argument-buffer support, placement) | | `new_depth_stencil_state` | `newDepthStencilStateWithDescriptor:` | `Device::new_depth_stencil_state` | | `new_indirect_command_buffer` | `newIndirectCommandBufferWithDescriptor:maxCommandCount:options:` | `Device::new_indirect_command_buffer` (placement as an option) |