diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 5d4ba82ee..0658a4e94 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -283,8 +283,11 @@ the record the pass is making. - A buffer descriptor's `exported_as` (`MemoryExport::OpaqueFd` or `MemoryExport::DmaBuf`) makes such a buffer of either handle type with the descriptor's other fields: `aligned_byte` lays that byte on a multiple of 256 bytes of the exported memory, and `padding_unobserved` lets textures - over it alias it with rows apart. A texture over such a buffer is a linear image made for the - memory's handle type, as Vulkan requires of an image bound in exported memory; such an image + over it alias it with rows apart. A texture over such a buffer is a linear image made for a + handle type the memory is exportable as, as Vulkan requires of an image bound in exported memory + (a block of dma-bufs is exportable as an opaque file descriptor too where the device's buffer + queries answer both together, and its image names that where the device takes no dma-buf for + it: RADV's linear images); such an image starts `UNDEFINED`, so it takes the memory in place where the device's in-place check of that exported memory passed, and a texture made before the check answered is a shadow that moves in place at a later commit (docs/HOWTO.md, section 7, says where each plane must lie). Memory the diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index b964b1c4e..fa7faf60b 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -2125,6 +2125,11 @@ impl Device { (usage, handle), ) }; + // A shared block of dma-bufs is exportable as the handle types the device exports + // together. + if let Some(export) = &dma_buf_export { + memory.export_dma_bufs_as(export.exports); + } (opaque, dma_buf_export) }; // How the device exports a timeline semaphore as an opaque file descriptor, where it diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs index 36770644c..85207832d 100644 --- a/crates/metal2vulkan-runtime/src/dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -1590,6 +1590,17 @@ impl Device { features.as_raw() )); } + let compatible = imported.external_memory_properties.compatible_handle_types; + if !compatible.contains(memory.shared_with()) { + return Err(format!( + "its image format query lists handle types {:#x} as compatible with a \ + DRM_FORMAT_MOD_LINEAR image of {:?} for {}, whose memory is exported as {:#x}", + compatible.as_raw(), + plan.format, + memory.words(), + memory.shared_with().as_raw() + )); + } Ok(limits) } } @@ -1624,14 +1635,18 @@ impl Device { /// ([`Device::dma_buf_image`]); host pages imported by their pointer, where a texture's image in /// place lays its rows out at Metal's pitch (`texture/in_place_image.rs`); or a buffer's memory of /// the runtime's own, where a texture over the buffer lays its rows out at Metal's pitch -/// (`texture.rs`'s `alias_image`): with no external memory, or exported as the handle type its -/// record names (`memory.rs`'s `Memory::bound_memory`, `exported_memory.rs`). +/// (`texture.rs`'s `alias_image`): with no external memory, or exported as the handle types its +/// record names (`memory.rs`'s `Memory::bound_memory`, `exported_memory.rs`), the image naming +/// one of them, `named` (`VUID-vkBindImageMemory-memory-02728`). #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum ModifierMemory { DmaBuf, Host, Own, - Exported(vk::ExternalMemoryHandleTypeFlags), + Exported { + named: vk::ExternalMemoryHandleTypeFlags, + exports: vk::ExternalMemoryHandleTypeFlags, + }, } impl std::fmt::Debug for ModifierMemory { @@ -1640,7 +1655,12 @@ impl std::fmt::Debug for ModifierMemory { ModifierMemory::DmaBuf => f.write_str("DmaBuf"), ModifierMemory::Host => f.write_str("Host"), ModifierMemory::Own => f.write_str("Own"), - ModifierMemory::Exported(handle) => write!(f, "Exported({:#x})", handle.as_raw()), + ModifierMemory::Exported { named, exports } => write!( + f, + "Exported({:#x} of {:#x})", + named.as_raw(), + exports.as_raw() + ), } } } @@ -1653,7 +1673,21 @@ impl ModifierMemory { ModifierMemory::DmaBuf => Some(DMA_BUF), ModifierMemory::Host => Some(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT), ModifierMemory::Own => None, - ModifierMemory::Exported(handle) => Some(handle), + ModifierMemory::Exported { named, .. } => Some(named), + } + } + + /// The handle types an image's format query must list as compatible with the one it names + /// (`VkExternalMemoryProperties::compatibleHandleTypes`): for the runtime's exported memory, + /// every type its blocks are exported as, which an image bound there shares memory with + /// (`VUID-VkExportMemoryAllocateInfo-handleTypes-09860`); none for other memory, whose + /// allocation names the image's type alone. + pub(super) fn shared_with(self) -> vk::ExternalMemoryHandleTypeFlags { + match self { + ModifierMemory::Exported { exports, .. } => exports, + ModifierMemory::DmaBuf | ModifierMemory::Host | ModifierMemory::Own => { + vk::ExternalMemoryHandleTypeFlags::empty() + } } } @@ -1663,8 +1697,13 @@ impl ModifierMemory { ModifierMemory::DmaBuf => "dma-bufs", ModifierMemory::Host => "host allocations", ModifierMemory::Own => "the runtime's own memory", - ModifierMemory::Exported(DMA_BUF) => "the runtime's memory exported as dma-bufs", - ModifierMemory::Exported(_) => { + ModifierMemory::Exported { named: DMA_BUF, .. } => { + "the runtime's memory exported as dma-bufs" + } + ModifierMemory::Exported { exports, .. } if exports.contains(DMA_BUF) => { + "the runtime's memory exported as dma-bufs, named as opaque file descriptors" + } + ModifierMemory::Exported { .. } => { "the runtime's memory exported as opaque file descriptors" } } @@ -1675,7 +1714,7 @@ impl ModifierMemory { /// for an import. pub(super) fn needs(self) -> vk::ExternalMemoryFeatureFlags { match self { - ModifierMemory::Exported(_) => vk::ExternalMemoryFeatureFlags::EXPORTABLE, + ModifierMemory::Exported { .. } => vk::ExternalMemoryFeatureFlags::EXPORTABLE, ModifierMemory::DmaBuf | ModifierMemory::Host | ModifierMemory::Own => { vk::ExternalMemoryFeatureFlags::IMPORTABLE } @@ -1688,7 +1727,7 @@ impl ModifierMemory { /// the image's own pages is its dedicated import. pub(super) fn shared_memory(self) -> bool { match self { - ModifierMemory::Host | ModifierMemory::Exported(_) => true, + ModifierMemory::Host | ModifierMemory::Exported { .. } => true, ModifierMemory::DmaBuf | ModifierMemory::Own => false, } } diff --git a/crates/metal2vulkan-runtime/src/exported_memory.rs b/crates/metal2vulkan-runtime/src/exported_memory.rs index 3d4cbed33..4ef0ed28d 100644 --- a/crates/metal2vulkan-runtime/src/exported_memory.rs +++ b/crates/metal2vulkan-runtime/src/exported_memory.rs @@ -27,7 +27,11 @@ //! or the driver prefers or requires one (`VkMemoryDedicatedRequirements`), it is the buffer's //! dedicated allocation (`VkMemoryDedicatedAllocateInfo`, `VkExportMemoryAllocateInfo`), freed //! with it. Else it lies in a block that exportable buffers of its handle type share, allocated -//! exportable (`memory.rs`'s `Holds::Exports`, `Holds::DmaBufs`), at a multiple of 256 bytes as +//! exportable (`memory.rs`'s `Holds::Exports`, `Holds::DmaBufs`): as that handle type, and a +//! block of dma-bufs as an opaque file descriptor too where the device's buffer queries answer +//! both exportable together, each compatible with the other ([`FdExport::new`]), so that an +//! image bound there may name either; the buffer's export is a dma-buf of the same memory +//! either way. It lies at a multiple of 256 bytes as //! any buffer of the runtime's memory (`buffer.rs`'s `placed`), as other buffers lie in pooled //! blocks: a block holds a 4K NV12 picture's 12.4 MB five times, and one that empties is kept //! for the next such buffers (`memory.rs`). On an RTX 5080 Laptop GPU a `Private` exportable @@ -54,7 +58,7 @@ //! buffer, whose host may read its contents at once, has it made then and waits for it alone. A //! texture over the buffer is a linear image of its memory in `GENERAL` (or a shadow of its //! bytes, which copies them), a host-accessible alias that reads what the buffer holds, made -//! for the memory's handle type, which an image bound in exported memory names +//! for a handle type the memory is exportable as, which an image bound in exported memory names //! (`VUID-vkBindImageMemory-memory-02728`), so made `UNDEFINED`, and taken where the device's //! check of that exported memory passed (`in_place.rs`, "The runtime's exported memory"); a //! shadow over a dedicated allocation, to which no image may be bound @@ -126,6 +130,33 @@ pub(super) struct FdExport { functions: ash::khr::external_memory_fd::Device, /// The device exports a buffer's memory as one only from the buffer's dedicated allocation. dedicated_only: bool, + /// The handle types a block that such buffers share is allocated exportable as + /// (`VkExportMemoryAllocateInfo`): the handle type, and for a dma-buf also an opaque file + /// descriptor where the device exports a buffer's memory as both together ([`FdExport::new`]). + pub(super) exports: vk::ExternalMemoryHandleTypeFlags, +} + +/// What `vkGetPhysicalDeviceExternalBufferProperties` answers for a buffer of `usage` exported as +/// `handle`: its external memory features and the handle types compatible with it. +/// +/// # Safety +/// +/// `physical` is a physical device of `instance`, made at Vulkan 1.1 or later. +unsafe fn buffer_export( + instance: &ash::Instance, + physical: vk::PhysicalDevice, + usage: vk::BufferUsageFlags, + handle: vk::ExternalMemoryHandleTypeFlags, +) -> vk::ExternalMemoryProperties { + let query = vk::PhysicalDeviceExternalBufferInfo::default() + .usage(usage) + .handle_type(handle); + let mut properties = vk::ExternalBufferProperties::default(); + // SAFETY: the caller's contract. + unsafe { + instance.get_physical_device_external_buffer_properties(physical, &query, &mut properties) + }; + properties.external_memory_properties } impl FdExport { @@ -134,6 +165,14 @@ impl FdExport { /// where it lacks an extension) and `vkGetPhysicalDeviceExternalBufferProperties` answers the /// handle type exportable from a buffer's memory. `None` where it lacks either. /// + /// A dma-buf's shared blocks are exportable as an opaque file descriptor too where that query + /// answers each handle type compatible with the other and an opaque file descriptor + /// exportable from a buffer's memory not only as a dedicated allocation: an image bound in such + /// a block may name either (`VUID-vkBindImageMemory-memory-02728`), and a device whose images + /// of a dma-buf's handle type take only a dedicated allocation (RADV's) binds one naming an + /// opaque file descriptor there (`texture.rs`'s `alias_unbound`). The dma-buf a buffer's export + /// answers is the same memory's either way (`vkGetMemoryFdKHR` of the dma-buf handle type). + /// /// # Safety /// /// `physical` is a physical device of `instance`, made at Vulkan 1.1 or later. @@ -145,25 +184,33 @@ impl FdExport { ) -> Option { let functions = functions?; let handle = export.handle(); - let query = vk::PhysicalDeviceExternalBufferInfo::default() - .usage(usage) - .handle_type(handle); - let mut properties = vk::ExternalBufferProperties::default(); // SAFETY: the caller's contract. - unsafe { - instance.get_physical_device_external_buffer_properties( - physical, - &query, - &mut properties, - ) - }; - let memory = properties.external_memory_properties; + let memory = unsafe { buffer_export(instance, physical, usage, handle) }; let features = memory.external_memory_features; - let exports = features.contains(vk::ExternalMemoryFeatureFlags::EXPORTABLE) + let exportable = features.contains(vk::ExternalMemoryFeatureFlags::EXPORTABLE) && memory.compatible_handle_types.contains(handle); - exports.then_some(FdExport { + if !exportable { + return None; + } + let mut exports = handle; + if export == MemoryExport::DmaBuf && memory.compatible_handle_types.contains(EXPORT_HANDLE) + { + // SAFETY: the caller's contract. + let opaque = unsafe { buffer_export(instance, physical, usage, EXPORT_HANDLE) }; + let opaque_features = opaque.external_memory_features; + if opaque_features.contains(vk::ExternalMemoryFeatureFlags::EXPORTABLE) + && !opaque_features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY) + && opaque + .compatible_handle_types + .contains(handle | EXPORT_HANDLE) + { + exports |= EXPORT_HANDLE; + } + } + Some(FdExport { functions, dedicated_only: features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY), + exports, }) } } @@ -301,8 +348,11 @@ impl Device { // SAFETY: `raw` is a live buffer of this device, at Vulkan 1.1 or later. unsafe { raw_device.get_buffer_memory_requirements2(&query, &mut requirements) }; let requirements = requirements.memory_requirements; + // A dedicated allocation is exportable as the handle type alone (no image is bound in it); + // a shared block as its pool's blocks are (`memory.rs`'s `Memory::export_dma_bufs_as`). let exported = Exported { handle, + exports: handle, dedicated: exports.dedicated_only || dedicated.prefers_dedicated_allocation == vk::TRUE || dedicated.requires_dedicated_allocation == vk::TRUE, diff --git a/crates/metal2vulkan-runtime/src/in_place.rs b/crates/metal2vulkan-runtime/src/in_place.rs index 350c6a388..f29db0167 100644 --- a/crates/metal2vulkan-runtime/src/in_place.rs +++ b/crates/metal2vulkan-runtime/src/in_place.rs @@ -86,16 +86,20 @@ //! - **The runtime's exported memory.** A texture over a buffer whose memory the runtime exports //! (`exported_memory.rs`: a block that exportable buffers of one handle type share) takes the //! device's linear image, else the `DRM_FORMAT_MOD_LINEAR` one at Metal's pitch, each made for -//! the handle type the memory's own record names (`memory.rs`'s `Memory::bound_memory`), as an -//! image bound in exported memory must name it (`VUID-vkBindImageMemory-memory-02728`): so it +//! a handle type the memory's own record names (`memory.rs`'s `Memory::bound_memory`), as an +//! image bound in exported memory must name one (`VUID-vkBindImageMemory-memory-02728`): so it //! starts `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`) whichever it is, and the same rule -//! takes it, under the check of that handle type's exported memory -//! ([`PagesClass::ExportedFd`], [`PagesClass::ExportedDmaBuf`]), moving in place once the -//! verdicts pass as over the pooled memory. Where the device's image format query -//! (`VkPhysicalDeviceExternalImageFormatInfo`) takes the handle type for no such image of the -//! texture's format, usage and tiling but with a dedicated allocation, or where the memory is -//! the buffer's dedicated allocation (`VUID-vkBindImageMemory-memory-10926`), the texture is a -//! shadow, its notice naming why. Where such an image lies is decided as for any texture over a +//! takes it, under the check of that exported memory ([`PagesClass::ExportedFd`], +//! [`PagesClass::ExportedDmaBuf`]), moving in place once the verdicts pass as over the pooled +//! memory. A block of dma-bufs exportable as an opaque file descriptor too +//! (`exported_memory.rs`'s `FdExport::new`) has its image name the dma-buf handle type, else +//! the opaque one; the check's own textures over that memory take the same image, so its +//! verdicts are of the image a texture takes. Where the device's image format query +//! (`VkPhysicalDeviceExternalImageFormatInfo`) takes none of those handle types for such an +//! image of the texture's format, usage and tiling but with a dedicated allocation, or lists +//! not every type the block is exported as among those compatible with it, or where the memory +//! is the buffer's dedicated allocation (`VUID-vkBindImageMemory-memory-10926`), the texture is +//! a shadow, its notice naming why. Where such an image lies is decided as for any texture over a //! buffer (`linear_plan::aliases`), of the image made for the handle type, for each texture (each //! plane of a picture) apart: the texels' offset in the memory (the buffer's first byte lies at //! a multiple of 256 bytes there, or its `aligned_byte` does, `BufferDescriptor::aligned_byte`; @@ -213,13 +217,17 @@ impl PagesClass { } } - /// The class of the runtime's memory exported as `handle` (`memory.rs`'s - /// `Memory::bound_memory`): `None` for a handle type the runtime exports no memory as. - pub(crate) fn exported(handle: vk::ExternalMemoryHandleTypeFlags) -> Option { - match handle { - vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD => Some(PagesClass::ExportedFd), - vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT => Some(PagesClass::ExportedDmaBuf), - _ => None, + /// The class of the runtime's memory exported as `exports` (`memory.rs`'s + /// `Memory::bound_memory`): a block of dma-bufs whatever else it is exportable as (an opaque + /// file descriptor too, `exported_memory.rs`'s `FdExport::new`), else one of opaque file + /// descriptors; `None` for memory the runtime exports as neither. + pub(crate) fn exported(exports: vk::ExternalMemoryHandleTypeFlags) -> Option { + if exports.contains(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) { + Some(PagesClass::ExportedDmaBuf) + } else if exports == vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD { + Some(PagesClass::ExportedFd) + } else { + None } } @@ -944,7 +952,7 @@ impl Drop for Waiting<'_> { /// differs, and so does the version it holds). The runtime's own version is not in the record: a /// release that changes none of these keeps the verdicts the driver gave, so a device made after /// it reads them again rather than checking anew. -pub(crate) const CHECK_VERSION: u32 = 13; +pub(crate) const CHECK_VERSION: u32 = 14; /// A record's first bytes. const MAGIC: [u8; 8] = *b"M2VINPL\0"; diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 82158720e..730b45bf0 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -1094,8 +1094,12 @@ impl NoImage { /// allocation. #[derive(Clone, Copy, PartialEq, Eq)] pub(super) struct Exported { - /// The handle type it exports. + /// The handle type it exports to the buffers' consumers, which the buffers name. pub(super) handle: vk::ExternalMemoryHandleTypeFlags, + /// Every handle type it was allocated exportable as: `handle`, and for a shared block of + /// dma-bufs an opaque file descriptor too where the device exports both together + /// ([`Memory::export_dma_bufs_as`]). An image bound in it names one of them. + pub(super) exports: vk::ExternalMemoryHandleTypeFlags, /// It is the buffer's dedicated allocation (`VkMemoryDedicatedAllocateInfo`). pub(super) dedicated: bool, } @@ -1104,6 +1108,7 @@ impl std::fmt::Debug for Exported { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Exported") .field("handle", &self.handle.as_raw()) + .field("exports", &self.exports.as_raw()) .field("dedicated", &self.dedicated) .finish() } @@ -1546,6 +1551,9 @@ pub(super) struct Memory { /// Blocks of images are allocated with `VK_MEMORY_ALLOCATE_ZERO_INITIALIZE_BIT_EXT` /// ([`Memory::zero_image_blocks`]). zero_images: bool, + /// The handle types a shared block of dma-bufs ([`Holds::DmaBufs`]) is allocated exportable + /// as ([`Memory::export_dma_bufs_as`]). + dma_buf_exports: vk::ExternalMemoryHandleTypeFlags, /// The pool a color texture's host-transfer image places in, once asked: `Some(None)` where /// the device copies no color texture on the host ([`Memory::host_copy_pool`]). host_copy_pool: Option>, @@ -1662,6 +1670,7 @@ impl Memory { binds_wait: binds_wait(driver), overflows: 0, zero_images: false, + dma_buf_exports: DMA_BUF_HANDLE, host_copy_pool: None, readying: Vec::new(), host_copy_blocks: HostCopyBlocks::default(), @@ -1685,6 +1694,13 @@ impl Memory { self.zero_images = true; } + /// Allocate every shared block of dma-bufs ([`Holds::DmaBufs`]) exportable as `exports`, the + /// dma-buf handle type among them: the device's answer for such blocks + /// (`exported_memory.rs`'s `FdExport::new`), as the device is made, before any is. + pub(super) fn export_dma_bufs_as(&mut self, exports: vk::ExternalMemoryHandleTypeFlags) { + self.dma_buf_exports = exports | DMA_BUF_HANDLE; + } + /// Share its buffers among `families`: the device's, then its staging queue's (`sharing.rs`). pub(super) fn share_buffers_among(&mut self, families: Vec) { self.buffer_families = families; @@ -2143,6 +2159,7 @@ impl Memory { device_address: self.device_address, families: self.buffer_families.clone(), zero_images: self.zero_images, + dma_buf_exports: self.dma_buf_exports, } } @@ -2552,7 +2569,7 @@ impl Memory { Some(Exported { dedicated: true, .. }) => BoundMemory::NoImage(NoImage::Dedicated), - Some(exported) => BoundMemory::External(exported.handle), + Some(exported) => BoundMemory::External(exported.exports), None if block.imported || block.pages.is_some() || block.view.is_some() => { BoundMemory::External(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT) } @@ -2635,6 +2652,8 @@ struct BlockMaker { families: Vec, /// As [`Memory`]'s. zero_images: bool, + /// As [`Memory`]'s. + dma_buf_exports: vk::ExternalMemoryHandleTypeFlags, } impl BlockMaker { @@ -2642,7 +2661,8 @@ impl BlockMaker { /// of addresses where `addressed` gives the counts of such buffers made (its memory then as /// long as that buffer requires, if longer), allocated zero-initialized where it holds images /// on a device whose blocks of images are ([`Memory::zero_image_blocks`]), and exportable as - /// the handle type of the exportable buffers it holds ([`Holds::handle`]). + /// the handle type of the exportable buffers it holds ([`Holds::handle`]; a block of dma-bufs + /// as [`Memory::export_dma_bufs_as`] says). fn make( &self, device: &ash::Device, @@ -2652,8 +2672,13 @@ impl BlockMaker { ) -> Result { let zeroed = holds == Holds::Images && self.zero_images; let export = holds.handle().map(|handle| { + let exports = match holds { + Holds::DmaBufs => self.dma_buf_exports, + _ => handle, + }; let exported = Exported { handle, + exports, dedicated: false, }; (vk::Buffer::null(), exported) @@ -2700,7 +2725,7 @@ impl BlockMaker { } let handle = export.map_or( vk::ExternalMemoryHandleTypeFlags::empty(), - |(_, exported)| exported.handle, + |(_, exported)| exported.exports, ); let mut exportable = vk::ExportMemoryAllocateInfo::default().handle_types(handle); let dedicated_to = (export.filter(|(_, exported)| exported.dedicated)) diff --git a/crates/metal2vulkan-runtime/src/tests/exported_textures.rs b/crates/metal2vulkan-runtime/src/tests/exported_textures.rs index 2cdbe7ebb..0902eff66 100644 --- a/crates/metal2vulkan-runtime/src/tests/exported_textures.rs +++ b/crates/metal2vulkan-runtime/src/tests/exported_textures.rs @@ -5,7 +5,7 @@ //! memory (`aligned_byte`), so each plane lies at a multiple of 256 there. //! //! - **The image names the memory's handle type.** Each plane's texture is an image bound in the -//! buffer's exported memory, which must name the memory's handle type +//! buffer's exported memory, which must name a handle type the memory is exportable as //! (`VUID-vkBindImageMemory-memory-02728`); the validation layer, enabled on the device, reports //! nothing ([`Watched::layer_reported_nothing`]): without the handle type it reports 02728 at the //! bind. @@ -25,9 +25,22 @@ //! (`VUID-vkBindImageMemory-memory-10926`), each texture is a shadow that reads the same bytes, //! its placement refused (`InPlaceRefusal::Placement`). //! -//! Printed (`EXPORTED-TEXTURES`): what the device exported, and for each plane its image's -//! alignment, row pitch and size as `vkGetImageMemoryRequirements` and `vkGetImageSubresourceLayout` -//! answer them, and its offset in the memory. +//! - **A dma-buf's block, its images naming an opaque file descriptor.** Where the device's +//! buffer queries (`vkGetPhysicalDeviceExternalBufferProperties`) answer a buffer's memory +//! exportable as a dma-buf and as an opaque file descriptor together, each compatible with the +//! other and the opaque one not only as a dedicated allocation, the block of dma-bufs is +//! exportable as both, and elsewhere as a dma-buf alone (the queries asked here, apart from the +//! runtime's). Where the device's image format query then takes a dma-buf's handle type for no +//! image of a plane's format in a shared block, linear or `DRM_FORMAT_MOD_LINEAR` (RADV: none +//! linear, and the other only in a dedicated allocation), the plane's image names the opaque +//! one: in place where the device's check of that memory passed, which made the same image +//! (`WorkCounts::exported_dma_buf_images_named_opaque_fd`), or a shadow of a byte the check +//! found changed, never one it made no image for. The descriptor the buffer exports is a dma-buf +//! of its memory either way. +//! +//! Printed (`EXPORTED-TEXTURES`, `EXPORTED-DMA-BUF`): what the device exported, and for each plane +//! its image's alignment, row pitch and size as `vkGetImageMemoryRequirements` and +//! `vkGetImageSubresourceLayout` answer them, and its offset in the memory. //! //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. @@ -36,6 +49,7 @@ use super::blit_holds::{Scratch, WAIT}; use super::layer_claim::Watched; use super::pending_rebind::device; use crate::error::{Error, RuntimeGap}; +use crate::memory::BoundMemory; use crate::{ BlitOption, Buffer, BufferContents, BufferDescriptor, Device, InPlaceRefusal, MemoryExport, Origin, ResourceOptions, Size, Texture, TextureDescriptor, TexturePlacement, @@ -396,3 +410,241 @@ fn an_nv12_picture_s_planes_over_exported_memory_go_in_place_naming_its_handle_t "textures over exported memory name its handle type (VUID-vkBindImageMemory-memory-02728)", ); } + +/// The dma-buf and opaque file descriptor handle types together. +const BOTH: vk::ExternalMemoryHandleTypeFlags = vk::ExternalMemoryHandleTypeFlags::from_raw( + vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT.as_raw() + | vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD.as_raw(), +); + +/// Whether `device`'s buffer queries (`vkGetPhysicalDeviceExternalBufferProperties`, of the usage +/// its buffers are made with) answer a buffer's memory exportable as a dma-buf and as an opaque +/// file descriptor together: each exportable and compatible with the other, the opaque one not +/// only as a dedicated allocation. +fn exports_both(device: &Device) -> bool { + let shared = device.shared(); + let usage = crate::buffer::usage(shared.device_address); + let query = |handle| { + let info = vk::PhysicalDeviceExternalBufferInfo::default() + .usage(usage) + .handle_type(handle); + let mut properties = vk::ExternalBufferProperties::default(); + // SAFETY: the device's physical device, of its instance at Vulkan 1.2 or later. + unsafe { + shared + .instance + .raw + .get_physical_device_external_buffer_properties( + shared.physical, + &info, + &mut properties, + ) + }; + properties.external_memory_properties + }; + let dma_buf = query(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT); + let opaque = query(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD); + let exportable = vk::ExternalMemoryFeatureFlags::EXPORTABLE; + (dma_buf.external_memory_features).contains(exportable) + && dma_buf.compatible_handle_types.contains(BOTH) + && (opaque.external_memory_features).contains(exportable) + && !(opaque.external_memory_features) + .contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY) + && opaque.compatible_handle_types.contains(BOTH) +} + +/// Whether `device`'s image format query takes a dma-buf's handle type, exportable and not only +/// as a dedicated allocation, for an image of `format` with the narrowest usage a sampled texture +/// over a buffer has (sampled, both transfers): linear, or `DRM_FORMAT_MOD_LINEAR` where the +/// device makes such images, shared among its queue families as the runtime's are. +fn dma_buf_images_shared(device: &Device, format: vk::Format) -> bool { + let shared = device.shared(); + let usage = vk::ImageUsageFlags::SAMPLED + | vk::ImageUsageFlags::TRANSFER_SRC + | vk::ImageUsageFlags::TRANSFER_DST; + let families = &shared.queue_families; + let takes = |tiling: vk::ImageTiling| { + let mut external = vk::PhysicalDeviceExternalImageFormatInfo::default() + .handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT); + let mut modifier = vk::PhysicalDeviceImageDrmFormatModifierInfoEXT::default() + .drm_format_modifier(crate::dma_buf::DRM_FORMAT_MOD_LINEAR); + modifier = match families.len() > 1 { + true => modifier + .sharing_mode(vk::SharingMode::CONCURRENT) + .queue_family_indices(families), + false => modifier.sharing_mode(vk::SharingMode::EXCLUSIVE), + }; + let mut info = vk::PhysicalDeviceImageFormatInfo2::default() + .format(format) + .ty(vk::ImageType::TYPE_2D) + .tiling(tiling) + .usage(usage) + .push_next(&mut external); + if tiling == vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT { + info = info.push_next(&mut modifier); + } + let mut answer = vk::ExternalImageFormatProperties::default(); + let mut properties = vk::ImageFormatProperties2::default().push_next(&mut answer); + // SAFETY: the device's physical device, of its instance at Vulkan 1.2 or later, which + // enables `VK_EXT_image_drm_format_modifier` where that tiling is asked; `info` and + // `properties` and their chains live for the call. + let queried = unsafe { + (shared.instance.raw).get_physical_device_image_format_properties2( + shared.physical, + &info, + &mut properties, + ) + }; + let features = answer.external_memory_properties.external_memory_features; + queried.is_ok() + && features.contains(vk::ExternalMemoryFeatureFlags::EXPORTABLE) + && !features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY) + }; + takes(vk::ImageTiling::LINEAR) + || (device.makes_modifier_images() && takes(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)) +} + +/// `plane`'s format as Vulkan names it. +fn vk_format(plane: Plane) -> vk::Format { + match plane.format { + PixelFormat::R8Unorm => vk::Format::R8_UNORM, + PixelFormat::RG8Unorm => vk::Format::R8G8_UNORM, + format => panic!("no plane of {format:?}"), + } +} + +/// Whether `fd` is a dma-buf: its `fdinfo` names the exporter of one (`exp_name`), as the kernel +/// writes for a dma-buf alone. +#[cfg(target_os = "linux")] +fn is_dma_buf(fd: &std::os::fd::OwnedFd) -> bool { + use std::os::fd::AsRawFd; + let info = std::fs::read_to_string(format!("/proc/self/fdinfo/{}", fd.as_raw_fd())).unwrap(); + info.lines().any(|line| line.starts_with("exp_name:")) +} + +#[test] +fn a_dma_buf_block_s_planes_name_an_opaque_fd_where_its_images_take_no_dma_buf_in_a_shared_block() { + let watched = Watched::default(); + let scratch = Scratch::new("exported-dma-buf-opaque"); + let device = device(&watched, &scratch.0); + let name = device.name().to_owned(); + let both = exports_both(&device); + let options = ResourceOptions::shared(); + let picture = match picture(&device, options, MemoryExport::DmaBuf) { + Ok(picture) => picture, + Err(Error::NotImplemented( + gap @ (RuntimeGap::ExportableMemory | RuntimeGap::DmaBufExport), + )) => { + eprintln!("EXPORTED-DMA-BUF on {name}: refused: {gap:?}"); + return; + } + Err(error) => panic!("{name}: {error:?}"), + }; + let exported = picture.export_memory_dma_buf().unwrap(); + #[cfg(target_os = "linux")] + assert!( + is_dma_buf(&exported.fd), + "the buffer's export is a dma-buf, whatever else its block is exportable as" + ); + let exports = match picture.bound_memory() { + BoundMemory::External(exports) => exports, + BoundMemory::NoImage(no) => { + assert!(exported.dedicated, "{no:?}"); + eprintln!("EXPORTED-DMA-BUF on {name}: a dedicated allocation, which takes no image"); + return; + } + BoundMemory::Own => panic!("{name}: the buffer's memory is not exported"), + }; + let dma_buf = vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT; + assert_eq!( + exports, + if both { BOTH } else { dma_buf }, + "{name}: the block is exportable as the device's buffer queries answer (both {both})" + ); + fill(&device, &picture); + // The first placement query starts the device's check of that memory: its answer first. + let first = descriptor(PLANES[0], options); + let _ = (picture.texture_placement(&first, PLANES[0].at, ROW)).unwrap(); + assert!(device.settle_in_place_checks(WAIT), "the check answered"); + let counts = device.work_counts(); + let (mut in_place, mut opaque) = (0, 0); + for plane in PLANES { + let shared_dma_buf = dma_buf_images_shared(&device, vk_format(plane)); + let descriptor = descriptor(plane, options); + let placement = (picture.texture_placement(&descriptor, plane.at, ROW)).unwrap(); + let texture = (picture.new_texture(&descriptor, plane.at, ROW)).unwrap(); + assert!( + read(&device, &texture, plane) == want(plane), + "{name} {plane:?}: the texels" + ); + let report = |placement: &TexturePlacement| { + eprintln!( + "EXPORTED-DMA-BUF on {name}: {:?} {}x{}: block exports {:#x}, a dma-buf image \ + in a shared block {shared_dma_buf}: {placement:?}", + plane.format, + plane.size[0], + plane.size[1], + exports.as_raw() + ); + }; + report(&placement); + if both && !shared_dma_buf { + // The image names an opaque file descriptor, which the check made too: in place, or a + // shadow of a byte the check found changed. + let changed = matches!( + placement, + TexturePlacement::Shadow(TextureShadowReason::CheckFailed { .. }) + ); + if placement != TexturePlacement::NotHostPages { + for line in (device.in_place_check_report().iter()) + .skip(crate::in_place::VERDICTS) + .filter(|line| line.starts_with("ExportedDmaBuf ")) + { + eprintln!("EXPORTED-DMA-BUF on {name}: the check: {line}"); + } + } + assert!( + placement == TexturePlacement::NotHostPages || changed, + "{name} {plane:?}: an image naming an opaque file descriptor, in place or a \ + shadow of a changed byte: {placement:?}" + ); + if placement == TexturePlacement::NotHostPages { + opaque += 1; + } + } + if placement == TexturePlacement::NotHostPages { + in_place += 1; + assert!(texture.shadow().is_none(), "{name} {plane:?}: in place"); + let [alignment, row_pitch, offset, size, at] = + image_facts(&device, &picture, &texture, plane); + eprintln!( + "EXPORTED-DMA-BUF on {name}: {:?}: in place, at {at} of the memory, alignment \ + {alignment}, row pitch {row_pitch}, offset {offset}, size {size}", + plane.format + ); + assert_eq!(at % alignment, 0); + assert_eq!((row_pitch, offset), (ROW, 0)); + } else { + assert!(texture.shadow().is_some(), "{name} {plane:?}: a shadow"); + } + } + let named = device.work_counts().exported_dma_buf_images_named_opaque_fd + - counts.exported_dma_buf_images_named_opaque_fd; + eprintln!( + "EXPORTED-DMA-BUF on {name}: {in_place} planes in place, {named} naming an opaque file \ + descriptor" + ); + // Each plane the dma-buf type takes no image of names the opaque one; one it takes may too, + // where its query of the texture's own usage refuses what the narrowest's took. + assert!( + (opaque..=in_place).contains(&named), + "{name}: {opaque} planes name an opaque file descriptor at least, {in_place} at most" + ); + if !both { + assert_eq!(named, 0, "{name}: a block exportable as a dma-buf alone"); + } + watched.layer_reported_nothing( + "images over a dma-buf block name a handle type it is exportable as \ + (VUID-vkBindImageMemory-memory-02728)", + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs index 1b5fa490b..a3bdb5b63 100644 --- a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs @@ -1439,8 +1439,13 @@ fn a_refused_linear_image_names_the_need_that_failed() { && import.contains("importable false, dedicated only true"), "{import}" ); + let opaque = vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD; + let dma_buf = vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT; let export = describe(LinearRefusal::External( - ModifierMemory::Exported(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD), + ModifierMemory::Exported { + named: opaque, + exports: opaque, + }, vk::ExternalMemoryFeatureFlags::EXPORTABLE | vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY, )); assert!( @@ -1448,6 +1453,19 @@ fn a_refused_linear_image_names_the_need_that_failed() { && export.contains("exportable true, dedicated only true"), "{export}" ); + let both = ModifierMemory::Exported { + named: opaque, + exports: opaque | dma_buf, + }; + let incompatible = describe(LinearRefusal::Incompatible(both, opaque)); + assert!( + incompatible.contains("lists handle types 0x1 as compatible") + && incompatible.contains( + "for the runtime's memory exported as dma-bufs, named as opaque file \ + descriptors, whose memory is exported as 0x201" + ), + "{incompatible}" + ); } /// The committed profiles of the devices linear images were measured on. diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 9f5c38928..739349fec 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -810,6 +810,10 @@ pub(super) enum LinearRefusal { /// type): the device's image format query takes none of that memory for such an image, or /// only a dedicated allocation (its external memory features). External(ModifierMemory, vk::ExternalMemoryFeatureFlags), + /// For the runtime's memory exported as more than one handle type: the device's image format + /// query, of the handle type the image names, lists these handle types as compatible with + /// it, not every one the memory is exported as. + Incompatible(ModifierMemory, vk::ExternalMemoryHandleTypeFlags), } impl LinearRefusal { @@ -860,6 +864,13 @@ impl LinearRefusal { features.contains(memory.needs()), features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY) ), + LinearRefusal::Incompatible(memory, compatible) => format!( + "its image format query lists handle types {:#x} as compatible with a linear \ + image of {format:?}, usage {usage:?}, for {}, whose memory is exported as {:#x}", + compatible.as_raw(), + memory.words(), + memory.shared_with().as_raw() + ), } } } @@ -886,6 +897,10 @@ type Aliased = Result<(Arc, AliasCount), (String, Option)>; struct AliasCount { /// A `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch (`WorkCounts::pooled_pitched_images`). pitched: bool, + /// It names an opaque file descriptor in a block of dma-bufs exportable as one too, whose + /// dma-buf handle type the device's image format query takes for no such image + /// (`WorkCounts::exported_dma_buf_images_named_opaque_fd`). + alternate: bool, /// Its rows (or slices) lie apart over bytes its buffer declares unobserved /// (`WorkCounts::unobserved_padding_aliases`). unobserved: bool, @@ -899,6 +914,9 @@ impl AliasCount { if self.pitched { counts.pooled_pitched_image(); } + if self.alternate { + counts.exported_dma_buf_image_named_opaque_fd(); + } if self.unobserved { counts.unobserved_padding_alias(); } @@ -2818,8 +2836,10 @@ impl Device { /// handle type (host allocations, `VK_EXT_external_memory_host`, or the runtime's memory /// exported as an opaque file descriptor or a dma-buf), where its image format query /// (`VkPhysicalDeviceExternalImageFormatInfo`) takes that memory for such an image (importable, - /// or exportable for memory the runtime exports) without a dedicated allocation; why not where - /// it does not, or makes no such image (the refusal named). + /// or exportable for memory the runtime exports) without a dedicated allocation, and lists + /// every handle type the memory is exported as among those compatible with it + /// (`ModifierMemory::shared_with`); why not where it does not, or makes no such image (the + /// refusal named). pub(super) fn external_image_limits( &self, info: &vk::ImageCreateInfo<'_>, @@ -2861,9 +2881,13 @@ impl Device { Ok(()) => { let takes = features.contains(memory.needs()) && !features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY); - match takes { - true => Ok(Ok(limits)), - false => Ok(Err(LinearRefusal::External(memory, features))), + let compatible = external.external_memory_properties.compatible_handle_types; + if !takes { + Ok(Err(LinearRefusal::External(memory, features))) + } else if !compatible.contains(memory.shared_with()) { + Ok(Err(LinearRefusal::Incompatible(memory, compatible))) + } else { + Ok(Ok(limits)) } } Err(vk::Result::ERROR_FORMAT_NOT_SUPPORTED) => { @@ -2884,50 +2908,61 @@ impl Device { /// ([`Device::pooled_pitched_image`]). The device's check of its pooled memory makes no /// linear image: it measures the pitched one. /// - In a block exported as an opaque file descriptor or a dma-buf (`exported_memory.rs`): - /// the same two images, each made for that handle type, which an image bound there must name - /// (`VUID-vkBindImageMemory-memory-02728`), and so made `UNDEFINED` - /// (`VUID-VkImageCreateInfo-pNext-01443`), whose first move may discard the bytes: where the - /// device's policy and its check of that exported memory ([`PagesClass::ExportedFd`], - /// [`PagesClass::ExportedDmaBuf`]) take each access the usage takes for texels that lie in - /// its lines as these do (a pending verdict starts the check, and the texture is a shadow - /// meanwhile), and where the device's image format query takes the handle type for the - /// image without a dedicated allocation. The check's own textures take them whatever the - /// verdicts. + /// the same two images, each made for a handle type the block is exported as, which an image + /// bound there must name one of (`VUID-vkBindImageMemory-memory-02728`), and so made + /// `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), whose first move may discard the + /// bytes: where the device's policy and its check of that exported memory + /// ([`PagesClass::ExportedFd`], [`PagesClass::ExportedDmaBuf`]) take each access the usage + /// takes for texels that lie in its lines as these do (a pending verdict starts the check, + /// and the texture is a shadow meanwhile), and where the device's image format query takes + /// the handle type for the image without a dedicated allocation, listing every type the + /// block is exported as among those compatible with it. A block of dma-bufs exportable as an + /// opaque file descriptor too (`exported_memory.rs`'s `FdExport::new`) has its image name the + /// dma-buf type where the query takes it, else the opaque one: RADV takes the dma-buf type + /// for no linear image and for a `DRM_FORMAT_MOD_LINEAR` one only in a dedicated allocation, + /// and takes the opaque one in a shared block. The check's own textures take them whatever + /// the verdicts, so its verdicts are of the image a texture names. /// - In a buffer's dedicated allocation (an exportable buffer's where the driver exports /// such memory only so, or prefers or requires it), no image /// (`VUID-vkBindImageMemory-memory-10926`). /// - /// Why not: why the linear image is not, and why the pitched image is not, its cause (a - /// refused pitch, image or placement, or the policy and the device's check), which the - /// placement query answers. + /// With whether it is the `DRM_FORMAT_MOD_LINEAR` one, and whether it names an opaque file + /// descriptor over a block of dma-bufs ([`AliasCount`]). Why not: why the linear image is not, + /// and why the pitched image is not, its cause (a refused pitch, image or placement, or the + /// policy and the device's check), which the placement query answers; over a block of + /// dma-bufs exportable as an opaque file descriptor too, each handle type's in turn. fn alias_unbound( &self, plan: &ImagePlan, texels: &Texels, usage: TextureUsage, facts: &ImageFacts<'_>, - ) -> Result, Error> { - let memory = match texels.buffer.bound_memory() { - BoundMemory::Own => ModifierMemory::Own, - BoundMemory::External(handle) => { - let Some(class) = PagesClass::exported(handle) else { + ) -> Result, Error> { + let exports = match texels.buffer.bound_memory() { + BoundMemory::Own => { + let made = + self.alias_unbound_in(plan, texels, usage, facts, ModifierMemory::Own)?; + return Ok(made.map(|(made, pitched)| (made, pitched, false))); + } + BoundMemory::External(exports) => { + let Some(class) = PagesClass::exported(exports) else { let why = format!( - "the buffer's memory is external memory of handle type {:#x}, which no \ + "the buffer's memory is external memory of handle types {:#x}, which no \ texture over a buffer of the runtime's own takes", - handle.as_raw() + exports.as_raw() ); let cause = ShadowCause::Refused(Refusal::Image, why.clone()); return Ok(Err((why, cause))); }; if let Err(cause) = self.exported_takes(class, texels, usage) { let why = format!( - "an image over {} names its handle type and starts UNDEFINED, whose first \ - move the device's check of that memory covers", + "an image over {} names a handle type it is exported as and starts \ + UNDEFINED, whose first move the device's check of that memory covers", class.words() ); return Ok(Err((why, cause))); } - ModifierMemory::Exported(handle) + exports } BoundMemory::NoImage(no) => { let cause = ShadowCause::Refused(Refusal::Placement, no.words().to_owned()); @@ -2937,6 +2972,55 @@ impl Device { ))); } }; + let dma_buf = vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT; + let opaque = vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD; + let mut refused: Option<(String, ShadowCause)> = None; + for named in [dma_buf, opaque] { + if !exports.contains(named) { + continue; + } + let memory = ModifierMemory::Exported { named, exports }; + let (linear, cause) = match self.alias_unbound_in(plan, texels, usage, facts, memory)? { + Ok((made, pitched)) => { + let alternate = named == opaque && exports.contains(dma_buf); + return Ok(Ok((made, pitched, alternate))); + } + Err(refusal) => refusal, + }; + refused = Some(match refused { + None => (linear, cause), + Some((first, first_cause)) => { + let cause = match first_cause { + ShadowCause::Refused(refusal, why) => ShadowCause::Refused( + refusal, + format!( + "{why}; and naming an opaque file descriptor, {}", + cause.words() + ), + ), + first_cause => first_cause, + }; + let why = format!("{first}; and naming an opaque file descriptor, {linear}"); + (why, cause) + } + }); + } + Ok(Err(refused.ok_or_else(|| { + internal("the runtime's exported memory names no handle type an image takes") + })?)) + } + + /// [`alias_unbound`](Self::alias_unbound)'s image over `texels` made for `memory` (the + /// runtime's own of no export, or exported, the image naming one handle type it is exported + /// as), with whether it is the `DRM_FORMAT_MOD_LINEAR` one; why not. + fn alias_unbound_in( + &self, + plan: &ImagePlan, + texels: &Texels, + usage: TextureUsage, + facts: &ImageFacts<'_>, + memory: ModifierMemory, + ) -> Result, Error> { let (_, buffer_offset, type_index) = texels.buffer.memory(); let memory_offset = buffer_offset + texels.layout.offset; let raw_device = self.shared().vk(); @@ -3050,7 +3134,7 @@ impl Device { facts: &ImageFacts<'_>, ) -> Result, Error> { Ok(match self.alias_unbound(plan, texels, usage, facts)? { - Ok((made, _)) => { + Ok((made, ..)) => { // SAFETY: the image is live and unbound, and no command uses it. unsafe { release::object(self.shared().vk(), made.raw) }; Ok(()) @@ -3165,7 +3249,7 @@ impl Device { let (memory, buffer_offset, _) = texels.buffer.memory(); let memory_offset = buffer_offset + texels.layout.offset; let raw_device = self.shared().vk(); - let (made, pitched) = match self.alias_unbound(&plan, texels, usage, facts)? { + let (made, pitched, alternate) = match self.alias_unbound(&plan, texels, usage, facts)? { Ok(made) => made, Err((linear, cause)) => { let why = format!("{linear}; and {}", cause.words()); @@ -3221,6 +3305,7 @@ impl Device { *lock(&image.first_move) = Some(first); let count = AliasCount { pitched, + alternate, unobserved: texels.buffer.padding_unobserved() && texels.layout.padded(), feedback: (image.plan().usage).contains(ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT), }; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 30529b19e..b46b5b41e 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -505,6 +505,7 @@ pub(crate) struct Counters { feedback_loop_alias_images: AtomicU64, unobserved_padding_aliases: AtomicU64, pooled_pitched_images: AtomicU64, + exported_dma_buf_images_named_opaque_fd: AtomicU64, pooled_textures_moved_in_place: AtomicU64, pooled_texture_shadows_freed_after_move: AtomicU64, feedback_loop_shadow_images: AtomicU64, @@ -3876,6 +3877,13 @@ impl Counters { self.pooled_pitched_images.fetch_add(1, Ordering::Relaxed); } + /// The device made an image aliasing a buffer's bytes in a block of dma-bufs that names an + /// opaque file descriptor, which the block is exportable as too, where its image format query + /// takes the dma-buf handle type for no such image (`texture.rs`'s `alias_unbound`). + pub(crate) fn exported_dma_buf_image_named_opaque_fd(&self) { + (self.exported_dma_buf_images_named_opaque_fd).fetch_add(1, Ordering::Relaxed); + } + /// A shadow over a buffer of the device's pooled memory made before that class's in-place /// verdicts moved to its image at Metal's pitch once they passed /// (`texture/storage_form.rs`). @@ -7424,6 +7432,15 @@ pub struct WorkCounts { /// host pages); without one the texture is a shadow (`shadowed_textures`). One per image made. /// A runtime extension: Metal has none. pub pooled_pitched_images: u64, + /// Images aliasing a buffer of the runtime's memory exported as dma-bufs + /// (`MemoryExport::DmaBuf`) that name an opaque file descriptor, as an image bound in memory + /// exportable as both may (`VUID-vkBindImageMemory-memory-02728`): made where the device + /// exports such a buffer's shared blocks as both handle types together, and its image format + /// query takes the dma-buf type for no such image but in a dedicated allocation (RADV) and + /// takes the opaque one in a shared block. Counted where the image is made, in place or as a + /// shadow's move; each is in place, not a shadow. The dma-buf the buffer exports is the same + /// memory's. A runtime extension: Metal has none. + pub exported_dma_buf_images_named_opaque_fd: u64, /// Textures over a buffer of the device's pooled memory made shadows before the device's /// check of that memory had answered (`TexturePlacement::Pending` as they were made, counted /// in `shadowed_textures`) that moved to their `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch @@ -8475,6 +8492,9 @@ impl Device { feedback_loop_alias_images: counters.feedback_loop_alias_images.load(Ordering::Relaxed), unobserved_padding_aliases: counters.unobserved_padding_aliases.load(Ordering::Relaxed), pooled_pitched_images: counters.pooled_pitched_images.load(Ordering::Relaxed), + exported_dma_buf_images_named_opaque_fd: (counters + .exported_dma_buf_images_named_opaque_fd) + .load(Ordering::Relaxed), pooled_textures_moved_in_place: (counters.pooled_textures_moved_in_place) .load(Ordering::Relaxed), pooled_texture_shadows_freed_after_move: (counters diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 91a8a3a3b..e000cd8a5 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2739,6 +2739,7 @@ field metal2vulkan-runtime::WorkCounts.encoder_primaries_begun_ahead pub encoder field metal2vulkan-runtime::WorkCounts.encoders_reencoded pub encoders_reencoded: u64 field metal2vulkan-runtime::WorkCounts.event_signals_behind_merge pub event_signals_behind_merge: u64 field metal2vulkan-runtime::WorkCounts.event_waits_met pub event_waits_met: u64 +field metal2vulkan-runtime::WorkCounts.exported_dma_buf_images_named_opaque_fd pub exported_dma_buf_images_named_opaque_fd: u64 field metal2vulkan-runtime::WorkCounts.feedback_loop_alias_images pub feedback_loop_alias_images: u64 field metal2vulkan-runtime::WorkCounts.feedback_loop_shadow_images pub feedback_loop_shadow_images: u64 field metal2vulkan-runtime::WorkCounts.fence_waits pub fence_waits: u64 diff --git a/docs/API.md b/docs/API.md index c30e970c4..6a409022e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1657,10 +1657,16 @@ bound. pending, failed or unchecked, as over host pages, a pending one moving to the image once the verdict passes, at a quiet commit, with no copy (`WorkCounts::pooled_textures_moved_in_place`); over memory the runtime exports (`MemoryExport`, a runtime extension), where either image names - the memory's handle type as Vulkan requires and so starts `UNDEFINED`, its check of that exported - memory has not passed for the texture's accesses (a pending one moving the same way), the - device's image format query takes the handle type for no such image but in a dedicated - allocation, or the memory is the buffer's dedicated allocation, to which no image may be bound; + a handle type the memory is exportable as, as Vulkan requires, and so starts `UNDEFINED`: its + check of that exported memory has not passed for the texture's accesses (a pending one moving + the same way), the device's image format query takes none of those handle types for such an + image but in a dedicated allocation, or lists not every one the memory is exportable as among + those compatible with it, or the memory is the buffer's dedicated allocation, to which no image + may be bound (a block of dma-bufs is exportable as an opaque file descriptor too where the + device's buffer queries answer both together, each compatible with the other, and its image then + names the opaque handle type where the query takes no dma-buf for it, as RADV's does for linear + images, `WorkCounts::exported_dma_buf_images_named_opaque_fd`; the buffer's export stays a dma-buf + of the same memory); for one that renders, whose rows each to its pitch share no line with bytes past them, the check of renders that lets the rows' padding change, as the declaration does, and no byte past the last row's pitch); past a bound in bytes of its rows to their diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 39b21a402..c47d6ed6f 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -812,14 +812,16 @@ let exported = frame.export_memory_dma_buf()?; // plane at `exported.offset` plus its offset in the frame, DRM_FORMAT_MOD_LINEAR. ``` -A texture over a plane of the frame is an image of the exported memory in place, made for the -export's handle type (`VkExternalMemoryImageCreateInfo`, as Vulkan requires of an image bound in -exported memory), where all of these hold for the plane's linear image (its format, extent and -usage, that handle type; the plain linear image first, else a `DRM_FORMAT_MOD_LINEAR` one): +A texture over a plane of the frame is an image of the exported memory in place, made for a +handle type the memory is exportable as (`VkExternalMemoryImageCreateInfo`, as Vulkan requires of +an image bound in exported memory), where all of these hold for the plane's linear image (its +format, extent and usage, that handle type; the plain linear image first, else a +`DRM_FORMAT_MOD_LINEAR` one): - the image format query (`vkGetPhysicalDeviceImageFormatProperties2` with `VkPhysicalDeviceExternalImageFormatInfo`) takes the handle type for it, and not in a dedicated - allocation alone; + allocation alone, and lists every handle type the memory is exportable as among those + compatible with it; - the plane's byte in the memory, `exported.offset` plus the plane's offset in the frame, is a multiple of the `alignment` `vkGetImageMemoryRequirements` answers for the image; - `vkGetImageSubresourceLayout` answers `offset` 0 and a `rowPitch` equal to the plane's row @@ -828,6 +830,17 @@ usage, that handle type; the plain linear image first, else a `DRM_FORMAT_MOD_LI the texture's access (a texture made before the check answered is a shadow that moves in place at a later commit). +Dma-buf-exportable buffers that share a block share one allocated exportable as a dma-buf, and as +an opaque file descriptor too where `vkGetPhysicalDeviceExternalBufferProperties` answers both +exportable for the runtime's buffers, each compatible with the other, the opaque one not only in a +dedicated allocation. A plane's image there names the dma-buf handle type where the format query +takes it as above, else the opaque one where the query takes that. RADV takes the dma-buf handle +type for no plain linear image and for a `DRM_FORMAT_MOD_LINEAR` image only in a dedicated +allocation, so its planes over such a block name the opaque one +(`WorkCounts::exported_dma_buf_images_named_opaque_fd`). `export_memory_dma_buf` answers a dma-buf +of the same memory whatever else the block is exportable as, and the device's check of that memory +makes the image a texture there makes. + Elsewhere the texture is a shadow, announced with its cause: the memory is the buffer's dedicated allocation (Vulkan binds no image in memory dedicated to a buffer), the format query refuses the handle type, the layout differs, or the check did not pass. Measured for a 3840x2160 NV12 frame