From d5a75b7b4b78d892f7c273687aaeaae75da0cd5a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 11 Nov 2026 12:27:52 -0800 Subject: [PATCH] dma-buf: split a source into chunks only where a sparse buffer takes every type a plain one imports as dma_buf_cycles_several_imports failed on the RTX 5080 Laptop GPU (NVIDIA 615.71.09, round job m3-max-16620 at 600b535875) with "the chunks imported left: 0 right: 800". The device asked for a split (a granule of 65536 bytes, 4 chunks a buffer), yet it made no sparse buffer and imported no chunk. Every buffer fell back to a copy of its pages. The test's line said "the device binds no sparse buffer over dma-bufs", which was wrong: a split had been asked for. The granule was chosen from the sparse buffer's alignment alone. A dma-buf's memory types are known only once its source has made it, so the split has to be safe for any type an import may be of. Device::sparse_granule now asks for the memory requirements of a sparse buffer and of a plain one, both made for dma-bufs. It splits only where the sparse buffer takes every importable type (Memory::dma_buf_importable: allocatable, not protected, not lazily allocated) that the plain buffer takes. There, wherever one chunk of the pages imports as a type the plain buffer takes, each of several chunks imports as that type, which the sparse buffer takes too. Elsewhere the granule is the request's length: one chunk, one plain buffer's import. The buffer-making step moves into dma_buf_buffer_requirements, which serves both buffers. importable_types is split out of dma_buf_candidates so that both use the same rule. The test now says whether the device asked for a split. It checks that every request asked alike, that each cycle made a sparse buffer where it split and none where it did not, and, as before, that every chunk was imported. Verified: with the change, NVIDIA 620.70.06 asks for no split and imports every buffer whole on the RTX 3090 (potluck m3-max-16941) and the RTX 2080 (m3-max-16901): 20 cycles, 20 imports. RADV on the 780M (Mesa 26.2.6) keeps its split (m3-max-16942): a granule of 65536 bytes, 4 chunks a buffer, 20 sparse buffers. --- crates/metal2vulkan-runtime/src/dma_buf.rs | 80 +++++++++++++------ crates/metal2vulkan-runtime/src/memory.rs | 33 +++++--- .../src/tests/dma_buf_import_cycles.rs | 28 ++++--- 3 files changed, 96 insertions(+), 45 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs index ec0439ff3..c5c5f4b8c 100644 --- a/crates/metal2vulkan-runtime/src/dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -26,11 +26,13 @@ //! (`device/submit.rs`): the call does not wait for it, which would wait behind that queue's //! work in flight; every later submission on every queue waits for it until it completed, and //! the buffer's release does where none did. The granule is the alignment of such a buffer -//! where the device has `sparseBinding`, its queue family binds sparse memory and it imports -//! dma-bufs for such a buffer (64 KiB on RADV of Mesa 26.2.4, 4 KiB on 26.0.8); elsewhere the -//! request's length, so that exactly one chunk is taken (NVIDIA's sparse buffers take no type -//! its dma-bufs import as; it imports the pointer anyway). The padding past the pages lies -//! inside the `VkBuffer` but past the bytes a copy or a binding reaches. +//! where the device has `sparseBinding`, its queue family binds sparse memory, it imports +//! dma-bufs for such a buffer, and such a buffer takes every memory type a plain one made for +//! dma-bufs takes (64 KiB on RADV of Mesa 26.2.4, 4 KiB on 26.0.8); elsewhere the request's +//! length, so that exactly one chunk is taken: a split never asks for chunks that import as no +//! type the buffer takes where one chunk would import (NVIDIA's sparse buffers take none of the +//! types its dma-bufs of host pages import as, `Device::sparse_granule`). The padding past the +//! pages lies inside the `VkBuffer` but past the bytes a copy or a binding reaches. //! - **The bytes.** The runtime never maps a dma-buf: `contents` stays the caller's pointer, and //! the CPU's writes through it and the GPU's through the imports meet in the same pages with no //! flush or invalidate (the types are host-coherent). @@ -1012,10 +1014,18 @@ impl Device { } /// The granule a dma-buf source's chunks split at, where the device assembles a buffer of - /// several: it has `sparseBinding`, its queue family binds sparse memory, and it imports - /// dma-bufs for a sparse buffer without a dedicated allocation; then the alignment of such a - /// buffer (of the host page), rounded up to the host page. `None` elsewhere. Asked of the - /// device once ([`Importer::sparse_granule`]). + /// several: it has `sparseBinding`, its queue family binds sparse memory, it imports + /// dma-bufs for a sparse buffer without a dedicated allocation, and such a buffer takes every + /// memory type a plain buffer made for dma-bufs takes that an import may be of + /// (`Memory::dma_buf_importable`); then the alignment of such a buffer (of the host page), + /// rounded up to the host page. `None` elsewhere, so that a request is one chunk. A dma-buf's + /// own types are known only from its descriptor, once the source made it, so the split asks + /// for none it may not import whole: wherever one chunk of the pages imports as a type the + /// plain buffer takes, each of several chunks imports as that type, which the sparse buffer + /// takes too. NVIDIA's sparse buffers take none of the types its dma-bufs of host pages import + /// as (dma-buf imports otherwise work there): split, the chunks imported as no type the buffer + /// took, and the buffer was a copy of the pages where one chunk imports. Asked of the device + /// once ([`Importer::sparse_granule`]). fn sparse_granule(&self, importer: &Importer) -> Option { *importer.sparse_granule.get_or_init(|| { let shared = self.shared(); @@ -1023,22 +1033,14 @@ impl Device { if !shared.sparse.binds() || !self.imports_dma_buf_buffers(flags) { return None; } - let raw_device = shared.vk(); - let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(DMA_BUF); - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .flags(flags) - .size(importer.page) - .usage(usage(shared.device_address)) - .push_next(&mut external), - ); - // SAFETY: the device is live, has `sparseBinding`, and `info` and its chain are valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.ok()?; - shared.counts.buffer_made(info.usage); - // SAFETY: `raw` is a live buffer of this device. - let alignment = unsafe { raw_device.get_buffer_memory_requirements(raw) }.alignment; - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; + let sparse = self.dma_buf_buffer_requirements(importer.page, flags)?; + let plain = + self.dma_buf_buffer_requirements(importer.page, vk::BufferCreateFlags::empty())?; + let importable = lock(&shared.memory).dma_buf_importable(); + if plain.memory_type_bits & importable & !sparse.memory_type_bits != 0 { + return None; + } + let alignment = sparse.alignment; alignment .max(1) .checked_next_multiple_of(importer.page) @@ -1046,6 +1048,34 @@ impl Device { }) } + /// The memory requirements of a buffer of `bytes` made for dma-bufs with `flags` (a sparse one + /// only where the device has `sparseBinding`); `None` where the driver refuses to make it. + fn dma_buf_buffer_requirements( + &self, + bytes: u64, + flags: vk::BufferCreateFlags, + ) -> Option { + let shared = self.shared(); + let raw_device = shared.vk(); + let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(DMA_BUF); + let info = shared.sharing().buffer( + vk::BufferCreateInfo::default() + .flags(flags) + .size(bytes) + .usage(usage(shared.device_address)) + .push_next(&mut external), + ); + // SAFETY: the device is live, has `sparseBinding` where `flags` asks for a sparse + // buffer (the caller's), and `info` and its chain are valid. + let raw = unsafe { crate::creation::buffer(raw_device, &info) }.ok()?; + shared.counts.buffer_made(info.usage); + // SAFETY: `raw` is a live buffer of this device. + let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; + // SAFETY: the buffer is unused. + unsafe { release::object(raw_device, raw) }; + Some(requirements) + } + /// 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 (`PointerImport::new`). diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 57d056d97..0cfc67013 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -906,23 +906,29 @@ pub(super) fn dma_buf_candidates( class: MemoryClass, unified: bool, ) -> Vec { - use vk::MemoryPropertyFlags as P; let mut ranked = candidates(types, allowed, class, unified); - let others: Vec = (types.iter().enumerate()) - .filter(|&(index, ty)| { - allowed & (1 << index) != 0 - && allocatable(ty.property_flags) - && !ty - .property_flags - .intersects(P::PROTECTED | P::LAZILY_ALLOCATED) - && !ranked.contains(&(index as u32)) - }) - .map(|(index, _)| index as u32) + let importable = importable_types(types); + let others: Vec = (0..types.len() as u32) + .filter(|&index| allowed & importable & (1 << index) != 0 && !ranked.contains(&index)) .collect(); ranked.extend(others); ranked } +/// The memory types a dma-buf may be imported as, as bits ([`dma_buf_candidates`]): every +/// allocatable type that is neither protected nor lazily allocated. +fn importable_types(types: &[vk::MemoryType]) -> u32 { + use vk::MemoryPropertyFlags as P; + (types.iter().enumerate()) + .filter(|(_, ty)| { + allocatable(ty.property_flags) + && !ty + .property_flags + .intersects(P::PROTECTED | P::LAZILY_ALLOCATED) + }) + .fold(0, |bits, (index, _)| bits | 1 << index) +} + /// Where a device's memory may lie ([`Memory::type_view`]), for the crate's device tests. #[cfg(all(test, any(m2v_cpu_icd, all(m2v_gpu, m2v_gpu_hazards))))] pub(super) struct TypeView { @@ -2921,6 +2927,11 @@ impl Memory { true } + /// The memory types a dma-buf may be imported as, as bits ([`dma_buf_candidates`]). + pub(super) fn dma_buf_importable(&self) -> u32 { + importable_types(&self.types) + } + /// The memory types of `class` among those `allowed` names, as bits. pub(super) fn class_types(&self, allowed: u32, class: MemoryClass) -> u32 { class_types(&self.types, allowed, class, self.unified) diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs index 5d2c2d344..18ce3fae6 100644 --- a/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs @@ -11,8 +11,10 @@ //! copy, waited for, released. //! - **several imports**: a no-copy buffer bound sparsely over several dma-buf imports, one per //! granule of the device's sparse buffers (`dma_buf.rs`'s `chunks_buffer`), the same use. Where -//! the device binds no such buffer (no `sparseBinding`, or none of its dma-buf imports for a -//! sparse buffer) each request takes one chunk: the line says so. +//! the device asks for no split (no `sparseBinding`, no dma-buf import for a sparse buffer, or +//! a sparse buffer that takes fewer memory types than a plain one: `Device::sparse_granule`) +//! each request's granule is its length and takes one chunk, one plain buffer's import: the +//! line says so. Either way every chunk is imported, none left to a copy. //! - **an image's import**: a 64x64 `RGBA8Unorm` texture that only reads, over a no-copy buffer //! made once for all the cycles, in place: its `DRM_FORMAT_MOD_LINEAR` image bound to a //! dedicated import of a dma-buf of its own pages; read by one GPU copy, waited for, released. @@ -501,17 +503,25 @@ fn dma_buf_cycles_several_imports() { let asked = asked.lock().unwrap(); let (granule, chunks) = asked.first().copied().unwrap_or_default(); let sparse = after.sparse - before.sparse; - let what = match sparse { - 0 => format!( - "the device binds no sparse buffer over dma-bufs: each request's granule is its \ - length ({granule} bytes), one chunk" + let what = match granule { + LENGTH => format!( + "the device asks for no split: each request's granule is its length ({granule} \ + bytes), one chunk" ), - _ => format!("{chunks} chunks of {granule} bytes a buffer"), + _ => format!("each request's granule {granule} bytes: {chunks} chunks a buffer"), }; report(&device, WAY, cycles, (before, after), &what); assert!( - sparse == 0 || (sparse == cycles as u64 && chunks > 1), - "{TEST}: {WAY}: a sparse buffer of several chunks a cycle" + asked.iter().all(|&ask| ask == (granule, chunks)), + "{TEST}: {WAY}: every request alike" + ); + assert_eq!( + sparse, + match chunks { + 1 => 0, + _ => cycles as u64, + }, + "{TEST}: {WAY}: a sparse buffer a cycle where it split, else none" ); assert_eq!( after.made - before.made,