From 12a8a907bcdd3c7ae5683ee436e83e42fd6397a4 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 11 Nov 2026 03:08:34 -0800 Subject: [PATCH] No-copy buffers on a device without VK_EXT_external_memory_host take the dma-buf route On a driver that lists no VK_EXT_external_memory_host but imports dma-bufs (Honeykrisp on Asahi, as the consumer reported: a macOS guest's newBufferWithDescriptor answered nil, "HostMemory needs ExtExternalMemoryHost", 704 times in one boot), every no-copy buffer, heap and guest RAM was refused: Importer::new refused before the dma-buf route was looked at, and the importer held the host-pointer extension's functions unconditionally. The importer now holds the pointer import as an option (host_memory.rs's PointerImport: its functions, page and minImportedHostPointerAlignment, and memory_types). Importer::new refuses only where the device imports neither pointers nor dma-bufs (the pointer's refusal, naming the extension, as before); a device with dma-bufs alone gets an importer whose pointer refusal stands for every pointer (Importer::pointer_import). Every pointer-import site takes a PointerImport, so a device without one never makes a host-allocation object: buffer_descriptor.rs (import_by_pointer, import_pointer, import_pointer_again, import_backing), host_shared_pointers.rs (false there), fresh_pages.rs and the page-buffer blocks (none there), the submission checks (unchecked there), host_ram.rs's chunk import by pointer. The unit an import's pages round out to is Importer::unit: the host page and the import alignment where the device imports pointers, the host page alone where it imports dma-bufs. Every device that imports pointers keeps the same calls. On a device that imports no pointer: - a no-copy buffer, heap or rebind over memory with a source is bound in imports of its dma-bufs; memory with none is refused, naming VK_EXT_external_memory_host (host_window), as it was; - memory of Metal's private option bit 24 that the runtime copies anyway (no read-only view on Linux) is no longer refused for lack of an import route, on any device; - a guest RAM with a source is taken and listed (its chunks its dma-bufs, imported on demand), the pointer never tried; one with no source is refused, naming the extension, as it was; - supportsResourceDetachBacking answers whether the device makes no-copy buffers (it has an importer), not whether it lists the extension. Docs: the runtime README, HOWTO section 6 and the RAM copies' refusal, RUNTIME-PORTING, the module docs of host_memory.rs, dma_buf.rs and host_ram.rs, HostBacking::ImportedAsDmaBuf, and the refusal lists of the no-copy buffer, heap, RAM and RAM copy calls. docs/REFUSALS.md regenerated (the HostMemory refusal's sites: PointerImport's and no_pointer_refusal). Verified: the next commit's device tests (RADV on the Radeon 780M, lavapipe), which fail at the base with the refusal; job ids in the branch's report. --- crates/metal2vulkan-runtime/README.md | 5 +- crates/metal2vulkan-runtime/src/buffer.rs | 2 +- .../src/buffer_descriptor.rs | 79 ++++---- crates/metal2vulkan-runtime/src/device/mod.rs | 12 +- crates/metal2vulkan-runtime/src/dma_buf.rs | 5 +- .../metal2vulkan-runtime/src/fresh_pages.rs | 16 +- crates/metal2vulkan-runtime/src/heap.rs | 5 +- .../metal2vulkan-runtime/src/host_backing.rs | 3 +- .../metal2vulkan-runtime/src/host_memory.rs | 182 +++++++++++++----- crates/metal2vulkan-runtime/src/host_ram.rs | 51 +++-- .../metal2vulkan-runtime/src/host_ram/copy.rs | 4 +- .../src/host_shared_pointers.rs | 20 +- .../src/in_place_check.rs | 5 +- .../src/private_properties.rs | 20 +- .../metal2vulkan-runtime/src/submit_check.rs | 16 +- .../src/tests/host_ram_device.rs | 3 +- .../src/tests/private_properties.rs | 9 + docs/HOWTO.md | 10 +- docs/REFUSALS.md | 4 +- docs/RUNTIME-PORTING.md | 2 +- 20 files changed, 300 insertions(+), 153 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index d4c66ea35..dba99f3be 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -378,7 +378,10 @@ the record the pass is making. 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)), and a no-copy buffer or heap - over memory made without a source is a copy of its pages, as below; on NVIDIA's driver the runtime + over memory made without a source is a copy of its pages, as below. A device that enables no + `VK_EXT_external_memory_host` but imports dma-bufs imports only those: memory made with a + source is imported from its dma-bufs, and memory made without one is refused + (`Unsupported`, naming the extension); on NVIDIA's driver the runtime never hands the driver pages the kernel cannot pin (a dma-buf's mapping): they take the source, and else, or where its import fails, a copy, as below. A no-copy buffer's import of such dma-bufs that only blits have read may be released while idle and imported again at its next diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index eb53071c2..154b95f27 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -2818,7 +2818,7 @@ impl Device { && !plain && lead == 0 && fresh_pages::takes_fresh_pages(size, class) - && shared.host_import.is_ok() + && (shared.host_import.as_ref()).is_ok_and(|importer| importer.pointers().is_some()) && (fresh == FreshPages::Wherever || self.fresh_pages_pay_now()); let making = (!of_heap && !plain && lead == 0 && fresh == FreshPages::WherePaid).then_some( BufferMaking { diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index cf82c3717..7ccf014c0 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -27,7 +27,7 @@ use super::host_bytes::HostBytes; use super::host_memory::{ based_size, binds_in, buffer_base, import_refused, import_window, not_importable, refuse_unwritable, refused, unpinnable, Deallocator, HostMemory, HostParts, HostRelease, - ImportRequest, ImportWindow, Importer, KeepAlive, Release, Source, + ImportRequest, ImportWindow, Importer, KeepAlive, PointerImport, Release, Source, }; use super::host_ram::{RamOnDevice, Routed}; #[cfg(unix)] @@ -484,9 +484,10 @@ impl Device { /// 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. With Metal's private option bit 24 + /// first command using it (24 to 88 ms per GiB). Where the device refuses the pointer, or + /// imports none (it enables no `VK_EXT_external_memory_host`), and `memory` carries a dma-buf + /// source ([`HostMemory::with_dma_buf`]), the dma-bufs it makes of the pages are imported + /// instead. With Metal's private option bit 24 /// ([`ResourceOptions::PRIVATE_BIT`]), the GPU's writes to the pages are dropped, as Metal's /// are: on macOS the pages are imported through a read-only view of them, by their pointer /// alone; elsewhere the buffer is made over a copy of them whose GPU writes are dropped, @@ -505,8 +506,8 @@ impl Device { /// /// Refused: a length of 0 or past `max_buffer_length` (`Nil`, as plain Metal answers nil); /// `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 + /// option (`Invalid`); on a device without `VK_EXT_external_memory_host`, memory that comes + /// with no dma-buf source it imports (`Unsupported`, naming it); memory this device /// 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 @@ -592,8 +593,7 @@ impl Device { let shared = self.shared(); // The unit an import's pages round out to: an import by pointer over a page the call // covers is taken anew at its next submission. - let unit = (shared.host_import.as_ref()) - .map_or(1, |importer| importer.page.max(importer.alignment)); + let unit = (shared.host_import.as_ref()).map_or(1, Importer::unit); let imports = (shared.aliases).remapped(start, start.saturating_add(length), unit); shared.counts.host_range_remapped(imports); } @@ -751,7 +751,7 @@ impl Device { let host = host_window(call, importer, pointer, length, source, drops_writes)?; let window = host.window; if of_heap && window.offset != 0 { - let alignment = importer.page.max(importer.alignment); + let alignment = importer.unit(); let problem = HeapProblem::HostMemoryAlignment { alignment }; return Err(invalid(call, Problem::Heap(problem))); } @@ -1096,7 +1096,7 @@ impl Device { let host = host_window(call, importer, pointer, length, source, drops_writes)?; let window = host.window; if heap.is_some() && window.offset != 0 { - let alignment = importer.page.max(importer.alignment); + let alignment = importer.unit(); let problem = HeapProblem::HostMemoryAlignment { alignment }; return Err(invalid(call, Problem::Heap(problem))); } @@ -1116,7 +1116,7 @@ impl Device { if moved && !copyable { return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); } - let unit = importer.page.max(importer.alignment); + let unit = importer.unit(); let copy_window = match moved { true => ImportWindow { start: (pointer.as_ptr() as u64).wrapping_sub(cell.offset()), @@ -1593,16 +1593,16 @@ impl Device { source, drops_writes, } = host; - let refusal = match by_pointer { + let refusal = match (by_pointer, importer.pointers()) { // SAFETY: the caller's. - true => match unsafe { - self.import_pointer(importer, pointer, length, &window, class, drops_writes) + (true, Some(pointers)) => match unsafe { + self.import_pointer(pointers, pointer, length, &window, class, drops_writes) } { Ok(imported) => return Ok(Ok(imported)), Err(error) if refused(&error) => error, Err(error) => return Err(error), }, - false => not_importable(), + _ => not_importable(), }; match source { Some(source) => Ok(Err((source, refusal))), @@ -1622,7 +1622,7 @@ impl Device { /// placement is freed. pub(super) unsafe fn import_pointer( &self, - importer: &Importer, + pointers: &PointerImport, pointer: NonNull, length: u64, window: &ImportWindow, @@ -1635,7 +1635,7 @@ impl Device { let start = pointer.as_ptr().wrapping_sub(window.offset as usize); let class = (class, drops_writes); // SAFETY: the caller's, and the buffer is a new one of this device. - match unsafe { self.import_backing(importer, &buffer, start, window, class) } { + match unsafe { self.import_backing(pointers, &buffer, start, window, class) } { Ok(placement) => Ok((buffer, placement)), Err(error) => { // SAFETY: the buffer is unused. @@ -1661,17 +1661,16 @@ impl Device { return Err(self.lost_refusal()); } let shared = self.shared(); - let importer = shared - .host_import - .as_ref() - .map_err(|_| internal("a pointer import made again on a device that imports none"))?; + let pointers = (shared.host_import.as_ref().ok()) + .and_then(Importer::pointers) + .ok_or_else(|| internal("a pointer import made again on a device that imports none"))?; let window = &again.window; // SAFETY: the caller's pages stay mapped at the pointer while the buffer lives // (`HostMemory::new`), and the buffer outlives the placement: the import holds it, and a // command buffer that reads it holds the buffer too. An import of a read-only view is // never made again (`Device::buffer_over_host_memory`). let (buffer, placement) = unsafe { - self.import_pointer(importer, pointer, again.length, window, again.class, false) + self.import_pointer(pointers, pointer, again.length, window, again.class, false) }?; Ok(self.pages_of( buffer.raw, @@ -2155,7 +2154,7 @@ impl Device { /// allocations. unsafe fn import_backing( &self, - importer: &Importer, + pointers: &PointerImport, buffer: &HostBuffer, start: *mut u8, window: &ImportWindow, @@ -2182,7 +2181,7 @@ impl Device { // SAFETY: the imported pages are host memory aligned to the import alignment (the // window's). let types = - unsafe { importer.memory_types(raw_device, imported) }.map_err(import_refused)?; + unsafe { pointers.memory_types(raw_device, imported) }.map_err(import_refused)?; let allowed = types & requirements.memory_type_bits; // An allocation past the device's, refused before the driver sees it. let largest = self @@ -2406,13 +2405,14 @@ fn source_failure(failed: Error, refusal: Error) -> Error { /// 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 (but where `dma_buf_only`, -/// `HostMemory::dma_buf_only`), 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, as is any where `drops_writes` -/// (imported through a read-only view, `read_only_view.rs`). Refused: memory past the address -/// space's end (`Nil`, as Metal makes no buffer over it); a range the import alignment cannot -/// cover, or memory imported only as dma-bufs, with no usable source (`Unsupported`, -/// `HostMemory`). +/// pointer where the device imports pointers and its import alignment covers them (but where +/// `dma_buf_only`, `HostMemory::dma_buf_only`), 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, as is any where +/// `drops_writes` (imported through a read-only view, `read_only_view.rs`, or a copy where the +/// system maps none). Refused: memory past the address space's end (`Nil`, as Metal makes no +/// buffer over it); with no usable source, memory to be imported that a device without +/// `VK_EXT_external_memory_host` imports no way (`Unsupported`, naming it), and a range the import +/// alignment cannot cover, or memory imported only as dma-bufs (`Unsupported`, `HostMemory`). fn host_window( call: &'static str, importer: &Importer, @@ -2425,10 +2425,19 @@ fn host_window( 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 = - !dma_buf_only && import_window(at, length, importer.page, importer.alignment).is_ok(); - if !by_pointer && source.is_none() { - return Err(not_importable()); + let by_pointer = !dma_buf_only + && (importer.pointers()).is_some_and(|pointers| { + import_window(at, length, importer.page, pointers.alignment).is_ok() + }); + // Memory whose GPU writes are dropped where the system maps no read-only view of the pages + // is a copy of them, imported by no route (`copied.rs`). + let copied = drops_writes && !crate::read_only_view::VIEWS_DROP_WRITES; + if !by_pointer && source.is_none() && !copied { + // A device that imports no pointer refuses as it imports none, naming what it lacks. + return Err(match importer.pointer_import() { + Ok(_) => not_importable(), + Err(refusal) => refusal, + }); } Ok(HostWindow { drops_writes, diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 422c142b0..bd29a0ce2 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -2292,14 +2292,14 @@ impl Device { // by their pointer, in the memory types the device imports such pages as, once its // submission check found that a held import costs its submissions nothing (`memory.rs`'s // "Buffers in the runtime's own pages"). - let (page_types, page_unit) = match &host_import { - Ok(importer) => { - let unit = importer.page.max(importer.alignment); - // SAFETY: `raw` is the importer's device. - let types = unsafe { crate::fresh_pages::own_page_types(importer, &raw, unit) }; + let (page_types, page_unit) = match host_import.as_ref().ok().and_then(Importer::pointers) { + Some(pointers) => { + let unit = pointers.unit(); + // SAFETY: `raw` is the import's device. + let types = unsafe { crate::fresh_pages::own_page_types(pointers, &raw, unit) }; (types, unit) } - Err(_) => (Err("the device imports no host pointer"), 1), + None => (Err("the device imports no host pointer"), 1), }; memory.page_buffer_blocks(&raw, page_types, page_unit)?; // How the device exports a buffer's memory as an opaque file descriptor, and as a dma-buf, diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs index 4ec80cbd1..94238c9e9 100644 --- a/crates/metal2vulkan-runtime/src/dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -1,6 +1,7 @@ //! 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` +//! shared mapping (a `memfd`'s among them), and the only import on one that imports no pointer (it +//! enables no `VK_EXT_external_memory_host`). 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 @@ -981,7 +982,7 @@ impl Device { /// 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`). + /// import host allocations for one (`PointerImport::new`). fn imports_dma_buf_buffers(&self, flags: vk::BufferCreateFlags) -> bool { let shared = self.shared(); let info = vk::PhysicalDeviceExternalBufferInfo::default() diff --git a/crates/metal2vulkan-runtime/src/fresh_pages.rs b/crates/metal2vulkan-runtime/src/fresh_pages.rs index 2772291ed..99976ce59 100644 --- a/crates/metal2vulkan-runtime/src/fresh_pages.rs +++ b/crates/metal2vulkan-runtime/src/fresh_pages.rs @@ -53,7 +53,7 @@ use super::buffer::usage; use super::device::lock; use super::error::{vulkan, Error}; -use super::host_memory::Importer; +use super::host_memory::{Importer, PointerImport}; use super::memory::{self, MemoryClass, Placement, BLOCK_BYTES}; use crate::release; use crate::Device; @@ -151,9 +151,9 @@ impl Drop for OwnPages { /// /// # Safety /// -/// `device` is `importer`'s device, and `unit` a multiple of its import alignment. +/// `device` is `pointers`' device, and `unit` a multiple of its import alignment. pub(super) unsafe fn own_page_types( - importer: &Importer, + pointers: &PointerImport, device: &ash::Device, unit: u64, ) -> Result { @@ -162,7 +162,7 @@ pub(super) unsafe fn own_page_types( }; // SAFETY: the caller's; the pages are host memory of this process at a host page, which the // import alignment divides. - match unsafe { importer.memory_types(device, pages.pointer()) } { + match unsafe { pointers.memory_types(device, pages.pointer()) } { Ok(0) | Err(_) => Err("the device's driver imports anonymous pages as no memory type"), Ok(types) => Ok(types), } @@ -195,7 +195,7 @@ impl Device { pages: Option>, ) -> Result, Error> { let shared = self.shared(); - let Ok(importer) = &shared.host_import else { + let Some(pointers) = (shared.host_import.as_ref().ok()).and_then(Importer::pointers) else { return Ok(None); }; let raw_device = shared.vk(); @@ -214,9 +214,7 @@ impl Device { let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; // Whole units of the host page and the import alignment, as the import requires of the // pointer and the length, and room for the buffer's requirements. - let unit = (importer.page) - .max(importer.alignment) - .max(requirements.alignment); + let unit = pointers.unit().max(requirements.alignment); let length = (requirements.size.max(size)).checked_next_multiple_of(unit); let pages = match pages { Some(pages) => length @@ -227,7 +225,7 @@ impl Device { let placed = pages.and_then(|pages| { // SAFETY: the pages are host memory of this process at a multiple of the unit, // which the import alignment divides (both are powers of two). - let types = unsafe { importer.memory_types(raw_device, pages.pointer()) }.ok()?; + let types = unsafe { pointers.memory_types(raw_device, pages.pointer()) }.ok()?; // The memory type the buffer would take without the pages: the pages take it, or // the buffer lies there as ever. let best = lock(&shared.memory).best_type(requirements.memory_type_bits, class)?; diff --git a/crates/metal2vulkan-runtime/src/heap.rs b/crates/metal2vulkan-runtime/src/heap.rs index 2839a2830..68efe2c1e 100644 --- a/crates/metal2vulkan-runtime/src/heap.rs +++ b/crates/metal2vulkan-runtime/src/heap.rs @@ -592,8 +592,9 @@ impl Device { /// 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 /// (`Invalid`, [`HeapProblem::HostMemoryAlignment`]); and as - /// [`Device::new_buffer_with_bytes_no_copy`] refuses the memory: a device without - /// `VK_EXT_external_memory_host` (`Unsupported`, naming it), memory it cannot import exactly + /// [`Device::new_buffer_with_bytes_no_copy`] refuses the memory: on a device without + /// `VK_EXT_external_memory_host`, memory that comes with no dma-buf source it imports + /// (`Unsupported`, naming it), memory it cannot import exactly /// (`Unsupported`, `HostMemory`), a size past the device's allocation (`OutOfMemory`) or /// `maxBufferSize` (`NotImplemented(HeapPastMaxBufferSize)`); a pinned address the space /// cannot honour (`PlacementConflict`). diff --git a/crates/metal2vulkan-runtime/src/host_backing.rs b/crates/metal2vulkan-runtime/src/host_backing.rs index 7b02c9d19..6b88615c5 100644 --- a/crates/metal2vulkan-runtime/src/host_backing.rs +++ b/crates/metal2vulkan-runtime/src/host_backing.rs @@ -26,7 +26,8 @@ pub enum HostBacking { ImportedByPointer, /// In place: the device imported dma-bufs of the pages that the caller's source made /// ([`HostMemory::with_dma_buf`](crate::HostMemory::with_dma_buf)), where it refused their - /// pointer. Released while idle and imported again as an import by pointer may be. + /// pointer or imports none (it enables no `VK_EXT_external_memory_host`). Released while idle + /// and imported again as an import by pointer may be. ImportedAsDmaBuf, /// In place: bound in the device's import of a chunk of a guest RAM it uses /// ([`Device::use_host_ram`](crate::Device::use_host_ram), diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index edfa52231..4bc1434e8 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -1,6 +1,7 @@ //! Buffers over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`), through -//! `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`). +//! `VK_EXT_external_memory_host`, or, where the device refuses the pointer or imports none, +//! 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 @@ -16,8 +17,9 @@ //! the buffer reads them past its length, the caller's bytes, as plain Metal reads them //! (`Buffer::copy_reach`). The import is never a dedicated allocation in Vulkan's sense //! (`VkMemoryDedicatedAllocateInfo`), which host memory cannot be. -//! - **What it refuses**, typed: a device without the extension (`Unsupported` naming it), and -//! what this device cannot import exactly (`Unsupported`, `not_representable`): an import +//! - **What it refuses**, typed: memory with no dma-buf source the device imports, on a device +//! without the extension (`Unsupported` naming it), and what this device cannot import exactly +//! (`Unsupported`, `not_representable`): an import //! alignment above the host page whose rounding would take pages the range does not touch, an //! offset in the pages that misses the buffer's memory alignment, no memory type both allow, or //! a driver that refuses the pointer. @@ -48,7 +50,12 @@ //! binding in it, the memory types, the driver, or the runtime for a driver that breaks on //! pages the kernel cannot pin, [`unpinnable`]) 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. +//! takes by its pointer is made exactly as before, with no call more. A device that enables no +//! `VK_EXT_external_memory_host` (a driver that lists none, or a device made withholding it, +//! `DeviceOptions::withheld_extensions`) but imports dma-bufs takes this route alone: no pointer +//! is asked of it ([`Importer::pointers`]), the pages are rounded out to the host page, and +//! memory that comes with no source is refused, naming the extension +//! ([`Importer::pointer_import`]). //! - **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, but on a driver whose pointer imports follow their address (as the @@ -1119,15 +1126,17 @@ fn mapping(line: &str, access: Access) -> Option<(u64, u64, bool)> { )) } -/// What a device knows to import host memory. A clone is the submission checks' own -/// (`submit_check.rs`), which hold nothing of the device. +/// What a device knows to import host memory: the pages' pointer ([`PointerImport`]), where it +/// enables `VK_EXT_external_memory_host`, and dma-bufs of the pages a caller's source makes +/// (`dma_buf.rs`), where it enables the dma-bufs' route. A device with neither has none +/// ([`Importer::new`]). #[derive(Clone)] pub(super) struct Importer { - functions: ash::ext::external_memory_host::DeviceFn, + /// The import of a pages' pointer, or why the device has none, where it imports only dma-bufs + /// of them: every pointer refused unasked, so ([`Importer::pointer_import`]). + pointers: Result, /// The host's page size. pub(super) page: u64, - /// `minImportedHostPointerAlignment`. - pub(super) alignment: u64, /// `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 @@ -1140,10 +1149,24 @@ pub(super) struct Importer { pub(super) sparse_granule: std::sync::OnceLock>, } +/// A device's import of host memory by its pointer (`VK_EXT_external_memory_host`). A clone is the +/// submission checks' own (`submit_check.rs`), which hold nothing of the device. +#[derive(Clone)] +pub(super) struct PointerImport { + functions: ash::ext::external_memory_host::DeviceFn, + /// The host's page size. + page: u64, + /// `minImportedHostPointerAlignment`. + pub(super) alignment: u64, +} + impl Importer { - /// The importer of a device, or the refusal every no-copy buffer on it gets: the device did - /// not enable `VK_EXT_external_memory_host`, the runtime does not know the host's page size, - /// or the device cannot bind a buffer of `usage` to imported host memory. + /// The importer of a device, or the refusal every no-copy buffer on it gets: where it imports + /// neither the pages' pointer ([`PointerImport::new`]'s refusal) nor dma-bufs of them + /// (`dma_buf`), the pointer's refusal; where the runtime does not know the host's page size, + /// not implemented. A device that imports dma-bufs alone imports them only: each no-copy + /// buffer's pages come from its caller's source ([`DmaBufSource`]), and memory with none is + /// refused as the pointer is ([`Importer::pointer_import`]). /// /// # Safety /// @@ -1160,57 +1183,57 @@ impl Importer { dma_buf: bool, dma_buf_images: bool, ) -> Result { - if !enabled - .extensions - .contains(&VkExtension::ExtExternalMemoryHost) - { - return Err(Unsupported::needs( - Feature::HostMemory, - metal2vulkan::error::Capability::Extension(VkExtension::ExtExternalMemoryHost), - )); - } - let page = host_page().ok_or_else(|| Unsupported::not_implemented(Feature::HostMemory))?; - let mut host = vk::PhysicalDeviceExternalMemoryHostPropertiesEXT::default(); - let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut host); - // SAFETY: the caller's contract; the structure belongs to an enabled extension. - unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; - let alignment = host.min_imported_host_pointer_alignment; - let info = vk::PhysicalDeviceExternalBufferInfo::default() - .usage(usage) - .handle_type(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT); - let mut external = vk::ExternalBufferProperties::default(); - // SAFETY: the caller's contract; the query is core in Vulkan 1.1. - unsafe { - instance.get_physical_device_external_buffer_properties(physical, &info, &mut external) - }; - let features = external.external_memory_properties.external_memory_features; - if !features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE) - || features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY) - { - return Err(Unsupported::not_representable(Feature::HostMemory)); - } let handle = device.handle(); let load = |name: &std::ffi::CStr| { // SAFETY: the device is live, and the loader serves `vkGetDeviceProcAddr` after its - // word is put back; the extension is enabled. + // word is put back; each caller loads the functions of an enabled extension. let function = unsafe { loader_word.restored(|| instance.get_device_proc_addr(handle, name.as_ptr())) }; function.map_or(std::ptr::null(), |function| function as *const c_void) }; - let functions = ash::ext::external_memory_host::DeviceFn::load(load); + // SAFETY: the caller's contract. + let pointers = unsafe { PointerImport::new(instance, physical, enabled, usage, load) }; let dma_buf = dma_buf.then(|| ash::khr::external_memory_fd::DeviceFn::load(load)); + let page = match (&pointers, &dma_buf) { + (Ok(pointers), _) => pointers.page, + // Dma-bufs of the pages alone, every pointer refused unasked. + (Err(_), Some(_)) => { + host_page().ok_or_else(|| Unsupported::not_implemented(Feature::HostMemory))? + } + (Err(refusal), None) => return Err(refusal.clone()), + }; let dma_buf_images = dma_buf.is_some() && dma_buf_images; Ok(Importer { - functions, + pointers, page, - alignment, dma_buf, dma_buf_images, sparse_granule: std::sync::OnceLock::new(), }) } + /// The device's import of host memory by its pointer (`VK_EXT_external_memory_host`); `None` + /// where it imports dma-bufs of the pages alone. + pub(super) fn pointers(&self) -> Option<&PointerImport> { + self.pointers.as_ref().ok() + } + + /// The device's import of host memory by its pointer, or, where it imports dma-bufs of the + /// pages alone, its refusal of every pointer, memory that comes with no source of them among + /// it: why it imports none, which names `VK_EXT_external_memory_host` where the device does + /// not enable it (`PointerImport::new`). + pub(super) fn pointer_import(&self) -> Result<&PointerImport, Error> { + (self.pointers.as_ref()).map_err(|refusal| Error::Unsupported(refusal.clone())) + } + + /// The unit an import's pages round out to: the larger of the host page and the device's + /// `minImportedHostPointerAlignment` where it imports the pointer, else the host page, which a + /// dma-buf of the pages is made in. + pub(super) fn unit(&self) -> u64 { + self.pointers().map_or(self.page, PointerImport::unit) + } + /// 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 { @@ -1284,12 +1307,69 @@ impl Importer { // SAFETY: a new descriptor Vulkan handed over, which the caller owns from here on. Ok(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) }) } +} + +impl PointerImport { + /// The import of a device that enables `VK_EXT_external_memory_host` (in `enabled`), its + /// functions loaded through `load`; else the refusal of its pointers: the extension not + /// enabled (`Unsupported`, naming it), the host's page size unknown to the runtime (not + /// implemented), or no buffer of `usage` bound to imported host memory (`not_representable`). + /// + /// # Safety + /// + /// `physical` is a physical device of `instance` whose device was made with `enabled` + /// enabled, and `load` answers that device's functions by name. + unsafe fn new( + instance: &ash::Instance, + physical: vk::PhysicalDevice, + enabled: &EnableSet, + usage: vk::BufferUsageFlags, + load: impl FnMut(&std::ffi::CStr) -> *const c_void, + ) -> Result { + if !enabled + .extensions + .contains(&VkExtension::ExtExternalMemoryHost) + { + return Err(no_pointer_refusal()); + } + let page = host_page().ok_or_else(|| Unsupported::not_implemented(Feature::HostMemory))?; + let mut host = vk::PhysicalDeviceExternalMemoryHostPropertiesEXT::default(); + let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut host); + // SAFETY: the caller's contract; the structure belongs to an enabled extension. + unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; + let alignment = host.min_imported_host_pointer_alignment; + let info = vk::PhysicalDeviceExternalBufferInfo::default() + .usage(usage) + .handle_type(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT); + let mut external = vk::ExternalBufferProperties::default(); + // SAFETY: the caller's contract; the query is core in Vulkan 1.1. + unsafe { + instance.get_physical_device_external_buffer_properties(physical, &info, &mut external) + }; + let features = external.external_memory_properties.external_memory_features; + if !features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE) + || features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY) + { + return Err(Unsupported::not_representable(Feature::HostMemory)); + } + Ok(PointerImport { + functions: ash::ext::external_memory_host::DeviceFn::load(load), + page, + alignment, + }) + } + + /// The unit an import of a pointer's pages rounds out to: the larger of the host page and + /// `minImportedHostPointerAlignment`. + pub(super) fn unit(&self) -> u64 { + self.page.max(self.alignment) + } /// The memory types `pointer` can be imported into (`vkGetMemoryHostPointerPropertiesEXT`). /// /// # Safety /// - /// `device` is the importer's device; `pointer` is host memory aligned to its import + /// `device` is the import's device; `pointer` is host memory aligned to its import /// alignment. pub(super) unsafe fn memory_types( &self, @@ -1310,6 +1390,14 @@ impl Importer { } } +/// The refusal of the pointers of a device that enables no `VK_EXT_external_memory_host`. +fn no_pointer_refusal() -> Unsupported { + Unsupported::needs( + Feature::HostMemory, + metal2vulkan::error::Capability::Extension(VkExtension::ExtExternalMemoryHost), + ) +} + /// What a no-copy buffer gives back when its last reference goes: the caller's range, to its /// deallocator, and its keep-alive. pub(super) struct Release { diff --git a/crates/metal2vulkan-runtime/src/host_ram.rs b/crates/metal2vulkan-runtime/src/host_ram.rs index d82618ed9..08ae026df 100644 --- a/crates/metal2vulkan-runtime/src/host_ram.rs +++ b/crates/metal2vulkan-runtime/src/host_ram.rs @@ -30,9 +30,11 @@ //! import in each submission: measured with a probe on the Radeon 780M, Mesa 26.2.6, Linux 7.3.1, //! an 8 GiB RAM held as 128 dma-bufs of 64 MiB raised a submission's median from 14 us to 60 to //! 88 us, as 32 of 256 MiB to 32 to 33 us, as 16 of 512 MiB to 24 us, as 3 of 2730 MiB to 16 -//! us), and the driver takes the source's dma-bufs (asked as the use begins, by an import of the -//! RAM's first page as one, the source asked for that page, released at once; not where it -//! refused one before: NVIDIA's refuses a udmabuf, and its RAMs keep their 64 MiB chunks), a +//! us) or the device imports no pointer (it enables no `VK_EXT_external_memory_host`, so each +//! import of the RAM is a dma-buf), and the driver takes the source's dma-bufs (asked as the +//! use begins, by an import of the RAM's first page as one, the source asked for that page, +//! released at once; not where it refused one before: NVIDIA's refuses a udmabuf, and its RAMs +//! keep their 64 MiB chunks), a //! chunk is as long as [`LONGEST_LISTED_CHUNK`] (512 MiB), one dma-buf of the source //! ([`HostRam::with_largest_dma_buf`]) and the device's `maxMemoryAllocationSize`, //! `maxBufferSize` and `maxStorageBufferRange` take, in whole [`CHUNK_BYTES`] @@ -2138,9 +2140,13 @@ impl Device { /// imported so with a source; with none, it is taken but imports no chunk, and each object /// over it is refused as its own import of the pointer is (`Unsupported`, `HostMemory`). /// - /// Refused: a device without `VK_EXT_external_memory_host` (`Unsupported`, naming it); a RAM - /// whose ranges meet those of a RAM the device uses already, itself among them (`Invalid`, - /// `Problem::HostRam`); a lost device. + /// On a device without `VK_EXT_external_memory_host` that imports dma-bufs, a RAM with a + /// source of them has every chunk imported as its dma-buf, never its pointer. + /// + /// Refused: a device without `VK_EXT_external_memory_host` (`Unsupported`, naming it), unless + /// it imports dma-bufs and the RAM has a source of them; a RAM whose ranges meet those of a + /// RAM the device uses already, itself among them (`Invalid`, `Problem::HostRam`); a lost + /// device. pub fn use_host_ram(&self, ram: &Arc) -> Result { self.at_serving(|device| device.use_host_ram_now(ram)) } @@ -2165,8 +2171,12 @@ impl Device { return Err(self.lost_refusal()); } let shared = self.shared(); - if let Err(unsupported) = &shared.host_import { - return Err(Error::Unsupported(unsupported.clone())); + let importer = (shared.host_import.as_ref()) + .map_err(|unsupported| Error::Unsupported(unsupported.clone()))?; + // A device that imports dma-bufs of the pages alone imports no chunk of a RAM with no + // source of them. + if let (Err(refusal), None) = (importer.pointer_import(), &ram.dma_buf) { + return Err(refusal); } // A RAM with a source of dma-bufs imports its chunks by the import tax's verdict, so the // device's submission checks answer first (`submit_check.rs`), waited for at most @@ -2265,7 +2275,9 @@ impl Device { impl Device { /// How the device imports `ram`'s chunks (the module docs): [`Plan::listed`] where the RAM has /// a source of dma-bufs, the device imports dma-bufs, its held imports add to the cost of - /// every submission (its submission checks' import tax, `submit_check.rs`) and the driver + /// every submission (its submission checks' import tax, `submit_check.rs`) or it imports no + /// pointer (it enables no `VK_EXT_external_memory_host`, so the RAM's imports are dma-bufs + /// alone, as each costs every submission what one import does) and the driver /// takes the source's dma-bufs (asked of it, by an import of the RAM's first page as one /// released at once, unless it refused one before: `Device::ram_takes_dma_bufs`), so that /// its chunks are its dma-bufs; [`Plan::AHEAD`] elsewhere, its chunks of shared memory refused @@ -2276,7 +2288,8 @@ impl Device { let importer = (self.shared().host_import.as_ref()).ok(); let listed = match (importer, ram.dma_buf.as_ref(), ram.ranges.first()) { (Some(importer), Some(source), Some(first)) => { - importer.imports_dma_bufs() && self.pointer_imports_tax_submissions() && { + let taxed = importer.pointers().is_none() || self.pointer_imports_tax_submissions(); + importer.imports_dma_bufs() && taxed && { let page = first.start..first.start + importer.page; // SAFETY: the RAM's first page, mapped while the RAM lives, past the import // released before this returns; the source's dma-bufs hold exactly the pages @@ -2461,7 +2474,8 @@ impl Device { /// dma-bufs ([`HostRam::with_dma_buf`]), as one dma-buf of it (`Device::ram_span_as_dma_buf`): /// that first where the device's held pointer imports add to the cost of every submission /// (its submission checks' import tax, `submit_check.rs`), the pointer where that fails; the - /// pointer first elsewhere, the dma-buf where the pointer is refused. Counted: + /// pointer first elsewhere, the dma-buf where the pointer is refused; the dma-buf alone where + /// the device imports no pointer. Counted: /// `WorkCounts::host_ram_dma_buf_imports` (each import of a dma-buf), /// `host_ram_dma_buf_imports_failed` (each that failed: NVIDIA's driver refuses a udmabuf, /// which the device then remembers, and no later span asks the source) and @@ -2496,6 +2510,10 @@ impl Device { self.shared().counts.host_ram_dma_buf_imported(); Ok(self.ram_chunk(ram, span, of, raw, placement)) }; + // A device that imports no pointer takes the dma-buf alone. + if importer.pointers().is_none() { + return as_dma_buf(span); + } match self.pointer_imports_tax_submissions() { true => as_dma_buf(span.clone()).or_else(|_: Error| by_pointer(span)), false => match by_pointer(span.clone()) { @@ -2575,9 +2593,9 @@ impl Device { /// its pointer: a dedicated block of memory of a coherent type both the pages and a /// host-allocation buffer allow, with the device-address flag where the device enables /// `bufferDeviceAddress` (`memory::import_host`), and a `VkBuffer` over the whole of it. - /// Refused where the device's import alignment misses the span's start or end, it passes the - /// device's allocation size, or the driver refuses the pages (or the runtime does for it, - /// `Device::refuse_unpinnable`). + /// Refused where the device imports no pointer ([`Importer::pointer_import`]), its import + /// alignment misses the span's start or end, it passes the device's allocation size, or the + /// driver refuses the pages (or the runtime does for it, `Device::refuse_unpinnable`). /// /// # Safety /// @@ -2589,10 +2607,11 @@ impl Device { span: Range, of: Imported, ) -> Result { + let pointers = importer.pointer_import()?; let shared = self.shared(); let raw_device = shared.vk(); let size = span.end - span.start; - let alignment = importer.alignment.max(1); + let alignment = pointers.alignment.max(1); if !span.start.is_multiple_of(alignment) || !size.is_multiple_of(alignment) { return Err(not_importable()); } @@ -2625,7 +2644,7 @@ impl Device { // SAFETY: `raw` is a live buffer of this device. let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; // SAFETY: the pages are host memory aligned to the import alignment (checked above). - let types = match unsafe { importer.memory_types(raw_device, pointer) } { + let types = match unsafe { pointers.memory_types(raw_device, pointer) } { Ok(types) => types & requirements.memory_type_bits, Err(error) => { discard(); diff --git a/crates/metal2vulkan-runtime/src/host_ram/copy.rs b/crates/metal2vulkan-runtime/src/host_ram/copy.rs index 3a50f48ca..2673158d7 100644 --- a/crates/metal2vulkan-runtime/src/host_ram/copy.rs +++ b/crates/metal2vulkan-runtime/src/host_ram/copy.rs @@ -876,8 +876,8 @@ impl BlitCommandEncoder { /// /// No runs copy nothing. /// - /// Refused: a device without `VK_EXT_external_memory_host` (`Unsupported`, naming it); a RAM - /// the device does not use ([`Device::use_host_ram`](crate::Device::use_host_ram)), a run that + /// Refused: a device that imports no host memory (`Unsupported`, naming + /// `VK_EXT_external_memory_host`); a RAM the device does not use ([`Device::use_host_ram`](crate::Device::use_host_ram)), a run that /// is empty, starts off a 4-byte word or lies outside the RAM's ranges, bytes of /// `destination` that start off a 4-byte word of its memory, or, of a copy by regions (a run /// ending off a word), a `destination` over host pages the runs' bytes overlap (`Invalid`, diff --git a/crates/metal2vulkan-runtime/src/host_shared_pointers.rs b/crates/metal2vulkan-runtime/src/host_shared_pointers.rs index b3dffb0d8..5e878c5c5 100644 --- a/crates/metal2vulkan-runtime/src/host_shared_pointers.rs +++ b/crates/metal2vulkan-runtime/src/host_shared_pointers.rs @@ -22,14 +22,16 @@ impl Device { /// counterpart (Metal takes any page). Found once per device by importing one page of a /// `memfd` mapped shared, read and write (anonymous shared memory off Linux), which is /// released at once, and answered from that after; the import is counted as a no-copy - /// buffer's is. False for a device that imports no host memory. + /// buffer's is. False for a device that imports no host pointer (one without + /// `VK_EXT_external_memory_host`). /// /// Where it is false, a no-copy buffer over shared memory is imported only from the caller's /// dma-buf source ([`HostMemory::with_dma_buf`](crate::HostMemory::with_dma_buf)), and without /// one that works is a copy of the pages, announced (`copied-host-pages`, - /// `WorkCounts::copied_host_buffers_device_refused`). A source is what such memory needs to be - /// imported, whatever its pages' protection: pages the process maps - /// read-only go to the source without their pointer's import being tried (a dma-buf pins + /// `WorkCounts::copied_host_buffers_device_refused`); on a device that imports no pointer, + /// memory that comes with no source is refused instead, naming the extension. A source is + /// what such memory needs to be imported, whatever its pages' protection: pages the process + /// maps read-only go to the source without their pointer's import being tried (a dma-buf pins /// nothing of the process's mapping), so a caller need not make a writable second mapping of /// them for the import. Measured: MoltenVK (an M3 Max) and lavapipe answer true, RADV (a /// Radeon 780M and an RX 7900 XTX, Mesa 26.2.4) false; NVIDIA's driver imported such memory @@ -47,23 +49,25 @@ impl Device { if let Some(&answer) = shared.shared_pointer_imports.get() { return Ok(answer); } - let Ok(importer) = shared.host_import.as_ref() else { + let Some((importer, pointers)) = (shared.host_import.as_ref().ok()) + .and_then(|importer| Some((importer, importer.pointers()?))) + else { return Ok(false); }; if self.is_lost() { return Err(self.lost_refusal()); } - let unit = importer.page.max(importer.alignment); + let unit = pointers.unit(); let memory = SharedPages::new(2 * unit).ok_or(Error::OutOfMemory(MemoryKind::Host))?; // The first whole unit of the pages: the import's window is exactly it. let at = (memory.at.as_ptr() as u64).next_multiple_of(unit); let pointer = NonNull::new(at as *mut u8).ok_or(Error::OutOfMemory(MemoryKind::Host))?; - let window = import_window(at, unit, importer.page, importer.alignment) + let window = import_window(at, unit, importer.page, pointers.alignment) .map_err(|_| Error::OutOfMemory(MemoryKind::Host))?; // SAFETY: the window's pages are this call's mapping, which stays mapped until the // placement is freed below. let imported = unsafe { - self.import_pointer(importer, pointer, unit, &window, MemoryClass::Shared, false) + self.import_pointer(pointers, pointer, unit, &window, MemoryClass::Shared, false) }; let answer = match imported { Ok((buffer, placement)) => { diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index e31eae277..1d6c3b242 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -1498,10 +1498,11 @@ fn contents(buffer: &Buffer) -> Result, Unmade> { } /// Pages of `device`'s that its imports did not take as the class's, `why`: a cause that lasts -/// where the device imports no host memory at all (`VK_EXT_external_memory_host`), else one that +/// where the device imports no host pointer at all (`VK_EXT_external_memory_host`), else one that /// may pass (the import of these pages refused or failed, `copied.rs`). fn unimported(device: &Device, why: &str) -> Unmade { - match device.shared().host_import.is_ok() { + let pointers = (device.shared().host_import.as_ref()).is_ok_and(|i| i.pointers().is_some()); + match pointers { true => Unmade::passing(why), false => Unmade::lasting(why), } diff --git a/crates/metal2vulkan-runtime/src/private_properties.rs b/crates/metal2vulkan-runtime/src/private_properties.rs index 547ee90a3..47925b09b 100644 --- a/crates/metal2vulkan-runtime/src/private_properties.rs +++ b/crates/metal2vulkan-runtime/src/private_properties.rs @@ -39,7 +39,7 @@ use crate::linear_plan::LINEAR_ALIGNMENT; use crate::render_state::MAX_VIEWPORTS; use crate::texture_descriptor::{largest_side, MAX_ARRAY_LENGTH}; use crate::{Degradation, Device}; -use metal2vulkan::device::{MetalDeviceProperties, VkExtension, VkFeature}; +use metal2vulkan::device::{MetalDeviceProperties, VkFeature}; use metal2vulkan::error::{Capability, Needs}; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureType}; @@ -329,7 +329,8 @@ pub enum PrivateFlag { /// `areProgrammableSamplePositionsSupported`, which Metal answers alike). SupportsProgrammableSamplePositions, /// `supportsResourceDetachBacking`: the device's (a no-copy buffer or heap is detached from - /// its pages, `detach_backing`, wherever one is made: the device imports host memory). + /// its pages, `detach_backing`, wherever one is made: the device imports host memory, by its + /// pointer or as dma-bufs of its pages). SupportsResourceDetachBacking, /// `supportsSharedTextureHandles`: the device's, yes (a shareable texture's handle, within /// the process, `new_shared_texture_handle`). @@ -467,12 +468,14 @@ impl PrivateProperties { /// The answers on a device of `properties`, whose compile layer answers /// `metal`, and whose rows of [`MEASURED_FAMILY`] are `rows`, and the runtime gives a pixel /// format the capabilities `formats` answers and a texture over a buffer the linear - /// alignment `linear_alignment` (`Device::device_linear_texture_alignment`). + /// alignment `linear_alignment` (`Device::device_linear_texture_alignment`), and makes no-copy + /// buffers where `no_copy` (it imports host memory: `host_memory.rs`'s `Importer`). pub(crate) fn of( properties: &DeviceProperties, metal: &MetalDeviceProperties, rows: &[RowAudit], (formats, linear_alignment): (&dyn Fn(PixelFormat) -> FormatCapabilities, u64), + no_copy: bool, ) -> PrivateProperties { let answers = Answers { properties, @@ -480,6 +483,7 @@ impl PrivateProperties { rows, formats, linear_alignment, + no_copy, }; PrivateProperties { counts: PrivateCount::ALL.map(|p| { @@ -521,6 +525,7 @@ impl Device { &|pf| self.pixel_format_capabilities_now(pf), self.device_linear_texture_alignment(), ), + self.shared().host_import.is_ok(), ); // The properties the device has no answer for, announced once. let unknown = answers.unknown(); @@ -552,6 +557,9 @@ struct Answers<'a> { formats: &'a dyn Fn(PixelFormat) -> FormatCapabilities, /// The device's linear texture alignment (`Device::device_linear_texture_alignment`). linear_alignment: u64, + /// The device makes no-copy buffers: it imports host memory, by its pointer or as dma-bufs + /// of its pages (`host_memory.rs`'s `Importer`). + no_copy: bool, } impl Answers<'_> { @@ -675,11 +683,7 @@ impl Answers<'_> { .are_programmable_sample_positions_supported() == Ok(true) } - F::SupportsResourceDetachBacking => self - .properties - .description - .extensions - .contains(&VkExtension::ExtExternalMemoryHost), + F::SupportsResourceDetachBacking => self.no_copy, F::SupportsSharedTextureHandles => true, F::SupportsSimdReduction => { self.exact(R::SimdReduction) && self.exact(R::QuadReduction) diff --git a/crates/metal2vulkan-runtime/src/submit_check.rs b/crates/metal2vulkan-runtime/src/submit_check.rs index 3c7d1ff1b..6d67e585d 100644 --- a/crates/metal2vulkan-runtime/src/submit_check.rs +++ b/crates/metal2vulkan-runtime/src/submit_check.rs @@ -159,7 +159,7 @@ use crate::device::submit_stalls::Uses; use crate::device::{lock, Device, QueueSlot}; use crate::exit_guard::{self, Call}; use crate::freed_memory::Parking; -use crate::host_memory::Importer; +use crate::host_memory::{Importer, PointerImport}; use crate::in_place::DriverIdentity; use crate::loader_word::{DeviceWord, Held}; use crate::recorder::{self, Command}; @@ -944,8 +944,8 @@ struct Parts { /// (`step_aside.rs`). allocations: Arc, store: Arc, - /// The device's importer of host pointers, where it imports them. - importer: Option, + /// The device's import of host pointers, where it imports them. + pointers: Option, /// The queue families its buffers are shared among. families: Vec, /// Its memory types' properties, by index. @@ -1019,7 +1019,9 @@ impl Parts { checks: Arc::clone(&shared.submit_checks), allocations: Arc::clone(&shared.allocations.allocations), store: shared.shader_cache.content_store_share(), - importer: shared.host_import.as_ref().ok().cloned(), + pointers: (shared.host_import.as_ref().ok()) + .and_then(Importer::pointers) + .cloned(), families: shared.queue_families.clone(), type_flags, identity: device.driver_identity(), @@ -1547,7 +1549,7 @@ impl<'p> Import<'p> { /// pointer takes. `Some(None)` where the device imports no host pointer, the pages take no /// such type, or a call was refused; `None` where the process is exiting. fn make(parts: &Parts, pages: &'p Pages, bound: bool) -> Option>> { - let Some(importer) = &parts.importer else { + let Some(pointers) = &parts.pointers else { return Some(None); }; let _held = parts.step_held(); @@ -1555,10 +1557,10 @@ impl<'p> Import<'p> { let raw = parts.vk(); // SAFETY: the pages are this process's, at a host page, whose size the import alignment // divides where the device imports at all (it is checked below). - let Ok(types) = (unsafe { importer.memory_types(raw, pages.start) }) else { + let Ok(types) = (unsafe { pointers.memory_types(raw, pages.start) }) else { return Some(None); }; - let unit = importer.page.max(importer.alignment); + let unit = pointers.unit(); if !pages.length.is_multiple_of(unit) || !(pages.start.as_ptr() as u64).is_multiple_of(unit) { return Some(None); diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs index 96f61f40c..54eba9cac 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs @@ -2500,8 +2500,7 @@ fn pages_refused_before_the_driver_with_no_source_are_copied() { let Some(device) = device() else { return; }; - let importer = device.shared().host_import.as_ref().unwrap(); - let unit = importer.page.max(importer.alignment); + let unit = device.shared().host_import.as_ref().unwrap().unit(); let length = 4 * unit; // Three objects' pages, one after the other: the buffer's, the heap's, the rebind's. let pattern: Vec = (0..3 * length).map(|i| (i % 251) as u8 ^ 0xA5).collect(); diff --git a/crates/metal2vulkan-runtime/src/tests/private_properties.rs b/crates/metal2vulkan-runtime/src/tests/private_properties.rs index 3b617de9d..c214978b4 100644 --- a/crates/metal2vulkan-runtime/src/tests/private_properties.rs +++ b/crates/metal2vulkan-runtime/src/tests/private_properties.rs @@ -35,9 +35,17 @@ fn answers(stem: &str, desc: &metal2vulkan::device::DeviceDescription) -> Privat compile.metal_properties(), &rows, (&formats, linear(stem)), + no_copy(desc), ) } +/// Whether a device of the committed profile `desc` makes no-copy buffers: one that enables +/// `VK_EXT_external_memory_host` where it lists it does (a profile names no dma-buf route, which is +/// outside the vocabulary). +fn no_copy(desc: &metal2vulkan::device::DeviceDescription) -> bool { + (desc.extensions).contains(&metal2vulkan::device::VkExtension::ExtExternalMemoryHost) +} + /// `ALL` lists each property once, in declaration order, under a selector of its own. #[test] fn every_property_has_one_selector() { @@ -255,6 +263,7 @@ fn the_core_count_and_fp16_are_the_devices() { compile.metal_properties(), &rows, (&formats, linear(&stem)), + no_copy(&desc), ) }; let unknown = of(&properties).count(PrivateCount::GpuCoreCount); diff --git a/docs/HOWTO.md b/docs/HOWTO.md index d7e36ab20..8c17adf88 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -207,6 +207,13 @@ pages, announced ([Copied host buffers](#copied-host-buffers), `WorkCounts::copied_host_buffers_device_refused`); a rebind to such memory without a working source is refused with `Unsupported`, `HostMemory`. +A device that enables no `VK_EXT_external_memory_host` (a driver that lists none, or a device made +with it in `DeviceOptions::withheld_extensions`) but enables the dma-buf route imports no pointer +at all: memory made with a source is imported from its dma-bufs, its pages rounded out to the host +page, and memory made without one is refused (`Unsupported`, naming the extension), as is every +no-copy object on a device with neither. A guest RAM there (`Device::use_host_ram`) needs a source +too, and its chunks are its dma-bufs. + No driver that pins imported pages imports a mapping the kernel cannot pin (`VM_IO` or `VM_PFNMAP`: a mapping of a dma-buf). NVIDIA's driver fails such an import as out of device memory and then fails the process's later host-visible allocations too @@ -785,7 +792,8 @@ submission, can give the device the guest's RAM once instead: page are not). The CPU's writes made before the commit are seen, the GPU's are in the pages at the completion, and where the RAM came with a log its scatters are reported to it as the GPU's writes in place, so copied buffers and shadows over those pages copy them in at their next commit. - Refused: a device without `VK_EXT_external_memory_host` (`Unsupported`); a RAM the device does + Refused: a device that imports no host memory (`Unsupported`, naming + `VK_EXT_external_memory_host`); a RAM the device does not use, a run empty, starting off a 4-byte word or outside the RAM, bytes of the buffer that start off a 4-byte word of its memory, or, of a copy by regions, a buffer over host pages the runs' bytes overlap (`Invalid`, `Problem::HostRam`); bytes past the buffer (`Invalid`, diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index f7a88ee25..1c4328939 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -160,7 +160,7 @@ Columns: | `TextureView` | A texture view Vulkan cannot make exactly on this image | every device (no Vulkan mechanism); every device (not implemented) | `ours` | 9: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`, `crates/metal2vulkan-runtime/src/texture.rs (view)` (+6) | `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) | `ours` | 7: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`, `crates/metal2vulkan-runtime/src/texture.rs (may_view)` (+5) | `app`: texture swizzles whose Metal behaviour is unmeasured | | `MipmapGeneration` | `generateMipmapsForTexture:` that cannot run on the device | devices without a format's usage; every device (not implemented) | `ours` | 6: `crates/metal2vulkan-runtime/src/blit_texture.rs (mipmaps)`, `crates/metal2vulkan-runtime/src/mipmap_pick.rs (pick_mipmaps)` (+2) | `app`: generateMipmapsForTexture: of a format or chain neither the device's blits nor the compute filter can run | -| `HostMemory` | A buffer over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`) | devices without VkExtension::ExtExternalMemoryHost; drivers with defect UnpinnablePagesBreakHostMemory; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 7: `crates/metal2vulkan-runtime/src/host_memory.rs (new, 3 sites)`, `crates/metal2vulkan-runtime/src/host_memory.rs (not_importable)` (+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; drivers with defect UnpinnablePagesBreakHostMemory; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 8: `crates/metal2vulkan-runtime/src/host_memory.rs (new, 3 sites)`, `crates/metal2vulkan-runtime/src/host_memory.rs (no_pointer_refusal)` (+4) | `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) | `device` | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (gpu_times)` | `rare`: GPU times on a queue without timestamps | | `CountingVisibility` | A `Counting` visibility result (`MTLVisibilityResultModeCounting`) on a device without `occlusionQueryPrecise` | devices without VkFeature::OcclusionQueryPrecise | `device` | 1: `crates/metal2vulkan-runtime/src/visibility.rs (check_mode)` | `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) | `device` | 1: `crates/metal2vulkan-runtime/src/view_plan.rs (reinterpretation_refused)` | `app`: a view of another component layout on a portability subset (MoltenVK) | @@ -681,7 +681,7 @@ Each refusal's sites, with the function that builds it. - `feature::TextureView`: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`; `crates/metal2vulkan-runtime/src/texture.rs (view)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs (make_second_twin)`; `crates/metal2vulkan-runtime/src/texture/view_shadow.rs (apart_refusal)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (converted_view)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (luma_view)`; `crates/metal2vulkan-runtime/src/view_plan.rs (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs (check_view, 2 sites)` - `feature::TextureSwizzle`: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`; `crates/metal2vulkan-runtime/src/texture.rs (may_view)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs (select)` - `feature::MipmapGeneration`: `crates/metal2vulkan-runtime/src/blit_texture.rs (mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_pick.rs (pick_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs (blit_lack, 2 sites)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs (plan_mipmaps, 2 sites)` -- `feature::HostMemory`: `crates/metal2vulkan-runtime/src/host_memory.rs (new, 3 sites)`; `crates/metal2vulkan-runtime/src/host_memory.rs (not_importable)`; `crates/metal2vulkan-runtime/src/host_memory.rs (refuse_unwritable)`; `crates/metal2vulkan-runtime/src/host_memory.rs (unpinnable)`; `crates/metal2vulkan-runtime/src/host_ram.rs (new)` +- `feature::HostMemory`: `crates/metal2vulkan-runtime/src/host_memory.rs (new, 3 sites)`; `crates/metal2vulkan-runtime/src/host_memory.rs (no_pointer_refusal)`; `crates/metal2vulkan-runtime/src/host_memory.rs (not_importable)`; `crates/metal2vulkan-runtime/src/host_memory.rs (refuse_unwritable)`; `crates/metal2vulkan-runtime/src/host_memory.rs (unpinnable)`; `crates/metal2vulkan-runtime/src/host_ram.rs (new)` - `feature::GpuTimes`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (gpu_times)` - `feature::CountingVisibility`: `crates/metal2vulkan-runtime/src/visibility.rs (check_mode)` - `feature::ViewFormatReinterpretation`: `crates/metal2vulkan-runtime/src/view_plan.rs (reinterpretation_refused)` diff --git a/docs/RUNTIME-PORTING.md b/docs/RUNTIME-PORTING.md index a39d22b91..c00761a21 100644 --- a/docs/RUNTIME-PORTING.md +++ b/docs/RUNTIME-PORTING.md @@ -247,7 +247,7 @@ narrow refusal that the call's rustdoc describes. | Item | Metal | Runtime | |---|---|---| | `heap_texture_size_and_align` | `heapTextureSizeAndAlignWithDescriptor:` | `Device::heap_texture_size_and_align`: Metal's answer wherever the runtime models it, the device's images' own footprint where it does not | -| `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_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 or imports none, 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` |