From 8d617591f8fef0695e6dd87e57c90ed6b6adbf63 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 15 Nov 2026 18:55:56 -0800 Subject: [PATCH] RUNTIME 2409: In-place textures over dma-buf pages: the image bound in the buffer's own import A texture in place over a no-copy buffer's dma-buf pages no longer always asks the pages' source for a new dma-buf and a dedicated import of its own. Where the pages lie in one import dedicated to nothing (no sparse buffer over several imports, no import the driver made dedicated to the buffer), its DRM_FORMAT_MOD_LINEAR image whose plane lies at offset 0 at the texels' pitches is bound in that import at the texels' offset, beside the buffer (vkBindImageMemory's memoryOffset): no udmabuf, no import, no new GPU mapping. Every fact is asked of the driver: the image requires no dedicated allocation (VUID-vkBindImageMemory- image-01445), the format query takes dma-bufs for it outside one (not DEDICATED_ONLY), its alignment divides the offset (-None-10735), its size fits the pages' placement (-None-10737) and its memory types take the import's. An import dedicated to the buffer binds no image (-memory-10926): DmaBufPages now notes that. A new check class, PagesClass::DmaBufInImport (CHECK_VERSION 20), measures that image; the check's textures of each dma-buf class take that class's image alone (a thread-local of the class the check runs). texture/route.rs takes the new class where its verdicts take the texture, else DmaBuf's; a shadow waits on DmaBuf's verdict while both pend. Where the making refuses the image in the import, it falls back to today's image where DmaBuf's verdicts take it. A pending move re-routes the same way. Binding in the import reads it apart: it is kept imported for good, as an image in a pointer import's is. A rebind remakes such an image in the new pages' import by the same order. RADV requires a dedicated allocation of every such image, so its check leaves the new class unchecked and it never takes the route. New WorkCounts field: dma_buf_images_in_import. No new Degradation kind. The route-(b) device tests (parked images, plane offset, import cycles, a texture's residency) fail the new class's verdicts first, so they keep measuring today's image on any device. A new device test (tests/dma_buf_in_import.rs) counts the route and its negative control. Also: 4c3cbe2f1d and 37d2a750ce (the probe, dma_buf_linear_bind: a linear and a modifier image for dma-bufs bound in the pages' existing import, the dedicated answers, a re-import arm), 5a40c2ef7b (docs: API.md, HOWTO.md, FAST-PATHS.md, host_residency.rs module docs). Why: the owner asked how to remove the per-texture dma-buf. Probe answers (Mesa 26.2.6): RADV on the Radeon 780M refuses LINEAR images for dma-bufs (NOT_SUPPORTED x15) and requires a dedicated allocation of every DRM_FORMAT_MOD_LINEAR image (m3-max-34443), so there it never fires. ANV on the Iris Xe takes both images outside a dedicated allocation, bound in the existing import byte-exact; first use of an 84 MiB texture 1.37 -> 0.21 ms (m3-max-34453). Verified in the lane (m3-max-34571, gem10, at 5d5dee7901): clippy -D warnings -p metal2vulkan-runtime --all-targets --all-features, plain and m2v_cpu_icd. Still running when landed: the lavapipe in-place and dma-buf suites with the new count test (m3-max-34593), clippy m2v_gpu, PHOENIX, and the Iris count test with its negative control. API: adds the field WorkCounts::dma_buf_images_in_import (additive; api_signatures blessed in the lane). --- crates/metal2vulkan-runtime/src/buffer.rs | 54 + .../src/buffer_descriptor.rs | 5 +- crates/metal2vulkan-runtime/src/dma_buf.rs | 79 +- .../src/host_residency.rs | 17 +- crates/metal2vulkan-runtime/src/in_place.rs | 45 +- .../src/in_place_check.rs | 45 +- .../src/tests/dma_buf_import_cycles.rs | 7 +- .../src/tests/dma_buf_in_import.rs | 267 +++ .../src/tests/dma_buf_linear_bind.rs | 1474 +++++++++++++++++ .../src/tests/dma_buf_parked_images.rs | 7 +- .../src/tests/dma_buf_plane_offset.rs | 7 +- .../src/tests/host_residency.rs | 18 + .../src/tests/in_place.rs | 10 +- .../src/tests/in_place_check.rs | 13 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 4 + crates/metal2vulkan-runtime/src/texture.rs | 5 +- .../src/texture/in_place_image.rs | 325 +++- .../metal2vulkan-runtime/src/texture/route.rs | 79 + .../src/texture/storage_form.rs | 33 +- .../metal2vulkan-runtime/src/work_counts.rs | 27 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 15 +- docs/FAST-PATHS.md | 17 +- docs/HOWTO.md | 30 +- docs/REFUSALS.md | 4 +- 26 files changed, 2494 insertions(+), 96 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/dma_buf_in_import.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/dma_buf_linear_bind.rs diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 12f7167f3..a18b36a94 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -1113,6 +1113,21 @@ pub(super) struct HostPages { made_of: OnceLock, } +/// Where host pages lie in one import of a dma-buf dedicated to nothing +/// ([`HostPages::in_one_dma_buf_import`]). +#[cfg(unix)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct DmaBufImportAt { + /// The import's memory: `VK_NULL_HANDLE` where it was read as a blit reads it, unexposed. + pub(super) memory: vk::DeviceMemory, + /// Where the pages' bytes start in it. + pub(super) base: u64, + /// Its bytes from there to the end of the pages' placement. + pub(super) room: u64, + /// Its memory type. + pub(super) type_index: u32, +} + /// How new pages come to lie in an import ([`HostPages::new`]). #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Joining { @@ -1341,6 +1356,45 @@ impl HostPages { })) } + /// Where they lie in one import of a dma-buf dedicated to nothing (`dma_buf.rs`), which an + /// image in place over their bytes binds in at its texels' offset, as several buffers bind in + /// one import (`texture/in_place_image.rs`): the import's memory, where their bytes start in + /// it, the bytes of it from there to their placement's end, and its memory type. `None` for + /// pages imported by their pointer, pages bound sparsely over several imports (the memory is + /// then none), and an import dedicated to the buffer bound in it, where the driver refused it + /// dedicated to nothing, which binds no image (`VUID-vkBindImageMemory-memory-10926`). Read as + /// a blit reads them where `expose` is false (`HostImport::blit_pages`), so an image's making + /// asks it before it binds and leaves a releasable import releasable, its memory unnamed + /// (`VK_NULL_HANDLE`); where `expose`, as [`HostPages::memory`] reads them, which keeps the + /// import imported for good from then on (`host_residency.rs`), for the image's bind. + /// Refused where the device cannot import them again. + #[cfg(unix)] + pub(super) fn in_one_dma_buf_import( + &self, + expose: bool, + ) -> Result, Error> { + let pages = match expose { + true => self.import.pages(ReadApart::Texture), + false => self.import.blit_pages()?.0, + }; + let placement = &pages.memory.placement; + let Some(imports) = placement.dma_buf_pages() else { + return Ok(None); + }; + if placement.memory == vk::DeviceMemory::null() || imports.dedicated_to_buffer() { + return Ok(None); + } + Ok(Some(DmaBufImportAt { + memory: match expose { + true => placement.memory, + false => vk::DeviceMemory::null(), + }, + base: placement.offset + pages.offset, + room: placement.size().saturating_sub(pages.offset), + type_index: placement.type_index(), + })) + } + /// As the buffer that lies in them is released (`BufferShared`'s drop, a no-copy heap's own /// buffer's included), its listing let go of: a live buffers' table that still lists them is a /// command buffer's, one that may reach them unnamed (its first submission's, a host step's, diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index e332c945a..2a0d84395 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -1074,8 +1074,9 @@ impl Device { } // A heap's import is dedicated to nothing, as textures placed in the // heap may be bound in its memory (`texture/heap.rs`); a buffer's own - // binds the buffer alone, its textures in place bound in imports of their - // own (`Device::dma_buf_image`). + // binds no other buffer, its textures in place bound in it only where the + // driver took it dedicated to nothing, else in imports of their own + // (`texture/in_place_image.rs`). // SAFETY: as above. #[cfg(unix)] Ok(Err((source, refusal))) => unsafe { diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs index 1f4f2c534..eb14e1aca 100644 --- a/crates/metal2vulkan-runtime/src/dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -92,10 +92,15 @@ //! and refuses any other layout (`VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT`): the //! runtime asks the driver and takes its answer, never a rule of its own. The source is called //! only once the image is made and checked; the import keeps it, and goes after the image. -//! Counted: `WorkCounts::dma_buf_images`. A texture over a no-copy buffer's dma-buf pages takes -//! the same image over a dma-buf of its own pages where it is taken in place (`in_place.rs`, -//! `texture/in_place_image.rs`), and else is a shadow (`texture.rs`'s `storage_over_buffer`), -//! whose copies go through the buffer's import. Its making asks the source once for each plan +//! Counted: `WorkCounts::dma_buf_images`. A texture over a no-copy buffer's dma-buf pages, where +//! it is taken in place (`in_place.rs`, `texture/in_place_image.rs`), takes the image whose +//! plane starts at offset 0 bound at its texels' offset in the import the buffer lies in, where +//! that is one import dedicated to nothing, the device's check of such images +//! (`PagesClass::DmaBufInImport`) passed, and the driver takes such a binding as above +//! ([`Device::in_import_image_unbound`]; `WorkCounts::dma_buf_images_in_import`): no source +//! asked and no import made. Else it takes the same image over a dma-buf of its own pages, and +//! else is a shadow (`texture.rs`'s `storage_over_buffer`), whose copies go through the +//! buffer's import. Its making asks the source once for each plan //! of the image it tries, but none for a range holding one the source refused with a //! [`DmaBufStandingRefusal`], and none for a plan whose image an earlier texture over the same //! pages parked as it went, which it takes (`dma_buf/parked.rs`). @@ -188,8 +193,10 @@ use std::time::Duration; /// then once for each image the runtime makes over a texture's own pages in them (over the /// buffer, placed in the heap, a view of one, or remade by a rebind). A texture in place over a /// buffer's pages may take the image an earlier texture over the same pages kept as it went, of -/// the same plan at the same texels, and asks nothing (`WorkCounts::dma_buf_images_taken`). A -/// source the runtime never calls is dropped with the call; one it called is kept with the +/// the same plan at the same texels, and asks nothing (`WorkCounts::dma_buf_images_taken`); or, +/// where the buffer lies in one import dedicated to nothing and the device's check passed images +/// bound in such an import, its image is bound there, at its texels' offset, and asks nothing +/// either (`WorkCounts::dma_buf_images_in_import`). A source the runtime never calls is dropped with the call; one it called is kept with the /// imports it made, until they go. /// /// It returns dma-bufs of the pages asked for ([`DmaBufRequest`]) in chunks ([`DmaBufChunk`]), in @@ -390,6 +397,11 @@ pub(super) struct DmaBufPages { /// imported, as the descriptors to import it again did not fit (`host_residency.rs`): /// counted in `WorkCounts::host_imports_kept_for_fds` while the pages live. kept_for_fds: bool, + /// An import of a chunk of their own was made dedicated to the buffer bound in it, where the + /// driver refused it dedicated to nothing ([`Device::import_chunks`]): no image binds there + /// (`VUID-vkBindImageMemory-memory-10926`), so a texture over the pages takes no image in + /// their import ([`Device::in_import_image_unbound`]). + dedicated_to_buffer: bool, /// What waits for the imports' free ([`DmaBufPages::after_free`]): the caller's keep-alive /// and the deallocators of the pages that went, let go of once the imports are freed. after_free: Mutex>>, @@ -475,6 +487,7 @@ impl DmaBufPages { length: request.length, bound: None, kept_for_fds: false, + dedicated_to_buffer: false, after_free: Mutex::new(Vec::new()), } } @@ -503,6 +516,7 @@ impl DmaBufPages { length: 0, bound: None, kept_for_fds: false, + dedicated_to_buffer: false, after_free: Mutex::new(Vec::new()), } } @@ -522,6 +536,7 @@ impl DmaBufPages { length, bound: None, kept_for_fds: false, + dedicated_to_buffer: false, after_free: Mutex::new(Vec::new()), } } @@ -574,6 +589,13 @@ impl DmaBufPages { } } + /// Whether an import of theirs is dedicated to the buffer bound in it, where the driver + /// refused it dedicated to nothing: an image binds in none of their memory then + /// (`VUID-vkBindImageMemory-memory-10926`). + pub(super) fn dedicated_to_buffer(&self) -> bool { + self.dedicated_to_buffer + } + /// Whether the pages hold the `length` bytes from host address `start`. fn holds(&self, start: u64, length: u64) -> bool { let end = start.checked_add(length); @@ -975,8 +997,9 @@ impl Device { /// /// The window's pages are host memory of this process that stays mapped until the placement /// is freed (`HostMemory::new`), and the chunks the source returns hold exactly those pages - /// (`HostMemory::with_dma_buf`). Where `sole`, the buffer is the only resource ever bound in - /// the imports ([`Device::chunks_buffer`]). + /// (`HostMemory::with_dma_buf`). Where `sole`, the buffer is the only buffer ever bound in + /// the imports, and an image is bound there only where they are dedicated to nothing + /// ([`Device::chunks_buffer`]). pub(super) unsafe fn import_from_source( &self, call: &'static str, @@ -1335,9 +1358,10 @@ impl Device { /// `vkBindBufferMemory` to a plain buffer, several by a sparse binding of a `SPARSE_BINDING` /// one (`Device::bind_sparse_buffer`, noted in `pages`). The buffer and where it is bound /// ([`BoundIn`]). A dma-buf of its own is imported dedicated to nothing; where `sole` (the - /// caller binds no other resource in its import, ever) and the buffer is a plain one, an - /// import the driver refuses so is made dedicated to the buffer (`memory.rs`'s - /// `DmaBufFor::Buffer`). A piece of a shared file lies in the device's one import of the file + /// caller binds no other buffer in its import, ever, and an image only where it is dedicated + /// to nothing: [`DmaBufPages::dedicated_to_buffer`]) and the buffer is a plain one, an import + /// the driver refuses so is made dedicated to the buffer (`memory.rs`'s + /// `DmaBufFor::Buffer`), and noted so in `pages`. A piece of a shared file lies in the device's one import of the file /// ([`Device::file_import`]), never dedicated: where the driver refuses that, the buffer is /// refused as for a refused chunk. Refused, the buffer released, where the bytes padded to 16 /// run past the pieces, the buffer's memory does not fit them or its alignment misses their @@ -1509,6 +1533,7 @@ impl Device { ImportFailure::Vulkan(error) => import_refused(error), })?; if dedicated { + pages.dedicated_to_buffer = true; shared.counts.dma_buf_buffer_import_dedicated(); } pages.hold(memory); @@ -2012,6 +2037,35 @@ impl Device { Ok(Ok(checked)) } + /// The image of `plan` (a texture's in place, viewed as `facts` says) over texels at `at` of + /// the memory of an import of their dma-buf pages dedicated to nothing, rows and slices + /// `pitches` apart, to be bound there beside the buffer bound in that import + /// (`texture/in_place_image.rs`): the `DRM_FORMAT_MOD_LINEAR` image made for dma-bufs whose one + /// plane lies at offset 0 at those pitches ([`offset_bound_image`](Self::offset_bound_image)), + /// unbound, with its memory requirements. It takes no dma-buf of the source's and no import of + /// its own: Vulkan binds an image at an offset of memory it shares (`vkBindImageMemory`'s + /// `memoryOffset`), so its texels are the import's bytes from `at`, which hold the pages' + /// from their first. Why not, of the kind a refusal is counted by: the checks of + /// [`dma_buf_unmade`](Self::dma_buf_unmade); then, of its plane's kind + /// ([`DmaBufRefusal::Pitch`]), the driver refuses the plane or lays it out otherwise, the + /// image requires a dedicated allocation, its memory's alignment does not divide `at`, or the + /// image format query takes dma-bufs for it in a dedicated allocation alone. + #[cfg(unix)] + pub(super) fn in_import_image_unbound( + &self, + plan: &ImagePlan, + facts: &ImageFacts<'_>, + at: u64, + pitches: (u64, u64), + ) -> Result, Error> { + let view_formats = match self.dma_buf_unmade(plan, facts)? { + Ok((_, view_formats)) => view_formats, + Err(refused) => return Ok(Err(refused)), + }; + let bound = self.offset_bound_image(plan, &view_formats, at, pitches)?; + Ok(bound.map_err(|why| (DmaBufRefusal::Pitch, why))) + } + /// [`Device::dma_buf_image`]'s image made and checked, unbound, with the request for its /// pages; why not where the device makes none before the source is asked. #[cfg(unix)] @@ -2139,7 +2193,8 @@ impl Device { /// plane at offset 0 with rows and slices `pitches` apart, unbound, with its memory /// requirements: to be bound at `offset` of an import of its texels' pages that is no /// dedicated allocation, where the driver lays out an explicit plane at `offset` at another - /// offset. Vulkan places an image's memory in memory it shares by its binding's offset + /// offset, or at `offset` of the import a buffer over the pages is bound in + /// ([`in_import_image_unbound`](Self::in_import_image_unbound)). Vulkan places an image's memory in memory it shares by its binding's offset /// (`vkBindImageMemory`'s `memoryOffset`: the image's bytes are those from there), and lays a /// `DRM_FORMAT_MOD_LINEAR` plane's texels from the plane's offset in them, so this image's /// texels are those from `offset` of the import, at the plane's pitches. The bytes of the diff --git a/crates/metal2vulkan-runtime/src/host_residency.rs b/crates/metal2vulkan-runtime/src/host_residency.rs index 01365f828..8007e4329 100644 --- a/crates/metal2vulkan-runtime/src/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/host_residency.rs @@ -57,13 +57,16 @@ //! read of each buffer in it was a blit's, or none: a buffer that is never read, made only to //! keep the bytes imported (a consumer's holder of a view of its guest's pages), keeps the //! import no more than a buffer only blits read does. Counted: -//! `WorkCounts::host_imports_joined_releasable`. A texture in place over a dma-buf -//! import's bytes is not such a read: its `DRM_FORMAT_MOD_LINEAR` image lies in an import of a -//! dma-buf of its own pages, which it asks the buffer's source for as it is made, reading the -//! buffer's import as a blit does (imported again where released, `dma_buf.rs`), and binds none -//! of the buffer's memory, so the buffer's import stays releasable beside it. Each such image is -//! a listed import of its own on RADV, and the buffer's import a second one only while blits use -//! it. +//! `WorkCounts::host_imports_joined_releasable`. A texture in place over a dma-buf import's +//! bytes whose image is bound in that import (`texture/in_place_image.rs`, where the import is +//! dedicated to nothing and the device's check of such images passed; never on RADV, whose such +//! images require a dedicated allocation) is a read apart as an image in a pointer import is: +//! the import is kept imported for good from its bind on, and the image adds no import. One +//! whose `DRM_FORMAT_MOD_LINEAR` image lies in an import of a dma-buf of its own pages, which it +//! asks the buffer's source for as it is made, is not: it reads the buffer's import as a blit +//! does (imported again where released, `dma_buf.rs`) and binds none of the buffer's memory, so +//! the buffer's import stays releasable beside it. Each such image is a listed import of its own +//! on RADV, and the buffer's import a second one only while blits use it. //! - **Released while idle** by the device's residency thread ([`Sweeper`]), every [`TICK`]: an //! import no command buffer holds, even weakly (every one that read it completed) and that no //! blit took for its window, [`IDLE`] at first and doubled at each import again, up to diff --git a/crates/metal2vulkan-runtime/src/in_place.rs b/crates/metal2vulkan-runtime/src/in_place.rs index d09a4bb0e..99b4c282e 100644 --- a/crates/metal2vulkan-runtime/src/in_place.rs +++ b/crates/metal2vulkan-runtime/src/in_place.rs @@ -214,11 +214,19 @@ pub(crate) enum PagesClass { /// decide whether the device's buffers lie in such blocks at all /// ([`Device::fd_blocks_checked`]). FdBlocks, + /// A no-copy buffer's pages imported as dma-bufs, in one import dedicated to nothing + /// (`dma_buf.rs`): a `DRM_FORMAT_MOD_LINEAR` image bound at the texels' offset of that very + /// import, beside the buffer and the other resources bound in it, with no dma-buf or import + /// of its own (`texture/in_place_image.rs`), its first move an acquire from + /// `VK_QUEUE_FAMILY_FOREIGN_EXT` as [`DmaBuf`](Self::DmaBuf)'s is. A texture over dma-buf pages + /// takes this class where its verdicts take it, else [`DmaBuf`](Self::DmaBuf)'s + /// (`texture/route.rs`), so each class's verdicts are those of the image it governs. + DmaBufInImport, } impl PagesClass { /// Every class, in the order the check runs them and the record holds their verdicts. - pub(crate) const ALL: [PagesClass; 7] = [ + pub(crate) const ALL: [PagesClass; 8] = [ PagesClass::Pointer, PagesClass::Fresh, PagesClass::DmaBuf, @@ -226,6 +234,7 @@ impl PagesClass { PagesClass::ExportedFd, PagesClass::ExportedDmaBuf, PagesClass::FdBlocks, + PagesClass::DmaBufInImport, ]; /// Its place in [`ALL`](Self::ALL). @@ -238,6 +247,7 @@ impl PagesClass { PagesClass::ExportedFd => 4, PagesClass::ExportedDmaBuf => 5, PagesClass::FdBlocks => 6, + PagesClass::DmaBufInImport => 7, } } @@ -251,6 +261,9 @@ impl PagesClass { 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", + PagesClass::DmaBufInImport => { + "host pages imported as dma-bufs, an image bound in their import" + } } } @@ -273,7 +286,10 @@ impl PagesClass { | PagesClass::ExportedFd | PagesClass::ExportedDmaBuf | PagesClass::FdBlocks => true, - PagesClass::Pointer | PagesClass::Fresh | PagesClass::DmaBuf => false, + PagesClass::Pointer + | PagesClass::Fresh + | PagesClass::DmaBuf + | PagesClass::DmaBufInImport => false, } } } @@ -736,6 +752,27 @@ pub(crate) fn checking() -> bool { CHECKING.with(std::cell::Cell::get) } +thread_local! { + /// The class whose rounds the device's check runs now on this thread + /// ([`checked_dma_buf_class`]): its textures over dma-buf pages take that class's image alone. + static CHECKED_CLASS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The class of pages imported as dma-bufs whose rounds the device's check runs now on this +/// thread ([`PagesClass::DmaBuf`] or [`PagesClass::DmaBufInImport`]): a texture the check makes +/// over such pages takes that class's image alone (`texture/route.rs`, +/// `texture/in_place_image.rs`), so each class's verdicts are its own image's. `None` off the +/// check's thread, and while it runs another class. +pub(crate) fn checked_dma_buf_class() -> Option { + let class = CHECKED_CLASS.with(std::cell::Cell::get)?; + matches!(class, PagesClass::DmaBuf | PagesClass::DmaBufInImport).then_some(class) +} + +/// The device's check runs `class`'s rounds on this thread from now (`None` once they are done). +pub(crate) fn set_checked_class(class: Option) { + CHECKED_CLASS.with(|checked| checked.set(class)); +} + /// Mark this thread as the device's check's, for good: it is a thread of its own. pub(crate) fn mark_checking() { CHECKING.with(|checking| checking.set(true)); @@ -1089,7 +1126,7 @@ pub(crate) fn blocks_take( /// differs, and so does the version it holds). The runtime's own version is not in the record: a /// release that changes none of these keeps the verdicts the driver gave, so a device made after /// it reads them again rather than checking anew. -pub(crate) const CHECK_VERSION: u32 = 19; +pub(crate) const CHECK_VERSION: u32 = 20; /// A record's first bytes. const MAGIC: [u8; 8] = *b"M2VINPL\0"; @@ -1166,7 +1203,7 @@ pub(crate) fn record_name(identity: &DriverIdentity) -> String { /// magic 8 bytes "M2VINPL\0" /// version u32 CHECK_VERSION /// identity 32 bytes DriverIdentity::digest -/// verdicts 56 bytes one per class, access and row ends, VERDICTS' order (verdict_index) +/// verdicts 128 bytes one per class, access and row ends, VERDICTS' order (verdict_index) /// checksum 32 bytes SHA-256 of every byte before it /// ``` /// diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index db73ea3a4..d2a699030 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -197,8 +197,8 @@ use crate::device::lock; use crate::exit_guard; use crate::host_memory::HostMemory; use crate::in_place::{ - encode, mark_checking, record_name, verdict_index, Access, Padding, PagesClass, RowEnds, - Verdict, + encode, mark_checking, record_name, set_checked_class, verdict_index, Access, Padding, + PagesClass, RowEnds, Verdict, }; use crate::linear_plan::BufferLayout; #[cfg(unix)] @@ -484,6 +484,7 @@ fn class_bytes(class: PagesClass) -> u64 { PagesClass::Pointer | PagesClass::Fresh | PagesClass::DmaBuf + | PagesClass::DmaBufInImport | PagesClass::ExportedFd | PagesClass::ExportedDmaBuf => BUFFER_BYTES, } @@ -576,7 +577,12 @@ fn run(weak: crate::device::WeakDevice) { continue; } let begun = Instant::now(); - let Some((verdicts, beside, passing)) = check_class(&device, class, access) else { + // Its textures over dma-buf pages take its class's image alone + // (`in_place::checked_dma_buf_class`). + set_checked_class(Some(class)); + let checked = check_class(&device, class, access); + set_checked_class(None); + let Some((verdicts, beside, passing)) = checked else { // The process is exiting, or the program let the device go: nothing is kept. return; }; @@ -1559,6 +1565,13 @@ impl ClassPages { Ok(ClassPages { buffer, start }) } PagesClass::DmaBuf => dma_buf_pages(device, length), + // The same pages, whose textures' images bind in the import their buffer lies in + // (`texture/in_place_image.rs`): only where that is one import dedicated to nothing. + PagesClass::DmaBufInImport => { + let pages = dma_buf_pages(device, length)?; + in_one_import(&pages.buffer)?; + Ok(pages) + } // 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 @@ -1819,6 +1832,32 @@ fn dma_buf_pages(_device: &Device, _length: u64) -> Result { Err(Unmade::lasting("the system has no dma-bufs")) } +/// Why `buffer`, a no-copy buffer over pages imported as dma-bufs, lies in no one import of a +/// dma-buf dedicated to nothing, where an image binds beside it +/// (`HostPages::in_one_dma_buf_import`): a cause that lasts where the import is dedicated to the +/// buffer (the driver refused it dedicated to nothing) or the buffer is bound sparsely over +/// several, as the device decides both of a buffer of the class's length. +#[cfg(unix)] +fn in_one_import(buffer: &Buffer) -> Result<(), Unmade> { + let Some(pages) = buffer.host_pages() else { + return Err(Unmade::passing("its buffer lies in no pages")); + }; + match pages.in_one_dma_buf_import(false) { + Ok(Some(_)) => Ok(()), + Ok(None) => Err(Unmade::lasting( + "its buffer lies in no one import of a dma-buf dedicated to nothing: in several, bound \ + sparsely, or in one dedicated to the buffer", + )), + Err(error) => Err(Unmade::of_error("its import was not made again", &error)), + } +} + +/// No pages are imported as dma-bufs on this system. +#[cfg(not(unix))] +fn in_one_import(_buffer: &Buffer) -> Result<(), Unmade> { + Err(Unmade::lasting("the system has no dma-bufs")) +} + /// A no-copy buffer of `length` bytes over pages the device refuses by their pointer, imported /// as dma-bufs: an allocation of the device's own, host-visible and exported as a dma-buf, mapped /// (the module docs). diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs index f61d849b7..29ec27ca8 100644 --- a/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs @@ -58,7 +58,9 @@ //! Where `/dev/udmabuf` cannot be opened, or the device lists no dma-buf route, it says so and //! passes without running. -use super::host_residency::{counting, host_page, udmabuf, udmabuf_openable, Scratch}; +use super::host_residency::{ + counting, host_page, own_dma_buf_images, udmabuf, udmabuf_openable, Scratch, +}; use super::merge_scratch::{blit, read}; use super::no_pointer_import::{device, lists_dma_buf_route}; use crate::{ @@ -550,6 +552,9 @@ fn dma_buf_cycles_image_import() { device.settle_in_place_checks(CHECK_WAIT), "{TEST}: the check" ); + // Each texture's image in a dma-buf import of its own, whatever the check of images in the + // buffer's import answered. + own_dma_buf_images(&device); let queue = device.new_command_queue().unwrap(); let out = (device.new_buffer(SIDE * SIDE * 4, ResourceOptions::shared())).unwrap(); let pages = Pages::new(); diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_in_import.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_in_import.rs new file mode 100644 index 000000000..6fec44a9c --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_in_import.rs @@ -0,0 +1,267 @@ +//! A texture in place over a no-copy buffer's dma-buf pages whose image is bound in the import the +//! buffer lies in (`texture/in_place_image.rs`, `PagesClass::DmaBufInImport`), on the device the +//! cfg selects made without `VK_EXT_external_memory_host`, so that its no-copy buffers are +//! imported as dma-bufs of their pages (`tests/no_pointer_import.rs`): a 64x32 `BGRA8Unorm` +//! texture that only reads, rows 512 bytes apart, 512 bytes into the second page of a no-copy +//! buffer over a `memfd`'s pages mapped shared, whose source makes `udmabuf`s of them and counts +//! its calls. +//! +//! - **In the import.** Where the device's check passed such images for the texture's reads, the +//! texture is in place with its image in the buffer's import +//! (`WorkCounts::dma_buf_images_in_import` + 1): no dma-buf image (`dma_buf_images` + 0), no +//! import of its own (`dma_buf_image_memories_live` + 0), and no call of the source. A blit +//! reads its texels from the pages, then the CPU's later bytes there; a blit's copy into it +//! writes its texels in the pages and leaves every other byte of them alone (the 256 bytes +//! between its rows among them). +//! - **Today's image, the negative control.** With that class's verdicts failed, the same texture +//! takes the image in a dma-buf import of its own (`dma_buf_images` + 1, the source asked once, +//! `dma_buf_images_in_import` + 0) where the device's check passed those images, and reads what +//! the image in the import reads. +//! - **Elsewhere** (a device whose check leaves the class unchecked: RADV, whose +//! `DRM_FORMAT_MOD_LINEAR` images for dma-bufs require a dedicated allocation), no texture's +//! image is bound in the import (`dma_buf_images_in_import` + 0), and the test says what the +//! texture took and passes. +//! +//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on Linux. +//! Where `/dev/udmabuf` cannot be opened, or the device lists no dma-buf route or makes no +//! `DRM_FORMAT_MOD_LINEAR` images, it says so and passes without running. + +use super::host_residency::{ + counting, host_page, own_dma_buf_images, udmabuf_openable, Ram, Scratch, +}; +use super::merge_scratch::{blit, read}; +use super::no_pointer_import::{device, lists_dma_buf_route}; +use crate::in_place::{Access, PagesClass, RowEnds, Verdict}; +use crate::linear_plan::BufferLayout; +use crate::{ + BlitOption, Buffer, CommandQueue, HostMemory, Origin, ResourceOptions, Size, Texture, + TextureDescriptor, WorkCounts, +}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +const TEST: &str = "IN-IMPORT"; +/// The texture's width and height, and the bytes from a row's first texel to the next row's: a +/// multiple of the 256 RADV lays a plane's rows at, with 256 bytes between rows. +const WIDTH: u64 = 64; +const HEIGHT: u64 = 32; +const ROW: u64 = 512; +const ROW_BYTES: u64 = 4 * WIDTH; +const CHECK_WAIT: Duration = Duration::from_secs(120); + +/// The texture's texels, copied out by a blit. +fn texels_of(queue: &CommandQueue, texture: &Texture) -> Vec { + let out = (queue.device()) + .new_buffer(ROW_BYTES * HEIGHT, ResourceOptions::shared()) + .unwrap(); + blit(queue, |encoder| { + (encoder.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(WIDTH, HEIGHT, 1), + &out, + 0, + ROW_BYTES, + ROW_BYTES * HEIGHT, + BlitOption::None, + )) + .unwrap() + }); + read(&out, ROW_BYTES * HEIGHT) +} + +/// The texels of a texture `at` bytes into `pages`, row after row. +fn texels_in(pages: &[u8], at: u64) -> Vec { + (0..HEIGHT) + .flat_map(|row| &pages[(at + row * ROW) as usize..][..ROW_BYTES as usize]) + .copied() + .collect() +} + +/// What making a texture changed: its images bound in an import, its dma-buf images, the live +/// imports of such images, and the source's calls. +fn made(before: &WorkCounts, after: &WorkCounts, calls: usize) -> (u64, u64, u64, usize) { + ( + after.dma_buf_images_in_import - before.dma_buf_images_in_import, + after.dma_buf_images - before.dma_buf_images, + after.dma_buf_image_memories_live - before.dma_buf_image_memories_live, + calls, + ) +} + +/// The checks the module's docs list. +#[test] +fn a_texture_over_a_dma_buf_buffer_s_pages_binds_in_its_import() { + if !udmabuf_openable(TEST) { + return; + } + let scratch = Scratch::new(); + let device = device(&scratch.0, None); + let name = device.name(); + if !lists_dma_buf_route(&device) || !device.makes_modifier_images() { + println!( + "{TEST}: {name} lists no dma-buf route or makes no DRM_FORMAT_MOD_LINEAR images: not \ + run" + ); + return; + } + assert!( + device.settle_in_place_checks(CHECK_WAIT), + "{TEST}: the check" + ); + for line in device.in_place_check_report() { + if line.starts_with("DmaBuf") { + println!("{TEST} on {name}: the check: {line}"); + } + } + let queue = device.new_command_queue().unwrap(); + let page = host_page(); + let offset = page as u64 + 512; + let length = offset + ROW * HEIGHT; + let file = (length as usize).next_multiple_of(page); + let ram = Ram::new(file, 0, file); + ram.write_file(0, &counting(file, 7)); + let calls = Arc::new(AtomicUsize::new(0)); + let asked = || calls.load(Ordering::Acquire); + // SAFETY: the view outlives the buffer, and the source makes dma-bufs of its pages. + let buffer: Buffer = unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::with_dma_buf(ram.pointer(0), ram.source(&calls)), + length, + ResourceOptions::default(), + None, + ) + } + .unwrap(); + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false); + descriptor.usage = TextureUsage::SHADER_READ; + // The verdicts the texture's route asks: its reads, for texels that lie in lines as its do. + let layout = BufferLayout { + offset, + row_pitch: ROW, + slice_pitch: ROW * HEIGHT, + row_bytes: ROW_BYTES, + rows: HEIGHT, + slices: 1, + }; + let start = ram.pointer(0).as_ptr().addr() as u64; + let rows = RowEnds::of(start, &layout, device.shared().in_place.line()); + let in_import = device.in_place_verdict(PagesClass::DmaBufInImport, Access::Reads, rows); + let own = device.in_place_verdict(PagesClass::DmaBuf, Access::Reads, rows); + + let before = device.work_counts(); + let by_buffer = asked(); + let texture = buffer.new_texture(&descriptor, offset, ROW).unwrap(); + let after = device.work_counts(); + // SAFETY: the handle is only compared, while the texture lives. + let in_place = unsafe { texture.vk_image() }.is_some(); + let first = made(&before, &after, asked() - by_buffer); + assert!( + texels_of(&queue, &texture) == texels_in(&counting(file, 7), offset), + "{TEST}: the texture's texels" + ); + if in_import != Verdict::Passed { + assert_eq!( + first.0, 0, + "{TEST}: no image in the import where its check did not pass ({in_import:?})" + ); + println!( + "{TEST} on {name}: the check of images in the import answered {in_import:?}, of \ + images in imports of their own {own:?}; the texture in place {in_place}: in the \ + import {}, dma-buf images {}, their imports live {}, source calls {}", + first.0, first.1, first.2, first.3 + ); + return; + } + assert!(in_place, "{TEST}: in place"); + assert_eq!( + first, + (1, 0, 0, 0), + "{TEST}: in the buffer's import, with no dma-buf image, import or source call (in the \ + import, dma-buf images, their imports live, source calls)" + ); + // The CPU's later bytes. + ram.write_file(0, &counting(file, 101)); + assert!( + texels_of(&queue, &texture) == texels_in(&counting(file, 101), offset), + "{TEST}: the CPU's later bytes" + ); + // A copy into it writes its texels in the pages, and no other byte. + let fresh = counting((ROW_BYTES * HEIGHT) as usize, 211); + let source = (device.new_buffer(ROW_BYTES * HEIGHT, ResourceOptions::shared())).unwrap(); + // SAFETY: inside the buffer's length, which no command uses now. + unsafe { + let contents = source.contents().unwrap().as_ptr(); + std::ptr::copy_nonoverlapping(fresh.as_ptr(), contents, fresh.len()); + } + blit(&queue, |encoder| { + (encoder.copy_from_buffer_to_texture( + &source, + 0, + ROW_BYTES, + ROW_BYTES * HEIGHT, + Size::new(WIDTH, HEIGHT, 1), + &texture, + 0, + 0, + Origin::new(0, 0, 0), + BlitOption::None, + )) + .unwrap() + }); + let mut want = counting(file, 101); + for row in 0..HEIGHT { + let at = (offset + row * ROW) as usize; + let from = (row * ROW_BYTES) as usize; + want[at..][..ROW_BYTES as usize].copy_from_slice(&fresh[from..][..ROW_BYTES as usize]); + } + assert!( + ram.read_file(0, file) == want, + "{TEST}: the copy wrote the texels alone" + ); + let in_the_import = texels_of(&queue, &texture); + assert!(in_the_import == fresh, "{TEST}: the copied texels read"); + + // Today's image, the negative control. + own_dma_buf_images(&device); + let before = device.work_counts(); + let by_first = asked(); + let control = buffer.new_texture(&descriptor, offset, ROW).unwrap(); + let after = device.work_counts(); + let second = made(&before, &after, asked() - by_first); + // SAFETY: as above. + let control_in_place = unsafe { control.vk_image() }.is_some(); + assert_eq!( + second.0, 0, + "{TEST}: no image in the import once its check failed" + ); + if own == Verdict::Passed { + assert!(control_in_place, "{TEST}: the control in place"); + assert_eq!( + (second.1, second.3), + (1, 1), + "{TEST}: the control's image in a dma-buf import of its own, the source asked once" + ); + } + assert!( + texels_of(&queue, &control) == in_the_import, + "{TEST}: the control reads what the image in the import reads" + ); + println!( + "{TEST} on {name}: in the import {} (dma-buf images {}, their imports live {}, source \ + calls {}); the control, its check of images in imports of their own {own:?}, in place \ + {control_in_place}: in the import {}, dma-buf images {}, source calls {}", + first.0, first.1, first.2, first.3, second.0, second.1, second.3 + ); + drop(control); + drop(texture); + drop(buffer); + drop(queue); + drop(device); + drop(ram); +} diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_linear_bind.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_linear_bind.rs new file mode 100644 index 000000000..3d240f3ef --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_linear_bind.rs @@ -0,0 +1,1474 @@ +//! Whether a device binds a texture's linear image in the dma-buf import its pages already have, +//! and what that spares against a dma-buf of the texture's own pages: a measurement, not a check. +//! Ignored, printed as `LINBIND` lines. +//! +//! The pages are the probe's own: a sealed `memfd` mapped shared, one `udmabuf` of it imported +//! once, dedicated to nothing, with a `VkBuffer` made for dma-bufs bound over it whole, as a +//! no-copy buffer's pages or a guest RAM's chunk are imported (`dma_buf.rs`, `host_ram.rs`). The +//! device is the probe's own, made through the loader, with no runtime in the way: +//! +//! - **The driver's answers** (`LINBIND-QUERY`, `LINBIND-LAYOUT`, `LINBIND-SHARE`), per format of +//! [`FORMATS`] and usage of [`usages`]: the image format query of a `VK_IMAGE_TILING_LINEAR` 2D +//! image with `VkPhysicalDeviceExternalImageFormatInfo` of dma-bufs (an image made for a handle +//! type the answer lists none of is invalid, `VUID-VkImageCreateInfo-pNext-00990`). Where it +//! takes one, for each width of [`WIDTHS`], such an image made `UNDEFINED` +//! (`VUID-VkImageCreateInfo-pNext-01443`): whether it requires or prefers a dedicated allocation +//! (one that requires it binds at offset 0 of its own allocation alone, +//! `VUID-vkBindImageMemory-image-01445`, `-memory-02628`), its memory's alignment, size and +//! types, and its subresource's offset and row pitch beside Metal's: the width's bytes rounded +//! up to 16, 64 and 256, and to the runtime's `minimumLinearTextureAlignmentForPixelFormat` +//! answer on the same GPU. +//! - **The binding** (`LINBIND-BIND`), per format, at each width of [`BIND_WIDTHS`] by +//! [`BIND_ROWS`] rows: the image bound in the import at an offset that meets its alignment, no +//! multiple of the page where the alignment allows (`VUID-vkBindImageMemory-memory-02989`: it +//! names the import's handle type; `-None-10735`, `-None-10737`), its rows' padding and the bytes +//! around it set apart; first moved as the runtime moves an image over dma-buf pages (an acquire +//! from `VK_QUEUE_FAMILY_FOREIGN_EXT`, `GENERAL` to `GENERAL`, `texture/first_move.rs`); then +//! copied out (the texels the CPU wrote, read back), written by a copy, cleared, and rendered (a +//! render pass that clears it, where its usage renders), each checked byte for byte through the +//! pages' mapping: the texels as the driver's layout places them, the padding and the bytes +//! around left alone. +//! - **First use** (`LINBIND-TIME`), per shape of [`TIMED`], [`ROUNDS`] rounds, the two ways in +//! turn: from nothing to a first copy out of the texture waited for, today's way (a +//! `DRM_FORMAT_MOD_LINEAR` image at the same pitch, a `udmabuf` of its pages, a dedicated +//! import of it bound at 0, `dma_buf.rs`'s `dma_buf_image`) against the linear image bound in +//! the import; each step's microseconds, and the release's. +//! +//! Run it in release under `--cfg m2v_gpu` (or `m2v_cpu_icd`) where `/dev/udmabuf` opens: +//! `cargo nextest run --release -p metal2vulkan-runtime --lib --run-ignored all +//! -E 'test(dma_buf_linear_bind)' --no-capture`. + +use super::host_residency::{device, host_page, udmabuf, udmabuf_openable, Ram, Scratch}; +use ash::vk; +use metal2vulkan::metal::PixelFormat; +use std::ffi::CStr; +use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd}; +use std::time::Instant; + +/// The formats asked: Vulkan's, its texel's bytes, and Metal's. +const FORMATS: [(vk::Format, u64, PixelFormat); 5] = [ + (vk::Format::B8G8R8A8_UNORM, 4, PixelFormat::BGRA8Unorm), + (vk::Format::R8G8B8A8_UNORM, 4, PixelFormat::RGBA8Unorm), + (vk::Format::R8_UNORM, 1, PixelFormat::R8Unorm), + (vk::Format::R16G16B16A16_SFLOAT, 8, PixelFormat::RGBA16Float), + (vk::Format::R32_SFLOAT, 4, PixelFormat::R32Float), +]; + +/// The widths each layout is asked at, in texels: no power of two, powers of two, screens'. +const WIDTHS: [u32; 16] = [ + 1, 3, 17, 64, 65, 100, 129, 256, 640, 1000, 1024, 1280, 1366, 1920, 2560, 3840, +]; + +/// The rows of each image whose layout is asked. +const LAYOUT_ROWS: u32 = 4; + +/// Metal's pitch alignments the driver's row pitch is set beside. +const METAL_ALIGNMENTS: [u64; 3] = [16, 64, 256]; + +/// The widths each format's image is bound and used at. +const BIND_WIDTHS: [u32; 3] = [100, 1366, 1920]; + +/// The rows of each bound image. +const BIND_ROWS: u32 = 33; + +/// The shapes timed, `BGRA8Unorm`: a screen's, and about the 84 MiB of the in-place lane's case. +const TIMED: [[u32; 2]; 2] = [[1920, 1080], [5120, 4300]]; + +/// The rounds of each shape's two ways; the first is a warm-up, printed apart. +const ROUNDS: usize = 4; + +/// The bytes of the probe's pages. +const RAM_BYTES: usize = 128 << 20; + +/// Where the bound images lie (before their offset in the page). +const BIND_AT: u64 = 4 << 20; + +/// Where the timed images lie. +const TIMED_AT: u64 = 16 << 20; + +/// Where the copies out land, tightly packed. +const OUT_AT: u64 = 112 << 20; + +/// Where the copies in come from, tightly packed. +const SOURCE_AT: u64 = 116 << 20; + +/// The bytes before and after each bound image checked as left alone. +const GUARD: u64 = 512; + +/// The byte of the rows' padding. +const PADDING: u8 = 0xa5; + +/// The byte around the image. +const AROUND: u8 = 0x5a; + +/// The texels of the timed first use's copy out, a square's side. +const FIRST_COPY: u32 = 64; + +/// `DRM_FORMAT_MOD_LINEAR`. +const MOD_LINEAR: u64 = 0; + +/// The dma-buf handle type. +const DMA_BUF: vk::ExternalMemoryHandleTypeFlags = vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT; + +/// The usages asked: reading, reading and rendering, reading and a shader's writes. +fn usages() -> [(&'static str, vk::ImageUsageFlags); 3] { + use vk::ImageUsageFlags as U; + let read = U::SAMPLED | U::TRANSFER_SRC | U::TRANSFER_DST; + [ + ("read", read), + ("render", read | U::COLOR_ATTACHMENT), + ("write", read | U::STORAGE), + ] +} + +/// `format`'s name, as the lines print it. +fn name(format: vk::Format) -> &'static str { + match format { + vk::Format::B8G8R8A8_UNORM => "BGRA8Unorm", + vk::Format::R8G8B8A8_UNORM => "RGBA8Unorm", + vk::Format::R8_UNORM => "R8Unorm", + vk::Format::R16G16B16A16_SFLOAT => "RGBA16Float", + vk::Format::R32_SFLOAT => "R32Float", + _ => "another format", + } +} + +/// The bytes of a texel of `format` whose every channel is 1.0. +fn ones(format: vk::Format) -> Vec { + match format { + vk::Format::R16G16B16A16_SFLOAT => [0x00, 0x3c].repeat(4), + vk::Format::R32_SFLOAT => vec![0x00, 0x00, 0x80, 0x3f], + vk::Format::R8_UNORM => vec![0xff], + _ => vec![0xff; 4], + } +} + +/// The byte `b` of row `r` of a pattern of `seed`: from 0x10 to 0x3f, so no float of the +/// formats' is a NaN or subnormal whatever byte of it the byte is. +fn pattern(seed: u64, r: u64, b: u64) -> u8 { + let hash = (r * 131 + b * 7 + seed * 977).wrapping_mul(0x9e37_79b9) >> 7; + 0x10 + (hash % 0x30) as u8 +} + +/// `value` rounded up to a multiple of `to`. +fn up(value: u64, to: u64) -> u64 { + value.div_ceil(to) * to +} + +/// The median of `values`. +fn median(mut values: Vec) -> f64 { + values.sort_by(f64::total_cmp); + values.get(values.len() / 2).copied().unwrap_or(f64::NAN) +} + +/// Microseconds since `from`. +fn us(from: Instant) -> f64 { + from.elapsed().as_secs_f64() * 1e6 +} + +/// What the driver answers of an image: its memory requirements, whether it requires and prefers +/// a dedicated allocation, and its first subresource's layout. +struct Facts { + requirements: vk::MemoryRequirements, + requires: bool, + prefers: bool, + layout: vk::SubresourceLayout, +} + +/// The probe's Vulkan device and its one queue's command buffer. +struct Probe { + _entry: ash::Entry, + instance: ash::Instance, + physical: vk::PhysicalDevice, + device: ash::Device, + fd: ash::khr::external_memory_fd::Device, + family: u32, + queue: vk::Queue, + pool: vk::CommandPool, + commands: vk::CommandBuffer, + fence: vk::Fence, + /// Whether the device enables `VK_EXT_queue_family_foreign`. + foreign: bool, + /// Whether it enables `VK_EXT_image_drm_format_modifier`. + modifiers: bool, + memory: vk::PhysicalDeviceMemoryProperties, +} + +/// The pages' import: its memory, its type, and the buffer bound over it whole. +struct Import { + memory: vk::DeviceMemory, + type_index: u32, + buffer: vk::Buffer, +} + +impl Probe { + /// The device the cfg selects (a CPU device under `m2v_cpu_icd`, else the first other), + /// with the dma-buf extensions; `None`, said, where it lists them not. + fn new() -> Option { + let entry = crate::device::create::open_loader(None).unwrap(); + let application = vk::ApplicationInfo::default().api_version(vk::API_VERSION_1_2); + let info = vk::InstanceCreateInfo::default().application_info(&application); + // SAFETY: `info` and what it points at live for the call. + let instance = unsafe { entry.create_instance(&info, None) }.unwrap(); + // SAFETY: the instance is live. + let physicals = unsafe { instance.enumerate_physical_devices() }.unwrap(); + let cpu = cfg!(m2v_cpu_icd); + let physical = physicals + .into_iter() + .find(|&physical| { + // SAFETY: the instance's. + let kind = unsafe { instance.get_physical_device_properties(physical) }.device_type; + (kind == vk::PhysicalDeviceType::CPU) == cpu + }) + .expect("a device of the kind the cfg selects"); + let mut driver = vk::PhysicalDeviceDriverProperties::default(); + let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut driver); + // SAFETY: the instance's; Vulkan 1.1's command, 1.2's structure. + unsafe { instance.get_physical_device_properties2(physical, &mut properties) }; + let name = (properties.properties.device_name_as_c_str()) + .map_or("?".to_owned(), |name| name.to_string_lossy().into_owned()); + let words = |name: Result<&CStr, _>| { + name.map_or("?".to_owned(), |name: &CStr| { + name.to_string_lossy().into_owned() + }) + }; + let (driver_name, driver_info) = ( + words(driver.driver_name_as_c_str()), + words(driver.driver_info_as_c_str()), + ); + // SAFETY: the instance's. + let listed = unsafe { instance.enumerate_device_extension_properties(physical) }.unwrap(); + let lists = |wanted: &CStr| { + (listed.iter()).any(|extension| extension.extension_name_as_c_str() == Ok(wanted)) + }; + let needed = [ + ash::khr::external_memory_fd::NAME, + ash::ext::external_memory_dma_buf::NAME, + ]; + if !needed.iter().all(|&name| lists(name)) { + println!("LINBIND-DEVICE {name}: lists no dma-buf imports: not run"); + return None; + } + let foreign = lists(ash::ext::queue_family_foreign::NAME); + let modifiers = lists(ash::ext::image_drm_format_modifier::NAME); + let mut enabled: Vec<*const std::ffi::c_char> = + needed.iter().map(|name| name.as_ptr()).collect(); + if foreign { + enabled.push(ash::ext::queue_family_foreign::NAME.as_ptr()); + } + if modifiers { + enabled.push(ash::ext::image_drm_format_modifier::NAME.as_ptr()); + } + // SAFETY: the instance's. + let families = unsafe { instance.get_physical_device_queue_family_properties(physical) }; + let family = (families.iter()) + .position(|family| family.queue_flags.contains(vk::QueueFlags::GRAPHICS)) + .expect("a graphics queue family") as u32; + let priorities = [1.0]; + let queues = [vk::DeviceQueueCreateInfo::default() + .queue_family_index(family) + .queue_priorities(&priorities)]; + let info = vk::DeviceCreateInfo::default() + .queue_create_infos(&queues) + .enabled_extension_names(&enabled); + // SAFETY: `info` and what it points at live for the call. + let device = unsafe { instance.create_device(physical, &info, None) }.unwrap(); + let fd = ash::khr::external_memory_fd::Device::new(&instance, &device); + // SAFETY: the instance's. + let memory = unsafe { instance.get_physical_device_memory_properties(physical) }; + // SAFETY: the device is live, the family and index were made; every info is valid. + let (queue, pool, commands, fence) = unsafe { + let queue = device.get_device_queue(family, 0); + let pool = device + .create_command_pool( + &vk::CommandPoolCreateInfo::default() + .queue_family_index(family) + .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER), + None, + ) + .unwrap(); + let commands = device + .allocate_command_buffers( + &vk::CommandBufferAllocateInfo::default() + .command_pool(pool) + .command_buffer_count(1), + ) + .unwrap()[0]; + let fence = (device.create_fence(&vk::FenceCreateInfo::default(), None)).unwrap(); + (queue, pool, commands, fence) + }; + println!( + "LINBIND-DEVICE {name}: driver {driver_name} ({driver_info}), queue family foreign \ + {foreign}, DRM format modifiers {modifiers}, page {}", + host_page() + ); + Some(Probe { + _entry: entry, + instance, + physical, + device, + fd, + family, + queue, + pool, + commands, + fence, + foreign, + modifiers, + memory, + }) + } + + /// The type of `bits` an import takes: host-visible and coherent first, as the runtime ranks + /// a buffer's (`memory.rs`). + fn type_of(&self, bits: u32) -> Option { + let coherent = + vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT; + let types = &self.memory.memory_types[..self.memory.memory_type_count as usize]; + let indices: Vec = (0..types.len() as u32) + .filter(|index| bits & (1 << index) != 0) + .collect(); + (indices.iter().copied()) + .find(|&index| types[index as usize].property_flags.contains(coherent)) + .or(indices.first().copied()) + } + + /// An import of the dma-buf `fd`, `size` bytes, of a type of `wanted` it takes, dedicated to + /// `dedicated` where it is an image, with its type; why not. + fn import( + &self, + fd: OwnedFd, + size: u64, + wanted: u32, + dedicated: Option, + ) -> Result<(vk::DeviceMemory, u32), String> { + let mut properties = vk::MemoryFdPropertiesKHR::default(); + // SAFETY: the device's; the descriptor is a dma-buf. + unsafe { (self.fd).get_memory_fd_properties(DMA_BUF, fd.as_raw_fd(), &mut properties) } + .map_err(|error| format!("the driver refuses the dma-buf ({error:?})"))?; + let bits = properties.memory_type_bits & wanted; + let index = (self.type_of(bits)).ok_or_else(|| { + format!( + "it imports as types {:#x}, none of {wanted:#x}", + properties.memory_type_bits + ) + })?; + let raw = fd.into_raw_fd(); + let mut import = vk::ImportMemoryFdInfoKHR::default() + .handle_type(DMA_BUF) + .fd(raw); + let mut alone = vk::MemoryDedicatedAllocateInfo::default(); + let mut info = vk::MemoryAllocateInfo::default() + .allocation_size(size) + .memory_type_index(index) + .push_next(&mut import); + if let Some(image) = dedicated { + alone = alone.image(image); + info = info.push_next(&mut alone); + } + // SAFETY: `info` and its chain live for the call; the import takes the descriptor where + // it succeeds. + let memory = unsafe { self.device.allocate_memory(&info, None) }.map_err(|error| { + // SAFETY: the import failed, so the descriptor is still ours. + drop(unsafe { OwnedFd::from_raw_fd(raw) }); + format!("the driver refuses the import ({error:?})") + })?; + Ok((memory, index)) + } + + /// The pages' import: `fd`, a dma-buf of them `size` bytes long, imported dedicated to + /// nothing, with a buffer made for dma-bufs bound over it whole. + fn buffer_import(&self, fd: OwnedFd, size: u64) -> Import { + let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(DMA_BUF); + let info = vk::BufferCreateInfo::default() + .size(size) + .usage(vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::TRANSFER_DST) + .push_next(&mut external); + // SAFETY: `info` and its chain live for the call. + let buffer = unsafe { self.device.create_buffer(&info, None) }.unwrap(); + // SAFETY: the buffer is live. + let requirements = unsafe { self.device.get_buffer_memory_requirements(buffer) }; + let (memory, type_index) = + (self.import(fd, size, requirements.memory_type_bits, None)).unwrap(); + // SAFETY: the buffer is unbound; the memory takes it whole, of a type it takes. + unsafe { self.device.bind_buffer_memory(buffer, memory, 0) }.unwrap(); + Import { + memory, + type_index, + buffer, + } + } + + /// The image format query of a 2D image of `format`, `usage` and `tiling` (of + /// `DRM_FORMAT_MOD_LINEAR` where that is the modifier's) for dma-bufs: its external memory + /// properties and limits, or the driver's error. + fn query( + &self, + format: vk::Format, + usage: vk::ImageUsageFlags, + tiling: vk::ImageTiling, + ) -> Result<(vk::ExternalMemoryProperties, vk::ImageFormatProperties), vk::Result> { + let mut external_info = + vk::PhysicalDeviceExternalImageFormatInfo::default().handle_type(DMA_BUF); + let mut modifier = vk::PhysicalDeviceImageDrmFormatModifierInfoEXT::default() + .drm_format_modifier(MOD_LINEAR) + .sharing_mode(vk::SharingMode::EXCLUSIVE); + let mut info = vk::PhysicalDeviceImageFormatInfo2::default() + .format(format) + .ty(vk::ImageType::TYPE_2D) + .tiling(tiling) + .usage(usage) + .push_next(&mut external_info); + if tiling == vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT { + info = info.push_next(&mut modifier); + } + let mut external = vk::ExternalImageFormatProperties::default(); + let mut properties = vk::ImageFormatProperties2::default().push_next(&mut external); + // SAFETY: the instance's; `info` and both chains live for the call. + unsafe { + (self.instance).get_physical_device_image_format_properties2( + self.physical, + &info, + &mut properties, + ) + }?; + let limits = properties.image_format_properties; + Ok((external.external_memory_properties, limits)) + } + + /// Whether the query takes dma-bufs for such an image, and its words. + fn takes( + &self, + format: vk::Format, + usage: vk::ImageUsageFlags, + tiling: vk::ImageTiling, + ) -> (bool, String) { + match self.query(format, usage, tiling) { + Ok((external, _)) => { + let features = external.external_memory_features; + let takes = features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE) + && external.compatible_handle_types.contains(DMA_BUF); + let words = format!( + "features {:#x} compatible {:#x}", + features.as_raw(), + external.compatible_handle_types.as_raw() + ); + (takes, words) + } + Err(error) => (false, format!("{error:?}")), + } + } + + /// A linear image of `format`, `usage` and `extent` made for dma-bufs, `UNDEFINED`. + fn linear_image( + &self, + format: vk::Format, + usage: vk::ImageUsageFlags, + [width, height]: [u32; 2], + ) -> vk::Image { + let mut external = vk::ExternalMemoryImageCreateInfo::default().handle_types(DMA_BUF); + let info = image_info(format, usage, [width, height]) + .tiling(vk::ImageTiling::LINEAR) + .push_next(&mut external); + // SAFETY: `info` and its chain live for the call; the query took the image's handle type. + unsafe { self.device.create_image(&info, None) }.unwrap() + } + + /// A `DRM_FORMAT_MOD_LINEAR` image of `format`, `usage` and `extent` made for dma-bufs, its + /// one plane at `offset` with rows `pitch` apart, `UNDEFINED`; or the driver's error. + fn modifier_image( + &self, + format: vk::Format, + usage: vk::ImageUsageFlags, + extent: [u32; 2], + (offset, pitch): (u64, u64), + ) -> Result { + let planes = [vk::SubresourceLayout { + offset, + size: 0, + row_pitch: pitch, + array_pitch: 0, + depth_pitch: 0, + }]; + let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default() + .drm_format_modifier(MOD_LINEAR) + .plane_layouts(&planes); + let mut external = vk::ExternalMemoryImageCreateInfo::default().handle_types(DMA_BUF); + let info = image_info(format, usage, extent) + .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) + .push_next(&mut external) + .push_next(&mut explicit); + // SAFETY: `info` and its chain live for the call; the query took such an image. + unsafe { self.device.create_image(&info, None) } + } + + /// The driver's answers of `image`, its layout asked of `aspect`. + fn facts(&self, image: vk::Image, aspect: vk::ImageAspectFlags) -> Facts { + let mut dedicated = vk::MemoryDedicatedRequirements::default(); + let mut requirements = vk::MemoryRequirements2::default().push_next(&mut dedicated); + let query = vk::ImageMemoryRequirementsInfo2::default().image(image); + let subresource = vk::ImageSubresource { + aspect_mask: aspect, + mip_level: 0, + array_layer: 0, + }; + // SAFETY: the image is live; the query is core in Vulkan 1.1; the aspect is its + // tiling's (color of a linear image, the memory plane of a modifier's). + let layout = unsafe { + (self.device).get_image_memory_requirements2(&query, &mut requirements); + self.device.get_image_subresource_layout(image, subresource) + }; + Facts { + requirements: requirements.memory_requirements, + requires: dedicated.requires_dedicated_allocation != vk::FALSE, + prefers: dedicated.prefers_dedicated_allocation != vk::FALSE, + layout, + } + } + + /// Record `record` into the command buffer, submit it, and wait: the microseconds of the + /// submission call and from its return to the fence. + fn submit(&self, record: impl FnOnce(vk::CommandBuffer)) -> (f64, f64) { + let device = &self.device; + let commands = self.commands; + // SAFETY: the command buffer is the pool's and idle (each submission is waited for); + // `record` records valid commands of live objects. + unsafe { + device + .reset_command_buffer(commands, vk::CommandBufferResetFlags::empty()) + .unwrap(); + let begin = vk::CommandBufferBeginInfo::default() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + device.begin_command_buffer(commands, &begin).unwrap(); + } + record(commands); + let buffers = [commands]; + let submit = [vk::SubmitInfo::default().command_buffers(&buffers)]; + // SAFETY: the command buffer is recording; the fence is unsignaled; it ends and is + // submitted, waited for and the fence reset. + unsafe { + device.end_command_buffer(commands).unwrap(); + let called = Instant::now(); + device + .queue_submit(self.queue, &submit, self.fence) + .unwrap(); + let submitted = us(called); + let returned = Instant::now(); + device + .wait_for_fences(&[self.fence], true, 10_000_000_000) + .unwrap(); + let waited = us(returned); + device.reset_fences(&[self.fence]).unwrap(); + (submitted, waited) + } + } + + /// Record the first move of `image`: an acquire from `VK_QUEUE_FAMILY_FOREIGN_EXT` (from + /// `VK_QUEUE_FAMILY_EXTERNAL` where the device enables none), `GENERAL` to `GENERAL`. + fn acquire(&self, commands: vk::CommandBuffer, image: vk::Image) { + let source = match self.foreign { + true => vk::QUEUE_FAMILY_FOREIGN_EXT, + false => vk::QUEUE_FAMILY_EXTERNAL, + }; + let barrier = vk::ImageMemoryBarrier::default() + .dst_access_mask(vk::AccessFlags::MEMORY_READ | vk::AccessFlags::MEMORY_WRITE) + .old_layout(vk::ImageLayout::GENERAL) + .new_layout(vk::ImageLayout::GENERAL) + .src_queue_family_index(source) + .dst_queue_family_index(self.family) + .image(image) + .subresource_range(color_range()); + // SAFETY: the command buffer is recording, outside a render pass; the image is live. + unsafe { + self.device.cmd_pipeline_barrier( + commands, + vk::PipelineStageFlags::TOP_OF_PIPE, + vk::PipelineStageFlags::ALL_COMMANDS, + vk::DependencyFlags::empty(), + &[], + &[], + &[barrier], + ) + }; + } + + /// Record a barrier from every command's writes to the host's reads. + fn to_host(&self, commands: vk::CommandBuffer) { + let barrier = vk::MemoryBarrier::default() + .src_access_mask(vk::AccessFlags::MEMORY_WRITE) + .dst_access_mask(vk::AccessFlags::HOST_READ); + // SAFETY: the command buffer is recording, outside a render pass. + unsafe { + self.device.cmd_pipeline_barrier( + commands, + vk::PipelineStageFlags::ALL_COMMANDS, + vk::PipelineStageFlags::HOST, + vk::DependencyFlags::empty(), + &[barrier], + &[], + &[], + ) + }; + } + + /// Record a copy of `image`'s `extent` texels from its origin into `buffer` at `at`, tightly. + fn copy_out( + &self, + commands: vk::CommandBuffer, + (image, extent): (vk::Image, [u32; 2]), + (buffer, at): (vk::Buffer, u64), + ) { + let region = region(at, extent); + // SAFETY: the command buffer is recording, outside a render pass; the image is live in + // `GENERAL` with transfer-source usage, the buffer live with transfer-destination usage + // and the region inside it. + unsafe { + self.device.cmd_copy_image_to_buffer( + commands, + image, + vk::ImageLayout::GENERAL, + buffer, + &[region], + ) + }; + } + + /// Clear `image` (of `format` and `extent`) to 1.0 in a render pass of it alone, waited for. + fn render_ones(&self, image: vk::Image, format: vk::Format, [width, height]: [u32; 2]) { + let device = &self.device; + let attachment = [vk::AttachmentDescription::default() + .format(format) + .samples(vk::SampleCountFlags::TYPE_1) + .load_op(vk::AttachmentLoadOp::CLEAR) + .store_op(vk::AttachmentStoreOp::STORE) + .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE) + .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE) + .initial_layout(vk::ImageLayout::GENERAL) + .final_layout(vk::ImageLayout::GENERAL)]; + let reference = [vk::AttachmentReference { + attachment: 0, + layout: vk::ImageLayout::GENERAL, + }]; + let subpass = [vk::SubpassDescription::default() + .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) + .color_attachments(&reference)]; + let pass_info = vk::RenderPassCreateInfo::default() + .attachments(&attachment) + .subpasses(&subpass); + let view_info = vk::ImageViewCreateInfo::default() + .image(image) + .view_type(vk::ImageViewType::TYPE_2D) + .format(format) + .subresource_range(color_range()); + // SAFETY: every info is valid and lives for its call; the image is live, with color + // attachment usage. + let (pass, view) = unsafe { + ( + device.create_render_pass(&pass_info, None).unwrap(), + device.create_image_view(&view_info, None).unwrap(), + ) + }; + let views = [view]; + let framebuffer_info = vk::FramebufferCreateInfo::default() + .render_pass(pass) + .attachments(&views) + .width(width) + .height(height) + .layers(1); + // SAFETY: the pass and view are live and match. + let framebuffer = unsafe { device.create_framebuffer(&framebuffer_info, None) }.unwrap(); + let clear = [vk::ClearValue { + color: vk::ClearColorValue { float32: [1.0; 4] }, + }]; + let begin = vk::RenderPassBeginInfo::default() + .render_pass(pass) + .framebuffer(framebuffer) + .render_area(vk::Rect2D { + offset: vk::Offset2D::default(), + extent: vk::Extent2D { width, height }, + }) + .clear_values(&clear); + self.submit(|commands| { + // SAFETY: the command buffer is recording, outside a render pass; the pass, + // framebuffer and image are live, the image in `GENERAL`. + unsafe { + device.cmd_begin_render_pass(commands, &begin, vk::SubpassContents::INLINE); + device.cmd_end_render_pass(commands); + } + self.to_host(commands); + }); + // SAFETY: the submission that used them completed. + unsafe { + device.destroy_framebuffer(framebuffer, None); + device.destroy_image_view(view, None); + device.destroy_render_pass(pass, None); + } + } +} + +impl Drop for Probe { + fn drop(&mut self) { + // SAFETY: every submission was waited for; the objects are the device's and go once. + unsafe { + self.device.device_wait_idle().unwrap(); + self.device.destroy_fence(self.fence, None); + self.device.destroy_command_pool(self.pool, None); + self.device.destroy_device(None); + self.instance.destroy_instance(None); + } + } +} + +/// A 2D image of one level and layer of `format`, `usage` and `extent`, `UNDEFINED`, exclusive. +fn image_info<'a>( + format: vk::Format, + usage: vk::ImageUsageFlags, + [width, height]: [u32; 2], +) -> vk::ImageCreateInfo<'a> { + vk::ImageCreateInfo::default() + .image_type(vk::ImageType::TYPE_2D) + .format(format) + .extent(vk::Extent3D { + width, + height, + depth: 1, + }) + .mip_levels(1) + .array_layers(1) + .samples(vk::SampleCountFlags::TYPE_1) + .usage(usage) + .sharing_mode(vk::SharingMode::EXCLUSIVE) + .initial_layout(vk::ImageLayout::UNDEFINED) +} + +/// The first level and layer of a color image. +fn color_range() -> vk::ImageSubresourceRange { + vk::ImageSubresourceRange { + aspect_mask: vk::ImageAspectFlags::COLOR, + base_mip_level: 0, + level_count: 1, + base_array_layer: 0, + layer_count: 1, + } +} + +/// A copy region of an image's `extent` texels from its origin, the buffer's from `at`, tight. +fn region(at: u64, [width, height]: [u32; 2]) -> vk::BufferImageCopy { + vk::BufferImageCopy { + buffer_offset: at, + buffer_row_length: 0, + buffer_image_height: 0, + image_subresource: vk::ImageSubresourceLayers { + aspect_mask: vk::ImageAspectFlags::COLOR, + mip_level: 0, + base_array_layer: 0, + layer_count: 1, + }, + image_offset: vk::Offset3D::default(), + image_extent: vk::Extent3D { + width, + height, + depth: 1, + }, + } +} + +/// The runtime's `minimumLinearTextureAlignmentForPixelFormat` answer of each of [`FORMATS`] on +/// the device the cfg selects. +fn runtime_alignments() -> Vec { + let scratch = Scratch::new(); + let device = device(&scratch.0); + let alignments = FORMATS + .iter() + .map(|&(_, _, metal)| { + (device.minimum_linear_texture_alignment_for_pixel_format(metal)).unwrap() + }) + .collect(); + drop(device); + alignments +} + +/// The pages' bytes: the probe's view of them, which no command reads or writes while the probe +/// does (each submission is waited for). +struct Pages<'a>(&'a Ram); + +impl Pages<'_> { + /// The address `at` bytes in, of `len` bytes inside the view. + fn at(&self, at: u64, len: u64) -> *mut u8 { + assert!((at + len) as usize <= RAM_BYTES); + self.0.pointer(at as usize).as_ptr() + } + + /// A copy of the `len` bytes from `at`. + fn read(&self, at: u64, len: u64) -> Vec { + let mut bytes = vec![0; len as usize]; + // SAFETY: inside the view, which lives while `self.0` does; no command writes them now. + unsafe { std::ptr::copy_nonoverlapping(self.at(at, len), bytes.as_mut_ptr(), bytes.len()) }; + bytes + } + + /// Write `bytes` from `at`. + fn write(&self, at: u64, bytes: &[u8]) { + let to = self.at(at, bytes.len() as u64); + // SAFETY: inside the view, which lives while `self.0` does; no command reads them now. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), to, bytes.len()) }; + } + + /// Write `len` bytes of `value` from `at`. + fn fill(&self, at: u64, len: u64, value: u8) { + // SAFETY: as `write`. + unsafe { std::ptr::write_bytes(self.at(at, len), value, len as usize) }; + } + + /// Lay out an image's bytes at `at`: `rows` rows `pitch` apart, of `row` bytes of texels of + /// the pattern of `seed`, their padding [`PADDING`], and [`AROUND`] from [`GUARD`] before + /// them to `size` bytes and [`GUARD`] after. + fn lay(&self, at: u64, (row, pitch, rows): (u64, u64, u64), size: u64, seed: u64) { + self.fill(at - GUARD, GUARD, AROUND); + let end = rows * pitch; + self.fill(at + end, size.max(end) - end + GUARD, AROUND); + for r in 0..rows { + let line: Vec = (0..pitch) + .map(|b| { + if b < row { + pattern(seed, r, b) + } else { + PADDING + } + }) + .collect(); + self.write(at + r * pitch, &line); + } + } + + /// The first byte that differs from the image's bytes laid out by [`lay`](Self::lay) with + /// texels of `texel(r, b)`: where from `at`, what it is and what it should be. + fn differs( + &self, + at: u64, + (row, pitch, rows): (u64, u64, u64), + size: u64, + texel: impl Fn(u64, u64) -> u8, + ) -> Option<(i64, u8, u8)> { + let before = self.read(at - GUARD, GUARD); + if let Some(i) = before.iter().position(|&byte| byte != AROUND) { + return Some((i as i64 - GUARD as i64, before[i], AROUND)); + } + let end = rows * pitch; + let after = self.read(at + end, size.max(end) - end + GUARD); + if let Some(i) = after.iter().position(|&byte| byte != AROUND) { + return Some(((end + i as u64) as i64, after[i], AROUND)); + } + let lines = self.read(at, end); + for r in 0..rows { + for b in 0..pitch { + let byte = lines[(r * pitch + b) as usize]; + let should = if b < row { texel(r, b) } else { PADDING }; + if byte != should { + return Some(((r * pitch + b) as i64, byte, should)); + } + } + } + None + } +} + +/// What a check found, in words. +fn verdict(differs: Option<(i64, u8, u8)>) -> String { + match differs { + None => "ok".to_owned(), + Some((at, byte, should)) => format!("FAIL(byte {at}: {byte:#04x} not {should:#04x})"), + } +} + +/// The driver's answers of each format's linear images for dma-bufs (`LINBIND-QUERY`, +/// `LINBIND-LAYOUT`, `LINBIND-SHARE`). +fn answers(probe: &Probe, alignments: &[u64]) { + for (&(format, texel, _), &runtime) in FORMATS.iter().zip(alignments) { + let named = name(format); + // SAFETY: the instance's. + let features = unsafe { + (probe.instance).get_physical_device_format_properties(probe.physical, format) + }; + for (usage_name, usage) in usages() { + let linear = vk::ImageTiling::LINEAR; + let (takes, words) = probe.takes(format, usage, linear); + let modifier = match probe.modifiers { + true => { + probe + .takes(format, usage, vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) + .1 + } + false => "not enabled".to_owned(), + }; + println!( + "LINBIND-QUERY {named} {usage_name}: linear tiling features {:#x}; linear for \ + dma-bufs: {words}; DRM_FORMAT_MOD_LINEAR for dma-bufs: {modifier}", + features.linear_tiling_features.as_raw() + ); + if probe.modifiers { + modifier_answers(probe, (format, texel), (usage_name, usage)); + } + if !takes { + continue; + } + let mut matched = [0; METAL_ALIGNMENTS.len() + 1]; + for width in WIDTHS { + let image = probe.linear_image(format, usage, [width, LAYOUT_ROWS]); + let facts = probe.facts(image, vk::ImageAspectFlags::COLOR); + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { probe.device.destroy_image(image, None) }; + let tight = u64::from(width) * texel; + let pitch = facts.layout.row_pitch; + let rule = METAL_ALIGNMENTS.iter().chain([&runtime]); + let equal: Vec = (rule.enumerate()) + .map(|(i, &alignment)| { + let metal = up(tight, alignment); + let same = metal == pitch && facts.layout.offset == 0; + matched[i] += usize::from(same); + format!("{alignment}:{}", if same { "=" } else { "x" }) + }) + .collect(); + println!( + "LINBIND-LAYOUT {named} {usage_name} width {width}: row pitch {pitch} \ + (texels {tight}), offset {}, size {} (rows x pitch {}), alignment {}, types \ + {:#x}, requires dedicated {}, prefers dedicated {}; Metal's pitch at {} \ + (runtime {runtime})", + facts.layout.offset, + facts.requirements.size, + u64::from(LAYOUT_ROWS) * pitch, + facts.requirements.alignment, + facts.requirements.memory_type_bits, + facts.requires, + facts.prefers, + equal.join(" ") + ); + } + println!( + "LINBIND-SHARE {named} {usage_name}: widths whose Metal pitch is the driver's, \ + of {}: at 16 {}, at 64 {}, at 256 {}, at the runtime's {runtime} {}", + WIDTHS.len(), + matched[0], + matched[1], + matched[2], + matched[3] + ); + } + } +} + +/// Whether the driver binds a `DRM_FORMAT_MOD_LINEAR` image of `format` (texels of `texel` +/// bytes) and `usage` for dma-bufs at an offset of memory it shares, as an image made for the +/// buffer's import would be (`LINBIND-MODIFIER`): per width of [`BIND_WIDTHS`], its plane at +/// offset 0 with rows the texels' bytes rounded up to 256 apart, whether it requires or prefers a +/// dedicated allocation, its alignment and size, and its plane as laid out. +fn modifier_answers( + probe: &Probe, + (format, texel): (vk::Format, u64), + (usage_name, usage): (&str, vk::ImageUsageFlags), +) { + if !probe + .takes(format, usage, vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) + .0 + { + return; + } + let named = name(format); + for width in BIND_WIDTHS { + let pitch = up(u64::from(width) * texel, 256); + let what = format!("LINBIND-MODIFIER {named} {usage_name} width {width} pitch {pitch}"); + match probe.modifier_image(format, usage, [width, LAYOUT_ROWS], (0, pitch)) { + Ok(image) => { + let facts = probe.facts(image, vk::ImageAspectFlags::MEMORY_PLANE_0_EXT); + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { probe.device.destroy_image(image, None) }; + println!( + "{what}: requires dedicated {}, prefers dedicated {}, alignment {}, size {}, \ + plane laid at {} with rows {} apart", + facts.requires, + facts.prefers, + facts.requirements.alignment, + facts.requirements.size, + facts.layout.offset, + facts.layout.row_pitch + ); + } + Err(error) => println!("{what}: refused ({error:?})"), + } + } +} + +/// Each format's linear image bound in the import and used (`LINBIND-BIND`). +fn binds(probe: &Probe, import: &Import, pages: &Pages<'_>) { + let page = host_page() as u64; + for &(format, texel, _) in &FORMATS { + let named = name(format); + let [(_, read), (_, render), _] = usages(); + let renders = probe.takes(format, render, vk::ImageTiling::LINEAR).0; + let usage = if renders { render } else { read }; + if !probe.takes(format, usage, vk::ImageTiling::LINEAR).0 { + println!("LINBIND-BIND {named}: the query takes no dma-buf for its linear image"); + continue; + } + for width in BIND_WIDTHS { + let extent = [width, BIND_ROWS]; + let image = probe.linear_image(format, usage, extent); + let facts = probe.facts(image, vk::ImageAspectFlags::COLOR); + let alignment = facts.requirements.alignment.max(1); + // An offset that meets the alignment, and lies inside a page where it can. + let at = match alignment < page { + true => BIND_AT + alignment.max(GUARD), + false => up(BIND_AT, alignment), + }; + let at = up(at, alignment); + let size = facts.requirements.size; + let shape = ( + u64::from(width) * texel, + facts.layout.row_pitch, + u64::from(BIND_ROWS), + ); + let what = format!( + "LINBIND-BIND {named} {width}x{BIND_ROWS} {}: at {at} (page offset {}), pitch \ + {}, size {size}, requires dedicated {}", + if renders { "render" } else { "read" }, + at % page, + facts.layout.row_pitch, + facts.requires + ); + let typed = facts.requirements.memory_type_bits & (1 << import.type_index) != 0; + assert!( + at + size <= OUT_AT, + "the bound image fits before the copies" + ); + if facts.requires || facts.layout.offset != 0 || !typed { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { probe.device.destroy_image(image, None) }; + println!( + "{what}: not bound (dedicated, its subresource at offset {}, or types {:#x} \ + without the import's {})", + facts.layout.offset, facts.requirements.memory_type_bits, import.type_index + ); + continue; + } + // SAFETY: the image is unbound and made for dma-bufs, the import's handle type; the + // memory is no dedicated allocation, of a type its bits take, the offset a multiple + // of its alignment and its size inside the memory. + let bound = unsafe { probe.device.bind_image_memory(image, import.memory, at) }; + if let Err(error) = bound { + // SAFETY: as above. + unsafe { probe.device.destroy_image(image, None) }; + println!("{what}: the driver refuses the binding ({error:?})"); + continue; + } + // The texels the CPU wrote, read back through a copy (with the first move). + pages.lay(at, shape, size, 1); + probe.submit(|commands| { + probe.acquire(commands, image); + probe.copy_out(commands, (image, extent), (import.buffer, OUT_AT)); + probe.to_host(commands); + }); + let row = shape.0; + let out = pages.read(OUT_AT, row * u64::from(BIND_ROWS)); + let read_back = (0..u64::from(BIND_ROWS)) + .flat_map(|r| (0..row).map(move |b| (r, b))) + .find(|&(r, b)| out[(r * row + b) as usize] != pattern(1, r, b)); + let read_words = match read_back { + None => "ok".to_owned(), + Some((r, b)) => format!("FAIL(row {r} byte {b})"), + }; + let around = verdict(pages.differs(at, shape, size, |r, b| pattern(1, r, b))); + // Written by a copy of a pattern of its own. + pages.lay(at, shape, size, 1); + let source: Vec = (0..u64::from(BIND_ROWS)) + .flat_map(|r| (0..row).map(move |b| pattern(2, r, b))) + .collect(); + pages.write(SOURCE_AT, &source); + probe.submit(|commands| { + let region = region(SOURCE_AT, extent); + // SAFETY: the command buffer is recording, outside a render pass; the image is + // live in `GENERAL` with transfer-destination usage, the region inside the buffer. + unsafe { + probe.device.cmd_copy_buffer_to_image( + commands, + import.buffer, + image, + vk::ImageLayout::GENERAL, + &[region], + ) + }; + probe.to_host(commands); + }); + let written = verdict(pages.differs(at, shape, size, |r, b| pattern(2, r, b))); + // Cleared, and rendered. + let one = ones(format); + let is_one = |_: u64, b: u64| one[(b % texel) as usize]; + pages.lay(at, shape, size, 1); + probe.submit(|commands| { + let value = vk::ClearColorValue { float32: [1.0; 4] }; + // SAFETY: the command buffer is recording, outside a render pass; the image is + // live in `GENERAL` with transfer-destination usage. + unsafe { + probe.device.cmd_clear_color_image( + commands, + image, + vk::ImageLayout::GENERAL, + &value, + &[color_range()], + ) + }; + probe.to_host(commands); + }); + let cleared = verdict(pages.differs(at, shape, size, is_one)); + let rendered = match renders { + true => { + pages.lay(at, shape, size, 1); + probe.render_ones(image, format, extent); + verdict(pages.differs(at, shape, size, is_one)) + } + false => "no render usage".to_owned(), + }; + // SAFETY: every submission that used it completed. + unsafe { probe.device.destroy_image(image, None) }; + println!( + "{what}: read {read_words} (bytes around {around}), written {written}, cleared \ + {cleared}, rendered {rendered}" + ); + } + } +} + +/// One first use's microseconds: the image made and checked, its pages' dma-buf, their import, +/// the binding, the submission call, the wait, and the release after. +#[derive(Default)] +struct Steps { + image: f64, + dma_buf: f64, + import: f64, + bind: f64, + submit: f64, + wait: f64, + release: f64, +} + +impl Steps { + /// Its steps to the first use's end. + fn total(&self) -> f64 { + self.image + self.dma_buf + self.import + self.bind + self.submit + self.wait + } +} + +/// A first use of a `BGRA8Unorm` texture of `extent` whose texels lie at `at` rows `pitch` +/// apart, today's way: a `DRM_FORMAT_MOD_LINEAR` image at that pitch, a `udmabuf` of its pages, +/// a dedicated import of it bound at 0; why not. +fn today( + probe: &Probe, + (ram, import): (&Ram, &Import), + extent: [u32; 2], + (at, pitch): (u64, u64), +) -> Result { + let page = host_page() as u64; + let usage = usages()[0].1; + let format = vk::Format::B8G8R8A8_UNORM; + if !probe + .takes(format, usage, vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) + .0 + { + return Err("the query takes no dma-buf for its DRM_FORMAT_MOD_LINEAR image".to_owned()); + } + let mut steps = Steps::default(); + let started = Instant::now(); + let offset = at % page; + let image = (probe.modifier_image(format, usage, extent, (offset, pitch))) + .map_err(|error| format!("the modifier image is refused ({error:?})"))?; + let facts = probe.facts(image, vk::ImageAspectFlags::MEMORY_PLANE_0_EXT); + steps.image = us(started); + let release = |memory: Option| { + // SAFETY: no command uses them any more. + unsafe { + probe.device.destroy_image(image, None); + if let Some(memory) = memory { + probe.device.free_memory(memory, None); + } + } + }; + if facts.layout.offset != offset || facts.layout.row_pitch != pitch { + release(None); + return Err(format!( + "the driver lays the plane at {} with rows {} apart", + facts.layout.offset, facts.layout.row_pitch + )); + } + let started = Instant::now(); + let length = up(offset + facts.requirements.size, page); + let fd = udmabuf(ram.file(), at - offset, length).map_err(|error| { + release(None); + format!("udmabuf: {error}") + })?; + steps.dma_buf = us(started); + let started = Instant::now(); + let bits = facts.requirements.memory_type_bits; + let size = facts.requirements.size; + let (memory, _) = (probe.import(fd, size, bits, Some(image))).inspect_err(|_| release(None))?; + steps.import = us(started); + let started = Instant::now(); + // SAFETY: the image is unbound; the memory is its dedicated import, of its size. + unsafe { probe.device.bind_image_memory(image, memory, 0) }.unwrap(); + steps.bind = us(started); + (steps.submit, steps.wait) = probe.submit(|commands| { + probe.acquire(commands, image); + let first = [FIRST_COPY, FIRST_COPY]; + probe.copy_out(commands, (image, first), (import.buffer, OUT_AT)); + probe.to_host(commands); + }); + let started = Instant::now(); + release(Some(memory)); + steps.release = us(started); + Ok(steps) +} + +/// The same first use, the driver's linear image for dma-bufs bound at `at` of the pages' import; +/// why not. +fn linear( + probe: &Probe, + import: &Import, + extent: [u32; 2], + (at, pitch): (u64, u64), +) -> Result { + let usage = usages()[0].1; + let format = vk::Format::B8G8R8A8_UNORM; + let mut steps = Steps::default(); + let started = Instant::now(); + let image = probe.linear_image(format, usage, extent); + let facts = probe.facts(image, vk::ImageAspectFlags::COLOR); + steps.image = us(started); + let release = || { + // SAFETY: no command uses it any more. + unsafe { probe.device.destroy_image(image, None) }; + }; + let alignment = facts.requirements.alignment.max(1); + let typed = facts.requirements.memory_type_bits & (1 << import.type_index) != 0; + let fits = at + facts.requirements.size <= OUT_AT; + if facts.requires || facts.layout.row_pitch != pitch || !at.is_multiple_of(alignment) { + release(); + return Err(format!( + "requires dedicated {}, pitch {}, alignment {alignment}", + facts.requires, facts.layout.row_pitch + )); + } + if !typed || !fits { + release(); + return Err(format!( + "types {:#x} without the import's {}, or {} bytes past the pages", + facts.requirements.memory_type_bits, import.type_index, facts.requirements.size + )); + } + let started = Instant::now(); + // SAFETY: the image is unbound and made for dma-bufs; the memory is no dedicated allocation, + // of a type it takes, the offset a multiple of its alignment and its size inside it. + unsafe { probe.device.bind_image_memory(image, import.memory, at) }.unwrap(); + steps.bind = us(started); + (steps.submit, steps.wait) = probe.submit(|commands| { + probe.acquire(commands, image); + let first = [FIRST_COPY, FIRST_COPY]; + probe.copy_out(commands, (image, first), (import.buffer, OUT_AT)); + probe.to_host(commands); + }); + let started = Instant::now(); + release(); + steps.release = us(started); + Ok(steps) +} + +/// The same first use, a `DRM_FORMAT_MOD_LINEAR` image whose plane lies at `at` of the pages' +/// whole dma-buf (`kept`, a descriptor of the one the import was made of), bound to a dedicated +/// import of that dma-buf again (Vulkan imports a payload any number of times into an instance, +/// each a memory of its own: Memory Allocation, "Importing Memory Using a File Descriptor"): no +/// new dma-buf, though an import of its own; why not. +fn reimport( + probe: &Probe, + (kept, import): (&OwnedFd, &Import), + extent: [u32; 2], + (at, pitch): (u64, u64), +) -> Result { + let usage = usages()[0].1; + let format = vk::Format::B8G8R8A8_UNORM; + if !probe + .takes(format, usage, vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) + .0 + { + return Err("the query takes no dma-buf for its DRM_FORMAT_MOD_LINEAR image".to_owned()); + } + let mut steps = Steps::default(); + let started = Instant::now(); + let image = (probe.modifier_image(format, usage, extent, (at, pitch))) + .map_err(|error| format!("the modifier image at {at} is refused ({error:?})"))?; + let facts = probe.facts(image, vk::ImageAspectFlags::MEMORY_PLANE_0_EXT); + steps.image = us(started); + let release = |memory: Option| { + // SAFETY: no command uses them any more. + unsafe { + probe.device.destroy_image(image, None); + if let Some(memory) = memory { + probe.device.free_memory(memory, None); + } + } + }; + let size = facts.requirements.size; + if facts.layout.offset != at || facts.layout.row_pitch != pitch || size > RAM_BYTES as u64 { + release(None); + return Err(format!( + "the driver lays the plane at {} with rows {} apart, its memory {size} bytes", + facts.layout.offset, facts.layout.row_pitch + )); + } + let started = Instant::now(); + let fd = kept.try_clone().map_err(|error| { + release(None); + format!("dup: {error}") + })?; + steps.dma_buf = us(started); + let started = Instant::now(); + let bits = facts.requirements.memory_type_bits; + let (memory, _) = (probe.import(fd, size, bits, Some(image))).inspect_err(|_| release(None))?; + steps.import = us(started); + let started = Instant::now(); + // SAFETY: the image is unbound; the memory is its dedicated import, at least its size. + unsafe { probe.device.bind_image_memory(image, memory, 0) }.unwrap(); + steps.bind = us(started); + (steps.submit, steps.wait) = probe.submit(|commands| { + probe.acquire(commands, image); + let first = [FIRST_COPY, FIRST_COPY]; + probe.copy_out(commands, (image, first), (import.buffer, OUT_AT)); + probe.to_host(commands); + }); + let started = Instant::now(); + release(Some(memory)); + steps.release = us(started); + Ok(steps) +} + +/// Each shape's first use each way (`LINBIND-TIME`). +fn timed(probe: &Probe, (ram, import): (&Ram, &Import), pages: &Pages<'_>, kept: &OwnedFd) { + let format = vk::Format::B8G8R8A8_UNORM; + let usage = usages()[0].1; + let linear_taken = probe.takes(format, usage, vk::ImageTiling::LINEAR).0; + for extent in TIMED { + // The driver's pitch where it makes the linear image, else the texels' at 256. + let pitch = match linear_taken { + true => { + let image = probe.linear_image(format, usage, extent); + let pitch = probe + .facts(image, vk::ImageAspectFlags::COLOR) + .layout + .row_pitch; + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { probe.device.destroy_image(image, None) }; + pitch + } + false => up(u64::from(extent[0]) * 4, 256), + }; + let bytes = pitch * u64::from(extent[1]); + assert!( + TIMED_AT + bytes <= OUT_AT, + "the timed texture fits before the copies" + ); + pages.fill(TIMED_AT, bytes, 0x33); + let mut ways: [(&str, Vec); 3] = [ + ("today", Vec::new()), + ("linear", Vec::new()), + ("reimport", Vec::new()), + ]; + for round in 0..ROUNDS { + for (way, runs) in &mut ways { + let place = (TIMED_AT, pitch); + let steps = match *way { + "today" | "reimport" if !probe.modifiers => { + Err("no DRM format modifiers".to_owned()) + } + "today" => today(probe, (ram, import), extent, place), + "reimport" => reimport(probe, (kept, import), extent, place), + _ if linear_taken => linear(probe, import, extent, place), + _ => Err("the query takes no dma-buf for the linear image".to_owned()), + }; + let [width, height] = extent; + match steps { + Ok(steps) => { + println!( + "LINBIND-TIME {width}x{height} pitch {pitch} {way} round {round}{}: \ + image {:.0} dma-buf {:.0} import {:.0} bind {:.0} submit {:.0} wait \ + {:.0} total {:.0} release {:.0} us", + if round == 0 { " (warm-up)" } else { "" }, + steps.image, + steps.dma_buf, + steps.import, + steps.bind, + steps.submit, + steps.wait, + steps.total(), + steps.release + ); + if round > 0 { + runs.push(steps); + } + } + Err(why) => println!("LINBIND-TIME {width}x{height} {way}: not run: {why}"), + } + } + } + for (way, runs) in &ways { + if runs.is_empty() { + continue; + } + let of = |step: fn(&Steps) -> f64| median(runs.iter().map(step).collect()); + println!( + "LINBIND-TIME {}x{} {way} median of {}: image {:.0} dma-buf {:.0} import {:.0} \ + bind {:.0} submit {:.0} wait {:.0} total {:.0} release {:.0} us", + extent[0], + extent[1], + runs.len(), + of(|s| s.image), + of(|s| s.dma_buf), + of(|s| s.import), + of(|s| s.bind), + of(|s| s.submit), + of(|s| s.wait), + of(Steps::total), + of(|s| s.release) + ); + } + } +} + +#[test] +#[ignore = "a measurement: run it by name in release, with --run-ignored all"] +fn dma_buf_linear_bind() { + if !udmabuf_openable("dma_buf_linear_bind") { + return; + } + let alignments = runtime_alignments(); + let Some(probe) = Probe::new() else { + return; + }; + let ram = Ram::new(RAM_BYTES, 0, RAM_BYTES); + let pages = Pages(&ram); + // Every page written once, so each dma-buf pins pages that are there. + pages.fill(0, RAM_BYTES as u64, 0); + let whole = udmabuf(ram.file(), 0, RAM_BYTES as u64).unwrap(); + let kept = whole.try_clone().unwrap(); + let import = probe.buffer_import(whole, RAM_BYTES as u64); + // The import used once, so no timed first use pays its first submission. + probe.submit(|commands| { + // SAFETY: the command buffer is recording, outside a render pass; the buffer is live + // with transfer-destination usage and the range inside it. + unsafe { (probe.device).cmd_fill_buffer(commands, import.buffer, OUT_AT, 4096, 0) }; + probe.to_host(commands); + }); + answers(&probe, &alignments); + binds(&probe, &import, &pages); + timed(&probe, (&ram, &import), &pages, &kept); + // SAFETY: every submission that used them completed. + unsafe { + probe.device.destroy_buffer(import.buffer, None); + probe.device.free_memory(import.memory, None); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_parked_images.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_parked_images.rs index d4b045fef..05743b815 100644 --- a/crates/metal2vulkan-runtime/src/tests/dma_buf_parked_images.rs +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_parked_images.rs @@ -31,7 +31,9 @@ //! `DRM_FORMAT_MOD_LINEAR` images, or the texture is a shadow (the device's check did not pass //! for such pages), it says so and passes without running. -use super::host_residency::{counting, host_page, udmabuf_openable, Ram, Scratch}; +use super::host_residency::{ + counting, host_page, own_dma_buf_images, udmabuf_openable, Ram, Scratch, +}; use super::merge_scratch::{blit, read}; use super::no_pointer_import::{device, lists_dma_buf_route}; use crate::{ @@ -108,6 +110,9 @@ fn a_texture_over_the_pages_of_one_that_went_takes_its_image() { device.settle_in_place_checks(CHECK_WAIT), "{TEST}: the check" ); + // The images in dma-buf imports of their own, which park, whatever the check of images in + // the buffer's import answered. + own_dma_buf_images(&device); let queue = device.new_command_queue().unwrap(); let length = ROW * HEIGHT; let file = (length as usize).next_multiple_of(host_page()); diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_plane_offset.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_plane_offset.rs index 34e0fdffb..8973f19f5 100644 --- a/crates/metal2vulkan-runtime/src/tests/dma_buf_plane_offset.rs +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_plane_offset.rs @@ -38,7 +38,9 @@ //! Where `/dev/udmabuf` cannot be opened, or the device lists no dma-buf route or makes no //! `DRM_FORMAT_MOD_LINEAR` images, it says so and passes without running. -use super::host_residency::{counting, host_page, udmabuf_openable, Ram, Scratch}; +use super::host_residency::{ + counting, host_page, own_dma_buf_images, udmabuf_openable, Ram, Scratch, +}; use super::merge_scratch::{blit, read}; use super::no_pointer_import::{device, lists_dma_buf_route}; use crate::dma_buf::PlaneRoute; @@ -406,6 +408,9 @@ fn a_texture_over_dma_buf_pages_past_a_page_s_first_byte_reads_its_texels_by_eac device.settle_in_place_checks(CHECK_WAIT), "{TEST}: the check" ); + // The images in dma-buf imports of their own, whatever the check of images in the buffer's + // import answered. + own_dma_buf_images(&device); for line in device.in_place_check_report() { if line.starts_with("DmaBuf") { println!("{TEST} on {name}: the check: {line}"); diff --git a/crates/metal2vulkan-runtime/src/tests/host_residency.rs b/crates/metal2vulkan-runtime/src/tests/host_residency.rs index a6d7bc3b3..d9248390d 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_residency.rs @@ -493,6 +493,22 @@ pub(super) fn gpu_fill( run(&command_buffer); } +/// Fail every verdict of `device`'s check of images bound in the import a no-copy buffer's +/// dma-buf pages lie in (`PagesClass::DmaBufInImport`), once its check answered: a texture in +/// place over such pages then takes the image in a dma-buf import of its own +/// (`Device::dma_buf_image`), as on a device whose check leaves that class unchecked (RADV, whose +/// such images require a dedicated allocation): for the tests of that image's import, its parks +/// and its residency. +pub(super) fn own_dma_buf_images(device: &Device) { + use crate::in_place::{Access, PagesClass, RowEnds, Verdict}; + let in_place = &device.shared().in_place; + for access in Access::ALL { + for rows in RowEnds::ALL { + in_place.set(PagesClass::DmaBufInImport, access, rows, Verdict::Failed); + } + } +} + /// Release `count` idle imports through the hook, retried until the command buffers that read /// them let go (each at its completion, on the device's handler thread), within [`SETTLE`]. pub(super) fn release(test: &str, device: &Device, count: usize) { @@ -871,6 +887,8 @@ fn a_texture_in_place_over_a_dma_buf_import_leaves_it_releasable() { device.settle_in_place_checks(CHECKS), "{TEST}: the in-place checks never answered" ); + // The image in a dma-buf import of its own, whatever the check of the other answered. + own_dma_buf_images(device); let page = host_page(); let len = 4 * page; // `BGRA8Unorm` rows of 256 bytes, a multiple of every plane pitch RADV lays out. diff --git a/crates/metal2vulkan-runtime/src/tests/in_place.rs b/crates/metal2vulkan-runtime/src/tests/in_place.rs index 3188d161c..fe65655e9 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place.rs @@ -128,7 +128,7 @@ fn next(verdict: Verdict) -> Verdict { fn of_host_pages(class: PagesClass) -> bool { matches!( class, - PagesClass::Pointer | PagesClass::Fresh | PagesClass::DmaBuf + PagesClass::Pointer | PagesClass::Fresh | PagesClass::DmaBuf | PagesClass::DmaBufInImport ) } @@ -330,7 +330,13 @@ fn a_texture_that_renders_lends_its_free_padding_where_the_copies_change_it_too( (decided, asked.into_inner()) }; let lent = [Access::Renders, Access::Copies, Access::UnobservedRenders]; - for class in [PagesClass::Pointer, PagesClass::Fresh, PagesClass::DmaBuf] { + let host = [ + PagesClass::Pointer, + PagesClass::Fresh, + PagesClass::DmaBuf, + PagesClass::DmaBufInImport, + ]; + for class in host { assert_eq!( decide(class, Padding::Free, Failed), (Ok(()), lent.to_vec()), diff --git a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs index 5ad09ad24..68fc01be8 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs @@ -689,6 +689,8 @@ fn the_in_place_check_imports_its_dma_buf_pages_as_dma_bufs() { let start = only.contents().map_or(0, |at| at.as_ptr().addr() as u64); let rows = RowEnds::of(start, &layout, device.shared().in_place.line()); let reads = device.in_place_verdict(PagesClass::DmaBuf, Access::Reads, rows); + // The image bound in the buffer's own import, where that class passed (`texture/route.rs`). + let in_import = device.in_place_verdict(PagesClass::DmaBufInImport, Access::Reads, rows); let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, w, h, false); descriptor.usage = TextureUsage::SHADER_READ; descriptor.resource_options = only.resource_options(); @@ -699,8 +701,8 @@ fn the_in_place_check_imports_its_dma_buf_pages_as_dma_bufs() { "IN-PLACE-DMA-BUF on {}: pointer-first import over the dma-buf {}, dma-buf-only {}; the \ DmaBuf verdicts (rows in lines, then on lines; reads, renders, writes, buffer writes, \ narrow writes, narrow buffer writes) \ - {verdicts:?}; a 234x18 BGRA8Unorm texture at 1024-byte rows ({rows:?}, reads {reads:?}) \ - in place {in_place}", + {verdicts:?}; a 234x18 BGRA8Unorm texture at 1024-byte rows ({rows:?}, reads {reads:?}, \ + in the import {in_import:?}) in place {in_place}", device.name(), pointer_first.over_dma_buf(), only.over_dma_buf() @@ -719,7 +721,12 @@ fn the_in_place_check_imports_its_dma_buf_pages_as_dma_bufs() { let verdict = device.in_place_verdict(PagesClass::DmaBuf, Access::Reads, rows); assert_ne!(verdict, InPlaceVerdict::Unchecked, "DmaBuf reads, {rows:?}"); } - assert_eq!(in_place, reads == InPlaceVerdict::Passed, "{reads:?}"); + let passed = InPlaceVerdict::Passed; + assert_eq!( + in_place, + reads == passed || in_import == passed, + "{reads:?}, {in_import:?}" + ); drop(texture); drop((pointer_first, only)); // Their imports' frees and keep-alives' drops go on a handler thread; the device's last drop diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 1b4e454ab..112d4e00e 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -211,10 +211,14 @@ mod dma_buf_first_imports; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod dma_buf_import_cycles; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] +mod dma_buf_in_import; +#[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod dma_buf_kept_files; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod dma_buf_leak_probe; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] +mod dma_buf_linear_bind; +#[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod dma_buf_parked_images; #[cfg(unix)] mod dma_buf_pieces; diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 048008d91..2ee9cb51f 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -2907,7 +2907,10 @@ impl Device { } => { let checking = in_place::checking(); let made = (&*texels, class, storable); - let cause = match self.in_place_image(&plan, descriptor, made, &facts)? { + // The class whose image it is: over dma-buf pages, the image in an import of its + // own where the one in the buffer's import was refused (`in_place_image`). + let (made, class) = self.in_place_image(&plan, descriptor, made, &facts)?; + let cause = match made { Ok((image, pitched)) => { if !checking { let counts = &self.shared().counts; diff --git a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs index 34dfb08f4..6a5e2c531 100644 --- a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs @@ -18,12 +18,27 @@ //! else a `DRM_FORMAT_MOD_LINEAR` one at that pitch made `UNDEFINED` (`Device::own_unbound`); //! bound in the copy's memory at the texels' offset, as over an import of the pages, and made //! again over a rebind's new pages as an image in place over the pages is. -//! - **Over pages imported as dma-bufs** (`dma_buf.rs`): the `DRM_FORMAT_MOD_LINEAR` image at the -//! texture's pitches bound to a dedicated import of the one dma-buf the pages' source makes of -//! its own pages ([`Device::dma_buf_image`]), as a no-copy heap's texture there takes, its first -//! move an acquire from `VK_QUEUE_FAMILY_FOREIGN_EXT`. It parks with its import under the -//! pages' import as it goes, and the next texture over the same pages of the same plan at the -//! same texels and pitches takes it ([`Device::take_parked`], `dma_buf/parked.rs`). +//! - **Over pages imported as dma-bufs** (`dma_buf.rs`), its first move an acquire from +//! `VK_QUEUE_FAMILY_FOREIGN_EXT`, in one of two forms, each under its own class of the device's +//! check (`texture/route.rs` picks the first whose verdicts take the texture): +//! - **In the pages' import** (`PagesClass::DmaBufInImport`): where the pages lie in one +//! import dedicated to nothing (no sparse buffer over several, no import the driver made +//! dedicated to the buffer), the `DRM_FORMAT_MOD_LINEAR` image whose one plane lies at offset +//! 0 at the texture's pitches, bound in that import at the texels' offset, beside the buffer +//! (`Device::in_import_image_unbound`): no dma-buf asked of the source and no import of its +//! own (`WorkCounts::dma_buf_images_in_import`). Only where the image requires no dedicated +//! allocation, the format query takes dma-bufs for it outside one, its memory's alignment +//! divides the offset and its memory fits in the pages' placement, each asked of the driver +//! (RADV requires a dedicated allocation of every such image, so its check leaves the class +//! unchecked). Binding there reads the import apart: it is kept imported for good from then +//! on (`host_residency.rs`). It parks nothing. +//! - **In a dma-buf import of its own** (`PagesClass::DmaBuf`): the `DRM_FORMAT_MOD_LINEAR` +//! image at the texture's pitches bound to a dedicated import of the one dma-buf the pages' +//! source makes of its own pages ([`Device::dma_buf_image`]), as a no-copy heap's texture +//! there takes; where the first form's verdicts do not take the texture, or its making +//! refuses it and this form's verdicts take it. It parks with its import under the pages' +//! import as it goes, and the next texture over the same pages of the same plan at the same +//! texels and pitches takes it ([`Device::take_parked`], `dma_buf/parked.rs`). //! - **Its rows.** Rows (and slices) that lie apart are held: the bytes between them are in the //! image's subresource, and its first move is the one operation that may touch them, which the //! device's check covers. Rows that share bytes (an IOSurface plane's GPU rows) are not: no image @@ -131,6 +146,17 @@ enum Unplaced { type_index: u32, at: u64, }, + /// Over pages imported as dma-bufs that lie in one import dedicated to nothing: the + /// `DRM_FORMAT_MOD_LINEAR` image to bind in that import, its requirements, the pages, and the + /// texels' offset in the import's memory, where its requirements were checked to take it + /// (`placed`), the import read as a blit reads it (`HostPages::in_one_dma_buf_import`). + #[cfg(unix)] + InImport { + raw: vk::Image, + requirements: vk::MemoryRequirements, + pages: Arc, + at: u64, + }, } impl Unplaced { @@ -140,6 +166,8 @@ impl Unplaced { match self { Unplaced::Host { .. } => None, #[cfg(unix)] + Unplaced::InImport { .. } => None, + #[cfg(unix)] Unplaced::DmaBuf { unbound, .. } => Some(unbound.asked()), } } @@ -230,7 +258,7 @@ fn in_place_memory(texels: &Texels, class: PagesClass) -> Result Ok(ModifierMemory::Own), _ if copied => Ok(ModifierMemory::Host), - PagesClass::DmaBuf => Ok(ModifierMemory::DmaBuf), + PagesClass::DmaBuf | PagesClass::DmaBufInImport => Ok(ModifierMemory::DmaBuf), PagesClass::Pointer | PagesClass::Fresh => Ok(ModifierMemory::Host), PagesClass::Pooled | PagesClass::ExportedFd @@ -426,13 +454,37 @@ impl Device { /// later plan whose bind would ask for a range holding the one refused takes that refusal, the /// source unasked. Over a no-copy buffer's pages (or a no-copy heap's) it is noted for a rebind /// to make again. Its first move is noted, for the device's next submission that takes it - /// (`texture/first_move.rs`). + /// (`texture/first_move.rs`). With the class whose image it is: over pages imported as + /// dma-bufs, where the image in the buffer's import (`PagesClass::DmaBufInImport`) is refused, + /// the image in an import of its own (`PagesClass::DmaBuf`) where that class's verdicts take + /// the texture ([`dma_buf_fallback`](Self::dma_buf_fallback)), but for the device's check's + /// textures, each of which measures its class's image alone. pub(super) fn in_place_image( &self, plan: &ImagePlan, descriptor: &TextureDescriptor, (texels, class, storable): (&Texels, PagesClass, bool), facts: &ImageFacts<'_>, + ) -> Result<(InPlace, PagesClass), Error> { + let made = self.in_place_image_of(plan, descriptor, (texels, class, storable), facts)?; + if class != PagesClass::DmaBufInImport || made.is_ok() { + return Ok((made, class)); + } + let Some(storable) = self.dma_buf_fallback(texels, descriptor) else { + return Ok((made, class)); + }; + let over = (texels, PagesClass::DmaBuf, storable); + let made = self.in_place_image_of(plan, descriptor, over, facts)?; + Ok((made, PagesClass::DmaBuf)) + } + + /// [`in_place_image`](Self::in_place_image) of `class` alone. + fn in_place_image_of( + &self, + plan: &ImagePlan, + descriptor: &TextureDescriptor, + (texels, class, storable): (&Texels, PagesClass, bool), + facts: &ImageFacts<'_>, ) -> Result { let layout = texels.layout; if let Some(refused) = rows_not_held(&layout, plan) { @@ -509,8 +561,30 @@ impl Device { /// `DRM_FORMAT_MOD_LINEAR` one where the driver lays the first out otherwise); the wider plans /// are asked only where it is refused, as the making takes the first plan made of them all. /// Over pages imported as dma-bufs it asks no source of the caller's: the source's answer and - /// the driver's import of its dma-buf are known only at the bind. + /// the driver's import of its dma-buf are known only at the bind. Where the image in the + /// buffer's import is refused, the image in an import of its own is asked where the making + /// would take it ([`in_place_image`](Self::in_place_image)). pub(crate) fn in_place_image_made( + &self, + made: (&ImagePlan, &TextureDescriptor), + (texels, class, storable): (&Texels, PagesClass, bool), + facts: &ImageFacts<'_>, + ) -> Result, Error> { + let answer = self.in_place_image_made_of(made, (texels, class, storable), facts)?; + if class != PagesClass::DmaBufInImport || answer.is_ok() { + return Ok(answer); + } + match self.dma_buf_fallback(texels, made.1) { + Some(storable) => { + let over = (texels, PagesClass::DmaBuf, storable); + self.in_place_image_made_of(made, over, facts) + } + None => Ok(answer), + } + } + + /// [`in_place_image_made`](Self::in_place_image_made) of `class` alone. + fn in_place_image_made_of( &self, (plan, descriptor): (&ImagePlan, &TextureDescriptor), (texels, class, storable): (&Texels, PagesClass, bool), @@ -701,8 +775,9 @@ impl Device { /// any memory is bound to it; why not. Over pages imported by their pointer, the image made /// for host allocations ([`in_place_unbound`](Self::in_place_unbound)) whose requirements /// take its place in the buffer's memory ([`placed`]); over pages imported as dma-bufs, the - /// `DRM_FORMAT_MOD_LINEAR` image over them, checked against their pages, before the caller's - /// source is asked (`dma_buf.rs`). + /// `DRM_FORMAT_MOD_LINEAR` image over them: for `PagesClass::DmaBufInImport`, the one to bind + /// in the import they lie in ([`in_import_unplaced`](Self::in_import_unplaced)); else the + /// one checked against their pages, before the caller's source is asked (`dma_buf.rs`). fn unplaced( &self, plan: &ImagePlan, @@ -716,6 +791,9 @@ impl Device { } match in_place_memory(texels, class)? { ModifierMemory::Own => self.copy_unplaced(plan, texels, facts), + ModifierMemory::DmaBuf if class == PagesClass::DmaBufInImport => { + self.in_import_unplaced(plan, texels, facts) + } ModifierMemory::DmaBuf => self.dma_buf_unplaced(plan, texels, facts), ModifierMemory::Host => self.host_unplaced(plan, texels, facts), ModifierMemory::Exported(_) => Err(internal( @@ -885,11 +963,74 @@ impl Device { ))) } + /// [`unplaced`](Self::unplaced) over pages imported as dma-bufs in the import the buffer lies + /// in (`PagesClass::DmaBufInImport`): where they lie in one import dedicated to nothing + /// (`HostPages::in_one_dma_buf_import`, read as a blit reads it, so the import stays + /// releasable until the bind), the `DRM_FORMAT_MOD_LINEAR` image whose plane lies at offset 0 + /// with the texels' pitches, to bind at their offset of that import's memory + /// (`Device::in_import_image_unbound`), whose requirements take its place there ([`placed`]). + /// No source is asked: the image takes no dma-buf and no import of its own. + #[cfg(unix)] + fn in_import_unplaced( + &self, + plan: &ImagePlan, + texels: &Texels, + facts: &ImageFacts<'_>, + ) -> Result, Error> { + let layout = texels.layout; + let Some(pages) = texels.buffer.host_pages() else { + return Ok(Err(( + Refusal::Detached, + "the buffer's bytes lie in no pages".to_owned(), + ))); + }; + let Some(import) = pages.in_one_dma_buf_import(false)? else { + return Ok(Err(( + Refusal::Placement, + "the buffer's pages lie in no one import of a dma-buf dedicated to nothing: in \ + several, bound sparsely, or in one dedicated to the buffer" + .to_owned(), + ))); + }; + let from_base = texels.buffer.offset_in_host_pages() + layout.offset; + let at = import.base + from_base; + let room = import.room.saturating_sub(from_base); + let pitches = (layout.row_pitch, layout.slice_pitch); + let (raw, requirements) = match self.in_import_image_unbound(plan, facts, at, pitches)? { + Ok(made) => made, + Err((kind, why)) => return Ok(Err((dma_buf_refusal(kind), why))), + }; + if let Err(refused) = placed(&requirements, at, room, import.type_index) { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { release::object(self.shared().vk(), raw) }; + return Ok(Err(refused)); + } + Ok(Ok(Unplaced::InImport { + raw, + requirements, + pages, + at, + })) + } + + /// No pages are imported as dma-bufs on this system. + #[cfg(not(unix))] + fn in_import_unplaced( + &self, + plan: &ImagePlan, + texels: &Texels, + facts: &ImageFacts<'_>, + ) -> Result, Error> { + self.dma_buf_unplaced(plan, texels, facts) + } + /// `unplaced`, an image in place of `plan` over `texels`, bound: over pages imported by their /// pointer (or a copied host buffer's copy of them), in the buffer's memory where it was - /// checked to lie, its first move noted; over pages imported as dma-bufs, to a dedicated import - /// of the dma-buf the caller's source makes of its pages (called with no lock of the runtime's - /// held), which may still refuse it. With whether it is a `DRM_FORMAT_MOD_LINEAR` image at + /// checked to lie, its first move noted; over pages imported as dma-bufs, in the import they + /// lie in, read again as it binds there, which keeps it imported for good (refused where they + /// no longer lie in it as the image was checked against), or to a dedicated import of the + /// dma-buf the caller's source makes of its pages (called with no lock of the runtime's held), + /// which may still refuse it. With whether it is a `DRM_FORMAT_MOD_LINEAR` image at /// Metal's pitch; and whether its refusal stands for every range that holds the pages its /// bind asked the source for (the source's `DmaBufStandingRefusal`). fn place( @@ -935,6 +1076,63 @@ impl Device { Ok((Ok((image.shared(), pitched)), false)) } #[cfg(unix)] + Unplaced::InImport { + raw, + requirements, + pages, + at, + } => { + let raw_device = self.shared().vk(); + // The import, kept imported for good from now on (`host_residency.rs`), as an + // image binds in its memory: where the pages still lie in it as the image was + // checked against it (made again since, it lies at the same offsets). + let from_base = texels.buffer.offset_in_host_pages() + texels.layout.offset; + let import = match pages.in_one_dma_buf_import(true) { + Ok(import) => import.filter(|import| { + let room = import.room.saturating_sub(from_base); + import.base + from_base == at + && placed(&requirements, at, room, import.type_index).is_ok() + }), + Err(error) => { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { release::object(raw_device, raw) }; + return Err(error); + } + }; + let Some(import) = import else { + // SAFETY: as above. + unsafe { release::object(raw_device, raw) }; + let why = "the buffer's pages no longer lie in one import of a dma-buf \ + dedicated to nothing where the image was made to bind"; + return Ok((Err((Refusal::Placement, why.to_owned())), false)); + }; + // SAFETY: the image is live and unbound, made for dma-bufs + // (`VUID-vkBindImageMemory-memory-02989`); the memory is the import of a dma-buf + // the buffer lies in, dedicated to nothing (`VUID-vkBindImageMemory-memory-10926`), + // in a type the image takes, at an offset that meets its alignment, its size inside + // the pages' placement (`placed`); the image requires no dedicated allocation + // (`VUID-vkBindImageMemory-image-01445`, `Device::in_import_image_unbound`). + if let Err(error) = + unsafe { crate::creation::bind_image(raw_device, raw, import.memory, at) } + { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { release::object(raw_device, raw) }; + return Err(vulkan(error)); + } + let image = self.in_place_of(Raw::new(raw), plan.clone(), descriptor, texels); + // Made `UNDEFINED`, as Vulkan makes an image of external memory + // (`VUID-VkImageCreateInfo-pNext-01443`): its first move acquires it from + // `VK_QUEUE_FAMILY_FOREIGN_EXT`, as an image in a dma-buf import of its own's does. + let undefined = vk::ImageLayout::UNDEFINED; + let first = FirstMove::new(raw, image.plan().format, undefined, pages_hold(&pages)) + .acquired(self.foreign_acquirer()); + *lock(&image.first_move) = Some(first); + if !in_place::checking() { + self.shared().counts.dma_buf_image_in_import(); + } + Ok((Ok((image.shared(), false)), false)) + } + #[cfg(unix)] Unplaced::DmaBuf { unbound, pages, @@ -985,8 +1183,9 @@ impl Device { /// (`dma_buf/parked.rs`), taken and made the image in place of a texture made with /// `descriptor` as a new one of the plan would be (`place`), but that it asks no source and /// imports nothing, and notes no move where a submission moved it: `None` where none is - /// parked there, the texels are not over pages imported as dma-bufs, or the making is the - /// device's check's, whose textures are its own measures. + /// parked there, the texels are not over pages imported as dma-bufs or their image is to + /// bind in the buffer's import (`PagesClass::DmaBufInImport`, which parks none), or the + /// making is the device's check's, whose textures are its own measures. #[cfg(unix)] fn take_parked( &self, @@ -995,7 +1194,10 @@ impl Device { texels: &Texels, class: PagesClass, ) -> Result, bool)>, Error> { - if in_place::checking() || in_place_memory(texels, class)? != ModifierMemory::DmaBuf { + if in_place::checking() + || class != PagesClass::DmaBuf + || in_place_memory(texels, class)? != ModifierMemory::DmaBuf + { return Ok(None); } let Some(pages) = texels.buffer.host_pages() else { @@ -1038,6 +1240,11 @@ impl Device { unsafe { release::object(self.shared().vk(), made.raw) }; } #[cfg(unix)] + Unplaced::InImport { raw, .. } => { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { release::object(self.shared().vk(), raw) }; + } + #[cfg(unix)] Unplaced::DmaBuf { unbound, .. } => unbound.release(self), } } @@ -1425,8 +1632,9 @@ impl Device { /// pages imported by their pointer, an image made for host allocations as /// [`in_place_image`](Self::in_place_image) made it, bound in their import; over pages /// imported as dma-bufs, the `DRM_FORMAT_MOD_LINEAR` image `remade` holds for it, made before - /// the rebind settled ([`dma_buf_in_place_again`](Self::dma_buf_in_place_again)), which its - /// first move acquires from `VK_QUEUE_FAMILY_FOREIGN_EXT`; over a copy of the caller's pages + /// the rebind settled ([`dma_buf_in_place_again`](Self::dma_buf_in_place_again): bound in + /// the new pages' import, or in a dma-buf import of its own), which its first move acquires + /// from `VK_QUEUE_FAMILY_FOREIGN_EXT`; over a copy of the caller's pages /// (`copied.rs`), the image [`in_place_over_copy`](Self::in_place_over_copy) makes. Refused /// (`NotImplemented(RebindTextures)`) where the device makes no such image there: the new /// memory's type is not one the image takes, the image's alignment misses its place, the @@ -1650,10 +1858,15 @@ impl Device { /// The images in place over a no-copy buffer's (or a no-copy heap's) bytes that `watches` /// note, made for a rebind's new pages, which it imported as dma-bufs (`placement`), the bytes - /// at `pointer`, into `remade`: for each, the `DRM_FORMAT_MOD_LINEAR` image of its plan at its + /// at `pointer`, into `remade`, by the order the texture's making took: an image bound in the + /// old pages' import (`PagesClass::DmaBufInImport`) is bound in the new pages' one at its + /// texels' offset, where they lie in one import dedicated to nothing and the image takes its + /// place there ([`in_import_again`](Self::in_import_again)); else, and for each image that + /// had a dma-buf import of its own, the `DRM_FORMAT_MOD_LINEAR` image of its plan at its /// texels' pitches over the one dma-buf the pages' source makes of its own pages - /// ([`Device::dma_buf_image`]). With no lock of the runtime's held, as the source is called - /// once for each. Nothing for pages imported by their pointer. Refused + /// ([`Device::dma_buf_image`]), for the first kind only where the device's check of such + /// images passed for its accesses. With no lock of the runtime's held, as the source is + /// called once for each such image. Nothing for pages imported by their pointer. Refused /// (`NotImplemented(RebindTextures)`) where the device makes no such image of one. #[cfg(unix)] pub(crate) fn dma_buf_in_place_again( @@ -1677,6 +1890,17 @@ impl Device { if remade.0.iter().any(|(made, _)| Arc::ptr_eq(made, &image)) { continue; } + if !image.raw.dedicated() { + if let Some(raw) = + self.in_import_again(&image, watch, placement, pointer, &facts)? + { + remade.0.push((image, ImageObjects::new(self, raw))); + continue; + } + if !self.class_takes(PagesClass::DmaBuf, image.plan(), self.watched_rows(watch)) { + return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); + } + } let texels = crate::dma_buf::DmaBufTexels { pages: imports, type_index: placement.type_index(), @@ -1692,6 +1916,63 @@ impl Device { Ok(()) } + /// `image`'s image in place, of the image in the old pages' import (`in_import_unplaced`), + /// made again for a rebind's new pages (`placement`, the bytes at `pointer`), its texels where + /// `watch` notes them: where the new pages lie in one import of a dma-buf dedicated to nothing + /// (as `HostPages::in_one_dma_buf_import` reads it of their placement), the + /// `DRM_FORMAT_MOD_LINEAR` image of its plan whose plane lies at offset 0 + /// (`Device::in_import_image_unbound`), bound at the texels' offset of that import's memory + /// where its requirements take its place there ([`placed`]). `None` where they do not, or the + /// device makes no such image there. + #[cfg(unix)] + fn in_import_again( + &self, + image: &Image, + watch: &InPlaceWatch, + placement: &crate::memory::Placement, + pointer: std::ptr::NonNull, + facts: &ImageFacts<'_>, + ) -> Result, Error> { + let (Some(imports), Some(mapped)) = (placement.dma_buf_pages(), placement.mapped) else { + return Ok(None); + }; + if placement.memory == vk::DeviceMemory::null() || imports.dedicated_to_buffer() { + return Ok(None); + } + // The bytes' first lies `pointer - mapped` bytes into the placement, from its offset in + // the memory. + let Some(into) = (pointer.as_ptr() as u64).checked_sub(mapped.as_ptr() as u64) else { + return Ok(None); + }; + let from_placement = into + watch.from_base; + let at = placement.offset + from_placement; + let room = placement.size().saturating_sub(from_placement); + let pitches = (watch.layout.row_pitch, watch.layout.slice_pitch); + let raw_device = self.shared().vk(); + let Ok((raw, requirements)) = + self.in_import_image_unbound(image.plan(), facts, at, pitches)? + else { + return Ok(None); + }; + if placed(&requirements, at, room, placement.type_index()).is_err() { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { release::object(raw_device, raw) }; + return Ok(None); + } + // SAFETY: the image is live and unbound, made for dma-bufs; the memory is the new pages' + // import of a dma-buf, dedicated to nothing, in a type the image takes, at an offset that + // meets its alignment, its size inside the pages' placement (`placed`), where its texels + // lie as they lay in the old pages (a rebind keeps the bytes' offset in their page). + if let Err(error) = + unsafe { crate::creation::bind_image(raw_device, raw, placement.memory, at) } + { + // SAFETY: the image is live and unbound, and no command uses it. + unsafe { release::object(raw_device, raw) }; + return Err(vulkan(error)); + } + Ok(Some(raw)) + } + /// No pages are imported as dma-bufs on this system: nothing is made. #[cfg(not(unix))] pub(crate) fn dma_buf_in_place_again( diff --git a/crates/metal2vulkan-runtime/src/texture/route.rs b/crates/metal2vulkan-runtime/src/texture/route.rs index a888681ef..3a1bcc305 100644 --- a/crates/metal2vulkan-runtime/src/texture/route.rs +++ b/crates/metal2vulkan-runtime/src/texture/route.rs @@ -296,9 +296,85 @@ impl Device { // (`in_place::RowEnds`), and whether a shader's writes may change their rows' padding // (`in_place::Padding`). let lie = texels.host_lie(class, self.shared().in_place.line()); + if class == PagesClass::DmaBuf { + return self.dma_buf_route(&lie, usage, || texels.device_copy(self)); + } self.host_route(&lie, usage, || texels.device_copy(self)) } + /// The route of a texture of Metal `usage` over pages imported as dma-bufs whose texels lie as + /// `lie` says (its class [`PagesClass::DmaBuf`]), as [`host_route`](Self::host_route) decides + /// it under the verdicts of one of the two classes of such pages: the image bound in the import + /// the pages lie in ([`PagesClass::DmaBufInImport`]) where its verdicts take the texture; + /// else the image in an import of its own ([`PagesClass::DmaBuf`]) where its verdicts do; + /// else the shadow, pending the verdict of the image in an import of its own while that is + /// pending, else the first class's while that is (so a device whose check leaves the first + /// class unchecked never has a texture wait on it), else the second's cause. The image in the + /// pages' import falls back to the other where the making refuses it + /// ([`dma_buf_fallback`](Self::dma_buf_fallback)). The device's check's own textures take the + /// class it checks now (`in_place::checked_dma_buf_class`), whose image each measures alone. + fn dma_buf_route( + &self, + lie: &HostLie, + usage: TextureUsage, + device_copy: impl Fn() -> bool, + ) -> Route { + if let Some(class) = in_place::checked_dma_buf_class() { + return self.host_route(&HostLie { class, ..*lie }, usage, device_copy); + } + let in_import = HostLie { + class: PagesClass::DmaBufInImport, + ..*lie + }; + let shadow = |route: &Route| match route { + Route::Host { + way: HostWay::Shadow(cause), + .. + } => Some(matches!(cause, ShadowCause::CheckPending(..))), + _ => None, + }; + let first = self.host_route(&in_import, usage, &device_copy); + let Some(first_pending) = shadow(&first) else { + return first; + }; + let own = HostLie { + class: PagesClass::DmaBuf, + ..*lie + }; + let second = self.host_route(&own, usage, &device_copy); + match shadow(&second) { + Some(false) if first_pending => first, + _ => second, + } + } + + /// Whether a texture made with `descriptor` over `texels`, pages imported as dma-bufs whose + /// image in their import ([`PagesClass::DmaBufInImport`]) the making refused (the pages lie + /// in several imports or one dedicated to the buffer, or the driver makes no such image there), + /// takes the image in an import of its own ([`PagesClass::DmaBuf`]) in place, as + /// [`host_route`](Self::host_route) takes it under that class's verdicts: with the storage + /// usage where that route says (`Some(storable)`). `None` where that class's verdicts do not + /// take it, and on the device's check's thread, whose textures measure one class's image + /// alone. + pub(super) fn dma_buf_fallback( + &self, + texels: &Texels, + descriptor: &TextureDescriptor, + ) -> Option { + if in_place::checking() { + return None; + } + let usage = texture_usage(descriptor.usage, descriptor.swizzle); + let lie = texels.host_lie(PagesClass::DmaBuf, self.shared().in_place.line()); + match self.host_route(&lie, usage, || false) { + Route::Host { + way: HostWay::InPlace { storable }, + .. + } => Some(storable), + _ => None, + } + } + /// The route of a texture of Metal `usage` and `levels` over host pages no buffer was made over /// yet, whose texels lie as `lie` says, `past` where they run past the buffer's length: as /// [`route_over_buffer`](Self::route_over_buffer) takes it over a no-copy buffer of them, @@ -308,6 +384,9 @@ impl Device { if let Some(route) = levels_or_past(levels) { return route; } + if lie.class == PagesClass::DmaBuf { + return self.dma_buf_route(lie, usage, || false); + } self.host_route(lie, usage, || false) } diff --git a/crates/metal2vulkan-runtime/src/texture/storage_form.rs b/crates/metal2vulkan-runtime/src/texture/storage_form.rs index b6ad48ada..a29368fa4 100644 --- a/crates/metal2vulkan-runtime/src/texture/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/texture/storage_form.rs @@ -459,19 +459,19 @@ impl Wanted { } let made = (&*texels, pending.class, storable); let image = device.in_place_image(&pending.plan, &pending.descriptor, made, &facts); - let Ok(Ok((image, pitched))) = image else { + let Ok((Ok((image, pitched)), class)) = image else { return Some(Made::Refused); }; let writes = InPlaceAccess::Writes.takes(pending.usage); let checks = &device.shared().in_place; let verdict = |class, access, rows| checks.verdict(class, access, rows); - let lie = (pending.class, pending.rows, pending.padding); + let lie = (class, pending.rows, pending.padding); let rendered = InPlaceAccess::rendered(pending.padding); let lent = InPlaceAccess::Renders.takes(pending.usage) && in_place::lent_to_copies(rendered, lie, verdict); Some(Made::Move { storage: Storage::Alias { image, texels }, - counted: MoveCount::Host(pending.class, pitched, writes, lent), + counted: MoveCount::Host(class, pitched, writes, lent), }) } } @@ -658,22 +658,33 @@ impl Texture { let checks = &image.device.shared().in_place; let verdict = |class, access, rows| checks.verdict(class, access, rows); let policy = image.device.compile_device().policy().host_page_textures; - let pages = ( - pending.class, - pending.rows, - texels.texel_bytes(), - pending.padding, - ); + let lie = |class| (class, pending.rows, texels.texel_bytes(), pending.padding); if texels.buffer.detached() || texels.buffer.copied() { return None; } + // Over dma-buf pages, the image in the import they lie in where its class's verdicts + // take the texture now, as one made now takes it (`texture/route.rs`). + let in_import = PagesClass::DmaBufInImport; + let class = match pending.class { + PagesClass::DmaBuf + if in_place::in_place(policy, pending.usage, lie(in_import), verdict) + .is_ok() => + { + in_import + } + class => class, + }; + let pages = lie(class); in_place::in_place(policy, pending.usage, pages, verdict).ok()?; // As the texture would have taken it as it was made (`Device::storage_over_buffer`). - let made = (pending.class, pending.rows, pages.2); + let made = (class, pending.rows, pages.2); let storable = in_place::storable(pending.usage, made, verdict); Some(Wanted::Move { texels: Arc::clone(texels), - pending: pending.clone(), + pending: in_place::PendingMove { + class, + ..pending.clone() + }, storable, }) }); diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index f42a271da..6a8c73d86 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -594,6 +594,7 @@ pub(crate) struct Counters { dma_buf_images_taken: AtomicU64, dma_buf_images_missed: AtomicU64, dma_buf_images_parked_released: AtomicU64, + dma_buf_images_in_import: AtomicU64, exported_dma_buf_images: AtomicU64, dma_buf_image_fallbacks: AtomicU64, modifier_feature_queries: AtomicU64, @@ -5149,6 +5150,14 @@ impl Counters { (self.dma_buf_images_parked_released).fetch_add(count as u64, Ordering::Relaxed); } + /// A texture in place over a no-copy buffer's dma-buf pages had its image bound in the + /// import the buffer lies in, asking no source and importing nothing + /// (`texture/in_place_image.rs`). + #[cfg(unix)] + pub(crate) fn dma_buf_image_in_import(&self) { + (self.dma_buf_images_in_import).fetch_add(1, Ordering::Relaxed); + } + /// The device made an image of a texture over a buffer of its own memory exported as a /// dma-buf bound to a dedicated import of that memory's own dma-buf (`dma_buf.rs`'s /// `bind_exported_dma_buf_image`). @@ -5360,7 +5369,7 @@ impl Counters { } match class { P::Pointer => {} - P::DmaBuf => { + P::DmaBuf | P::DmaBufInImport => { self.dma_buf_textures_in_place .fetch_add(1, Ordering::Relaxed); } @@ -10351,7 +10360,8 @@ pub struct WorkCounts { pub dma_buf_images_taken: u64, /// Textures in place over a no-copy buffer's dma-buf pages that found no parked image of /// their plan at their texels, whose image was made and imported anew (counted in - /// `dma_buf_images` too): with `dma_buf_images_taken`, every such texture's image. + /// `dma_buf_images` too): with `dma_buf_images_taken` and `dma_buf_images_in_import`, every + /// such texture's image. pub dma_buf_images_missed: u64, /// Parked images released untaken, their `VkImage` destroyed and their import freed: idle /// for 2 s (the residency's first idle window, `host_imports_released`), past the most the @@ -10359,6 +10369,15 @@ pub struct WorkCounts { /// the releasable imports), as `Device::host_range_remapped` names a range of their pages, or /// as the import of their pages went. pub dma_buf_images_parked_released: u64, + /// Textures in place over a no-copy buffer's dma-buf pages whose image was bound in the one + /// import the buffer lies in, at the texels' offset, beside the buffer: a + /// `DRM_FORMAT_MOD_LINEAR` image whose plane lies at offset 0 with the texels' pitches, made + /// where the device's check of such images passed (`DmaBufInImport` in its report) and the + /// import is dedicated to nothing, the image requiring no dedicated allocation and its memory's + /// alignment dividing the offset. No dma-buf asked of the source and nothing imported: not + /// counted in `dma_buf_images` or `dma_buf_imports`, and not parked. Never on a driver whose + /// `DRM_FORMAT_MOD_LINEAR` images for dma-bufs require a dedicated allocation (RADV). + pub dma_buf_images_in_import: u64, /// Images of textures over a buffer of the runtime's memory exported as a dma-buf /// (`MemoryExport::DmaBuf`: a shared block of such buffers, or a buffer's dedicated /// allocation) where no image binds in that memory itself (RADV takes the dma-buf handle type @@ -10522,7 +10541,8 @@ pub struct WorkCounts { pub managed_pages_in_ram_chunks: u64, /// Of `host_textures_in_place`, those over pages imported as dma-bufs: each a /// `DRM_FORMAT_MOD_LINEAR` image over a dma-buf of its own pages (also counted in - /// `dma_buf_images`). + /// `dma_buf_images`, or taken parked, `dma_buf_images_taken`), or bound in the import its + /// buffer lies in (`dma_buf_images_in_import`). pub dma_buf_textures_in_place: u64, /// Of `host_textures_in_place`, those over a buffer in fresh pages it imported. pub fresh_page_textures_in_place: u64, @@ -12850,6 +12870,7 @@ impl Device { dma_buf_images_missed: counters.dma_buf_images_missed.load(Ordering::Relaxed), dma_buf_images_parked_released: (counters.dma_buf_images_parked_released) .load(Ordering::Relaxed), + dma_buf_images_in_import: counters.dma_buf_images_in_import.load(Ordering::Relaxed), exported_dma_buf_images: counters.exported_dma_buf_images.load(Ordering::Relaxed), dma_buf_image_fallbacks: counters.dma_buf_image_fallbacks.load(Ordering::Relaxed), modifier_feature_queries: counters.modifier_feature_queries.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 285efb587..f0c3be8d0 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2408; +pub const RUNTIME_VERSION: u32 = 2409; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 671fb8b14..761b11154 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2928,6 +2928,7 @@ field metal2vulkan-runtime::WorkCounts.dma_buf_image_fallbacks pub dma_buf_image field metal2vulkan-runtime::WorkCounts.dma_buf_image_memories_live pub dma_buf_image_memories_live: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_images pub dma_buf_images: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_images_at_offset pub dma_buf_images_at_offset: u64 +field metal2vulkan-runtime::WorkCounts.dma_buf_images_in_import pub dma_buf_images_in_import: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_images_missed pub dma_buf_images_missed: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_images_parked pub dma_buf_images_parked: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_images_parked_released pub dma_buf_images_parked_released: u64 diff --git a/docs/API.md b/docs/API.md index 0bb75dee7..d035a1d08 100644 --- a/docs/API.md +++ b/docs/API.md @@ -404,14 +404,17 @@ not write; a render pass's load and store operations may too, for an image it re default `HostPageTexturePolicy::InPlace` the runtime relies on the driver there, checked: a texture over host pages whose declared usage samples, reads, renders into it or writes it through a shader (`ShaderWrite` or `ShaderAtomic`, of texels of 1, 2, 4, 8 or 16 bytes) is a linear image aliasing -the pages (one over dma-buf pages a `DRM_FORMAT_MOD_LINEAR` image over a dma-buf of its own pages, acquired -from `VK_QUEUE_FAMILY_FOREIGN_EXT`, its plane at the texels' offset in their first page, or, where -the driver lays such a plane out at another offset, at offset 0 of an image bound at the texels' -offset, `WorkCounts::dma_buf_images_at_offset`) wherever the device makes such an image and its own check +the pages (one over dma-buf pages a `DRM_FORMAT_MOD_LINEAR` image acquired from +`VK_QUEUE_FAMILY_FOREIGN_EXT`: where the buffer lies in one import dedicated to nothing and the +driver takes such an image there, its plane at offset 0, bound at the texels' offset in that import +and asking the buffer's source nothing, `WorkCounts::dma_buf_images_in_import`; else over a dma-buf +of its own pages, its plane at the texels' offset in their first page, or, where the driver lays +such a plane out at another offset, at offset 0 of an image bound at the texels' offset, +`WorkCounts::dma_buf_images_at_offset`) wherever the device makes such an image and its own check passed for that kind of pages and each of its accesses (`WorkCounts::host_textures_in_place`, `dma_buf_textures_in_place`, `fresh_page_textures_in_place`, and `host_textures_in_place_written` -for one a shader writes), on a discrete GPU as on any other. An image over dma-buf pages is kept -with its import as its texture goes, for the next texture over the same pages of the same plan, +for one a shader writes), on a discrete GPU as on any other. An image over a dma-buf of its own +pages is kept with its import as its texture goes, for the next texture over the same pages of the same plan, offset and pitches, which takes it asking the source nothing (`WorkCounts::dma_buf_images_taken`, docs/HOWTO.md). A texture that renders takes the feedback loop usage where the device makes the image with it, and the storage usage too where the diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 3c005c7b3..f73912f31 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -39,7 +39,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | Batches of command buffers on one `VkQueue`, on a driver measured to start no kernel submission of a queue before the one before it completed (ANV, RADV and NVIDIA's; `batch_order.rs`), are ordered by their ends: each ends with a barrier ordering its work before every later command of its `VkQueue` (the exact form's end orders it before the host's reads and writes alone), so a batch that depends on an earlier one there begins with no barrier of its own, often no command buffer of barriers, and its first encoder's GPU start is written at the bottom of the pipe, once everything before it completed. Metal starts an independent command buffer committed behind running work while that work runs (an M3 Max under macOS 27.0.1, probe `gpustart`); those drivers ran two batches of independent work one after the other under every shape measured (no end barrier, the host's or the widened one; in one `vkQueueSubmit` or two, merged into one kernel submission or not), where two dispatches of one command buffer ran side by side. The runtime's: no pipeline differs. | `batch_order = BatchOrderPolicy::Ends` | `batch_order = BatchOrderPolicy::Exact`: a barrier for each dependency of a batch's work on an earlier batch's of its `VkQueue`, the end's barrier to the host's reads and writes alone, the GPU start written at the top of the pipe; every other driver takes it under either value | None: on those drivers each batch starts once the one before it completed under either value, so the work's order, its results and its GPU times are the same, and a batch's GPU start is the end of the work before it, when such a driver starts it. Not announced; `runtime_lane::commit_work` and `runtime_lane::gpu_times` test both values | UHD 770 (ANV, RPL-S), the consumer's frame shape over 520 host imports, 67 command buffers a frame, Grouped completion, the widened end barrier against the exact form (a probe build of each): with no fill ahead of each command buffer, 67.0 command buffers submitted a frame against 129.3-129.7, the GPU's span a frame 1.84-1.90 ms against 1.99-2.06 ms, a frame through completion 2.13-2.22 ms against 2.27-2.38 ms; with a 1 MiB fill ahead of each, 134.0 against 262.9, 8.03-8.22 ms against 8.32-8.42 ms, 9.00-9.15 ms against 9.25-9.36 ms. Radeon 780M (RADV, Mesa 26.0.8), this switch: with no fill, 67.0 against 128.9-129.0, a frame through completion 48.3-48.6 ms against 42.6-47.0 ms; with a 16 MiB fill committed at once, 134.0 against 251.0-251.1, 50.6-50.8 ms against 50.8-57.3 ms; committed every 1 ms, 134.0 against 249.7-250.2, 71.3-83.6 ms against 106.3-113.6 ms (each kernel submission there leaves about 2.5 ms of the GPU idle over 520 host imports, which sets these frames) | | Command queues on a device whose GPU idles when consecutive work comes from another `VkQueue` share `VkQueue`s by choice (`queue_share.rs`): the runtime's own self-check, not a `DriverFact` row, measures that idling once per driver, release and runtime on a thread of its own and keeps its verdict (`Idles`, `DoesNotIdle`, `Unchecked`) in the shader cache's directory, as the in-place check keeps its own (`queue_switch_check.rs`: 48.7 to 51.3 us a switch on the RTX 5080 Laptop GPU, NVIDIA 615.71.09, `Idles` above 20 us). A command queue that makes a command buffer while it holds no other uncompleted one moves onto the busy `VkQueue` of its family whose oldest batch has run under 0.5 ms, the most batches in flight first, so short command buffers of several queues run with no switch between them. A queue one of whose command buffers ran on the GPU for over 2 ms, by its own timestamps (not the host's view of how long it ran as its `VkQueue`'s oldest, which also holds its wait for the GPU to start it and the waiter's lateness to see it complete), or held its `VkQueue` for over 2 ms from the submission of a batch that waited on the GPU for another `VkQueue`'s work (an `MTLEvent`'s signal, the tracker's wait, new resources' first work) to its own GPU end, is long: no queue joins its `VkQueue` while it lives, and it moves once more, at its next idle point, to an idle `VkQueue` no long or unshared queue holds. A queue whose command buffers must never wait behind another queue's (a compositor's beside an application's) is made with `Device::new_command_queue_unshared`: it never moves and no queue joins its `VkQueue`. Under either value, as a queue is made, it takes the round robin's `VkQueue` the fewest live command queues hold, of those no unshared queue holds, in turn among equals, and an unshared queue one no command queue holds where one is free (one pass over the `VkQueue`s' counts; one that finds none shares the one the fewest hold, `WorkCounts::unshared_queues_sharing_a_vk_queue`). Presenting queues and a queue that lent its `VkQueue` (`with_vk_queue`) never move. Before the verdict, and where it is not `Idles` or there are no two `VkQueue`s of one family (MoltenVK, RADV, lavapipe), every queue keeps the `VkQueue` it took at its creation; so does every queue of a device whose command buffers write no GPU timestamps it reads (`gpu_times_from_host`, or a driver whose timestamps wait for every queue's), which does not share and is counted (`WorkCounts::queue_sharing_untimed`). The runtime's: no pipeline differs. | `queue_sharing = QueueSharingPolicy::Adaptive` | `queue_sharing = QueueSharingPolicy::PerQueue`: each command queue keeps the `VkQueue` it took at its creation (the fewest live queues' as above), and the check does not run | A command buffer waits behind the command buffers of the queues sharing its `VkQueue`, where Metal's queues wait for each other only inside one command. The residual stall: once per logical queue that goes long, for a queue that joined its `VkQueue` during its short phase, about one long command buffer's length: the command buffers committed behind that queue's first long one there wait for its whole length (and those behind its later ones while it holds work, until its next idle point). Measured on the RTX 5080 Laptop GPU beside an application that alternates draws with 30 ms command buffers: a shared compositor's commits at 4,800 a second had 64 completions over 10 ms, at most 26.4 to 30.1 ms, in each of 3 runs of each of two such shapes (one join each), against none over 10 ms under `PerQueue` in those 6 runs (at most 5.6 to 9.7 ms); with 2 ms of draws between long command buffers, none over 10 ms in 3 runs (at most 5.7 to 9.8 ms) against 7, 0 and 0 under `PerQueue` (at most 6.9 to 11.2 ms). On an unshared queue, 0 over 10 ms in every run. A command buffer's GPU start time includes the other queues' work before it. `QueueSharing` (`queue-sharing`), at the device's first join | Command buffers a second on the RTX 5080 Laptop GPU, one-draw command buffers, each thread its own queue, the default against `PerQueue`, runs after a lock hold's first: 8 threads with 3 in flight 50.7k to 54.7k against 27.4k to 28.0k (5 runs each); 8 threads with 1 in flight 47.0k to 50.1k against 13.9k to 14.3k (5); 2 threads with 3 in flight 28.0k to 53.7k against 21.4k to 28.0k (10 each, in turn, the default above `PerQueue` in each pair; no thread's queue marked long), and beside another process's 30 ms command buffers 5.1k to 6.7k against 4.0k to 4.1k (3 each; the host's view marked a thread's queue long in 1 of 3 runs, which then ran at `PerQueue`'s 4.1k); 2 threads with 1 in flight 16.9k to 20.7k against 10.1k to 11.5k (5); one thread over 16 queues in turn 21.7k to 43.3k against 10.2k to 11.1k, over 2,048 20.0k to 39.2k against 10.2k to 11.2k (4). Beside an application whose queue never shared with the compositor (isolation, 300 and 30 dispatches), both 0 over 10 ms | | A chain of `half` additions, subtractions and products on a device without `shaderFloat16` (vk12-floor, SwiftShader, Pascal; capability emulation: the module computes each in `float` and rounds it by the device's `OpQuantizeToF16`): an operation whose flags hold `contract` and `reassoc` and whose result only such operations read is held at `float` precision unrounded, so the chain rounds where a value leaves it (a store, an output, a conversion, a comparison, a call, a phi, a vector move, an operation without both flags), one quantize per exit instead of one per operation (`lower::arith::half_chain`). A device with `shaderFloat16` computes `half` alike under either value. | `half_chains = HalfChainPolicy::AtExits` | `half_chains = HalfChainPolicy::EachOperation`: every operation's result rounded to `half`, as the AIR computes it | The result may differ from the rounded operations' by the roundings the chain skips, each within half a unit in the last place of a `half` at its step, compounded along the chain; a value inside the chain past `half`'s range (65504) stays finite where the rounded operations reach infinity. Within the AIR's flags, which let a compiler regroup and fuse such operations. `FastMathRewrites` (`fast-math-rewrites`) | Not timed. Size on vk12-floor (the fixtures' SPIR-V words, the default against the accurate form): `hfb_filter_bank` 121,270 against 131,766 (1,024 quantizes against 2,464), `grd_half_many_samples` 82,019 against 84,627, `nan_half_fast` 9,808 against 9,832 | -| A texture that samples, reads, renders into it or is written through a shader (`ShaderWrite` or `ShaderAtomic` usage, of texels of 1, 2, 4, 8 or 16 bytes) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages; or a copied host buffer's copy of them, `copied.rs`, its image bound in the copy's memory where the check passed for the pages, and for the copy's fresh pages or, for a `DRM_FORMAT_MOD_LINEAR` image in memory the device allocates, its pooled memory, `WorkCounts::copied_textures_in_place`) is a linear image aliasing the pages in place, where the device makes the image (its format and usage linear, at the pages' pitch) and its own check shows that the operations Vulkan lets read and write every byte bound to it leave every byte alone while the CPU writes beside it: the image's first move (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), and for one that renders a render pass's load and store operations and its moves into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back, and for one a shader writes a kernel's storage writes of its texels (which of a linear image a driver may widen past a texel), each access checked apart (a shader's writes of 1- or 2-byte texels apart from those of wider ones, which a driver may store through a wider access), and each apart for texels that share a line of the device's memory (`nonCoherentAtomSize`, "the size and alignment in bytes that bounds concurrent access to host-mapped device memory") with bytes beside them and for texels that share none (their start, their end and, with bytes between rows, each row's start and end on a line; `in_place::RowEnds`): a byte changed beside texels that share none fails both, one changed beside texels that share one fails those alone (the Iris Xe, ANV, Mesa 26.2.6, whose clear and store, and draws, write back whole the 64-byte line that holds a row's last texels, fails renders, and writes, for rows that end inside a line, a byte between rows changed, and passes both for rows that end on one: a 3840x2160 `BGRA8Unorm` surface's 15360-byte rows are 240 lines each). A kernel's writes of a texture over a buffer's rows (no IOSurface plane's) whose rows, each to its pitch, start and end on a line, its buffer holding the last row to its pitch, take a verdict of their own from the same rounds, which a round that changed only bytes of its rows' padding (after a row's last texel, before its pitch, the last row's included) passes (`in_place::Padding`, `Access::BufferWrites`): Metal leaves those bytes to the GPU there (an Intel UHD Graphics 630 under macOS 26.7.1 wrote older values back over the CPU's writes to them under a kernel's writes of a texture over a buffer, the last row's included, where an M3 Max under macOS 27.0.1 and a Radeon Pro 5300M kept them, and all three kept them under draws, clears and stores and over IOSurfaces; `crates/metal2vulkan-conformance/probes/row_padding_writes.m`), and the rule follows the x86 Macs' envelope (docs/API.md, section 10, **Kernels**), so the Iris Xe's written textures over a buffer take the image in place whatever their rows' ends. A deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's rulings (2026-10-26, and 2026-10-27 and 2026-11-07 for render targets and written textures: the GPU works on the caller's pages in place as a Mac's does, whatever a linear image costs it, on a discrete GPU too; `in_place.rs`). A texture over a buffer of the runtime's pooled memory whose rows the device's own linear image lays out otherwise (a padded pitch the driver does not take: ANV lays linear rows tight; rows apart only over a buffer that declares them unobserved, `BufferDescriptor::padding_unobserved`) is, by the same rule, a `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch bound in the buffer's memory, at any size, where the device makes one (no external memory, which Vulkan allows: `VUID-VkImageCreateInfo-tiling-02261`, `VUID-vkBindImageMemory-image-01445`), made `UNDEFINED` (`VUID-VkImageCreateInfo-initialLayout-12478`), whose first move the check's pooled class judges (`PagesClass::Pooled`: a buffer of that memory, its images at Metal's pitch alone; `WorkCounts::pooled_pitched_images`); a texture made before that class's verdict is a shadow that moves to that image once the verdict passes, as one over host pages moves in place (below; `WorkCounts::pooled_textures_moved_in_place`, `pooled_texture_shadows_freed_after_move`). A texture over a buffer whose memory the runtime exports (`exported_memory.rs`: a block that exportable buffers of one handle type share) is, by the same rule, the device's linear image or that `DRM_FORMAT_MOD_LINEAR` image made for the memory's handle type, which an image bound there must name (`VUID-vkBindImageMemory-memory-02728`), and so made `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), whose first move the check's exported classes judge, one per handle type (`PagesClass::ExportedFd`, `PagesClass::ExportedDmaBuf`: an exportable buffer of that handle type, its textures taking the product's image), a texture made before their verdicts moving to it once they pass as over the pooled memory; a shadow, its notice naming why, where the memory is a buffer's dedicated allocation (`VUID-vkBindImageMemory-memory-10926`) or the device's image format query (`VkPhysicalDeviceExternalImageFormatInfo`) takes the handle type for no such image without a dedicated allocation. A texture over a buffer in a block of the runtime's buffers allocated exportable as an opaque file descriptor and never exported (`memory.rs`'s "Buffers in exportable blocks") is the device's linear image made for that handle type, made `UNDEFINED`, or, over rows whose bytes between them only the device's ordered commands write at a pitch that image does not lie at, the `DRM_FORMAT_MOD_LINEAR` one made for that handle type where the device makes one without a dedicated allocation (RADV asks one of every such image made for a handle type, so there such a texture is a shadow: **Known gaps**), whose first move and accesses the check's class of such blocks judges (`PagesClass::FdBlocks`: a buffer in such a block, its textures taking the product's images, made only where such a block holds every image a texture over a plain block's buffer that keeps its padding takes in place, but for rows with bytes between them at a pitch the device's linear image does not lie at, `texture/fd_blocks_cover.rs`), its first move over rows whose bytes between them only the device's ordered commands write keeping the bytes it is bound to by copies whatever the verdicts (`texture/first_move.rs`'s `GpuKeep`, as for a `DRM_FORMAT_MOD_LINEAR` image over such rows in a plain block); the device's buffers lie there only where those verdicts give every texture over one what it takes over a plain block's buffer (`in_place::fd_blocks_take`), in plain blocks until they are known; a buffer that declares its padding unobserved never lies there, but in a block of its own kind allocated exportable as a dma-buf too where the device takes such blocks (`memory.rs`'s `Holds::FdDmaBufs`), in which no image is bound, a texture over it taking a `DRM_FORMAT_MOD_LINEAR` image bound to a dedicated import of the block's dma-buf, whose first move and accesses the check's class of exported dma-bufs judges (`PagesClass::ExportedDmaBuf`; `texture.rs`'s `exported_dma_buf_alias`), and in a plain block elsewhere, so that such a texture keeps a `DRM_FORMAT_MOD_LINEAR` image or the device's linear image either way. A texture that renders over a buffer that declares its padding unobserved, its rows each to its pitch sharing no line with bytes past them, takes the verdict of renders that lets a byte of its rows' padding change (`Access::UnobservedRenders`, `Padding::Unobserved`), which the renders' own rounds give as the writes' give theirs: the declaration lets a pass's load and store write those bytes (the Iris Xe's clear and store write back the 64-byte line that holds a row's last texels whole), and a byte past the last row's pitch, or a texel, fails it. So does a texture that renders over host pages whose rows' padding is free (not declared unobserved) where its renders failed and the class's copies of a texture's texels into a buffer's rows (`Access::Copies`: a blit into the rows of a buffer over the pages, as a shadow's copy back writes them, while the CPU writes beside them) failed too for those row ends: the shadow would lose the same bytes, so the image in place keeps as much, announced (`LineWriteBack`, `line-write-back`; `in_place::lent_to_copies`; the Iris Xe's render targets over rows that end inside a line, **Known gaps**). The check runs once per driver and driver version (its record named by the driver and the check's own version, not the runtime release), per class of pages, access and row ends, on a thread of its own, the verdicts it measured kept in the shader cache's directory with those it could not check for a cause that lasts for the driver (the device lacks an extension, a feature, an import, a format or an image of the shape), while one it could not check for a cause that may pass (pages or memory not made, an import refused, its writer thread not started, a move or the stores that failed) is checked again by the next device, its reason noted; a texture made before its verdict is a shadow, made without waiting for the check (its rounds take seconds on some devices and builds; `host_texture_shadows_check_pending`), and moves in place once its class's verdicts pass, at the commit of the device's only uncommitted command buffer, with no copy (`host_textures_moved_in_place`), its shadow's image freed once the command buffer that took the move completed (`host_texture_shadows_freed_after_move`), or, where a view made before the move presents it, a shadow made over it holds it as its truth, or the texture is untracked, once those and the texture went. A texture a shader writes of texels of a width no check stores (none of 1, 2, 4, 8 and 16 bytes), a check that failed or made no image, and a format, usage or pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`, those that render and those a shader writes counted apart in `host_texture_shadows_render_target` and `host_texture_shadows_shader_write`). On a discrete GPU a `Shared` texture and an IOSurface's are in place too, read across the bus, never copied to the device's memory for speed; a `Managed` no-copy buffer there is two copies (`managed_copy.rs`, the **Costs of matching Metal** bullet), and a texture over its bytes is over its GPU copy, no texture over host pages; a `Managed` texture over the bytes of a no-copy buffer that lies in its pages there (its GPU copy found no room, or Metal's private option bit 24 drops its GPU writes) that only samples or reads, over memory that carries a log of its writes, is a device copy instead (`WorkCounts::device_copy_textures`), the GPU's copy of the two Metal keeps of a `Managed` resource on a Mac with a discrete GPU, its copies in only the rows the log reports changed. | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each, for an image that reads and one that renders (its pass a clear at load and a store, then a draw over its last column in a pass that loads and stores it; a resolve into it is not among the rounds), the CPU writing beside the texels sweep after sweep until each step completed, so that a device that writes back bytes it read beside them, wherever in the step, puts back an older value the check finds, and, for one a shader writes, of 4, 8 and 16-byte texels, rows apart (of widths no multiple of 4 and odd heights among them) or tight, and 1920x1080, and apart of 1- and 2-byte texels, rows apart at a 256-byte pitch (of rows that end inside a 4-byte word and odd heights) or tight, and 1024x64, each texel stored by a kernel through an unsigned-integer view (a program's atomics, and its stores through a float view, are not among the rounds); a driver whose operations changed a byte outside every round's window would undo a CPU write made meanwhile. A kernel's writes of a texture over a buffer whose padding is free may change that padding, as an x86 Mac's GPU's do (above). Not announced where the check passed. A texture that renders, in place by its class's copies' verdict, may lose a CPU write to its rows' padding in the line that holds a row's last texels while a pass writes those texels, as its shadow would (`line-write-back`). A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer, and a render target's shadow copies it in, keeps it and merges it back at each render pass instance | +| A texture that samples, reads, renders into it or is written through a shader (`ShaderWrite` or `ShaderAtomic` usage, of texels of 1, 2, 4, 8 or 16 bytes) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages; or a copied host buffer's copy of them, `copied.rs`, its image bound in the copy's memory where the check passed for the pages, and for the copy's fresh pages or, for a `DRM_FORMAT_MOD_LINEAR` image in memory the device allocates, its pooled memory, `WorkCounts::copied_textures_in_place`) is a linear image aliasing the pages in place, where the device makes the image (its format and usage linear, at the pages' pitch) and its own check shows that the operations Vulkan lets read and write every byte bound to it leave every byte alone while the CPU writes beside it: the image's first move (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), and for one that renders a render pass's load and store operations and its moves into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back, and for one a shader writes a kernel's storage writes of its texels (which of a linear image a driver may widen past a texel), each access checked apart (a shader's writes of 1- or 2-byte texels apart from those of wider ones, which a driver may store through a wider access), and each apart for texels that share a line of the device's memory (`nonCoherentAtomSize`, "the size and alignment in bytes that bounds concurrent access to host-mapped device memory") with bytes beside them and for texels that share none (their start, their end and, with bytes between rows, each row's start and end on a line; `in_place::RowEnds`): a byte changed beside texels that share none fails both, one changed beside texels that share one fails those alone (the Iris Xe, ANV, Mesa 26.2.6, whose clear and store, and draws, write back whole the 64-byte line that holds a row's last texels, fails renders, and writes, for rows that end inside a line, a byte between rows changed, and passes both for rows that end on one: a 3840x2160 `BGRA8Unorm` surface's 15360-byte rows are 240 lines each). Over a no-copy buffer's dma-buf pages the image is a `DRM_FORMAT_MOD_LINEAR` one whose first move acquires it from `VK_QUEUE_FAMILY_FOREIGN_EXT`, in one of two forms, each judged by a class of its own: bound at the texels' offset in the import the buffer lies in, its plane at offset 0, where that is one import dedicated to nothing and the driver takes such an image there (no dedicated allocation required, `VUID-vkBindImageMemory-image-01445`; none of the buffer's, `-memory-10926`; its alignment dividing the offset, `-None-10735`), with no dma-buf or import of its own (`PagesClass::DmaBufInImport`, `WorkCounts::dma_buf_images_in_import`); else over a dma-buf of its own pages in a dedicated import (`PagesClass::DmaBuf`; RADV, **Known gaps**). A kernel's writes of a texture over a buffer's rows (no IOSurface plane's) whose rows, each to its pitch, start and end on a line, its buffer holding the last row to its pitch, take a verdict of their own from the same rounds, which a round that changed only bytes of its rows' padding (after a row's last texel, before its pitch, the last row's included) passes (`in_place::Padding`, `Access::BufferWrites`): Metal leaves those bytes to the GPU there (an Intel UHD Graphics 630 under macOS 26.7.1 wrote older values back over the CPU's writes to them under a kernel's writes of a texture over a buffer, the last row's included, where an M3 Max under macOS 27.0.1 and a Radeon Pro 5300M kept them, and all three kept them under draws, clears and stores and over IOSurfaces; `crates/metal2vulkan-conformance/probes/row_padding_writes.m`), and the rule follows the x86 Macs' envelope (docs/API.md, section 10, **Kernels**), so the Iris Xe's written textures over a buffer take the image in place whatever their rows' ends. A deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's rulings (2026-10-26, and 2026-10-27 and 2026-11-07 for render targets and written textures: the GPU works on the caller's pages in place as a Mac's does, whatever a linear image costs it, on a discrete GPU too; `in_place.rs`). A texture over a buffer of the runtime's pooled memory whose rows the device's own linear image lays out otherwise (a padded pitch the driver does not take: ANV lays linear rows tight; rows apart only over a buffer that declares them unobserved, `BufferDescriptor::padding_unobserved`) is, by the same rule, a `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch bound in the buffer's memory, at any size, where the device makes one (no external memory, which Vulkan allows: `VUID-VkImageCreateInfo-tiling-02261`, `VUID-vkBindImageMemory-image-01445`), made `UNDEFINED` (`VUID-VkImageCreateInfo-initialLayout-12478`), whose first move the check's pooled class judges (`PagesClass::Pooled`: a buffer of that memory, its images at Metal's pitch alone; `WorkCounts::pooled_pitched_images`); a texture made before that class's verdict is a shadow that moves to that image once the verdict passes, as one over host pages moves in place (below; `WorkCounts::pooled_textures_moved_in_place`, `pooled_texture_shadows_freed_after_move`). A texture over a buffer whose memory the runtime exports (`exported_memory.rs`: a block that exportable buffers of one handle type share) is, by the same rule, the device's linear image or that `DRM_FORMAT_MOD_LINEAR` image made for the memory's handle type, which an image bound there must name (`VUID-vkBindImageMemory-memory-02728`), and so made `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), whose first move the check's exported classes judge, one per handle type (`PagesClass::ExportedFd`, `PagesClass::ExportedDmaBuf`: an exportable buffer of that handle type, its textures taking the product's image), a texture made before their verdicts moving to it once they pass as over the pooled memory; a shadow, its notice naming why, where the memory is a buffer's dedicated allocation (`VUID-vkBindImageMemory-memory-10926`) or the device's image format query (`VkPhysicalDeviceExternalImageFormatInfo`) takes the handle type for no such image without a dedicated allocation. A texture over a buffer in a block of the runtime's buffers allocated exportable as an opaque file descriptor and never exported (`memory.rs`'s "Buffers in exportable blocks") is the device's linear image made for that handle type, made `UNDEFINED`, or, over rows whose bytes between them only the device's ordered commands write at a pitch that image does not lie at, the `DRM_FORMAT_MOD_LINEAR` one made for that handle type where the device makes one without a dedicated allocation (RADV asks one of every such image made for a handle type, so there such a texture is a shadow: **Known gaps**), whose first move and accesses the check's class of such blocks judges (`PagesClass::FdBlocks`: a buffer in such a block, its textures taking the product's images, made only where such a block holds every image a texture over a plain block's buffer that keeps its padding takes in place, but for rows with bytes between them at a pitch the device's linear image does not lie at, `texture/fd_blocks_cover.rs`), its first move over rows whose bytes between them only the device's ordered commands write keeping the bytes it is bound to by copies whatever the verdicts (`texture/first_move.rs`'s `GpuKeep`, as for a `DRM_FORMAT_MOD_LINEAR` image over such rows in a plain block); the device's buffers lie there only where those verdicts give every texture over one what it takes over a plain block's buffer (`in_place::fd_blocks_take`), in plain blocks until they are known; a buffer that declares its padding unobserved never lies there, but in a block of its own kind allocated exportable as a dma-buf too where the device takes such blocks (`memory.rs`'s `Holds::FdDmaBufs`), in which no image is bound, a texture over it taking a `DRM_FORMAT_MOD_LINEAR` image bound to a dedicated import of the block's dma-buf, whose first move and accesses the check's class of exported dma-bufs judges (`PagesClass::ExportedDmaBuf`; `texture.rs`'s `exported_dma_buf_alias`), and in a plain block elsewhere, so that such a texture keeps a `DRM_FORMAT_MOD_LINEAR` image or the device's linear image either way. A texture that renders over a buffer that declares its padding unobserved, its rows each to its pitch sharing no line with bytes past them, takes the verdict of renders that lets a byte of its rows' padding change (`Access::UnobservedRenders`, `Padding::Unobserved`), which the renders' own rounds give as the writes' give theirs: the declaration lets a pass's load and store write those bytes (the Iris Xe's clear and store write back the 64-byte line that holds a row's last texels whole), and a byte past the last row's pitch, or a texel, fails it. So does a texture that renders over host pages whose rows' padding is free (not declared unobserved) where its renders failed and the class's copies of a texture's texels into a buffer's rows (`Access::Copies`: a blit into the rows of a buffer over the pages, as a shadow's copy back writes them, while the CPU writes beside them) failed too for those row ends: the shadow would lose the same bytes, so the image in place keeps as much, announced (`LineWriteBack`, `line-write-back`; `in_place::lent_to_copies`; the Iris Xe's render targets over rows that end inside a line, **Known gaps**). The check runs once per driver and driver version (its record named by the driver and the check's own version, not the runtime release), per class of pages, access and row ends, on a thread of its own, the verdicts it measured kept in the shader cache's directory with those it could not check for a cause that lasts for the driver (the device lacks an extension, a feature, an import, a format or an image of the shape), while one it could not check for a cause that may pass (pages or memory not made, an import refused, its writer thread not started, a move or the stores that failed) is checked again by the next device, its reason noted; a texture made before its verdict is a shadow, made without waiting for the check (its rounds take seconds on some devices and builds; `host_texture_shadows_check_pending`), and moves in place once its class's verdicts pass, at the commit of the device's only uncommitted command buffer, with no copy (`host_textures_moved_in_place`), its shadow's image freed once the command buffer that took the move completed (`host_texture_shadows_freed_after_move`), or, where a view made before the move presents it, a shadow made over it holds it as its truth, or the texture is untracked, once those and the texture went. A texture a shader writes of texels of a width no check stores (none of 1, 2, 4, 8 and 16 bytes), a check that failed or made no image, and a format, usage or pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`, those that render and those a shader writes counted apart in `host_texture_shadows_render_target` and `host_texture_shadows_shader_write`). On a discrete GPU a `Shared` texture and an IOSurface's are in place too, read across the bus, never copied to the device's memory for speed; a `Managed` no-copy buffer there is two copies (`managed_copy.rs`, the **Costs of matching Metal** bullet), and a texture over its bytes is over its GPU copy, no texture over host pages; a `Managed` texture over the bytes of a no-copy buffer that lies in its pages there (its GPU copy found no room, or Metal's private option bit 24 drops its GPU writes) that only samples or reads, over memory that carries a log of its writes, is a device copy instead (`WorkCounts::device_copy_textures`), the GPU's copy of the two Metal keeps of a `Managed` resource on a Mac with a discrete GPU, its copies in only the rows the log reports changed. | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each, for an image that reads and one that renders (its pass a clear at load and a store, then a draw over its last column in a pass that loads and stores it; a resolve into it is not among the rounds), the CPU writing beside the texels sweep after sweep until each step completed, so that a device that writes back bytes it read beside them, wherever in the step, puts back an older value the check finds, and, for one a shader writes, of 4, 8 and 16-byte texels, rows apart (of widths no multiple of 4 and odd heights among them) or tight, and 1920x1080, and apart of 1- and 2-byte texels, rows apart at a 256-byte pitch (of rows that end inside a 4-byte word and odd heights) or tight, and 1024x64, each texel stored by a kernel through an unsigned-integer view (a program's atomics, and its stores through a float view, are not among the rounds); a driver whose operations changed a byte outside every round's window would undo a CPU write made meanwhile. A kernel's writes of a texture over a buffer whose padding is free may change that padding, as an x86 Mac's GPU's do (above). Not announced where the check passed. A texture that renders, in place by its class's copies' verdict, may lose a CPU write to its rows' padding in the line that holds a row's last texels while a pass writes those texels, as its shadow would (`line-write-back`). A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer, and a render target's shadow copies it in, keeps it and merges it back at each render pass instance | | A render or compute state's creation hands the driver's making of its predicted pipeline (`pipeline/predicted.rs`, `pipeline/dispatch_making.rs`) to the runtime's pool, kept by the state as a draw's or dispatch's making is, and waits for it `pipeline_creation_wait` at most, returning with it in flight. A committed command buffer's draws and dispatches (a compute encoder's, a render pass's tile dispatches, an execution's replayed draws, whose pipelines the commit's settle hands to the pool) wait for their pipelines until they are made, however long that takes: the batch is held in its queue's line (`Segment::steps_after_pipelines`), on the scheduler's thread, which no call waits for, and records them once made, so no command is dropped for its making's time and the command buffer completes later, as on a slower GPU. A `commit` waits for the pipelines of a pass that executes render commands the CPU writes, and for those its executions' replay begins itself, until its commit plus `pipeline_commit_wait` at most, and leaves the pass to its host step past that, which records it once they are made (`DeferredPass::left_for_makings`); a host step waits on its own thread for a making it begins itself. Metal compiles inside `newRenderPipelineState`; a host that creates a state inside a command buffer's encoding (the consumer creates a guest's state at an execution's first lookup of it) held that execution through the driver's whole compile: 11.59 s inside one execution on an M2 Pro (MoltenVK 1.4.2, a cold Metal compiler service; a sample of such a stall finds the compile's thread waiting in `MVKMetalCompiler::compile` for Metal's compiler). Each bound is 4.5 s: a creation and a commit may fall in one step of the guest's FIFO, and no runtime call waits for both, so one step's calls wait 9 s at most for makings. A creation waits on no command buffer's deadline and a `commit` on no creation's; every other recording runs on the scheduler's thread, a host step's on one of the steps' threads. Made until made under either value, in the call that makes them: a draw that records nothing, one in a pass of custom sample positions and one recorded again into another instance of its pass (each in the draw's call or an execution's replay), a device replay's draws (in its `commit`), and a failed making made again (`PipelineWaitPolicy`'s docs). The runtime's: no pipeline differs. | `pipeline_waits = PipelineWaitPolicy::Bounded`, `pipeline_creation_wait = 4.5 s`, `pipeline_commit_wait = 4.5 s` | `pipeline_waits = PipelineWaitPolicy::Exact`: the creation makes its predicted pipeline before it returns (a render state's first key on its own thread, the rest on the pool, joined; a compute state's on its own thread), an execution's settle makes its replayed draws' pipelines at the commit, and a command buffer waits for each draw's and dispatch's pipeline until it is made | A creation returns after `pipeline_creation_wait` at most with its making in flight (`WorkCounts::creations_left_making`), where Metal's returns with it made, and a command buffer whose draw or dispatch takes a making still in flight completes once it lands: its completion, and the calls that wait for the GPU (a wait for its completion or scheduling, an event it signals, a new command buffer of a queue whose most are all uncompleted), wait up to the rest of the compile; nothing renders or writes otherwise. Only its queue's later command buffers wait behind it. `deferred_calls::a_draw_whose_pipeline_is_still_being_made_past_its_bound_renders_once_made`, `a_replayed_draw_whose_pipeline_is_still_being_made_at_its_bound_renders_once_made`, `a_dispatch_whose_pipeline_is_still_being_made_past_its_bound_runs_once_made`, `a_compute_state_s_creation_waits_its_bound_for_its_predicted_making` and `under_the_exact_wait_a_held_making_holds_its_command_buffer_until_it_lands` | No GPU cost. The exact form holds the creating thread for the whole compile: up to 11.59 s on the M2 Pro's cold boot (that boot's 2,483 render state creations, translation included: 300 over 16 ms, 151 over 100 ms, 14 over 250 ms, 3 over 1 s, the longest 11.59 s, 5.82 s and 1.17 s), where the default holds a creation for 4.5 s at most. Under either value a command buffer committed before its making lands completes when it lands, its queue's later command buffers after it: a guest's kernel of 4.5 M SPIR-V words took 116 s to make on the RX 7900 XTX (RADV) | | A line Apple's `setLineWidth:` widens (`w' = floor(16 w) / 16`, other than 1), and a triangle's edge in fill mode `Lines`, is drawn by the device's own lines at `w'` wherever it draws that width (`wideLines`, `w'` in `lineWidthRange` and above 0), where Metal draws the parallelogram Vulkan's non-strict wide lines may be (`render/line_width.rs`). No device's are taken as it, announced on every device: a strict device's rectangle with square ends (lavapipe, NVIDIA), lines Vulkan does not state as parallelograms (ANV, and every width below 1), a width rounded to the granularity, and a driver's parallelograms (`strictLines` unset, `nonStrictWideLinesUseParallelogram` set), whose ends the driver places (RADV on the Radeon RX 7900 XTX draws 21 of `runtime_lane::line_widths`'s 48 scattered lines at width 2.5 a row or a column off Metal's at an end). A mesh draw's lines and edges and a tessellated patch draw's edges take the device's lines under either value, the band not drawing them (at the nearest width they draw where they do not draw `w'`, announced `lines-at-nearest-width`: a known gap below). The runtime's: no pipeline's code differs. | `wide_lines = WideLinePolicy::Device` | `wide_lines = WideLinePolicy::Exact`: a draw of lines or edges the device's lines draw is the pipeline's band variant (`VariantKey::line_band`, `pipeline::link::band`) on a device with `tessellationShader` (the device's lines where it has none, or where the translator refuses the state's band or the draw's): two triangles over each line's parallelogram, and each triangle's three edges' parallelograms facing as the triangle, through a tessellation control and evaluation stage; every other width other than 1 is the band under either value | The lines can cover pixels the parallelogram does not, and miss others, at each end and along each edge: up to half the width past each end (square ends), a rounded width, and a row or a column at an end (a driver's parallelograms). `DeviceWideLines` (`device-wide-lines`), at each such draw where `DeviceOptions::announce_each` asks, else once per device; `WorkCounts::device_wide_line_draws`, `line_band_draws`, `nearest_width_line_draws`; `runtime_lane::line_widths` (the band matches Metal's maps of lines and of triangles' edges, their facing, culling, flat inputs, primitive IDs and depth on MoltenVK under both values, which has no `wideLines`; a band of edges under a depth bias is announced `wide-edge-depth-bias`) | Not measured. Expected from the band's form: a second pipeline variant made for each render state that draws such lines or edges (its two synthesized stages), each line tessellated as a patch of two control points into four corners and each triangle as a patch of three into 21 triangles (12 degenerate), and a strip, loop or fan drawn as the list of its primitives | | A blit or fill through a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed (`allowGPUOptimizedContents`, 16 texels or more a side, neither `ShaderWrite` nor `PixelFormatView` usage, one sample, not over a buffer) is the device's copy, which keeps the bytes it moves, on every device: Metal's GPU blit into, out of or between such textures moves the texels through its compression, which writes each 16-bit field's low six bits cleared and the alpha code clamped to `[384, 894]`, and its fill clears the low six bits alone (an Apple M3 Max under macOS 27.0.1, every direction, storage mode, usage and size that decides the compression; CPU copies keep the bytes on Metal too). A pass's draws through such an attachment are the device-gap row below. The runtime's choice: no pipeline differs (`compressed_blit.rs`). | `extended_range_blits = ExtendedRangeBlitPolicy::Kept` | `extended_range_blits = ExtendedRangeBlitPolicy::Canonical`: after a blit writes such a texture's region, or a blit out of one writes a buffer's words, a texture over a buffer's or another texture's, a compute dispatch (`bind::extended_canonical_module`, `extended_canonical.rs`) rewrites the texels it wrote in Metal's encoding: in place in a buffer's bytes, an image's through a scratch buffer, a copy out and back around the dispatch; a fill's texel is encoded before it is written. A buffer whose words the device cannot bind (an offset or pitch off 4 bytes, a region past `maxStorageBufferRange`) and a texture over a buffer whose rows share bytes keep the bytes under either value, announced | Bytes no Metal write left (uploaded, CPU-copied or kernel-written texels: a field's low six bits, an alpha code outside `[384, 894]`) keep what Metal's blit would rewrite; a texel reads the same value either way, its low six bits unread and its alpha read clamped. `ExtendedRangeBitsKept` (`extended-range-bits-kept`), once per device; under `Canonical` not for the blits it makes exact; `runtime_lane::compressed_blits` (both values on MoltenVK), the conformance cases `compressed-blits-bgra10xr` and `compressed-blits-bgra10xr-srgb` | Measured, `Canonical` against `Kept`, on `Private` `BGRA10_XR` textures Metal keeps compressed (the sRGB twin and fills not measured), 256x256 and 2048x2048, one whole-texture blit a command buffer: p50 of 300 blits a run, the two values interleaved in one process, three runs a host. RTX 5080 Laptop (NVIDIA 615.71.09, the command buffer's GPU time): a buffer into the texture 23.5 against 11.5 us and 761 against 244 us from a `Private` buffer, 42 against 30 us and 1,945 against 1,176 us from a `Shared` one; the texture into a `Private` buffer 14.1 against 11.2 us and 287 against 246 us, into a `Shared` one, whose words the dispatch rewrites in system memory, 66 against 27 us and 3,386 against 1,182 us; texture into texture 22.5 against 9.7 us and 630 against 80 us. Apple M3 Max (MoltenVK 1.4.2, whose GPU times are the host's, so per blit of 16 in one command buffer), the same blits: into the texture +38 to +57 us and +536 to +548 us, out of it into a buffer +15 us and +84 to +94 us, texture into texture +46 to +48 us and +535 to +541 us. Every figure is above its `Kept` one in every run, by more than the runs' spread (under 1 us on the 5080): measurable at both sizes on both hosts. Into an image a blit adds a copy out into a scratch buffer of the region's size, the dispatch, a copy back and the barriers between them; into a buffer the dispatch and a barrier. The scratch is made without zeros, since the copy out writes every byte the dispatch and the copy back read; the figures above were taken while it was zeroed first, by a command buffer of its own (a fill on the 5080, a copy on MoltenVK). CPU from the command buffer's making through its commit, a blit alone: +1 to +3 us on the M3 Max, +1 to +127 us on the 5080, whose host other builds loaded; 16 blits into 2048x2048 images in one command buffer hold 16 scratch buffers of 32 MiB, and encoding each costs 141 to 165 us (5080) and 286 to 356 us (M3 Max), new memory blocks among it, against 2 to 6 us under `Kept`. Nothing for a texture Metal keeps uncompressed or of another format | @@ -272,8 +272,9 @@ recorded here. idle window (2 s, doubled at each import again up to 64 s). The encoding thread pays its import again at the first blit after the window (HOWTO.md section 6). A texture in place over such a buffer lies in an import of its own (`dma_buf.rs`) and leaves the buffer's import to this - release; a blit of the texture runs on the buffer's bytes, so it imports the buffer again as any - blit does. On the Radeon 780M (`runtime_lane::submit_per_surface`, three runs), 128 surfaces of + release (on RADV every such texture; where its image binds in the buffer's import instead, that + import is kept for good, as one under an image in a pointer import is); a blit of the texture + runs on the buffer's bytes, so it imports the buffer again as any blit does. On the Radeon 780M (`runtime_lane::submit_per_surface`, three runs), 128 surfaces of 64 KiB, each a buffer and a texture in place over it, list 256 dma-bufs in each kernel submission (115 to 129 µs in the ioctl) while their buffers are in use, and 128 once the buffers sat idle past their window (58 to 67 µs); on the RX 7900 XTX 108 to 109 µs and 59 to 70 µs. For @@ -830,7 +831,15 @@ driver's. Each is open work. each call apart lists every import again. The runtime keeps fewer imports live where nothing of Metal's changes (idle imports released, a guest RAM in chunks, above), but a texture in place over a dma-buf keeps its image's import, which RADV takes only as a dedicated allocation, while - the texture lives: on the 780M, 128 such textures listed 128 dma-bufs in each kernel submission + the texture lives. RADV's image query takes the dma-buf handle type for no `VK_IMAGE_TILING_LINEAR` + image (`VK_ERROR_FORMAT_NOT_SUPPORTED`) and requires a dedicated allocation of every + `DRM_FORMAT_MOD_LINEAR` one (Mesa 26.2.6, on the 780M, `tests::dma_buf_linear_bind`), so no + such image binds in the import its buffer lies in, as one does where the driver takes it + (`PagesClass::DmaBufInImport`, `WorkCounts::dma_buf_images_in_import`); the device's check leaves + that class unchecked there. A dedicated import of the buffer's own dma-buf for each texture, + which Vulkan allows, took longer at first use than a dma-buf of the texture's own pages in that + probe (a 1920x1080 `BGRA8Unorm` texture: 17.5 ms against 1.2 ms, medians of 3), so it is not + taken. On the 780M, 128 such textures listed 128 dma-bufs in each kernel submission with their buffers released (58 to 67 µs in the ioctl, against 10 to 12 µs with none). So does a texture over a buffer that declares its padding unobserved where such buffers lie in blocks exportable as dma-bufs too (`memory.rs`'s `Holds::FdDmaBufs`, the `Private` row below), each diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 74e9f315a..6edfd1e90 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -323,8 +323,16 @@ items: a macOS desktop guest of 14 GiB was measured importing up to 63.3 MiB in 16,201 separate 4 KiB runs, with 19 to 29 of its imports past 1024 runs; at a 64 KiB granule such an object takes 16 chunks. -A texture over such memory is an image over a dma-buf of its own pages where the device also lists -`VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign` (RADV does). RADV (Mesa 26.2.4 +A texture over such memory is a `DRM_FORMAT_MOD_LINEAR` image where the device also lists +`VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign` (RADV does). Where its buffer +lies in one import dedicated to nothing (no sparse buffer over several chunks, no import the +driver took only dedicated to the buffer), and the driver takes such an image there (it requires +no dedicated allocation of it, its format query takes dma-bufs for it outside one, and its +memory's alignment divides the texels' offset), the image's plane starts at offset 0 and it is +bound at the texels' offset in that import, beside the buffer: the source is not asked, and +nothing is imported (`dma_buf_images_in_import`). RADV requires a dedicated allocation of every +such image, so there, and wherever that does not hold, the image lies over a dma-buf of its own +pages. RADV (Mesa 26.2.4 and 26.0.8) lays such an image's plane only at an offset in its page that is a multiple of 256 bytes, with rows a multiple of 256 bytes apart: keep a texture's offset and `bytes_per_row` so (a 4 KiB-aligned surface with 256-byte-aligned rows always is), with no byte between its rows (below). @@ -336,11 +344,12 @@ allocation (RADV requires one of every such image) and its memory's alignment di (`dma_buf_images_at_offset`). Elsewhere the texture takes a shadow of the bytes, announced (`shadowed-texture`, naming why), and a rebind that cannot make the image again is refused (`NotImplemented(RebindTextures)`). `WorkCounts::dma_buf_imports`, `dma_buf_sparse_buffers`, -`dma_buf_images`, `dma_buf_images_at_offset` and `dma_buf_image_fallbacks` count what the route -did. +`dma_buf_images`, `dma_buf_images_at_offset`, `dma_buf_images_in_import` and +`dma_buf_image_fallbacks` count what the route did. The making of such a texture tries its image in place with each of its plans in turn (images of -usages wider than the texture's, then its own), and asks the source once for each, for the pages +usages wider than the texture's, then its own), and, for an image over a dma-buf of its own pages, +asks the source once for each, for the pages that plan's image covers from the page of the texels' first byte; RADV of Mesa 26.2.6 tried four plans for an `RGBA8Unorm` `ShaderRead` texture. An error refuses the request it answers alone, and the next plan's request is asked: the source may refuse one range and accept a wider one. A source @@ -355,7 +364,7 @@ Each such image's import costs the kernel work for every page: the `udmabuf` pin maps the dma-buf anew, the next submission waiting for its page tables. On the Radeon 780M a command buffer sampling a new 84 MiB texture over 4 KiB pages took 7.1 ms, where the same over a texture in the device's own memory took 2.2 ms. So a texture in place over a no-copy buffer's pages -keeps its image as it goes, a runtime-internal reuse: the image and its import are parked under the +whose image has an import of its own keeps its image as it goes, a runtime-internal reuse: the image and its import are parked under the buffer's import, and the next texture over the same pages of the same image plan, offset and pitches takes them, asking the source nothing and importing nothing (an image moved to `GENERAL` stays there, owned by the device's queue family, as a live one does between submissions). A @@ -426,10 +435,11 @@ do a heap's and a rebind's imports. A no-copy buffer made over the same bytes li reads it as the first does, so the import stays releasable while every read of each of them was a blit's, or none (a buffer never read, which only holds the bytes imported, among them; `host_imports_joined_releasable`). A -texture in place over a dma-buf import's bytes lies in an import of a dma-buf of its own pages, -asked of the buffer's source, and leaves the buffer's import releasable: on RADV a guest surface (a -no-copy buffer and a texture in place over it) lists the texture's import alone in each kernel -submission while the buffer is idle. `WorkCounts::host_imports_released`, +texture in place over a dma-buf import's bytes whose image is bound in that import keeps it +imported for good, as one in an import of their pointer does; one whose image lies in an import of +a dma-buf of its own pages, asked of the buffer's source (on RADV, every such texture), leaves the +buffer's import releasable: on RADV a guest surface (a no-copy buffer and a texture in place over +it) lists the texture's import alone in each kernel submission while the buffer is idle. `WorkCounts::host_imports_released`, `host_imports_reimported`, `host_imports_resident` (the releasable imports holding their memory) and `host_import_fds_kept` count it, and `host_imports_held_for_good` the imports that were releasable until a read other than a blit's kept them for good. For imports diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 22e04f74a..c3f3a0118 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -248,7 +248,7 @@ Columns: | `LayeredPass` | A layered render pass (`renderTargetArrayLength` 2 or more) that needs a step of one layer | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/color_resolve.rs (plan)` | `rare`: layered passes needing a per-layer color resolve | | `OverlappingTextureCopies` | A blit copy between overlapping regions of one texture's texels (`copyFromTexture:...` with the source's region meeting the destination's, through... (not scheduled) | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/blit_texture.rs (texture_copies_of_bytes)` | `rare`: overlapping texture copies (Metal races) | | `EmptyFillPattern` | A texture fill given no pattern bytes (`fillTexture:level:slice:region:bytes:length:` of length 0,... | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/blit_fill.rs (check_pattern)` | `none`: a fill of no pattern bytes through the Apple-private fillTexture:...:bytes:length: | -| `RebindTextures` | `Buffer::rebind_bytes_no_copy` of a no-copy buffer whose GPU writes are dropped (Metal's private option bit 24) with a live texture over its... | every device (runtime piece not built) | `ours` | 10: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)`, `crates/metal2vulkan-runtime/src/texture/heap.rs (dma_buf_heap_images_again)` (+4) | `none`: a runtime extension's rebind with a live texture | +| `RebindTextures` | `Buffer::rebind_bytes_no_copy` of a no-copy buffer whose GPU writes are dropped (Metal's private option bit 24) with a live texture over its... | every device (runtime piece not built) | `ours` | 11: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)`, `crates/metal2vulkan-runtime/src/texture/heap.rs (dma_buf_heap_images_again)` (+4) | `none`: a runtime extension's rebind with a live texture | | `PvrtcBlockOrder` | A PVRTC texture's blocks in a Metal block order the runtime does not lay out | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/texture.rs (host_copy)` | `rare`: PVRTC regions off whole levels | | `DecodedHeapTexture` | A heap's or a sparse heap's texture of an ASTC format on a device without that ASTC format (`astc.rs`), or a sparse heap's texture of an ETC2 or... | every device (runtime piece not built) | `ours` | 4: `crates/metal2vulkan-runtime/src/texture.rs (plan_sparse_texture)`, `crates/metal2vulkan-runtime/src/texture/heap.rs (heap_plan)` (+1) | `app`: an ASTC texture in a heap on a device without ASTC | | `VertexFetchPast4GiB` | A draw (`drawPrimitives:` and its forms, or an indirect command buffer's command) that may read a vertex attribute the pipeline fetches in its... | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/render/vertex_reach.rs (check_vertex_reach)` | `rare`: vertex fetch past 4 GiB of a bind offset | @@ -780,7 +780,7 @@ Each refusal's sites, with the function that builds it. - `gap::LayeredPass`: `crates/metal2vulkan-runtime/src/color_resolve.rs (plan)` - `gap::OverlappingTextureCopies`: `crates/metal2vulkan-runtime/src/blit_texture.rs (texture_copies_of_bytes)` - `gap::EmptyFillPattern`: `crates/metal2vulkan-runtime/src/blit_fill.rs (check_pattern)` -- `gap::RebindTextures`: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (dma_buf_heap_images_again)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (rebound_heap_images, 3 sites)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (dma_buf_in_place_again)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (in_place_over_copy)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (rebound_in_place_images, 3 sites)` +- `gap::RebindTextures`: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (dma_buf_heap_images_again)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (rebound_heap_images, 3 sites)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (dma_buf_in_place_again, 2 sites)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (in_place_over_copy)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (rebound_in_place_images, 3 sites)` - `gap::PvrtcBlockOrder`: `crates/metal2vulkan-runtime/src/texture.rs (host_copy)` - `gap::DecodedHeapTexture`: `crates/metal2vulkan-runtime/src/texture.rs (plan_sparse_texture)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (heap_texture_size_and_align_now, 2 sites)` - `gap::VertexFetchPast4GiB`: `crates/metal2vulkan-runtime/src/render/vertex_reach.rs (check_vertex_reach)`