diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index f7e9eafbe..93f819408 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -204,7 +204,9 @@ the runtime made. attachment lies in them uses them from its open. 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)). A no-copy buffer's import of such + ([HOWTO](../../docs/HOWTO.md#6-host-memory-a-driver-refuses)); 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 blit, which then costs time: RADV lists every import in every submission. Nothing of Metal's observes it. A no-copy buffer, heap, or buffer's or heap's rebind whose import the caller's gate diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index bb94020aa..14ebe7dad 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -22,8 +22,8 @@ use super::heap::{Heap, HeapProblem}; use super::host_bytes::HostBytes; use super::host_memory::{ based_size, binds_in, buffer_base, import_refused, import_window, not_importable, - refuse_unwritable, refused, Deallocator, HostMemory, HostParts, HostRelease, ImportRequest, - ImportWindow, Importer, KeepAlive, Source, + refuse_unwritable, refused, unpinnable, Deallocator, HostMemory, HostParts, HostRelease, + ImportRequest, ImportWindow, Importer, KeepAlive, Source, }; use super::host_ram::Routed; #[cfg(unix)] @@ -584,18 +584,20 @@ impl Device { Ok((buffer, memory, again)) } // SAFETY: as above. - Ok(Err(source)) => unsafe { + Ok(Err((source, refusal))) => unsafe { let keep = !of_heap; let window = &window; self.import_from_source( call, importer, pointer, length, window, source, class, keep, ) - }, + } + .map_err(|failed| source_failure(failed, refusal)), Err(error) => Err(error), }; let (buffer, memory, again) = match imported { Ok(imported) => imported, - // An import the device and the gate admitted that then failed: a copy, + // An import the device and the gate admitted that then failed, or pages the + // runtime refused for the driver that no dma-buf of them served: a copy, // announced. Err(error) if copyable && copies_after(&error) => { // SAFETY: the caller's contract. @@ -860,7 +862,7 @@ impl Device { // 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. - Ok(Err(source)) => { + Ok(Err((source, refusal))) => { let was_settled = settled.take().is_some(); // SAFETY: as above, and the source's pieces hold the pages // (`HostMemory::with_dma_buf`). @@ -869,7 +871,8 @@ impl Device { self.import_from_source( call, importer, pointer, length, window, source, class, false, ) - }; + } + .map_err(|failed| source_failure(failed, refusal)); let made = match from_source { Ok((host, placement, _)) => { // The heap's images bound to its bytes, and the images in place @@ -900,7 +903,8 @@ impl Device { } } // An import of the caller's dma-bufs the gate admitted that then - // failed: a copy, as where the pointer's fails. + // failed, or that served pages the runtime refused for the driver: a + // copy, as where the pointer's fails. Err(error) if copyable && copies_after(&error) => Err(Some(error)), Err(error) => return Err(error), }; @@ -1122,9 +1126,10 @@ impl Device { /// 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 + /// no window, a buffer that does not fit it, no memory type, a driver refusal, the runtime's + /// refusal of pages the kernel cannot pin) and the caller gave a dma-buf source the device can + /// use, the source, uncalled, with the refusal (`Err`), for the caller to call with no lock of + /// the runtime's held (`Device::import_from_source`, `dma_buf.rs`; [`source_failure`]). A /// refusal without such a source is the pointer's. /// /// # Safety @@ -1138,7 +1143,7 @@ impl Device { length: u64, host: HostWindow, class: MemoryClass, - ) -> Result, Error> { + ) -> Result, Error> { let HostWindow { window, by_pointer, @@ -1157,7 +1162,10 @@ impl Device { }, false => not_importable(), }; - source.map(Err).ok_or(refusal) + match source { + Some(source) => Ok(Err((source, refusal))), + None => Err(refusal), + } } /// The `VkBuffer` of a no-copy buffer of `length` bytes at `pointer`, made for host @@ -1333,7 +1341,9 @@ impl Device { Err(why) => { discard(&memory); return Err(match why { - NotCopied::Unreadable => failed.unwrap_or_else(not_importable), + NotCopied::Unreadable => failed + .filter(|failed| !refused(failed)) + .unwrap_or_else(not_importable), NotCopied::OutOfHostMemory => Error::OutOfMemory(MemoryKind::Host), }); } @@ -1477,7 +1487,13 @@ impl Device { ) -> Result { let shared = self.shared(); let raw_device = shared.vk(); - let unreadable = |failed: Option| failed.unwrap_or_else(not_importable); + // The pages' refusal where they cannot be copied: the import's failure, or a refusal of + // them. + let unreadable = |failed: Option| { + failed + .filter(|failed| !refused(failed)) + .unwrap_or_else(not_importable) + }; let bytes = usize::try_from(length).map_err(|_| Error::OutOfMemory(MemoryKind::Host))?; // Padded to 16 bytes, so a device fill clears every byte too, as a buffer of its own. let size = length @@ -1668,6 +1684,9 @@ impl Device { false => None, }; let imported = view.as_ref().map_or(start, ReadOnlyView::pointer); + // Pages the kernel cannot pin, never handed to a driver whose failed import of them + // breaks its later allocations. + self.refuse_unpinnable(imported, window.size)?; // SAFETY: the imported pages are host memory aligned to the import alignment (the // window's). let types = @@ -1801,10 +1820,24 @@ fn writability_settled( } /// Whether `error`, an import's failure that is not the device's refusal of the pages, leaves the -/// no-copy buffer a copy of them (`copied.rs`): out of memory, or another Vulkan error. A lost -/// device does not, nor does misuse. +/// no-copy buffer a copy of them (`copied.rs`): out of memory, another Vulkan error, or the +/// runtime's refusal of pages the kernel cannot pin, made for a driver whose failed import of them +/// breaks its later allocations ([`unpinnable`]), which no dma-buf of them served. A lost device +/// does not, nor does misuse. fn copies_after(error: &Error) -> bool { - matches!(error, Error::OutOfMemory(_) | Error::Vulkan(_)) + matches!(error, Error::OutOfMemory(_) | Error::Vulkan(_)) || *error == unpinnable() +} + +/// What an import of the caller's dma-bufs (`dma_buf.rs`) that `failed` answers, made where the +/// pages' pointer was refused with `refusal` ([`Device::import_by_pointer`]): the runtime's refusal +/// of pages the kernel cannot pin ([`unpinnable`]) where the dma-bufs were refused too (no source +/// answered, or the device refused them), so the object is a copy of the pages as where no source +/// is given ([`copies_after`]); else `failed`, misuse and a lost device among it. +fn source_failure(failed: Error, refusal: Error) -> Error { + match refused(&failed) && refusal == unpinnable() { + true => refusal, + false => failed, + } } /// The host pages a no-copy object of `length` bytes at `pointer` imports on the device of diff --git a/crates/metal2vulkan-runtime/src/copied.rs b/crates/metal2vulkan-runtime/src/copied.rs index fb0d47836..c41da89d6 100644 --- a/crates/metal2vulkan-runtime/src/copied.rs +++ b/crates/metal2vulkan-runtime/src/copied.rs @@ -1,7 +1,9 @@ //! Copied host buffers: a no-copy buffer whose import of the caller's pages the caller's gate //! refused ([`HostMemory::with_import_gate`](crate::HostMemory)), or whose import the gate and -//! the device admitted and that then failed (out of memory, another Vulkan error), is made all the -//! same over a copy of its bytes (`Device::buffer_over_host_memory`), announced +//! the device admitted and that then failed (out of memory, another Vulkan error, or the runtime's +//! refusal of pages the kernel cannot pin on a driver whose failed import of them breaks it, +//! `RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`, that no dma-buf of them served), is made +//! all the same over a copy of its bytes (`Device::buffer_over_host_memory`), announced //! (`copied-host-pages`). No import maps the pages, so they take no kernel mapping. //! //! - **The copy.** A `VkBuffer` of the buffer's length in host-visible, coherent memory of the diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index d6cc78dbd..e6e5962c4 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1850,9 +1850,12 @@ degradations! { /// (`HostMemory::with_import_gate`) refused the pages' import, or the import the device /// and the gate admitted failed, of the pointer or of the caller's dma-bufs (out of /// memory, or another Vulkan error, such as a driver out of the mappings the host kernel - /// allows). A copy of pages the process maps read-only drops the GPU's writes, as Metal - /// drops them: never written to the pages (`WorkCounts::copied_dropped_bytes`; the detail - /// says so). A copy whose own allocation fails refuses the call (`OutOfMemory`). + /// allows), or the runtime kept pages the kernel cannot pin from a driver whose failed + /// import of them breaks it (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`) and no + /// dma-buf of them served. A copy of pages the process maps read-only drops the GPU's + /// writes, as Metal drops them: never written to the pages + /// (`WorkCounts::copied_dropped_bytes`; the detail says so). A copy whose own allocation + /// fails refuses the call (`OutOfMemory`). /// Announced once per device, by the call that makes it, or at each such call where /// `DeviceOptions::announce_each` asks. Counted: `WorkCounts::copied_host_buffers_made`. CopiedHostPages = "copied-host-pages", Precision, diff --git a/crates/metal2vulkan-runtime/src/driver_defects.rs b/crates/metal2vulkan-runtime/src/driver_defects.rs index de56c5783..b767cb24e 100644 --- a/crates/metal2vulkan-runtime/src/driver_defects.rs +++ b/crates/metal2vulkan-runtime/src/driver_defects.rs @@ -444,6 +444,32 @@ pub(super) struct Affected { /// Nothing is refused: a 10-bit two-plane texture converts through Metal's arithmetic there, and /// its planes read in place through the texel buffer (`ycbcr_device.rs`, /// `texture/ycbcr_planes.rs`). +/// +/// `UnpinnablePagesBreakHostMemory`: +/// - NVIDIA's (`NVIDIA_PROPRIETARY`): on the RTX 5080 Laptop GPU (`deviceID` 0x2c19) under Linux, +/// `vkAllocateMemory` importing the pointer of a mapping of a udmabuf of a `memfd`'s pages +/// (`VM_PFNMAP`, which the kernel's `get_user_pages` refuses) answers +/// `VK_ERROR_OUT_OF_DEVICE_MEMORY` on both memory types `vkGetMemoryHostPointerPropertiesEXT` +/// allows (2 and 3), where Vulkan requires `VK_ERROR_INVALID_EXTERNAL_HANDLE` of a pointer +/// "platform-specific restrictions" keep from being imported ("Host External Memory"), and +/// later allocations of the process fail as out of device memory too, where Vulkan's +/// out-of-memory errors "do not modify any currently existing Vulkan objects". After such an +/// import tried as type 2, then 3: every host-pointer import measured (a `memfd`'s shared pages, +/// 8 KiB to 8 MiB at any offset; 8 MiB of private anonymous pages; 8 MiB 512 MiB away from the +/// mapping; 40 tries over 3 s; on a second device made after it) and a plain 64 KiB +/// allocation of host-visible type 2, while a device-local one allocates. After the runtime's +/// own import of such pages (type 3, then 2): an 8 MiB import 8 times in a row, and a guest +/// RAM's chunk at each of 7 objects over it, while each object's own one-page import succeeded. +/// Neither the pointer's properties query alone, a failed import of the udmabuf itself, nor a +/// mapping of one never imported broke anything. Measured on 615.71.09 with the runtime's +/// device tests: known broken through 615.71.09; every other NVIDIA GPU, unprobed, takes the +/// same path. Nothing is refused that the driver would import: on Linux the runtime asks the +/// kernel whether it pins each mapping over the pages before it hands the driver their pointer +/// (`host_memory.rs`'s `refuse_unpinnable`), and never hands it pages it cannot pin: a no-copy +/// buffer, heap or rebind over them takes the caller's dma-buf source, and else, or where its +/// import fails, a copy of them, as where a pointer import fails (`copied.rs`, +/// `copied-host-pages`); a RAM's chunk over them is not imported, and its objects take their +/// own paths to the same end. pub(super) const AFFECTED: &[Affected] = &[ Affected { defect: RuntimeDriverDefect::HostTransferImagesCopiedAtBind, @@ -577,6 +603,11 @@ pub(super) const AFFECTED: &[Affected] = &[ driver: DriverId::MESA_RADV, clean: &[], }, + Affected { + defect: RuntimeDriverDefect::UnpinnablePagesBreakHostMemory, + driver: DriverId::NVIDIA_PROPRIETARY, + clean: &[], + }, ]; /// The defects of the driver and device `description` names, its GPU read by the `deviceID` it diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index b9c4326f0..408c6dfb4 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -45,7 +45,8 @@ //! 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 +//! 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. //! - **When**. The pages are imported when the buffer is made, on every platform, as Metal wires @@ -111,7 +112,7 @@ use super::program_objects::ProgramObject; use super::work_counts::Counters; use ash::vk; use metal2vulkan::device::{EnableSet, VkExtension}; -use metal2vulkan::error::{Feature, Unsupported}; +use metal2vulkan::error::{Feature, RuntimeDriverDefect, Unsupported}; use std::ffi::c_void; use std::ops::Range; use std::ptr::NonNull; @@ -610,9 +611,22 @@ pub(super) fn not_importable() -> Error { /// 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`]). +/// refused the pointer, or the runtime refused it for the driver ([`unpinnable`]); a dma-buf of +/// its pages may serve it ([`DmaBufSource`]). pub(super) fn refused(error: &Error) -> bool { - *error == not_importable() + *error == not_importable() || *error == unpinnable() +} + +/// The runtime's refusal of host pages the kernel cannot pin, made before a driver that breaks as +/// it fails their import sees their pointer (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`, +/// `Device::refuse_unpinnable`): a dma-buf of the pages may serve them, as where the driver +/// refuses the pointer ([`refused`]), and else a no-copy object is a copy of them (`copied.rs`), +/// as where their import fails. +pub(super) fn unpinnable() -> Error { + Error::Unsupported(Unsupported::runtime_driver_defect( + Feature::HostMemory, + RuntimeDriverDefect::UnpinnablePagesBreakHostMemory, + )) } /// The error of a failed import call (`vkGetMemoryHostPointerPropertiesEXT` or the allocation): a @@ -656,6 +670,38 @@ pub(super) fn refuse_unwritable(window: &ImportWindow, counts: &Counters) -> Res } } +impl super::Device { + /// Refuse `size` bytes of host pages at `pages` before the driver is handed their pointer + /// ([`unpinnable`]), where the device's driver breaks its later allocations as it fails an + /// import of pages the kernel cannot pin (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`) + /// and the kernel does not pin every mapping over them (`Access::Pin`: one `PROCMAP_QUERY` + /// and one read a mapping, or the lines of `/proc/self/maps` before Linux 6.11); counted + /// (`WorkCounts::host_imports_unpinnable`). Pages whose mappings cannot be asked are refused + /// too. On every other driver, and off Linux, nothing is asked. + pub(super) fn refuse_unpinnable(&self, pages: NonNull, size: u64) -> Result<(), Error> { + let defect = RuntimeDriverDefect::UnpinnablePagesBreakHostMemory; + if !self.properties().driver_defects.contains(&defect) || kernel_pins(pages, size) { + return Ok(()); + } + self.shared().counts.host_import_unpinnable(); + Err(unpinnable()) + } +} + +/// Whether the kernel pins every mapping over `size` bytes of host pages at `pages` +/// ([`Access::Pin`]); `false` where the mappings cannot be asked. +#[cfg(target_os = "linux")] +fn kernel_pins(pages: NonNull, size: u64) -> bool { + let start = pages.as_ptr() as u64; + mappings_permitted(start, start.saturating_add(size), Access::Pin, &mut 0) == Some(true) +} + +/// [`kernel_pins`] off Linux, where no driver is kept from host pages: `true`. +#[cfg(not(target_os = "linux"))] +fn kernel_pins(_pages: NonNull, _size: u64) -> bool { + true +} + /// Whether the process maps every page of `[start, end)` with read permission, as the kernel /// answers now ([`mappings_permitted`]): where it does, the CPU reads the bytes with plain loads, /// as a copied host buffer's comparisons read them at each commit (`copied.rs`). `false` where @@ -748,6 +794,13 @@ pub(super) enum Access { Read, /// `VM_WRITE`, the `w`: Linux drivers pin imported pages for writing ([`refuse_unwritable`]). Write, + /// `VM_READ`, and the kernel pins the mapping's pages: it reads a byte of the mapping's first + /// page in the window through `process_vm_readv`, which pins each page it reads + /// (`copied::read_pages`). The kernel pins no page of a `VM_IO` or `VM_PFNMAP` mapping, such + /// as a mapping of a dma-buf, and answers that for the whole mapping (`check_vma_flags` in + /// `mm/gup.c`), so one read a mapping answers for all of its pages + /// (`Device::refuse_unpinnable`). + Pin, } #[cfg(target_os = "linux")] @@ -755,15 +808,28 @@ impl Access { /// The mapping's flag of the permission in `PROCMAP_QUERY`'s answer (`vma_flags`). fn queried(self) -> u64 { match self { - Access::Read => PROCMAP_QUERY_VMA_READABLE, + Access::Read | Access::Pin => PROCMAP_QUERY_VMA_READABLE, Access::Write => PROCMAP_QUERY_VMA_WRITABLE, } } + /// Whether the mapping holding `address` meets the access beyond its permission: for + /// [`Access::Pin`], whether the kernel reads the byte at `address` through a pin of its page; + /// for the others, always. + fn pinned(self, address: u64) -> bool { + if self != Access::Pin { + return true; + } + let Some(page) = NonNull::new(address as *mut u8) else { + return false; + }; + super::copied::read_pages(page, &mut [0]) + } + /// The permission's place and letter in a maps line's permissions (`rw-p`). fn letter(self) -> (usize, u8) { match self { - Access::Read => (0, b'r'), + Access::Read | Access::Pin => (0, b'r'), Access::Write => (1, b'w'), } } @@ -886,7 +952,7 @@ pub(super) fn queried_permitted( if query.vma_start > covered || query.vma_end <= covered { return None; } - if query.vma_flags & access.queried() == 0 { + if query.vma_flags & access.queried() == 0 || !access.pinned(covered) { return Some(false); } covered = query.vma_end; @@ -925,7 +991,7 @@ pub(super) fn permitted( continue; } *asked += 1; - if from > covered || !allowed { + if from > covered || !allowed || !access.pinned(covered) { return false; } covered = to; diff --git a/crates/metal2vulkan-runtime/src/host_ram.rs b/crates/metal2vulkan-runtime/src/host_ram.rs index b134bf215..05b716dbd 100644 --- a/crates/metal2vulkan-runtime/src/host_ram.rs +++ b/crates/metal2vulkan-runtime/src/host_ram.rs @@ -581,7 +581,8 @@ impl Device { /// 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. + /// it passes the device's allocation size, or the driver refuses the pages (or the runtime + /// does for it, `Device::refuse_unpinnable`). /// /// # Safety /// @@ -607,6 +608,9 @@ impl Device { return Err(Error::OutOfMemory(MemoryKind::Device)); } let pointer = NonNull::new(span.start as *mut u8).ok_or_else(not_importable)?; + // Pages the kernel cannot pin, never handed to a driver whose failed import of them + // breaks its later allocations. + self.refuse_unpinnable(pointer, size)?; let mut external = vk::ExternalMemoryBufferCreateInfo::default() .handle_types(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT); let info = shared.sharing().buffer( diff --git a/crates/metal2vulkan-runtime/src/tests/copied.rs b/crates/metal2vulkan-runtime/src/tests/copied.rs index 16c06835b..5a4f0146e 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied.rs @@ -314,6 +314,25 @@ impl DmaBufMapping { } } +#[cfg(all(target_os = "linux", any(m2v_gpu, m2v_cpu_icd)))] +impl DmaBufMapping { + /// A source of the mapping's own dma-buf, for a request of all of its pages: a clone of the + /// descriptor, which the runtime takes. A request of other pages is refused. + pub(super) fn source(&self) -> crate::DmaBufSource { + let dma_buf = std::sync::Arc::new(self._dma_buf.try_clone().unwrap()); + let (start, length) = (self.pages.as_ptr() as usize, self.length as u64); + std::sync::Arc::new(move |request: crate::DmaBufRequest| { + if request.start.as_ptr() as usize != start || request.length != length { + return Err(std::io::Error::other("not the mapping's pages")); + } + Ok(vec![crate::DmaBufChunk { + fd: dma_buf.try_clone()?, + length, + }]) + }) + } +} + #[cfg(target_os = "linux")] impl Drop for DmaBufMapping { fn drop(&mut self) { diff --git a/crates/metal2vulkan-runtime/src/tests/driver_defects.rs b/crates/metal2vulkan-runtime/src/tests/driver_defects.rs index edd0cf7b0..affe374d7 100644 --- a/crates/metal2vulkan-runtime/src/tests/driver_defects.rs +++ b/crates/metal2vulkan-runtime/src/tests/driver_defects.rs @@ -31,6 +31,7 @@ const BIND_COPIES: RuntimeDriverDefect = RuntimeDriverDefect::HostTransferImages const LOST_SIGNALS: RuntimeDriverDefect = RuntimeDriverDefect::WaitForAnyObjectLosesASignal; const CHROMA: RuntimeDriverDefect = RuntimeDriverDefect::TwoPlaneChromaMisplaced; const TEN_BIT_WORDS: RuntimeDriverDefect = RuntimeDriverDefect::TenBitCodesReadAsWords; +const UNPINNABLE: RuntimeDriverDefect = RuntimeDriverDefect::UnpinnablePagesBreakHostMemory; /// Every committed profile's driver has its defects at every release and GPU but those a probe /// found clean: MoltenVK the multisampled depth/stencil colour copies, the inexact depths past @@ -53,7 +54,8 @@ const TEN_BIT_WORDS: RuntimeDriverDefect = RuntimeDriverDefect::TenBitCodesReadA /// descriptors a pipeline bind leaves stale on every GPU (Arrow Lake's, not measured, too); /// NVIDIA's the /// stencil colour copies on every GPU but the RTX 5080 Laptop GPU, measured clean (the GTX 1060 and -/// the RTX 5080 desktop GPU, not measured, take them); SwiftShader none. +/// the RTX 5080 desktop GPU, not measured, take them), and the host memory a failed import of +/// unpinnable pages breaks on every GPU; SwiftShader none. #[test] fn the_committed_profiles_drivers_have_their_defects() { let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles"); @@ -93,8 +95,8 @@ fn the_committed_profiles_drivers_have_their_defects() { } Some(DriverId::MESA_RADV) => vec![NAN_COPIES, PREPROCESS, TEN_BIT_WORDS], Some(DriverId::INTEL_OPEN_SOURCE_MESA) => vec![COMPRESSION, COUNTS, STALE_PUSHES], - Some(DriverId::NVIDIA_PROPRIETARY) if desc.device_id == 0x2c19 => Vec::new(), - Some(DriverId::NVIDIA_PROPRIETARY) => vec![STENCIL_COPIES], + Some(DriverId::NVIDIA_PROPRIETARY) if desc.device_id == 0x2c19 => vec![UNPINNABLE], + Some(DriverId::NVIDIA_PROPRIETARY) => vec![STENCIL_COPIES, UNPINNABLE], _ => Vec::new(), }; let defects: Vec<_> = of(&desc).into_iter().collect(); @@ -102,8 +104,8 @@ fn the_committed_profiles_drivers_have_their_defects() { drivers += usize::from(!expected.is_empty()); } assert!( - drivers >= 13, - "lavapipe's three, MoltenVK's two, ANV's four, RADV's three and NVIDIA's two" + drivers >= 14, + "lavapipe's three, MoltenVK's two, ANV's four, RADV's three and NVIDIA's three" ); } @@ -125,7 +127,8 @@ fn a_clean_gpu_alone_lacks_the_defect() { /// NVIDIA's stencil colour-copy defect, measured on the RTX 3090 (`deviceID` 0x2204), is every /// NVIDIA GPU's but the RTX 5080 Laptop GPU's (0x2c19), measured clean: the RTX 3070 (0x2484) and -/// an Ada GPU (0x2684) take it; a device that runs another driver has none. +/// an Ada GPU (0x2684) take it; a device that runs another driver has none. The unpinnable pages' +/// defect, measured on the 5080, is every NVIDIA GPU's, and no other driver's. #[test] fn nvidia_s_colour_copies_are_clean_on_the_gpu_measured_alone() { let nvidia = Some(DriverId::NVIDIA_PROPRIETARY); @@ -133,13 +136,21 @@ fn nvidia_s_colour_copies_are_clean_on_the_gpu_measured_alone() { for device in [0x2204, 0x2484, 0x2684] { assert_eq!( of(device).into_iter().collect::>(), - vec![STENCIL_COPIES], + vec![STENCIL_COPIES, UNPINNABLE], "{device:#x}" ); } - assert!(of(0x2c19).is_empty()); + assert_eq!(of(0x2c19).into_iter().collect::>(), vec![UNPINNABLE]); let radv = among(AFFECTED, Some(DriverId::MESA_RADV), 0x2204); assert!(!radv.contains(&COPIES) && !radv.contains(&STENCIL_COPIES)); + for driver in [ + DriverId::MESA_RADV, + DriverId::MESA_LLVMPIPE, + DriverId::INTEL_OPEN_SOURCE_MESA, + DriverId::MOLTENVK, + ] { + assert!(!among(AFFECTED, Some(driver), 0x2c19).contains(&UNPINNABLE)); + } } /// RADV's implicit preprocessing after an execution set, measured broken on the RX 7900 XTX diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs index 4bc663399..bfe72aa9e 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs @@ -15,6 +15,13 @@ //! - **Rebinds.** A buffer's or heap's rebind asks the resolver once with its new window: one run //! in a chunk binds there, the gate unasked and nothing imported; several runs take the gate, //! and the copy where it refuses. +//! - **After pages the kernel cannot pin.** A no-copy buffer over a dma-buf's mapping +//! (`VM_PFNMAP`, Linux, where `/dev/udmabuf` opens), made first, takes nothing from the device: +//! the RAM's first chunk is imported after it, and buffers bound in it, on a driver whose failed +//! import of such pages breaks its later ones +//! (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`, NVIDIA's) too, where the runtime +//! refuses the pages before the driver sees them. There a buffer, a heap and a rebind over such +//! pages with no dma-buf source are each a copy of them, whose bytes the GPU reads. //! - **The use.** Dropping the use while a command buffer still holds a chunk frees the chunk //! after that command buffer completed, and the RAM's keep-alive goes after it; the same RAM //! used twice is refused, a RAM apart from it taken; a new RAM over the same ranges is taken once @@ -838,3 +845,202 @@ fn a_rebind_onto_several_runs_takes_the_gate_and_the_copy_where_it_refuses() { drop((made, used, ram)); assert!(settles(&dropped)); } + +/// Whether `device`'s driver breaks its later allocations as it fails an import of pages the +/// kernel cannot pin (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`, NVIDIA's). +#[cfg(target_os = "linux")] +fn breaks_on_unpinnable_pages(device: &Device) -> bool { + let defect = metal2vulkan::error::RuntimeDriverDefect::UnpinnablePagesBreakHostMemory; + device.properties().driver_defects.contains(&defect) +} + +/// A new RAM's first chunk is imported on `device`, two buffers bound in it, their bytes the +/// GPU's. +#[cfg(target_os = "linux")] +fn a_chunk_binds(device: &Device) { + let page = device.shared().host_import.as_ref().unwrap().page; + let (ram, start, dropped) = new_ram(); + let used = device.use_host_ram(&ram).unwrap(); + let (a, b) = (start + MIB, start + 3 * MIB); + fill_pattern(a..a + 2 * page); + fill_pattern(b..b + page); + let (runs, gates): (Arc>, Arc>) = Default::default(); + let before = device.work_counts(); + let over = |at, length| { + buffer( + device, + at, + length, + resolver(&runs, itself), + gate(&gates, true), + ) + }; + let (first, second) = (over(a, 2 * page).unwrap(), over(b, page).unwrap()); + let after = device.work_counts(); + let made = ( + after.host_ram_chunks_imported - before.host_ram_chunks_imported, + after.chunk_bound_buffers_made - before.chunk_bound_buffers_made, + ); + assert_eq!( + made, + (1, 2), + "the first chunk imported, both buffers bound in it" + ); + assert_eq!(gpu_bytes(device, &first, 2 * page), bytes(a..a + 2 * page)); + assert_eq!(gpu_bytes(device, &second, page), bytes(b..b + page)); + drop((first, second, used, ram)); + assert!(settles(&dropped)); +} + +/// A no-copy buffer over a dma-buf's mapping, with a source of its dma-buf, made before the RAM's +/// first chunk is imported, leaves that import and the buffers bound in it as they are without +/// it ([`a_chunk_binds`]). On a driver whose failed import of such pages breaks its later ones, +/// the runtime refuses the pages before the driver sees them, and the buffer is the dma-buf's or +/// a copy of the pages; elsewhere it is whatever the driver makes of them. Linux only, where +/// `/dev/udmabuf` opens. +#[cfg(target_os = "linux")] +#[test] +fn a_chunk_is_imported_after_a_refused_import_of_a_dma_buf_mapping() { + let Some(device) = device() else { + return; + }; + let page = device.shared().host_import.as_ref().unwrap().page; + let Some(mapping) = super::copied::DmaBufMapping::new(&vec![0x5Au8; 2 * page as usize]) else { + return; + }; + let before = device.work_counts(); + // SAFETY: the mapping outlives the buffer, and the source makes dma-bufs of its pages. + let first = unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::with_dma_buf(mapping.pages, mapping.source()), + 2 * page, + ResourceOptions::default(), + None, + ) + }; + let after = device.work_counts(); + let unpinnable = after.host_imports_unpinnable - before.host_imports_unpinnable; + eprintln!( + "HOST-RAM: the dma-buf mapping's buffer: {:?}; refused unpinnable {unpinnable}, pointer \ + imports {}, dma-buf imports {}, copies {}", + first.as_ref().map(|buffer| buffer.copied()), + after.host_pointer_imports_made - before.host_pointer_imports_made, + after.dma_buf_imports - before.dma_buf_imports, + after.copied_host_buffers_made - before.copied_host_buffers_made, + ); + let breaks = breaks_on_unpinnable_pages(&device); + assert_eq!(unpinnable, u64::from(breaks), "refused before the driver"); + assert!(!breaks || first.is_ok(), "the dma-buf's or a copy"); + drop(first); + a_chunk_binds(&device); + drop(mapping); +} + +/// A no-copy buffer, a no-copy heap and a buffer's rebind over pages of a dma-buf's mapping, each +/// with no gate and no source: on a driver whose failed import of such pages breaks its later ones, +/// the runtime refuses the pages before the driver sees them (`WorkCounts::host_imports_unpinnable`) +/// and each is a copy of them (`WorkCounts::copied_host_buffers_made`, for a failed import), whose +/// bytes the GPU reads; the RAM's first chunk is imported after them, and buffers bound in it +/// ([`a_chunk_binds`]). Elsewhere each is whatever the driver makes of the pages, and the chunk is +/// imported all the same. Linux only, where `/dev/udmabuf` opens. +#[cfg(target_os = "linux")] +#[test] +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 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(); + let Some(mapping) = super::copied::DmaBufMapping::new(&pattern) else { + return; + }; + let pages = |object: u64| { + let at = mapping + .pages + .as_ptr() + .wrapping_add((object * length) as usize); + // SAFETY: the mapping's pages, which outlive every object over them. + unsafe { HostMemory::new(NonNull::new(at).unwrap()) } + }; + let expected = |object: u64| &pattern[(object * length) as usize..][..length as usize]; + let (ram, start, dropped) = new_ram(); + // SAFETY: the RAM's bytes, mapped until its keep-alive goes, after every device let go. + let rebound = unsafe { + let memory = HostMemory::new(NonNull::new((start + 5 * MIB) as *mut u8).unwrap()); + device.new_buffer_with_bytes_no_copy(memory, length, ResourceOptions::default(), None) + } + .unwrap(); + let before = device.work_counts(); + // SAFETY: as above. + let made = unsafe { + device.new_buffer_with_bytes_no_copy(pages(0), length, ResourceOptions::default(), None) + }; + let descriptor = crate::HeapDescriptor::new( + crate::HeapType::Placement, + length, + ResourceOptions::default(), + ); + // SAFETY: as above. + let heap = unsafe { device.new_heap_with_bytes_no_copy(pages(1), &descriptor, None, None) }; + // SAFETY: as above; nothing uses the buffer. + let rebind = unsafe { rebound.rebind_bytes_no_copy(pages(2), None, None) }; + let after = device.work_counts(); + let counted = |of: fn(&crate::WorkCounts) -> u64| of(&after) - of(&before); + eprintln!( + "HOST-RAM: over the dma-buf mapping, no source: buffer {:?}, heap {:?}, rebind {:?}; \ + refused unpinnable {}, copies {} ({} for a failed import), heaps copied {}, rebinds \ + copied {}", + made.as_ref().map(|buffer| buffer.copied()), + heap.as_ref().map(|_| ()), + rebind, + counted(|counts| counts.host_imports_unpinnable), + counted(|counts| counts.copied_host_buffers_made), + counted(|counts| counts.copied_host_buffers_degraded), + counted(|counts| counts.copied_heaps_made), + counted(|counts| counts.copied_rebind_pages_made), + ); + let breaks = breaks_on_unpinnable_pages(&device); + assert_eq!( + counted(|counts| counts.host_imports_unpinnable), + 3 * u64::from(breaks), + "refused before the driver, each" + ); + if breaks { + let made = made.unwrap(); + let heap = heap.unwrap(); + rebind.unwrap(); + assert!(made.copied() && rebound.copied(), "copies"); + let copies = ( + counted(|counts| counts.copied_host_buffers_made), + counted(|counts| counts.copied_host_buffers_degraded), + counted(|counts| counts.copied_heaps_made), + counted(|counts| counts.copied_rebind_pages_made), + ); + assert_eq!( + copies, + (3, 3, 1, 1), + "three copies, each for a failed import" + ); + let placed = (heap.new_buffer_at_offset(length, ResourceOptions::default(), 0)).unwrap(); + assert!( + gpu_bytes(&device, &made, length) == expected(0), + "the buffer's bytes" + ); + assert!( + gpu_bytes(&device, &placed, length) == expected(1), + "the heap's bytes" + ); + assert!( + gpu_bytes(&device, &rebound, length) == expected(2), + "the rebind's bytes" + ); + drop((made, placed, heap)); + } + drop((rebound, ram)); + assert!(settles(&dropped)); + a_chunk_binds(&device); + drop(mapping); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 6a47cb24e..bd368e2c9 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -290,6 +290,7 @@ pub(crate) struct Counters { host_imports_remapped: AtomicU64, host_pointer_imports_made: AtomicU64, host_pointer_import_bytes_made: AtomicU64, + host_imports_unpinnable: AtomicU64, host_imports_refused_by_host: AtomicU64, copied_host_buffers_made: AtomicU64, copied_host_buffers_refused: AtomicU64, @@ -2013,6 +2014,12 @@ impl Counters { (self.host_pointer_import_bytes_made).fetch_add(bytes, Ordering::Relaxed); } + /// The runtime kept host pages the kernel cannot pin from the driver + /// (`Device::refuse_unpinnable`). + pub(crate) fn host_import_unpinnable(&self) { + (self.host_imports_unpinnable).fetch_add(1, Ordering::Relaxed); + } + /// The caller's import gate refused a no-copy buffer's import (`HostMemory::with_import_gate`). pub(crate) fn host_import_refused_by_host(&self) { (self.host_imports_refused_by_host).fetch_add(1, Ordering::Relaxed); @@ -4345,6 +4352,13 @@ pub struct WorkCounts { pub host_pointer_imports_made: u64, /// Their bytes: whole pages, rounded out to the import's unit. pub host_pointer_import_bytes_made: u64, + /// The imports of host pages by their pointer the runtime refused before the driver saw them, + /// because the kernel pins no page of a mapping over them (a mapping of a dma-buf), on a + /// driver whose failed import of such pages breaks its later allocations + /// (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`): no-copy objects', rebinds' and + /// guest RAM's chunks'. Such an object takes the caller's dma-bufs of the pages, or else a + /// copy of them (`copied_host_buffers_degraded`). None on every other driver, and off Linux. + pub host_imports_unpinnable: u64, /// The no-copy buffers' imports the caller's gate refused (`HostMemory::with_import_gate`): /// each made a copied host buffer instead (`copied_host_buffers_refused`). pub host_imports_refused_by_host: u64, @@ -4355,7 +4369,8 @@ pub struct WorkCounts { /// Of those, the ones made because the caller's gate refused the import. pub copied_host_buffers_refused: u64, /// Of those, the ones made because an import the device and the gate admitted failed (out - /// of memory, another Vulkan error). + /// of memory, another Vulkan error), or because the runtime refused the pages for the driver + /// and no dma-buf of them served (`host_imports_unpinnable`). pub copied_host_buffers_degraded: u64, /// Of those, the ones a rebind made because the new bytes lie at another offset in their /// page than the old, where a texture over the buffer was planned at the old offset @@ -5457,6 +5472,7 @@ impl Device { host_pointer_import_bytes_made: counters .host_pointer_import_bytes_made .load(Ordering::Relaxed), + host_imports_unpinnable: counters.host_imports_unpinnable.load(Ordering::Relaxed), host_imports_refused_by_host: counters .host_imports_refused_by_host .load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 4ab13c812..8b0d57579 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -faca8fc6a81d13b1e16caba23bb8a2197ee15157d4826c24bad0de831aa7ac8d +166b255c7193c77b160eeae8b0a21293e17e10098b140a1466f8e6255fb14803 diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index cd4059a1f..e3ee5e4b1 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 479; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1703; +pub const RUNTIME_VERSION: u32 = 1704; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 964b3fb68..e1d02a8cc 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -991,6 +991,20 @@ pub enum RuntimeDriverDefect { /// low (1023 as 0.999039). Nothing is refused: the runtime converts such a texture's planes /// with its own kernel there, as on a device without the conversion. TenBitCodesReadAsWords, + /// An import of a host pointer (`VK_EXT_external_memory_host`) over pages the kernel cannot + /// pin (a mapping of a dma-buf, `VM_PFNMAP`) fails as out of device memory, where Vulkan + /// requires `VK_ERROR_INVALID_EXTERNAL_HANDLE` of a pointer a platform restriction keeps from + /// being imported, and from then on the process's host-visible allocations fail as out of + /// device memory too, imports and plain allocations alike, on every device of the process, + /// where an out-of-memory error modifies no existing object. Nothing is refused that the + /// driver would import, and the pages are still served: on Linux the runtime asks the kernel + /// whether it pins each mapping over them before it hands the driver their pointer, and pages + /// it cannot pin are never handed to the driver. A no-copy buffer, heap or rebind over them + /// takes the caller's dma-buf source where one is given, and else, or where its import fails, + /// a copy of them, as where a pointer import fails (`copied-host-pages`); a guest RAM's chunk + /// over them is not imported, its objects taking their own paths. Pages that are not mapped + /// readable cannot be copied, and are refused (`Unsupported`, `HostMemory`). + UnpinnablePagesBreakHostMemory, } /// One device capability a refusal can name. diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 186df8ceb..92308e8b9 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2612,6 +2612,7 @@ field metal2vulkan-runtime::WorkCounts.host_imports_reimported pub host_imports_ field metal2vulkan-runtime::WorkCounts.host_imports_released pub host_imports_released: u64 field metal2vulkan-runtime::WorkCounts.host_imports_remapped pub host_imports_remapped: u64 field metal2vulkan-runtime::WorkCounts.host_imports_resident pub host_imports_resident: u64 +field metal2vulkan-runtime::WorkCounts.host_imports_unpinnable pub host_imports_unpinnable: u64 field metal2vulkan-runtime::WorkCounts.host_imports_used pub host_imports_used: u64 field metal2vulkan-runtime::WorkCounts.host_keep_alives_covered pub host_keep_alives_covered: u64 field metal2vulkan-runtime::WorkCounts.host_keep_alives_kept pub host_keep_alives_kept: u64 @@ -13222,6 +13223,7 @@ variant metal2vulkan::error::RuntimeDriverDefect::ReadsCommandBuffersAfterTheirS variant metal2vulkan::error::RuntimeDriverDefect::SetLayoutSupportUnderstated SetLayoutSupportUnderstated variant metal2vulkan::error::RuntimeDriverDefect::TenBitCodesReadAsWords TenBitCodesReadAsWords variant metal2vulkan::error::RuntimeDriverDefect::TwoPlaneChromaMisplaced TwoPlaneChromaMisplaced +variant metal2vulkan::error::RuntimeDriverDefect::UnpinnablePagesBreakHostMemory UnpinnablePagesBreakHostMemory variant metal2vulkan::error::RuntimeDriverDefect::WaitForAnyObjectLosesASignal WaitForAnyObjectLosesASignal variant metal2vulkan::error::RuntimeInput::AlphaTest AlphaTest variant metal2vulkan::error::RuntimeInput::ColorWrites ColorWrites diff --git a/docs/API.md b/docs/API.md index 314e1f317..c45c1ff0d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2508,7 +2508,10 @@ bound. the device's own, which no import maps (a heap's textures shadows of its bytes): the caller's gate (`HostMemory::with_import_gate`) refused the pages' import, or the import the device and the gate admitted failed, of the pointer or of the caller's dma-bufs (out of memory, or - another Vulkan error, such as a driver out of the mappings the host kernel allows). The gate is + another Vulkan error, such as a driver out of the mappings the host kernel allows), or the + runtime kept pages the kernel cannot pin (a dma-buf's mapping) from NVIDIA's driver, whose failed + import of them breaks it (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`), and no dma-buf + of them served. The gate is asked before the pages' write permission: pages the process maps read-only (a VMM's alias of a read-only replace) are copied as any, and the copy drops the GPU's writes, as Metal drops them: each batch's completion takes them back out of the copy and writes nothing to the pages diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index d42cf5b1f..b5be134f9 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -865,6 +865,17 @@ driver's. Each is open work. (importing the pointer) is the one NVIDIA takes for writable pages and is unaffected. A device that imports dma-bufs (RADV) is **unaudited** for the clone. +- **A pointer import of pages the kernel cannot pin on NVIDIA** (a dma-buf's mapping, `VM_PFNMAP`) + fails as out of device memory (615.71.09), where Vulkan requires + `VK_ERROR_INVALID_EXTERNAL_HANDLE`, and leaves the process's later host-visible allocations failing + (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`, the runtime's `driver_defects.rs`). The + runtime keeps such pages from that driver, asking the kernel before it hands their pointer over + (`host_memory.rs`), at a `PROCMAP_QUERY` and a one-byte `process_vm_readv` a mapping per import: + a no-copy buffer, heap or rebind over them takes its dma-buf source (whose import of a udmabuf + NVIDIA fails, above), and with none, or where its import fails, a copy of them + (`copied-host-pages`), at a copy's cost; a guest RAM's chunk over them is not imported. Which later allocations the driver fails, and for how long, is + **unaudited** past the shapes measured there. + - **Reflection after a compute descriptor reset on RADV**: `max_total_threads_per_threadgroup` answers 0 where Metal answers 96, `required_threads_per_threadgroup` `0x0x0` where Metal answers `8x6x2`, and `threadgroup_size_is_multiple_of_execution_width` false where Metal answers true diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 59209c69f..1fadc06df 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -175,6 +175,15 @@ Linux) imports a pointer through amdgpu's userptr, which takes anonymous pages o `memory-backend-memfd,share=on` guest RAM among them) with `Unsupported`, `HostMemory`. NVIDIA and lavapipe import the same memory. +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 +(`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`), so on Linux the runtime asks the kernel +first on that driver (one `PROCMAP_QUERY` and one one-byte `process_vm_readv` per mapping) and +never hands it such pages (`WorkCounts::host_imports_unpinnable`): the source is called, and with +none, or where its import fails, the object is a copy of the pages, as where an import fails +([Copied host buffers](#copied-host-buffers)). Pages not mapped readable are refused. + 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 @@ -330,7 +339,11 @@ happens where: Metal's private option bit 24 drops, a rebind whose bytes moved in their page under a texture (below), or where the device refused the pointer before it; - an import the device and the gate admitted fails, of the pointer or of the dma-bufs of the - caller's source (out of memory, another Vulkan error: `copied_host_buffers_degraded`). + caller's source (out of memory, another Vulkan error: `copied_host_buffers_degraded`); +- on NVIDIA's driver, the pages are a mapping the kernel cannot pin (a dma-buf's), which the + runtime never hands that driver (`RuntimeDriverDefect::UnpinnablePagesBreakHostMemory`, + `WorkCounts::host_imports_unpinnable`), and no dma-buf of the caller's source served them + (`copied_host_buffers_degraded`). The copy is host-visible memory of the device's own; the buffer's `contents` is still the pointer. Each commit writes into the copy every byte the CPU changed in the pages since the copy and the diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 1f899a545..24e92580e 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -158,7 +158,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; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 6: `crates/metal2vulkan-runtime/src/host_memory.rs (new, 3 sites)`, `crates/metal2vulkan-runtime/src/host_memory.rs (not_importable)` (+2) | `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` | 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 | | `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) | @@ -660,7 +660,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_ram.rs (new)` +- `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::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)`