diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 379eab916..b72423b95 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -2314,11 +2314,13 @@ impl Device { } /// 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 { + /// block of the runtime's pooled memory that holds `holds`, whatever kind of block the + /// device's own buffers take: `Holds::Buffers` for the in-place check's class of plain + /// pooled memory (`in_place_check.rs`, `PagesClass::Pooled`), whose image names no handle + /// type, and `Holds::FdBuffers` for its class of the blocks allocated exportable + /// (`PagesClass::FdBlocks`), whose image names one of their handle types (`memory.rs`'s + /// "Buffers in exportable blocks"). Refused as [`Device::new_buffer`] refuses its length. + pub(super) fn pooled_check_buffer(&self, length: u64, holds: Holds) -> Result { const CALL: &str = "new_buffer"; let modes = Modes::of(ResourceOptions::shared())?; let class = buffer_class(CALL, modes)?; @@ -2330,7 +2332,7 @@ impl Device { CALL, length, (modes, class), - NewBufferOf::PlainBlock, + NewBufferOf::Check(holds), placed, ) } @@ -2412,9 +2414,9 @@ impl Device { let (of_heap, fresh) = match of { NewBufferOf::Heap => (true, FreshPages::WherePaid), NewBufferOf::Runtime(fresh) => (false, fresh), - NewBufferOf::PlainBlock => (false, FreshPages::WherePaid), + NewBufferOf::Check(_) => (false, FreshPages::WherePaid), }; - let plain = of == NewBufferOf::PlainBlock; + let plain = matches!(of, NewBufferOf::Check(_)); if self.is_lost() { return Err(self.lost_refusal()); } @@ -2440,12 +2442,17 @@ impl Device { 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`). + // buffers do, whose blocks may be exportable as an opaque file descriptor once the + // device's check of them passed, 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, + NewBufferOf::Runtime(_) => { + let exportable = lock(&shared.memory).fd_buffer_types.is_ok(); + let checked = exportable && self.fd_blocks_checked(); + lock(&shared.memory).own_buffers(checked) + } + NewBufferOf::Heap => Holds::Buffers, + NewBufferOf::Check(holds) => holds, }; let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(EXPORT_HANDLE); @@ -3035,10 +3042,12 @@ enum NewBufferOf { /// 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, + /// The in-place check's buffer of a class of the runtime's pooled memory + /// (`in_place_check.rs`): in a block that holds this, `Holds::Buffers` for + /// `PagesClass::Pooled` (exported as no handle type) and `Holds::FdBuffers` for + /// `PagesClass::FdBlocks` (allocated exportable, never exported) whatever the class's + /// verdicts, never in fresh pages and never parked. + Check(Holds), } /// 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 40f7ea589..ae8b934d8 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -2135,44 +2135,66 @@ impl Device { // 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, and its policy takes textures - // over memory of an export in place by its check (`memory.rs`'s "Buffers in - // exportable blocks"). + // over memory of an export in place by its check; exportable as dma-bufs too where it + // exports one of such memory as well, each handle type compatible with the other + // (`memory.rs`'s "Buffers in exportable blocks"). let in_place = compile.policy().host_page_textures == metal2vulkan::device::HostPageTexturePolicy::InPlace; - let exports = match &functions { - None => Err("the device enables no VK_KHR_external_memory_fd"), - Some(_) if !in_place => { - Err("the device's policy shadows every texture over memory of an export") - } - Some(_) => { - let usages = [ - Some(super::buffer::usage(false)), - device_address.then_some(usage), - ]; - let pooled = usages.into_iter().flatten().all(|usage| { + let usages = [ + Some(super::buffer::usage(false)), + device_address.then_some(usage), + ]; + // The handle types each usage's pooled memory exportable as `export` is compatible + // with, where the device exports it so for every usage. + let compatible = |export, functions: Option| { + (usages.into_iter().flatten()) + .map(|usage| { // SAFETY: as above. let export = unsafe { crate::exported_memory::FdExport::new( &instance.raw, physical, functions.clone(), - (usage, handle), + (usage, export), ) }; - 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"), - } - } + let export = export?; + export.pooled().then(|| export.compatible()) + }) + .collect::>>() }; - memory.fd_buffer_blocks(crate::memory::fd_buffer_types( - &memory_properties, - properties.has_unified_memory, - exports, - )); + let exports = match &functions { + None => Err("the device enables no VK_KHR_external_memory_fd"), + Some(_) if !in_place => { + Err("the device's policy shadows every texture over memory of an export") + } + Some(_) => match compatible(handle, functions.clone()) { + None => Err("the device exports an opaque file descriptor of no pooled \ + buffer's memory of the runtime's usages"), + Some(fd) => { + let dma_buf_handle = crate::buffer_descriptor::MemoryExport::DmaBuf; + let dma = compatible(dma_buf_handle, functions.clone().filter(|_| dma_buf)); + let both = dma.is_some_and(|dma| { + let (fd_handle, dma_handle) = + (handle.handle(), dma_buf_handle.handle()); + (fd.iter()).all(|types| types.contains(dma_handle)) + && (dma.iter()).all(|types| types.contains(fd_handle)) + }); + Ok(match both { + true => handle.handle() | dma_buf_handle.handle(), + false => handle.handle(), + }) + } + }, + }; + memory.fd_buffer_blocks( + crate::memory::fd_buffer_types( + &memory_properties, + properties.has_unified_memory, + exports.map(|_| ()), + ), + exports.unwrap_or(crate::memory::EXPORT_HANDLE), + ); // 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 f40c76958..e7fef0e32 100644 --- a/crates/metal2vulkan-runtime/src/exported_memory.rs +++ b/crates/metal2vulkan-runtime/src/exported_memory.rs @@ -98,7 +98,7 @@ use super::buffer_descriptor::MemoryExport; impl MemoryExport { /// The handle type its buffers export their memory as. - fn handle(self) -> vk::ExternalMemoryHandleTypeFlags { + pub(super) fn handle(self) -> vk::ExternalMemoryHandleTypeFlags { match self { MemoryExport::OpaqueFd => EXPORT_HANDLE, MemoryExport::DmaBuf => DMA_BUF_HANDLE, @@ -130,6 +130,9 @@ 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 memory exportable as it may be exportable as too + /// (`VkExternalMemoryProperties::compatibleHandleTypes`). + compatible: vk::ExternalMemoryHandleTypeFlags, } impl FdExport { @@ -168,6 +171,7 @@ impl FdExport { exports.then_some(FdExport { functions, dedicated_only: features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY), + compatible: memory.compatible_handle_types, }) } @@ -176,6 +180,13 @@ impl FdExport { pub(super) fn pooled(&self) -> bool { !self.dedicated_only } + + /// The handle types such memory may be allocated exportable as beside this one + /// (`VUID-VkExportMemoryAllocateInfo-handleTypes-00656`: those of one allocation are + /// compatible). + pub(super) fn compatible(&self) -> vk::ExternalMemoryHandleTypeFlags { + self.compatible + } } /// 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.rs b/crates/metal2vulkan-runtime/src/in_place.rs index c62880aa2..168e8b7b6 100644 --- a/crates/metal2vulkan-runtime/src/in_place.rs +++ b/crates/metal2vulkan-runtime/src/in_place.rs @@ -185,17 +185,29 @@ pub(crate) enum PagesClass { ExportedFd, /// As [`ExportedFd`](Self::ExportedFd), of memory the runtime exports as a dma-buf. ExportedDmaBuf, + /// A buffer of the runtime's own in a block of the kind its buffers take where the device + /// allocates their blocks exportable and never exports them (`memory.rs`'s + /// `Holds::FdBuffers`, "Buffers in exportable blocks"): the device's linear image made for + /// one of the block's handle types its image format query takes for it, else a + /// `DRM_FORMAT_MOD_LINEAR` one at Metal's pitch made for one it takes for that, bound in the + /// buffer's memory (`texture.rs`'s `alias_image`). Either names that handle type + /// (`VUID-vkBindImageMemory-memory-02728`), so it is made `UNDEFINED` + /// (`VUID-VkImageCreateInfo-pNext-01443`), and its first move leaves that layout. Its verdicts + /// decide whether the device's buffers lie in such blocks at all + /// ([`Device::fd_blocks_checked`]). + FdBlocks, } impl PagesClass { /// Every class, in the order the check runs them and the record holds their verdicts. - pub(crate) const ALL: [PagesClass; 6] = [ + pub(crate) const ALL: [PagesClass; 7] = [ PagesClass::Pointer, PagesClass::Fresh, PagesClass::DmaBuf, PagesClass::Pooled, PagesClass::ExportedFd, PagesClass::ExportedDmaBuf, + PagesClass::FdBlocks, ]; /// Its place in [`ALL`](Self::ALL). @@ -207,6 +219,7 @@ impl PagesClass { PagesClass::Pooled => 3, PagesClass::ExportedFd => 4, PagesClass::ExportedDmaBuf => 5, + PagesClass::FdBlocks => 6, } } @@ -219,6 +232,7 @@ impl PagesClass { PagesClass::Pooled => "the runtime's pooled memory at Metal's pitch", PagesClass::ExportedFd => "the runtime's memory exported as opaque file descriptors", PagesClass::ExportedDmaBuf => "the runtime's memory exported as dma-bufs", + PagesClass::FdBlocks => "the runtime's buffers' blocks allocated exportable", } } @@ -237,7 +251,10 @@ impl PagesClass { /// texture's making makes it (`Device::pooled_move_image`), not over host pages. pub(crate) fn over_own_memory(self) -> bool { match self { - PagesClass::Pooled | PagesClass::ExportedFd | PagesClass::ExportedDmaBuf => true, + PagesClass::Pooled + | PagesClass::ExportedFd + | PagesClass::ExportedDmaBuf + | PagesClass::FdBlocks => true, PagesClass::Pointer | PagesClass::Fresh | PagesClass::DmaBuf => false, } } @@ -947,6 +964,65 @@ impl Drop for Waiting<'_> { } } +/// What the device's verdicts say of the runtime's own buffers' blocks allocated exportable +/// ([`fd_blocks_take`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FdBlocksTake { + /// Its buffers lie there: a texture over one takes in place whatever it takes over a plain + /// block's buffer. + Take, + /// A verdict that decides it is pending: its buffers lie in plain blocks meanwhile. + Pending, + /// A texture over such a buffer, of this access and row ends, would be a shadow where over a + /// plain block's buffer it is in place: its buffers lie in plain blocks. + Refused(Access, RowEnds), +} + +/// What `verdict` (each class's, access's and row ends') says of the runtime's own buffers lying +/// in blocks allocated exportable, never exported ([`PagesClass::FdBlocks`]; `memory.rs`'s +/// "Buffers in exportable blocks"): they lie there where every texture over such a buffer takes +/// in place what it takes over a buffer of a plain block, whose blocks hold the same memory +/// exported as no handle type. Over a plain block's buffer, the device's own linear image is +/// made `PREINITIALIZED`, whose first move keeps its bytes, and needs no verdict; over an +/// exportable block's, it names a handle type and so is made `UNDEFINED` +/// (`VUID-VkImageCreateInfo-pNext-01443`), its other operations the same: so the class's verdict +/// of that move ([`Access::Reads`]) must pass for texels of both row ends. A +/// `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch is made `UNDEFINED` in both, and takes each +/// access its usage takes where its class passed: so every verdict of plain pooled memory +/// ([`PagesClass::Pooled`]) that passed must pass for the class too. Pending where one of those +/// is pending; else refused for the first access and row ends that did not pass. +pub(crate) fn fd_blocks_take( + verdict: impl Fn(PagesClass, Access, RowEnds) -> Verdict, +) -> FdBlocksTake { + let mut pending = false; + for rows in RowEnds::ALL { + match verdict(PagesClass::FdBlocks, Access::Reads, rows) { + Verdict::Passed => {} + Verdict::Pending => pending = true, + Verdict::Failed | Verdict::Unchecked => { + return FdBlocksTake::Refused(Access::Reads, rows) + } + } + } + for access in Access::ALL { + for rows in RowEnds::ALL { + let plain = verdict(PagesClass::Pooled, access, rows); + let exportable = verdict(PagesClass::FdBlocks, access, rows); + match (plain, exportable) { + (Verdict::Pending, _) | (Verdict::Passed, Verdict::Pending) => pending = true, + (Verdict::Passed, Verdict::Failed | Verdict::Unchecked) => { + return FdBlocksTake::Refused(access, rows) + } + (Verdict::Passed, Verdict::Passed) | (Verdict::Failed | Verdict::Unchecked, _) => {} + } + } + } + match pending { + true => FdBlocksTake::Pending, + false => FdBlocksTake::Take, + } +} + /// The version of what the check does, of the images over host pages it checks as the product /// makes them (their usage, layout and moves), and of how a record of it is named and framed: a /// change to any of them bumps it, and a record of another version is never read (its name @@ -1175,6 +1251,26 @@ impl Device { verdict } + /// Whether the runtime's own buffers lie in blocks allocated exportable (`memory.rs`'s + /// "Buffers in exportable blocks"), by the device's verdicts ([`fd_blocks_take`]), asked as + /// such a buffer is made: a pending verdict starts the check, and the buffer lies in a plain + /// block meanwhile, as it does where the verdicts refuse such blocks; each counted + /// (`WorkCounts::fd_blocks_awaited`, `WorkCounts::fd_blocks_refused`). Never waits. + pub(crate) fn fd_blocks_checked(&self) -> bool { + let verdict = |class, access, rows| self.in_place_verdict(class, access, rows); + match fd_blocks_take(verdict) { + FdBlocksTake::Take => true, + FdBlocksTake::Pending => { + self.shared().counts.fd_blocks_awaited(); + false + } + FdBlocksTake::Refused(..) => { + self.shared().counts.fd_blocks_refused(); + false + } + } + } + /// Start the device's check of textures over host pages in place where its verdicts are /// pending and no check started, and wait until every verdict is known or `timeout` passed: /// whether they are. A runtime extension: Metal has no such check, as a Mac's GPU works on a diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index 719873311..7d561dbb6 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -172,6 +172,7 @@ use crate::buffer_descriptor::MemoryExport; use crate::check_draw::CheckDraw; use crate::device::holds::Holder; +use crate::device::lock; use crate::exit_guard; use crate::host_memory::HostMemory; use crate::in_place::{ @@ -179,7 +180,7 @@ use crate::in_place::{ Verdict, }; use crate::linear_plan::BufferLayout; -use crate::memory::{BoundMemory, NoImage}; +use crate::memory::{BoundMemory, Holds, NoImage}; use crate::values::ResourceOptions; use crate::{ AddressPlacement, Buffer, BufferContents, BufferDescriptor, ClearColor, CommandQueue, Device, @@ -452,7 +453,7 @@ const POOLED_BYTES: u64 = 24 << 20; /// The bytes of `class`'s buffer. fn class_bytes(class: PagesClass) -> u64 { match class { - PagesClass::Pooled => POOLED_BYTES, + PagesClass::Pooled | PagesClass::FdBlocks => POOLED_BYTES, PagesClass::Pointer | PagesClass::Fresh | PagesClass::DmaBuf @@ -1384,7 +1385,7 @@ impl ClassPages { let why = "the device makes no DRM_FORMAT_MOD_LINEAR images"; return Err(Unmade::lasting(why)); } - let buffer = (device.pooled_check_buffer(length)) + let buffer = (device.pooled_check_buffer(length, Holds::Buffers)) .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"; @@ -1396,6 +1397,31 @@ impl ClassPages { } PagesClass::ExportedFd => exported_pages(device, MemoryExport::OpaqueFd, length), PagesClass::ExportedDmaBuf => exported_pages(device, MemoryExport::DmaBuf, length), + // A buffer of the runtime's own in a block of the kind its buffers take where the + // device allocates their blocks exportable (`memory.rs`'s `Holds::FdBuffers`), whatever + // this class's verdicts, which decide whether they lie there + // (`Device::fd_blocks_checked`), that declares the bytes between a texture's rows + // unobserved, as the product's buffers whose textures take a `DRM_FORMAT_MOD_LINEAR` + // image do: its textures take the images a texture over such a buffer takes + // (`texture.rs`'s `alias_image`). + PagesClass::FdBlocks => { + let exportable = lock(&device.shared().memory).fd_buffer_types; + if let Err(why) = exportable { + return Err(Unmade::lasting(why)); + } + let buffer = (device.pooled_check_buffer(length, Holds::FdBuffers)) + .map_err(|error| Unmade::of_error("its buffer was refused", &error))?; + match buffer.bound_memory() { + BoundMemory::Blocks(_) => {} + _ => { + let why = "its buffer lies in no block allocated exportable"; + return Err(Unmade::passing(why)); + } + } + buffer.declare_padding_unobserved(); + let start = contents(&buffer)?; + Ok(ClassPages { buffer, start }) + } } } } @@ -1429,7 +1455,9 @@ fn exported_pages( BoundMemory::External(_) => {} BoundMemory::NoImage(NoImage::Dedicated) if export == MemoryExport::DmaBuf => {} BoundMemory::NoImage(no) => return Err(Unmade::lasting(no.words())), - BoundMemory::Own => return Err(Unmade::passing("its buffer's memory is not exported")), + BoundMemory::Own | BoundMemory::Blocks(_) => { + return Err(Unmade::passing("its buffer's memory is not exported")) + } } buffer.declare_padding_unobserved(); let start = contents(&buffer)?; diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index ce73655c9..bde6e4b64 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -302,9 +302,10 @@ enum Exportable { /// 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, + /// The handle types of the runtime's own buffers' blocks ([`Memory::fd_handles`]): an opaque + /// file descriptor ([`EXPORT_HANDLE`]), and a dma-buf where the device takes both, never + /// exported: a block of [`Holds::FdBuffers`] of a memory type [`fd_buffer_types`] names. + Fd(vk::ExternalMemoryHandleTypeFlags), } impl Exportable { @@ -313,7 +314,7 @@ impl Exportable { match self { Exportable::No => None, Exportable::For(_, exported) => Some(exported.handle), - Exportable::Fd => Some(EXPORT_HANDLE), + Exportable::Fd(handles) => Some(handles), } } } @@ -1130,9 +1131,9 @@ 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`]). + /// It was allocated exportable as the runtime's own buffers' handle types + /// ([`Memory::fd_handles`]) and is never exported ([`Holds::FdBuffers`]): an image bound in + /// it names one of them ([`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`]). @@ -1147,6 +1148,10 @@ pub(super) enum BoundMemory { Own, /// Memory exported or imported as this handle type, which an image bound in it names. External(vk::ExternalMemoryHandleTypeFlags), + /// A block of the runtime's own buffers allocated exportable as these handle types and never + /// exported ([`Holds::FdBuffers`]): an image bound in it names one of them, that its image + /// format query takes for it (`VUID-vkBindImageMemory-memory-02728`). + Blocks(vk::ExternalMemoryHandleTypeFlags), /// Memory no image of the runtime's is bound in. NoImage(NoImage), } @@ -1168,6 +1173,7 @@ impl std::fmt::Debug for BoundMemory { match self { BoundMemory::Own => f.write_str("Own"), BoundMemory::External(handle) => write!(f, "External({:#x})", handle.as_raw()), + BoundMemory::Blocks(handles) => write!(f, "Blocks({:#x})", handles.as_raw()), BoundMemory::NoImage(no) => write!(f, "NoImage({no:?})"), } } @@ -1606,12 +1612,19 @@ 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. + /// As `address_types`, of a buffer of addresses made for [`Memory::fd_handles`], 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`]). pub(super) fd_buffer_types: Result, + /// The handle types those blocks are allocated exportable as, never exported: an opaque file + /// descriptor ([`EXPORT_HANDLE`]), and a dma-buf ([`DMA_BUF_HANDLE`]) where the device + /// exports pooled memory of the runtime's buffers' usages as both, each compatible with the + /// other (`VUID-VkExportMemoryAllocateInfo-handleTypes-00656`): an image bound there names + /// one of them its image format query takes for it (`VUID-vkBindImageMemory-memory-02728`, + /// [`BoundMemory::Blocks`]). + pub(super) fd_handles: vk::ExternalMemoryHandleTypeFlags, fd_blocks: FdBlocks, /// The pools the runtime's encodings and commits place their own resources in, once asked /// ([`Memory::kept`], [`keep_room`]). @@ -1774,6 +1787,7 @@ impl Memory { address_types: None, fd_address_types: None, fd_buffer_types: Err("the device was not asked for exportable buffer memory"), + fd_handles: EXPORT_HANDLE, fd_blocks: FdBlocks::default(), kept: None, unified, @@ -1819,30 +1833,37 @@ impl Memory { } /// 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) { + /// exportable as `handles` 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 an opaque file descriptor and places them there once the device's check of + /// such blocks passed ([`Memory::own_buffers`]). + pub(super) fn fd_buffer_blocks( + &mut self, + types: Result, + handles: vk::ExternalMemoryHandleTypeFlags, + ) { 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" + as handle types {:#x} once the device's check of them passed", + handles.as_raw() ), Err(why) => format!("the runtime's own buffers lie in plain blocks: {why}"), }); } self.fd_buffer_types = types; + self.fd_handles = handles; } /// 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 { + /// exportable ([`Memory::fd_buffer_blocks`]) and its check of such blocks passed (`checked`, + /// `in_place.rs`'s `Device::fd_blocks_checked`), else [`Holds::Buffers`]. + pub(super) fn own_buffers(&self, checked: bool) -> Holds { match self.fd_buffer_types { - Ok(_) => Holds::FdBuffers, - Err(_) => Holds::Buffers, + Ok(_) if checked => Holds::FdBuffers, + Ok(_) | Err(_) => Holds::Buffers, } } @@ -2193,7 +2214,7 @@ impl Memory { /// 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`]. + /// buffer made for their handle types ([`Memory::fd_handles`]). fn address_types(&mut self, device: &ash::Device, holds: Holds) -> Result, Error> { if !self.device_address { return Ok(None); @@ -2207,7 +2228,7 @@ impl Memory { return Ok(Some(types)); } let sharing = Sharing::with_buffers(&self.families, &self.buffer_families); - let handle = fd.then_some(EXPORT_HANDLE); + let handle = fd.then_some(self.fd_handles); let types = buffer_types(device, usage(true), sharing, handle)?; match fd { true => self.fd_address_types = Some(types), @@ -2329,6 +2350,7 @@ impl Memory { block_bytes: self.block_bytes, host_visible, fd_types: self.fd_buffer_types.unwrap_or(0), + fd_handles: self.fd_handles, device_address: self.device_address, families: self.buffer_families.clone(), zero_images: self.zero_images, @@ -2455,7 +2477,7 @@ impl Memory { if payload.addresses.is_some() { return Ok(()); } - let handle = payload.fd.then_some(EXPORT_HANDLE); + let handle = payload.fd.then_some(self.fd_handles); let (raw, required) = address_buffer(device, payload.size, sharing, handle)?; if required > payload.size { // SAFETY: the buffer is unused. @@ -2764,7 +2786,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.fd => BoundMemory::Blocks(self.fd_handles), None if block.imported || block.pages.is_some() || block.view.is_some() => { BoundMemory::External(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT) } @@ -2843,6 +2865,8 @@ struct BlockMaker { host_visible: u32, /// The memory types whose [`Holds::FdBuffers`] blocks are allocated exportable, as bits. fd_types: u32, + /// The handle types they are allocated exportable as ([`Memory::fd_handles`]). + fd_handles: vk::ExternalMemoryHandleTypeFlags, /// As [`Memory`]'s. device_address: bool, /// The families its buffers of addresses are shared among: [`Memory`]'s buffers'. @@ -2856,9 +2880,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`]), or as an opaque - /// file descriptor where it is a block of [`Holds::FdBuffers`] of a memory type - /// [`fd_buffer_types`] names. + /// the handle type of the exportable buffers it holds ([`Holds::handle`]), or as the runtime's + /// own buffers' handle types ([`Memory::fd_handles`]) where it is a block of + /// [`Holds::FdBuffers`] of a memory type [`fd_buffer_types`] names. fn make( &self, device: &ash::Device, @@ -2876,7 +2900,7 @@ impl BlockMaker { }, ), None if holds == Holds::FdBuffers && self.fd_types & 1 << type_index != 0 => { - Exportable::Fd + Exportable::Fd(self.fd_handles) } None => Exportable::No, }; @@ -2991,9 +3015,9 @@ impl BlockMaker { type_index, exported: match export { Exportable::For(_, exported) => Some(exported), - Exportable::No | Exportable::Fd => None, + Exportable::No | Exportable::Fd(_) => None, }, - fd: matches!(export, Exportable::Fd), + fd: matches!(export, Exportable::Fd(_)), zeroed, }) } diff --git a/crates/metal2vulkan-runtime/src/tests/exported_textures.rs b/crates/metal2vulkan-runtime/src/tests/exported_textures.rs index 46c119df1..c72317940 100644 --- a/crates/metal2vulkan-runtime/src/tests/exported_textures.rs +++ b/crates/metal2vulkan-runtime/src/tests/exported_textures.rs @@ -37,13 +37,14 @@ //! 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. +//! export, its rows' padding declared unobserved as the consumer's caches declare it. One made +//! before the device's in-place check answered lies in a plain block. Once it answered, where the +//! device allocates its buffers' blocks exportable and the check passed them (`memory.rs`'s +//! "Buffers in exportable blocks", `in_place.rs`'s `fd_blocks_take`), 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 is in place, its image naming one of the +//! block's handle types, the layer reporting nothing; elsewhere its memory is a plain block, +//! each plane in place or the shadow the check decided. Each reads the same bytes. //! //! Printed (`EXPORTED-TEXTURES`): what the device exported, and for each plane its image's //! alignment, row pitch and size as `vkGetImageMemoryRequirements` and `vkGetImageSubresourceLayout` @@ -64,6 +65,7 @@ use crate::{ }; use ash::vk; use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use std::time::Duration; /// The byte the luma plane starts at: a header's 32 bytes in, as the consumer's cache lays it. const LUMA_AT: u64 = 32; @@ -694,21 +696,50 @@ fn an_nv12_picture_s_planes_over_a_buffer_of_the_runtime_s_own_name_its_block_s_ 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 made = BufferDescriptor::new(LENGTH, options, BufferContents::Zero) + let (types, handles) = { + let memory = crate::device::lock(&device.shared().memory); + (memory.fd_buffer_types, memory.fd_handles) + }; + eprintln!( + "EXPORTED-TEXTURES on {name}: the blocks of the runtime's own buffers: {types:?}, \ + exportable as {:#x}", + handles.as_raw() + ); + let descriptor_of = |options| { + BufferDescriptor::new(LENGTH, options, BufferContents::Zero) .with_aligned_byte(LUMA_AT) - .with_padding_unobserved(); - let picture = device.new_buffer_with_descriptor(made).unwrap(); + .with_padding_unobserved() + }; + // Made before the device's check answered: a plain block, whatever the check answers. + let early = + (device.new_buffer_with_descriptor(descriptor_of(ResourceOptions::shared()))).unwrap(); + let verdicts_known = device.settle_in_place_checks(Duration::ZERO); + if !verdicts_known { + assert!( + early.bound_memory() == BoundMemory::Own, + "made while the check was pending" + ); + } + assert!(device.settle_in_place_checks(WAIT), "the check answered"); + let verdict = |class, access, rows| device.in_place_verdict(class, access, rows); + let take = crate::in_place::fd_blocks_take(verdict); + let exportable = types.is_ok() && take == crate::in_place::FdBlocksTake::Take; + eprintln!( + "EXPORTED-TEXTURES on {name}: the check of exportable blocks: {take:?} (known at once \ + {verdicts_known}); awaited {}, refused {}", + device.work_counts().fd_blocks_awaited, + device.work_counts().fd_blocks_refused + ); + for options in [ResourceOptions::private(), ResourceOptions::shared()] { + let picture = device + .new_buffer_with_descriptor(descriptor_of(options)) + .unwrap(); let (bound, counts) = (picture.bound_memory(), device.work_counts()); - match types { - Ok(_) => { - let fd = BoundMemory::External(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD); + match exportable { + true => { assert!( - bound == fd, - "{options:?}: a block exportable as an opaque fd" + bound == BoundMemory::Blocks(handles), + "{options:?}: {bound:?}" ); assert!( counts.fd_buffer_blocks_made > 0, @@ -725,25 +756,20 @@ fn an_nv12_picture_s_planes_over_a_buffer_of_the_runtime_s_own_name_its_block_s_ "{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"); + false => { + assert!( + bound == BoundMemory::Own, + "{options:?}: a plain block, {bound:?}" + ); + if types.is_err() { + let made = (counts.fd_buffer_blocks_made, counts.fd_buffer_blocks_plain); + assert_eq!(made, (0, 0), "{options:?}: no block of such buffers"); + let asked = (counts.fd_blocks_awaited, counts.fd_blocks_refused); + assert_eq!(asked, (0, 0), "{options:?}: no check of such blocks asked"); + } } } 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(); @@ -760,13 +786,23 @@ fn an_nv12_picture_s_planes_over_a_buffer_of_the_runtime_s_own_name_its_block_s_ "{options:?} {plane:?}: in place, or a shadow the device's check decided: \ {placement:?}" ); + // Where the buffers lie in such blocks, every plane is in place as over a plain + // block's buffer: the device's linear image, or the DRM_FORMAT_MOD_LINEAR one the + // check passed. + if exportable { + assert_eq!( + placement, + TexturePlacement::NotHostPages, + "{options:?} {plane:?}" + ); + } 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" + "{options:?} {plane:?}: the texels, read as made" ); eprintln!( "EXPORTED-TEXTURES on {name}: a buffer of the runtime's own, {options:?} {:?} \ @@ -776,7 +812,7 @@ fn an_nv12_picture_s_planes_over_a_buffer_of_the_runtime_s_own_name_its_block_s_ } } watched.layer_reported_nothing( - "buffers and textures in blocks exportable as opaque fds name the handle type \ + "buffers and textures in blocks allocated exportable name one of their handle types \ (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 04b2d30a4..0839f64b1 100644 --- a/crates/metal2vulkan-runtime/src/tests/memory.rs +++ b/crates/metal2vulkan-runtime/src/tests/memory.rs @@ -287,6 +287,64 @@ fn own_buffer_blocks_are_exportable_in_a_unified_device_s_system_heap() { assert!(fd_buffer_types(&anv, true, Ok(())).is_err()); } +/// The device's verdicts decide whether the runtime's buffers lie in blocks allocated exportable +/// (`in_place.rs`'s `fd_blocks_take`): the first move of the class's linear image must pass for +/// both row ends, and the class must pass wherever plain pooled memory passed; a pending verdict +/// that decides it leaves them in plain blocks meanwhile. +#[test] +fn exportable_blocks_take_what_plain_blocks_take() { + use crate::in_place::{fd_blocks_take, Access, FdBlocksTake, PagesClass, RowEnds, Verdict}; + // Every verdict of a class, but those `except` gives. + let all = |class: PagesClass, verdict: Verdict| { + move |of: PagesClass, + access: Access, + rows: RowEnds, + except: &[(Access, RowEnds, Verdict)]| { + match of == class { + true => (except.iter()) + .find(|(a, r, _)| *a == access && *r == rows) + .map_or(verdict, |(_, _, v)| *v), + false => Verdict::Unchecked, + } + } + }; + let take = |plain: Verdict, exportable: Verdict, except: &[(Access, RowEnds, Verdict)]| { + fd_blocks_take(|class, access, rows| match class { + PagesClass::Pooled => all(PagesClass::Pooled, plain)(class, access, rows, &[]), + PagesClass::FdBlocks => { + all(PagesClass::FdBlocks, exportable)(class, access, rows, except) + } + _ => Verdict::Unchecked, + }) + }; + use Verdict::{Failed, Passed, Pending, Unchecked}; + assert_eq!(take(Passed, Passed, &[]), FdBlocksTake::Take); + // Plain pooled memory unchecked (no DRM_FORMAT_MOD_LINEAR images): the first move decides. + assert_eq!(take(Unchecked, Passed, &[]), FdBlocksTake::Take); + assert_eq!(take(Unchecked, Pending, &[]), FdBlocksTake::Pending); + assert_eq!(take(Pending, Passed, &[]), FdBlocksTake::Pending); + let (reads, on) = (Access::Reads, RowEnds::OnLines); + assert_eq!( + take(Unchecked, Passed, &[(reads, on, Failed)]), + FdBlocksTake::Refused(reads, on) + ); + assert_eq!( + take(Unchecked, Passed, &[(reads, on, Unchecked)]), + FdBlocksTake::Refused(reads, on) + ); + // An access plain memory passed and the class did not. + let renders = (Access::Renders, RowEnds::InLines); + assert_eq!( + take(Passed, Passed, &[(renders.0, renders.1, Failed)]), + FdBlocksTake::Refused(renders.0, renders.1) + ); + // One plain memory did not pass either: nothing lost. + assert_eq!( + take(Failed, Passed, &[(renders.0, renders.1, Failed)]), + FdBlocksTake::Take + ); +} + /// 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/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 186e4ac89..d0e4dcc59 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -83,10 +83,10 @@ use super::host_bytes::HostBytes; use super::image_plan::{ check_image_limits, plan_image, AnyViews, DepthImageFacts, ImageFacts, ImagePlan, ImageRefusal, }; -use super::in_place::{self, PagesClass, Refusal, ShadowCause}; +use super::in_place::{self, Access, PagesClass, Refusal, ShadowCause, Verdict}; use super::key_hash::KeyMap; use super::linear_plan::{aliases, check_linear_limits, linear_lack, LinearImage, LinearLack}; -use super::memory::{BoundMemory, MemoryClass, Placement}; +use super::memory::{BoundMemory, MemoryClass, Placement, DMA_BUF_HANDLE, EXPORT_HANDLE}; use super::nan_clear; use super::neutral::Neutrals; use super::pvrtc::{ @@ -2907,6 +2907,15 @@ impl Device { /// 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. + /// - In a block of the runtime's buffers allocated exportable and never exported + /// (`memory.rs`'s "Buffers in exportable blocks"): the same two images, the linear one made + /// for the first of the block's handle types the device's image format query takes for it + /// without a dedicated allocation (an opaque file descriptor, then a dma-buf) and the + /// `DRM_FORMAT_MOD_LINEAR` one for the first it takes for that (a dma-buf, then an opaque + /// file descriptor), each so made `UNDEFINED`: the linear one where the device's check of + /// such blocks ([`PagesClass::FdBlocks`]) passed its first move for texels that lie in its + /// lines as these do ([`Device::blocks_linear_image`]), the other where it passed each + /// access the usage takes, as of plain pooled memory ([`Device::pooled_pitched_image`]). /// - 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`). @@ -2921,8 +2930,15 @@ impl Device { usage: TextureUsage, facts: &ImageFacts<'_>, ) -> Result, Error> { + // The handle types of a block of the runtime's buffers allocated exportable, where the + // buffer lies in one. + let mut blocks = None; let memory = match texels.buffer.bound_memory() { BoundMemory::Own => ModifierMemory::Own, + BoundMemory::Blocks(handles) => { + blocks = Some(handles); + ModifierMemory::Own + } BoundMemory::External(handle) => { let Some(class) = PagesClass::exported(handle) else { let why = format!( @@ -2986,16 +3002,19 @@ impl Device { // SAFETY: the image is live and unbound, and no command uses it. unsafe { release::object(raw_device, made.raw) }; }; - let linear = if in_place::checking() && memory == ModifierMemory::Own { + let linear = if in_place::checking() && memory == ModifierMemory::Own && blocks.is_none() { Err("the device's check of its pooled memory makes no linear image".to_owned()) } else if let Some(LinearLack { format, features }) = linear_lack(plan, facts) { Err(LinearRefusal::Need(LinearNeed::Features { format, features }).describe(plan)) } else { - let made = match memory { - ModifierMemory::Own => self.linear_image(plan)?, - _ => self.external_linear_image(plan, memory)?, - }; - made.map_err(|refusal| refusal.describe(plan)) + match (memory, blocks) { + (_, Some(handles)) => self.blocks_linear_image(plan, texels, handles)?, + (ModifierMemory::Own, None) => { + (self.linear_image(plan)?).map_err(|refusal| refusal.describe(plan)) + } + (_, None) => (self.external_linear_image(plan, memory)?) + .map_err(|refusal| refusal.describe(plan)), + } }; let linear = match linear { Ok(made) => match elsewhere(&made) { @@ -3007,9 +3026,17 @@ impl Device { }, Err(why) => format!("the device makes no linear image of the texture: {why}"), }; - let pitched = match memory { - ModifierMemory::Own => self.pooled_pitched_image(plan, texels, usage, facts)?, - _ => (self.pitched_image(plan, &texels.layout, facts, memory)?) + let pitched = match (memory, blocks) { + (_, Some(handles)) => { + let memories = blocks_memories(handles, [DMA_BUF_HANDLE, EXPORT_HANDLE]); + let pooled = (PagesClass::FdBlocks, &memories[..]); + self.pooled_pitched_image(plan, texels, usage, facts, pooled)? + } + (ModifierMemory::Own, None) => { + let pooled = (PagesClass::Pooled, &[ModifierMemory::Own][..]); + self.pooled_pitched_image(plan, texels, usage, facts, pooled)? + } + (_, None) => (self.pitched_image(plan, &texels.layout, facts, memory)?) .map_err(|(refusal, why)| ShadowCause::Refused(refusal, why)), }; Ok(match pitched { @@ -3198,13 +3225,16 @@ impl Device { } /// A `DRM_FORMAT_MOD_LINEAR` image of `plan` over `texels` in their buffer's pooled memory, its - /// one plane at Metal's pitch (`VkImageDrmFormatModifierExplicitCreateInfoEXT`), no external - /// memory (`dma_buf::ModifierMemory::Own`), unbound and made `UNDEFINED` + /// one plane at Metal's pitch (`VkImageDrmFormatModifierExplicitCreateInfoEXT`), made for the + /// first of `memories` the device makes it for: no external memory + /// (`dma_buf::ModifierMemory::Own`) in a plain block, of class [`PagesClass::Pooled`], and a + /// handle type of the block in one allocated exportable, of class [`PagesClass::FdBlocks`] + /// (`memory.rs`'s "Buffers in exportable blocks"); unbound and made `UNDEFINED` /// (`Device::pitched_image`), for a texture of Metal `usage` whose texels the device's own /// linear image lays out otherwise: where the device makes such images, the texture's rows to /// their pitch take no more than `in_place::POOLED_PITCHED_BYTES` (past it, a linear image - /// renders and samples slower than the shadow), and its policy and its check of the pooled - /// class ([`PagesClass::Pooled`]) take each access the usage takes + /// renders and samples slower than the shadow), and its policy and its check of `class` take + /// each access the usage takes /// for texels that lie in its lines as these do (`in_place::in_place`; a pending verdict /// starts the check, and the texture is a shadow meanwhile); the check's own textures whatever /// the verdicts. Why not. @@ -3227,6 +3257,7 @@ impl Device { texels: &Texels, usage: TextureUsage, facts: &ImageFacts<'_>, + (class, memories): (PagesClass, &[ModifierMemory]), ) -> Result, Error> { if !self.makes_modifier_images() { return Ok(Err(ShadowCause::Refused( @@ -3248,7 +3279,7 @@ impl Device { } let line = self.shared().in_place.line(); let pages = ( - PagesClass::Pooled, + class, texels.rows(line), texels.texel_bytes(), texels.padding(line), @@ -3259,9 +3290,57 @@ impl Device { return Ok(Err(cause)); } } - let own = crate::dma_buf::ModifierMemory::Own; - let made = self.pitched_image(plan, &texels.layout, facts, own)?; - Ok(made.map_err(|(refusal, why)| ShadowCause::Refused(refusal, why))) + // The first of `memories` the device makes such an image for. + let mut refused = None; + for &memory in memories { + match self.pitched_image(plan, &texels.layout, facts, memory)? { + Ok(made) => return Ok(Ok(made)), + Err(refusal) => refused = refused.or(Some(refusal)), + } + } + let (refusal, why) = refused.unwrap_or(( + Refusal::Image, + "no handle type of the buffer's block takes such an image".to_owned(), + )); + Ok(Err(ShadowCause::Refused(refusal, why))) + } + + /// The device's linear image of `plan` over `texels` in a block of the runtime's buffers + /// allocated exportable as `handles` (`memory.rs`'s "Buffers in exportable blocks"), + /// unbound, made for the first of them the device's image format query takes for it without + /// a dedicated allocation (an opaque file descriptor, then a dma-buf), which an image bound + /// there names (`VUID-vkBindImageMemory-memory-02728`), and so made `UNDEFINED` + /// (`VUID-VkImageCreateInfo-pNext-01443`): where the device's check of such blocks + /// ([`PagesClass::FdBlocks`]) passed that move for texels that lie in its lines as these do, + /// as it did wherever the device's buffers lie there (`in_place.rs`'s `fd_blocks_take`); the + /// check's own textures whatever its verdicts. Why not. + fn blocks_linear_image( + &self, + plan: &ImagePlan, + texels: &Texels, + handles: vk::ExternalMemoryHandleTypeFlags, + ) -> Result, Error> { + if !in_place::checking() { + let rows = texels.rows(self.shared().in_place.line()); + let verdict = self.in_place_verdict(PagesClass::FdBlocks, Access::Reads, rows); + if verdict != Verdict::Passed { + return Ok(Err(format!( + "its image over {} names a handle type and starts UNDEFINED, whose first move \ + the device's check of that memory answered {verdict:?} for texels of {rows:?}", + PagesClass::FdBlocks.words() + ))); + } + } + let mut refused = None; + for memory in blocks_memories(handles, [EXPORT_HANDLE, DMA_BUF_HANDLE]) { + match self.external_linear_image(plan, memory)? { + Ok(made) => return Ok(Ok(made)), + Err(refusal) => refused = refused.or(Some(refusal.describe(plan))), + } + } + Ok(Err(refused.unwrap_or_else(|| { + "no handle type of the buffer's block takes such an image".to_owned() + }))) } /// The linear image of `plan` aliasing `texels` in their buffer's memory (the runtime's own), @@ -7231,3 +7310,16 @@ impl Upload<'_> { } } } + +/// The memories of `handles`, a block of the runtime's buffers allocated exportable +/// (`memory.rs`'s "Buffers in exportable blocks"), an image bound there may be made for, in +/// `order`: one per handle type of `order` that `handles` holds. +fn blocks_memories( + handles: vk::ExternalMemoryHandleTypeFlags, + order: [vk::ExternalMemoryHandleTypeFlags; 2], +) -> Vec { + (order.into_iter()) + .filter(|&handle| handles.contains(handle)) + .map(ModifierMemory::Exported) + .collect() +} diff --git a/crates/metal2vulkan-runtime/src/texture/ycbcr_planes.rs b/crates/metal2vulkan-runtime/src/texture/ycbcr_planes.rs index 0905aa63a..7db86f382 100644 --- a/crates/metal2vulkan-runtime/src/texture/ycbcr_planes.rs +++ b/crates/metal2vulkan-runtime/src/texture/ycbcr_planes.rs @@ -60,14 +60,20 @@ pub(crate) enum KeptTexels { Memory, /// The driver's image lays the planes out otherwise, or does not fit the buffer there. Layout, + /// The planes lie in a block of the runtime's buffers allocated exportable and never + /// exported (`memory.rs`'s "Buffers in exportable blocks"), whose image would name one of its + /// handle types (`VUID-vkBindImageMemory-memory-02728`) and so start `UNDEFINED`, which the + /// device's check of such blocks covers for single-plane images alone. + ExportableBlock, } impl KeptTexels { /// The reasons, in their counters' order. - pub(crate) const ALL: [KeptTexels; 3] = [ + pub(crate) const ALL: [KeptTexels; 4] = [ KeptTexels::Conversion, KeptTexels::Memory, KeptTexels::Layout, + KeptTexels::ExportableBlock, ]; } @@ -132,8 +138,11 @@ impl Device { else { return Ok(Err(KeptTexels::Conversion)); }; - let own = texels.buffer.bound_memory() == crate::memory::BoundMemory::Own; - if texels.buffer.caller_memory().is_some() || !own { + let bound = texels.buffer.bound_memory(); + if let crate::memory::BoundMemory::Blocks(_) = bound { + return Ok(Err(KeptTexels::ExportableBlock)); + } + if texels.buffer.caller_memory().is_some() || bound != crate::memory::BoundMemory::Own { return Ok(Err(KeptTexels::Memory)); } let [luma_at, luma_row] = planes.luma.map(u64::from); diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index b40da455d..6a3d17830 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -154,7 +154,9 @@ pub(crate) struct Counters { ycbcr_textures_in_place: AtomicU64, ycbcr_images_kept: [AtomicU64; 7], ycbcr_planes_images: AtomicU64, - ycbcr_planes_images_kept: [AtomicU64; 3], + fd_blocks_awaited: AtomicU64, + fd_blocks_refused: AtomicU64, + ycbcr_planes_images_kept: [AtomicU64; 4], ycbcr_device_conversions: AtomicU64, ycbcr_device_samples: AtomicU64, attachment_clears_recorded: AtomicU64, @@ -1727,6 +1729,18 @@ impl Counters { self.ycbcr_planes_images.fetch_add(1, Ordering::Relaxed); } + /// A buffer of the runtime's own lay in a plain block while the device's check of its + /// exportable blocks was pending (`in_place.rs`'s `Device::fd_blocks_checked`). + pub(crate) fn fd_blocks_awaited(&self) { + self.fd_blocks_awaited.fetch_add(1, Ordering::Relaxed); + } + + /// A buffer of the runtime's own lay in a plain block, the device's check of its exportable + /// blocks having refused them (`in_place.rs`'s `fd_blocks_take`). + pub(crate) fn fd_blocks_refused(&self) { + self.fd_blocks_refused.fetch_add(1, Ordering::Relaxed); + } + /// A two-plane YCbCr texture's planes read in place were made no image the device's /// conversion samples, for `kept` (`texture/ycbcr_planes.rs`). pub(crate) fn ycbcr_planes_image_kept(&self, kept: crate::texture::KeptTexels) { @@ -5048,6 +5062,15 @@ pub struct WorkCounts { /// memory type of a device-local heap, which such buffers overflowed into or their class /// takes first. pub fd_buffer_blocks_plain: u64, + /// The buffers of the runtime's own and the program's made so far in a plain block, not one + /// allocated exportable, on a device that allocates such blocks, while the device's in-place + /// check of them was pending (`in_place.rs`'s `Device::fd_blocks_checked`): its first run on a + /// driver, before the check's record holds its verdicts. 0 once they are known. + pub fd_blocks_awaited: u64, + /// As `fd_blocks_awaited`, once the device's check of such blocks found a texture over one's + /// buffer would be a shadow where over a plain block's it is not (`in_place.rs`'s + /// `fd_blocks_take`): every such buffer from then on. + pub fd_blocks_refused: 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, @@ -5237,6 +5260,12 @@ pub struct WorkCounts { /// Two-plane YCbCr textures whose planes read in place take no such image because the driver's /// image lays the planes out otherwise than the surface, or does not fit their buffer there. pub ycbcr_planes_images_kept_layout: u64, + /// Two-plane YCbCr textures whose planes read in place take no such image because the planes + /// lie in a block of the runtime's buffers allocated exportable (`memory.rs`'s "Buffers in + /// exportable blocks"), whose image would start `UNDEFINED`, which the device's in-place check + /// covers for single-plane images alone: the texel buffer reads them, announced + /// (`ycbcr-planes-exportable-block`). + pub ycbcr_planes_images_kept_exportable_block: u64, /// Bindings of two-plane YCbCr textures' planes images written into descriptor sets. pub ycbcr_planes_images_bound: u64, /// Two-plane YCbCr textures made whose conversions sample the planes' image through the @@ -8181,12 +8210,16 @@ impl Device { ycbcr_images_kept_view: counters.ycbcr_images_kept[6].load(Ordering::Relaxed), ycbcr_planes_bound: commands(|counts| &counts.ycbcr_planes_bound), ycbcr_planes_images: counters.ycbcr_planes_images.load(Ordering::Relaxed), + fd_blocks_awaited: counters.fd_blocks_awaited.load(Ordering::Relaxed), + fd_blocks_refused: counters.fd_blocks_refused.load(Ordering::Relaxed), ycbcr_planes_images_kept_conversion: counters.ycbcr_planes_images_kept[0] .load(Ordering::Relaxed), ycbcr_planes_images_kept_memory: counters.ycbcr_planes_images_kept[1] .load(Ordering::Relaxed), ycbcr_planes_images_kept_layout: counters.ycbcr_planes_images_kept[2] .load(Ordering::Relaxed), + ycbcr_planes_images_kept_exportable_block: counters.ycbcr_planes_images_kept[3] + .load(Ordering::Relaxed), ycbcr_planes_images_bound: commands(|counts| &counts.ycbcr_planes_images_bound), ycbcr_device_conversions: counters.ycbcr_device_conversions.load(Ordering::Relaxed), ycbcr_device_samples: counters.ycbcr_device_samples.load(Ordering::Relaxed),