diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 0540a548a..379eab916 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -37,7 +37,9 @@ use super::host_memory::{HeldBack, KeepAlive, Release}; use super::host_ram::RamOnDevice; #[cfg(unix)] use super::host_residency::{Again, Residency}; -use super::memory::{BoundMemory, Mapped, MemoryClass, Placement, BLOCK_BYTES}; +use super::memory::{ + BoundMemory, Holds, Mapped, MemoryClass, Placement, BLOCK_BYTES, EXPORT_HANDLE, +}; use super::program_objects::ProgramObject; use super::rebind::{ImportHold, Unexact}; use super::recycle::{self, BufferMaking}; @@ -2311,6 +2313,28 @@ impl Device { Ok(buffer) } + /// A `Shared` buffer of `length` bytes, all zero, outside the Metal address space, in a + /// block of the runtime's pooled memory that is exported as no handle type, whatever kind of + /// block the device's own buffers take (`memory.rs`'s `Holds::FdBuffers`): the in-place + /// check's class of pooled memory (`in_place_check.rs`, `PagesClass::Pooled`), whose image + /// names no handle type. Refused as [`Device::new_buffer`] refuses its length. + pub(super) fn pooled_check_buffer(&self, length: u64) -> Result { + const CALL: &str = "new_buffer"; + let modes = Modes::of(ResourceOptions::shared())?; + let class = buffer_class(CALL, modes)?; + if length == 0 || length > self.properties().max_buffer_length { + return Err(nil(CALL, Problem::BufferLength { length })); + } + let placed = (AddressPlacement::Outside.into(), None); + self.zeroed_buffer_of( + CALL, + length, + (modes, class), + NewBufferOf::PlainBlock, + placed, + ) + } + /// A `Private` buffer of `length` bytes that the runtime makes for its own use and whose /// bytes hold no value before the GPU writes them: made without a submission, so that one of /// the runtime's sections, a host step's replay of an emulated mesh draw among them, makes @@ -2388,7 +2412,9 @@ impl Device { let (of_heap, fresh) = match of { NewBufferOf::Heap => (true, FreshPages::WherePaid), NewBufferOf::Runtime(fresh) => (false, fresh), + NewBufferOf::PlainBlock => (false, FreshPages::WherePaid), }; + let plain = of == NewBufferOf::PlainBlock; if self.is_lost() { return Err(self.lost_refusal()); } @@ -2413,26 +2439,42 @@ impl Device { Some(_) => MemoryClass::Private, None => class, }; + // The kind of block it lies in: one of the runtime's own lies where the device's own + // buffers do, whose blocks may be exportable as an opaque file descriptor, so that its + // `VkBuffer` names that handle type there (`VUID-vkBindBufferMemory-memory-02726`; + // `memory.rs`'s `Holds::FdBuffers`). + let holds = match of { + NewBufferOf::Runtime(_) => lock(&shared.memory).own_buffers(), + NewBufferOf::Heap | NewBufferOf::PlainBlock => Holds::Buffers, + }; + let mut external = + vk::ExternalMemoryBufferCreateInfo::default().handle_types(EXPORT_HANDLE); // Its device address is its block's (`place_buffer_with`). - let info = shared.sharing().buffer( + let mut info = shared.sharing().buffer( vk::BufferCreateInfo::default() .size(size) .usage(usage(false)), ); + if holds == Holds::FdBuffers { + info = info.push_next(&mut external); + } // A heap's own buffer lies where its textures can too, and is never parked. A long // host-visible one of the runtime's own lies in fresh pages where the device takes them // and its check found a held import adds nothing to its submissions (`fresh_pages.rs`). + // The in-place check's buffer of pooled memory lies in neither. let wants_fresh = !of_heap + && !plain && lead == 0 && fresh_pages::takes_fresh_pages(size, class) && shared.host_import.is_ok() && (fresh == FreshPages::Wherever || self.fresh_pages_pay_now()); - let making = - (!of_heap && lead == 0 && fresh == FreshPages::WherePaid).then_some(BufferMaking { + let making = (!of_heap && !plain && lead == 0 && fresh == FreshPages::WherePaid).then_some( + BufferMaking { size, class, fresh_pages: wants_fresh, - }); + }, + ); let mut taken = making.and_then(|making| self.recycled_buffer(&making)); let fresh = match (&taken, wants_fresh) { (None, true) => self.fresh_page_buffer(size, class)?, @@ -2479,7 +2521,7 @@ impl Device { let placed = if of_heap { self.place_heap_buffer(raw, length, class, placement) } else { - self.place_buffer(raw, length, class, placement) + self.place_buffer_in(raw, length, (class, holds), placement) }; match placed { Ok(placed) => { @@ -2637,7 +2679,7 @@ impl Device { raw, requirements, required.size, - MemoryClass::Private, + (MemoryClass::Private, Holds::Buffers), AddressPlacement::Outside.into(), false, ); @@ -2902,10 +2944,22 @@ impl Device { length: u64, class: MemoryClass, at: Place, + ) -> Result<(Placement, (GpuAddress, Held)), Error> { + self.place_buffer_in(raw, length, (class, Holds::Buffers), at) + } + + /// [`place_buffer`](Device::place_buffer) in a block that holds `holds`: `Holds::Buffers`, or + /// `Holds::FdBuffers` for a buffer made for `EXPORT_HANDLE` (`memory.rs`). + fn place_buffer_in( + &self, + raw: vk::Buffer, + length: u64, + (class, holds): (MemoryClass, Holds), + at: Place, ) -> Result<(Placement, (GpuAddress, Held)), Error> { // SAFETY: `raw` is a live buffer of this device. let requirements = unsafe { self.shared().vk().get_buffer_memory_requirements(raw) }; - self.place_buffer_with(raw, requirements, length, class, at, true) + self.place_buffer_with(raw, requirements, length, (class, holds), at, true) } /// [`place_buffer`](Device::place_buffer) for a heap's own buffer: where the heap's textures @@ -2920,19 +2974,20 @@ impl Device { // SAFETY: `raw` is a live buffer of this device. let own = unsafe { self.shared().vk().get_buffer_memory_requirements(raw) }; let requirements = self.heap_requirements(own, class)?; - self.place_buffer_with(raw, requirements, length, class, at, true) + self.place_buffer_with(raw, requirements, length, (class, Holds::Buffers), at, true) } /// [`place_buffer`](Device::place_buffer) in memory that meets `requirements`, which hold - /// the buffer's own. Where `block_address`, `raw` was made without the device-address usage - /// and its device address is its block's (`memory::allocate_addressed`, the placement's - /// `address`); else its own, where it has the usage. + /// the buffer's own, in a block that holds `holds` ([`Device::place_buffer_in`]). Where + /// `block_address`, `raw` was made without the device-address usage and its device address + /// is its block's (`memory::allocate_addressed`, the placement's `address`); else its own, + /// where it has the usage. fn place_buffer_with( &self, raw: vk::Buffer, requirements: vk::MemoryRequirements, length: u64, - class: MemoryClass, + (class, holds): (MemoryClass, Holds), at: Place, block_address: bool, ) -> Result<(Placement, (GpuAddress, Held)), Error> { @@ -2940,15 +2995,15 @@ impl Device { let raw_device = shared.vk(); let requirements = placed(requirements); let placement = if block_address { - crate::memory::allocate_addressed( + crate::memory::allocate_addressed_in( &shared.memory, raw_device, &requirements, - class, + (class, holds), &shared.counts, )? } else { - crate::memory::allocate(&shared.memory, raw_device, &requirements, class)? + crate::memory::allocate_in(&shared.memory, raw_device, &requirements, class, holds)? }; // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. let bound = unsafe { @@ -2971,14 +3026,19 @@ impl Device { } } -/// Whose a buffer [`Device::placed_new_buffer`] makes is: a heap's own buffer, or one of the -/// runtime's own, with where it lies in fresh pages. +/// Whose a buffer [`Device::placed_new_buffer`] makes is: a heap's own buffer, one of the +/// runtime's own, with where it lies in fresh pages, or the in-place check's of pooled memory. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum NewBufferOf { - /// A heap's own buffer (`heap.rs`), never in fresh pages. + /// A heap's own buffer (`heap.rs`), never in fresh pages, in a block of `Holds::Buffers`. Heap, - /// A buffer of the runtime's own, in fresh pages where it says. + /// A buffer of the runtime's own, in fresh pages where it says, else in a block of the kind + /// the device's own buffers take (`memory.rs`'s `Memory::own_buffers`). Runtime(FreshPages), + /// The in-place check's buffer of the runtime's pooled memory (`in_place_check.rs`, + /// `PagesClass::Pooled`): in a block of `Holds::Buffers`, whose memory is exported as no + /// handle type, never in fresh pages and never parked. + PlainBlock, } /// Where [`Device::placed_new_buffer`] lays a long host-visible buffer of the runtime's own in diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 7681dbabf..9ec8176b9 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -2132,6 +2132,41 @@ impl Device { (usage, handle), ) }; + // The device's own buffers lie in blocks exportable as opaque file descriptors, never + // exported, where it exports such a descriptor of a pooled buffer's memory for the + // usage of those buffers and of a buffer of addresses (`memory.rs`'s "Buffers in + // exportable blocks"). + let exports = match &functions { + None => Err("the device enables no VK_KHR_external_memory_fd"), + Some(_) => { + let usages = [ + Some(super::buffer::usage(false)), + device_address.then(|| usage), + ]; + let pooled = usages.into_iter().flatten().all(|usage| { + // SAFETY: as above. + let export = unsafe { + crate::exported_memory::FdExport::new( + &instance.raw, + physical, + functions.clone(), + (usage, handle), + ) + }; + export.is_some_and(|export| export.pooled()) + }); + match pooled { + true => Ok(()), + false => Err("the device exports an opaque file descriptor of no pooled \ + buffer's memory of the runtime's usages"), + } + } + }; + memory.fd_buffer_blocks(crate::memory::fd_buffer_types( + &memory_properties, + properties.has_unified_memory, + exports, + )); // As a dma-buf where it enables the route's extensions, which name // `VK_KHR_external_memory_fd`, and the foreign family its acquire names. let dma_buf_functions = functions.filter(|_| dma_buf && foreign_family); diff --git a/crates/metal2vulkan-runtime/src/exported_memory.rs b/crates/metal2vulkan-runtime/src/exported_memory.rs index cb6eb8383..f40c76958 100644 --- a/crates/metal2vulkan-runtime/src/exported_memory.rs +++ b/crates/metal2vulkan-runtime/src/exported_memory.rs @@ -170,6 +170,12 @@ impl FdExport { dedicated_only: features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY), }) } + + /// Whether the device exports such memory from a block that buffers share, not only from a + /// buffer's dedicated allocation. + pub(super) fn pooled(&self) -> bool { + !self.dedicated_only + } } /// No Metal counterpart: a buffer's memory, exported as a file descriptor of its handle type diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index c95e10185..719873311 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -1373,18 +1373,18 @@ impl ClassPages { Ok(ClassPages { buffer, start }) } PagesClass::DmaBuf => dma_buf_pages(device, length), - // A buffer of the runtime's own in its pooled memory that declares the bytes between - // a texture's rows unobserved, as the product's buffers whose textures take such an - // image do (`texture.rs`'s `alias_image`): only where the device makes - // `DRM_FORMAT_MOD_LINEAR` images. + // A buffer of the runtime's own in its pooled memory exported as no handle type + // (where the device's own buffers lie in blocks exportable as opaque file + // descriptors, a block of plain buffers: `memory.rs`'s `Holds::FdBuffers`) that + // declares the bytes between a texture's rows unobserved, as the product's buffers + // whose textures take such an image do (`texture.rs`'s `alias_image`): only where the + // device makes `DRM_FORMAT_MOD_LINEAR` images. PagesClass::Pooled => { if !device.makes_modifier_images() { let why = "the device makes no DRM_FORMAT_MOD_LINEAR images"; return Err(Unmade::lasting(why)); } - let shared = ResourceOptions::shared(); - let outside = AddressPlacement::Outside; - let buffer = (device.new_buffer_placed(length, shared, outside)) + let buffer = (device.pooled_check_buffer(length)) .map_err(|error| Unmade::of_error("its buffer was refused", &error))?; if buffer.in_fresh_pages() { let why = "its buffer lies in fresh pages, not pooled memory"; diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 77e393ab4..e7658d938 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -64,6 +64,29 @@ //! buffers alone share, pooled and kept as any other; or in its dedicated allocation, freed with //! it, where the device needs or prefers one for the export. //! +//! - **Buffers in exportable blocks** ([`Holds::FdBuffers`], [`fd_buffer_types`]). On a device +//! with unified memory whose memory types of a heap that is not device-local (the system +//! heap, where `Private` memory lies first, [`candidates`]) export an opaque file descriptor of +//! a pooled buffer's memory (`vkGetPhysicalDeviceExternalBufferProperties`, for the program's +//! buffers' usage and a buffer of addresses' usage: exportable, and not only from a dedicated +//! allocation), the buffers the runtime's buffer path makes (`buffer.rs`'s +//! `placed_new_buffer`: the program's, those of buffer descriptors, and the runtime's own, not a +//! heap's own buffer nor the in-place check's buffer of pooled memory) are made with +//! `VkExternalMemoryBufferCreateInfo` naming that handle type and lie in blocks of their own, +//! whose blocks of those memory types are allocated exportable as it (`VkExportMemoryAllocateInfo`) +//! and never exported; their buffers of addresses are made for it too, as a buffer bound in +//! such memory must name its handle type (`VUID-vkBindBufferMemory-memory-02726`), and an image +//! bound in it names it as well (`VUID-vkBindImageMemory-memory-02728`, [`Memory::bound_memory`]: +//! a texture over such a buffer takes the in-place check's class of the runtime's memory +//! exported as opaque file descriptors). On a Radeon 780M (RADV) a block's `vkAllocateMemory` +//! of a buffer object private to the process takes the reservation of the process's GPU +//! address space, which every submission also takes, for as long as the kernel fills its +//! pages: each 64 MiB block of the system heap held the scheduler's `vkQueueSubmit` 9 ms on a +//! quiet host, and up to 22 ms on one whose free memory lay in single pages; memory allocated +//! exportable is a buffer object of its own reservation, whose making held no submission. Such +//! memory costs each submission about 0.9 us more for each such block (`docs/FAST-PATHS.md`). +//! Every other block of buffers, of images and of a heap is allocated as before. +//! //! - **Blocks made ahead** (`memory/ready.rs`). Each pool the encodings and commits place their //! own resources in ([`keep_room`]) gets a block made off the program's thread while it grows, //! and the pool a color texture's host-transfer image places in ([`Memory::host_copy_pool`]) @@ -196,31 +219,103 @@ pub(super) enum MemoryClass { /// blocks are allocated exportable, as an opaque file descriptor ([`EXPORT_HANDLE`]) or as a /// dma-buf ([`DMA_BUF_HANDLE`]), which a buffer made without that handle type may not be bound to /// (`VUID-vkBindBufferMemory-memory-02726`), and the buffers of each handle type share them. +/// +/// A fifth, [`Holds::FdBuffers`], holds the buffers the runtime's buffer path makes on a device +/// whose blocks of them in memory of a heap that is not device-local are allocated exportable as +/// an opaque file descriptor, never exported (the module docs, "Buffers in exportable blocks"). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Holds { Buffers, Images, Exports, DmaBufs, + /// The buffers `buffer.rs`'s `placed_new_buffer` makes for the program and for the runtime + /// (not a heap's own buffer, nor the in-place check's buffer of pooled memory), on a device + /// that takes such blocks ([`Memory::fd_buffer_blocks`]): each made with + /// `VkExternalMemoryBufferCreateInfo` naming [`EXPORT_HANDLE`], so that it may be bound in a + /// block allocated exportable as that handle type (`VUID-vkBindBufferMemory-memory-02726`). + /// Its blocks of the memory types [`fd_buffer_types`] names are allocated so, its others as + /// any block of buffers. + FdBuffers, } impl Holds { /// The kinds, in the order of the device's pools ([`Memory::pool`]). - const ALL: [Holds; 4] = [ + const ALL: [Holds; 5] = [ Holds::Buffers, Holds::Images, Holds::Exports, Holds::DmaBufs, + Holds::FdBuffers, ]; - /// The handle type its blocks are allocated exportable as; `None` for blocks not exported. + /// The handle type its blocks are allocated exportable as for another API's import; `None` + /// for blocks never exported, [`Holds::FdBuffers`]' among them. fn handle(self) -> Option { match self { - Holds::Buffers | Holds::Images => None, + Holds::Buffers | Holds::Images | Holds::FdBuffers => None, Holds::Exports => Some(EXPORT_HANDLE), Holds::DmaBufs => Some(DMA_BUF_HANDLE), } } + + /// Whether its blocks hold buffers, and so may carry a buffer of addresses. + fn buffers(self) -> bool { + matches!(self, Holds::Buffers | Holds::FdBuffers) + } +} + +/// The memory types whose [`Holds::FdBuffers`] blocks a device allocates exportable as an opaque +/// file descriptor ([`EXPORT_HANDLE`]), as bits (the module docs, "Buffers in exportable +/// blocks"), of a device with `properties`, with unified memory or without (`unified`), whose +/// answers for an opaque file descriptor of a pooled buffer's memory are `exports`: with unified +/// memory, the types of a heap that is not device-local, where the device exports such memory +/// from a block that buffers share. Else why it takes none. +pub(super) fn fd_buffer_types( + properties: &vk::PhysicalDeviceMemoryProperties, + unified: bool, + exports: Result<(), &'static str>, +) -> Result { + if !unified { + return Err("the device has no unified memory"); + } + exports?; + let count = (properties.memory_type_count as usize).min(vk::MAX_MEMORY_TYPES); + let heaps = &properties.memory_heaps; + let types = (properties.memory_types[..count].iter().enumerate()) + .filter(|(_, memory_type)| { + (heaps.get(memory_type.heap_index as usize)) + .is_some_and(|heap| !heap.flags.contains(vk::MemoryHeapFlags::DEVICE_LOCAL)) + }) + .fold(0, |bits, (index, _)| bits | 1 << index); + match types { + 0 => Err("the device has no memory type of a heap that is not device-local"), + types => Ok(types), + } +} + +/// What a new block's memory is allocated exportable as ([`BlockMaker::make_as`]). +#[derive(Clone, Copy, Debug)] +enum Exportable { + /// Nothing. + No, + /// The handle type of the exportable buffers it holds (`exported_memory.rs`), for its buffer: + /// that buffer's dedicated allocation where `Exported::dedicated` says so. + For(vk::Buffer, Exported), + /// An opaque file descriptor ([`EXPORT_HANDLE`]), never exported: a block of + /// [`Holds::FdBuffers`] of a memory type [`fd_buffer_types`] names. + Fd, +} + +impl Exportable { + /// The handle type it names; `None` for [`Exportable::No`]. + fn handle(self) -> Option { + match self { + Exportable::No => None, + Exportable::For(_, exported) => Some(exported.handle), + Exportable::Fd => Some(EXPORT_HANDLE), + } + } } /// The handle type the runtime exports a buffer's memory as (`exported_memory.rs`): an opaque file @@ -1035,6 +1130,10 @@ pub(super) struct Block { type_index: u32, /// What it was allocated exportable as, where it was ([`allocate_exported`]). exported: Option, + /// It was allocated exportable as an opaque file descriptor and is never exported + /// ([`Holds::FdBuffers`]): an image bound in it names that handle type + /// ([`Memory::bound_memory`]). + fd: bool, /// It was allocated with `VK_MEMORY_ALLOCATE_ZERO_INITIALIZE_BIT_EXT`, which reads zero until /// written ([`Memory::zero_image_blocks`]). zeroed: bool, @@ -1191,17 +1290,24 @@ impl Block { } /// A buffer of `size` bytes with every usage of an addressed buffer, shared as `sharing` says, -/// unbound, and the bytes of memory it requires. +/// made for `handle` where given (for a block exportable as it, +/// `VUID-vkBindBufferMemory-memory-02726`), unbound, and the bytes of memory it requires. fn address_buffer( device: &ash::Device, size: u64, sharing: Sharing<'_>, + handle: Option, ) -> Result<(vk::Buffer, u64), Error> { - let info = sharing.buffer( + let mut external = + vk::ExternalMemoryBufferCreateInfo::default().handle_types(handle.unwrap_or_default()); + let mut info = sharing.buffer( vk::BufferCreateInfo::default() .size(size) .usage(usage(true)), ); + if handle.is_some() { + info = info.push_next(&mut external); + } // SAFETY: the device is live and `info` valid. let raw = unsafe { crate::creation::buffer(device, &info) }.map_err(vulkan)?; // SAFETY: `raw` is a live buffer of this device. @@ -1500,6 +1606,13 @@ pub(super) struct Memory { /// The memory types a buffer of addresses takes, as bits, once asked /// ([`allocate_addressed`]). address_types: Option, + /// As `address_types`, of a buffer of addresses made for [`EXPORT_HANDLE`], which the blocks + /// of [`Holds::FdBuffers`] that are allocated exportable carry. + fd_address_types: Option, + /// The memory types whose [`Holds::FdBuffers`] blocks are allocated exportable, as bits, or + /// why none are ([`fd_buffer_types`]). + fd_buffer_types: Result, + fd_blocks: FdBlocks, /// The pools the runtime's encodings and commits place their own resources in, once asked /// ([`Memory::kept`], [`keep_room`]). kept: Option>, @@ -1610,6 +1723,17 @@ impl AheadBlocks { } } +/// The counts of the blocks of [`Holds::FdBuffers`] made so far. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct FdBlocks { + /// Allocated exportable as an opaque file descriptor: of a memory type [`fd_buffer_types`] + /// names. + pub(super) exportable: u64, + /// Allocated as any block of buffers: of a memory type it does not name (device-local memory + /// the program's buffers overflowed into, or that their class takes first). + pub(super) plain: u64, +} + /// The counts of the blocks of the pool host copies place in ([`Memory::host_copy_pool`]). #[derive(Clone, Copy, Debug, Default)] pub(super) struct HostCopyBlocks { @@ -1648,6 +1772,9 @@ impl Memory { block_bytes: BLOCK_BYTES.min(max_allocation.max(1)), device_address, address_types: None, + fd_address_types: None, + fd_buffer_types: Err("the device was not asked for exportable buffer memory"), + fd_blocks: FdBlocks::default(), kept: None, unified, buffer_families: families.clone(), @@ -1691,6 +1818,45 @@ impl Memory { self.buffer_families = families; } + /// Allocate the blocks of [`Holds::FdBuffers`] of the memory types `types` names (as bits) + /// exportable as an opaque file descriptor from now on, where it names any, else note why + /// not (the memory log says which), as the device is made: `buffer.rs`'s + /// `placed_new_buffer` then makes its buffers for that handle type and places them there + /// ([`Memory::own_buffers`]). + pub(super) fn fd_buffer_blocks(&mut self, types: Result) { + if let Some(log) = &self.log { + log.line(match types { + Ok(types) => format!( + "the runtime's own buffers lie in blocks of memory types {types:#x} exportable \ + as opaque file descriptors" + ), + Err(why) => format!("the runtime's own buffers lie in plain blocks: {why}"), + }); + } + self.fd_buffer_types = types; + } + + /// The memory types whose [`Holds::FdBuffers`] blocks are allocated exportable, as bits, or + /// why none are. + pub(super) fn fd_buffer_types(&self) -> Result { + self.fd_buffer_types + } + + /// The kind of block the buffers `buffer.rs`'s `placed_new_buffer` makes for the program and + /// for the runtime take: [`Holds::FdBuffers`] where the device allocates any of them + /// exportable ([`Memory::fd_buffer_blocks`]), else [`Holds::Buffers`]. + pub(super) fn own_buffers(&self) -> Holds { + match self.fd_buffer_types { + Ok(_) => Holds::FdBuffers, + Err(_) => Holds::Buffers, + } + } + + /// The counts of the blocks of [`Holds::FdBuffers`] made so far. + pub(super) fn fd_blocks(&self) -> FdBlocks { + self.fd_blocks + } + /// Log each `VkDeviceMemory` allocated, imported or freed from now on to `log` /// (`memory_log.rs`). pub(super) fn log_to(&mut self, log: Option) { @@ -1859,7 +2025,7 @@ impl Memory { Ok(TypeView { types: self.types.clone(), heap_sizes: self.heaps.iter().map(|&(size, _)| size).collect(), - buffers: buffer_types(device, usage(false), sharing)?, + buffers: buffer_types(device, usage(false), sharing, None)?, images: color_image_types(device, sharing)?, }) } @@ -2030,17 +2196,30 @@ impl Memory { &self.pools[self.pool_at(holds, type_index)] } - /// The memory types a buffer of addresses takes, as bits, asked once: `None` without - /// `bufferDeviceAddress`, where blocks carry no buffer of addresses. - fn address_types(&mut self, device: &ash::Device) -> Result, Error> { + /// The memory types a buffer of addresses of a block that holds `holds` takes, as bits, + /// asked once: `None` without `bufferDeviceAddress`, where blocks carry no buffer of + /// addresses. Of [`Holds::FdBuffers`] on a device that allocates its blocks exportable, a + /// buffer made for [`EXPORT_HANDLE`]. + fn address_types(&mut self, device: &ash::Device, holds: Holds) -> Result, Error> { if !self.device_address { return Ok(None); } - if self.address_types.is_none() { - let sharing = Sharing::with_buffers(&self.families, &self.buffer_families); - self.address_types = Some(buffer_types(device, usage(true), sharing)?); + let fd = holds == Holds::FdBuffers && self.fd_buffer_types.is_ok(); + let known = match fd { + true => self.fd_address_types, + false => self.address_types, + }; + if let Some(types) = known { + return Ok(Some(types)); } - Ok(self.address_types) + let sharing = Sharing::with_buffers(&self.families, &self.buffer_families); + let handle = fd.then_some(EXPORT_HANDLE); + let types = buffer_types(device, usage(true), sharing, handle)?; + match fd { + true => self.fd_address_types = Some(types), + false => self.address_types = Some(types), + } + Ok(Some(types)) } /// `size` bytes aligned to `align` in a pooled block of `pool` that has room, in a block @@ -2059,7 +2238,7 @@ impl Memory { return Ok(None); }; if let Some(counts) = addressed { - if let Err(error) = self.address_block(device, type_index, block, counts) { + if let Err(error) = self.address_block(device, (holds, type_index), block, counts) { drop(self.release_range(device, (holds, type_index), block, offset, size, None)); return Err(error); } @@ -2086,7 +2265,7 @@ impl Memory { return Ok(None); }; if let Some(counts) = addressed { - if let Err(error) = self.address_block(device, type_index, block, counts) { + if let Err(error) = self.address_block(device, (holds, type_index), block, counts) { drop(self.release_range(device, (holds, type_index), block, 0, size, None)); return Err(error); } @@ -2112,13 +2291,27 @@ impl Memory { (false, Holds::Images) => "made a pooled block of images", (false, Holds::Exports) => "made a pooled block of exportable buffers", (false, Holds::DmaBufs) => "made a pooled block of dma-buf-exportable buffers", + (false, Holds::FdBuffers) if block.fd => { + "made a pooled block of fd-exportable buffers" + } + (false, Holds::FdBuffers) => "made a pooled block of buffers", (true, Holds::Buffers) => "made a dedicated block of a buffer", (true, Holds::Images) => "made a dedicated block of an image", (true, Holds::Exports) => "made a dedicated block of an exportable buffer", (true, Holds::DmaBufs) => "made a dedicated block of a dma-buf-exportable buffer", + (true, Holds::FdBuffers) if block.fd => { + "made a dedicated block of an fd-exportable buffer" + } + (true, Holds::FdBuffers) => "made a dedicated block of a buffer", }; self.say_block(what, &block); } + if holds == Holds::FdBuffers { + match block.fd { + true => self.fd_blocks.exportable += 1, + false => self.fd_blocks.plain += 1, + } + } self.allocated += size; let heap = self.heap_of(type_index); if let Some((_, live)) = self.heaps.get_mut(heap) { @@ -2141,6 +2334,7 @@ impl Memory { BlockMaker { block_bytes: self.block_bytes, host_visible, + fd_types: self.fd_buffer_types.unwrap_or(0), device_address: self.device_address, families: self.buffer_families.clone(), zero_images: self.zero_images, @@ -2150,16 +2344,33 @@ impl Memory { /// The pools the runtime's encodings and commits place their own resources in, found once: /// of buffers, the best memory type of `Private`, `WriteCombined` and `Shared` memory among /// those a buffer the runtime places takes (`buffer::usage(false)`, its address from a buffer - /// of addresses, [`allocate_addressed`]); of images, the best `Private` type among those a - /// color image of optimal tiling takes, which every such image takes (the Vulkan - /// specification's `VkMemoryRequirements`). + /// of addresses, [`allocate_addressed`]), in the blocks of [`Holds::Buffers`] and, where the + /// device allocates blocks of [`Holds::FdBuffers`] exportable, in those too, of a buffer made + /// for [`EXPORT_HANDLE`]; of images, the best `Private` type among those a color image of + /// optimal tiling takes, which every such image takes (the Vulkan specification's + /// `VkMemoryRequirements`). fn kept(&mut self, device: &ash::Device) -> Result, Error> { if let Some(kept) = &self.kept { return Ok(kept.clone()); } - let addresses = self.address_types(device)?.unwrap_or(u32::MAX); + let addresses = self + .address_types(device, Holds::Buffers)? + .unwrap_or(u32::MAX); + let fd = match self.fd_buffer_types { + Ok(_) => Some( + self.address_types(device, Holds::FdBuffers)? + .unwrap_or(u32::MAX), + ), + Err(_) => None, + }; let sharing = Sharing::with_buffers(&self.families, &self.buffer_families); - let buffers = buffer_types(device, usage(false), sharing)? & addresses; + let buffers = buffer_types(device, usage(false), sharing, None)? & addresses; + let fd_buffers = match fd { + Some(addresses) => { + buffer_types(device, usage(false), sharing, Some(EXPORT_HANDLE))? & addresses + } + None => 0, + }; let images = color_image_types(device, sharing)?; let best = |bits: u32, class: MemoryClass| { candidates(&self.types, bits, class, self.unified) @@ -2175,9 +2386,12 @@ impl Memory { let buffer_pools = (classes.into_iter()) .filter_map(|class| best(buffers, class)) .map(|type_index| (Holds::Buffers, type_index)); + let fd_pools = (classes.into_iter()) + .filter_map(|class| best(fd_buffers, class)) + .map(|type_index| (Holds::FdBuffers, type_index)); let image_pool = best(images, MemoryClass::Private).map(|type_index| (Holds::Images, type_index)); - for pool in buffer_pools.chain(image_pool) { + for pool in buffer_pools.chain(fd_pools).chain(image_pool) { if !kept.contains(&pool) { kept.push(pool); } @@ -2227,18 +2441,19 @@ impl Memory { } } - /// Give pooled block `block` of memory type `type_index` a buffer of addresses where it has - /// none: over its whole size, which it takes since the block is of a type such a buffer - /// takes ([`allocate_addressed`]); refused (an invariant) where the buffer would - /// need more bytes than the block has. + /// Give pooled block `block` of the pool of memory type `type_index` that holds `holds` a + /// buffer of addresses where it has none: over its whole size, which it takes since the + /// block is of a type such a buffer takes ([`allocate_addressed`]), made for the block's + /// handle type where it is exportable (`VUID-vkBindBufferMemory-memory-02726`); refused (an + /// invariant) where the buffer would need more bytes than the block has. fn address_block( &mut self, device: &ash::Device, - type_index: u32, + (holds, type_index): (Holds, u32), block: usize, counts: &Counters, ) -> Result<(), Error> { - let at = self.pool_at(Holds::Buffers, type_index); + let at = self.pool_at(holds, type_index); let sharing = Sharing::with_buffers(&self.families, &self.buffer_families); let payload = self.pools[at] .payload_mut(block) @@ -2246,7 +2461,8 @@ impl Memory { if payload.addresses.is_some() { return Ok(()); } - let (raw, required) = address_buffer(device, payload.size, sharing)?; + let handle = payload.fd.then_some(EXPORT_HANDLE); + let (raw, required) = address_buffer(device, payload.size, sharing, handle)?; if required > payload.size { // SAFETY: the buffer is unused. unsafe { release::object(device, raw) }; @@ -2554,6 +2770,7 @@ impl Memory { dedicated: true, .. }) => BoundMemory::NoImage(NoImage::Dedicated), Some(exported) => BoundMemory::External(exported.handle), + None if block.fd => BoundMemory::External(EXPORT_HANDLE), None if block.imported || block.pages.is_some() || block.view.is_some() => { BoundMemory::External(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT) } @@ -2630,6 +2847,8 @@ struct BlockMaker { block_bytes: u64, /// The host-visible memory types, as bits: a block of one is mapped whole. host_visible: u32, + /// The memory types whose [`Holds::FdBuffers`] blocks are allocated exportable, as bits. + fd_types: u32, /// As [`Memory`]'s. device_address: bool, /// The families its buffers of addresses are shared among: [`Memory`]'s buffers'. @@ -2643,7 +2862,9 @@ 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`]), or as an opaque + /// file descriptor where it is a block of [`Holds::FdBuffers`] of a memory type + /// [`fd_buffer_types`] names. fn make( &self, device: &ash::Device, @@ -2652,30 +2873,38 @@ impl BlockMaker { addressed: Option<&Counters>, ) -> Result { let zeroed = holds == Holds::Images && self.zero_images; - let export = holds.handle().map(|handle| { - let exported = Exported { - handle, - dedicated: false, - }; - (vk::Buffer::null(), exported) - }); + let export = match holds.handle() { + Some(handle) => Exportable::For( + vk::Buffer::null(), + Exported { + handle, + dedicated: false, + }, + ), + None if holds == Holds::FdBuffers && self.fd_types & 1 << type_index != 0 => { + Exportable::Fd + } + None => Exportable::No, + }; self.make_as(device, type_index, size, addressed, export, zeroed) } - /// [`make`](Self::make), its memory allocated exportable as `export` says where given, for its - /// buffer, the dedicated allocation of that buffer where it says so ([`allocate_exported`]), - /// and with `VK_MEMORY_ALLOCATE_ZERO_INITIALIZE_BIT_EXT` where `zeroed`. + /// [`make`](Self::make), its memory allocated exportable as `export` says, the dedicated + /// allocation of its buffer where it says so ([`allocate_exported`]), and with + /// `VK_MEMORY_ALLOCATE_ZERO_INITIALIZE_BIT_EXT` where `zeroed`. Its buffer of addresses is + /// made for the handle type it is exportable as (`VUID-vkBindBufferMemory-memory-02726`). fn make_as( &self, device: &ash::Device, type_index: u32, size: u64, addressed: Option<&Counters>, - export: Option<(vk::Buffer, Exported)>, + export: Exportable, zeroed: bool, ) -> Result { let addresses = if addressed.is_some() && self.device_address { - Some(address_buffer(device, size, Sharing::new(&self.families))?) + let sharing = Sharing::new(&self.families); + Some(address_buffer(device, size, sharing, export.handle())?) } else { None }; @@ -2699,15 +2928,15 @@ impl BlockMaker { if !allocate.is_empty() { info = info.push_next(&mut flags); } - let handle = export.map_or( - vk::ExternalMemoryHandleTypeFlags::empty(), - |(_, exported)| exported.handle, - ); - let mut exportable = vk::ExportMemoryAllocateInfo::default().handle_types(handle); - let dedicated_to = (export.filter(|(_, exported)| exported.dedicated)) - .map_or(vk::Buffer::null(), |(buffer, _)| buffer); + let handle = export.handle(); + let mut exportable = + vk::ExportMemoryAllocateInfo::default().handle_types(handle.unwrap_or_default()); + let dedicated_to = match export { + Exportable::For(buffer, exported) if exported.dedicated => buffer, + _ => vk::Buffer::null(), + }; let mut dedicated = vk::MemoryDedicatedAllocateInfo::default().buffer(dedicated_to); - if export.is_some() { + if handle.is_some() { info = info.push_next(&mut exportable); } if dedicated_to != vk::Buffer::null() { @@ -2766,20 +2995,31 @@ impl BlockMaker { pages: None, view: None, type_index, - exported: export.map(|(_, exported)| exported), + exported: match export { + Exportable::For(_, exported) => Some(exported), + Exportable::No | Exportable::Fd => None, + }, + fd: matches!(export, Exportable::Fd), zeroed, }) } } -/// The memory types a buffer of `usage` takes, as bits: those of one made for the query and -/// destroyed at once, with no memory bound. Every buffer of one usage takes the same types. +/// The memory types a buffer of `usage` takes, made for `handle` where given, as bits: those of +/// one made for the query and destroyed at once, with no memory bound. Every buffer of one usage +/// and handle type takes the same types. fn buffer_types( device: &ash::Device, usage: vk::BufferUsageFlags, sharing: Sharing<'_>, + handle: Option, ) -> Result { - let info = sharing.buffer(vk::BufferCreateInfo::default().size(16).usage(usage)); + let mut external = + vk::ExternalMemoryBufferCreateInfo::default().handle_types(handle.unwrap_or_default()); + let mut info = sharing.buffer(vk::BufferCreateInfo::default().size(16).usage(usage)); + if handle.is_some() { + info = info.push_next(&mut external); + } // SAFETY: the device is live and `info` valid. let raw = unsafe { crate::creation::buffer(device, &info) }.map_err(vulkan)?; // SAFETY: `raw` is a live buffer of this device, destroyed right after the query with no @@ -2997,6 +3237,7 @@ pub(super) unsafe fn import_host( view, type_index, exported: None, + fd: false, zeroed: false, }; let host = pointer.as_ptr() as usize; @@ -3032,6 +3273,7 @@ pub(super) fn import_own_pages( view: None, type_index, exported: None, + fd: false, zeroed: false, }; let mut memory = lock(memory); @@ -3087,6 +3329,18 @@ pub(super) fn allocate( device: &ash::Device, requirements: &vk::MemoryRequirements, class: MemoryClass, +) -> Result { + allocate_in(memory, device, requirements, class, Holds::Buffers) +} + +/// [`allocate`] in a block that holds `holds`: [`Holds::Buffers`], or [`Holds::FdBuffers`] for a +/// buffer made for [`EXPORT_HANDLE`] (`buffer.rs`'s `placed_new_buffer`). +pub(super) fn allocate_in( + memory: &Mutex, + device: &ash::Device, + requirements: &vk::MemoryRequirements, + class: MemoryClass, + holds: Holds, ) -> Result { place( memory, @@ -3094,7 +3348,7 @@ pub(super) fn allocate( requirements, class, None, - Holds::Buffers, + holds, Fit::Pooled, ) } @@ -3162,8 +3416,25 @@ pub(super) fn allocate_addressed( class: MemoryClass, counts: &Counters, ) -> Result { - let Some(types) = lock(memory).address_types(device)? else { - return allocate(memory, device, requirements, class); + allocate_addressed_in( + memory, + device, + requirements, + (class, Holds::Buffers), + counts, + ) +} + +/// [`allocate_addressed`] in a block that holds `holds` ([`allocate_in`]). +pub(super) fn allocate_addressed_in( + memory: &Mutex, + device: &ash::Device, + requirements: &vk::MemoryRequirements, + (class, holds): (MemoryClass, Holds), + counts: &Counters, +) -> Result { + let Some(types) = lock(memory).address_types(device, holds)? else { + return allocate_in(memory, device, requirements, class, holds); }; let requirements = vk::MemoryRequirements { memory_type_bits: requirements.memory_type_bits & types, @@ -3175,7 +3446,7 @@ pub(super) fn allocate_addressed( &requirements, class, Some(counts), - Holds::Buffers, + holds, Fit::Pooled, ) } @@ -3228,7 +3499,7 @@ pub(super) fn allocate_exported( if let Some(frees) = before { frees.wait(); } - let export = Some((buffer, exported)); + let export = Exportable::For(buffer, exported); match maker.make_as(device, type_index, size, None, export, false) { Ok(block) => { let pool = (Holds::Buffers, type_index); @@ -3403,7 +3674,7 @@ pub(super) fn keep_room( }; let room = maker.block_bytes / 2; for pool in kept { - let addressed = (pool.0 == Holds::Buffers).then_some(&**counts); + let addressed = pool.0.buffers().then_some(&**counts); loop { let mut guard = lock(memory); if guard.pool(pool.0, pool.1).has_room(room) { @@ -3441,7 +3712,7 @@ pub(super) fn keep_room( if !grew || pool_of.has_room(maker.block_bytes) || guard.readying_at(pool).is_some() { continue; } - let addressed = (pool.0 == Holds::Buffers).then(|| Arc::clone(counts)); + let addressed = pool.0.buffers().then(|| Arc::clone(counts)); let started = ready::Readying::start( guard.maker(), Arc::clone(functions), diff --git a/crates/metal2vulkan-runtime/src/tests/exported_textures.rs b/crates/metal2vulkan-runtime/src/tests/exported_textures.rs index 6be2b9de8..2a2944678 100644 --- a/crates/metal2vulkan-runtime/src/tests/exported_textures.rs +++ b/crates/metal2vulkan-runtime/src/tests/exported_textures.rs @@ -36,6 +36,15 @@ //! its placement refused (`InPlaceRefusal::Placement`); a dma-buf's dedicated allocation takes //! the import of its own dma-buf (below) where the device makes one. //! +//! - **The runtime's own buffers' blocks.** The same picture in a buffer the program made with no +//! export, its rows' padding declared unobserved as the consumer's caches declare it: where the +//! device's own buffers lie in blocks exportable as opaque file descriptors (`memory.rs`'s +//! "Buffers in exportable blocks"), its memory is such a block (`WorkCounts::fd_buffer_blocks_made`), +//! which the runtime never exports (`export_memory_fd` refuses it, `NotExportable`), and each +//! plane's image names the block's handle type, the layer reporting nothing; once the device's +//! check of that memory answered, each plane is in place or the shadow its verdict decided, and +//! reads the same bytes. Elsewhere its memory is a plain block, as before. +//! //! 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. @@ -46,7 +55,8 @@ use super::blit_holds::{Scratch, WAIT}; use super::layer_claim::Watched; use super::pending_rebind::device; -use crate::error::{Error, RuntimeGap}; +use crate::error::{Error, Invalid, Problem, RuntimeGap}; +use crate::memory::BoundMemory; use crate::{ BlitOption, Buffer, BufferContents, BufferDescriptor, Device, InPlaceRefusal, MemoryExport, Origin, ResourceOptions, Size, Texture, TextureDescriptor, TexturePlacement, @@ -677,3 +687,96 @@ fn a_dma_buf_export_s_planes_go_in_place_through_its_own_dma_buf_where_no_image_ "images over a dma-buf export, in its memory or through its own dma-buf", ); } + +#[test] +fn an_nv12_picture_s_planes_over_a_buffer_of_the_runtime_s_own_name_its_block_s_handle_type() { + let watched = Watched::default(); + let scratch = Scratch::new("own-buffer-textures"); + let device = device(&watched, &scratch.0); + let name = device.name().to_owned(); + let types = crate::device::lock(&device.shared().memory).fd_buffer_types(); + eprintln!("EXPORTED-TEXTURES on {name}: the blocks of the runtime's own buffers: {types:?}"); + let mut first = true; + for options in [ResourceOptions::private(), ResourceOptions::shared()] { + let descriptor = BufferDescriptor::new(LENGTH, options, BufferContents::Zero) + .with_aligned_byte(LUMA_AT) + .with_padding_unobserved(); + let picture = device.new_buffer_with_descriptor(descriptor).unwrap(); + let (bound, counts) = (picture.bound_memory(), device.work_counts()); + match types { + Ok(_) => { + let fd = BoundMemory::External(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD); + assert!( + bound == fd, + "{options:?}: a block exportable as an opaque fd" + ); + assert!( + counts.fd_buffer_blocks_made > 0, + "{options:?}: such blocks made" + ); + assert!( + matches!( + picture.export_memory_fd(), + Err(Error::Invalid(Invalid { + problem: Problem::NotExportable, + .. + })) + ), + "{options:?}: the runtime exports no such buffer" + ); + } + Err(_) => { + assert!(bound == BoundMemory::Own, "{options:?}: a plain block"); + let made = (counts.fd_buffer_blocks_made, counts.fd_buffer_blocks_plain); + assert_eq!(made, (0, 0), "{options:?}: no block of such buffers"); + } + } + fill(&device, &picture); + for plane in PLANES { + let texture = + (picture.new_texture(&descriptor(plane, options), plane.at, ROW)).unwrap(); + assert!( + read(&device, &texture, plane) == want(plane), + "{options:?} {plane:?}: the texels, read as made" + ); + } + if first { + assert!(device.settle_in_place_checks(WAIT), "the check answered"); + first = false; + } + for plane in PLANES { + 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!( + matches!( + placement, + TexturePlacement::NotHostPages + | TexturePlacement::Shadow( + TextureShadowReason::Unchecked { .. } + | TextureShadowReason::CheckFailed { .. } + ) + ), + "{options:?} {plane:?}: in place, or a shadow the device's check decided: \ + {placement:?}" + ); + assert_eq!( + texture.shadow().is_none(), + placement == TexturePlacement::NotHostPages + ); + assert!( + read(&device, &texture, plane) == want(plane), + "{options:?} {plane:?}: the texels, read after the check answered" + ); + eprintln!( + "EXPORTED-TEXTURES on {name}: a buffer of the runtime's own, {options:?} {:?} \ + {}x{}: {placement:?}", + plane.format, plane.size[0], plane.size[1] + ); + } + } + watched.layer_reported_nothing( + "buffers and textures in blocks exportable as opaque fds name the handle type \ + (VUID-vkBindBufferMemory-memory-02726, VUID-vkBindImageMemory-memory-02728)", + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/memory.rs b/crates/metal2vulkan-runtime/src/tests/memory.rs index d05c51132..04b2d30a4 100644 --- a/crates/metal2vulkan-runtime/src/tests/memory.rs +++ b/crates/metal2vulkan-runtime/src/tests/memory.rs @@ -1,5 +1,5 @@ use crate::memory::{ - candidates, host_cached, host_cached_placement, host_incoherent, kept_budget, + candidates, fd_buffer_types, host_cached, host_cached_placement, host_incoherent, kept_budget, overflow_candidates, MemoryClass, Pool, KEPT_EMPTY_BLOCKS, KEPT_EMPTY_BYTES, KEPT_EMPTY_FOR, }; use ash::vk; @@ -238,6 +238,55 @@ fn unified_private_memory_takes_the_system_heap_first() { assert_eq!(candidates(&anv, 0b11, private, true), [0, 1]); } +/// The memory types whose blocks of the runtime's own buffers are allocated exportable as an +/// opaque file descriptor (`memory.rs`'s "Buffers in exportable blocks"): with unified memory, +/// those of a heap that is not device-local, where the device exports such memory from a pooled +/// block; else none, and why. +#[test] +fn own_buffer_blocks_are_exportable_in_a_unified_device_s_system_heap() { + use vk::MemoryPropertyFlags as P; + // RADV (Mesa 26.2.4) on a Radeon 780M: heap 0 device-local, heap 1 system memory; types as + // in `unified_private_memory_takes_the_system_heap_first`, each in the heap its flags say. + let flags = [ + 0x1, 0x1, 0x6, 0x7, 0x7, 0xe, 0xe, 0x21, 0x21, 0x21, 0x21, 0x20, 0x20, 0xc1, 0xc6, 0xc7, + 0xce, + ]; + let properties = |flags: &[u32], heaps: &[vk::MemoryHeapFlags]| { + let mut properties = vk::PhysicalDeviceMemoryProperties { + memory_type_count: flags.len() as u32, + memory_heap_count: heaps.len() as u32, + ..Default::default() + }; + for (at, &flags) in flags.iter().enumerate() { + let flags = P::from_raw(flags); + let heap = u32::from(!flags.contains(P::DEVICE_LOCAL) && heaps.len() > 1); + properties.memory_types[at] = vk::MemoryType { + property_flags: flags, + heap_index: heap, + }; + } + for (at, &flags) in heaps.iter().enumerate() { + properties.memory_heaps[at] = vk::MemoryHeap { + size: 1 << 33, + flags, + }; + } + properties + }; + let local = vk::MemoryHeapFlags::DEVICE_LOCAL; + let radv = properties(&flags, &[local, vk::MemoryHeapFlags::empty()]); + let system = 1 << 2 | 1 << 5 | 1 << 6 | 1 << 11 | 1 << 12 | 1 << 14 | 1 << 16; + assert_eq!(fd_buffer_types(&radv, true, Ok(())), Ok(system)); + // Where the device exports no such memory from a pooled block, none, for its reason. + let refused = "refused"; + assert_eq!(fd_buffer_types(&radv, true, Err(refused)), Err(refused)); + // Without unified memory (a discrete GPU's system heap), none. + assert!(fd_buffer_types(&radv, false, Ok(())).is_err()); + // Every heap device-local (ANV, lavapipe, MoltenVK): none. + let anv = properties(&[0x1, 0x7], &[local]); + assert!(fd_buffer_types(&anv, true, Ok(())).is_err()); +} + /// No class takes a device-coherent or device-uncached type of `VK_AMD_device_coherent_memory`, /// whose allocation needs a feature the runtime does not enable, even where it is the only type /// the resource allows or ranks best by its other properties. diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 0bed054a3..b40da455d 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -5038,6 +5038,16 @@ pub struct WorkCounts { /// creation call that found its pool without room for half a block, or a placement that /// found no room (`memory/ready.rs`). pub buffer_blocks_made_in_place: u64, + /// The blocks the runtime's own buffers and the program's lie in (`memory.rs`'s + /// `Holds::FdBuffers`) made so far, pooled or dedicated, allocated exportable as an opaque + /// file descriptor and never exported, so that their making holds no other submission (the + /// module docs of `memory.rs`, "Buffers in exportable blocks"): 0 on a device that takes no + /// such blocks (`Memory::fd_buffer_types`'s reason, which the memory log names). + pub fd_buffer_blocks_made: u64, + /// The blocks of those buffers made so far as any block of buffers, not exportable: of a + /// memory type of a device-local heap, which such buffers overflowed into or their class + /// takes first. + pub fd_buffer_blocks_plain: u64, /// As `buffer_blocks_made_ahead`, of images, those of the pool host copies place in among /// them (`host_copy_blocks_readied`). pub image_blocks_made_ahead: u64, @@ -7930,7 +7940,7 @@ impl Device { (made, freed), frees, host_copy, - ahead, + (ahead, fd_blocks), ) = { let memory = lock(&self.shared().memory); let turnover = memory.turnover(); @@ -7942,7 +7952,7 @@ impl Device { turnover, memory.frees(), memory.host_copy_blocks(), - memory.ahead_blocks(), + (memory.ahead_blocks(), memory.fd_blocks()), ) }; let (frees_posted, frees_queue_full, free_waits) = self.shared().frees.counts(); @@ -8108,6 +8118,8 @@ impl Device { host_copy_blocks_made_in_place: host_copy.made_in_place, buffer_blocks_made_ahead: ahead.buffers_ahead, buffer_blocks_made_in_place: ahead.buffers_in_place, + fd_buffer_blocks_made: fd_blocks.exportable, + fd_buffer_blocks_plain: fd_blocks.plain, image_blocks_made_ahead: ahead.images_ahead, image_blocks_made_in_place: ahead.images_in_place, blocks_ahead_waited_for: ahead.waited_for, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 9f2ee12ed..1ea9048b9 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2763,6 +2763,8 @@ field metal2vulkan-runtime::WorkCounts.encoders_reencoded pub encoders_reencoded 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 pub exported_dma_buf_images: u64 +field metal2vulkan-runtime::WorkCounts.fd_buffer_blocks_made pub fd_buffer_blocks_made: u64 +field metal2vulkan-runtime::WorkCounts.fd_buffer_blocks_plain pub fd_buffer_blocks_plain: 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