diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 7fa2961d1..8f4da6599 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -206,13 +206,10 @@ the runtime made. bytes widened to 16-byte granules from the device's offset alignment, so it reports hazards between commands whose bytes are apart, as it does between untracked uses Metal leaves to the program; no order of either changes a result. -- **Textures over buffers** share the buffer's bytes. An image over a no-copy buffer's host pages - starts `UNDEFINED`, as Vulkan makes an image for host allocations; the host keeps the bytes it - is bound to across its first move, reading them before and writing them back after - (`WorkCounts::first_move_keeps`). The runtime keeps a copy and announces it - (`shadowed-texture`) where the device's linear images cannot hold Metal's layout, and where the - rows lie with bytes between them and the texture renders or a shader writes it (or it only - reads, under `PaddedReadsPolicy::Shadow`). +- **Textures over buffers** share the buffer's bytes. The runtime keeps a copy and announces it + (`shadowed-texture`) over a no-copy buffer's host pages (an image bound to them would start + `UNDEFINED`, and its first move may rewrite any byte bound to it), where the device's linear + images cannot hold Metal's layout, and where the rows lie with bytes between them. ## Runtime extensions diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 66ef536b1..706d70bd1 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -25,7 +25,7 @@ use super::attributes::ResourceAttributes; use super::buffer_texture::TexelViews; use super::degradation::Degradation; use super::device::{lock, DeviceShared}; -use super::error::{internal, invalid, nil, vulkan, Error, Problem, RuntimeGap}; +use super::error::{internal, invalid, nil, vulkan, Error, Problem}; use super::exit_guard; use super::generated_commands::PREPROCESS_BUFFER; use super::heap::{Heap, HeapType}; @@ -38,8 +38,6 @@ use super::program_objects::ProgramObject; use super::rebind::{ImportHold, Unexact}; use super::resource::{Identity, ObjectId, ResourceKey}; use super::texture::first_move::Filled; -use super::texture::shared_alias::SharedImages; -use super::texture::AliasWatch; use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode}; use super::Device; use crate::release; @@ -143,9 +141,6 @@ pub(super) struct HostCell { /// The texel buffer views of the textures over the buffer's bytes (a no-copy heap's: over /// its buffers'), which view its pages: a rebind empties them. texels: Mutex>>, - /// The linear images of the textures over the buffer's bytes (a no-copy heap's: over its - /// buffers') bound to its pages: a rebind makes them again over the new pages. - aliases: Mutex>, /// The images of the textures over the buffer's bytes (a no-copy heap's: over its buffers' /// and in it), which a detach makes present stand-ins (`detach.rs`), and the textures being /// made over them, which a detach refuses while one is. @@ -435,20 +430,6 @@ impl HostCell { texels.retain(|views| views.strong_count() > 0); texels.push(Arc::downgrade(views)); } - - /// The live aliasing images bound to the buffer's pages. - pub(super) fn aliases(&self) -> Vec { - let mut aliases = lock(&self.aliases); - aliases.retain(AliasWatch::lives); - aliases.clone() - } - - /// Note `watch`, an aliasing image bound to the buffer's pages, forgetting those gone. - fn watch_alias(&self, watch: AliasWatch) { - let mut aliases = lock(&self.aliases); - aliases.retain(AliasWatch::lives); - aliases.push(watch); - } } /// A hold on the pages a buffer of its own lies in (`Buffer::resident`), kept and never read: @@ -645,14 +626,6 @@ impl HostPages { self.import.shape.offset } - /// The host address of the byte `from_base` bytes past their bytes' start - /// ([`HostPages::memory`]): where an image bound there lies for the host. `None` where the - /// import is not mapped. - pub(super) fn host_at(&self, from_base: u64) -> Option { - let shape = &self.import.shape; - Some(shape.mapped?.add(shape.offset + from_base)) - } - /// The index of their memory's type. pub(super) fn type_index(&self) -> u32 { self.import.shape.type_index @@ -819,9 +792,6 @@ pub(super) struct HostImport { /// The releases of pages that went while it lived with no keep-alive: their deallocators /// run once it is freed. after_free: Mutex>, - /// The `VkImage`s textures of one image over the same bytes of it share - /// (`texture/shared_alias.rs`), held while it lives, and dropped before its memory is freed. - shared: SharedImages, } /// Where a host import's bytes lie in its `VkBuffer` and memory, which reading needs no @@ -992,7 +962,6 @@ impl HostImport { unlisted: AtomicBool::new(unlisted), kept: Mutex::new(None), after_free: Mutex::new(Vec::new()), - shared: SharedImages::default(), } } @@ -1168,9 +1137,6 @@ impl Drop for HostImport { unsafe { ManuallyDrop::drop(&mut self.objects) }; return; }; - // Its shared images go before the memory they are bound in is freed: nothing else holds - // one, as every holder of one holds the import. - self.shared.clear(); let shared = self.device.shared(); let read_apart = self.read_apart.load(Ordering::Relaxed); if read_apart != 0 { @@ -2236,7 +2202,6 @@ impl Device { let cell = Arc::new(HostCell { pages: Mutex::new(Lying::In(Arc::new(host))), texels: Mutex::new(Vec::new()), - aliases: Mutex::new(Vec::new()), textures: Mutex::new(TexturesOver::default()), exposed: AtomicU8::new(0), device: self.clone(), diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index 014376851..8c4088950 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -588,12 +588,9 @@ impl Device { return Err(invalid(call, Problem::Heap(problem))); } // The texel views and copies of the textures over the bytes are planned at their offset - // in the `VkBuffer`, the bytes' offset in their page; and their aliasing images are - // bound where Metal lays their texels out, which keeps their alignment only at that - // offset. + // in the `VkBuffer`, the bytes' offset in their page. let texels = cell.texels(); - let aliases = cell.aliases(); - if (!texels.is_empty() || !aliases.is_empty()) && window.offset != cell.offset() { + if !texels.is_empty() && window.offset != cell.offset() { return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); } // Detached bytes are given pages with no texture being made over them, and none is @@ -607,7 +604,11 @@ impl Device { // its import, as a buffer made over them lies in it (`host_aliases.rs`), the dma-buf source // dropped uncalled: they pin no page, that import's making asked about the same window, // and the pages stay writable while imported (`HostMemory::new`). A heap's own buffer + // imports its own, whose images bound to its bytes are made again over the new import's + // memory or its dma-bufs. let made_over = (pointer.as_ptr() as u64, length); + let shares = heap + .is_none() .then(|| shared.aliases.import(made_over, class)) .flatten(); let (pages, remade) = match shares { @@ -639,6 +640,12 @@ impl Device { call, importer, pointer, length, window, source, class, false, ) }?; + // The heap's images bound to its bytes, made over dma-bufs of their own + // pages, each of which the source makes: still with no lock held. + let again = match heap { + Some(heap) => self.dma_buf_images_again(heap, &placement, pointer), + None => Ok(Remade::default()), + }; let remade = match again { Ok(remade) => remade, Err(error) => { @@ -673,14 +680,10 @@ impl Device { // The heap's images bound to its bytes, made again over the new pages. A refusal drops // them and the new pages unreleased: the deallocator goes unrun. let mut remade = remade; - let mut swaps = match heap { + let swaps = match heap { Some(heap) => self.rebound_heap_images(heap, &pages, &mut remade)?, None => Vec::new(), }; - // The aliasing images of the textures over the bytes, made again over the new pages. - if !aliases.is_empty() { - swaps.extend(self.rebound_alias_images(&aliases, &pages, remade)?); - } let (old, again) = shared .rebinds .replace(key, cell, Arc::clone(&pages)) @@ -1054,18 +1057,13 @@ impl Device { ) -> Result { let shared = self.shared(); let raw_device = shared.vk(); - let export_metal = shared - .host_import - .as_ref() - .is_ok_and(|importer| importer.exports_metal()); // SAFETY: the caller's contract keeps the pages mapped until the placement is freed. - let placement = unsafe { - lock(&shared.memory).import_host(raw_device, start, size, allowed, class, export_metal) - } - .map_err(|failure| match failure { - ImportFailure::NoMemoryType => not_importable(), - ImportFailure::Vulkan(error) => import_refused(error), - })?; + let placement = + unsafe { lock(&shared.memory).import_host(raw_device, start, size, allowed, class) } + .map_err(|failure| match failure { + ImportFailure::NoMemoryType => not_importable(), + ImportFailure::Vulkan(error) => import_refused(error), + })?; // SAFETY: the placement is the pages' memory, the buffer's size and requirements of it // available from `at` (the caller's), and the buffer is unbound. let bound = diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index 41a5f4e86..06b900aa9 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -1313,16 +1313,7 @@ impl Texels { .device() .own_buffer(span.next_multiple_of(4), options)?; let (_, start) = buffer.at(0); - let rows = (0..layout.slices).flat_map(|slice| { - (0..layout.rows).map(move |row| slice * layout.slice_pitch + row * layout.row_pitch) - }); - let back = rows - .map(|row| vk::BufferCopy { - src_offset: start + row, - dst_offset: at + row, - size: layout.row_bytes, - }) - .collect(); + let back = staged_rows_back(layout, start, at); Ok(ShadowStaging { into: vk::BufferCopy { src_offset: at, @@ -1562,3 +1553,26 @@ pub(super) fn view_usage( _ => Err(Error::NotImplemented(RuntimeGap::Textures)), } } + +/// The regions that copy the texels laid out as `layout` from a staging buffer, where they start at +/// `start`, back into the texture's `VkBuffer`, where they start at `at` (`ShadowStaging::back`): +/// one a row, but one for rows that lie one after another. +pub(super) fn staged_rows_back(layout: &BufferLayout, start: u64, at: u64) -> Vec { + let rows = (0..layout.slices).flat_map(|slice| { + (0..layout.rows).map(move |row| slice * layout.slice_pitch + row * layout.row_pitch) + }); + let mut back: Vec = Vec::new(); + for row in rows { + match back.last_mut() { + Some(last) if last.src_offset + last.size == start + row => { + last.size += layout.row_bytes; + } + _ => back.push(vk::BufferCopy { + src_offset: start + row, + dst_offset: at + row, + size: layout.row_bytes, + }), + } + } + back +} diff --git a/crates/metal2vulkan-runtime/src/chroma_pairs.rs b/crates/metal2vulkan-runtime/src/chroma_pairs.rs index 5031836fe..baa680cad 100644 --- a/crates/metal2vulkan-runtime/src/chroma_pairs.rs +++ b/crates/metal2vulkan-runtime/src/chroma_pairs.rs @@ -46,12 +46,6 @@ pub(super) const CARRIER: Format = Format::R8G8_UNORM; /// The bytes of a 4:2:2 texel. pub(super) const TEXEL_BYTES: u32 = 2; -/// The Metal format whose own Vulkan format is [`CARRIER`]: a Metal texture over a 4:2:2 -/// texture's bytes is of it (`metal_texture.rs`), since Metal makes no linear texture of a 4:2:2 -/// format (it asserts "Linear textures do not support compressed pixel formats", EV -/// APX2-l2-mvk4). -pub(super) const CARRIER_PIXEL_FORMAT: PixelFormat = PixelFormat::RG8Unorm; - /// Whether `pf` is a 4:2:2 format. pub(super) fn is_four_two_two(pf: PixelFormat) -> bool { matches!(pf, PixelFormat::GBGR422 | PixelFormat::BGRG422) diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index eb12a2901..750be1dd0 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -488,6 +488,9 @@ pub(super) struct State { /// state made without `supportIndirectCommandBuffers`): as it commits, they run nothing, and /// it completes with `CommandBufferError::PageFault`. faulted: BTreeSet, + /// The shadowed textures its ended encoders' passes took as attachments + /// (`render/shadows.rs`), each once. + shadow_attachments: Vec, /// The shadowed textures its ended encoders copied in first (`shadow.rs`), each once. shadows_copied_in: Vec, /// The pools of its commands' set 0 (`descriptor_arena.rs`), given back or released with @@ -976,6 +979,19 @@ impl State { self.fails_from.get_or_insert((encoder, error)); } + /// Note the shadowed textures an ended encoder's pass took as attachments: how many of them + /// no pass of the command buffer took before. + pub(super) fn shadows_attached(&mut self, keys: &[ResourceKey]) -> usize { + let mut first = 0; + for &key in keys { + if !self.shadow_attachments.contains(&key) { + self.shadow_attachments.push(key); + first += 1; + } + } + first + } + /// Note the shadowed textures an ended encoder copied in first, each copy's texture and /// texels: the texels of those an earlier encoder of the command buffer copied in too. pub(super) fn shadows_copied_in(&mut self, copies: &[(ResourceKey, u64)]) -> u64 { @@ -1382,6 +1398,7 @@ impl CommandBuffer { unlisted_argument_samplers: false, fails_from: None, faulted: BTreeSet::new(), + shadow_attachments: Vec::new(), shadows_copied_in: Vec::new(), descriptors: DescriptorArena::default(), status_words: None, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index f764b7246..140c58f4c 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -341,6 +341,7 @@ impl CommandBufferShared { // Whether the batch may wait in the scheduler's group for one kernel submission with the // batches after it (`group.rs`), as far as is known before anything changes; first work // it takes still sends it now. One that may not, or of another `VkQueue`, waits, + // nothing changed, for the group to go first. Its event signals ride to the group's end; // a wait for an event a batch held signals, which only that end meets, goes after it. let met = (event_waits.iter()).any(|&wait| scheduler.group.meets(wait)); let joins = { @@ -524,17 +525,10 @@ impl CommandBufferShared { // The new resources' first work, before every command (`texture/first_move.rs`), given // back if the submission is not made. A batch's commands may reach every texture // unnamed, so it takes every move, those of images bound to host pages among them, whose - // pages it then holds. The moves that keep the bytes their images are bound to the host - // makes first, once every submission before completed (`Device::keep_on_host`); one - // registered meanwhile too. + // pages it then holds. Its commands bind the heap sets, so it holds the texture slots' + // writes until its submission was made (`heap_sets::hold`). let firsts = &shared.textures.first_moves; - let first_work = loop { - (device.keep_on_host(|_| true)).map_err(|error| recording_error(device, error))?; - let work = firsts.take(|_| true); - if !work.has_keeps() { - break work; - } - }; + let first_work = firsts.take_holding(|_| true, || crate::heap_sets::hold(device)); let entry = (!entries.is_empty()).then(|| Summary::outside_encoders(entry_uses)); let exit = (!exits.is_empty()).then(|| Summary::outside_encoders(exit_uses)); // The held depths' moves before each encoder that names one, into the layout it needs diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 6753ce783..e0812144d 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -231,28 +231,21 @@ macro_rules! degradations { degradations! { runtime { - /// A 2D texture over a buffer is a shadow image: its rows (or an array's slices) lie with - /// the buffer's bytes between them, and it renders or a shader writes it (or it only - /// reads, under [`metal2vulkan::device::PaddedReadsPolicy::Shadow`]), which an image over - /// them would hold in its subresource, where Vulkan lets the image's layout transitions - /// (its first move among them) read and write any byte of its subresources, and a render - /// pass's load and store operations read and write back any byte of an attachment's image - /// subresource, and Metal leaves them as the program writes them (but where the device's - /// image of it is a Metal texture over the buffer, on MoltenVK); or no linear image of the device - /// lays its texels out as Metal does in the buffer's memory, holding no byte past them - /// (over a no-copy buffer's imported - /// host memory, no linear image made for host allocations does: neither the driver's own - /// nor, where the device enables `VK_EXT_image_drm_format_modifier`, a - /// `DRM_FORMAT_MOD_LINEAR` image laid out at Metal's row pitch, which the driver may refuse - /// for the texture's format, usage or pitch, and which the runtime makes of no depth or - /// stencil format, nor of a height that is no multiple of 4 where the driver renders an - /// explicit plane's rows past its height - /// ([`metal2vulkan::error::RuntimeDriverDefect::ExplicitPlaneRowsPastHeight`])), or the - /// buffer is over - /// the caller's `VkBuffer`, whose memory backs no image of the runtime's, or over host - /// pages imported as dma-bufs (`HostMemory::with_dma_buf`) where the device makes no image - /// over a dma-buf of the texture's own pages (the notice names why). Also a heap's depth - /// or stencil texture on a device whose driver lays such images apart from their memory + /// A 2D texture over a buffer is a shadow image: the buffer is over host pages (a no-copy + /// buffer's, imported by their pointer or as dma-bufs), where an image bound to them would + /// start `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`) and Vulkan lets its layout + /// transitions (its first move among them) read and write any byte bound to it, where + /// Metal keeps every CPU write; or its rows (or an array's slices) lie with the buffer's + /// bytes between them, which an image over them would hold in its subresource, where + /// Vulkan lets the image's layout transitions read and write any byte of its subresources, + /// and a render pass's load and store operations read and write back any byte of an + /// attachment's image subresource, and Metal leaves them as the program writes them; or no + /// linear image of the device lays its texels out as Metal does in the buffer's memory, + /// holding no byte past them; or the buffer is over the caller's `VkBuffer`, whose memory + /// backs no image of the runtime's. Also a heap's texture over host pages imported as + /// dma-bufs where the device makes no image over a dma-buf of the texture's own pages (the + /// notice names why). Also a heap's depth or stencil texture on a device whose driver lays + /// such images apart from their memory /// ([`metal2vulkan::device::DriverFact::DepthStencilImagesLieApart`]): its image is a /// shadow of the heap's bytes in its range. Also a heap's 2D texture of one level of /// `RGB10A8_2P_XR10` or its sRGB twin: its image is a shadow of its two planes in the @@ -1632,9 +1625,7 @@ degradations! { texture's linear image in place costs more"; /// A pass renders a color attachment that it stores with `DontCare` (or resolves alone, /// `MultisampleResolve`) and whose texture's image lies over the buffer the texture lies - /// in (a linear image over an ordinary buffer's memory, a no-copy buffer's host pages, a - /// dma-buf's, a surface's; on MoltenVK, a Metal texture over a no-copy or surface buffer's - /// `MTLBuffer`) through an image its texture keeps, so that the buffer keeps its bytes, as + /// in (a linear image over an ordinary buffer's memory) through an image its texture keeps, so that the buffer keeps its bytes, as /// Metal's does (`kept_bytes.rs`): rendered in place, the pass would write them. Not where /// the pass hands the attachment to a driver that stores `DONT_CARE` as Metal's own /// `DontCare` (`DriverFact::DontCareStoreIsMetals`), one render pass instance the driver @@ -1832,17 +1823,6 @@ degradations! { VisibilityCountPerColor = "visibility-count-per-color", Precision, "the result is Metal's count multiplied by the colors the draw writes; a `Boolean` \ result is Metal's"; - /// A texture's first move over a no-copy buffer's host pages (or a rebind's new pages) - /// changed bytes the host kept across it, on pages the process maps without write - /// permission when the host writes them back: on Linux, pages made read-only after the - /// buffer was made (Linux refuses read-only pages at the import); on macOS also pages - /// read-only from the start, which Metal reads (a GPU write into them fails its command - /// buffer). Not observed on RADV, which fails the command buffers submitted after a page - /// of an import loses write permission (`HostMemory::new`). Announced once per device, on - /// the thread that makes the submission; the payload counts the bytes. - UnrestoredFirstMoveBytes = "unrestored-first-move-bytes", Precision, - "those bytes keep what the image's move from `UNDEFINED` wrote, where Metal's \ - texture leaves its pages as they were"; /// A device whose policy takes native device maths (`FloatMathsPolicy::Native`, the /// default) where its float functions are not Metal's own (not MoltenVK, /// `DriverDeviation::MetalFloatFunctions`): Metal flushes a `float` product or fused @@ -2155,6 +2135,15 @@ impl Degradation { "none: a no-copy buffer's deallocator runs in its release, on the releasing thread, \ as Metal runs it", ), + ( + // An aliasing image's first move over a no-copy buffer's host pages changed bytes the + // host kept across it, on pages the process maps read-only. No image is bound to a + // no-copy buffer's host pages: a texture over them is a shadow, which writes no byte + // its commands do not write. + "metal2vulkan-degrade-unrestored-first-move-bytes", + "none: a texture over a no-copy buffer's host pages is a shadow, which takes no first \ + move over them", + ), ]; /// The kind of `code`, if any. diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs index ec12973f9..3ca98c4e3 100644 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ b/crates/metal2vulkan-runtime/src/device/adopt.rs @@ -47,8 +47,6 @@ pub struct RawDevice { /// by default): `VK_KHR_calibrated_timestamps` or `VK_EXT_calibrated_timestamps` places /// command buffers' GPU times on the host's clock /// ([`CommandBuffer::gpu_start_time`](crate::CommandBuffer::gpu_start_time)); - /// `VK_EXT_metal_objects`, on a driver that runs on Metal, makes a texture over a no-copy - /// buffer a Metal texture over the buffer's imported memory, without a copy; /// `VK_NV_linear_color_attachment`, with its `linearColorAttachment` feature enabled beside /// it (and, below Vulkan 1.3, `VK_KHR_format_feature_flags2`, which it requires there), makes /// a texture over a buffer's memory render into its linear image in place; @@ -268,10 +266,6 @@ impl Device { compile, description: enabled, enabled: raw.enabled, - metal_objects: raw - .device_extensions - .iter() - .any(|name| name.as_c_str() == ash::ext::metal_objects::NAME), creation_feedback: raw .device_extensions .iter() diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index c35627839..c6b99e162 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -1103,16 +1103,6 @@ fn create_on( // The runtime's own need, outside the vocabulary, where listed: GPU times on the host's // clock (`gpu_time.rs`). let calibration = gpu_time::Extension::among(&listed); - // The runtime's own need, outside the vocabulary, where listed beside the host imports it - // serves: a texture over a no-copy buffer as a Metal texture over the import's `MTLBuffer` - // on a driver that runs on Metal (`metal_texture.rs`). - let metal_name = ash::ext::metal_objects::NAME; - let metal_objects = - listed.contains(metal_name) && set.extensions.contains(&VkExtension::ExtExternalMemoryHost); - let metal_asked = options - .device_extensions - .iter() - .any(|name| name.as_c_str() == metal_name); // The runtime's own need, outside the vocabulary, wherever listed (Not only on a driver that // compiles every library of saved cache data at load): which stages a variant's cache held // (`shader_cache/variant.rs`), and whether the driver's cache held a pipeline @@ -1132,7 +1122,6 @@ fn create_on( .iter() .cloned() .chain(calibration.map(|extension| extension.name().to_owned())) - .chain((metal_objects && !metal_asked).then(|| metal_name.to_owned())) .chain((creation_feedback && !feedback_asked).then(|| feedback_name.to_owned())) .chain(dma_buf.into_iter().flatten().map(CStr::to_owned)) .chain(dma_buf_images.into_iter().flatten().map(CStr::to_owned)) @@ -1278,7 +1267,6 @@ fn create_on( host_image_copy, linear_color_attachment, graphics_pipeline_library, - metal_objects: metal_objects || metal_asked, creation_feedback: creation_feedback || feedback_asked, dma_buf: dma_buf.is_some(), dma_buf_images: dma_buf_images.is_some(), diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 4e03acb7e..f1e8f3e23 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -939,10 +939,6 @@ pub(super) struct Parts { /// `adopt.rs`, where the consumer lists it), outside `enabled`'s vocabulary: its render /// pipelines are linked from libraries (`pipeline/libraries.rs`). pub(super) graphics_pipeline_library: bool, - /// It enables `VK_EXT_metal_objects` (`create.rs`), outside `enabled`'s vocabulary: textures - /// over no-copy buffers are Metal textures over their imports' `MTLBuffer`s - /// (`metal_texture.rs`). - pub(super) metal_objects: bool, /// It enables `VK_EXT_pipeline_creation_feedback` (`create.rs`), outside `enabled`'s /// vocabulary, wherever listed: each making of a program's pipeline reads whether its cache /// held the pipeline (`shader_cache/mod.rs`). @@ -996,7 +992,6 @@ impl Device { host_image_copy, linear_color_attachment, graphics_pipeline_library, - metal_objects, creation_feedback, dma_buf, dma_buf_images, @@ -1345,8 +1340,6 @@ impl Device { &enabled, super::buffer::usage(device_address), &loader_word, - metal_objects, - instance.sink().is_some(), dma_buf, dma_buf_images, ) diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs index a1d86a6f7..b49b87e99 100644 --- a/crates/metal2vulkan-runtime/src/device/submit.rs +++ b/crates/metal2vulkan-runtime/src/device/submit.rs @@ -20,7 +20,6 @@ use super::functions::Vk; use super::relay::By; use super::{lock, Device}; -use crate::degradation::Degradation; use crate::error::{vulkan, Error}; use crate::exit_guard::{self, Call}; use crate::release; @@ -34,19 +33,6 @@ use std::time::Duration; /// How long one wait for an internal submission lasts before it is repeated. const WAIT_SLICE: Duration = Duration::from_millis(100); -/// One wait of [`WAIT_SLICE`] on `info`'s timelines. -/// -/// # Safety -/// -/// The timelines are `device`'s. -unsafe fn raw_wait( - device: &ash::Device, - info: &vk::SemaphoreWaitInfo<'_>, -) -> Result<(), vk::Result> { - // SAFETY: the caller's contract. - unsafe { device.wait_semaphores(info, WAIT_SLICE.as_nanos() as u64) } -} - /// A timeline the device's own submissions signal outside the batches (the internal ones here, /// the staging queue's copies, `staging.rs`), and the value through which the host saw them /// complete. Each batch with work waits for it at that value, once per value on its `VkQueue` @@ -185,19 +171,12 @@ impl Device { let firsts = &shared.textures.first_moves; // The new resources' first work, given back if the submission is not made, after every // batch on another `VkQueue` that did some. Its place in the submissions' order is held - // until it was made. The moves that keep the bytes their images are bound to the host - // makes first ([`keep_on_host`](Self::keep_on_host)); one registered meanwhile too. - let (mut internal, taken) = loop { - self.keep_on_host(&named)?; - let mut internal = lock(&shared.internal); - if internal.is_none() { - *internal = Some(Internal::new(self)?); - } - let taken = firsts.take(&named); - if !taken.has_keeps() { - break (internal, taken); - } - }; + // until it was made. + let mut internal = lock(&shared.internal); + if internal.is_none() { + *internal = Some(Internal::new(self)?); + } + let taken = firsts.take(&named); let Some(objects) = internal.as_mut() else { unreachable!("made above"); }; @@ -312,144 +291,19 @@ impl Device { } } - /// The new images' first moves that keep the bytes they are bound to (`texture/first_move.rs`'s - /// `Keep`), of every resource but those bound to host pages whose key `named` does not name, - /// made by the host before a submission takes the rest of the first work: once every /// submission made before on each `VkQueue` completed ([`drain_submitted`]), each image's - /// bytes are read through the host pointer, the moves alone are submitted and waited for, and - /// the bytes the moves changed are written back (`KeptBytes::write_back`: none where they - /// changed none; a run on pages the process cannot write stays as the move left it, announced - /// once as `Degradation::UnrestoredFirstMoveBytes`). Nothing where no such move waits. The - /// bytes the move may write are its image's own: "Image layout transitions may perform read and - /// write accesses on all memory bound to the image subresource range"; and a linear image's - /// subresource in `GENERAL` is host-accessible, its memory "interpreted" as its subresource - /// layout lays it, so the host's writes are what the image then holds. - /// /// [`drain_submitted`]: Self::drain_submitted - pub(crate) fn keep_on_host(&self, named: impl Fn(ResourceKey) -> bool) -> Result<(), Error> { - let shared = self.shared(); - let firsts = &shared.textures.first_moves; - if !firsts.keeps_wait() { - return Ok(()); - } - if self.is_lost() { - return Err(Error::DeviceLost); - } - let raw = shared.vk(); - let mut internal = lock(&shared.internal); - if internal.is_none() { - *internal = Some(Internal::new(self)?); - } - let Some(objects) = internal.as_mut() else { - unreachable!("made above"); - }; let taken = firsts.take_keeps(named); if !taken.has_keeps() { return Ok(()); } - // What every submission before wrote is in the bytes, available to the host (each // batch's last barrier, `tracker.rs`'s `to_host`). self.drain_submitted()?; - let kept = taken.read_kept(); - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - // SAFETY: the command buffer is not pending (every internal submission is waited for) - // and the internal lock is held; beginning it resets it. - unsafe { raw.begin_command_buffer(objects.first, &begin) }.map_err(vulkan)?; - shared.counts.command_buffer_begun(); - // SAFETY: recording, outside a render pass, for the queue family; it is submitted alone - // and waited for below, before any submission that uses the images. - unsafe { taken.record(raw, objects.first, shared.queue_flags_of(0)) }; - // SAFETY: as above. - unsafe { raw.end_command_buffer(objects.first) }.map_err(vulkan)?; - // SAFETY: the fence is unsignaled or signaled and not pending. - unsafe { raw.reset_fences(&[objects.fence]) }.map_err(vulkan)?; - // After the last binding of a no-copy buffer's dma-bufs, until it completed. - let (wait_semaphores, wait_values): (Vec, Vec) = - self.binding_wait().into_iter().unzip(); - let wait_stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; wait_semaphores.len()]; - let value = objects.signalled + 1; - let buffers = [objects.first]; - let signal_semaphores = [objects.timeline]; - let signal_values = [value]; - let mut timeline = vk::TimelineSemaphoreSubmitInfo::default() - .wait_semaphore_values(&wait_values) - .signal_semaphore_values(&signal_values); - let submit = vk::SubmitInfo::default() - .wait_semaphores(&wait_semaphores) - .wait_dst_stage_mask(&wait_stages) - .command_buffers(&buffers) - .signal_semaphores(&signal_semaphores) - .push_next(&mut timeline); - // As in `submit_internal_naming`. - let _own = (shared.parking.get()).map(|parking| parking.own_submission(self)); - // SAFETY: as in `submit_internal_naming`. - let made = shared.use_queue(0, By::Runtime, |queue| unsafe { - shared.counts.queue_submitted(1); - raw.queue_submit(queue, &[submit], objects.fence) - }); - // A `vkQueueSubmit` that fails gives the moves back as `taken` drops. - if let Err(error) = made { - return Err(self.failed(error)); - } - objects.signalled = value; - shared.counts.internal_submission(); - shared.counts.first_move_kept(taken.kept()); - // The moves and the pages their bytes lie in, held until the bytes are written back. - let held = taken.submitted_internally(objects.timeline, value); - loop { - // SAFETY: the fence was submitted just now. - match unsafe { - raw.wait_for_fences(&[objects.fence], true, WAIT_SLICE.as_nanos() as u64) - } { - Ok(()) => break, - Err(vk::Result::TIMEOUT) => continue, - Err(error) => return Err(self.failed(error)), - } - } - firsts.internal_completed(value); - shared.internal_done.reached(value); - let restored = kept.write_back(); - drop(held); - shared.counts.first_move_restored(restored.stored); - if restored.unwritable > 0 { - self.degrade_once(Degradation::UnrestoredFirstMoveBytes, || { - ( - format!("{} bytes of host pages", restored.unwritable), - "a texture's first move changed them, and the process maps their pages \ - without write permission, so the host could not put back the bytes it kept" - .to_owned(), - ) - }); - } - Ok(()) - } - /// Wait until every batch submitted to each `VkQueue` before now completed. fn drain_submitted(&self) -> Result<(), Error> { let shared = self.shared(); let (timelines, values): (Vec, Vec) = (shared.queues.iter()) - .map(|queue| (queue.timeline, queue.submitted_value())) - .filter(|&(_, value)| value != 0) .unzip(); - if timelines.is_empty() { - return Ok(()); - } - let info = vk::SemaphoreWaitInfo::default() - .semaphores(&timelines) - .values(&values); - loop { - // SAFETY: the timelines are the device's; each value was submitted to be signalled, - // and no batch submitted waits for a signal not submitted (`scheduler`). - match unsafe { raw_wait(shared.vk(), &info) } { - Ok(()) => return Ok(()), - Err(vk::Result::TIMEOUT) if !self.is_lost() => continue, - Err(vk::Result::TIMEOUT) => return Err(Error::DeviceLost), - Err(error) => return Err(self.failed(error)), - } - } - } - /// Bind `binds` to `buffer`, a sparse buffer no command has used, with one /// `vkQueueBindSparse` on the device's first `VkQueue` that signals the internal timeline, /// and return without waiting for it: every submission made after it, on every `VkQueue`, diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs index 03d62b86a..2e0927de5 100644 --- a/crates/metal2vulkan-runtime/src/dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -27,41 +27,24 @@ //! - **The bytes.** The runtime never maps a dma-buf: `contents` stays the caller's pointer, and //! the CPU's writes through it and the GPU's through the imports meet in the same pages with no //! flush or invalidate (the types are host-coherent). -//! - **Textures** over such pages (a no-copy buffer's texture and its views, or a texture placed in -//! such a heap), where the device also lists `VK_EXT_image_drm_format_modifier` and -//! `VK_EXT_queue_family_foreign` (enabled beside the route, `create.rs`'s `dma_buf_image_names`), -//! are each an image of `DRM_FORMAT_MOD_LINEAR` made for dma-bufs and bound to a dedicated import -//! (`VkMemoryDedicatedAllocateInfo`) of the one dma-buf the source makes of the pages its memory -//! requirements cover ([`Device::dma_buf_image`]). Its one plane starts at the texels' offset in -//! their first page; its rows are the texture's (`bytesPerRow`) over a buffer, and the driver's -//! own (`VkImageDrmFormatModifierListCreateInfoEXT`) in a heap, where a texture over pages -//! imported by their pointer is the driver's linear image. Its features are the modifier's -//! (64-bit where the device has `format_feature_flags2`: `modifier_features`), checked as a -//! linear image's are against the optimal tiling's for the texture's usage, and its limits the -//! format query's for that modifier and dma-bufs. RADV (Mesa 26.2.4 and 26.0.8) lays a plane only -//! at an offset that is a multiple of 256 bytes and rows a multiple of 256 apart, 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 whose rows (or slices) lie with the buffer's bytes -//! between them takes no such image unless it only reads (under `PaddedReadsPolicy::Alias`, the -//! default), nor one whose plane holds bytes past its texels (past its last row's pitch, for one -//! that only reads): Vulkan lets an image's layout transitions and a render pass's load and -//! store operations write any byte of its subresource (`linear_plan::holding`, `Holds`); it is a -//! shadow, the source not asked, counted as a fallback. Over pages imported by their pointer, a texture over a -//! buffer, its rows packed, whose rows the driver's linear image lays out otherwise is likewise -//! a `DRM_FORMAT_MOD_LINEAR` image, its plane at the texture's pitches, made for host allocations -//! ([`ModifierMemory::Host`]) and bound in the buffer's import, its features and limits checked -//! the same way (`texture.rs`'s `host_pitched_image`; counted: -//! `WorkCounts::pitched_host_images`), where the driver takes that layout. Measured -//! (`runtime_lane::surface_texture_costs::pitch_classes`): ANV of Mesa 26.2.4 takes every pitch -//! of every format and usage asked; NVIDIA 615.71.09 a pitch at least its own linear image's row -//! (128-byte aligned), for a texture it samples or writes and not one it renders to, and not in -//! `R16Float`, `R32Float` or `RGBA32Float`, whose `DRM_FORMAT_MOD_LINEAR` tiling it gives no -//! sampling or transfers; RADV of Mesa 26.2.4 refuses a pitch that is not a multiple of 256 -//! bytes and asks a dedicated allocation of an image at any other, so none but its own row. The -//! driver's refusal of an image is kept and not asked again (`texture/pitch_refusals.rs`; -//! `WorkCounts::pitched_host_image_refusals`). +//! - **Textures** placed in a heap over such pages (and their views), where the device also lists +//! `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign` (enabled beside the +//! route, `create.rs`'s `dma_buf_image_names`), are each an image of `DRM_FORMAT_MOD_LINEAR` made +//! for dma-bufs and bound to a dedicated import (`VkMemoryDedicatedAllocateInfo`) of the one +//! dma-buf the source makes of the pages its memory requirements cover +//! ([`Device::dma_buf_image`]). Its one plane starts at the texels' offset in their first page, +//! its rows the driver's own (`VkImageDrmFormatModifierListCreateInfoEXT`), as a texture placed +//! in a heap over pages imported by their pointer is the driver's linear image. Its features are +//! the modifier's (64-bit where the device has `format_feature_flags2`: `modifier_features`), +//! checked as a linear image's are against the optimal tiling's for the texture's usage, and its +//! limits the format query's for that modifier and dma-bufs. RADV (Mesa 26.2.4 and 26.0.8) lays +//! a plane only at an offset that is a multiple of 256 bytes and rows a multiple of 256 apart, +//! 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 pages, a dma-buf's or +//! a pointer's, takes no image over them: it is a shadow (`texture.rs`'s `storage_over_buffer`), +//! whose copies go through the buffer's import. //! - **Their layouts.** The image is made `UNDEFINED`, as Vulkan makes an image of external //! memory (`VUID-VkImageCreateInfo-pNext-01443`), and the first submission that uses it acquires //! it from `VK_QUEUE_FAMILY_FOREIGN_EXT` into `GENERAL` (`texture/first_move.rs`), from @@ -74,14 +57,14 @@ //! foreign write could leave stale. Measured on RADV of both versions: a CPU write between two //! submissions, with no acquire between, is what the second reads; the GPU's writes reach the //! pages at the texels' places and leave the rows' padding. -//! - **Their hazards.** The image takes the identity of the bytes it lies over (the buffer's, or -//! the heap's), so hazard tracking orders its uses against the buffer's and the heap's other -//! resources' over the same pages, as for any aliasing image, though its import is its own. -//! - **Where none is made** (for the reasons [`Device::dma_buf_image`] lists), the texture takes -//! the way it took before such images: a shadow of the bytes, counted -//! (`WorkCounts::dma_buf_image_fallbacks`) and announced (`shadowed-texture`, naming why). -//! - **Rebinds** onto pages imported as dma-bufs make each texture's image again over its own new -//! pages before the rebind settles (`rebind.rs`), and are refused +//! - **Their hazards.** The image takes the identity of the heap's bytes it lies over, so hazard +//! tracking orders its uses against the heap's other resources' over the same pages, as for any +//! aliasing image, though its import is its own. +//! - **Where none is made** (for the reasons [`Device::dma_buf_image`] lists), the texture is a +//! shadow of the heap's bytes, counted (`WorkCounts::dma_buf_image_fallbacks`) and announced +//! (`shadowed-texture`, naming why). +//! - **Rebinds** of a heap onto pages imported as dma-bufs make each such texture's image again +//! over its own new pages before the rebind settles (`rebind.rs`), and are refused //! (`NotImplemented(RebindTextures)`) where one is not made. //! - **Refused** (the pointer's refusal: `Unsupported`, `HostMemory`): a source that fails, chunks //! the device imports as no type the buffer takes, a driver that refuses a chunk, and a sparse @@ -96,9 +79,7 @@ use super::exit_guard::{self, Call}; use super::host_memory::{based_size, import_refused, not_importable, ImportWindow, Importer}; use super::host_residency::Again; use super::image_plan::{ImageFacts, ImagePlan}; -use super::linear_plan::{ - check_linear_limits, tiling_lack, viewed_formats, BufferLayout, Holds, LinearLack, -}; +use super::linear_plan::{check_linear_limits, tiling_lack, viewed_formats, LinearLack}; use super::memory::{ImportFailure, MemoryClass, Placement}; use super::program_objects::ProgramObject; use super::Device; @@ -737,7 +718,7 @@ pub(super) const DRM_FORMAT_MOD_LINEAR: u64 = 0; /// Where a texture's texels lie in dma-buf pages, for its image over them /// ([`Device::dma_buf_image`]). pub(super) struct DmaBufTexels<'a> { - /// The imports of the pages (a no-copy buffer's or heap's), with the caller's source. + /// The imports of the pages (a no-copy heap's), with the caller's source. pub(super) pages: &'a DmaBufPages, /// Their memory type, which the image's import takes too. pub(super) type_index: u32, @@ -747,10 +728,6 @@ pub(super) struct DmaBufTexels<'a> { pub(super) row_pitch: u64, /// The bytes from a slice's first texel to the next slice's, for a plan of several layers. pub(super) slice_pitch: u64, - /// For a texture over a buffer, its texels' layout, and what the image's plane may hold beside - /// them (`linear_plan::Holds`): the buffer's other bytes are the program's. `None` for a - /// heap's texture, whose image's bytes are its own. - pub(super) alone: Option<(BufferLayout, Holds)>, } /// A texture's image over dma-buf pages, made and bound ([`Device::dma_buf_image`]): its @@ -789,9 +766,8 @@ struct Unbound { } impl Device { - /// The image of the first of `plans` the device makes one of (a texture's plans, each viewed - /// as `facts` says), and its index, over `texels`, where the texels lie in the caller's - /// dma-buf pages: a `DRM_FORMAT_MOD_LINEAR` image + /// The image of `plan` (a heap texture's, viewed as `facts` says) over `texels`, where the + /// texels lie in the caller's dma-buf pages: a `DRM_FORMAT_MOD_LINEAR` image /// (`VK_EXT_image_drm_format_modifier`) whose one plane starts at the texels' offset in their /// first page, rows `row_pitch` apart (slices `slice_pitch`), made for dma-bufs, and bound to /// a dedicated import (`VkMemoryDedicatedAllocateInfo`) of the one dma-buf the caller's source @@ -806,27 +782,19 @@ impl Device { /// feature the plan's optimal tiling has for its usage; the format query refuses such an /// image, or the plan passes its limits; the driver refuses the plane layout or lays it out /// otherwise; the image's memory runs past the pages or takes no memory of their type; the - /// source fails or answers against its contract; the driver refuses the import. The reason is - /// the last plan's; everything made is released then. The source is called at most once, for - /// the first plan the device makes an image of before asking it, with no lock of the - /// runtime's held (the caller holds none). + /// source fails or answers against its contract; the driver refuses the import. Everything + /// made is released then. The source is called at most once, once the image is made and + /// checked, with no lock of the runtime's held (the caller holds none). pub(super) fn dma_buf_image( &self, - plans: &[&ImagePlan], + plan: &ImagePlan, facts: &ImageFacts<'_>, texels: &DmaBufTexels<'_>, - ) -> Result, Error> { - let mut why = "no plan".to_owned(); - for (index, plan) in plans.iter().enumerate() { - match self.dma_buf_image_unbound(plan, facts, texels)? { - Ok(unbound) => { - let made = self.bind_dma_buf_image(unbound, texels)?; - return Ok(made.map(|image| (index, image))); - } - Err(reason) => why = reason, - } + ) -> Result, Error> { + match self.dma_buf_image_unbound(plan, facts, texels)? { + Ok(unbound) => self.bind_dma_buf_image(unbound, texels), + Err(why) => Ok(Err(why)), } - Ok(Err(why)) } /// The queue family the first move of an image over dma-buf pages acquires it for: the @@ -872,8 +840,7 @@ impl Device { let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default() .drm_format_modifier(DRM_FORMAT_MOD_LINEAR) .plane_layouts(&planes); - let dma_buf = ModifierMemory::DmaBuf; - let raw = match self.drm_linear_image(plan, &view_formats, &mut explicit, dma_buf)? { + let raw = match self.drm_linear_image(plan, &view_formats, &mut explicit)? { Ok(raw) => raw, Err(error) => { return Ok(Err(format!( @@ -904,15 +871,6 @@ impl Device { report.offset, report.row_pitch, report.array_pitch, texels.row_pitch )); } - if let Some((layout, holds)) = &texels.alone { - if !holds.fits(layout, report.size, report.array_pitch) { - return refuse(format!( - "the driver's plane takes {} bytes, past the texels' {}", - report.size, - holds.reach(layout) - )); - } - } // The pages from the texels' first, through the image's memory. let first = texels.at - offset; let length = match requirements.size.checked_next_multiple_of(page) { @@ -1055,16 +1013,16 @@ impl Device { )) } }; - let checked = self.modifier_image_checks(plan, facts, ModifierMemory::DmaBuf)?; + let checked = self.modifier_image_checks(plan, facts)?; Ok(checked.map(|view_formats| (page, view_formats))) } - /// What a `DRM_FORMAT_MOD_LINEAR` image of `plan` for `memory` takes before its plane is laid + /// What a `DRM_FORMAT_MOD_LINEAR` image of `plan` for dma-bufs takes before its plane is laid /// out, on a device that enables `VK_EXT_image_drm_format_modifier`: the formats it lists for /// its views; why not where the device makes none: the plan has several levels, depth or /// samples, or a mutable format with no list of its views; its format has a depth or stencil /// component; the modifier's tiling lacks a feature the plan's optimal tiling has for its - /// usage; the format query refuses such an image for `memory`, or the plan passes its limits. + /// usage; the format query refuses such an image for dma-bufs, or the plan passes its limits. /// /// The runtime takes a modifier image's plane layout from the driver /// (`vkGetImageSubresourceLayout`), and Vulkan has no valid such query of a format with a @@ -1077,7 +1035,6 @@ impl Device { &self, plan: &ImagePlan, facts: &ImageFacts<'_>, - memory: ModifierMemory, ) -> Result, String>, Error> { if plan.levels != 1 || plan.extent[2] != 1 || plan.samples != SampleCountFlags::COUNT_1 { return Ok(Err(format!( @@ -1115,16 +1072,15 @@ impl Device { ))); } let view_formats: Vec = formats.iter().map(|&format| format.into()).collect(); - let limits = match self.modifier_image_limits(plan, &view_formats, memory) { + let limits = match self.modifier_image_limits(plan, &view_formats) { Ok(limits) => limits, Err(why) => return Ok(Err(why)), }; if let Err(need) = check_linear_limits(plan, &limits) { return Ok(Err(format!( "its image passes the device's limits for a DRM_FORMAT_MOD_LINEAR image of \ - {:?} for {}: {need:?}", + {:?} for dma-bufs: {need:?}", plan.format, - memory.words() ))); } Ok(Ok(view_formats)) @@ -1149,8 +1105,7 @@ impl Device { let modifiers = [DRM_FORMAT_MOD_LINEAR]; let mut chosen = vk::ImageDrmFormatModifierListCreateInfoEXT::default().drm_format_modifiers(&modifiers); - let dma_buf = ModifierMemory::DmaBuf; - let raw = match self.drm_linear_image(plan, &view_formats, &mut chosen, dma_buf)? { + let raw = match self.drm_linear_image(plan, &view_formats, &mut chosen)? { Ok(raw) => raw, Err(error) => { return Ok(Err(format!( @@ -1175,7 +1130,7 @@ impl Device { })) } - /// A `DRM_FORMAT_MOD_LINEAR` image of `plan` for `memory`, viewed as `view_formats`, its + /// A `DRM_FORMAT_MOD_LINEAR` image of `plan` for dma-bufs, viewed as `view_formats`, its /// plane laid out as `modifier` says (an explicit layout, or the modifier listed for the driver /// to lay out), made `UNDEFINED` as Vulkan makes an image of external memory; or the driver's /// refusal of it. @@ -1184,11 +1139,9 @@ impl Device { plan: &ImagePlan, view_formats: &[vk::Format], modifier: &mut impl vk::ExtendsImageCreateInfo, - memory: ModifierMemory, ) -> Result, Error> { let shared = self.shared(); - let mut external = - vk::ExternalMemoryImageCreateInfo::default().handle_types(memory.handle_type()); + let mut external = vk::ExternalMemoryImageCreateInfo::default().handle_types(DMA_BUF); let mut list = vk::ImageFormatListCreateInfo::default(); let info = plan .create_info(shared.sharing(), view_formats, &mut list) @@ -1277,15 +1230,13 @@ impl Device { features.map_or(FormatFeatureFlags2::empty(), FormatFeatureFlags2::from_raw) } - /// The device's limits for a `DRM_FORMAT_MOD_LINEAR` image of `plan` for `memory`, viewed as - /// `view_formats`; why not where its format query refuses such an image or it imports no such - /// memory for one (for host allocations, none but a dedicated one: such an image is bound at - /// an offset of a buffer's import). + /// The device's limits for a `DRM_FORMAT_MOD_LINEAR` image of `plan` for dma-bufs, viewed as + /// `view_formats`; why not where its format query refuses such an image or it imports no + /// dma-buf for one. fn modifier_image_limits( &self, plan: &ImagePlan, view_formats: &[vk::Format], - memory: ModifierMemory, ) -> Result { let shared = self.shared(); let families = &shared.queue_families; @@ -1298,7 +1249,7 @@ impl Device { false => modifier.sharing_mode(vk::SharingMode::EXCLUSIVE), }; let mut external = - vk::PhysicalDeviceExternalImageFormatInfo::default().handle_type(memory.handle_type()); + vk::PhysicalDeviceExternalImageFormatInfo::default().handle_type(DMA_BUF); let mut list = vk::ImageFormatListCreateInfo::default().view_formats(view_formats); let mut query = vk::PhysicalDeviceImageFormatInfo2::default() .format(plan.format.into()) @@ -1328,22 +1279,16 @@ impl Device { if let Err(error) = queried { return Err(format!( "the device's image format query reports no DRM_FORMAT_MOD_LINEAR image of {:?}, \ - usage {:?}, flags {:?} for {} ({error:?})", - plan.format, - plan.usage, - plan.flags, - memory.words() + usage {:?}, flags {:?} for dma-bufs ({error:?})", + plan.format, plan.usage, plan.flags, )); } let limits = properties.image_format_properties; let features = imported.external_memory_properties.external_memory_features; - let dedicated_only = memory == ModifierMemory::Host - && features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY); - if !features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE) || dedicated_only { + if !features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE) { return Err(format!( - "it imports no {} for a DRM_FORMAT_MOD_LINEAR image of {:?} (importable {}, \ + "it imports no dma-bufs for a DRM_FORMAT_MOD_LINEAR image of {:?} (importable {}, \ dedicated only {})", - memory.words(), plan.format, features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE), features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY) @@ -1371,30 +1316,3 @@ impl Device { ) } } - -/// The memory a `DRM_FORMAT_MOD_LINEAR` image is made for: a dma-buf of its own pages -/// ([`Device::dma_buf_image`]), or a no-copy buffer's host pages imported by their pointer, where -/// the image lays its rows out at Metal's pitch (`texture.rs`'s `host_pitched_image`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum ModifierMemory { - DmaBuf, - Host, -} - -impl ModifierMemory { - /// The external memory handle type the image is made for. - fn handle_type(self) -> vk::ExternalMemoryHandleTypeFlags { - match self { - ModifierMemory::DmaBuf => DMA_BUF, - ModifierMemory::Host => vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT, - } - } - - /// The memory, in words. - fn words(self) -> &'static str { - match self { - ModifierMemory::DmaBuf => "dma-bufs", - ModifierMemory::Host => "host allocations", - } - } -} diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 1ad8d88dd..cacdb89ad 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -208,6 +208,9 @@ pub(super) struct EncoderCore { /// open, so a use at that place of the same key, named only where that one was, is kept and /// named already. touched: Vec<(ResourceKey, bool)>, + /// The shadowed textures its pass took as attachments (`render/shadows.rs`): `end` notes them + /// in the command buffer (`WorkCounts::shadow_attachment_passes`). + attachment_shadows: Vec, /// Its first copies in of shadowed textures, each copy's texture and texels: `end` notes them /// in the command buffer (`WorkCounts::shadow_texels_first_copied_in_again`). first_copies: Vec<(ResourceKey, u64)>, @@ -325,6 +328,7 @@ impl EncoderCore { shadows: ShadowSync::default(), keys: BTreeSet::new(), touched: Vec::new(), + attachment_shadows: Vec::new(), first_copies: Vec::new(), heaps: Vec::new(), holds: Holds::new(command_buffer.device()), @@ -401,6 +405,7 @@ impl EncoderCore { shadows: ShadowSync::default(), keys: BTreeSet::new(), touched: Vec::new(), + attachment_shadows: Vec::new(), first_copies: Vec::new(), heaps: Vec::new(), holds: Holds::new(command_buffer.device()), @@ -982,6 +987,13 @@ impl EncoderCore { Ok(copies) } + /// Note that the encoder's pass takes the shadowed texture `key` as an attachment. + pub(super) fn shadow_attached(&mut self, key: ResourceKey) { + if !self.attachment_shadows.contains(&key) { + self.attachment_shadows.push(key); + } + } + /// Count shadowed textures' `copies` as planned (`WorkCounts::shadow_copies`), the texels /// their copies in and back of buffers' textures' images move, each copy in's texels by why /// it is made and what holds its truth (`WorkCounts::shadow_texels_first_copied_in` and kin), @@ -1346,6 +1358,7 @@ impl EncoderCore { retained, executions, keys, + attachment_shadows, first_copies, mut heaps, holds, @@ -1364,6 +1377,11 @@ impl EncoderCore { .among(keys.iter().copied()); heaps.extend(keyed); let mut state = open.command_buffer.state(); + if !attachment_shadows.is_empty() { + let first = state.shadows_attached(&attachment_shadows); + (open.command_buffer.device().shared().counts) + .shadow_attachments(attachment_shadows.len(), first); + } if !first_copies.is_empty() { let again = state.shadows_copied_in(&first_copies); if again > 0 { diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 8681bf02e..2bd72ce2f 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -437,9 +437,9 @@ pub(super) fn refuse_unwritable(window: &ImportWindow, counts: &Counters) -> Res } /// Whether the process maps `[start, end)` without a gap, each page with write permission, as the -/// kernel answers now: on Linux for the mappings over it ([`queried_writable`]), or from the lines -/// of `/proc/self/maps` where the kernel predates the query ([`writable`]); `None` when that file -/// cannot be opened. +/// kernel answers now: for the mappings over it ([`queried_writable`]), or from the lines of +/// `/proc/self/maps` where the kernel predates the query ([`writable`]); `None` when that file +/// cannot be opened. Each mapping asked is added to `asked`. #[cfg(target_os = "linux")] fn mappings_writable(start: u64, end: u64, asked: &mut u64) -> Option { use std::io::BufRead; @@ -613,13 +613,6 @@ pub(super) struct Importer { pub(super) page: u64, /// `minImportedHostPointerAlignment`. pub(super) alignment: u64, - /// `vkExportMetalObjectsEXT`, where the device enables `VK_EXT_metal_objects`: each import is - /// then allocated for export of its `MTLBuffer` (`metal_texture.rs`). - metal: Option, - /// `vkSetDebugUtilsObjectNameEXT`, where the device exports `MTLBuffer`s and the runtime's - /// instance reports through `VK_EXT_debug_utils`: an image made of a Metal texture is named - /// [`METAL_TEXTURE_IMAGE`] for the layers' messages. - names: Option, /// `vkGetMemoryFdPropertiesKHR`, where the device enables the dma-buf route (`dma_buf.rs`). dma_buf: Option, /// Whether the device also enables the route's image extensions (`create.rs`'s @@ -632,14 +625,6 @@ pub(super) struct Importer { pub(super) sparse_granule: std::sync::OnceLock>, } -/// The debug name of an image the runtime made of a Metal texture over an import's `MTLBuffer` -/// (`VkImportMetalTextureInfoEXT`, `metal_texture.rs`), where its instance reports messages. The -/// validation layer (1.4.357, and its main of 2026-10-07) does not model that import, which -/// Vulkan treats as bound, and reports such an image as used with no memory bound; the name lets -/// a reader tell those reports from others. -pub(super) const METAL_TEXTURE_IMAGE: &std::ffi::CStr = - c"metal2vulkan: a Metal texture over imported host memory"; - impl Importer { /// The importer of a device, or the refusal every no-copy buffer on it gets: the device did /// not enable `VK_EXT_external_memory_host`, the runtime does not know the host's page size, @@ -657,8 +642,6 @@ impl Importer { enabled: &EnableSet, usage: vk::BufferUsageFlags, loader_word: &LoaderWord, - metal_objects: bool, - debug_names: bool, dma_buf: bool, dma_buf_images: bool, ) -> Result { @@ -702,17 +685,12 @@ impl Importer { function.map_or(std::ptr::null(), |function| function as *const c_void) }; let functions = ash::ext::external_memory_host::DeviceFn::load(load); - let metal = metal_objects.then(|| ash::ext::metal_objects::DeviceFn::load(load)); - let names = - (metal_objects && debug_names).then(|| ash::ext::debug_utils::DeviceFn::load(load)); let dma_buf = dma_buf.then(|| ash::khr::external_memory_fd::DeviceFn::load(load)); let dma_buf_images = dma_buf.is_some() && dma_buf_images; Ok(Importer { functions, page, alignment, - metal, - names, dma_buf, dma_buf_images, sparse_granule: std::sync::OnceLock::new(), @@ -727,9 +705,7 @@ impl Importer { /// Whether the device makes images over dma-bufs of host pages (`dma_buf.rs`): it imports /// dma-bufs and enables `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign` - /// (`create.rs`'s `dma_buf_image_names`). A texture over host pages imported by their pointer - /// may then be a `DRM_FORMAT_MOD_LINEAR` image at Metal's row pitch too (`texture.rs`'s - /// `host_pitched_image`). + /// (`create.rs`'s `dma_buf_image_names`). pub(super) fn makes_dma_buf_images(&self) -> bool { self.dma_buf_images } @@ -765,51 +741,6 @@ impl Importer { result.result_with_success(properties.memory_type_bits) } - /// Whether the device's imports are allocated for export of their `MTLBuffer` - /// (`VK_EXT_metal_objects`). - pub(super) fn exports_metal(&self) -> bool { - self.metal.is_some() - } - - /// The `id` behind `memory`, an import of this importer's device allocated for - /// export; `None` where the device does not export one. - /// - /// # Safety - /// - /// `device` is the importer's device and `memory` a live import of it. - pub(super) unsafe fn metal_buffer( - &self, - device: &ash::Device, - memory: vk::DeviceMemory, - ) -> Option { - let metal = self.metal.as_ref()?; - let mut buffer = vk::ExportMetalBufferInfoEXT::default().memory(memory); - let mut info = vk::ExportMetalObjectsInfoEXT::default().push_next(&mut buffer); - // SAFETY: the caller's; the memory was allocated for export of its `MTLBuffer` - // (`Memory::import_host`), and the function was loaded for this device. - unsafe { (metal.export_metal_objects_ext)(device.handle(), &mut info) }; - let exported = buffer.mtl_buffer; - (!exported.is_null()).then_some(exported) - } - - /// Name `image`, made of a Metal texture, [`METAL_TEXTURE_IMAGE`] where the instance reports - /// messages; a failure to name it is ignored (the name serves messages only). - /// - /// # Safety - /// - /// `device` is the importer's device and `image` a live image of it. - pub(super) unsafe fn name_metal_image(&self, device: &ash::Device, image: vk::Image) { - let Some(names) = &self.names else { - return; - }; - let info = vk::DebugUtilsObjectNameInfoEXT::default() - .object_handle(image) - .object_name(METAL_TEXTURE_IMAGE); - // SAFETY: the caller's; the instance enables `VK_EXT_debug_utils` (it reports messages), - // and the function was loaded for this device. - let _ = unsafe { (names.set_debug_utils_object_name_ext)(device.handle(), &info) }; - } - /// The memory types `pointer` can be imported into (`vkGetMemoryHostPointerPropertiesEXT`). /// /// # Safety diff --git a/crates/metal2vulkan-runtime/src/interop.rs b/crates/metal2vulkan-runtime/src/interop.rs index b7edf0881..a00042355 100644 --- a/crates/metal2vulkan-runtime/src/interop.rs +++ b/crates/metal2vulkan-runtime/src/interop.rs @@ -96,31 +96,25 @@ impl Device { impl Texture { /// No Metal counterpart (an interop hook): the texture's `VkImage`, the image of the texture - /// and of every view of it, made by the - /// runtime or the caller's + /// and of every view of it, made by the runtime or the caller's /// ([`Device::new_texture_with_vk_image`](super::Device::new_texture_with_vk_image)). `None` /// where the texels are a buffer's bytes the runtime copies into and out of an image of its - /// own (a texture buffer, or a texture over a buffer that does not alias it), or another - /// image's texels it so copies (a view of another component layout on a device whose views - /// reinterpret none). A texture with a depth twin gives its `R32_SFLOAT` image, which holds its - /// texels; its comparisons read the twin, which a write into the image does not reach. + /// own (a texture buffer, a texture over a no-copy buffer's host pages, or a texture over + /// another buffer that does not alias it), or another image's texels it so copies (a view of + /// another component layout on a device whose views reinterpret none). A texture with a depth + /// twin gives its `R32_SFLOAT` image, which holds its texels; its comparisons read the twin, + /// which a write into the image does not reach. /// - /// A texture over a buffer's bytes whose image aliases them gives a linear image: of - /// `VK_IMAGE_TILING_LINEAR`, or of `VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT` with - /// `DRM_FORMAT_MOD_LINEAR` and one memory plane laid out at the texels' offset and the - /// texture's `bytes_per_row`. Such a texture's rows lie one after another and its image's - /// subresource holds no byte but its texels, or, for a texture that only reads under - /// `PaddedReadsPolicy::Alias` (the default), its rows lie apart and its subresource holds the - /// buffer's bytes between them too, up to its last row's pitch. A texture whose rows lie with - /// the buffer's bytes between them and which renders or which a shader writes gives none (it - /// is a shadow, `shadowed-texture`) but on MoltenVK, whose image is a Metal texture over the - /// buffer. The second is the image over host pages imported as - /// dma-bufs (`HostMemory::with_dma_buf`), and over a no-copy buffer's host pages where the - /// driver's own linear image lays its rows out otherwise than `bytes_per_row` - /// (`WorkCounts::pitched_host_images` counts them). Ask such an image's layout of its memory - /// plane (`VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT`, not the color aspect), and its modifier - /// with `vkGetImageDrmFormatModifierPropertiesEXT`. Textures of one image over the same bytes - /// of one import of host pages give the same `VkImage`, which they share. + /// A texture over a buffer's bytes whose image aliases them gives a linear image of + /// `VK_IMAGE_TILING_LINEAR`, bound to the buffer's memory, the runtime's own: such a texture's + /// rows lie one after another and its image's subresource holds no byte but its texels. A + /// texture over a no-copy buffer's host pages (imported by their pointer or as dma-bufs) gives + /// none: an image bound to them would start `VK_IMAGE_LAYOUT_UNDEFINED`, whose first move + /// Vulkan lets read and write every byte bound to it (it is a shadow, `shadowed-texture`). A + /// texture placed in a heap over host pages imported as dma-bufs (`HostMemory::with_dma_buf`) + /// gives an image of `VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT` with `DRM_FORMAT_MOD_LINEAR`: + /// ask its layout of its memory plane (`VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT`, not the color + /// aspect), and its modifier with `vkGetImageDrmFormatModifierPropertiesEXT`. /// /// # Safety /// diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index c3fe9bace..07b46a1d0 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -135,7 +135,6 @@ mod managed; mod memory; mod memory_log; mod metal_level; -mod metal_texture; mod mipmap; mod mipmap_filter; mod mipmap_pick; diff --git a/crates/metal2vulkan-runtime/src/linear_attachment.rs b/crates/metal2vulkan-runtime/src/linear_attachment.rs index dd001ad1d..5e090e82f 100644 --- a/crates/metal2vulkan-runtime/src/linear_attachment.rs +++ b/crates/metal2vulkan-runtime/src/linear_attachment.rs @@ -1,14 +1,15 @@ //! Color attachments rendered into linear images in place. //! -//! A texture over a buffer's memory, a no-copy buffer's host pages included, is a linear image -//! over the buffer's bytes where the device makes one that lies on Metal's layout there -//! (`Device::alias_image`), and a heap's texture may be a linear image (`texture/heap.rs`). On a -//! device that enabled `VK_NV_linear_color_attachment`'s `linearColorAttachment` (`enables.rs`), -//! such an image of a format whose linear tiling has `LINEAR_COLOR_ATTACHMENT_NV` takes color -//! attachment usage (`ImageFacts::linear`), and a pass renders into it in place: no shadow, no -//! copy in, no copy back. Vulkan renders it there only where every color attachment of the -//! render pass instance is linear (the extension's rule): such an attachment is *bound* -//! ([`bound`]; `ImageFacts::linear_attachment_rule`). A multisampled image is never linear, so: +//! A texture over a buffer of the runtime's memory is a linear image over the buffer's bytes where +//! the device makes one that lies on Metal's layout there (`Device::alias_image`; one over a +//! no-copy buffer's host pages is a shadow), and a heap's texture may be a linear image +//! (`texture/heap.rs`). On a device that enabled `VK_NV_linear_color_attachment`'s +//! `linearColorAttachment` (`enables.rs`), such an image of a format whose linear tiling has +//! `LINEAR_COLOR_ATTACHMENT_NV` takes color attachment usage (`ImageFacts::linear`), and a pass +//! renders into it in place: no shadow, no copy in, no copy back. Vulkan renders it there only +//! where every color attachment of the render pass instance is linear (the extension's rule): such +//! an attachment is *bound* ([`bound`]; `ImageFacts::linear_attachment_rule`). A multisampled image +//! is never linear, so: //! //! - **A pass beside a color attachment that is not linear** (a private texture's image, an image //! of the runtime's standing in for an attachment), **or with a depth or stencil attachment** diff --git a/crates/metal2vulkan-runtime/src/linear_plan.rs b/crates/metal2vulkan-runtime/src/linear_plan.rs index 93190866b..d78c52e4e 100644 --- a/crates/metal2vulkan-runtime/src/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/linear_plan.rs @@ -119,13 +119,11 @@ //! (it lacks nothing, [`linear_lack`]), and the image the device made, at the pitch it chose //! itself, sits exactly on Metal's layout and holds no byte but the texels ([`aliases`]). A //! texture whose rows or slices lie with the buffer's bytes between them, which Metal leaves as the -//! program writes them, is one only where it only reads, under the policy's default -//! (`PaddedReadsPolicy::Alias`): its image then holds those bytes too, which Vulkan lets its layout -//! transitions write, and it takes one, its first move ([`holding`]). A texture that renders or -//! writes over such rows never is one, as a render pass's load and store operations write every -//! byte of an attachment's subresource. Otherwise it is a shadow image the encoders copy from and -//! to the buffer (`shadow.rs`), whose copies address the buffer's texels alone, which is exact for -//! Metal's defined behaviour. +//! program writes them, never is one, whatever its usage ([`holding`]): its image would hold those +//! bytes too, which Vulkan lets its layout transitions (its first move among them) and a render +//! pass's load and store operations write. Otherwise it is a shadow image the encoders copy from +//! and to the buffer (`shadow.rs`), whose copies address the buffer's texels alone, which is exact +//! for Metal's defined behaviour. use super::chroma_pairs::is_four_two_two; use super::copy_plan::block_extent; @@ -133,7 +131,6 @@ use super::image_plan::{compatible, view_formats, ImageFacts, ImagePlan}; use super::metal_level::MetalLevel; use super::texture_descriptor::TextureLayout; use super::values::StorageMode; -use metal2vulkan::device::PaddedReadsPolicy; use metal2vulkan::error::LinearNeed; use metal2vulkan::metal::format::is_depth_stencil; use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; @@ -705,13 +702,11 @@ pub(super) struct LinearImage { /// memory block), holds exactly Metal's texels in the `room` bytes from there to the end of the /// buffer's memory: the binding is a multiple of the image's alignment, its texels start at the /// binding, its row pitch is Metal's and so is its slice pitch where it has several slices, its -/// subresources hold no byte but what `holds` lets them (the texture's texels, and for -/// [`Holds::Padding`] the bytes between its rows), and its memory stays in the buffer's. A driver -/// may report a pitch other than the one asked of it (NVIDIA does for explicit layouts it does not -/// support), so the image's own report decides. +/// subresources hold no byte but the texture's texels ([`texels_alone`]), and its memory stays in +/// the buffer's. A driver may report a pitch other than the one asked of it (NVIDIA does for +/// explicit layouts it does not support), so the image's own report decides. pub(super) fn aliases( layout: &BufferLayout, - holds: Holds, memory_offset: u64, room: u64, image: &LinearImage, @@ -721,60 +716,14 @@ pub(super) fn aliases( && image.offset == 0 && image.row_pitch == layout.row_pitch && (layout.slices == 1 || image.array_pitch == layout.slice_pitch) - && holds.fits(layout, image.subresource, image.array_pitch) + && texels_alone(layout, image.subresource, image.array_pitch) && image.size <= room } -/// What an image over a texture's texels in a buffer may hold in its subresources beside the -/// texels ([`holding`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Holds { - /// The texels alone: no byte of its subresources is another's ([`texels_alone`]). - Texels, - /// The texels and the bytes between the texture's rows (and slices), its last row's to its row - /// pitch among them, but nothing past them ([`padded_alone`]): a texture that only reads, over - /// rows that lie apart, under `PaddedReadsPolicy::Alias`. - Padding, -} - -impl Holds { - /// Whether an image whose subresources take `size` bytes each from the first texel of their - /// slice, `array_pitch` apart, holds only what `self` lets it over `layout`'s texels. - pub(super) fn fits(self, layout: &BufferLayout, size: u64, array_pitch: u64) -> bool { - match self { - Holds::Texels => texels_alone(layout, size, array_pitch), - Holds::Padding => padded_alone(layout, size, array_pitch), - } - } - - /// The bytes from the texture's first texel that its image's subresources may reach. - pub(super) fn reach(self, layout: &BufferLayout) -> u64 { - match self { - Holds::Texels => layout.end() - layout.offset, - Holds::Padding => rows_end(layout) - layout.offset, - } - } -} - -/// Whether a texture of Metal `usage` (as Metal reports it: `Unknown` as `ShaderRead | -/// ShaderWrite | RenderTarget | PixelFormatView`, `texture_descriptor::texture_usage`) only reads: -/// no render pass takes its image as an attachment (`RenderTarget`), and no shader writes it -/// (`ShaderWrite`, `ShaderAtomic`, block writes). -pub(super) fn only_reads(usage: TextureUsage) -> bool { - !usage.intersects( - TextureUsage::RENDER_TARGET - | TextureUsage::SHADER_WRITE - | TextureUsage::SHADER_ATOMIC - | TextureUsage::BLOCK_WRITES_ONLY, - ) -} - -/// What an image over `layout`'s texels may hold beside them, for a texture of Metal `usage` (as -/// [`only_reads`] takes it) under `policy`, or why no image may hold them: the texels alone -/// where its rows (and slices) lie one after another, or it has one row (one slice); else, where +/// Whether an image over `layout`'s texels, for a texture of Metal `usage`, may hold them: where +/// its rows (and slices) lie one after another, or it has one row (one slice); else why not, where /// they lie with bytes between them that are not texels (the buffer's, which Metal's writes of the -/// texture never reach), those bytes too where the texture only reads and the policy aliases them -/// (`PaddedReadsPolicy::Alias`), and else why not. +/// texture never reach), whatever its usage. /// /// An image whose rows lie `row_pitch` apart holds those bytes in its subresource /// (`VkSubresourceLayout`: "size includes any extra memory that is required based on rowPitch"), @@ -796,18 +745,13 @@ pub(super) fn only_reads(usage: TextureUsage) -> bool { /// /// A copy and a shader's read or write of the image touch its texels alone (the Memory /// Model: "A memory operation must not affect memory at a memory location not within its set of -/// memory locations"). So a texture that renders or writes is a shadow: a write back of what was -/// read would undo the program's write of the bytes meanwhile, which Metal keeps, and lavapipe -/// reads the bytes its 4-texel blocks reach past a row's texels and writes them back, a signaling -/// NaN's bits quieted. A texture that only reads meets the bytes at its first move alone, across -/// which the host keeps them (`texture/first_move.rs`'s `Keep`; a CPU write to them meanwhile is -/// undone, `docs/FAST-PATHS.md`'s known gaps): the policy's default aliases them, and -/// `PaddedReadsPolicy::Shadow` keeps the shadow. -pub(super) fn holding( - layout: &BufferLayout, - usage: TextureUsage, - policy: PaddedReadsPolicy, -) -> Result { +/// memory locations"). But every image takes a first move, across which the host could keep the +/// bytes only by reading them before it and writing them back after (`texture/first_move.rs`'s +/// `Keep`), undoing a CPU write made to them meanwhile, where Metal keeps every one; and lavapipe's +/// shader writes read the bytes its 4-texel blocks reach past a row's texels and write them back, a +/// signaling NaN's bits quieted. So such a texture is a shadow, whose copies address its texels +/// alone. +pub(super) fn holding(layout: &BufferLayout, usage: TextureUsage) -> Result<(), String> { let (rows, slices) = apart(layout); let apart = if rows { format!( @@ -820,12 +764,8 @@ pub(super) fn holding( layout.slice_pitch, layout.rows, layout.row_pitch ) } else { - return Ok(Holds::Texels); + return Ok(()); }; - let reads = only_reads(usage); - if reads && policy == PaddedReadsPolicy::Alias { - return Ok(Holds::Padding); - } let writers = if usage.contains(TextureUsage::RENDER_TARGET) { "its layout transitions read and write, and a render pass's load and store operations \ write back" @@ -833,15 +773,8 @@ pub(super) fn holding( "its layout transitions read and write, its first move from the layout it is made in \ among them" }; - let asked = if reads { - " (the device's policy asks no image over them for a texture that only reads, \ - `PaddedReadsPolicy::Shadow`)" - } else { - "" - }; Err(format!( - "{apart}: an image over them holds the bytes between them, which Vulkan lets \ - {writers}{asked}" + "{apart}: an image over them holds the bytes between them, which Vulkan lets {writers}" )) } @@ -860,24 +793,6 @@ pub(super) fn texels_alone(layout: &BufferLayout, size: u64, array_pitch: u64) - apart(layout) == (false, false) && last.saturating_add(size) <= texels } -/// Whether a linear image over `layout`'s texels, whose subresources take `size` bytes each from -/// the first texel of their slice, `array_pitch` apart, holds no byte but the texture's texels and -/// the bytes between its rows and slices ([`Holds::Padding`]): its last subresource ends at its last -/// row's pitch or before ([`rows_end`]). A byte past that is no row's, and no move of the image may -/// reach it, as [`texels_alone`] keeps it for tight rows (lavapipe's rows rounded up to 4). -pub(super) fn padded_alone(layout: &BufferLayout, size: u64, array_pitch: u64) -> bool { - let last = array_pitch.saturating_mul(layout.slices - 1); - last.saturating_add(size) <= rows_end(layout) - layout.offset -} - -/// One past `layout`'s last row at its row pitch: the texels' end with the last row's padding. -fn rows_end(layout: &BufferLayout) -> u64 { - layout - .offset - .saturating_add(layout.slice_pitch.saturating_mul(layout.slices - 1)) - .saturating_add(layout.row_pitch.saturating_mul(layout.rows)) -} - /// Whether `layout`'s rows, and its slices, lie with bytes between them that are not texels. fn apart(layout: &BufferLayout) -> (bool, bool) { let rows = layout.rows > 1 && layout.row_pitch != layout.row_bytes; diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 609974cdf..3606da98f 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -535,12 +535,6 @@ impl Mapped { pub(super) fn as_ptr(self) -> *mut u8 { self.0.as_ptr() } - - /// The address `bytes` past this one, in the same mapping. - pub(super) fn add(self, bytes: u64) -> Mapped { - let bytes = usize::try_from(bytes).unwrap_or(usize::MAX); - Mapped(NonNull::new(self.0.as_ptr().wrapping_add(bytes)).unwrap_or(self.0)) - } } /// One `VkDeviceMemory` block. @@ -1280,9 +1274,8 @@ impl Memory { /// import alignment), as a dedicated block of the best memory type of `class` among /// `allowed` (the types both the pointer and the resource take): its placement at offset 0, /// whose `mapped` is `pointer`. The block is never pooled and is freed with the placement, - /// as a dedicated block is (`host_memory.rs`). Allocated for export of its - /// `MTLBuffer` where `export_metal` (`VK_EXT_metal_objects`, `metal_texture.rs`). Refused - /// when no type of `class` is among `allowed`, else with the failure of the last type tried. + /// as a dedicated block is (`host_memory.rs`). Refused when no type of `class` is among + /// `allowed`, else with the failure of the last type tried. /// /// # Safety /// @@ -1295,7 +1288,6 @@ impl Memory { size: u64, allowed: u32, class: MemoryClass, - export_metal: bool, ) -> Result { let mut failure = ImportFailure::NoMemoryType; for type_index in candidates(&self.types, allowed, class, self.unified) { @@ -1304,8 +1296,6 @@ impl Memory { .host_pointer(pointer.as_ptr().cast()); let mut flags = vk::MemoryAllocateFlagsInfo::default() .flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); - let mut export = vk::ExportMetalObjectCreateInfoEXT::default() - .export_object_type(vk::ExportMetalObjectTypeFlagsEXT::METAL_BUFFER); let mut info = vk::MemoryAllocateInfo::default() .allocation_size(size) .memory_type_index(type_index) @@ -1313,9 +1303,6 @@ impl Memory { if self.device_address { info = info.push_next(&mut flags); } - if export_metal { - info = info.push_next(&mut export); - } // SAFETY: `info` and its chain live for the call; the type index is the device's and // allows the pointer; the caller's contract keeps the memory mapped. match unsafe { device.allocate_memory(&info, None) } { diff --git a/crates/metal2vulkan-runtime/src/metal_texture.rs b/crates/metal2vulkan-runtime/src/metal_texture.rs deleted file mode 100644 index 342e92630..000000000 --- a/crates/metal2vulkan-runtime/src/metal_texture.rs +++ /dev/null @@ -1,429 +0,0 @@ -//! Metal textures over the `MTLBuffer` of a Vulkan-on-Metal device's imported host memory. -//! -//! A texture over a no-copy buffer aliases the caller's pages through a linear image made for -//! host allocations where the device makes one that lies on Metal's layout (`texture.rs`, -//! `Device::alias_image`). MoltenVK makes none that renders on macOS: its linear images have no -//! colour-attachment or blend feature there, and it refuses the host import for render-target -//! usage. Metal itself makes a texture over a buffer's bytes that renders -//! (`-[MTLBuffer newTextureWithDescriptor:offset:bytesPerRow:]`), and a device that lists -//! `VK_EXT_metal_objects` gives the `MTLBuffer` behind memory it imported -//! (`vkExportMetalObjectsEXT`, memory allocated for export) and makes an image of an -//! `MTLTexture` the caller gives it (`VkImportMetalTextureInfoEXT`, treated as bound). So on such -//! a device a texture over a no-copy buffer is an image of a Metal texture over the import's -//! `MTLBuffer`, at the texels' offset and row pitch, where Metal makes one there: no shadow, and -//! one `MTLBuffer` for Metal's hazard tracking, as the buffer's own uses name. -//! -//! The texture's description is the image's: a 2D texture of one level, slice and sample, or a -//! 2D array of one level and sample whose slices lie as Metal's linear call lays them out (below), -//! of the Metal pixel format whose Vulkan format the image is directly (`FormatEmulation::Direct`), -//! or for one of Apple's extended-range formats whose image holds Metal's bytes in an unsigned -//! integer format (`FormatEmulation::ExtendedRange`) the integer Metal format of that Vulkan -//! format, which holds the same bytes, and for a 4:2:2 texture, whose image is the carrier's, the -//! carrier's own Metal format (`RG8Unorm`, the same bytes; Metal makes no linear 4:2:2 texture); -//! the `MTLTextureUsage` its Vulkan usage needs on Metal, and the buffer's resource options (Metal -//! makes a texture over a buffer only in the buffer's storage and CPU cache modes). Elsewhere -//! (another platform, or no such texture) the answer is `None`, and the texture stays as it was: a -//! linear alias where one lies on Metal's layout, else a shadow. -//! -//! A 2D array: Metal's public `newTextureWithDescriptor:offset:bytesPerRow:` asserts on any array, -//! and only the call outside the public SDK, -//! `newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:`, makes one over a buffer (the -//! call a caller's `Buffer::new_linear_texture` stands for), each slice `bytesPerRow` x height, -//! rounded up to 128 bytes, after the one before, whatever `bytesPerImage` is (EV ZCI2-spiprobe-m4 -//! over a no-copy buffer too). Private Metal that real Metal has belongs to the runtime (the user's -//! ruling of 2026-10-08), so an array is made through that call where the buffer answers to it -//! (`respondsToSelector:`), at an offset that is a multiple of 128 and rows a multiple of 16 (Metal -//! asserts otherwise), and stays shadowed where it does not. - -use super::chroma_pairs; -use super::image_plan::ImagePlan; -use super::linear_plan::ARRAY_ALIGNMENT; -use ash::vk; -use metal2vulkan::metal::format::{is_depth_stencil, ExtendedRange, FormatEmulation}; -use metal2vulkan::metal::PixelFormat; -use std::ffi::c_void; - -/// `MTLTextureUsage`'s bits. -const SHADER_READ: u64 = 0x1; -const SHADER_WRITE: u64 = 0x2; -const RENDER_TARGET: u64 = 0x4; -const PIXEL_FORMAT_VIEW: u64 = 0x10; - -/// A Metal texture over a buffer's bytes, as [`texture_over`] makes it: what a rebind makes again -/// over the new pages (`texture.rs`'s `AliasWatch`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) struct MetalOver { - /// The texture's `MTLPixelFormat`. - pixel_format: u64, - width: u64, - height: u64, - /// Its `MTLTextureUsage`. - usage: u64, - bytes_per_row: u64, - /// The slices of a 2D array (made through the linear call), 1 for a 2D texture. - slices: u64, - /// A 2D array's slice stride, the linear call's `bytesPerImage` (Metal's own, which the call - /// keeps whatever it is given); 0 for a 2D texture. - bytes_per_image: u64, -} - -impl MetalOver { - /// The Metal texture of `plan`, rows `bytes_per_row` bytes apart and (a 2D array's) slices - /// `bytes_per_image` apart; for an image no such texture is, why (for the shadow's notice): - /// not 2D of one level and sample, an array whose slices lie otherwise than Metal's linear - /// call lays them out, or not holding a Metal pixel format's bytes in that format's own Vulkan - /// format. - pub(super) fn of( - plan: &ImagePlan, - bytes_per_row: u64, - bytes_per_image: u64, - ) -> Result { - let [width, height, depth] = plan.extent; - let plane = depth == 1 - && plan.levels == 1 - && vk::SampleCountFlags::from(plan.samples) == vk::SampleCountFlags::TYPE_1 - && vk::ImageType::from(plan.image_type) == vk::ImageType::TYPE_2D; - if !plane { - return Err( - "its image is not 2D of one level and sample, as a Metal texture over a buffer \ - is", - ); - } - // Metal makes no linear texture of a depth or stencil format: asked for one, its device - // aborts the process ("Linear textures do not support depth/stencil pixel formats", an - // M4 under MoltenVK). Such a texture (a planar surface's, `linear_plan.rs`) is the aspect - // shadow (`Device::storage_over_buffer`). - if is_depth_stencil(plan.pixel_format) { - return Err("Metal makes no linear texture of a depth or stencil format"); - } - let slices = u64::from(plan.layers); - let metal_stride = bytes_per_row - .saturating_mul(u64::from(height)) - .checked_next_multiple_of(ARRAY_ALIGNMENT); - if slices > 1 && metal_stride != Some(bytes_per_image) { - return Err( - "its slices lie otherwise than those of the 2D array Metal's linear call makes \ - over a buffer", - ); - } - let pixel_format = match plan.mapping.emulation { - FormatEmulation::Direct if chroma_pairs::holds_pairs(plan) => { - chroma_pairs::CARRIER_PIXEL_FORMAT - } - FormatEmulation::Direct if plan.pixel_format != PixelFormat::Invalid => { - plan.pixel_format - } - FormatEmulation::ExtendedRange | FormatEmulation::Bfloat => { - integer_twin(plan.pixel_format).ok_or( - "its format's image holds the texels' two planes side by side, which no Metal \ - texture over the buffer's bytes is", - )? - } - _ => { - return Err( - "its format's image holds no Metal pixel format's texels in that \ - format's own Vulkan format", - ) - } - }; - let usage_flags = vk::ImageUsageFlags::from(plan.usage); - let mut usage = SHADER_READ; - if usage_flags.contains(vk::ImageUsageFlags::STORAGE) { - usage |= SHADER_WRITE; - } - // MoltenVK clears an image (a transfer write) in a render pass. - if usage_flags - .intersects(vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::TRANSFER_DST) - { - usage |= RENDER_TARGET; - } - if vk::ImageCreateFlags::from(plan.flags).contains(vk::ImageCreateFlags::MUTABLE_FORMAT) { - usage |= PIXEL_FORMAT_VIEW; - } - Ok(MetalOver { - pixel_format: u64::from(pixel_format.as_raw()), - width: u64::from(width), - height: u64::from(height), - usage, - bytes_per_row, - slices, - bytes_per_image: if slices > 1 { bytes_per_image } else { 0 }, - }) - } - - /// The texture's description, for the shadow's notice where Metal makes none. - pub(super) fn describe(&self) -> String { - let slices = if self.slices > 1 { - format!( - " in {} slices {} bytes apart", - self.slices, self.bytes_per_image - ) - } else { - String::new() - }; - format!( - "MTLPixelFormat {} of {}x{}{slices}, usage {:#x}, with rows of {} bytes", - self.pixel_format, self.width, self.height, self.usage, self.bytes_per_row - ) - } -} - -/// The unsigned integer Metal format of the Vulkan format an image of Apple's extended-range -/// format `pf` holds Metal's bytes in (`ExtendedRange::raw_format`), which holds the same bytes: -/// `R32Uint` for `BGR10_XR` and its sRGB twin (`R32_UINT`), `RGBA16Uint` for `BGRA10_XR` and its -/// twin (`R16G16B16A16_UINT`), `R16Uint` and `RG16Uint` for the padded 10-bit formats, `R16Uint`, -/// `RG16Uint` and `RGBA16Uint` for the bfloat formats. `None` for the two-plane formats, whose -/// image holds both planes side by side (not Metal's bytes), and any other format. -pub(super) fn integer_twin(pf: PixelFormat) -> Option { - match ExtendedRange::of(pf)? { - ExtendedRange::Bgr10 { .. } => Some(PixelFormat::R32Uint), - ExtendedRange::Bgra10 { .. } => Some(PixelFormat::RGBA16Uint), - ExtendedRange::R10X6 | ExtendedRange::R10X6Srgb => Some(PixelFormat::R16Uint), - ExtendedRange::Rg10X12 | ExtendedRange::Rg10X12Srgb => Some(PixelFormat::RG16Uint), - ExtendedRange::R16Bfloat => Some(PixelFormat::R16Uint), - ExtendedRange::Rg16Bfloat => Some(PixelFormat::RG16Uint), - ExtendedRange::Rgba16Bfloat => Some(PixelFormat::RGBA16Uint), - _ => None, - } -} - -/// A Metal texture the runtime made (+1), released when this goes. -pub(super) struct MetalTexture(*mut c_void); - -impl MetalTexture { - /// The `id`, for `VkImportMetalTextureInfoEXT`. - pub(super) fn id(&self) -> vk::MTLTexture_id { - self.0 - } -} - -impl Drop for MetalTexture { - fn drop(&mut self) { - // SAFETY: the texture is the runtime's own reference, released once. - unsafe { objc::release(self.0) }; - } -} - -/// The Metal texture `over` describes over `buffer`'s bytes from `offset`, in the buffer's -/// storage and CPU cache modes; where Metal makes none there, why: no Metal, off its alignment -/// for the format (or an array's), a buffer that has no linear call for an array, or refused. -/// -/// # Safety -/// -/// `buffer` is a live `id` holding at least the texture's bytes from `offset`. -pub(super) unsafe fn texture_over( - buffer: vk::MTLBuffer_id, - over: &MetalOver, - offset: u64, -) -> Result { - let words = [ - over.pixel_format, - over.width, - over.height, - over.usage, - over.bytes_per_row, - offset, - over.slices, - over.bytes_per_image, - ]; - // SAFETY: the caller's. - let made = unsafe { objc::texture_over(buffer, words) }?; - Ok(MetalTexture(made)) -} - -#[cfg(target_os = "macos")] -mod objc { - //! The few Objective-C messages a Metal texture over a buffer takes, sent through the - //! Objective-C runtime the Metal framework (loaded by the Vulkan driver) runs on. - - use std::ffi::{c_char, c_void, CStr}; - - /// The words of a texture over a buffer's bytes: `super::MetalOver`'s and the offset. - struct Texture { - pixel_format: u64, - width: u64, - height: u64, - usage: u64, - bytes_per_row: u64, - offset: u64, - slices: u64, - bytes_per_image: u64, - } - - type Id = *mut c_void; - type Sel = *const c_void; - - #[link(name = "objc", kind = "dylib")] - extern "C" { - fn objc_getClass(name: *const c_char) -> Id; - fn sel_registerName(name: *const c_char) -> Sel; - fn objc_msgSend(); - fn objc_autoreleasePoolPush() -> *mut c_void; - fn objc_autoreleasePoolPop(pool: *mut c_void); - } - - /// `objc_msgSend` as a function of the message's arguments and answer. - macro_rules! send { - ($receiver:expr, $selector:expr $(, $argument:expr => $kind:ty)* ; $answer:ty) => {{ - // SAFETY: `objc_msgSend` is called with the receiver's method's exact signature. - let send = unsafe { - std::mem::transmute::< - unsafe extern "C" fn(), - unsafe extern "C" fn(Id, Sel $(, $kind)*) -> $answer, - >(objc_msgSend) - }; - // SAFETY: the selector names a method of the receiver taking those arguments. - unsafe { send($receiver, selector($selector) $(, $argument)*) } - }}; - } - - fn selector(name: &CStr) -> Sel { - // SAFETY: a NUL-terminated name; registering a selector has no other precondition. - unsafe { sel_registerName(name.as_ptr()) } - } - - /// `[object release]`. - /// - /// # Safety - /// - /// `object` is a live object the caller holds a reference to, which this gives up. - pub(super) unsafe fn release(object: Id) { - send!(object, c"release"; ()); - } - - /// The `+1` texture over `buffer`'s bytes (`newTextureWithDescriptor:offset:bytesPerRow:`, - /// or for an array `newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:`), or - /// why none is made. - /// - /// # Safety - /// - /// `buffer` is a live `id`. - pub(super) unsafe fn texture_over(buffer: Id, words: [u64; 8]) -> Result { - let [pixel_format, width, height, usage, bytes_per_row, offset, slices, bytes_per_image] = - words; - let texture = Texture { - pixel_format, - width, - height, - usage, - bytes_per_row, - offset, - slices, - bytes_per_image, - }; - // SAFETY: no precondition; popped below. - let pool = unsafe { objc_autoreleasePoolPush() }; - // SAFETY: the caller's. - let made = unsafe { texture_in_pool(buffer, &texture) }; - // SAFETY: the pool pushed above, the innermost. - unsafe { objc_autoreleasePoolPop(pool) }; - made - } - - /// [`texture_over`] inside an autorelease pool. - /// - /// # Safety - /// - /// As [`texture_over`]'s. - unsafe fn texture_in_pool(buffer: Id, over: &Texture) -> Result { - let refused = "Metal answers no texture there"; - // SAFETY: a NUL-terminated name. - let class = unsafe { objc_getClass(c"MTLTextureDescriptor".as_ptr()) }; - if class.is_null() || buffer.is_null() { - return Err(refused); - } - let device: Id = send!(buffer, c"device"; Id); - if device.is_null() { - return Err(refused); - } - let alignment: usize = send!( - device, - c"minimumLinearTextureAlignmentForPixelFormat:", - over.pixel_format as usize => usize; - usize - ); - let alignment = alignment.max(1) as u64; - if !over.offset.is_multiple_of(alignment) || !over.bytes_per_row.is_multiple_of(alignment) { - return Err("the offset or the rows are off Metal's linear texture alignment"); - } - let array = over.slices > 1; - let linear = c"newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:"; - if array { - // Metal asserts on an array's offset off 128 (`ARRAY_ALIGNMENT`) or rows off 16. - if !over.offset.is_multiple_of(super::ARRAY_ALIGNMENT) - || !over.bytes_per_row.is_multiple_of(16) - { - return Err("the offset or the rows are off Metal's 2D array alignment"); - } - let answers: i8 = send!(buffer, c"respondsToSelector:", selector(linear) => Sel; i8); - if answers == 0 { - return Err( - "Metal's buffer has no newLinearTextureWithDescriptor:offset:bytesPerRow:\ - bytesPerImage:, the only call that makes a 2D array over a buffer", - ); - } - } - let options: usize = send!(buffer, c"resourceOptions"; usize); - let allocated: Id = send!(class, c"alloc"; Id); - let descriptor: Id = send!(allocated, c"init"; Id); - if descriptor.is_null() { - return Err(refused); - } - // MTLTextureType2D, or MTLTextureType2DArray. - let texture_type: usize = if array { 3 } else { 2 }; - send!(descriptor, c"setTextureType:", texture_type => usize; ()); - send!(descriptor, c"setPixelFormat:", over.pixel_format as usize => usize; ()); - send!(descriptor, c"setWidth:", over.width as usize => usize; ()); - send!(descriptor, c"setHeight:", over.height as usize => usize; ()); - if array { - send!(descriptor, c"setArrayLength:", over.slices as usize => usize; ()); - } - send!(descriptor, c"setUsage:", over.usage as usize => usize; ()); - send!(descriptor, c"setResourceOptions:", options => usize; ()); - let texture: Id = if array { - send!( - buffer, - linear, - descriptor => Id, - over.offset as usize => usize, - over.bytes_per_row as usize => usize, - over.bytes_per_image as usize => usize; - Id - ) - } else { - send!( - buffer, - c"newTextureWithDescriptor:offset:bytesPerRow:", - descriptor => Id, - over.offset as usize => usize, - over.bytes_per_row as usize => usize; - Id - ) - }; - // SAFETY: the descriptor this made (+1). - unsafe { release(descriptor) }; - if texture.is_null() { - Err(refused) - } else { - Ok(texture) - } - } -} - -#[cfg(not(target_os = "macos"))] -mod objc { - //! No Metal: no texture is made. - - use std::ffi::c_void; - - /// Never reached: no texture is made here. - pub(super) unsafe fn release(_object: *mut c_void) {} - - /// No texture: there is no Metal here. - pub(super) unsafe fn texture_over( - _buffer: *mut c_void, - _words: [u64; 8], - ) -> Result<*mut c_void, &'static str> { - Err("there is no Metal here") - } -} diff --git a/crates/metal2vulkan-runtime/src/render/shadows.rs b/crates/metal2vulkan-runtime/src/render/shadows.rs index 8a95813d2..f2139caea 100644 --- a/crates/metal2vulkan-runtime/src/render/shadows.rs +++ b/crates/metal2vulkan-runtime/src/render/shadows.rs @@ -277,10 +277,15 @@ pub(super) fn plan<'a>( writes.push((uses, texture.usage_shadow_copies())); } let mut copies = Vec::new(); - for (instance, bound) in instances { + for (index, (instance, bound)) in instances.enumerate() { let bound = bound.filter(|_| drawn.is_some()); let attachments = attachment_shadows(layout, reached, drawn, bound); + if index == 0 { + for shadow in &attachments { + core.shadow_attached(shadow.copies.shadow_key); + } count_colors(&core.device().shared().counts, layout, reached, drawn, area); + } let mut shadows = Vec::with_capacity(attachments.len() + instance.shadows.len()); for shadow in attachments.iter().chain(&instance.shadows) { shadow::join(&mut shadows, shadow); diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index 53796c158..8e3f147c3 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -413,7 +413,8 @@ pub(super) struct ShadowStaging { pub(super) buffer: Buffer, /// The texture's bytes from its buffer into the staging buffer. pub(super) into: vk::BufferCopy, - /// Each row of texels from the staging buffer back into the texture's buffer. + /// Each row of texels from the staging buffer back into the texture's buffer: one region for + /// rows that lie one after another. pub(super) back: Vec, } diff --git a/crates/metal2vulkan-runtime/src/tests/buffer_texture.rs b/crates/metal2vulkan-runtime/src/tests/buffer_texture.rs index 9635b2e98..809710eba 100644 --- a/crates/metal2vulkan-runtime/src/tests/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/tests/buffer_texture.rs @@ -1,8 +1,11 @@ //! Texture buffers' texel buffer views (`buffer_texture`): the usage a view takes beside its -//! buffer's, by the kinds of texel buffer its format serves on the device. +//! buffer's, by the kinds of texel buffer its format serves on the device; and a staged shadow's +//! regions back into its buffer. -use super::super::buffer_texture::{view_usage, ViewUsage}; +use super::super::buffer_texture::{staged_rows_back, view_usage, ViewUsage}; use super::super::error::{Error, RuntimeGap}; +use super::super::linear_plan::BufferLayout; +use ash::vk; use metal2vulkan::device::FormatUsage; /// Whether `result` is the typed gap of a view the runtime does not make. @@ -41,3 +44,37 @@ fn a_view_names_the_one_kind_its_format_serves_where_maintenance5_allows() { assert!(not_made(view_usage(uniform_only, true, true))); assert!(not_made(view_usage(|_| false, true, true))); } + +/// A staged shadow's texels go back into the buffer as one region where its rows lie one after +/// another (a 1080p surface's packed rows: one region, not 1080), and a region a row where bytes +/// lie between them; each slice of packed rows joins the next where the slices lie one after +/// another too. +#[test] +fn packed_rows_go_back_as_one_region() { + let layout = |row_pitch: u64, rows: u64, slices: u64| BufferLayout { + offset: 0, + row_pitch, + slice_pitch: row_pitch * rows, + row_bytes: 7680, + rows, + slices, + }; + let regions = |layout: BufferLayout, start: u64, at: u64| -> Vec<(u64, u64, u64)> { + (staged_rows_back(&layout, start, at).iter()) + .map(|copy: &vk::BufferCopy| (copy.src_offset, copy.dst_offset, copy.size)) + .collect() + }; + assert_eq!( + regions(layout(7680, 1080, 1), 64, 3), + [(64, 3, 7680 * 1080)] + ); + assert_eq!(regions(layout(7680, 4, 2), 0, 5), [(0, 5, 7680 * 8)]); + assert_eq!( + regions(layout(7744, 3, 1), 0, 5), + [ + (0, 5, 7680), + (7744, 7749, 7680), + (2 * 7744, 2 * 7744 + 5, 7680) + ] + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/first_moves.rs b/crates/metal2vulkan-runtime/src/tests/first_moves.rs index 71110f86e..c23570ba4 100644 --- a/crates/metal2vulkan-runtime/src/tests/first_moves.rs +++ b/crates/metal2vulkan-runtime/src/tests/first_moves.rs @@ -28,165 +28,3 @@ fn a_staged_decode_alone_leaves_the_texels_to_cpu_copies() { assert!(!firsts.texels_wait(at(&decoding))); assert!(firsts.texels_wait(at(&copied))); } - -/// The runs of changed bytes are exact: each as long as it runs, across the comparison's 64-byte -/// blocks, and none where nothing changed. -#[test] -fn the_changed_runs_are_the_bytes_that_differ() { - use crate::texture::first_move::changed_runs; - let kept: Vec = (0..300u32).map(|i| (i * 7) as u8).collect(); - assert_eq!(changed_runs(&kept, &kept), Vec::new()); - let mut now = kept.clone(); - for at in [0, 1, 2, 63, 64, 130, 299] { - now[at] ^= 0x5a; - } - assert_eq!( - changed_runs(&kept, &now), - vec![0..3, 63..65, 130..131, 299..300] - ); - let mut now = kept.clone(); - now[10..250].iter_mut().for_each(|byte| *byte = !*byte); - assert_eq!(changed_runs(&kept, &now), vec![10..250]); -} - -/// Fresh private pages, `pages` of them, read and write, holding `fill`; unmapped as it drops. -#[cfg(any(target_os = "linux", target_vendor = "apple"))] -struct Pages { - at: *mut u8, - len: usize, - page: usize, -} - -#[cfg(any(target_os = "linux", target_vendor = "apple"))] -impl Pages { - fn new(pages: usize, fill: u8) -> Pages { - // SAFETY: `sysconf` reads a system constant. - let page = usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap(); - let len = pages * page; - // SAFETY: a fresh private mapping, unmapped as `Pages` drops. - let at = unsafe { - libc::mmap( - std::ptr::null_mut(), - len, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANON, - -1, - 0, - ) - }; - assert_ne!(at, libc::MAP_FAILED); - let at = at.cast::(); - // SAFETY: the mapping's own bytes. - unsafe { at.write_bytes(fill, len) }; - Pages { at, len, page } - } - - /// Make page `index` read-only. - fn read_only(&self, index: usize) { - // SAFETY: a page of this mapping. - let done = unsafe { - libc::mprotect( - self.at.add(index * self.page).cast(), - self.page, - libc::PROT_READ, - ) - }; - assert_eq!(done, 0, "mprotect"); - } - - fn bytes(&self) -> Vec { - // SAFETY: the mapping's own bytes, readable. - unsafe { std::slice::from_raw_parts(self.at, self.len) }.to_vec() - } - - fn write(&self, at: usize, byte: u8) { - // SAFETY: a byte of the mapping, on a page still writable. - unsafe { self.at.add(at).write(byte) }; - } -} - -#[cfg(any(target_os = "linux", target_vendor = "apple"))] -impl Drop for Pages { - fn drop(&mut self) { - // SAFETY: the mapping is this value's. - unsafe { libc::munmap(self.at.cast(), self.len) }; - } -} - -/// The kernel's answer for the process's own pages: a fresh mapping is writable until a page of it -/// is made read-only, and pages no longer mapped are not (`host_memory::host_writable`, on Linux -/// and Apple's systems). -#[cfg(any(target_os = "linux", target_vendor = "apple"))] -#[test] -fn the_kernel_says_which_of_the_process_s_pages_are_writable() { - use crate::host_memory::host_writable; - let pages = Pages::new(3, 0); - let (at, page) = (pages.at as u64, pages.page as u64); - assert_eq!(host_writable(at, at + 3 * page), Some(true)); - assert_eq!(host_writable(at + 5, at + 6), Some(true)); - pages.read_only(1); - assert_eq!(host_writable(at, at + page), Some(true)); - assert_eq!(host_writable(at, at + 3 * page), Some(false)); - assert_eq!(host_writable(at + page + 9, at + page + 10), Some(false)); - assert_eq!(host_writable(at + 2 * page, at + 3 * page), Some(true)); - drop(pages); - assert_eq!(host_writable(at, at + page), Some(false)); -} - -/// The write back of a first move's kept bytes (`KeptBytes::write_back`, through `put_back`) -/// stores only what the move changed. Over read-only pages it changed nothing on, it stores -/// nothing, so it cannot fault: the reims-vgpu crash (`SIGBUS` on MoltenVK, a texture over guest -/// pages the host maps read-only) stored every byte. Changed bytes on writable pages are put back; -/// changed bytes on a read-only page stay as they are and are counted, which the caller announces -/// (`Degradation::UnrestoredFirstMoveBytes`, a site no lane can meet: no driver's move is made to -/// change bytes on purpose). -#[cfg(any(target_os = "linux", target_vendor = "apple"))] -#[test] -fn the_write_back_stores_only_what_the_move_changed_and_only_where_the_host_may_write() { - use crate::texture::first_move::{put_back, Restored}; - // Unchanged, read-only: nothing stored, no fault. - let pages = Pages::new(2, 0x3c); - let kept = pages.bytes(); - pages.read_only(0); - pages.read_only(1); - // SAFETY: the mapping's bytes, readable; nothing else writes them. - let restored = unsafe { put_back(pages.at, &kept) }; - assert_eq!(restored, Restored::default()); - assert_eq!(pages.bytes(), kept); - // Changed on writable pages: every changed byte put back, and only those counted. - let pages = Pages::new(2, 0x3c); - let kept = pages.bytes(); - for at in [0, 1, 70, pages.page + 3] { - pages.write(at, 0xa5); - } - // SAFETY: as above. - let restored = unsafe { put_back(pages.at, &kept) }; - assert_eq!( - restored, - Restored { - stored: 4, - unwritable: 0 - } - ); - assert_eq!(pages.bytes(), kept); - // Changed on both pages, the second then made read-only: the first's put back, the second's - // left and counted. - let pages = Pages::new(2, 0x3c); - let kept = pages.bytes(); - for at in [5, pages.page + 7, pages.page + 8] { - pages.write(at, 0xa5); - } - pages.read_only(1); - // SAFETY: as above. - let restored = unsafe { put_back(pages.at, &kept) }; - assert_eq!( - restored, - Restored { - stored: 1, - unwritable: 2 - } - ); - let now = pages.bytes(); - assert_eq!(now[5], 0x3c); - assert_eq!(&now[pages.page + 7..pages.page + 9], &[0xa5, 0xa5]); -} diff --git a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs index 3352ee8c2..30cef2ebe 100644 --- a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs @@ -4,17 +4,15 @@ use super::super::image_plan::plan_image; use super::super::linear_plan::{ - aliases, check_linear_limits, holding, linear_alignment, linear_lack, only_reads, - plan_buffer_texture, BufferFacts, BufferLayout, BufferRefusal, BufferTexture, - BufferTextureCall, BufferTextureProblem, Holds, LinearImage, LinearLack, Placed, - LINEAR_ALIGNMENT, + aliases, check_linear_limits, holding, linear_alignment, linear_lack, plan_buffer_texture, + BufferFacts, BufferLayout, BufferRefusal, BufferTexture, BufferTextureCall, + BufferTextureProblem, LinearImage, LinearLack, Placed, LINEAR_ALIGNMENT, }; use super::super::texture_descriptor::{effective_usage, no_texture_alone, TextureDescriptor}; use super::super::values::StorageMode; use super::image_plan::{committed, facts}; use super::texture_descriptor::APPLE; use crate::MetalLevel; -use metal2vulkan::device::PaddedReadsPolicy; use metal2vulkan::metal::format::direct_format; use metal2vulkan::metal::PixelFormat as P; use metal2vulkan::metal::TextureType; @@ -711,11 +709,10 @@ fn a_linear_image_aliases_only_metals_layout() { row_pitch: 80, array_pitch: 320, }; - assert!(aliases(&single, Holds::Texels, 4096 + 256, 320, &image)); + assert!(aliases(&single, 4096 + 256, 320, &image)); // The binding off the image's alignment (RADV's 256 at a 16-byte offset). assert!(!aliases( &single, - Holds::Texels, 4096 + 272, 320, &LinearImage { @@ -726,7 +723,6 @@ fn a_linear_image_aliases_only_metals_layout() { // The driver's own pitch where another was asked for (NVIDIA's explicit layouts). assert!(!aliases( &single, - Holds::Texels, 4096, 320, &LinearImage { @@ -737,7 +733,6 @@ fn a_linear_image_aliases_only_metals_layout() { // Texels not at the binding, or memory past the buffer's. assert!(!aliases( &single, - Holds::Texels, 4096, 320, &LinearImage { @@ -745,11 +740,10 @@ fn a_linear_image_aliases_only_metals_layout() { ..image } )); - assert!(!aliases(&single, Holds::Texels, 4096, 319, &image)); + assert!(!aliases(&single, 4096, 319, &image)); // Memory past the subresource, within the buffer's: no write through the image reaches it. assert!(aliases( &single, - Holds::Texels, 4096, 4096, &LinearImage { @@ -759,10 +753,9 @@ fn a_linear_image_aliases_only_metals_layout() { )); // A subresource past the texels (lavapipe's rows rounded up to 4, of a texture of 3). let three = BufferLayout { rows: 3, ..single }; - assert!(!aliases(&three, Holds::Texels, 4096, 320, &image)); + assert!(!aliases(&three, 4096, 320, &image)); assert!(aliases( &three, - Holds::Texels, 4096, 320, &LinearImage { @@ -775,45 +768,24 @@ fn a_linear_image_aliases_only_metals_layout() { row_bytes: 68, ..single }; - assert!(!aliases(&padded, Holds::Texels, 4096, 320, &image)); - let renders = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - let alias = PaddedReadsPolicy::Alias; - assert!(holding(&padded, renders, alias).is_err()); - assert_eq!(holding(&single, renders, alias), Ok(Holds::Texels)); - // A texture that only reads may hold the bytes between its rows, its last row's to its pitch - // among them, but none past them. - assert!(aliases(&padded, Holds::Padding, 4096, 320, &image)); - assert!(!aliases( - &padded, - Holds::Padding, - 4096, - 400, - &LinearImage { - size: 400, - subresource: 400, - ..image - } - )); - assert!(!aliases( - &padded, - Holds::Padding, - 4096, - 320, - &LinearImage { - row_pitch: 96, - ..image - } - )); + assert!(!aliases(&padded, 4096, 320, &image)); + // Whatever its usage: a texture that only reads takes a first move over them too. + for usage in [ + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + TextureUsage::SHADER_READ, + ] { + assert!(holding(&padded, usage).is_err(), "{usage:?}"); + assert_eq!(holding(&single, usage), Ok(()), "{usage:?}"); + } // One row has nothing between rows, but its pitch's padding past the texels. let row = BufferLayout { rows: 1, slice_pitch: 80, ..padded }; - assert_eq!(holding(&row, renders, alias), Ok(Holds::Texels)); + assert_eq!(holding(&row, TextureUsage::SHADER_READ), Ok(())); assert!(!aliases( &row, - Holds::Texels, 4096, 80, &LinearImage { @@ -824,7 +796,6 @@ fn a_linear_image_aliases_only_metals_layout() { )); assert!(aliases( &row, - Holds::Texels, 4096, 80, &LinearImage { @@ -839,10 +810,9 @@ fn a_linear_image_aliases_only_metals_layout() { ..single }; let stacked = LinearImage { size: 960, ..image }; - assert!(aliases(&slices, Holds::Texels, 4096, 960, &stacked)); + assert!(aliases(&slices, 4096, 960, &stacked)); assert!(!aliases( &slices, - Holds::Texels, 4096, 960, &LinearImage { @@ -855,25 +825,14 @@ fn a_linear_image_aliases_only_metals_layout() { slice_pitch: 384, ..slices }; - assert!(holding(&apart, renders, alias).is_err()); - assert_eq!( - holding(&apart, TextureUsage::SHADER_READ, alias), - Ok(Holds::Padding) - ); - assert!(aliases( - &apart, - Holds::Padding, - 4096, - 1088, - &LinearImage { - size: 1088, - array_pitch: 384, - ..image - } - )); + for usage in [ + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + TextureUsage::SHADER_READ, + ] { + assert!(holding(&apart, usage).is_err(), "{usage:?}"); + } assert!(!aliases( &apart, - Holds::Texels, 4096, 1088, &LinearImage { @@ -885,7 +844,6 @@ fn a_linear_image_aliases_only_metals_layout() { // A driver that reports the array's whole bytes as its first subresource's. assert!(!aliases( &slices, - Holds::Texels, 4096, 960, &LinearImage { @@ -896,7 +854,6 @@ fn a_linear_image_aliases_only_metals_layout() { // A single slice ignores the array pitch a driver reports. assert!(aliases( &single, - Holds::Texels, 4096, 320, &LinearImage { @@ -906,12 +863,11 @@ fn a_linear_image_aliases_only_metals_layout() { )); } -/// A texture over padded rows is a shadow for the operations Vulkan lets write the padding: a -/// render target names its image's layout transitions (its first move among them) and a render -/// pass's load and store operations; a texture a shader writes names its layout transitions alone, -/// as one that only reads does under `PaddedReadsPolicy::Shadow`, which says the policy asked it. -/// A texture that only reads, under `PaddedReadsPolicy::Alias`, may hold the bytes between its -/// rows: its usage as Metal reports it decides, `Unknown` a render target's. +/// A texture over padded rows is a shadow, whatever its usage, naming the operations Vulkan lets +/// write the padding: a render target its image's layout transitions (its first move among them) +/// and a render pass's load and store operations; any other (one that only reads, or that a +/// shader writes) its layout transitions alone. Its usage as Metal reports it decides, `Unknown` +/// a render target's. #[test] fn a_padded_texture_s_shadow_names_what_may_write_its_padding() { let padded = BufferLayout { @@ -922,49 +878,32 @@ fn a_padded_texture_s_shadow_names_what_may_write_its_padding() { rows: 4, slices: 1, }; - let (alias, shadow) = (PaddedReadsPolicy::Alias, PaddedReadsPolicy::Shadow); let transitions = "its rows lie 80 bytes apart, 68 bytes of texels each: an image over them \ holds the bytes between them, which Vulkan lets its layout transitions \ read and write, its first move from the layout it is made in among them"; - let reads = holding(&padded, TextureUsage::SHADER_READ, shadow).unwrap_err(); - assert_eq!( - reads, - format!( - "{transitions} (the device's policy asks no image over them for a texture that only \ - reads, `PaddedReadsPolicy::Shadow`)" - ) - ); - assert!(!reads.contains("render pass"), "{reads}"); - let writes = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - for policy in [alias, shadow] { - assert_eq!( - holding(&padded, writes, policy), - Err(transitions.to_owned()) - ); - let renders = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - assert_eq!( - holding(&padded, renders, policy).unwrap_err(), - "its rows lie 80 bytes apart, 68 bytes of texels each: an image over them holds the \ - bytes between them, which Vulkan lets its layout transitions read and write, and a \ - render pass's load and store operations write back" - ); - } + let passes = "its rows lie 80 bytes apart, 68 bytes of texels each: an image over them holds \ + the bytes between them, which Vulkan lets its layout transitions read and write, \ + and a render pass's load and store operations write back"; for usage in [ TextureUsage::SHADER_READ, TextureUsage::SHADER_READ | TextureUsage::PIXEL_FORMAT_VIEW, - ] { - assert!(only_reads(usage), "{usage:?}"); - assert_eq!(holding(&padded, usage, alias), Ok(Holds::Padding)); - } - for usage in [ - TextureUsage::RENDER_TARGET, + TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE, TextureUsage::SHADER_WRITE, TextureUsage::SHADER_ATOMIC, TextureUsage::BLOCK_WRITES_ONLY, + ] { + assert_eq!( + holding(&padded, usage), + Err(transitions.to_owned()), + "{usage:?}" + ); + } + for usage in [ + TextureUsage::RENDER_TARGET, + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, effective_usage(TextureUsage::UNKNOWN), ] { - assert!(!only_reads(usage), "{usage:?}"); - assert!(holding(&padded, usage, alias).is_err(), "{usage:?}"); + assert_eq!(holding(&padded, usage), Err(passes.to_owned()), "{usage:?}"); } } @@ -1265,8 +1204,7 @@ fn a_linear_image_s_limits_name_what_it_lacks() { /// A texture over a buffer that takes no linear image says which need failed: the features the /// format's linear tiling lacks, the format query's refusal with the format, usage and flags, -/// a limit with what it needs and what the device holds, an import that is not importable or -/// dedicated only, a dedicated allocation. +/// a limit with what it needs and what the device holds, an import that is not importable. #[test] fn a_refused_linear_image_names_the_need_that_failed() { use super::super::texture::LinearRefusal; @@ -1287,47 +1225,36 @@ fn a_refused_linear_image_names_the_need_that_failed() { .unwrap(); let usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; let plan = plan_image(&layout, usage, false, &facts).unwrap(); - let describe = |refusal: LinearRefusal, host: bool| refusal.describe(&plan, host); - let lacks = describe( - LinearRefusal::Need(LinearNeed::Features { - format: Format::B8G8R8A8_UNORM, - features: FormatFeatureFlags2::COLOR_ATTACHMENT, - }), - true, - ); + let describe = |refusal: LinearRefusal| refusal.describe(&plan); + let lacks = describe(LinearRefusal::Need(LinearNeed::Features { + format: Format::B8G8R8A8_UNORM, + features: FormatFeatureFlags2::COLOR_ATTACHMENT, + })); assert!( lacks.contains("B8G8R8A8_UNORM") && lacks.contains("COLOR_ATTACHMENT"), "{lacks}" ); - let refused = describe(LinearRefusal::Need(LinearNeed::Image), true); + let refused = describe(LinearRefusal::Need(LinearNeed::Image)); assert!( - refused.contains("B8G8R8A8_UNORM") - && refused.contains("COLOR_ATTACHMENT") - && refused.contains("for host allocations"), + refused.contains("B8G8R8A8_UNORM") && refused.contains("COLOR_ATTACHMENT"), "{refused}" ); - let layers = describe( - LinearRefusal::Need(LinearNeed::ArrayLayers { - required: 2, - available: 1, - }), - true, - ); + let layers = describe(LinearRefusal::Need(LinearNeed::ArrayLayers { + required: 2, + available: 1, + })); assert!( - layers.starts_with("2 array layers, where its linear images for host allocations") + layers.starts_with("2 array layers, where its linear images of") && layers.ends_with("hold 1"), "{layers}" ); - let import = describe( - LinearRefusal::NotImportable(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY), - true, - ); + let import = describe(LinearRefusal::NotImportable( + vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY, + )); assert!( import.contains("importable false, dedicated only true"), "{import}" ); - let dedicated = describe(LinearRefusal::Dedicated, false); - assert!(dedicated.contains("dedicated allocation"), "{dedicated}"); } /// The committed profiles of the devices linear images were measured on. @@ -1520,145 +1447,6 @@ fn iosurface_planes_lie_where_metal_puts_them() { } } -/// A Metal texture over a no-copy buffer's `MTLBuffer` stands for an extended-range texture's -/// image (`metal_texture::integer_twin`) only where it holds the image's bytes: the twin's own -/// Vulkan format is the one the image holds Metal's bytes in, for `BGR10_XR`, `BGRA10_XR` and -/// their sRGB twins; the two-plane formats, whose image holds both planes side by side, and every -/// other format have none. -#[test] -fn an_extended_range_texture_s_metal_twin_holds_its_image_s_bytes() { - use super::super::metal_texture::integer_twin; - use metal2vulkan::metal::format::ExtendedRange; - for pf in [P::BGR10XR, P::BGR10XRSRGB, P::BGRA10XR, P::BGRA10XRSRGB] { - let range = ExtendedRange::of(pf).unwrap(); - let twin = integer_twin(pf).unwrap(); - assert_eq!(direct_format(twin), Some(range.raw_format()), "{pf:?}"); - } - for pf in [ - P::RGB10A82PXR10, - P::RGB10A82PXR10SRGB, - P::RGBA8Unorm, - P::R32Uint, - ] { - assert_eq!(integer_twin(pf), None, "{pf:?}"); - } -} - -/// A Metal texture over a no-copy buffer's `MTLBuffer` stands for a 2D texture of one level and -/// sample, and for a 2D array whose slices lie as Metal's linear call lays them out: each -/// `bytesPerRow` x height, rounded up to 128 bytes, after the one before. An array of another -/// slice stride, and an image of two levels, keep their shadow with the reason the notice names. -#[test] -fn a_metal_texture_stands_for_an_array_at_metal_s_slice_stride() { - use super::super::metal_texture::MetalOver; - let (_, desc, device) = committed().into_iter().next().unwrap(); - let facts = facts(&desc, &device); - let usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; - let plan = |texture_type: TextureType, side: u64, slices: u64, levels: u64| { - let layout = TextureDescriptor { - pixel_format: P::RGBA8Unorm, - texture_type, - width: side, - height: side, - mipmap_level_count: levels, - array_length: slices, - usage, - ..TextureDescriptor::default() - } - .check(APPLE) - .unwrap(); - plan_image(&layout, usage, false, &facts).unwrap() - }; - let array = TextureType::Type2DArray; - // 8x8 rows of 32 bytes: 256-byte slices, already a multiple of 128. - assert!(MetalOver::of(&plan(array, 8, 2, 1), 32, 256).is_ok()); - // 4x4 rows of 16 bytes: 64-byte images, slices 128 bytes apart. - assert!(MetalOver::of(&plan(array, 4, 2, 1), 16, 128).is_ok()); - let elsewhere = "its slices lie otherwise than those of the 2D array Metal's linear call \ - makes over a buffer"; - assert_eq!(MetalOver::of(&plan(array, 4, 2, 1), 16, 64), Err(elsewhere)); - assert_eq!( - MetalOver::of(&plan(array, 8, 2, 1), 32, 384), - Err(elsewhere) - ); - // A 2D texture, and a one-slice array, whatever the slice stride. - assert!(MetalOver::of(&plan(TextureType::Type2D, 8, 1, 1), 32, 0).is_ok()); - assert!(MetalOver::of(&plan(array, 8, 1, 1), 32, 256).is_ok()); - assert_eq!( - MetalOver::of(&plan(TextureType::Type2D, 8, 1, 2), 32, 256), - Err("its image is not 2D of one level and sample, as a Metal texture over a buffer is") - ); -} - -/// No Metal texture over a no-copy buffer's `MTLBuffer` stands for a depth or stencil texture -/// (a planar surface's): Metal makes no linear texture of such a format and aborts the process when -/// asked for one (an M4 under MoltenVK), so the texture keeps its aspect shadow, with the reason -/// the notice names. -#[test] -fn no_metal_texture_stands_for_a_depth_or_stencil_texture() { - use super::super::metal_texture::MetalOver; - let (_, desc, device) = committed().into_iter().next().unwrap(); - let facts = facts(&desc, &device); - let usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; - for (pf, unit) in [ - (P::Depth16Unorm, 2u64), - (P::Depth32Float, 4), - (P::Depth32FloatStencil8, 4), - (P::Stencil8, 1), - (P::X32Stencil8, 1), - ] { - let layout = TextureDescriptor { - pixel_format: pf, - width: 4, - height: 4, - usage, - ..TextureDescriptor::default() - } - .check(APPLE) - .unwrap(); - let plan = plan_image(&layout, usage, false, &facts).unwrap(); - assert_eq!( - MetalOver::of(&plan, (4 * unit).next_multiple_of(16), 0), - Err("Metal makes no linear texture of a depth or stencil format"), - "{pf:?}" - ); - } -} - -/// A Metal texture over a 4:2:2 texture's bytes is of the carrier's own Metal format, -/// `RG8Unorm`, whose Vulkan format the carrier is: Metal makes no linear texture of a 4:2:2 -/// format (it asserts, EV APX2-l2-mvk4), and `RG8Unorm`'s 2-byte texels are the same bytes. -#[test] -fn a_metal_texture_over_four_two_two_texels_is_the_carrier_s() { - use super::super::chroma_pairs::{CARRIER, CARRIER_PIXEL_FORMAT}; - use super::super::metal_texture::MetalOver; - assert_eq!(direct_format(CARRIER_PIXEL_FORMAT), Some(CARRIER)); - let (_, desc, device) = committed().into_iter().next().unwrap(); - let facts = facts(&desc, &device); - let usage = TextureUsage::SHADER_READ; - for pf in [P::GBGR422, P::BGRG422] { - let layout = TextureDescriptor { - pixel_format: pf, - width: 16, - height: 4, - usage, - ..TextureDescriptor::default() - } - .check(APPLE) - .unwrap(); - let plan = plan_image(&layout, usage, false, &facts).unwrap(); - assert_eq!(plan.format, CARRIER, "{pf:?}"); - // One slice: the slice stride is not looked at. - let over = MetalOver::of(&plan, 64, 0).unwrap(); - let named = format!("MTLPixelFormat {} of 16x4", CARRIER_PIXEL_FORMAT.as_raw()); - assert!( - over.describe().starts_with(&named), - "{pf:?}: {}", - over.describe() - ); - } -} - /// The depth and stencil formats Metal makes over a plane of a surface with planes (an M4 under /// macOS 27.0.1, TTG2's format scout), sampled or read and drawn. const PLANAR_DEPTH: [P; 5] = [ diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 67671f717..f19927c88 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -119,7 +119,6 @@ mod pipeline; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod pipeline_wait_order; #[cfg(unix)] -mod pitch_refusals; mod pixel_format_info; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod pointer_residency; diff --git a/crates/metal2vulkan-runtime/src/tests/pitch_refusals.rs b/crates/metal2vulkan-runtime/src/tests/pitch_refusals.rs deleted file mode 100644 index bc9b687e7..000000000 --- a/crates/metal2vulkan-runtime/src/tests/pitch_refusals.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! The kept refusals of `DRM_FORMAT_MOD_LINEAR` images at Metal's row pitch -//! (`texture/pitch_refusals.rs`): which later images a refusal answers, and how many are kept. - -use super::super::image_plan::{plan_image, ImagePlan}; -use super::super::texture::pitch_refusals::{PitchRefusals, PitchedLayout, KEPT}; -use super::super::texture_descriptor::TextureDescriptor; -use super::image_plan::{committed, facts}; -use super::texture_descriptor::APPLE; -use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; - -/// The image plan of a `BGRA8Unorm` texture of `width`x`height`, `layers` slices and `usage` on -/// the first committed profile. -fn plan(width: u64, height: u64, layers: u64, usage: TextureUsage) -> ImagePlan { - let (_, desc, device) = committed().into_iter().next().unwrap(); - let layout = TextureDescriptor { - pixel_format: PixelFormat::BGRA8Unorm, - texture_type: if layers > 1 { - TextureType::Type2DArray - } else { - TextureType::Type2D - }, - width, - height, - array_length: layers, - usage, - ..TextureDescriptor::default() - } - .check(APPLE) - .unwrap(); - plan_image(&layout, usage, false, &facts(&desc, &device)).unwrap() -} - -/// A kept refusal answers the same image at the same row pitch only: another pitch of the same -/// power-of-two class, another extent or another usage is asked again (NVIDIA answers pitches of -/// one class both ways), and an image of several slices is never kept. -#[test] -fn a_refusal_answers_the_same_image_at_the_same_pitch_alone() { - let read = TextureUsage::SHADER_READ; - let tile = plan(1307, 512, 1, read); - let refusals = PitchRefusals::default(); - let refused = PitchedLayout::of(&tile, 5248).unwrap(); - assert!(!refusals.refused(&refused)); - refusals.keep(refused.clone()); - assert!(refusals.refused(&refused)); - assert!(refusals.refused(&PitchedLayout::of(&tile, 5248).unwrap())); - // 5376 = 42 x 128, the class of 5248 = 41 x 128. - assert!(!refusals.refused(&PitchedLayout::of(&tile, 5376).unwrap())); - let taller = plan(1307, 513, 1, read); - assert!(!refusals.refused(&PitchedLayout::of(&taller, 5248).unwrap())); - let rendered = plan(1307, 512, 1, read | TextureUsage::RENDER_TARGET); - assert!(!refusals.refused(&PitchedLayout::of(&rendered, 5248).unwrap())); - assert_eq!(PitchedLayout::of(&plan(1307, 512, 2, read), 5248), None); -} - -/// At most [`KEPT`] refusals are kept: past them a refusal is not, and the driver is asked again. -#[test] -fn at_most_the_bound_of_refusals_is_kept() { - let tile = plan(300, 200, 1, TextureUsage::SHADER_READ); - let refusals = PitchRefusals::default(); - let pitch = |k: usize| 1216 + 16 * k as u64; - for k in 0..KEPT { - refusals.keep(PitchedLayout::of(&tile, pitch(k)).unwrap()); - } - assert!((0..KEPT).all(|k| refusals.refused(&PitchedLayout::of(&tile, pitch(k)).unwrap()))); - let past = PitchedLayout::of(&tile, pitch(KEPT)).unwrap(); - refusals.keep(past.clone()); - assert!(!refusals.refused(&past)); -} diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index b7958ecf1..60a65b0c4 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -27,11 +27,9 @@ //! - **Texture buffers** hold no image: their texels are a buffer's bytes, viewed as a texel //! buffer where a function binds them (`buffer_texture.rs`). A 2D texture or array over a //! buffer holds both: the bytes, which CPU access reads and writes, and an image: a linear -//! image bound to the buffer's memory where the device lays it out as Metal does (its uses -//! are then uses of the buffer's bytes; over a no-copy buffer's pages, made for host -//! allocations, or on a driver that runs on Metal made of a Metal texture over the import's -//! `MTLBuffer`, `metal_texture.rs`), else one the encoders copy them into and back -//! (`shadow.rs`). +//! image bound to the buffer's memory where the device lays it out as Metal does and the memory +//! is the runtime's own (its uses are then uses of the buffer's bytes), else one the encoders +//! copy them into and back (`shadow.rs`), as over a no-copy buffer's host pages always. //! - **Memoryless** textures are transient attachments (`VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT`) //! in lazily allocated memory where the device has it, else in device-local memory, and start //! undefined: Metal keeps no contents for them (a Metal probe on an M4). Metal makes them of @@ -85,11 +83,9 @@ use super::image_plan::{ }; use super::key_hash::KeyMap; use super::linear_plan::{ - aliases, check_linear_limits, holding, linear_lack, BufferLayout, Holds, LinearImage, - LinearLack, + aliases, check_linear_limits, holding, linear_lack, LinearImage, LinearLack, }; use super::memory::{MemoryClass, Placement}; -use super::metal_texture::{self, MetalOver}; use super::mipmap::MipmapChecks; use super::nan_clear; use super::neutral::Neutrals; @@ -121,7 +117,7 @@ use crate::release; use ash::vk; use ash::vk::Handle; use decoded_twin::{Decoded, PassScratch}; -use first_move::{FirstMove, Fresh, Keep, Pattern, Patterned, TexelCopy, PATTERN_BYTES}; +use first_move::{FirstMove, Fresh, Pattern, Patterned, TexelCopy, PATTERN_BYTES}; use heap_tiled::{FreshDepth, FreshPattern}; use metal2vulkan::bind::{AstcDecode, EtcDecode, ImageViewDesc, PvrtcDecode, TextureFacts}; use metal2vulkan::device::{ @@ -137,7 +133,6 @@ use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; use metal2vulkan::vk::{ ComponentMapping, Format, FormatFeatureFlags2, ImageAspectFlags, ImageUsageFlags, ImageViewType, }; -use shared_alias::{AliasForm, AliasKey, SharedAlias}; use stand_in::StandIn; use std::any::Any; use std::collections::{BTreeSet, HashMap}; @@ -159,10 +154,8 @@ pub(super) mod heap_two_planes; pub(crate) mod held_depth; pub(crate) mod host_copy; #[cfg(unix)] -pub(crate) mod pitch_refusals; mod rotation; mod shared; -pub(super) mod shared_alias; pub(super) mod signed_depth; mod staging_copy; pub(super) mod stand_in; @@ -207,11 +200,6 @@ pub(super) struct TextureState { /// per format at most. #[cfg(unix)] pub(super) modifier_features: Mutex>, - /// The layouts the driver refused a `DRM_FORMAT_MOD_LINEAR` image for host allocations at - /// Metal's row pitch (`texture/pitch_refusals.rs`): a texture of a kept layout is not tried at - /// its pitch again. - #[cfg(unix)] - pitch_refusals: pitch_refusals::PitchRefusals, /// The memory types a heap's buffer and its textures' images take, worked out at the first /// heap's (`texture/heap.rs`). pub(super) heap_types: std::sync::OnceLock, @@ -253,8 +241,6 @@ impl TextureState { format_answers: Mutex::new(HashMap::new()), #[cfg(unix)] modifier_features: Mutex::new(HashMap::new()), - #[cfg(unix)] - pitch_refusals: pitch_refusals::PitchRefusals::default(), heap_types: std::sync::OnceLock::new(), storage_forms: storage_form::StorageForms::default(), first_moves: first_move::FirstMoves::default(), @@ -522,9 +508,8 @@ struct Image { /// CPU copies may run there (`texture/host_copy.rs`). host_copies: bool, /// Its `VkImage` has linear tiling, or `DRM_FORMAT_MOD_LINEAR`'s, whose rows lie as a linear - /// image's: a texture over a buffer's memory (`alias_image`, `dma_buf_alias_image`), or a - /// heap's linear image (`texture/heap.rs`). Not a Metal texture over a buffer - /// (`metal_alias_image`), which renders where Metal's textures do. + /// image's: a texture over a buffer's memory (`alias_image`), or a heap's linear image + /// (`texture/heap.rs`). linear: bool, /// It was moved to `GENERAL` and zeroed on the device's staging queue as it was made, so its /// CPU copies may run there (`texture/staging_copy.rs`). @@ -541,8 +526,7 @@ struct DetachedImage { stand_in: Arc, /// The image's own `VkImage`, for an image in memory of its own: a reattach swaps it back, /// and the image's drop destroys it. `None` for one bound to the detached pages, which went - /// with them; a reattach makes it again over the new pages (`Device::rebound_heap_images`, - /// `Device::rebound_alias_images`). + /// with them; a reattach makes it again over the new pages (`Device::rebound_heap_images`). own: Option, } @@ -566,19 +550,9 @@ struct Raw { } /// What keeps an image's `VkImage` beside the image: the dedicated import of dma-buf pages it is -/// bound to (`dma_buf.rs`), freed after it is destroyed; or the shared image that owns it -/// (`texture/shared_alias.rs`), which destroys it once nothing holds it, so that its holders -/// never do. +/// bound to (`dma_buf.rs`), freed after it is destroyed. pub(super) enum RawHold { Import { _pages: ImageImport }, - Shared(Arc), -} - -impl RawHold { - /// Whether `hold` is a shared image's, whose `VkImage` its holders never destroy. - fn is_shared(hold: &Option) -> bool { - matches!(hold, Some(RawHold::Shared(_))) - } } /// The dedicated import of the pages a texture's image over dma-buf pages is bound to @@ -607,36 +581,14 @@ impl Raw { } } - /// The `VkImage` of `alias`, a shared image, which `alias` keeps. - fn of_shared(alias: Arc) -> Raw { - Raw { - image: AtomicU64::new(alias.raw().as_raw()), - import: Mutex::new(Some(RawHold::Shared(alias))), - } - } - /// Whether the `VkImage` now is bound to a dedicated import of its own pages. fn dedicated(&self) -> bool { match &*lock(&self.import) { Some(RawHold::Import { .. }) => true, - Some(RawHold::Shared(alias)) => alias.dedicated(), None => false, } } - /// The shared image whose `VkImage` it holds now, where it holds one. - fn shared(&self) -> Option> { - match &*lock(&self.import) { - Some(RawHold::Shared(alias)) => Some(Arc::clone(alias)), - Some(RawHold::Import { .. }) | None => None, - } - } - - /// Whether the `VkImage` now is a shared image's, which the image never destroys. - fn is_shared(&self) -> bool { - RawHold::is_shared(&lock(&self.import)) - } - /// The `VkImage` now. fn get(&self) -> vk::Image { vk::Image::from_raw(self.image.load(Ordering::Acquire)) @@ -662,8 +614,7 @@ pub(super) struct ImageObjects { /// What becomes of `raw` as this goes. raw_goes: RawGoes, /// What keeps `raw` beside these objects ([`RawHold`]): a dedicated import, freed as this goes, - /// after `raw` is destroyed; or a shared image, which destroys `raw` itself once nothing holds - /// it. + /// after `raw` is destroyed. import: Option, } @@ -684,7 +635,6 @@ impl Drop for ImageObjects { // A stand-in's read image goes with the stand-in, once its last holder lets go (this // one's after the views above). match &self.raw_goes { - RawGoes::Destroyed if RawHold::is_shared(&self.import) => {} RawGoes::Destroyed => { release::object(raw, self.raw); } @@ -709,16 +659,13 @@ pub(super) struct ImageSwap { } /// A linear image for a texture over a buffer's bytes, made and not yet bound -/// ([`Device::linear_image`], [`Device::host_linear_image`], [`Device::host_pitched_image`]): its -/// memory requirements, the layout of its first subresource, and the layout it starts in. +/// ([`Device::linear_image`]): its memory requirements, the layout of its first subresource, and +/// the layout it starts in. struct LinearMade { raw: vk::Image, requirements: vk::MemoryRequirements, report: vk::SubresourceLayout, initial: vk::ImageLayout, - /// It is a `DRM_FORMAT_MOD_LINEAR` image laid out at Metal's pitches - /// ([`Device::host_pitched_image`]), not the driver's linear image. - pitched: bool, } /// Why a texture over a buffer takes no linear image: the need that failed, which the @@ -730,18 +677,11 @@ pub(super) enum LinearRefusal { /// For host allocations: the device imports none for such an image, or only a dedicated /// one (its external memory features). NotImportable(vk::ExternalMemoryFeatureFlags), - /// The device asks a dedicated allocation of the image, which one bound at an offset of a - /// buffer's import is not. - Dedicated, } impl LinearRefusal { - /// The refusal of a linear image of `plan` (`host`: made for host allocations), in words. - pub(super) fn describe(&self, plan: &ImagePlan, host: bool) -> String { - let what = match host { - true => " for host allocations", - false => "", - }; + /// The refusal of a linear image of `plan`, in words. + pub(super) fn describe(&self, plan: &ImagePlan) -> String { let (format, usage) = (plan.format, plan.usage); match self { LinearRefusal::Need(LinearNeed::Features { format, features }) => format!( @@ -750,41 +690,37 @@ impl LinearRefusal { ), LinearRefusal::Need(LinearNeed::Image) => format!( "the device's image format query reports no linear image of {format:?}, usage \ - {usage:?}, flags {:?}{what}", + {usage:?}, flags {:?}", plan.flags ), LinearRefusal::Need(LinearNeed::Extent { required, available, }) => format!( - "an extent of {required} texels, where its linear images{what} of {format:?} \ + "an extent of {required} texels, where its linear images of {format:?} \ hold {available}" ), LinearRefusal::Need(LinearNeed::MipLevels { required, available, }) => format!( - "{required} mip levels, where its linear images{what} of {format:?} hold \ + "{required} mip levels, where its linear images of {format:?} hold \ {available}" ), LinearRefusal::Need(LinearNeed::ArrayLayers { required, available, }) => format!( - "{required} array layers, where its linear images{what} of {format:?} hold \ + "{required} array layers, where its linear images of {format:?} hold \ {available}" ), - LinearRefusal::Need(need) => format!("{need:?} of its linear images{what}"), + LinearRefusal::Need(need) => format!("{need:?} of its linear images"), LinearRefusal::NotImportable(features) => format!( "it imports no host allocation for a linear image of {format:?}, usage \ {usage:?}, but with a dedicated allocation (importable {}, dedicated only {})", features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE), features.contains(vk::ExternalMemoryFeatureFlags::DEDICATED_ONLY) ), - LinearRefusal::Dedicated => format!( - "it asks a dedicated allocation of a linear image of {format:?}{what}, which one \ - bound at an offset of the buffer's import is not" - ), } } } @@ -802,39 +738,6 @@ fn first_color_subresource() -> vk::ImageSubresource { /// (`shadowed-texture`) names. type Aliased = Result, String>; -/// An image aliasing the host pages of a no-copy buffer (or of a no-copy heap, for a texture over -/// one of its buffers), noted in the pages' hold (`buffer.rs`'s `HostCell`) so that a rebind makes -/// it again over the new pages ([`Device::rebound_alias_images`]): the image, and where its texels -/// lie, in bytes from where the pages' bytes start (in their memory, and in the host addresses -/// they lie at). -#[derive(Clone)] -pub(super) struct AliasWatch { - image: Weak, - from_base: u64, - /// The texture's type: a 2D texture or array. - texture_type: TextureType, - /// What the image is made as. - kind: AliasKind, - /// The bytes from `from_base` an image of the kind made again is bound to, its subresources' - /// reach, which its first move from `UNDEFINED` keeps (`texture/first_move.rs`'s `Keep`). - reach: u64, -} - -/// What an aliasing image over host pages is made as ([`AliasWatch`]). -#[derive(Clone)] -pub(super) enum AliasKind { - /// A linear image, its rows (and slices) the texels' pitches apart: over pages imported by - /// their pointer, one made for host allocations and bound in the pages' import - /// ([`Device::alias_image`]); over pages imported as dma-bufs, a `DRM_FORMAT_MOD_LINEAR` image - /// bound to a dedicated import of a dma-buf of its own pages - /// ([`Device::dma_buf_alias_image`]). A rebind makes the kind its new pages take, over the - /// same texels (`layout`, whose offset is in the buffer the texture was made over), holding - /// what the first held beside them (`holds`). - Linear { layout: BufferLayout, holds: Holds }, - /// A Metal texture over the import's `MTLBuffer` (`metal_texture.rs`). - Metal(MetalOver), -} - /// The images a rebind made for the textures over the bytes it gives pages it imported as /// dma-bufs ([`Device::dma_buf_images_again`]), before it settled: each texture's image with its /// new `VkImage`, bound to a dedicated import of its own pages (`dma_buf.rs`). Dropped unused, @@ -853,13 +756,6 @@ impl Remade { } } -impl AliasWatch { - /// Whether the image lives. - pub(super) fn lives(&self) -> bool { - self.image.strong_count() > 0 - } -} - impl ImageObjects { /// `raw`, a new image of `device`'s, with no views yet. fn new(device: &Device, raw: vk::Image) -> ImageObjects { @@ -1113,8 +1009,7 @@ impl Image { fn settle(&self) -> Result<(), Error> { let firsts = &self.device.shared().textures.first_moves; let at: *const Image = self; - let shared = self.raw.shared().and_then(|alias| alias.move_waits()); - if !self.move_waits() && shared.is_none() && !firsts.texels_wait(at.cast()) { + if !self.move_waits() && !firsts.texels_wait(at.cast()) { return Ok(()); } self.submit_copy(|_, _| {}) @@ -1122,13 +1017,12 @@ impl Image { /// Record a host call's copy of its texels with `record`, on an internal submission the call /// waits for, which makes its own waiting move first, one of an image over host pages - /// included (a shared image's, `texture/shared_alias.rs`, too): the call holds its texture, - /// and so the pages, until the submission completed. So the copy finds it in `GENERAL`. + /// included: the call holds its texture, and so the pages, until the submission completed. + /// So the copy finds it in `GENERAL`. fn submit_copy(&self, record: impl FnOnce(&Vk, vk::CommandBuffer)) -> Result<(), Error> { let key = self.identity.key; - let shared = self.raw.shared().and_then(|alias| alias.move_waits()); self.device - .submit_internal_naming(|named| named == key || Some(named) == shared, record) + .submit_internal_naming(|named| named == key, record) } /// Whether `raw` is its `VkImage`: the one it presents, or its own while it presents a @@ -1248,10 +1142,8 @@ impl Drop for Image { // own; the image only where it made it. // An image presenting a stand-in destroys its own `VkImage` where it kept one, and // never the stand-in's. - // A shared image's `VkImage` goes with the shared image, once nothing holds it. let raw = match &*lock(&self.detached) { Some(detached) => detached.own, - None if self.raw.is_shared() => None, None => Some(self.raw.get()), }; // The kept resolve objects go before the views they were made of. @@ -1339,7 +1231,7 @@ pub(super) enum Owner { shareable: bool, purgeable: Mutex, }, - /// The runtime made a linear image (or a Metal texture) in a buffer's memory: the image goes + /// The runtime made a linear image in a buffer's memory: the image goes /// with it, the memory stays the buffer's. The image holds the memory, so it outlives every /// command that reaches the image, a batch that took its first move and holds only the image /// included. It holds the memory alone, never the buffer: the texture objects hold the buffer, @@ -2125,13 +2017,21 @@ impl Device { let wider = undeclared_usage(plan.clone(), layout, usage, false, &facts, |_, wider| { Ok(wider) })?; - // What an image over the texels may hold beside them: the bytes between padded rows too - // where the texture only reads, by the policy (`linear_plan::holding`); else why none may. - let policy = self.compile_device().policy().padded_reads; - let holds = holding(&texels.layout, usage, policy); + // Whether an image may hold the texels: none where their rows (or slices) lie with the + // buffer's bytes between them (`linear_plan::holding`), and else why. + let holds = holding(&texels.layout, usage); // Over bytes detached from their pages (`detach.rs`) no image aliases them: the texture // is their shadow, which presents a stand-in until they lie in pages again. let detached = texels.buffer.detached(); + // Nor over the caller's host pages (a no-copy buffer's, or a no-copy heap's buffer's, + // imported by their pointer or as dma-bufs): an image bound to imported memory starts + // `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), and its first move, a layout + // transition or an acquire from `VK_QUEUE_FAMILY_FOREIGN_EXT`, "may perform read and write + // accesses on all memory bound to the image subresource range", whatever the texture's + // usage. A CPU write to the bytes then could be undone, where Metal keeps every one, and + // Metal's contract leaves no moment the CPU may not write them. The shadow's copies + // address its texels alone, through the buffer. + let host = texels.buffer.caller_memory() == Some(CallerMemory::HostPages); // The plans a linear image aliasing the bytes is tried with, the first the device makes: // with the feedback loop usage a draw takes that reads the texture its own pass renders // through a snapshot (`feedback_candidate`, `texture/attached_reads.rs`), which costs a @@ -2143,6 +2043,8 @@ impl Device { plans.push(&wider); } plans.push(&plan); + // An aliasing image, counted where it took the feedback loop usage. + let alias = |image: Arc, texels: Arc| { let usage = image.plan().usage; if usage.contains(ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT) { self.shared().counts.feedback_loop_alias_image(); @@ -2154,27 +2056,20 @@ impl Device { "the buffer's bytes were detached from their pages (detach_backing) as the texture \ was made" .to_owned() - } else if dma_buf { - // Over dma-buf pages, one image of the two plans at most, its pages' source called - // once (`dma_buf.rs`). - let plans = [&wider, &plan]; - let plans = if wider != plan { - &plans[..] - } else { - &plans[1..] - }; - let over = (&*texels, &holds); - match self.dma_buf_alias_image(plans, layout, descriptor, over, &facts)? { - Ok(image) => return Ok(Storage::Alias { image, texels }), - Err(why) => why, - } + } else if host { + "the buffer's bytes are the caller's host pages, which an image could alias only from \ + UNDEFINED, whose first move Vulkan lets read and write every byte it is bound to, \ + where Metal keeps every CPU write" + .to_owned() } else { let over = (&*texels, &holds); for &wider in &plans[..plans.len() - 1] { + let made = self.alias_image(wider.clone(), descriptor, over, &facts)?; if let Ok(image) = made { return alias(image, texels); } } + match self.alias_image(plan.clone(), descriptor, over, &facts)? { Ok(image) => return alias(image, texels), Err(why) => why, } @@ -2409,30 +2304,26 @@ impl Device { } } - /// The linear image of `plan` aliasing `texels` in their buffer's memory, in the `GENERAL` - /// layout and holding the buffer's bytes, where the device makes one that lies exactly on - /// Metal's layout there (`linear_plan::linear_lack` and `aliases`); `None` where it does - /// not, and for a buffer over the caller's `VkBuffer`, whose memory's handle type an image - /// bound to it would have to be made for. Over a no-copy buffer's host pages (or a no-copy - /// heap's) the image is made for host allocations ([`Device::host_linear_image`]), as Vulkan - /// binds no other image to imported host memory, and noted in the pages' hold, which a rebind - /// makes it again over ([`Device::rebound_alias_images`]); on a device whose imports give - /// their `MTLBuffer`s it is instead made of a Metal texture over the import's `MTLBuffer` - /// ([`Device::metal_alias_image`]), which renders where the driver's linear images do not. - /// Pages the runtime imported as dma-buf memory take [`Device::dma_buf_alias_image`]'s image - /// instead. The image's hazard tracking is the buffer's. `holds`: what the image may hold - /// beside the texels (`linear_plan::holding`), or why no image may hold them. + /// The linear image of `plan` aliasing `texels` in their buffer's memory (the runtime's own), + /// in the `GENERAL` layout and holding the buffer's bytes, where the device makes one that + /// lies exactly on Metal's layout there (`linear_plan::linear_lack` and `aliases`); why not + /// where it does not, and for a buffer over the caller's `VkBuffer`, whose memory's handle type + /// an image bound to it would have to be made for (a texture over the caller's host pages is + /// always a shadow: `storage_over_buffer`). It starts `PREINITIALIZED`, which its move to + /// `GENERAL` keeps. The image's hazard tracking is the buffer's. `holds`: whether an image may + /// hold the texels (`linear_plan::holding`), or why not. fn alias_image( &self, plan: ImagePlan, - layout: &TextureLayout, descriptor: &TextureDescriptor, - (texels, holds): (&Texels, &Result), + (texels, holds): (&Texels, &Result<(), String>), facts: &ImageFacts<'_>, ) -> Result { - let host = match texels.buffer.caller_memory() { - None => false, - Some(CallerMemory::HostPages) => true, + match texels.buffer.caller_memory() { + None => {} + Some(CallerMemory::HostPages) => { + return Err(internal("an aliasing image over the caller's host pages")); + } Some(CallerMemory::VkBuffer) => { return Ok(Err( "the buffer is over the caller's VkBuffer, whose memory backs no \ @@ -2440,56 +2331,28 @@ impl Device { .to_owned(), )) } - }; - if host && self.exports_metal() { - return self.metal_alias_image(plan, layout, descriptor, texels); } - let holds = match holds { - Ok(holds) => *holds, - Err(why) => return Ok(Err(why.clone())), - }; + if let Err(why) = holds { + return Ok(Err(why.clone())); + } let (memory, buffer_offset, type_index) = texels.buffer.memory(); let memory_offset = buffer_offset + texels.layout.offset; - let kind = AliasKind::Linear { - layout: texels.layout, - holds, - }; - // Over host pages, the image of the same plan over the same bytes their import holds - // (`texture/shared_alias.rs`). - let form = AliasForm::Linear(holds); - let key = host.then(|| AliasKey::new(memory_offset, &plan, &texels.layout, form)); - let over = (layout, descriptor, texels); - if let Some(alias) = (key.as_ref()).and_then(|key| self.take_shared_alias(texels, key)) { - let image = self.over_shared_alias(alias, plan, over, (memory_offset, kind)); - return image.map(Ok); - } - let who = if host { - "the buffer is a no-copy buffer, and the device" - } else { - "the device" - }; - let made = if host { - self.host_alias_unbound(&plan, &texels.layout, holds, facts)? - } else if let Some(LinearLack { format, features }) = linear_lack(&plan, facts) { - Err( - LinearRefusal::Need(LinearNeed::Features { format, features }) - .describe(&plan, host), - ) + let made = if let Some(LinearLack { format, features }) = linear_lack(&plan, facts) { + Err(LinearRefusal::Need(LinearNeed::Features { format, features }).describe(&plan)) } else { self.linear_image(&plan)? - .map_err(|refusal| refusal.describe(&plan, host)) + .map_err(|refusal| refusal.describe(&plan)) }; let LinearMade { raw, requirements, report, initial, - pitched, } = match made { Ok(made) => made, Err(why) => { return Ok(Err(format!( - "{who} makes no linear image of the texture: {why}" + "the device makes no linear image of the texture: {why}" ))); } }; @@ -2503,17 +2366,18 @@ impl Device { row_pitch: report.row_pitch, array_pitch: report.array_pitch, }; - let why = if !aliases(&texels.layout, holds, memory_offset, room, &image) { + let why = if !aliases(&texels.layout, memory_offset, room, &image) { Some(format!( - "{who}'s linear image of the texture lays its texels out otherwise than Metal \ - at the texels' offset and row pitch, or holds other bytes than its texels \ + "the device's linear image of the texture lays its texels out otherwise than \ + Metal at the texels' offset and row pitch, or holds other bytes than its texels \ (rows {} bytes apart, a subresource of {} bytes, aligned to {})", report.row_pitch, report.size, requirements.alignment )) } else if requirements.memory_type_bits & (1 << type_index) == 0 { - Some(format!( - "{who}'s linear image of the texture takes no memory of the buffer's type" - )) + Some( + "the device's linear image of the texture takes no memory of the buffer's type" + .to_owned(), + ) } else { None }; @@ -2522,41 +2386,14 @@ impl Device { unsafe { release::object(raw_device, raw) }; return Ok(Err(why)); } - // Over host pages, its move keeps the texels it lies over, as it starts `UNDEFINED` - // (`VUID-VkImageCreateInfo-pNext-01443`; `texture/first_move.rs`'s `Keep`). - let first = match host { - false => None, - true => { - let moved = (raw, plan.format, initial); - let reach = holds.reach(&texels.layout); - match self.shared_first_move(moved, texels, (memory_offset, reach)) { - Ok(first) => Some(first), - Err(error) => { - // SAFETY: the image is live and unbound, and no command uses it. - unsafe { release::object(raw_device, raw) }; - return Err(error); - } - } - } - }; // SAFETY: the image is live and unbound; the memory is the buffer's, which outlives the // texture holding it, in a type the image takes, at an offset `aliases` checked against - // the image's alignment and size. An image bound to imported host memory was made for - // host allocations. + // the image's alignment and size. if let Err(error) = unsafe { raw_device.bind_image_memory(raw, memory, memory_offset) } { // SAFETY: the image is live and unbound, and no command uses it. unsafe { release::object(raw_device, raw) }; return Err(vulkan(error)); } - if pitched { - self.shared().counts.pitched_host_image_made(); - } - // Over host pages, shared by the textures of the same plan over the same bytes. - if let (Some((first, named)), Some(key)) = (first, key) { - let alias = self.new_shared_alias(texels, (raw, None), (key, named), first); - let image = self.over_shared_alias(alias, plan, over, (memory_offset, kind)); - return image.map(Ok); - } let image = Image { device: self.clone(), raw: Raw::new(raw), @@ -2593,304 +2430,6 @@ impl Device { Ok(Ok(image.shared())) } - /// The shared image of `key` over the host pages `texels` lie in, where their import holds - /// one (`texture/shared_alias.rs`): counted as taken. - fn take_shared_alias(&self, texels: &Texels, key: &AliasKey) -> Option> { - let pages = texels.buffer.host_pages()?; - let alias = pages.import().shared_images().find(key)?; - self.shared().counts.shared_alias_taken(); - Some(alias) - } - - /// The shared image `made` (a `VkImage`, and the dedicated import it is bound to where it has - /// one) of `key`, whose move is `first`, which a host call naming `named` makes: held by the - /// import of the host pages `texels` lie in (`texture/shared_alias.rs`). - fn new_shared_alias( - &self, - texels: &Texels, - made: (vk::Image, Option), - (key, named): (AliasKey, ResourceKey), - first: FirstMove, - ) -> Arc { - let alias = SharedAlias::new(self, made, (key, named), first); - if let Some(pages) = texels.buffer.host_pages() { - pages.import().shared_images().hold(&alias); - } - alias - } - - /// The image of a texture of `plan` over `over`'s texels whose `VkImage` is `alias`'s, shared - /// with the other textures of its key (`texture/shared_alias.rs`): the texture's own image - /// otherwise (its views, its hazard identity, the buffer's memory it holds), noted in its - /// pages' hold as `kind` at `memory_offset`, keeping its own texels (`AliasWatch`), so that a - /// rebind makes it an image of its own over the new pages; its pages noted with the shared - /// image, for the submission that takes the image's move to hold (`SharedAlias::taken_over`). - fn over_shared_alias( - &self, - alias: Arc, - plan: ImagePlan, - (layout, descriptor, texels): (&TextureLayout, &TextureDescriptor, &Texels), - (memory_offset, kind): (u64, AliasKind), - ) -> Result, Error> { - let base = texels.buffer.pages_base()?; - let linear = !matches!(kind, AliasKind::Metal(_)); - // A detached buffer's bytes are in no memory: no texture is made over them. - let pages = (texels.buffer.host_pages()) - .ok_or(Error::NotImplemented(RuntimeGap::DetachTextures))?; - alias.taken_over(&pages); - let image = Image { - device: self.clone(), - raw: Raw::of_shared(alias), - owner: Owner::Buffer { - memory: Mutex::new(texels.buffer.memory_hold()), - }, - plan, - options: texels.options(), - allow_gpu_optimized_contents: descriptor.allow_gpu_optimized_contents, - // The buffer's bytes, tracked as the texture is. - identity: Identity { - tracked: texels.tracked(), - ..texels.buffer.identity() - }, - views: Mutex::new(KeyMap::default()), - own_views: Mutex::new(KeyMap::default()), - resolves: KeptResolves::new(), - twin: None, - decoded: None, - form: Default::default(), - kept_outside: AtomicBool::new(false), - signed_depth: AtomicBool::new(false), - detached: Mutex::new(None), - first_move: Mutex::new(None), - host_copies: false, - linear, - staging_copies: false, - objects: ObjectsToken::default(), - }; - let image = image.shared(); - let reach = alias_reach(&kind, texels); - texels.buffer.watch_alias(AliasWatch { - image: Arc::downgrade(&image), - from_base: memory_offset - base, - texture_type: layout.texture_type, - kind, - reach, - }); - Ok(image) - } - - /// The key of the memory `texels`' bytes lie in, which every buffer made over them joins - /// (`HostAliases::of`): their buffer's own where it joined none. - fn memory_key(&self, texels: &Texels) -> ResourceKey { - let own = texels.buffer.identity().key; - (self.shared().aliases.of(own)).map_or(own, |alias| alias.key) - } - - /// The first move of `moved`, a shared image (of a format, from a layout), bound to the host - /// pages `texels` lie in at `memory_offset`, where they start, its subresources reaching - /// `reach` bytes from there (`texture/shared_alias.rs`): noting those pages weakly (the - /// submission that takes it holds the pages of a texture over the image that lives then, - /// `SharedAlias::take`), and keeping those bytes - /// ([`pages_first_move`](Self::pages_first_move)); with the key of the memory they lie in - /// ([`memory_key`](Self::memory_key)), which a host call that makes the move names. - fn shared_first_move( - &self, - moved: (vk::Image, Format, vk::ImageLayout), - texels: &Texels, - (memory_offset, reach): (u64, u64), - ) -> Result<(FirstMove, ResourceKey), Error> { - // A detached buffer's bytes are in no memory: no texture is made over them. - let pages = (texels.buffer.host_pages()) - .ok_or(Error::NotImplemented(RuntimeGap::DetachTextures))?; - let from_base = memory_offset - pages.memory().1; - let held = (&*pages, pages_hold(&pages)); - let first = self.pages_first_move(moved, held, from_base, reach)?; - Ok((first, self.memory_key(texels))) - } - - /// The first move of `moved`, an image (of a format) from a layout, bound to host `pages` at - /// `from_base` from their bytes' start, its subresources reaching `reach` bytes from there: - /// noting `hold` (the pages, which a rebind may swap it out of) weakly while it waits - /// (`texture/first_move.rs`), and, from `UNDEFINED`, keeping those bytes, every one, through - /// the host (`Keep`). - fn pages_first_move( - &self, - (raw, format, initial): (vk::Image, Format, vk::ImageLayout), - (pages, hold): (&HostPages, Option>), - from_base: u64, - reach: u64, - ) -> Result { - let first = FirstMove::new(raw, format, initial, hold); - if initial != vk::ImageLayout::UNDEFINED { - return Ok(first); - } - let at = (pages.host_at(from_base)) - .ok_or_else(|| internal("an image over host pages the host does not reach"))?; - let keep = Keep::new(&self.shared().textures.first_moves, at, reach); - Ok(first.keeping(keep)) - } - - /// Whether the device's host imports give their `MTLBuffer`s (`VK_EXT_metal_objects`): a - /// texture over a no-copy buffer is then a Metal texture over it ([`metal_alias_image`]). - /// - /// [`metal_alias_image`]: Self::metal_alias_image - fn exports_metal(&self) -> bool { - self.shared() - .host_import - .as_ref() - .is_ok_and(|importer| importer.exports_metal()) - } - - /// The image of `plan` aliasing `texels`, over a no-copy buffer's host pages (or a no-copy - /// heap's), made of a Metal texture over the import's `MTLBuffer` at the texels' offset and - /// row pitch (`metal_texture.rs`), in the `GENERAL` layout and holding the buffer's bytes, - /// and noted in the pages' hold, which a rebind makes it again over - /// ([`Device::rebound_alias_images`]); `None` where Metal makes no such texture there: the - /// texture is shadowed. The image's hazard tracking is the buffer's. - fn metal_alias_image( - &self, - plan: ImagePlan, - layout: &TextureLayout, - descriptor: &TextureDescriptor, - texels: &Texels, - ) -> Result { - let refused = |why: String| Ok(Err(format!("the buffer is a no-copy buffer, and {why}"))); - if texels.layout.slices != u64::from(plan.layers) { - return refused("the texels lie in other slices than the image's layers".to_owned()); - } - let over = match MetalOver::of(&plan, texels.layout.row_pitch, texels.layout.slice_pitch) { - Ok(over) => over, - Err(why) => return refused(why.to_owned()), - }; - let (memory, buffer_offset, _) = texels.buffer.memory(); - let memory_offset = buffer_offset + texels.layout.offset; - let place = (layout, descriptor, texels); - let kind = AliasKind::Metal(over); - // The Metal texture of the same plan over the same bytes their import holds - // (`texture/shared_alias.rs`). - let form = AliasForm::Metal(over, layout.texture_type); - let key = AliasKey::new(memory_offset, &plan, &texels.layout, form); - if let Some(alias) = self.take_shared_alias(texels, &key) { - let image = self.over_shared_alias(alias, plan, place, (memory_offset, kind)); - return image.map(Ok); - } - // The Metal texture is the buffer's bytes, whose texels its move from `UNDEFINED` keeps - // (`texture/first_move.rs`'s `Keep`). - let (first, named) = { - let moved = (vk::Image::null(), plan.format, vk::ImageLayout::UNDEFINED); - let reach = texels.layout.end() - texels.layout.offset; - self.shared_first_move(moved, texels, (memory_offset, reach))? - }; - let made = self.metal_image(&plan, &over, layout.texture_type, memory, memory_offset)?; - let raw = match made { - Ok(raw) => raw, - Err(why) => return refused(why), - }; - let first = first.of_image(raw); - let alias = self.new_shared_alias(texels, (raw, None), (key, named), first); - let image = self.over_shared_alias(alias, plan, place, (memory_offset, kind)); - image.map(Ok) - } - - /// The image of the first of `plans` the device makes over `texels`, whose bytes lie in host - /// pages the runtime imported as dma-buf memory (`dma_buf.rs`): a `DRM_FORMAT_MOD_LINEAR` - /// image bound to a dedicated import of a dma-buf of its own pages, which the pages' source - /// makes (called once), its rows the texels' rows; noted in the pages' hold, which a rebind - /// makes it again over ([`Device::rebound_alias_images`]). Its first move acquires it from - /// `VK_QUEUE_FAMILY_FOREIGN_EXT` into `GENERAL`, keeping the bytes. It aliases the buffer's - /// bytes through another import of the same pages, so its hazard tracking is the buffer's (its - /// key), as every image aliasing a buffer's bytes is: a write through the one orders before a - /// read through the other in a command buffer, by the tracker's memory barriers. Where the - /// device makes none, why, the fallback counted (`WorkCounts::dma_buf_image_fallbacks`): the - /// texture takes the way a texture over memory no image aliases takes. `holds`: what the image - /// may hold beside the texels (`linear_plan::holding`), or why no image may hold them. - #[cfg(unix)] - fn dma_buf_alias_image( - &self, - plans: &[&ImagePlan], - layout: &TextureLayout, - descriptor: &TextureDescriptor, - (texels, holds): (&Texels, &Result), - facts: &ImageFacts<'_>, - ) -> Result { - let pages = texels.buffer.host_pages(); - let over = pages - .as_ref() - .and_then(|pages| Some((pages, pages.dma_buf()?))); - let Some((pages, (imports, start, type_index))) = over else { - return Err(internal( - "a texture over dma-buf pages the buffer does not lie in", - )); - }; - // Rows (or slices) with the buffer's bytes between them take no image but that of a - // texture that only reads, by the policy (`linear_plan::holding`): else the pages' source - // is not asked. - let holds = match holds { - Ok(holds) => *holds, - Err(why) => { - self.shared().counts.dma_buf_image_fell_back(); - return Ok(Err(why.clone())); - } - }; - let base = texels.buffer.pages_base()?; - let (_, buffer_offset, _) = texels.buffer.memory(); - let memory_offset = buffer_offset + texels.layout.offset; - let from_base = memory_offset - base; - let over = (layout, descriptor, texels); - let kind = AliasKind::Linear { - layout: texels.layout, - holds, - }; - // The image of the same plan over the same bytes of these pages their import holds - // (`texture/shared_alias.rs`): the source is not asked again. - let key_of = |plan: &ImagePlan| { - AliasKey::new( - start + from_base, - plan, - &texels.layout, - AliasForm::DmaBuf(holds), - ) - }; - let found = (plans.iter()) - .find_map(|&plan| Some((plan, self.take_shared_alias(texels, &key_of(plan))?))); - if let Some((plan, alias)) = found { - let place = (memory_offset, kind); - return self - .over_shared_alias(alias, plan.clone(), over, place) - .map(Ok); - } - let place = crate::dma_buf::DmaBufTexels { - pages: &imports, - type_index, - at: start + from_base, - row_pitch: texels.layout.row_pitch, - slice_pitch: texels.layout.slice_pitch, - alone: Some((texels.layout, holds)), - }; - let made = match self.dma_buf_image(plans, facts, &place)? { - Ok(made) => made, - Err(why) => { - self.shared().counts.dma_buf_image_fell_back(); - return Ok(Err(format!( - "the buffer's host pages are imported as dma-buf memory, and {why}" - ))); - } - }; - let (index, crate::dma_buf::DmaBufImage { raw, import }) = made; - let plan = plans[index]; - // Its acquire keeps the bytes; the submission that takes it holds the pages of a texture - // over it that lives then (`SharedAlias::take`). - let undefined = vk::ImageLayout::UNDEFINED; - let first = FirstMove::new(raw, plan.format, undefined, pages_hold(pages)) - .acquired(self.foreign_acquirer()); - let named = self.memory_key(texels); - let made = (raw, Some(import)); - let alias = self.new_shared_alias(texels, made, (key_of(plan), named), first); - let place = (memory_offset, kind); - self.over_shared_alias(alias, plan.clone(), over, place) - .map(Ok) - } - /// The image of a texture over dma-buf pages (over a buffer, or placed in a heap), `made` of /// `plan` (`dma_buf.rs`), with its `owner`, its options and whether it allows GPU-optimized /// contents, and the `identity` of its bytes: a `DRM_FORMAT_MOD_LINEAR` image, whose rows are a @@ -2939,78 +2478,6 @@ impl Device { image } - /// No host pages are imported as dma-bufs on this system. - #[cfg(not(unix))] - fn dma_buf_alias_image( - &self, - _plans: &[&ImagePlan], - _layout: &TextureLayout, - _descriptor: &TextureDescriptor, - _over: (&Texels, &Result), - _facts: &ImageFacts<'_>, - ) -> Result { - Err(internal("a texture over dma-buf pages on a system of none")) - } - - /// A `VkImage` of `plan` (of Metal's `texture_type`), made of the Metal texture `over` - /// describes over the `MTLBuffer` of `memory`, an import allocated for its export, from - /// `offset`: treated as bound (`VkImportMetalTextureInfoEXT`). Where none is made, why (for - /// the shadow's notice): the device gives no `MTLBuffer`, makes no optimal image of the plan - /// within its limits, or Metal makes no such texture there. - fn metal_image( - &self, - plan: &ImagePlan, - over: &MetalOver, - texture_type: TextureType, - memory: vk::DeviceMemory, - offset: u64, - ) -> Result, Error> { - let shared = self.shared(); - let raw_device = shared.vk(); - let no_buffer = || Ok(Err("the device gives no MTLBuffer of its memory".to_owned())); - let Ok(importer) = shared.host_import.as_ref() else { - return no_buffer(); - }; - // SAFETY: the memory is a live import of this device's, allocated for export of its - // `MTLBuffer` (`Memory::import_host`, the importer exports). - let Some(buffer) = (unsafe { importer.metal_buffer(raw_device, memory) }) else { - return no_buffer(); - }; - let view_formats = plan.ash_view_formats(); - let mut list = vk::ImageFormatListCreateInfo::default(); - let info = plan.create_info(self.shared().sharing(), &view_formats, &mut list); - let limits = self.image_limits(&info, &view_formats)?; - if check_image_limits(plan, texture_type, &limits).is_err() { - return Ok(Err( - "the device makes no image of the texture within its limits".to_owned(), - )); - } - // SAFETY: the buffer is the live `MTLBuffer` of the import, which holds the texels from - // `offset` (the texture lies over the buffer's bytes, inside the import). - let texture = match unsafe { metal_texture::texture_over(buffer, over, offset) } { - Ok(texture) => texture, - Err(why) => { - return Ok(Err(format!( - "Metal makes no texture of {} over its memory's MTLBuffer at offset \ - {offset}: {why}", - over.describe() - ))) - } - }; - let mut import = vk::ImportMetalTextureInfoEXT::default() - .plane(vk::ImageAspectFlags::PLANE_0) - .mtl_texture(texture.id()); - let info = info.push_next(&mut import); - // SAFETY: the device is live and `info` (with its chain) valid and within the device's - // limits for the plan; the Metal texture is of the plan's format, extent and usage. The - // device holds its own reference to the texture, ours going below. - let raw = unsafe { crate::creation::image(raw_device, &info) }?; - drop(texture); - // SAFETY: the image is a live image of this device, which nothing uses yet. - unsafe { importer.name_metal_image(raw_device, raw) }; - Ok(Ok(raw)) - } - /// A linear image of `plan` (of Metal's `texture_type`), unbound, with its memory /// requirements and its first subresource's layout, to start `PREINITIALIZED` (it keeps its /// memory's bytes); why not where the device makes no such image (the format query, or @@ -3043,394 +2510,19 @@ impl Device { requirements, report, initial: vk::ImageLayout::PREINITIALIZED, - pitched: false, })) } - /// A linear image of `plan` (of Metal's `texture_type`) made for host allocations - /// (`VK_EXT_external_memory_host`), unbound, with its memory requirements and its first - /// subresource's layout, starting `UNDEFINED` as Vulkan has such an image made; why not - /// where the device imports no host memory for such an image (`host_image_limits`), makes - /// none within its limits, or asks a dedicated allocation of it, which an image bound at an - /// offset of a buffer's import is not (The refusal named). - fn host_linear_image( - &self, - plan: &ImagePlan, - ) -> Result, Error> { - let raw_device = self.shared().vk(); - let view_formats = plan.ash_view_formats(); - let mut list = vk::ImageFormatListCreateInfo::default(); - let mut external = vk::ExternalMemoryImageCreateInfo::default() - .handle_types(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT); - let info = plan - .create_info(self.shared().sharing(), &view_formats, &mut list) - .tiling(vk::ImageTiling::LINEAR) - .initial_layout(vk::ImageLayout::UNDEFINED) - .push_next(&mut external); - let limits = match self.host_image_limits(&info, &view_formats)? { - Ok(limits) => limits, - Err(refusal) => return Ok(Err(refusal)), - }; - if let Err(need) = check_linear_limits(plan, &limits) { - return Ok(Err(LinearRefusal::Need(need))); - } - // SAFETY: the device is live and `info` (with its chain) valid and within the device's - // limits for an image of host allocations. - let raw = unsafe { crate::creation::image(raw_device, &info) }?; - let mut dedicated = vk::MemoryDedicatedRequirements::default(); - let requirements = { - let mut requirements = vk::MemoryRequirements2::default().push_next(&mut dedicated); - let query = vk::ImageMemoryRequirementsInfo2::default().image(raw); - // SAFETY: `raw` is a live image of this device; the query is core in Vulkan 1.1. - unsafe { raw_device.get_image_memory_requirements2(&query, &mut requirements) }; - requirements.memory_requirements - }; - if dedicated.requires_dedicated_allocation != vk::FALSE { - // SAFETY: the image is live and unbound, and no command uses it. - unsafe { release::object(raw_device, raw) }; - return Ok(Err(LinearRefusal::Dedicated)); - } - // SAFETY: `raw` is a live linear image of this device, and its first subresource has - // the color aspect. - let report = - unsafe { raw_device.get_image_subresource_layout(raw, first_color_subresource()) }; - Ok(Ok(LinearMade { - raw, - requirements, - report, - initial: vk::ImageLayout::UNDEFINED, - pitched: false, - })) - } - - /// The unbound image of `plan` made for host allocations whose texels lie at Metal's `layout` - /// in a no-copy buffer's pages, its rows `layout.row_pitch` apart (and slices - /// `layout.slice_pitch`), holding no byte but what `holds` lets it (`linear_plan::Holds`): the driver's - /// linear image ([`Device::host_linear_image`]) where it lays them out so, its subresource at - /// offset 0; else, where the device enables `VK_EXT_image_drm_format_modifier`, a - /// `DRM_FORMAT_MOD_LINEAR` image whose one plane the runtime lays out at those pitches - /// ([`Device::host_pitched_image`]). Why not, each attempt's refusal named, where the device - /// makes neither. The caller checks the image's alignment, size and memory types against the - /// buffer's. - fn host_alias_unbound( - &self, - plan: &ImagePlan, - layout: &BufferLayout, - holds: Holds, - facts: &ImageFacts<'_>, - ) -> Result, Error> { - let lies = |report: &vk::SubresourceLayout| { - report.offset == 0 - && report.row_pitch == layout.row_pitch - && (layout.slices == 1 || report.array_pitch == layout.slice_pitch) - && holds.fits(layout, report.size, report.array_pitch) - }; - let made = match linear_lack(plan, facts) { - Some(LinearLack { format, features }) => { - Err(LinearRefusal::Need(LinearNeed::Features { - format, - features, - })) - } - None => self.host_linear_image(plan)?, - }; - let linear = match made { - Ok(made) if lies(&made.report) => return Ok(Ok(made)), - Ok(made) => { - // SAFETY: the image is live and unbound, and no command uses it. - unsafe { release::object(self.shared().vk(), made.raw) }; - format!( - "its linear image for host allocations lays rows {} bytes apart (slices {}) \ - from offset {}, a subresource of {} bytes", - made.report.row_pitch, - made.report.array_pitch, - made.report.offset, - made.report.size - ) - } - Err(refusal) => refusal.describe(plan, true), - }; - Ok(self - .host_pitched_image(plan, layout, holds, facts)? - .map_err(|pitched| format!("{linear}; and {pitched}"))) - } - - /// A `DRM_FORMAT_MOD_LINEAR` image of `plan` made for host allocations, unbound, whose one - /// plane lies at offset 0 with rows `texels.row_pitch` apart (and slices `texels.slice_pitch`, - /// for a plan of several layers), holding no byte but what `holds` lets it: a texture over a - /// no-copy buffer's host pages, its rows one after another (or, for a texture that only reads, - /// apart: `linear_plan::Holds::Padding`), where the driver's own linear image lays them out - /// otherwise (further apart, its row pitch rounded up to an alignment of its own). - /// Its memory requirements and its plane's layout as the driver reports - /// them, starting `UNDEFINED` as Vulkan has an image of external memory made. Why not where - /// the device does not enable the extension, makes no such image for host allocations - /// (`Device::modifier_image_checks`), refuses the layout, lays it out otherwise (NVIDIA lays - /// rows closer than its own linear image's at its own) or past the texels - /// (`linear_plan::texels_alone`), or asks a dedicated allocation of it: the runtime asks the - /// driver and takes its answer, never a rule of its own. A layout the driver refused is kept - /// and refused again unasked (`texture/pitch_refusals.rs`). - #[cfg(unix)] - fn host_pitched_image( - &self, - plan: &ImagePlan, - texels: &BufferLayout, - holds: Holds, - facts: &ImageFacts<'_>, - ) -> Result, Error> { - use crate::dma_buf::{memory_plane_0, ModifierMemory, DRM_FORMAT_MOD_LINEAR}; - let (row_pitch, slice_pitch) = (texels.row_pitch, texels.slice_pitch); - let raw_device = self.shared().vk(); - let enabled = (self.shared().host_import.as_ref()) - .is_ok_and(|importer| importer.makes_dma_buf_images()); - if !enabled { - return Ok(Err( - "the device enables no VK_EXT_image_drm_format_modifier for an image at Metal's \ - row pitch" - .to_owned(), - )); - } - // A layout the driver refused before is refused again, unasked. - let layout = pitch_refusals::PitchedLayout::of(plan, row_pitch); - let refusals = &self.shared().textures.pitch_refusals; - if layout - .as_ref() - .is_some_and(|layout| refusals.refused(layout)) - { - self.shared().counts.pitched_host_image_refusal_recalled(); - return Ok(Err(format!( - "the driver refused this DRM_FORMAT_MOD_LINEAR image for host allocations with \ - rows {row_pitch} bytes apart before" - ))); - } - let host = ModifierMemory::Host; - let view_formats = match self.modifier_image_checks(plan, facts, host)? { - Ok(view_formats) => view_formats, - Err(why) => return Ok(Err(why)), - }; - if let Some(why) = self.explicit_plane_rows(plan) { - return Ok(Err(why)); - } - let array_pitch = if plan.layers > 1 { slice_pitch } else { 0 }; - let planes = [vk::SubresourceLayout { - offset: 0, - size: 0, - row_pitch, - array_pitch, - depth_pitch: 0, - }]; - let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default() - .drm_format_modifier(DRM_FORMAT_MOD_LINEAR) - .plane_layouts(&planes); - // The driver's refusal of the image itself (of its layout, or of an allocation it is not - // dedicated) is kept (`texture/pitch_refusals.rs`), and counted. - let refused_image = |layout: Option| { - self.shared().counts.pitched_host_image_refused(); - if let Some(layout) = layout { - refusals.keep(layout); - } - }; - let raw = match self.drm_linear_image(plan, &view_formats, &mut explicit, host)? { - Ok(raw) => raw, - Err(error) => { - if error == vk::Result::ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT { - refused_image(layout); - } - return Ok(Err(format!( - "the driver refuses a DRM_FORMAT_MOD_LINEAR image for host allocations with \ - rows {row_pitch} bytes apart ({error:?})" - ))); - } - }; - let mut dedicated = vk::MemoryDedicatedRequirements::default(); - let requirements = { - let mut requirements = vk::MemoryRequirements2::default().push_next(&mut dedicated); - let query = vk::ImageMemoryRequirementsInfo2::default().image(raw); - // SAFETY: `raw` is a live image of this device; the query is core in Vulkan 1.1. - unsafe { raw_device.get_image_memory_requirements2(&query, &mut requirements) }; - requirements.memory_requirements - }; - // SAFETY: `raw` is a live image of a DRM format modifier's tiling, whose one memory plane - // is plane 0 (`VUID-vkGetImageSubresourceLayout-tiling-09433`). - let report = unsafe { raw_device.get_image_subresource_layout(raw, memory_plane_0()) }; - let why = if dedicated.requires_dedicated_allocation != vk::FALSE { - refused_image(layout); - Some(format!( - "it asks a dedicated allocation of a DRM_FORMAT_MOD_LINEAR image of {:?} for \ - host allocations, which one bound at an offset of the buffer's import is not", - plan.format - )) - } else if report.offset != 0 - || report.row_pitch != row_pitch - || (plan.layers > 1 && report.array_pitch != array_pitch) - { - refused_image(layout); - Some(format!( - "the driver lays a DRM_FORMAT_MOD_LINEAR plane for host allocations out at offset \ - {}, rows {} and slices {} bytes apart, where the texels lie at offset 0, rows \ - {row_pitch} and slices {array_pitch} apart", - report.offset, report.row_pitch, report.array_pitch - )) - } else if !holds.fits(texels, report.size, report.array_pitch) { - Some(format!( - "the driver's DRM_FORMAT_MOD_LINEAR plane for host allocations takes {} bytes, \ - past the texels' {}", - report.size, - holds.reach(texels) - )) - } else { - None - }; - if let Some(why) = why { - // SAFETY: the image is live and unbound, and no command uses it. - unsafe { release::object(raw_device, raw) }; - return Ok(Err(why)); - } - Ok(Ok(LinearMade { - raw, - requirements, - report, - initial: vk::ImageLayout::UNDEFINED, - pitched: true, - })) - } - - /// No image is laid out by DRM format modifier on this system. - #[cfg(not(unix))] - fn host_pitched_image( - &self, - _plan: &ImagePlan, - _texels: &BufferLayout, - _holds: Holds, - _facts: &ImageFacts<'_>, - ) -> Result, Error> { - Ok(Err( - "the system lays out no image by DRM format modifier".to_owned() - )) - } - - /// The aliasing images of `watches`, over a no-copy buffer's (or a no-copy heap's) host - /// pages, made again over a rebind's new `pages` (`rebind.rs`): each of the same plan, made - /// as the new pages take it, its texels as far from the new pages' first byte as they were - /// from the old's; swapped in once the rebind is made, the device's next submission that - /// names it moving it to `GENERAL`. Over pages imported by their pointer, an image made for - /// host allocations as [`alias_image`](Self::alias_image) made it, bound in their import (or - /// a Metal texture over its `MTLBuffer`, as [`metal_alias_image`](Self::metal_alias_image) - /// made it); over pages imported as dma-bufs (`dma_buf.rs`), the `DRM_FORMAT_MOD_LINEAR` - /// image `remade` holds for it, made before the rebind settled - /// ([`dma_buf_images_again`](Self::dma_buf_images_again)), which its first move acquires - /// from `VK_QUEUE_FAMILY_FOREIGN_EXT`. Refused (`NotImplemented(RebindTextures)`) where the - /// device makes no such image there: the new import's memory type is not one the image - /// takes, the image's alignment misses its place, `remade` holds none for it, or a Metal - /// texture's pages are imported as dma-bufs. - pub(super) fn rebound_alias_images( - &self, - watches: &[AliasWatch], - pages: &Arc, - mut remade: Remade, - ) -> Result, Error> { - let dma_buf = pages.over_dma_buf(); - let (memory, base) = pages.memory(); - let type_index = pages.type_index(); - let raw_device = self.shared().vk(); - let facts = self - .shared() - .textures - .facts(self.compile_device().profile()); - let mut swaps: Vec = Vec::new(); - for watch in watches { - let Some(image) = watch.image.upgrade() else { - continue; - }; - let at = base + watch.from_base; - if dma_buf { - let objects = match &watch.kind { - AliasKind::Linear { .. } => remade.take(&image), - AliasKind::Metal(_) => None, - }; - let Some(objects) = objects else { - return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); - }; - let family = self.foreign_acquirer(); - // Dropped on a later failure, the images made so far go. - swaps.push(ImageSwap::acquired(image, objects, pages, family)); - continue; - } - let (layout, holds) = match &watch.kind { - AliasKind::Linear { layout, holds } => (*layout, *holds), - AliasKind::Metal(over) => { - let made = - self.metal_image(image.plan(), over, watch.texture_type, memory, at)?; - let Ok(raw) = made else { - return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); - }; - let objects = ImageObjects::new(self, raw); - let moved = (raw, image.plan().format, vk::ImageLayout::UNDEFINED); - let held = (&**pages, pages_hold(pages)); - let at = watch.from_base; - let first = self.pages_first_move(moved, held, at, watch.reach)?; - // Dropped on a later failure, the images made so far go. - swaps.push(ImageSwap::new(Arc::clone(&image), objects, first, pages)); - continue; - } - }; - // Its rows (and slices) lie as the old image's did: the texture's, in the driver's - // linear image where it lays them out so, else in a `DRM_FORMAT_MOD_LINEAR` image - // at those pitches; either holding no byte but what the old image held. - let made = self.host_alias_unbound(image.plan(), &layout, holds, &facts)?; - let Ok(LinearMade { - raw, - requirements, - initial, - pitched, - .. - }) = made - else { - return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); - }; - if requirements.memory_type_bits & (1 << type_index) == 0 - || !at.is_multiple_of(requirements.alignment.max(1)) - { - // SAFETY: the image is live and unbound, and no command uses it. - unsafe { release::object(raw_device, raw) }; - return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); - } - // SAFETY: the image is live and unbound; the memory is the new pages', in a type the - // image takes, at an offset that meets its alignment, where its texels lie as they - // lay in the old pages (the rebind keeps the bytes' offset in their page). - if let Err(error) = unsafe { raw_device.bind_image_memory(raw, memory, at) } { - // SAFETY: the image is live and unbound, and no command uses it. - unsafe { release::object(raw_device, raw) }; - return Err(vulkan(error)); - } - if pitched { - self.shared().counts.pitched_host_image_made(); - } - let objects = ImageObjects::new(self, raw); - let moved = (raw, image.plan().format, initial); - let held = (&**pages, pages_hold(pages)); - let at = watch.from_base; - let first = self.pages_first_move(moved, held, at, watch.reach)?; - // Dropped on a later failure, the images made so far go. - swaps.push(ImageSwap::new(Arc::clone(&image), objects, first, pages)); - } - Ok(swaps) - } - - /// The images of the textures over a no-copy buffer's (or a no-copy heap's) bytes, made for a - /// rebind's new pages, which it imported as dma-bufs (`placement`), the bytes at `pointer`: - /// for each linear one `watches` note, a `DRM_FORMAT_MOD_LINEAR` image of its plan over the - /// one dma-buf the pages' source makes of its own pages ([`Device::dma_buf_image`]), its - /// texels as far from the new bytes' first as they were from the old's, and its rows as far - /// apart; and for each of `heap`'s textures bound to its bytes, one in the driver's layout at - /// its offset (`texture/heap.rs`). Made before the rebind settles, with no lock of the - /// runtime's held: the source is called once for each. Nothing for pages imported by their - /// pointer. Refused (`NotImplemented(RebindTextures)`), what was made released, where the - /// device makes no such image of one (`dma_buf_image`'s reasons). + /// The images of `heap`'s textures bound to its bytes (a no-copy heap's), made for a rebind's + /// new pages, which it imported as dma-bufs (`placement`), the bytes at `pointer`: for each, + /// one in the driver's layout at its offset (`texture/heap.rs`). Made before the rebind + /// settles, with no lock of the runtime's held: the source is called once for each. Nothing + /// for pages imported by their pointer. Refused (`NotImplemented(RebindTextures)`), what was + /// made released, where the device makes no such image of one (`dma_buf_image`'s reasons). #[cfg(unix)] pub(super) fn dma_buf_images_again( &self, - watches: &[AliasWatch], - heap: Option<&Heap>, + heap: &Heap, placement: &Placement, pointer: NonNull, ) -> Result { @@ -3438,36 +2530,8 @@ impl Device { let Some(imports) = placement.dma_buf_pages() else { return Ok(remade); }; - if let Some(heap) = heap { - let type_index = placement.type_index(); - self.dma_buf_heap_images_again(heap, imports, type_index, pointer, &mut remade)?; - } - let facts = self - .shared() - .textures - .facts(self.compile_device().profile()); - for watch in watches { - let Some(image) = watch.image.upgrade() else { - continue; - }; - // A Metal texture's rebind to dma-buf pages is refused as the swaps are made. - let AliasKind::Linear { layout, holds } = watch.kind else { - continue; - }; - let texels = crate::dma_buf::DmaBufTexels { - pages: imports, - type_index: placement.type_index(), - at: pointer.as_ptr() as u64 + watch.from_base, - row_pitch: layout.row_pitch, - slice_pitch: layout.slice_pitch, - alone: Some((layout, holds)), - }; - let Ok((_, made)) = self.dma_buf_image(&[image.plan()], &facts, &texels)? else { - return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); - }; - let objects = ImageObjects::imported(self, made.raw, made.import); - remade.0.push((image, objects)); - } + let type_index = placement.type_index(); + self.dma_buf_heap_images_again(heap, imports, type_index, pointer, &mut remade)?; Ok(remade) } @@ -3475,8 +2539,7 @@ impl Device { #[cfg(not(unix))] pub(super) fn dma_buf_images_again( &self, - _watches: &[AliasWatch], - _heap: Option<&Heap>, + _heap: &Heap, _placement: &Placement, _pointer: NonNull, ) -> Result { @@ -4541,16 +3604,6 @@ fn pages_hold(pages: &Arc) -> Option> { Some(pages) } -/// The bytes from an aliasing image's first texel its subresources reach, by its kind -/// (`AliasWatch::reach`): a linear image's as what it holds beside the texels lets them, a Metal -/// texture's to its last texel. -fn alias_reach(kind: &AliasKind, texels: &Texels) -> u64 { - match kind { - AliasKind::Linear { layout, holds } => holds.reach(layout), - AliasKind::Metal(_) => texels.layout.end() - texels.layout.offset, - } -} - /// The barrier ordering a copy of the internal submission after every earlier access of the /// device's memory, and every later access after the copy. pub(super) fn transfer_barrier( @@ -4846,9 +3899,9 @@ impl Texture { matches!(self.0.storage, Storage::Alias { .. }) && self.linear_image().unwrap_or(false) } - /// Whether the texture's image lies over its buffer's bytes now: an aliasing image, linear - /// or a Metal texture over the import's `MTLBuffer` (`AliasKind`), not presenting a stand-in - /// while its bytes are detached (`detach.rs`), so a pass that renders it writes those bytes. + /// Whether the texture's image lies over its buffer's bytes now: an aliasing image, not + /// presenting a stand-in while its bytes are detached (`detach.rs`), so a pass that renders it + /// writes those bytes. pub(super) fn image_over_buffer(&self) -> bool { match &self.0.storage { Storage::Alias { image, .. } => lock(&image.detached).is_none(), diff --git a/crates/metal2vulkan-runtime/src/texture/first_move.rs b/crates/metal2vulkan-runtime/src/texture/first_move.rs index eb90bab5b..213aef8db 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -9,7 +9,7 @@ //! and 18 µs with its command buffer still scheduled (the consumer's PS ask, an M3 Max). An //! encoder that made a scratch buffer for its own commands waited so too. //! - **What waits.** Every image the runtime makes in memory it binds (its own, a buffer's, a -//! heap's, host pages', a Metal texture over an `MTLBuffer`), and a stand-in's images +//! heap's, a no-copy heap's host pages'), and a stand-in's images //! (`stand_in.rs`), starts in `UNDEFINED` (`PREINITIALIZED` for a linear image whose bytes it //! keeps) and notes its move ([`FirstMove`]): for one that reads zero (a new `Shared` or //! `Managed` texture, a stand-in) with the copies of the device's zeros ([`Zeros`]) that write @@ -55,32 +55,12 @@ //! submission (staged bytes' copies into buffers, a `Managed` buffer's uploads, and staged texel //! copies), the call that staged the last makes a submission for them and waits //! (`FirstMoves::register_bytes` and `register_texels` answer when). -//! - **The bytes kept.** An image bound to a no-copy buffer's host pages (the driver's linear -//! image for host allocations, a `DRM_FORMAT_MOD_LINEAR` image at Metal's row pitch, and on -//! MoltenVK a Metal texture over the import's `MTLBuffer`) starts in `UNDEFINED`, as Vulkan -//! makes an image for host allocations (`VUID-VkImageCreateInfo-pNext-01443`), and a move from -//! `UNDEFINED` "will cause the contents of the image's memory to be undefined": "Image layout -//! transitions may perform read and write accesses on all memory bound to the image -//! subresource range". The host keeps those bytes across it ([`Keep`], -//! `device/submit.rs`'s `keep_on_host`), before a submission takes the rest of the first work: -//! once every submission made before on each `VkQueue` completed (each batch's last barrier -//! makes its writes available to the host), it reads the bytes the image's subresources reach -//! through the host pointer, submits the moves alone (and a barrier that makes their writes -//! available to the host) and waits for them, then writes back the bytes the moves changed -//! ([`KeptBytes::write_back`]), so the memory holds every byte read: a linear image's -//! subresource in `GENERAL` is host-accessible, and the host's writes are what it then holds. A -//! move that changed nothing has nothing stored, so pages the process cannot write stay -//! untouched (Metal makes a buffer over read-only pages, and MoltenVK imports them in place; -//! Linux refuses them at the import, `host_memory.rs`). Changed bytes on pages the process maps -//! without write permission when the write back comes (a program's later `mprotect`) keep what -//! the move wrote, announced once (`Degradation::UnrestoredFirstMoveBytes`). No GPU command -//! writes the bytes, so none writes back a cache line that also holds another's bytes: ANV did, -//! the texels' copies back undoing the CPU's writes of the bytes beside them in their 64-byte -//! lines (Mesa 26.2.4, the lane's -//! `a_cpu_write_during_a_texture_s_first_move_stays_outside_its_bytes`). A CPU write to the bytes -//! between their read and their write back is undone: once per image, in the submission that -//! makes its move. Counted: `WorkCounts::first_move_keeps`, `first_move_kept_bytes` and -//! `first_move_restored_bytes`. +//! - **Over host pages.** An image bound to imported host memory starts in `UNDEFINED` +//! (`VUID-VkImageCreateInfo-pNext-01443`), and its move "may perform read and write accesses +//! on all memory bound to the image subresource range": a no-copy heap's texture bound to the +//! heap's bytes (`texture/heap.rs`) takes such a move. A texture over a no-copy buffer's host +//! pages takes no such image: it is a shadow, whose copies address its texels alone +//! (`texture.rs`'s `storage_over_buffer`). //! - **The work.** A barrier from every command before (memory other commands wrote), then the //! buffers' fills with zeros, then their copies of staged bytes after a barrier, then a //! barrier carrying each image's move (after the fills: an image placed in a new heap moves @@ -104,6 +84,7 @@ //! the M3 Max waited up to 13 ms, in 20 of 60 makings: MoltenVK encodes a command buffer's Metal //! commands inside `vkQueueSubmit`, on the calling thread (4.5 to 17 ms for those batches); with //! the hold, no making of 60 took past 0.16 ms. A device whose heap sets take no writes while a +//! `recorder`, before its take), only for the recording of a submission's own barriers and its //! - **Failure.** A submission that fails gives its work back, still to be done. //! - **Out of reach of a submission.** A texture's `VkImage` handed out (`Texture::vk_image`) //! rests in `GENERAL` as its contract says: handing it out does its work first, by an internal @@ -115,7 +96,7 @@ use super::super::error::{internal, vulkan, Error, MemoryKind}; use super::super::exit_guard::{self, Call}; use super::super::host_memory::host_writable; use super::super::image_barrier::{image_barrier, ImageDst}; -use super::super::memory::{Mapped, Memory, MemoryClass, Placement}; +use super::super::memory::{Memory, MemoryClass, Placement}; use super::super::release; use super::super::resource::ResourceKey; use super::super::tracker::Point; @@ -151,119 +132,6 @@ pub(crate) struct FirstMove { /// The queue family the move acquires the image for from `VK_QUEUE_FAMILY_FOREIGN_EXT`, an /// image over dma-buf pages the CPU writes ([`FirstMove::acquired`]). acquire: Option, - /// The bytes the image lies over, kept across the move ([`FirstMove::keeping`]). - keep: Option, -} - -/// The bytes an image bound to host pages is bound to, which its move from `UNDEFINED` may -/// discard, kept across it by the host ([`FirstMove::keeping`]; the module docs): read through -/// the host pointer once every submission before completed, the move submitted alone and waited -/// for, then written back where the move changed them ([`KeptBytes::write_back`]). -pub(crate) struct Keep { - /// The host address of the first byte the image is bound to. - at: Mapped, - /// The bytes from there its subresources may reach: all the move may write. - length: usize, - /// The device's count of keeps alive ([`FirstMoves::keeps_wait`]). - live: Arc, -} - -/// The bytes of each of a submission's keeps, read before their moves ([`Taken::read_kept`]), -/// with where they lie. -pub(crate) struct KeptBytes(Vec<(Mapped, Vec)>); - -impl KeptBytes { - /// Put each keep's bytes back where their moves changed them: once the moves completed, their - /// writes available to the host, before any submission after them, while the pages they lie - /// in are held (with the moves, `Taken::submitted_internally`). Only the bytes that differ - /// from those read are stored ([`changed_runs`]), so the pages end holding every byte read, - /// and a move that changed none stores nothing: the pages may be ones the process cannot - /// write (Metal makes a buffer over read-only pages, and MoltenVK imports them). A run of - /// changed bytes is stored where the process maps its pages writable now - /// (`host_memory::host_writable`), else left as the move left it and counted for the caller - /// to announce ([`Restored::unwritable`]). - pub(crate) fn write_back(self) -> Restored { - let mut restored = Restored::default(); - for (at, kept) in self.0 { - // SAFETY: the bytes lie in host pages the caller holds, mapped and readable for as - // long; the moves that may have written them completed and their writes were made - // available to the host. A CPU write to them meanwhile is the program's (the known gap - // the module docs name). - let one = unsafe { put_back(at.as_ptr(), &kept) }; - restored.stored += one.stored; - restored.unwritable += one.unwritable; - } - restored - } -} - -/// Store `kept` again at `at` where the bytes there now differ from it ([`changed_runs`]), each -/// run where the process maps its pages writable now (`host_memory::host_writable`, asked once -/// for the span of every run, then run by run where that span is not all writable). -/// -/// # Safety -/// -/// The `kept.len()` bytes at `at` are mapped and readable for the call, and nothing writes them -/// meanwhile but the program, whose write is a race as on Metal. -pub(crate) unsafe fn put_back(at: *mut u8, kept: &[u8]) -> Restored { - let runs = { - // SAFETY: the caller's. - let now = unsafe { std::slice::from_raw_parts(at.cast_const(), kept.len()) }; - changed_runs(kept, now) - }; - let mut restored = Restored::default(); - let (Some(first), Some(last)) = (runs.first(), runs.last()) else { - return restored; - }; - let address = |offset: usize| at as u64 + offset as u64; - let all = host_writable(address(first.start), address(last.end)) == Some(true); - for run in runs { - let len = run.len() as u64; - if all || host_writable(address(run.start), address(run.end)) == Some(true) { - // SAFETY: the caller's, and the process maps the run's pages writable. - unsafe { - std::ptr::copy_nonoverlapping( - kept[run.clone()].as_ptr(), - at.add(run.start), - run.len(), - ); - } - restored.stored += len; - } else { - restored.unwritable += len; - } - } - restored -} - -/// What [`KeptBytes::write_back`] put back of the bytes the moves changed. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct Restored { - /// The changed bytes it stored again (`WorkCounts::first_move_restored_bytes`). - pub(crate) stored: u64, - /// The changed bytes on pages the process does not map writable, which keep what the move - /// wrote (`Degradation::UnrestoredFirstMoveBytes`). - pub(crate) unwritable: u64, -} - -/// The ranges of bytes where `now` differs from `kept`, in order, each as long as it runs. -pub(crate) fn changed_runs(kept: &[u8], now: &[u8]) -> Vec> { - /// The bytes compared at once before a byte-by-byte look. - const BLOCK: usize = 64; - let mut runs: Vec> = Vec::new(); - for (block, (kept, now)) in kept.chunks(BLOCK).zip(now.chunks(BLOCK)).enumerate() { - if kept == now { - continue; - } - for (i, _) in (kept.iter().zip(now).enumerate()).filter(|(_, (k, n))| k != n) { - let at = block * BLOCK + i; - match runs.last_mut() { - Some(run) if run.end == at => run.end = at + 1, - _ => runs.push(at..at + 1), - } - } - } - runs } /// How a first move writes Metal's pattern into the first `levels` levels of its image, of @@ -377,16 +245,9 @@ impl FirstMove { holding: None, pattern: None, acquire: None, - keep: None, } } - /// The move, of `image` (made after the move was planned, with what it keeps). - pub(crate) fn of_image(mut self, image: vk::Image) -> FirstMove { - self.image = image; - self - } - /// Whether the image is bound to host pages, which a rebind may swap it out of (the module /// docs). pub(super) fn rebindable(&self) -> bool { @@ -402,29 +263,12 @@ impl FirstMove { Some(self) } - /// The move, holding `pages` from now on, the pages a submission that takes it holds: those - /// of a texture over a shared image that lives (`texture/shared_alias.rs`). - pub(super) fn holding_now(mut self, pages: Arc) -> FirstMove { - self.pages = Some(Arc::downgrade(&pages)); - self.holding = Some(pages); - self - } - /// The move, given back by a submission not made: no longer holding its pages. fn unheld(mut self) -> FirstMove { self.holding = None; self } - /// The move, which also keeps `keep`'s texels, those the image lies over: a move from - /// `UNDEFINED` "will cause the contents of the image's memory to be undefined" (the image - /// layouts' chapter), so the work copies them into its staging buffer before the move and - /// back after it (the module docs). - pub(crate) fn keeping(mut self, keep: Keep) -> FirstMove { - self.keep = Some(keep); - self - } - /// The move, an acquire of the image from `VK_QUEUE_FAMILY_FOREIGN_EXT` for `family` (the /// device's one queue family, or `VK_QUEUE_FAMILY_IGNORED` for an image concurrent among /// several, `sharing.rs`): an image over dma-buf pages (`dma_buf.rs`), made `UNDEFINED` as @@ -748,34 +592,6 @@ enum Zero { Clear, } -impl Keep { - /// The keep of the `length` bytes from the host address `at`, where an image of `moves`'s - /// device is bound to host pages. - pub(crate) fn new(moves: &FirstMoves, at: Mapped, length: u64) -> Keep { - moves.live_keeps.fetch_add(1, AtomicOrdering::AcqRel); - Keep { - at, - length: usize::try_from(length).unwrap_or(usize::MAX), - live: Arc::clone(&moves.live_keeps), - } - } - - /// The bytes as they lie now, and where. - fn read(&self) -> (Mapped, Vec) { - // SAFETY: the bytes lie in host pages the submission that took the move holds, mapped - // for as long; a CPU write to them meanwhile is the program's (the known gap the module - // docs name). - let bytes = unsafe { std::slice::from_raw_parts(self.at.as_ptr(), self.length) }; - (self.at, bytes.to_vec()) - } -} - -impl Drop for Keep { - fn drop(&mut self) { - self.live.fetch_sub(1, AtomicOrdering::AcqRel); - } -} - /// The most bytes host calls' copies stage for the device's next submission before one is made /// for them, waited for (the module docs). const STAGED_BYTES: u64 = 256 << 20; @@ -887,15 +703,8 @@ impl TexelCopy { /// What holds first moves not yet made: an image of the runtime's, or a stand-in. pub(crate) trait Fresh: Send + Sync { - /// Its moves not yet taken, taken now: none where a move may wait for a later submission - /// ([`still_waits`](Fresh::still_waits)). + /// Its moves not yet taken, taken now. fn take(&self) -> Vec; - /// Whether a move of it waits still, which [`take`](Fresh::take) gave no submission: one of a - /// shared image no texture over which lives (`texture/shared_alias.rs`). A later submission - /// takes it. - fn still_waits(&self) -> bool { - false - } /// `moves`, which [`take`](Fresh::take) gave and no submission made, given back. fn give_back(&self, moves: Vec); /// The key the commands that use it name, where a move of it waiting is of an image bound to @@ -935,7 +744,7 @@ impl Held { /// What keeps the resource, or its memory (and a fill's staging buffer). fn keeper(self) -> Box { match self { - // The moves keep the pages their images are bound to, and their keeps' staging. + // The moves keep the pages their images are bound to. Held::Moves(fresh, moves) => Box::new((fresh, moves)), Held::Fill(_, memory, fill) => match fill.staging { Some(staging) => Box::new((memory, staging)), @@ -981,8 +790,6 @@ pub(crate) struct FirstMoves { /// (`texture/decoded_twin.rs`, `PassScratch::Device`), and its bytes: made at the first such /// decode, kept with the device. decode_scratch: Mutex>, - /// The keeps alive ([`Keep`]): while none is, no submission looks for one to make. - live_keeps: Arc, } /// The side of each of the device's multisampled scratch images ([`FirstMoves::scratch`]): its @@ -1072,65 +879,6 @@ impl FirstMoves { past_bound(&waiting) } - /// Whether a move that keeps the bytes its image is bound to may wait ([`Keep`]). - pub(crate) fn keeps_wait(&self) -> bool { - self.live_keeps.load(AtomicOrdering::Acquire) > 0 - } - - /// Take the moves that keep the bytes their images are bound to ([`Keep`]), which the host - /// makes before a submission takes the rest (`device/submit.rs`'s `keep_on_host`): of every - /// resource but those bound to host pages whose key `named` does not name, as - /// [`take`](Self::take). Every other move goes back to its resource, which stays registered. - pub(crate) fn take_keeps(&self, named: impl Fn(ResourceKey) -> bool) -> Taken<'_> { - let order = lock(&self.order); - let mut held = Vec::new(); - let mut left: Vec> = Vec::new(); - { - let mut waiting = lock(&self.waiting); - let mut kept = Vec::new(); - for entry in waiting.drain(..) { - let Waiting::Moves(weak) = entry else { - kept.push(entry); - continue; - }; - let Some(fresh) = weak.upgrade() else { - continue; - }; - if fresh.rebindable().is_some_and(|key| !named(key)) { - kept.push(Waiting::Moves(weak)); - left.push(Box::new(fresh)); - continue; - } - let (keeping, others): (Vec, Vec) = fresh - .take() - .into_iter() - .partition(|first| first.keep.is_some()); - let rest = !others.is_empty(); - if rest { - fresh.give_back(others); - } - let keeping: Vec = - keeping.into_iter().filter_map(FirstMove::held).collect(); - // A resource whose move waits on (`Fresh::still_waits`) stays registered. - if rest || fresh.still_waits() { - kept.push(Waiting::Moves(weak.clone())); - } - if keeping.is_empty() { - left.push(Box::new(fresh)); - } else { - held.push(Held::Moves(fresh, keeping)); - } - } - waiting.extend(kept); - } - drop(left); - Taken { - moves: self, - held, - _order: order, - } - } - /// Take the work a submission does: all of it, but the moves of images bound to host pages /// whose key `named` does not name (an internal submission's; a batch names every key, the /// module docs). What goes is dropped once the lock is free. @@ -1168,9 +916,6 @@ impl FirstMoves { .filter_map(FirstMove::held) .collect(); if moves.is_empty() { - if fresh.still_waits() { - kept.push(Waiting::Moves(weak)); - } left.push(Box::new(fresh)); } else { held.push(Held::Moves(fresh, moves)); @@ -1536,35 +1281,6 @@ impl Taken<'_> { (self.held.iter()).any(|held| matches!(held, Held::Moves(..) | Held::Fill(..))) } - /// Whether one of its moves keeps the bytes its image is bound to ([`Keep`]). - pub(crate) fn has_keeps(&self) -> bool { - self.keeps().next().is_some() - } - - /// How many of its moves keep the bytes their images are bound to, and how many bytes in all. - pub(crate) fn kept(&self) -> (usize, u64) { - (self.keeps()).fold((0, 0), |(count, bytes), keep| { - (count + 1, bytes + keep.length as u64) - }) - } - - /// The bytes each of its keeps keeps, read now: once every submission before completed, and - /// before the moves are submitted ([`Keep`]). - pub(crate) fn read_kept(&self) -> KeptBytes { - KeptBytes(self.keeps().map(Keep::read).collect()) - } - - /// The keeps of its moves. - fn keeps(&self) -> impl Iterator { - self.held.iter().flat_map(|held| { - let moves: &[FirstMove] = match held { - Held::Moves(_, moves) => moves, - Held::Fill(..) | Held::Texels(..) => &[], - }; - moves.iter().filter_map(|first| first.keep.as_ref()) - }) - } - /// Whether it took host calls' staged copies ([`record_staged`](Self::record_staged)'s). pub(crate) fn has_staged(&self) -> bool { (self.held.iter()).any(|held| matches!(held, Held::Texels(..))) @@ -1656,7 +1372,6 @@ impl Taken<'_> { Held::Fill(..) | Held::Texels(..) => &[], }) }; - let keeps = self.has_keeps(); if !fills.is_empty() { // SAFETY: the caller's contract. unsafe { @@ -1712,28 +1427,6 @@ impl Taken<'_> { } exit_guard::called(Call::CmdPipelineBarrier); } - // The moves whose bytes the host keeps: their writes, which a layout transition makes - // available, made available to the host too, before it writes the bytes back ([`Keep`]). - if keeps { - let host = [vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::MEMORY_WRITE) - .dst_access_mask(vk::AccessFlags::HOST_READ | vk::AccessFlags::HOST_WRITE)]; - // SAFETY: the caller's contract. - unsafe { - let flags = vk::DependencyFlags::empty(); - let host_stage = vk::PipelineStageFlags::HOST; - device.cmd_pipeline_barrier( - command_buffer, - all, - host_stage, - flags, - &host, - &[], - &[], - ); - } - exit_guard::called(Call::CmdPipelineBarrier); - } let mut copied = !fills.is_empty(); for first in moves().filter(|first| first.writes()) { // SAFETY: as above; the image is in `GENERAL` now and has `TRANSFER_DST` usage where @@ -2094,58 +1787,6 @@ mod tests { drop(held); } - /// A resource whose move a submission takes only once it is `ready`, as a shared image's - /// while a texture over it lives (`texture/shared_alias.rs`). - struct Waiter { - moves: Mutex>, - ready: std::sync::atomic::AtomicBool, - } - - impl Fresh for Waiter { - fn take(&self) -> Vec { - match self.ready.load(std::sync::atomic::Ordering::Relaxed) { - true => lock(&self.moves).drain(..).collect(), - false => Vec::new(), - } - } - - fn still_waits(&self) -> bool { - !lock(&self.moves).is_empty() - } - - fn give_back(&self, moves: Vec) { - lock(&self.moves).extend(moves); - } - - fn rebindable(&self) -> Option { - None - } - } - - /// A move a submission found waiting still stays registered, and a later submission takes it. - #[test] - fn a_move_that_waits_still_stays_for_a_later_submission() { - let moves = FirstMoves::default(); - let waiter = Arc::new(Waiter { - moves: Mutex::new(vec![first(1, false)]), - ready: std::sync::atomic::AtomicBool::new(false), - }); - let weak: Weak = Arc::downgrade(&waiter); - moves.register(weak); - let taken = moves.take(|_| false); - assert!(taken.held.is_empty(), "nothing is taken while it waits"); - drop(taken.submitted(None)); - assert_eq!(lock(&moves.waiting).len(), 1, "it stays registered"); - waiter - .ready - .store(true, std::sync::atomic::Ordering::Relaxed); - let taken = moves.take(|_| false); - assert_eq!(taken.held.len(), 1, "a later submission takes it"); - drop(taken.submitted(None)); - assert!(lock(&moves.waiting).is_empty()); - assert!(lock(&waiter.moves).is_empty()); - } - #[test] fn work_of_resources_gone_is_dropped() { let moves = FirstMoves::default(); diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index 86237f5a7..37679873a 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -1960,9 +1960,8 @@ impl Device { at, row_pitch: natural.row_pitch, slice_pitch: natural.slice_pitch, - alone: None, }; - Ok((self.dma_buf_image(&[plan], facts, &texels)?).map(|(_, made)| made)) + self.dma_buf_image(plan, facts, &texels) } /// No pages are imported as dma-bufs on this system: never reached. diff --git a/crates/metal2vulkan-runtime/src/texture/pitch_refusals.rs b/crates/metal2vulkan-runtime/src/texture/pitch_refusals.rs deleted file mode 100644 index d01d130b7..000000000 --- a/crates/metal2vulkan-runtime/src/texture/pitch_refusals.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! The layouts a device's driver refused a texture's `DRM_FORMAT_MOD_LINEAR` image at Metal's row -//! pitch, kept so that it is not asked again (`texture.rs`'s `host_pitched_image`). -//! -//! A texture over a no-copy buffer's host pages whose rows the driver's own linear image lays out -//! otherwise than Metal is tried as a `DRM_FORMAT_MOD_LINEAR` image laid out at Metal's row pitch, -//! which the driver may refuse: it refuses the layout -//! (`VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT`; RADV of Mesa 26.2.4 at a pitch that is -//! not a multiple of 256 bytes), lays the plane out at another pitch than asked (NVIDIA 615.71.09 -//! below its own linear image's row), or asks a dedicated allocation of the image, which one bound -//! in a buffer's import is not (RADV at every other pitch). The driver answers the same image the -//! same way while the device lives, so a refusal is kept by everything the image is made of that a -//! texture varies: its format, extent, usage, flags and view formats, and the row pitch. A consumer -//! making the same surface's texture each frame asks the driver once. -//! -//! Not kept by the pitch's class (the largest power of two dividing it) alone: measured -//! (`runtime_lane::surface_texture_costs::pitch_classes`, nine formats, four usages, five widths, -//! two pitches of each class from 16 to 4096 bytes), NVIDIA takes a pitch of any class at least its -//! own linear image's row and refuses one below it, so one class holds both answers. -//! -//! Kept only for a refusal of the image itself, never one that may pass another time (the driver -//! out of memory, which the caller reports as it is); and only for a plan of one slice and depth, -//! whose plane has no array pitch. At most [`KEPT`] refusals are kept; past them the driver is -//! asked again each time. - -use crate::device::lock; -use crate::image_plan::ImagePlan; -use metal2vulkan::vk::{Format, ImageCreateFlags, ImageUsageFlags}; -use std::collections::HashSet; -use std::sync::Mutex; - -/// The most refusals a device keeps. -pub(crate) const KEPT: usize = 256; - -/// What a `DRM_FORMAT_MOD_LINEAR` image at a row pitch is made of, of what a texture varies. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub(crate) struct PitchedLayout { - format: Format, - extent: [u32; 3], - usage: ImageUsageFlags, - flags: ImageCreateFlags, - view_formats: Vec, - row_pitch: u64, -} - -impl PitchedLayout { - /// The layout of an image of `plan` with rows `row_pitch` apart; `None` for a plan of several - /// slices or depths, whose refusals are not kept. - pub(crate) fn of(plan: &ImagePlan, row_pitch: u64) -> Option { - (plan.layers == 1 && plan.extent[2] == 1).then(|| PitchedLayout { - format: plan.format, - extent: plan.extent, - usage: plan.usage, - flags: plan.flags, - view_formats: plan.view_formats.clone(), - row_pitch, - }) - } -} - -/// A device's kept refusals of `DRM_FORMAT_MOD_LINEAR` layouts at a row pitch. -#[derive(Debug, Default)] -pub(crate) struct PitchRefusals { - refused: Mutex>, -} - -impl PitchRefusals { - /// Whether the driver refused `layout` before. - pub(crate) fn refused(&self, layout: &PitchedLayout) -> bool { - lock(&self.refused).contains(layout) - } - - /// Keep the driver's refusal of `layout`, while fewer than [`KEPT`] are kept. - pub(crate) fn keep(&self, layout: PitchedLayout) { - let mut refused = lock(&self.refused); - if refused.len() < KEPT { - refused.insert(layout); - } - } -} diff --git a/crates/metal2vulkan-runtime/src/texture/shared_alias.rs b/crates/metal2vulkan-runtime/src/texture/shared_alias.rs deleted file mode 100644 index 10ee36693..000000000 --- a/crates/metal2vulkan-runtime/src/texture/shared_alias.rs +++ /dev/null @@ -1,305 +0,0 @@ -//! One `VkImage` shared by the textures of one image over the same bytes of one import of host -//! pages. A consumer makes a texture over the presented surface at each present (a no-copy buffer -//! over the surface's pages, which joins the import of a buffer that lives across presents, -//! `host_aliases.rs`, and a texture of its plane over it), releasing the one before first: each -//! the same image over the same bytes. Each texture stays its own Metal object, with its own -//! resource ID, views and hazard identity (its buffer's, which hazard tracking orders with the -//! others' over the same bytes); the `VkImage`, its first move (which keeps the texels it lies -//! over, `texture/first_move.rs`) and, over dma-buf pages, the dedicated import it is bound to -//! (`dma_buf.rs`) are made once. -//! -//! - **The key** ([`AliasKey`]) is structural: the image's place in the import (in its memory, or -//! from the dma-buf pages' first byte), its plan, the texels' pitches and slices, and its form -//! (a linear image of the driver's or at Metal's pitch, holding what beside the texels; a Metal -//! texture of a type; an image over a dma-buf of its pages). -//! - **Held by the import.** The import of the pages (`buffer.rs`'s `HostImport`) holds its -//! shared images ([`SharedImages`]): the [`HELD_PER_IMPORT`] made or taken last, the oldest -//! dropped past them, and all of them as the import goes, before its memory is freed. So a -//! texture made after the one before went takes its image, while a buffer keeps the import. A -//! texture holds its shared image too, so one dropped by its import goes with the last texture -//! over it, once the submissions that used it completed. The shared image holds nothing of its -//! import: every texture over it holds the import, and so does every submission that takes its -//! move. -//! - **Its move** waits for the next submission that may reach it, as an image's does. The image -//! notes weakly the pages of each texture over it ([`SharedAlias::taken_over`]); the submission -//! that takes the move holds the pages of one that lives then until it completed, so no -//! deallocator runs under its copies, as an image's own pages are held. Where none lives, no -//! texture reaches the image, and the move waits, registered still, for a submission while one -//! lives ([`Fresh::still_waits`]). It keeps the texels under the key of the memory the buffers -//! over them join (`HostAliases::of`), which every joined buffer's uses carry, so hazard -//! tracking orders it with the uses of any buffer over those bytes, the one that made the image -//! gone or not. -//! - **A rebind or a detach** of one texture's buffer gives that texture an image of its own over -//! the new pages, or a stand-in (`rebind.rs`, `detach.rs`); the others keep the shared one, over -//! the import their buffers still lie in. -//! - **Counted**: `WorkCounts::shared_alias_images`, a texture that took a shared image rather than -//! make one, and `shared_alias_moves_waited`, a submission that left a move waiting. - -use super::first_move::{FirstMove, Fresh}; -use super::{ImageImport, ImagePlan}; -use crate::device::lock; -use crate::exit_guard; -use crate::linear_plan::{BufferLayout, Holds}; -use crate::metal_texture::MetalOver; -use crate::release; -use crate::resource::ResourceKey; -use crate::Device; -use ash::vk; -use metal2vulkan::metal::TextureType; -use std::any::Any; -use std::collections::VecDeque; -use std::sync::{Arc, Mutex, Weak}; - -/// The most shared images an import holds ([`SharedImages`]): a surface's import carries its -/// presented texture's image, and the few other images a consumer makes of it (another usage, a -/// view format); one past them drops the oldest. -pub(crate) const HELD_PER_IMPORT: usize = 4; - -/// What a shared image is, by structure, within its import ([`SharedImages`]): textures of the -/// same key take the same `VkImage`. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct AliasKey { - /// The image's place: in the import's memory, or from the dma-buf pages' first byte. - at: u64, - plan: ImagePlan, - /// The texels' row and slice pitches, and slices (their offset in their buffer aside). - row_pitch: u64, - slice_pitch: u64, - slices: u64, - form: AliasForm, -} - -/// How a shared image is made ([`AliasKey`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum AliasForm { - /// A linear image made for host allocations, bound in the pages' import, holding what - /// `Holds` lets it beside the texels. - Linear(Holds), - /// A Metal texture over the import's `MTLBuffer` (`metal_texture.rs`), of a type. - Metal(MetalOver, TextureType), - /// A `DRM_FORMAT_MOD_LINEAR` image over a dma-buf of its own pages, holding what `Holds` - /// lets it. - DmaBuf(Holds), -} - -impl AliasKey { - /// The key of an image of `plan` over texels laid out as `layout`, made as `form`, at `at` in - /// its import. - pub(crate) fn new( - at: u64, - plan: &ImagePlan, - layout: &BufferLayout, - form: AliasForm, - ) -> AliasKey { - AliasKey { - at, - plan: plan.clone(), - row_pitch: layout.row_pitch, - slice_pitch: layout.slice_pitch, - slices: layout.slices, - form, - } - } -} - -/// A `VkImage` the textures of one [`AliasKey`] share, and its first move until a submission -/// takes it. -pub(crate) struct SharedAlias { - device: Device, - raw: vk::Image, - /// The dedicated import `raw` is bound to, over dma-buf pages: freed after `raw` is - /// destroyed. - import: Option, - key: AliasKey, - /// The key a host call that makes its move names ([`Fresh::rebindable`]): the memory's its - /// texels lie in, as the buffers over them join it. - named: ResourceKey, - first_move: Mutex>, - /// The host pages of the textures over it, noted weakly, those gone dropped as one is noted: - /// the submission that takes its move holds one that lives. - takers: Mutex>>, -} - -impl SharedAlias { - /// The shared image `raw` of `key`, bound to `import` where it is a dedicated import's, whose - /// move is `first`, which a host call naming `named` makes: registered with the device's - /// first moves. Its import holds it ([`SharedImages::hold`]). - pub(crate) fn new( - device: &Device, - (raw, import): (vk::Image, Option), - (key, named): (AliasKey, ResourceKey), - first: FirstMove, - ) -> Arc { - let alias = Arc::new(SharedAlias { - device: device.clone(), - raw, - import, - key, - named, - first_move: Mutex::new(Some(first)), - takers: Mutex::new(Vec::new()), - }); - let weak: Weak = Arc::downgrade(&alias); - let fresh: Weak = weak; - device.shared().textures.first_moves.register(fresh); - alias - } - - /// The `VkImage`. - pub(crate) fn raw(&self) -> vk::Image { - self.raw - } - - /// Whether it is bound to a dedicated import of its own pages. - pub(crate) fn dedicated(&self) -> bool { - self.import.is_some() - } - - /// Whether its move waits for a submission, and the key a host call that makes it names. - pub(crate) fn move_waits(&self) -> Option { - lock(&self.first_move).is_some().then_some(self.named) - } - - /// A texture over it was made, over the host `pages`: noted weakly, for the submission that - /// takes its move to hold. - pub(crate) fn taken_over(&self, pages: &Arc) { - let pages: Weak = Arc::downgrade(pages) as _; - let mut takers = lock(&self.takers); - takers.retain(|taker| taker.strong_count() > 0); - takers.push(pages); - } -} - -impl Fresh for SharedAlias { - /// Its move, holding the pages of a texture over it that lives; where none lives, no texture - /// reaches it, and it waits. - fn take(&self) -> Vec { - let mut waiting = lock(&self.first_move); - let Some(first) = waiting.take() else { - return Vec::new(); - }; - let live = lock(&self.takers).iter().find_map(Weak::upgrade); - match live { - Some(pages) => vec![first.holding_now(pages)], - None => { - *waiting = Some(first); - self.device.shared().counts.shared_alias_move_waited(); - Vec::new() - } - } - } - - fn still_waits(&self) -> bool { - lock(&self.first_move).is_some() - } - - fn give_back(&self, moves: Vec) { - let mut waiting = lock(&self.first_move); - for first in moves { - if waiting.is_none() { - *waiting = Some(first); - } - } - } - - fn rebindable(&self) -> Option { - let waiting = lock(&self.first_move); - (waiting.as_ref()) - .is_some_and(|first| first.rebindable()) - .then_some(self.named) - } -} - -impl Drop for SharedAlias { - fn drop(&mut self) { - // Once the process is exiting, the image is left to its end (`exit_guard`). - let Some(_busy) = exit_guard::enter() else { - return; - }; - // SAFETY: nothing holds the image: its import let go of it, every texture over it went, - // each after the command buffers that used it completed, and so did every submission - // that took its move; their views went before it. Its dedicated import goes after it, as - // it drops; the memory it is bound in is freed after it (its import drops its shared - // images first, and every holder of it holds the import). - unsafe { release::object(self.device.shared().vk(), self.raw) }; - } -} - -/// An import's shared images ([`SharedAlias`]), held while it lives: the [`HELD_PER_IMPORT`] made -/// or taken last. -#[derive(Default)] -pub(crate) struct SharedImages { - held: Mutex>>, -} - -impl SharedImages { - /// The shared image of `key`, where the import holds one: held as the one taken last. - pub(crate) fn find(&self, key: &AliasKey) -> Option> { - let mut held = lock(&self.held); - held.find(|alias| alias.key == *key).cloned() - } - - /// Hold `alias`, made over the import, as the one made last; the oldest goes past - /// [`HELD_PER_IMPORT`], once the lock is free. - pub(crate) fn hold(&self, alias: &Arc) { - let dropped = lock(&self.held).hold(Arc::clone(alias), HELD_PER_IMPORT); - drop(dropped); - } - - /// Let go of every one, as the import goes: once the lock is free. - pub(crate) fn clear(&self) { - let held: Vec> = lock(&self.held).items.drain(..).collect(); - drop(held); - } -} - -/// Items held in the order they were held or found last, the oldest first. -struct Recent { - items: VecDeque, -} - -impl Default for Recent { - fn default() -> Recent { - Recent { - items: VecDeque::new(), - } - } -} - -impl Recent { - /// The first item `matches` takes, moved to the end (found last). - fn find(&mut self, matches: impl Fn(&T) -> bool) -> Option<&T> { - let at = self.items.iter().position(matches)?; - let item = self.items.remove(at)?; - self.items.push_back(item); - self.items.back() - } - - /// Hold `item` last, and give back the oldest past `bound`. - fn hold(&mut self, item: T, bound: usize) -> Vec { - self.items.push_back(item); - let past = self.items.len().saturating_sub(bound); - self.items.drain(..past).collect() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// An import holds its last [`HELD_PER_IMPORT`] images, a found one counting as held last, - /// and gives back the oldest past them. - #[test] - fn an_import_holds_its_last_shared_images() { - let mut recent = Recent::default(); - for item in 0..HELD_PER_IMPORT { - assert!(recent.hold(item, HELD_PER_IMPORT).is_empty()); - } - assert_eq!(recent.find(|&item| item == 0), Some(&0)); - assert_eq!(recent.hold(HELD_PER_IMPORT, HELD_PER_IMPORT), vec![1]); - assert_eq!(recent.find(|&item| item == 1), None); - let held: Vec = recent.items.iter().copied().collect(); - assert_eq!(held, [2, 3, 0, 4]); - assert_eq!(recent.hold(5, 2), vec![2, 3, 0]); - } -} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 7b2786e04..0d58c917d 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -200,14 +200,6 @@ pub(crate) struct Counters { dma_buf_sparse_buffers: AtomicU64, dma_buf_images: AtomicU64, dma_buf_image_fallbacks: AtomicU64, - pitched_host_images: AtomicU64, - pitched_host_image_refusals: AtomicU64, - pitched_host_image_refusals_recalled: AtomicU64, - first_move_keeps: AtomicU64, - first_move_kept_bytes: AtomicU64, - first_move_restored_bytes: AtomicU64, - shared_alias_images: AtomicU64, - shared_alias_moves_waited: AtomicU64, modifier_feature_queries: AtomicU64, shadowed_textures: AtomicU64, shadows_zeroed: AtomicU64, @@ -245,6 +237,8 @@ pub(crate) struct Counters { shadow_merge_scratches_reused: AtomicU64, shadow_merge_scratches_zeroed: AtomicU64, shadow_merges_fetched: AtomicU64, + shadow_attachment_passes: AtomicU64, + shadow_attachment_textures: AtomicU64, shadow_attachment_loads_within: AtomicU64, shadow_attachment_loads_whole: AtomicU64, shadow_attachment_clears: AtomicU64, @@ -1332,68 +1326,12 @@ impl Counters { self.dma_buf_images.fetch_add(1, Ordering::Relaxed); } - /// A texture over dma-buf pages that such an image would alias took the path of a texture - /// over memory no image aliases instead: the device made no such image of it (`dma_buf.rs`). + /// A texture placed in a heap over dma-buf pages that such an image would alias is a shadow of + /// the heap's bytes instead: the device made no such image of it (`texture/heap.rs`). pub(crate) fn dma_buf_image_fell_back(&self) { self.dma_buf_image_fallbacks.fetch_add(1, Ordering::Relaxed); } - /// A texture's image over a no-copy buffer's host pages imported by their pointer was made a - /// `DRM_FORMAT_MOD_LINEAR` image at Metal's row pitch and bound there (`texture.rs`'s - /// `host_pitched_image`). - pub(crate) fn pitched_host_image_made(&self) { - self.pitched_host_images.fetch_add(1, Ordering::Relaxed); - } - - /// The driver refused a `DRM_FORMAT_MOD_LINEAR` image at Metal's row pitch (`texture.rs`'s - /// `host_pitched_image`). - #[cfg(unix)] - pub(crate) fn pitched_host_image_refused(&self) { - self.pitched_host_image_refusals - .fetch_add(1, Ordering::Relaxed); - } - - /// A texture's image at Metal's row pitch was not asked of the driver, which refused the same - /// image before (`texture/pitch_refusals.rs`). - #[cfg(unix)] - pub(crate) fn pitched_host_image_refusal_recalled(&self) { - self.pitched_host_image_refusals_recalled - .fetch_add(1, Ordering::Relaxed); - } - - /// The host kept the bytes `count` first moves' images are bound to across them, `bytes` of - /// them in all (`texture/first_move.rs`'s `Keep`). - pub(crate) fn first_move_kept(&self, (count, bytes): (usize, u64)) { - if count > 0 { - self.first_move_keeps - .fetch_add(count as u64, Ordering::Relaxed); - self.first_move_kept_bytes - .fetch_add(bytes, Ordering::Relaxed); - } - } - - /// The host stored `bytes` of the kept bytes again, those first moves changed - /// (`texture/first_move.rs`'s `KeptBytes::write_back`). - pub(crate) fn first_move_restored(&self, bytes: u64) { - if bytes > 0 { - self.first_move_restored_bytes - .fetch_add(bytes, Ordering::Relaxed); - } - } - - /// A texture over host pages took the `VkImage` another texture of the same image over the - /// same bytes made (`texture/shared_alias.rs`). - pub(crate) fn shared_alias_taken(&self) { - self.shared_alias_images.fetch_add(1, Ordering::Relaxed); - } - - /// A submission left a shared image's first move waiting: no texture over the image lived - /// (`texture/shared_alias.rs`). - pub(crate) fn shared_alias_move_waited(&self) { - self.shared_alias_moves_waited - .fetch_add(1, Ordering::Relaxed); - } - /// The driver was asked a format's `DRM_FORMAT_MOD_LINEAR` tiling features (`dma_buf.rs`'s /// `modifier_features`). #[cfg(unix)] @@ -1529,6 +1467,15 @@ impl Counters { self.shadow_merges_fetched.fetch_add(1, Ordering::Relaxed); } + /// An ended encoder's pass took `passes` shadowed textures as attachments, `first` of them + /// taken by no pass of its command buffer before (`render/shadows.rs`). + pub(crate) fn shadow_attachments(&self, passes: usize, first: usize) { + self.shadow_attachment_passes + .fetch_add(passes as u64, Ordering::Relaxed); + self.shadow_attachment_textures + .fetch_add(first as u64, Ordering::Relaxed); + } + /// A render pass took a shadowed texture as a color attachment so (`render/shadows.rs`). pub(crate) fn shadow_color_taken(&self, taken: ColorTaken) { let counter = match taken { @@ -2580,52 +2527,19 @@ pub struct WorkCounts { /// Of those buffers, heaps and rebinds, the ones whose `VkBuffer` is a sparse buffer /// assembled from several chunks. pub dma_buf_sparse_buffers: u64, - /// Images of textures over such dma-buf memory (over a no-copy buffer, placed in a no-copy - /// heap, a view of either), each a `DRM_FORMAT_MOD_LINEAR` image bound to a dedicated import - /// of a dma-buf of its own pages from the caller's source, aliasing the buffer's bytes: one per - /// image made, a rebind's too. Not counted in `dma_buf_imports`. + /// Images of textures placed in a no-copy heap over such dma-buf memory (or a view of one), + /// each a `DRM_FORMAT_MOD_LINEAR` image bound to a dedicated import of a dma-buf of its own + /// pages from the caller's source, aliasing the heap's bytes: one per image made, a rebind's + /// too. Not counted in `dma_buf_imports`. A texture over a no-copy buffer's pages takes no such + /// image: it is a shadow (`shadowed-texture`). pub dma_buf_images: u64, - /// Textures over such dma-buf memory that such an image would alias but the device made none + /// Textures placed in such a heap that such an image would alias but the device made none /// (the source failed, the format, usage, extent or plane layout is not supported, or the - /// driver refused the import): each takes the path of a texture over memory no image aliases + /// driver refused the import): each is a shadow of the heap's bytes in memory of its own /// (`shadowed-texture`). pub dma_buf_image_fallbacks: u64, - /// Images of textures over no-copy buffers' host pages imported by their pointer made - /// `DRM_FORMAT_MOD_LINEAR` images at Metal's row pitch, where the driver's own linear image - /// lays the rows out otherwise (ANV packs them tight), each bound in the buffer's import and - /// aliasing its bytes: one per image made, a rebind's too. - pub pitched_host_images: u64, - /// Images at Metal's row pitch the driver refused (with - /// `VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT`, by laying the plane out at another - /// offset or pitch, or by asking a dedicated allocation of it): one per image asked of the - /// driver, and a texture asks up to two (with a usage it did not declare, then without). - pub pitched_host_image_refusals: u64, - /// Images at Metal's row pitch not asked of the driver, which refused the same image (format, - /// extent, usage, flags, view formats and row pitch) before (`texture/pitch_refusals.rs`). - pub pitched_host_image_refusals_recalled: u64, - /// First moves of images over a no-copy buffer's host pages (or a rebind's new pages) across - /// which the host kept the bytes the image is bound to, which a move from `UNDEFINED` may - /// discard: read through the host pointer once the submissions before completed, the move - /// submitted alone and waited for, the bytes it changed written back. One per image moved, a - /// rebind's too. - pub first_move_keeps: u64, - /// The bytes those moves kept, each read once, and read again after the move. - pub first_move_kept_bytes: u64, - /// The kept bytes a move changed that the host stored again: none where the driver's moves - /// change no byte of the memory bound to the image. - pub first_move_restored_bytes: u64, - /// Textures over a no-copy buffer's host pages that took the `VkImage` another texture of the - /// same image over the same bytes of the same import made, which the import or a texture - /// holds, rather than make one (and move it, keep its texels or, over dma-buf pages, ask the - /// pages' source and import one). - pub shared_alias_images: u64, - /// Submissions that found a shared image's first move with no texture over the image alive, - /// and left it waiting for a submission while one is (one a submission and image): the move - /// holds the host pages of a texture over the image while it runs. - pub shared_alias_moves_waited: u64, /// Formats whose `DRM_FORMAT_MOD_LINEAR` tiling features the driver was asked, for an image - /// over dma-bufs or one at Metal's row pitch over host pages: each format once at most, as - /// the answer is kept. + /// over dma-bufs: each format once at most, as the answer is kept. pub modifier_feature_queries: u64, /// Textures over a buffer's bytes (a 2D texture or array over a buffer, a no-copy buffer or an /// IOSurface plane, or a view of another layout of one) that no image aliases, each an image @@ -2755,6 +2669,16 @@ pub struct WorkCounts { /// through its unsigned-integer view, comparing them with the kept texels, in place of a copy /// of them into the scratch (`shadow_merge.rs`): a cut merge whose shadow has the view. pub shadow_merges_fetched: u64, + /// The shadowed textures render passes took as attachments, each once a pass + /// (`render/shadows.rs`): among them textures over a buffer's bytes, a no-copy buffer's or an + /// IOSurface plane's, whose pass copies the texels in before it where it loads them and back + /// after it where it stores them. + pub shadow_attachment_passes: u64, + /// Of `shadow_attachment_passes`, those of a texture no earlier pass of its command buffer + /// took as an attachment. The difference counts the passes on a texture after its first in a + /// command buffer: the copies in and back a shadow kept across a command buffer's passes + /// could leave out, at most. + pub shadow_attachment_textures: u64, /// The shadowed textures render passes took as color attachments and loaded, each once a /// pass, whose copies are cut to the rectangle bounding the pass's draws' scissors /// (`render/shadows.rs`): the copy in moves the texels inside it alone, as do the copy back @@ -3198,18 +3122,6 @@ impl Device { dma_buf_sparse_buffers: counters.dma_buf_sparse_buffers.load(Ordering::Relaxed), dma_buf_images: counters.dma_buf_images.load(Ordering::Relaxed), dma_buf_image_fallbacks: counters.dma_buf_image_fallbacks.load(Ordering::Relaxed), - pitched_host_images: counters.pitched_host_images.load(Ordering::Relaxed), - pitched_host_image_refusals: counters - .pitched_host_image_refusals - .load(Ordering::Relaxed), - pitched_host_image_refusals_recalled: counters - .pitched_host_image_refusals_recalled - .load(Ordering::Relaxed), - first_move_keeps: counters.first_move_keeps.load(Ordering::Relaxed), - first_move_kept_bytes: counters.first_move_kept_bytes.load(Ordering::Relaxed), - first_move_restored_bytes: counters.first_move_restored_bytes.load(Ordering::Relaxed), - shared_alias_images: counters.shared_alias_images.load(Ordering::Relaxed), - shared_alias_moves_waited: counters.shared_alias_moves_waited.load(Ordering::Relaxed), modifier_feature_queries: counters.modifier_feature_queries.load(Ordering::Relaxed), shadowed_textures: counters.shadowed_textures.load(Ordering::Relaxed), views_through_swizzle: counters.views_through_swizzle.load(Ordering::Relaxed), @@ -3320,6 +3232,8 @@ impl Device { .shadow_merge_scratches_zeroed .load(Ordering::Relaxed), shadow_merges_fetched: counters.shadow_merges_fetched.load(Ordering::Relaxed), + shadow_attachment_passes: counters.shadow_attachment_passes.load(Ordering::Relaxed), + shadow_attachment_textures: counters.shadow_attachment_textures.load(Ordering::Relaxed), shadow_attachment_loads_within: counters .shadow_attachment_loads_within .load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case.rs index bc433b312..28e129ba5 100644 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case.rs +++ b/crates/metal2vulkan-validation/src/candidate/runtime_case.rs @@ -190,10 +190,13 @@ pub(crate) fn report_each_message() { /// /// Two layer gaps pass, on the layer releases whose source was read with their cause in place: /// the layer's synchronization validation forgetting a semaphore chain once the host waited on a +/// timeline (`runtime_case/host_wait_gap.rs`); and the layer's synchronization validation not +/// reading rasterization-order attachment access, so that it reports an input attachment read of +/// the runtime's pipelines made with it (named so) after an earlier draw's color write /// (`runtime_case/raster_order_gap.rs`). Each message passed prints a `LAYER-GAP` line with the /// layer's source, and a test's count of them prints once its messages go. On any other release -/// each fails, marked "re-read WaitForSemaphore in layer X.Y.Z" or "re-read the image state in -/// layer X.Y.Z". +/// each fails, marked "re-read WaitForSemaphore in layer X.Y.Z" or "re-read the input attachment +/// ordering in layer X.Y.Z". /// /// One message about the driver passes too, once the runtime announced it: the layer's report /// of a vertex module's subgroup operations outside `subgroupSupportedStages` @@ -208,7 +211,7 @@ pub struct Messages(Arc>); struct Reported { failing: Vec, notices: Vec, - /// How many of the layer gaps' messages passed. + /// How many of the layer gap's messages passed. layer_gaps: usize, /// Whether a device announced `Degradation::UnadvertisedVertexSimdgroups`. unadvertised_vertex: bool, @@ -332,7 +335,7 @@ impl Messages { } /// How many of the layer gaps' messages passed so far (`runtime_case/host_wait_gap.rs`, - /// `runtime_case/metal_import_gap.rs`). + /// `runtime_case/raster_order_gap.rs`). pub fn layer_gaps(&self) -> usize { self.0.lock().unwrap_or_else(|p| p.into_inner()).layer_gaps } diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/metal_import_gap.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/metal_import_gap.rs deleted file mode 100644 index aacd68413..000000000 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/metal_import_gap.rs +++ /dev/null @@ -1,170 +0,0 @@ -//! The second validation-layer gap a [`Messages`](super::Messages) sink lets pass: the layer -//! does not model an image made of an imported Metal texture, which Vulkan treats as bound, and -//! reports each use of it as a use with no memory bound. -//! -//! `VK_EXT_metal_objects` makes an image of an `MTLTexture` given at its creation -//! (`VkImportMetalTextureInfoEXT`), and "due to `id` already being backed by memory, -//! images created with `VkImportMetalTextureInfoEXT` in the `pNext` of the `VkImageCreateInfo` -//! will be treated as bound to a `VkDeviceMemory`" (the extension's reference page); binding one -//! again is forbidden (`VUID-vkBindImageMemory-image-01044`). The layer's image state reads no -//! such import: `vvl::Image::Image` picks the image's memory tracker from its create flags alone, -//! a `BindableLinearMemoryTracker` for every image that is neither sparse nor disjoint, which -//! only `vkBindImageMemory` marks bound (Vulkan-ValidationLayers v1.4.357, -//! `layers/state_tracker/image_state.cpp`, the `Image` constructors; its Metal code there handles -//! exports alone, `GetMetalExport`; unchanged in main of 2026-10-07). So every barrier, view, -//! framebuffer and descriptor of such an image, every copy from it and every clear of it, reports -//! it "used with no memory bound". -//! -//! The runtime makes such an image for a texture over a no-copy buffer on a driver that runs on -//! Metal (`runtime/src/metal_texture.rs`) and names it [`NAME`] where its instance reports -//! messages (`runtime/src/host_memory.rs`, `METAL_TEXTURE_IMAGE`). [`shape`] matches exactly the -//! six messages the layer gives such an image, and only when the image they name bears that -//! name; [`read`] keys the layer releases whose source was read with the gap in place. On any -//! other release such a message fails, marked "re-read the image state in layer X.Y.Z", so a -//! fixed or changed layer is checked again rather than trusted. - -use ash::vk; - -/// The messages the layer gives an image it believes unbound, as the lanes saw them on MoltenVK -/// (EV `ZCI-mvkprobe1-mvk4`): a barrier, a view, a framebuffer attachment, a descriptor; the -/// source of an image copy, as the kept-bytes lanes saw it there (a pass copying the texels of -/// such a texture into the image its texture keeps, `runtime/src/kept_bytes.rs`); and the image -/// of a clear, as the window-surface lanes saw it there (a pass's color that its first instance -/// leaves out, cleared before the pass, `runtime/src/render.rs`'s `Clears`). -const ID_NAMES: [&str; 6] = [ - "VUID-VkImageMemoryBarrier-image-01932", - "VUID-VkImageViewCreateInfo-image-01020", - "UNASSIGNED-VkFramebufferCreateInfo-BoundResourceFreedMemoryAccess", - "UNASSIGNED-VkDescriptorImageInfo-BoundResourceFreedMemoryAccess", - "VUID-vkCmdCopyImage-srcImage-07966", - "VUID-vkCmdClearColorImage-image-00003", -]; - -/// The runtime's name for an image made of a Metal texture (`runtime/src/host_memory.rs`, -/// `METAL_TEXTURE_IMAGE`), which the layer prints after the image's handle. -pub(super) const NAME: &str = "metal2vulkan: a Metal texture over imported host memory"; - -/// What follows the image in each of those messages. -const UNBOUND: &str = " used with no memory bound"; - -/// The layer releases (`VkLayerProperties::specVersion` of `VK_LAYER_KHRONOS_validation`) whose -/// image state was read with the gap in place: v1.4.357. -pub(super) const READ: &[u32] = &[vk::make_api_version(0, 1, 4, 357)]; - -/// Where the gap is, for the line each message let pass prints. -pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.357 \ - layers/state_tracker/image_state.cpp, vvl::Image::Image: the memory tracker is chosen from \ - the create flags alone; no VkImportMetalTextureInfoEXT handling"; - -/// Whether a message with this id name and text is the gap's: one of the six messages, about a -/// `VkImage` the runtime named [`NAME`], used with no memory bound: the `VkImage` the text names -/// last before that phrase must bear the name. -pub(super) fn shape(id_name: &str, text: &str) -> bool { - if !ID_NAMES.contains(&id_name) { - return false; - } - let Some(at) = text.find(UNBOUND) else { - return false; - }; - let named = format!("[{NAME}]"); - let before = &text[..at]; - let Some(image_at) = before.rfind("VkImage 0x") else { - return false; - }; - let image = &before[image_at + "VkImage 0x".len()..]; - let hex_end = image - .find(|c: char| !c.is_ascii_hexdigit()) - .unwrap_or(image.len()); - hex_end > 0 && image[hex_end..] == named -} - -/// Whether the layer release `version` is one whose source was read with the gap in place. -pub(super) fn read(version: u32) -> bool { - READ.contains(&version) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The layer's messages as the lanes saw them on MoltenVK, with the runtime's name after the - /// handle (the layer prints an object's debug name there). - fn seen(id_name: &str) -> String { - let image = format!("VkImage 0x6c000000006c[{NAME}]"); - match id_name { - "VUID-VkImageMemoryBarrier-image-01932" => format!( - "vkCmdPipelineBarrier(): pImageMemoryBarriers[0].image {image} used with no \ - memory bound. Memory should be bound by calling vkBindImageMemory().\nThe \ - Vulkan spec states: If image is non-sparse then the image or each specified \ - disjoint plane must be bound completely and contiguously to a single \ - VkDeviceMemory object" - ), - "VUID-VkImageViewCreateInfo-image-01020" => format!( - "vkCreateImageView(): pCreateInfo->image {image} used with no memory bound. \ - Memory should be bound by calling vkBindImageMemory()." - ), - "VUID-vkCmdCopyImage-srcImage-07966" => format!( - "vkCmdCopyImage(): srcImage {image} used with no memory bound. Memory should be \ - bound by calling vkBindImageMemory().\nThe Vulkan spec states: If srcImage is \ - non-sparse then the image or each specified disjoint plane must be bound \ - completely and contiguously to a single VkDeviceMemory object" - ), - "VUID-vkCmdClearColorImage-image-00003" => format!( - "vkCmdClearColorImage(): image {image} used with no memory bound. Memory should \ - be bound by calling vkBindImageMemory().\nThe Vulkan spec states: If image is \ - non-sparse then it must be bound completely and contiguously to a single \ - VkDeviceMemory object" - ), - _ => format!( - "vkCreateFramebuffer(): pCreateInfo->pAttachments[0] {image} used with no memory \ - bound. Memory should be bound by calling vkBindImageMemory()." - ), - } - } - - #[test] - fn the_layer_s_messages_about_a_metal_texture_image_are_the_gap() { - for id_name in ID_NAMES { - assert!(shape(id_name, &seen(id_name)), "{id_name}"); - } - } - - #[test] - fn the_messages_about_another_image_are_not_the_gap() { - for id_name in ID_NAMES { - let text = seen(id_name); - // No name: an image the runtime made otherwise, which must be bound. - let unnamed = text.replace(&format!("[{NAME}]"), ""); - assert!(!shape(id_name, &unnamed), "{id_name}: unnamed"); - // Another name, or the name inside another one. - let other = text.replace(NAME, "the caller's image"); - assert!(!shape(id_name, &other), "{id_name}: another name"); - let wider = text.replace(NAME, &format!("{NAME} and more")); - assert!(!shape(id_name, &wider), "{id_name}: a wider name"); - // The name on another object, the image unnamed. - let elsewhere = format!( - "VkImageView 0x10[{NAME}] of {}", - text.replace(&format!("[{NAME}]"), "") - ); - assert!(!shape(id_name, &elsewhere), "{id_name}: the name elsewhere"); - } - } - - #[test] - fn other_messages_about_the_image_are_not_the_gap() { - let text = seen("VUID-VkImageMemoryBarrier-image-01932"); - assert!(!shape("VUID-VkImageMemoryBarrier-oldLayout-01197", &text)); - assert!(!shape("VUID-VkImageMemoryBarrier2-image-01932", &text)); - assert!(!shape("", &text)); - let freed = text.replace(UNBOUND, " used after its memory was freed"); - assert!(!shape("VUID-VkImageMemoryBarrier-image-01932", &freed)); - } - - #[test] - fn only_the_releases_read_pass() { - assert!(read(vk::make_api_version(0, 1, 4, 357))); - assert!(!read(vk::make_api_version(0, 1, 4, 356))); - assert!(!read(vk::make_api_version(0, 1, 4, 358))); - assert!(!read(vk::make_api_version(0, 1, 5, 0))); - } -} diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index b12749e5b..e4615a501 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -419,6 +419,8 @@ mod fetch_costs; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod first_use; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod first_use_writes; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod first_vertex; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod format_copies; @@ -452,6 +454,8 @@ mod gpu_times; mod grouped_submissions; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod guarded_effects; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] +mod guest_frame_costs; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod half_output_blends; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] diff --git a/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs b/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs index d67f044a2..d8892e1a2 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs @@ -1411,68 +1411,6 @@ fn a_planar_surface_s_depth_or_stencil_texture_s_passes_write_metal_s_elements_a ); } -/// No depth or stencil texture over a buffer's bytes asks the driver for a -/// `DRM_FORMAT_MOD_LINEAR` image, at Metal's row pitch over host pages or over dma-buf pages, even -/// where the driver lists the modifier for its format (lavapipe does): the runtime asks the layout -/// of every such image it makes of a memory plane (`VUID-vkGetImageSubresourceLayout-tiling-09433`), -/// and Vulkan has no such query of a format with depth or stencil, whose aspect it must name -/// (`-format-04462`, `-format-04463`). Each texture of a surface's plane is made, at a padded row -/// pitch and a browser's, and the work counts show no such image made or refused. -#[test] -fn no_depth_or_stencil_texture_over_a_buffer_asks_for_a_modifier_image() { - use metal2vulkan_runtime::WorkCounts; - let asked = |counts: &WorkCounts| { - ( - counts.pitched_host_images, - counts.pitched_host_image_refusals, - counts.dma_buf_images, - ) - }; - let messages = Messages::default(); - let cache = ScratchCache::new().unwrap(); - { - let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); - eprintln!("device {}", device.name()); - for kind in [Kind::Ordinary, Kind::NoCopy] { - let Some(held) = Held::new(&device, kind) else { - eprintln!("{}: no {kind:?} buffer", device.name()); - continue; - }; - for pf in [ - PixelFormat::Depth16Unorm, - PixelFormat::Depth32Float, - PixelFormat::Depth32FloatStencil8, - PixelFormat::Stencil8, - PixelFormat::X32Stencil8, - ] { - for usage in [TextureUsage::SHADER_READ, TextureUsage::RENDER_TARGET] { - for bpr in [64, 256] { - let what = format!("{kind:?} {pf:?} {usage:?}, rows {bpr} bytes apart"); - let mut d = TextureDescriptor::texture_2d(pf, 4, 4, false); - d.usage = usage; - d.resource_options = held.buffer.resource_options(); - let before = device.work_counts(); - held.buffer - .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, bpr, true)) - .unwrap_or_else(|e| panic!("{what}: {e}")); - assert_eq!( - asked(&device.work_counts()), - asked(&before), - "{what}: DRM_FORMAT_MOD_LINEAR images asked of the driver (made at \ - Metal's row pitch, refused there, made over dma-bufs)" - ); - } - } - } - } - } - let messages = messages.take(); - assert!( - messages.is_empty(), - "the validation layer reported: {messages:#?}" - ); -} - /// The rows of a `w`x`h` plane `row` bytes wide, from `offset`, `pitch` bytes apart. fn plane_rows(offset: u64, pitch: u64, row: u64, h: u64) -> Vec> { (0..h) diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index 36b61ef5b..6e0e7fb06 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -436,8 +436,7 @@ pub(super) fn on_device_with( /// Every kind is taken by a lane test's site: listed above, or a stage's precision note or /// reconvergence; no kind is in two lists, and no list names a kind twice. `misplaced-notice` -/// ([`MISPLACED`]) and `unrestored-first-move-bytes` ([`UNRESTORED`]) are taken by the runtime's -/// own tests instead, as no lane can meet them. +/// ([`MISPLACED`]) is taken by the runtime's own tests instead, as no lane can meet it. #[test] fn every_kind_has_a_site_a_lane_test_takes() { let stage_kinds = Degradation::ALL.iter().copied().filter(|kind| { @@ -547,7 +546,6 @@ fn every_kind_has_a_site_a_lane_test_takes() { &KEPT_BYTES, &DELAYED_DEALLOCATORS, &MISPLACED, - &UNRESTORED, &DEPTH_DENORMALS, &SIGNED_DEPTH_TESTS, &FIRST_SPARSE, @@ -890,13 +888,6 @@ fn an_anisotropic_state_without_mips_is_announced_through_metals_sampler() { /// takes its site, as a build without debug assertions does. const MISPLACED: [Degradation; 1] = [Degradation::MisplacedNotice]; -/// The kind a first move's write back announces where the move changed kept bytes on pages the -/// process no longer maps writable. No lane meets it: no measured driver's move changes a byte of -/// the memory bound to the image, and none can be made to. The runtime's own test -/// `the_write_back_stores_only_what_the_move_changed_and_only_where_the_host_may_write` takes its -/// site (the write back over read-only pages it changed), as such a move would. -const UNRESTORED: [Degradation; 1] = [Degradation::UnrestoredFirstMoveBytes]; - /// The kind Metal's private option bit takes ([`the_private_option_bit_is_ignored_once`]). const PRIVATE_OPTION: [Degradation; 1] = [Degradation::PrivateResourceOption]; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs index d50dbe043..314bf5033 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs @@ -13,12 +13,14 @@ //! as a consumer does: the runtime runs no udmabuf code. //! //! RADV refuses the pointer of such memory and imports the chunks, which the runtime counts -//! (`WorkCounts::dma_buf_imports`, and `dma_buf_sparse_buffers` for a buffer of several), and -//! makes each texture over them an image of `DRM_FORMAT_MOD_LINEAR` over a dma-buf of its own -//! pages, which it asks the source for too (`dma_buf_images`), or its shadow where it makes none -//! (`dma_buf_image_fallbacks`); NVIDIA and lavapipe import the pointer, never call the source and -//! count nothing. A driver not measured has its answers printed. Where `/dev/udmabuf` cannot be -//! opened each test says so and passes without running. +//! (`WorkCounts::dma_buf_imports`, and `dma_buf_sparse_buffers` for a buffer of several). A +//! texture over a no-copy buffer of them is a shadow of its bytes, as over any host pages, and +//! asks the source for nothing; a texture placed in a no-copy heap over them is an image of +//! `DRM_FORMAT_MOD_LINEAR` over a dma-buf of its own pages, which it asks the source for too +//! (`dma_buf_images`), or its shadow where it makes none (`dma_buf_image_fallbacks`). NVIDIA and +//! lavapipe import the pointer, never call the source and count nothing. A driver not measured +//! has its answers printed. Where `/dev/udmabuf` cannot be opened each test says so and passes +//! without running. use super::first_use::{read_mark, release, scheduled, Busy, ENDED}; use super::host_memory::{ @@ -814,11 +816,11 @@ fn shared_memory_is_refused_without_a_working_source() { } /// The source runs with no lock of the runtime's held: one that makes a buffer of the device's -/// own and a no-copy buffer of private memory before it answers, for a no-copy buffer, a texture -/// over it and a view of that texture in another format (each texture's image over a dma-buf of -/// its own pages), and for a rebind of one onto memfd memory, returns, and each is made over its -/// chunks (RADV) or over the pointer, the source uncalled (elsewhere). The rebound buffer's bytes -/// are then the view's. +/// own and a no-copy buffer of private memory before it answers, for a no-copy buffer, a no-copy +/// heap and a texture placed in it (its image over a dma-buf of its own pages), and for a rebind +/// of a buffer onto memfd memory, returns, and each is made over its chunks (RADV) or over the +/// pointer, the source uncalled (elsewhere). A texture over the no-copy buffer, a shadow of its +/// bytes, asks it nothing. The rebound buffer's bytes are then the view's. #[test] fn the_source_runs_with_no_runtime_lock_held() { const TEST: &str = "dma-buf source calls the runtime"; @@ -830,8 +832,8 @@ fn the_source_runs_with_no_runtime_lock_held() { let queue = device.new_command_queue().unwrap(); let ram = Memfd::new(8 * page); let view = ram.view(&[(4 * page, 2 * page)]); - let reentrant = |calls: &Calls| -> DmaBufSource { - let inner = ram.source(&view, calls); + let reentrant = |ram: &Memfd, view: &View, calls: &Calls| -> DmaBufSource { + let inner = ram.source(view, calls); let device = device.clone(); Arc::new(move |request| { let own = device.new_buffer(4096, ResourceOptions::default()).unwrap(); @@ -852,7 +854,8 @@ fn the_source_runs_with_no_runtime_lock_held() { }; let calls = Calls::default(); let before = dma_buf_counts(device); - let buffer = no_copy(device, &view, 0, 2 * page, reentrant(&calls)).unwrap(); + let source = reentrant(&ram, &view, &calls); + let buffer = no_copy(device, &view, 0, 2 * page, source).unwrap(); check_route( TEST, device, @@ -861,15 +864,48 @@ fn the_source_runs_with_no_runtime_lock_held() { before, Some(1), ); - // A texture over it, and a view of another format: each image's call (RADV) too. + // A texture over it, a shadow, asks the source nothing. let counted = image_counts(device); + let asked = calls.lock().unwrap().len(); let texture = buffer .new_texture(&read_only(PixelFormat::BGRA8Unorm, 64, 8), 0, 256) .unwrap(); - let viewed = texture.new_texture_view(PixelFormat::RGBA8Unorm).unwrap(); - check_images(TEST, device, counted, 2, 0); - drop((viewed, texture)); + check_images(TEST, device, counted, 0, 0); + assert_eq!( + calls.lock().unwrap().len(), + asked, + "{TEST}: the texture's calls" + ); + drop(texture); drop(buffer); + // A heap over other pages, and a texture placed in it: the heap's call, and the texture + // image's (RADV). + let heap_size = 1 << 20; + let heap_ram = Memfd::new(heap_size); + let heap_view = heap_ram.view(&[(0, heap_size)]); + let calls = Calls::default(); + let before = dma_buf_counts(device); + let source = reentrant(&heap_ram, &heap_view, &calls); + let descriptor = HeapDescriptor::new(HeapType::Placement, heap_size as u64, shared()); + // SAFETY: the view outlives the heap, and the source makes dma-bufs of its pages. + let heap = unsafe { + device.new_heap_with_bytes_no_copy( + HostMemory::with_dma_buf(heap_view.pointer(0), source), + &descriptor, + None, + None, + ) + } + .unwrap(); + let pages = (heap_view.at, heap_size as u64); + check_route(TEST, device, &calls, pages, before, None); + let mut placed = read_only(PixelFormat::RGBA8Unorm, 64, 64); + placed.resource_options = shared(); + let counted = image_counts(device); + let texture = heap.new_texture_at_offset(&placed, 0).unwrap(); + check_images(TEST, device, counted, 1, 0); + drop(texture); + drop(heap); // A rebind of a buffer over private memory onto the view. let private = Mapping::anonymous(2 * page); // SAFETY: the mapping outlives the buffer. @@ -889,7 +925,7 @@ fn the_source_runs_with_no_runtime_lock_held() { // SAFETY: the view outlives the buffer, and no other thread encodes or commits. unsafe { buffer.rebind_bytes_no_copy( - HostMemory::with_dma_buf(view.pointer(0), reentrant(&calls)), + HostMemory::with_dma_buf(view.pointer(0), reentrant(&ram, &view, &calls)), None, None, ) @@ -1196,8 +1232,8 @@ fn a_sparse_buffer_s_binding_waits_for_no_gpu_work() { }); } -/// The device's counts of textures' images made over dma-bufs of their own pages, and of textures -/// over dma-buf pages that took the path such a texture took before (a shadow of the bytes). +/// The device's counts of heap textures' images made over dma-bufs of their own pages, and of +/// heap textures over dma-buf pages that took their shadow instead. fn image_counts(device: &Device) -> (u64, u64) { let counts = device.work_counts(); (counts.dma_buf_images, counts.dma_buf_image_fallbacks) @@ -1206,7 +1242,7 @@ fn image_counts(device: &Device) -> (u64, u64) { /// Check what making textures over dma-buf pages counted since `before`: `images` images and /// `fallbacks` fallbacks where the device imports dma-bufs (RADV, whose list holds /// `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign`); none where it imports -/// the pointer (NVIDIA, lavapipe), whose textures take the path they took before. +/// the pointer (NVIDIA, lavapipe), whose heap textures are images bound to the pointer's import. fn check_images(test: &str, device: &Device, before: (u64, u64), images: u64, fallbacks: u64) { let now = image_counts(device); let counted = (now.0 - before.0, now.1 - before.1); @@ -1234,10 +1270,10 @@ fn read_only(pf: PixelFormat, width: u64, height: u64) -> TextureDescriptor { /// Check the source's requests `asked`, made as a texture whose `texels` are `(pitch, row, rows)` /// (rows `pitch` bytes apart, `row` bytes each) was made at `offset` of a view starting `at`: -/// where the device made its image over a dma-buf of its own pages (`image`, on RADV), one request, -/// for the page its texels start in and the pages from there its image's memory covers, in one -/// chunk (its granule its length), one chunk answered; none where it took its shadow, or where the -/// device imports the pointer. +/// where the device made its image over a dma-buf of its own pages (`image`, a heap texture on +/// RADV), one request, for the page its texels start in and the pages from there its image's +/// memory covers, in one chunk (its granule its length), one chunk answered; none where it took +/// its shadow, or where the device imports the pointer. fn check_texture_request( test: &str, device: &Device, @@ -1273,27 +1309,18 @@ fn check_texture_request( } /// Textures over a no-copy buffer of memfd memory (the consumer's display-path surfaces), rows 256 -/// bytes apart: where the device imports the buffer's pages as dma-bufs (RADV), each whose rows -/// are 256 bytes of texels is an image of `DRM_FORMAT_MOD_LINEAR` bound to a dedicated import of a -/// dma-buf of its own pages, which the source is asked for once, counted, its plane at the texels' -/// offset in their first page: over three pages, a page into the buffer; 256 bytes into a page; -/// one a shader writes, whose modifier's storage features above bit 31 the device reports only in -/// the 64-bit list (`STORAGE_*_WITHOUT_FORMAT`, which the optimal tiling has). One over one page, -/// whose rows of 240 bytes of texels have 16 of the file's between them, and one 64 bytes into a -/// page, of 64-byte rows, take their shadows instead (an image over them would hold the bytes -/// between the rows, which Vulkan lets a render pass write back), the source not called, counted -/// as fallbacks. Each reads the bytes the CPU wrote; the CPU's later writes, with no call between, are -/// what the next command buffer reads (the image rests in `GENERAL` after its one acquire from the -/// foreign queue family); a blit's write into it lands in the file's pages at the texels' places, -/// the padding past each row keeping the CPU's bytes; the same texture made again asks the driver -/// no format's modifier features (`WorkCounts::modifier_feature_queries`, which RADV's images -/// ask). The one over three pages, `BGRA8Unorm` made without `PixelFormatView` usage, is read and -/// written through a view in `RGBA8Unorm` (`texture/view_shadow.rs`), an image over a dma-buf of -/// its own pages too, counted, whose write the texture then reads. Where the device imports the -/// pointer (NVIDIA, lavapipe) the textures take the path they took before: the source uncalled, -/// nothing counted. +/// bytes apart, are shadows of the buffer's bytes on every device (`shadowed-texture`), as over any +/// host pages: none asks the source, none counts as an image or a fallback, and making one asks +/// the driver no format's modifier features (`WorkCounts::modifier_feature_queries`). Over three +/// pages, a page into the buffer; over one page, whose rows of 240 bytes of texels have 16 of the +/// file's between them; 256 bytes into a page; 64 bytes into a page, of 64-byte rows; and one a +/// shader writes. Each reads the bytes the CPU wrote; the CPU's later writes, with no call between, +/// are what the next command buffer reads; a blit's write into it lands in the file's pages at the +/// texels' places, the padding past each row keeping the CPU's bytes. The one over three pages, +/// `BGRA8Unorm` made without `PixelFormatView` usage, is read and written through a view in +/// `RGBA8Unorm` (`texture/view_shadow.rs`), whose write the texture then reads. #[test] -fn a_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() { +fn a_texture_over_dma_buf_pages_is_a_shadow_of_them() { const TEST: &str = "dma-buf texture"; if !udmabuf_openable(TEST) { return; @@ -1311,8 +1338,7 @@ fn a_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() { let buffer = no_copy(device, &pages, 0, length, ram.source(&pages, &calls)).unwrap(); check_route(TEST, device, &calls, (at, length as u64), before, Some(1)); let pitch = 256; - // What, its descriptor, offset, whether RADV makes its image over a dma-buf of its own - // pages, and whether it is used through a view. + // What, its descriptor, offset, and whether it is used through a view. let writable = |pf, width, height| { let mut descriptor = read_only(pf, width, height); descriptor.usage |= TextureUsage::SHADER_WRITE; @@ -1324,20 +1350,17 @@ fn a_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() { read_only(PixelFormat::RGBA8Unorm, 60, 16), 0, false, - false, ), ( "three pages", read_only(PixelFormat::BGRA8Unorm, 64, 40), page, true, - true, ), ( "256 bytes in", read_only(PixelFormat::RGBA8Unorm, 64, 20), 5 * page + 256, - true, false, ), ( @@ -1345,18 +1368,16 @@ fn a_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() { read_only(PixelFormat::RGBA8Unorm, 16, 8), 7 * page + 64, false, - false, ), ( "shader write", writable(PixelFormat::RGBA8Unorm, 64, 16), 0, - true, false, ), ]; for (k, case) in cases.into_iter().enumerate() { - let (what, descriptor, offset, image, view) = case; + let (what, descriptor, offset, view) = case; let test = format!("{TEST}: {what}"); let size = (descriptor.width, descriptor.height); let (row, rows) = (4 * size.0 as usize, size.1 as usize); @@ -1364,18 +1385,27 @@ fn a_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() { let counted = image_counts(device); let earlier = counting(pitch * rows, 20 + k); ram.whole.write(2 * page + offset, &earlier); + let queries = device.work_counts().modifier_feature_queries; let texture = buffer .new_texture(&descriptor, offset as u64, pitch as u64) .unwrap(); - check_images(&test, device, counted, u64::from(image), u64::from(!image)); + assert_eq!( + device.work_counts().modifier_feature_queries, + queries, + "{test}: the texture asked the driver's modifier features" + ); + // SAFETY: the handle is only compared, while the texture lives. + let bound = unsafe { texture.vk_image() }.is_some(); + assert!(!bound, "{test}: an image bound to host pages"); + check_images(&test, device, counted, 0, 0); let asked = calls.lock().unwrap()[asked_before..].to_vec(); let texels = (pitch, row, rows); - check_texture_request(&test, device, &asked, at, offset, texels, image); + check_texture_request(&test, device, &asked, at, offset, texels, false); let target = match view { true => { let counted = image_counts(device); let viewed = texture.new_texture_view(PixelFormat::RGBA8Unorm).unwrap(); - check_images(&test, device, counted, 1, 0); + check_images(&test, device, counted, 0, 0); viewed } false => texture.clone(), @@ -1413,38 +1443,17 @@ fn a_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() { ); } drop((target, texture)); - eprintln!( - "{test}: on {}: {}", - device.name(), - match image_counts(device).0 - counted.0 { - 0 => "the path taken before", - _ => "an image over a dma-buf of its own pages", - } - ); - // A format's modifier features are asked of the driver once: the same texture made - // again asks none. - let queries = device.work_counts().modifier_feature_queries; - drop( - buffer - .new_texture(&descriptor, offset as u64, pitch as u64) - .unwrap(), - ); - assert_eq!( - device.work_counts().modifier_feature_queries, - queries, - "{test}: the same texture made again asked the driver's modifier features" - ); } drop(buffer); }); } -/// A texture's image over a dma-buf of its own pages and its buffer's import of the same pages -/// are one resource to hazard tracking (the texture's image takes the buffer's identity): in one -/// command buffer, a blit's write of the buffer is what the next encoder's copy out of the texture -/// reads, and a copy into the texture is what the next encoder's copy out of the buffer reads; -/// and so across two command buffers on one queue. Where the device imports the pointer the -/// texture is what it was before, and the same holds. +/// A texture over a no-copy buffer of dma-buf pages, a shadow of the buffer's bytes, is ordered +/// with the buffer's other uses (its copy in reads the buffer's bytes, its copy back writes them): +/// in one command buffer, a blit's write of the buffer is what the next encoder's copy out of the +/// texture reads, and a copy into the texture is what the next encoder's copy out of the buffer +/// reads; and so across two command buffers on one queue. Nothing counts as an image or a +/// fallback. Where the device imports the pointer the same holds. #[test] fn a_buffer_and_its_texture_over_dma_buf_pages_order_their_writes() { const TEST: &str = "dma-buf texture and buffer"; @@ -1466,7 +1475,7 @@ fn a_buffer_and_its_texture_over_dma_buf_pages_order_their_writes() { let texture = buffer .new_texture(&read_only(PixelFormat::RGBA8Unorm, size.0, size.1), 0, 256) .unwrap(); - check_images(TEST, device, counted, 1, 0); + check_images(TEST, device, counted, 0, 0); let out = device .new_buffer(bytes as u64, ResourceOptions::shared()) .unwrap(); @@ -1517,14 +1526,14 @@ fn a_buffer_and_its_texture_over_dma_buf_pages_order_their_writes() { }); } -/// Where the source fails for a texture's pages (it answers the buffer's request, then none), the -/// texture over dma-buf pages takes the path it took before: a shadow of the bytes, counted as a -/// fallback and announced once (`shadowed-texture`, naming the dma-buf pages and the source's -/// failure); the source asked once for it. The shadow reads the CPU's bytes, and a blit's write -/// through it reaches them. Where the device imports the pointer, nothing is asked or counted. +/// Where the source fails for a heap texture's pages (it answers the heap's request, then none), +/// the texture placed in a no-copy heap over dma-buf pages takes its shadow of the heap's bytes, +/// counted as a fallback and announced once (`shadowed-texture`, naming the dma-buf pages and the +/// source's failure); the source asked once for it. A blit's write through it reads back. Where +/// the device imports the pointer, nothing is asked or counted. #[test] -fn a_texture_over_dma_buf_pages_takes_its_shadow_where_the_source_fails() { - const TEST: &str = "dma-buf texture fallback"; +fn a_heap_texture_over_dma_buf_pages_takes_its_shadow_where_the_source_fails() { + const TEST: &str = "dma-buf heap texture fallback"; if !udmabuf_openable(TEST) { return; } @@ -1533,12 +1542,11 @@ fn a_texture_over_dma_buf_pages_takes_its_shadow_where_the_source_fails() { { let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); let page = host_page(); + let size = 1 << 20; let queue = device.new_command_queue().unwrap(); - let length = 2 * page; - let ram = Memfd::new(4 * page); - let view = ram.view(&[(page, length)]); - let earlier = counting(length, 17); - ram.whole.write(page, &earlier); + let ram = Memfd::new(size + 2 * page); + let view = ram.view(&[(2 * page, size)]); + ram.whole.write(2 * page, &counting(size, 17)); let calls = Calls::default(); let inner = ram.source(&view, &calls); let answered = Arc::new(Mutex::new(0usize)); @@ -1551,12 +1559,27 @@ fn a_texture_over_dma_buf_pages_takes_its_shadow_where_the_source_fails() { _ => Err(std::io::Error::other("no dma-buf for a texture")), } }); - let buffer = no_copy(&device, &view, 0, length, once).unwrap(); + let descriptor = HeapDescriptor::new(HeapType::Placement, size as u64, shared()); + // SAFETY: the view outlives the heap, and the source makes dma-bufs of its pages. + let heap = unsafe { + device.new_heap_with_bytes_no_copy( + HostMemory::with_dma_buf(view.pointer(0), once), + &descriptor, + None, + None, + ) + } + .unwrap(); + let extent = (64, 64); + let mut texture_descriptor = read_only(PixelFormat::RGBA8Unorm, extent.0, extent.1); + texture_descriptor.resource_options = shared(); + let answer = device + .heap_texture_size_and_align(&texture_descriptor) + .unwrap(); + let offset = answer.align.max(page as u64) * 3; let counted = image_counts(&device); - let size = (64, 32); - let bytes = (4 * size.0 * size.1) as usize; - let texture = buffer - .new_texture(&read_only(PixelFormat::RGBA8Unorm, size.0, size.1), 0, 256) + let texture = heap + .new_texture_at_offset(&texture_descriptor, offset) .unwrap(); check_images(TEST, &device, counted, 0, 1); let notices: Vec<_> = messages @@ -1579,17 +1602,14 @@ fn a_texture_over_dma_buf_pages_takes_its_shadow_where_the_source_fails() { Some(false) => assert_eq!(*answered.lock().unwrap(), 0, "{TEST}: called"), None => eprintln!("{TEST}: on {}: notices {notices:?}", device.name()), } - assert!( - blit_texels(&queue, &texture, size, 4) == earlier[..bytes], - "{TEST}: the CPU's bytes" - ); + let bytes = (4 * extent.0 * extent.1) as usize; let texels = counting(bytes, 61); - blit_into(&queue, &texture, size, 4, &texels); + blit_into(&queue, &texture, extent, 4, &texels); assert!( - ram.whole.read(page..page + bytes) == texels, - "{TEST}: the blit's write" + blit_texels(&queue, &texture, extent, 4) == texels, + "{TEST}: the blit's write reads back" ); - drop((texture, buffer)); + drop((texture, heap)); } let failing = messages.take(); assert!( @@ -1687,11 +1707,12 @@ fn a_no_copy_heap_s_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() }); } -/// A rebind of bytes over dma-buf pages to other such pages makes each texture's image again over -/// a dma-buf of its own new pages (RADV), counted, the new source asked once for the bytes and -/// once for each texture: a no-copy buffer's texture, and a no-copy heap's. Each then reads the -/// new pages' bytes, and a blit's write through it lands there, the old pages keeping theirs. -/// Elsewhere the textures are made again as before, nothing counted or asked. +/// A rebind of bytes over dma-buf pages to other such pages: a no-copy buffer's texture, a shadow +/// of the bytes, copies the new pages' texels, the new source asked once for the bytes alone, +/// nothing counted; a no-copy heap's texture is made again as an image over a dma-buf of its own +/// new pages (RADV), counted, the new source asked once for the bytes and once for the texture. +/// Each then reads the new pages' bytes, and a blit's write through it lands there, the old pages +/// keeping theirs. Elsewhere the textures are made again as before, nothing counted or asked. #[test] fn a_rebind_makes_textures_over_dma_buf_pages_again_over_the_new_pages() { const TEST: &str = "dma-buf texture rebind"; @@ -1729,10 +1750,9 @@ fn a_rebind_makes_textures_over_dma_buf_pages_again_over_the_new_pages() { ) } .unwrap(); - check_images(TEST, device, counted, 1, 0); - let expected = if radv { 2 } else { 0 }; + check_images(TEST, device, counted, 0, 0); let asked = calls.lock().unwrap().len(); - assert_eq!(asked, expected, "{TEST}: the new source's calls"); + assert_eq!(asked, usize::from(radv), "{TEST}: the new source's calls"); assert!( blit_texels(&queue, &texture, size, 4) == after[..bytes], "{TEST}: the texture reads the new pages" @@ -1774,6 +1794,7 @@ fn a_rebind_makes_textures_over_dma_buf_pages_again_over_the_new_pages() { .unwrap(); check_images(TEST, device, counted, 1, 0); let asked = calls.lock().unwrap().len(); + let expected = if radv { 2 } else { 0 }; assert_eq!(asked, expected, "{TEST}: the heap's new source's calls"); let texels = counting(heap_bytes, 131); blit_into(&queue, &texture, extent, 4, &texels); @@ -1798,9 +1819,8 @@ fn a_rebind_makes_textures_over_dma_buf_pages_again_over_the_new_pages() { /// A rebind between pages a source answers in one chunk and pages it answers a chunk per granule /// (a sparse buffer, RADV), both ways, of a no-copy buffer 80 bytes into its page with a texture -/// over it whose rows are 240 bytes apart: RADV lays no `DRM_FORMAT_MOD_LINEAR` plane there, so -/// the texture is a shadow of the bytes, its copies planned at the bytes' offset in their -/// `VkBuffer`. Either buffer holds the bytes at their offset in their page, so each rebind is made +/// over it whose rows are 240 bytes apart: the texture is a shadow of the bytes, as every texture +/// over a no-copy buffer's pages, its copies planned at the bytes' offset in their `VkBuffer`. Either buffer holds the bytes at their offset in their page, so each rebind is made /// and the texture reads each new pages' texels. Elsewhere the pointer is imported each time. Then /// a rebind onto anonymous memory, whose pointer every device imports: made, the texture reading /// its texels, or refused (`NotImplemented`, `RebindTextures`) where that import holds the bytes @@ -1833,7 +1853,7 @@ fn a_rebind_between_one_chunk_and_several_keeps_a_texture_s_texels() { let counted = image_counts(device); let descriptor = read_only(PixelFormat::RGBA8Unorm, size.0, size.1); let texture = buffer.new_texture(&descriptor, 0, pitch).unwrap(); - check_images(TEST, device, counted, 0, 1); + check_images(TEST, device, counted, 0, 0); assert!(blit_texels(&queue, &texture, size, 4) == fills[0][offset..offset + bytes]); for (at, several) in [(1, true), (2, false)] { let calls = Calls::default(); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs index fb8c712af..434f09e35 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs @@ -14,6 +14,12 @@ //! texture over it is rebound. The end mark reads 0 as each call returns. Afterwards every //! texture and buffer holds what Metal's holds: zero where new, the bytes it was made with, the //! bytes it lies over where it aliases, what a blit wrote. +//! - **Making waits for no submission's replay.** A command buffer whose deferred command buffers +//! take long to replay (`recorder`) and to submit is committed, and a `Private` texture made +//! `Private` texture: its move waits for a submission, so its making registers it, where a new +//! `Shared` texture's move is made on the host on a device with host image copies +//! (`texture/host_copy.rs`), registering nothing, whatever the order. One is made before, +//! untimed: a device's first texture making took 4 to 9 ms on RADV //! - **The zeros come before every use, on every queue** (the coordinator's conditions). A new //! `Private` buffer whose memory held other bytes is read through its address unnamed, and //! through its heap made resident, by a command buffer on another queue, after a command diff --git a/crates/metal2vulkan-validation/src/runtime_lane/first_use_writes.rs b/crates/metal2vulkan-validation/src/runtime_lane/first_use_writes.rs new file mode 100644 index 000000000..f847cb956 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/first_use_writes.rs @@ -0,0 +1,252 @@ +//! A CPU write to bytes of a texture over host pages that the texture's first use does not read +//! stays, on the device the cfg selects, under the validation layer: Metal never writes such +//! bytes, so it keeps every such write (an M3 Max probe: every CPU write between rows, and to +//! texels the command buffer did not read, stayed in each of 10 rounds). +//! +//! A texture that only reads (`ShaderRead` usage) is made over a no-copy buffer of anonymous pages +//! at each of [`LAYOUTS`] (a 1080p surface's packed rows, and a browser tile's padded ones), and +//! its first use is a pass whose draw reads it inside a scissor of the top half of its rows. Around +//! that command buffer's commit, another thread writes a byte of a texel in each row of the bottom +//! half, the byte after each such row's texels where the rows are padded, and bytes past the last +//! row: one row after another, [`SPACING`] apart, starting at each of [`STARTS`] from the commit +//! (a fresh texture each), so the writes cover the commit, the submission and the first use. Every +//! write stays, and the pass reads the texels of the top half as they were. A texture over host +//! pages is a shadow, whose first use copies the texels in and writes none of the pages' bytes; an +//! image bound to the pages would start `UNDEFINED`, and its first move, which Vulkan lets read +//! and write every byte it is bound to, could be kept only by writing the bytes back over such a +//! write. Printed (`FIRST-USE-WRITES`): per layout and start, the writes undone and the texels read +//! that differ. + +use super::host_memory::{counting, no_copy, not_importable, Mapping, GUEST_PAGE}; +use super::no_copy_textures::{floats, staged}; +use super::pitched_surfaces::reading; +use super::{validated_device, Messages, ScratchCache, WAIT}; +use crate::gpu::TEST_DEVICE; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan_runtime::{ + BlitOption, ClearColor, IoSurfacePlane, LoadAction, Origin, RenderPassDescriptor, + ResourceOptions, ScissorRect, Size, StoreAction, TextureDescriptor, +}; +use std::ptr::NonNull; +use std::time::{Duration, Instant}; + +/// A surface's `BGRA8Unorm` plane: its name, width, height and bytes per row. +const LAYOUTS: [(&str, u64, u64, u64); 2] = [ + ("1920x1080/7680", 1920, 1080, 7680), + ("1307x512/5248", 1307, 512, 5248), +]; + +/// When the writes start, in microseconds from the commit (before it where negative): the commit, +/// the submission and the first use take a time of their own on each device, so the writes start +/// at several times and some of them overlap each. +const STARTS: [i64; 6] = [-2000, -1000, -300, 0, 500, 2000]; + +/// The time between two rows' writes. +const SPACING: Duration = Duration::from_micros(4); + +/// The bytes past the last row the pages hold, and the CPU writes the first and last of. +const PAST: u64 = 64; + +/// The time before the first of a round's two steps (the commit, the writes' start). +const LEAD: Duration = Duration::from_millis(1); + +fn spin_until(at: Instant) { + while Instant::now() < at { + std::hint::spin_loop(); + } +} + +/// The pages' first byte, for the writing thread: the test keeps the mapping alive until the +/// thread is joined, and the bytes it writes are no other thread's. +#[derive(Clone, Copy)] +struct Pages(NonNull); + +// SAFETY: see the type's docs; the thread writes bytes no other thread reads or writes meanwhile. +unsafe impl Send for Pages {} + +#[test] +fn a_cpu_write_to_bytes_a_first_use_does_not_read_stays() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let mut lapses = Vec::new(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let reads = reading(&device, PixelFormat::BGRA8Unorm, "tob_read"); + let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); + 'layouts: for (name, w, h, bpr) in LAYOUTS { + let row = w * 4; + let bound = bpr * h; + let len = ((bound + PAST) as usize).next_multiple_of(GUEST_PAGE); + let top = h / 2; + // The bytes the thread writes, in order: a texel's in each row of the bottom half, the + // byte after the row's texels where the rows are padded, and bytes past the last row. + let mut targets = Vec::new(); + for y in top..h { + targets.push((y * bpr + (y % w) * 4) as usize); + if bpr > row { + targets.push((y * bpr + row) as usize); + } + } + targets.extend([bound as usize, (bound + PAST - 1) as usize]); + for start in STARTS { + let mapping = Mapping::anonymous(len); + let pages = counting(len, 7); + mapping.write(0, &pages); + // SAFETY: the mapping outlives the buffer and the texture (dropped first). + let made = unsafe { + no_copy( + &device, + mapping.pointer(), + len, + ResourceOptions::default(), + None, + ) + }; + let buffer = match made { + Ok(buffer) => buffer, + Err(error) if not_importable(&error) => { + eprintln!("FIRST-USE-WRITES: the device imports no host memory: {error:?}"); + break 'layouts; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, w, h, false); + d.usage = TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = buffer + .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, bpr, false)) + .unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + let form = match unsafe { texture.vk_image() } { + Some(_) => "aliased", + None => "shadowed", + }; + let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, w, h, false); + d.usage = TextureUsage::RENDER_TARGET; + d.resource_options = ResourceOptions::private(); + let target = device.new_texture(&d).unwrap(); + let read = device + .new_buffer(row * h, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&reads).unwrap(); + encoder + .set_scissor_rect(ScissorRect::new(0, 0, w, top)) + .unwrap(); + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + encoder.set_fragment_texture(Some(&texture), 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(w, h, 1), + &read, + 0, + row, + row * h, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + let expected: Vec = { + let mut expected = pages.clone(); + for &at in &targets { + expected[at] = pages[at] ^ 0xA5; + } + expected + }; + let base = Instant::now() + LEAD; + let shift = Duration::from_micros(start.unsigned_abs()); + let (writes_at, commit_at) = match start < 0 { + true => (base, base + shift), + false => (base + shift, base), + }; + let at = Pages(mapping.pointer()); + std::thread::scope(|scope| { + let (targets, expected) = (&targets, &expected); + let writer = scope.spawn(move || { + let pages = at; + spin_until(writes_at); + for (k, &byte) in targets.iter().enumerate() { + spin_until(writes_at + SPACING * k as u32); + // SAFETY: `byte` lies inside the mapping, which outlives the thread, + // and no other thread touches it meanwhile. + unsafe { pages.0.as_ptr().add(byte).write_volatile(expected[byte]) }; + } + }); + spin_until(commit_at); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + writer.join().unwrap(); + }); + assert_eq!(command_buffer.error(), None); + let now = mapping.read(0..len); + let undone: Vec = (targets.iter().copied()) + .filter(|&at| now[at] != expected[at]) + .collect(); + let changed = (0..len).filter(|&at| now[at] != expected[at]).count() - undone.len(); + let contents = read.contents().unwrap(); + // SAFETY: the buffer's `row * h` bytes, which no command writes any longer. + let got = + unsafe { std::slice::from_raw_parts(contents.as_ptr(), (row * h) as usize) }; + let differ = (0..top) + .flat_map(|y| (0..w).map(move |x| (y, x))) + .filter(|&(y, x)| { + let at = (y * bpr + x * 4) as usize; + let out = (y * row + x * 4) as usize; + got[out..out + 4] != pages[at..at + 4] + }) + .count(); + let what = format!("{name}, writes from {start} us of the commit"); + eprintln!( + "FIRST-USE-WRITES on {}: {what}: {form}: {} of {} writes undone, {changed} \ + other bytes changed, {differ} texels read differ", + device.name(), + undone.len(), + targets.len(), + ); + if let Some(&at) = undone.first() { + lapses.push(format!( + "{what}: {} of {} CPU writes undone, the first at byte {at}", + undone.len(), + targets.len() + )); + } + if changed != 0 { + lapses.push(format!("{what}: {changed} bytes no one wrote changed")); + } + if differ != 0 { + lapses.push(format!( + "{what}: {differ} texels of the top half read differ from the pages'" + )); + } + drop((texture, buffer, target, read)); + drop(mapping); + } + } + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); + assert!( + lapses.is_empty(), + "a first use undid a CPU write, or changed or misread bytes:\n{}", + lapses.join("\n") + ); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs index 1fa0c19c0..234c39c34 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs @@ -1,3 +1,418 @@ +//! What a guest's frame of render passes into its window's surface costs, on the device the cfg +//! selects: report only, in release builds. The surface is a 1920x1080 `BGRA8Unorm` IOSurface of +//! packed rows (7680 bytes) over anonymous pages, a `Managed` no-copy buffer over them and a +//! texture of its plane, each pass loading and storing it and blending three rectangles (the whole +//! surface, then two quarters). Printed per round and shape (`GUEST-FRAME`): the texture's form, +//! the medians and 90th percentiles of the frame's commit to completion (from the first commit to +//! the last command buffer's completion), its GPU time (each command buffer's `GPUEndTime` less +//! `GPUStartTime`, summed) and the process's CPU time, each busy thread's CPU time per frame (the +//! encoding thread, the recorder that replays its Vulkan commands, the scheduler, the queue's + +use super::host_memory::Mapping; +use super::no_copy_textures::{blending, floats, staged}; +use super::pitched_surfaces::{reading, sampler}; +use super::{validated_device_with, Messages, ScratchCache, WAIT}; +use crate::gpu::TEST_DEVICE; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, SamplerMinMagFilter, TextureUsage}; +use metal2vulkan_runtime::{ + Buffer, CommandBuffer, CpuCacheMode, Device, HazardTrackingMode, HostMemory, IoSurfacePlane, + LoadAction, Origin, RenderPassDescriptor, ResourceOptions, Size, StorageMode, StoreAction, + Texture, TextureDescriptor, WorkCounts, +}; +use std::time::Instant; + +const WARM: usize = 10; +const FRAMES: usize = 60; +/// The passes of a frame of several. +const PASSES: usize = 12; +const WIDTH: u64 = 1920; +const HEIGHT: u64 = 1080; +const ROW: u64 = WIDTH * 4; + +/// What a frame does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Shape { + /// One command buffer, one pass into the surface's texture. + Pass, + /// One command buffer, [`PASSES`] passes into the surface's texture, an encoder each. + Passes, + /// [`PASSES`] command buffers of one pass each into the surface's texture. + PassesApart, + /// As [`Shape::Pass`], into a `Private` texture of the surface's size: the pass alone. + PrivatePass, + /// As [`Shape::Passes`], into the `Private` texture: the passes alone. + PrivatePasses, + /// One command buffer: blits of the surface's bytes into the `Private` texture and of the + /// texture into a private buffer, [`PASSES`] passes into the texture, blits of the texture + /// into a second private buffer and of that into the surface's bytes: one shadow's copy in, + /// keep, changed copy and copy back for every pass of the command buffer. + SharedShadow, + /// The consumer's present: a new no-copy buffer and texture over the surface each frame, + /// sampled by one draw into a `Private` target, beside the buffer kept across frames. + Presented, +} + +const SHAPES: [Shape; 7] = [ + Shape::Pass, + Shape::PrivatePass, + Shape::Passes, + Shape::PassesApart, + Shape::PrivatePasses, + Shape::SharedShadow, + Shape::Presented, +]; + +fn process_cpu_us() -> f64 { + let mut now = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: `now` is a valid timespec for the call to fill. + let read = unsafe { libc::clock_gettime(libc::CLOCK_PROCESS_CPUTIME_ID, &mut now) }; + assert_eq!(read, 0, "the process's CPU clock"); + now.tv_sec as f64 * 1e6 + now.tv_nsec as f64 / 1e3 +} + +/// Each thread of the process: its id, its name (Linux keeps 15 bytes of it) and the CPU time it +/// ran, in microseconds. +fn thread_cpu_us() -> Vec<(i32, String, f64)> { + let mut threads = Vec::new(); + for task in std::fs::read_dir("/proc/self/task").unwrap().flatten() { + let Some(tid) = task + .file_name() + .to_str() + .and_then(|n| n.parse::().ok()) + else { + continue; + }; + let name = std::fs::read_to_string(task.path().join("comm")).unwrap_or_default(); + // The clock of one thread's CPU time: `MAKE_THREAD_CPUCLOCK(tid, CPUCLOCK_SCHED)`. + let clock = (!tid << 3) | 6; + let mut now = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: `now` is a valid timespec for the call to fill; a thread gone meanwhile fails + // the call, and is left out. + if unsafe { libc::clock_gettime(clock, &mut now) } == 0 { + let us = now.tv_sec as f64 * 1e6 + now.tv_nsec as f64 / 1e3; + threads.push((tid, name.trim().to_owned(), us)); + } + } + threads +} + +/// The CPU time per frame each thread ran from `before` to `after` (of [`thread_cpu_us`]), by +/// name, the calling thread's as `encoding`, the busiest first, those under 1 us a frame left out. +fn threads_per_frame(before: &[(i32, String, f64)], after: &[(i32, String, f64)]) -> String { + // SAFETY: no precondition. + let me = unsafe { libc::gettid() }; + let mut by_name: Vec<(String, f64)> = Vec::new(); + for (tid, name, us) in after { + let start = before + .iter() + .find(|(had, _, _)| had == tid) + .map_or(0.0, |(_, _, us)| *us); + let name = match *tid == me { + true => "encoding".to_owned(), + false => name.clone(), + }; + let ran = (us - start) / FRAMES as f64; + match by_name.iter_mut().find(|(known, _)| *known == name) { + Some((_, total)) => *total += ran, + None => by_name.push((name, ran)), + } + } + by_name.sort_by(|a, b| b.1.total_cmp(&a.1)); + let busy: Vec = (by_name.iter()) + .filter(|(_, us)| *us >= 1.0) + .map(|(name, us)| format!("{name} {us:.0}")) + .collect(); + busy.join(", ") +} + +fn median_p90(mut values: Vec) -> (f64, f64) { + values.sort_by(f64::total_cmp); + let at = |p: usize| values[(values.len() * p / 100).min(values.len() - 1)]; + (at(50), at(90)) +} + +fn managed() -> ResourceOptions { + ResourceOptions::new( + StorageMode::Managed, + CpuCacheMode::DefaultCache, + HazardTrackingMode::Default, + ) +} + +/// A `Managed` no-copy buffer over `mapping`'s first `len` bytes. +fn surface_buffer(device: &Device, mapping: &Mapping, len: usize) -> Buffer { + // SAFETY: the mapping outlives every buffer over it (the test drops them first). + let memory = unsafe { HostMemory::new(mapping.pointer()) }; + // SAFETY: as above. + unsafe { device.new_buffer_with_bytes_no_copy(memory, len as u64, managed(), None) }.unwrap() +} + +fn plane_texture(buffer: &Buffer, usage: TextureUsage) -> Texture { + let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false); + d.usage = usage; + d.resource_options = buffer.resource_options(); + buffer + .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, ROW, false)) + .unwrap() +} + +fn form_of(texture: &Texture) -> &'static str { + // SAFETY: the handle is only compared, while the texture lives. + match unsafe { texture.vk_image() }.is_some() { + true => "aliased", + false => "shadowed", + } +} + +/// What a pass draws. +struct Drawing { + blend: metal2vulkan_runtime::RenderPipelineState, + rects: [Buffer; 3], + color: Buffer, +} + +impl Drawing { + fn pass(&self, command_buffer: &CommandBuffer, texture: &Texture) { + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(texture.clone()); + attachment.load_action = LoadAction::Load; + attachment.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&self.blend).unwrap(); + encoder + .set_fragment_buffer(Some(&self.color), 0, 0) + .unwrap(); + for rect in &self.rects { + encoder.set_vertex_buffer(Some(rect), 0, 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + } + encoder.end_encoding().unwrap(); + } +} + +fn per_frame(before: &WorkCounts, after: &WorkCounts) -> String { + let per = |f: fn(&WorkCounts) -> u64| (f(after) - f(before)) as f64 / FRAMES as f64; + format!( + "vkQueueSubmit {:.2}, command buffers {:.2}, internal submissions {:.2}, shadows made \ + {:.2}, zeroed {:.2}, shadow copies {:.2}, texels in {:.0}, back {:.0}, copies back \ dispatched {:.2}, copies in dispatched {:.2}, merge copies dispatched {:.2}, merge \ + per(|c| c.queue_submissions), + per(|c| c.command_buffers_submitted), + per(|c| c.internal_submissions), + per(|c| c.shadowed_textures), + per(|c| c.shadows_zeroed), + per(|c| c.shadow_copies), + per(|c| c.shadow_texels_copied_in), + per(|c| c.shadow_texels_copied_back), + per(|c| c.shadow_copies_back_dispatched), per(|c| c.shadow_copies_in_dispatched), + per(|c| c.shadow_merge_copies_dispatched), + per(|c| c.shadow_merge_scratches_reused), + per(|c| c.shadow_merge_scratches_zeroed), per(|c| c.owned_descriptor_pools), + ) +} + +/// The guest's frames over its window's surface, each [`Shape`] on a device of its own, +/// interleaved in two rounds. +#[test] +#[ignore = "a release-mode measurement: run by name"] +fn guest_frame_costs() { + let len = ((ROW * HEIGHT) as usize).next_multiple_of(16384); + let mapping = Mapping::anonymous(len); + for round in 0..2 { + for shape in SHAPES { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |o| { + o.layers.clear(); + }) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let drawing = Drawing { + blend: blending(&device, PixelFormat::BGRA8Unorm), + rects: [ + staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])), + staged(&device, &floats([-1.0, -1.0, 0.0, 0.0])), + staged(&device, &floats([0.0, 0.0, 1.0, 1.0])), + ], + color: staged(&device, &floats([0.25, 0.5, 0.75, 0.5])), + }; + let read = reading(&device, PixelFormat::BGRA8Unorm, "tob_sample"); + let nearest = sampler(&device, SamplerMinMagFilter::Nearest); + let mut d = + TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::private(); + let private = device.new_texture(&d).unwrap(); + let size = ROW * HEIGHT; + let scratches = [ + device.new_buffer(size, ResourceOptions::private()).unwrap(), + device.new_buffer(size, ResourceOptions::private()).unwrap(), + ]; + let kept = surface_buffer(&device, &mapping, len); + let surface = plane_texture( + &kept, + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + ); + let mut form = match shape { + Shape::PrivatePass | Shape::PrivatePasses | Shape::SharedShadow => "private", + _ => form_of(&surface), + }; + let (mut waits, mut gpus, mut cpus) = (Vec::new(), Vec::new(), Vec::new()); + let mut before = device.work_counts(); + let mut threads = thread_cpu_us(); + for k in 0..WARM + FRAMES { + if k == WARM { + before = device.work_counts(); + threads = thread_cpu_us(); + } + let cpu = process_cpu_us(); + let mut command_buffers = vec![queue.command_buffer().unwrap()]; + let mut presented = None; + match shape { + Shape::Pass => drawing.pass(&command_buffers[0], &surface), + Shape::PrivatePass => drawing.pass(&command_buffers[0], &private), + Shape::Passes => { + for _ in 0..PASSES { + drawing.pass(&command_buffers[0], &surface); + } + } + Shape::PrivatePasses => { + for _ in 0..PASSES { + drawing.pass(&command_buffers[0], &private); + } + } + Shape::PassesApart => { + drawing.pass(&command_buffers[0], &surface); + for _ in 1..PASSES { + let command_buffer = queue.command_buffer().unwrap(); + drawing.pass(&command_buffer, &surface); + command_buffers.push(command_buffer); + } + } + Shape::SharedShadow => { + let command_buffer = &command_buffers[0]; + let at = Origin::new(0, 0, 0); + let extent = Size::new(WIDTH, HEIGHT, 1); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_texture( + &kept, + 0, + ROW, + size, + extent, + &private, + 0, + 0, + at, + metal2vulkan_runtime::BlitOption::None, + ) + .unwrap(); + blit.copy_from_texture_to_buffer( + &private, + 0, + 0, + at, + extent, + &scratches[0], + 0, + ROW, + size, + metal2vulkan_runtime::BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + for _ in 0..PASSES { + drawing.pass(command_buffer, &private); + } + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &private, + 0, + 0, + at, + extent, + &scratches[1], + 0, + ROW, + size, + metal2vulkan_runtime::BlitOption::None, + ) + .unwrap(); + blit.copy_from_buffer_to_buffer(&scratches[1], 0, &kept, 0, size) + .unwrap(); + blit.end_encoding().unwrap(); + } + Shape::Presented => { + let buffer = surface_buffer(&device, &mapping, len); + let texture = plane_texture(&buffer, TextureUsage::SHADER_READ); + form = form_of(&texture); + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(private.clone()); + attachment.load_action = LoadAction::Clear; + attachment.store_action = StoreAction::Store; + let mut encoder = command_buffers[0].render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&read).unwrap(); + encoder + .set_vertex_buffer(Some(&drawing.rects[0]), 0, 0) + .unwrap(); + encoder + .set_fragment_sampler_state(Some(&nearest), 0) + .unwrap(); + encoder.set_fragment_texture(Some(&texture), 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + presented = Some((texture, buffer)); + } + } + let committed = Instant::now(); + for command_buffer in &command_buffers { + command_buffer.commit().unwrap(); + } + let last = command_buffers.last().unwrap(); + last.wait_until_completed_for(WAIT).unwrap(); + let waited = committed.elapsed().as_secs_f64() * 1e6; + if k >= WARM { + waits.push(waited); + let mut gpu = 0.0; + for command_buffer in &command_buffers { + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + gpu += command_buffer.gpu_end_time().unwrap() + - command_buffer.gpu_start_time().unwrap(); + } + gpus.push(gpu * 1e6); + cpus.push(process_cpu_us() - cpu); + } + drop(presented); + } + let after = device.work_counts(); + let threads = threads_per_frame(&threads, &thread_cpu_us()); + let (wait, wait90) = median_p90(waits); + let (gpu, gpu90) = median_p90(gpus); + let (cpu, cpu90) = median_p90(cpus); + println!( + "GUEST-FRAME on {}: round {round}, {shape:?}: the texture {form}; commit to \ + completion {wait:.0} us (p90 {wait90:.0}), GPU {gpu:.0} us (p90 {gpu90:.0}), \ + process CPU {cpu:.0} us (p90 {cpu90:.0}); threads' CPU per frame (us): \ + {threads}; per frame: {}", + device.name(), + per_frame(&before, &after), + ); + drop((surface, kept, private, scratches)); + } + } +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/linear_attachments.rs b/crates/metal2vulkan-validation/src/runtime_lane/linear_attachments.rs index 49df4ea87..41ae24329 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/linear_attachments.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/linear_attachments.rs @@ -1,24 +1,31 @@ //! Device tests of render passes over linear images on the device the cfg selects, under the -//! validation layer. A render target over a no-copy buffer's host pages is its own linear image -//! where the device renders one there; on a device that does so only by -//! `VK_NV_linear_color_attachment` (NVIDIA's, whose linear tiling has the extension's bit and not -//! the color attachment feature: [`by_the_rule`]), the runtime enables the extension and renders -//! it in place, but only where every color attachment of the render pass instance is linear, as -//! the extension rules. A pass beside a private attachment, and a multisampled pass resolving into -//! it, render it through an image of the runtime's, copied in and back, and announce -//! `linear-attachment-copies` ([`LINEAR_COPIES`]) once a device. Elsewhere nothing is announced. +//! validation layer. A render target over a `Shared` buffer of the runtime's memory is its own +//! linear image where the device renders one there ([`surface`]), as on every device that renders +//! one only by the rule below; one over a no-copy buffer's host pages is a shadow on every device +//! (`shadowed-texture`), which the detach, rebind and shadow tests take ([`host_surface`]). On a +//! device that renders a linear image only by `VK_NV_linear_color_attachment` (NVIDIA's, whose +//! linear tiling has the extension's bit and not the color attachment feature: [`by_the_rule`]), +//! the runtime enables the extension and renders it in place, but only where every color attachment +//! of the render pass instance is linear, as the extension rules. A pass beside a private +//! attachment, and a multisampled pass resolving into it, render it through an image of the +//! runtime's, copied in and back, and announce `linear-attachment-copies` ([`LINEAR_COPIES`]) once +//! a device. Elsewhere nothing is announced. //! -//! - [`a_render_target_over_host_pages_renders_in_place`]: a 256x64 `BGRA8Unorm` render target -//! over a no-copy buffer is aliased where the device renders by the rule, and a pass that loads -//! it alone renders it in place, announcing nothing; one that clears it announces -//! `linear-attachment-clear-copies` exactly where it is aliased by the rule; the pages hold what -//! each pass stored. +//! - [`a_cleared_render_target_over_a_shared_buffer_renders_through_copies`]: a 256x64 +//! `BGRA8Unorm` render target over a `Shared` buffer, aliased; a pass of it alone that loads it +//! and draws nothing changes no texel and records nothing, counted neither way; one that clears +//! it renders it through copies and announces `linear-attachment-clear-copies`, by the rule +//! (counted so); the buffer holds what each pass stored. +//! - [`a_render_target_over_host_pages_is_a_shadow`]: a 256x64 `BGRA8Unorm` render target over a +//! no-copy buffer is a shadow, never an image bound to the pages; a pass of it alone that loads +//! it and one that clears it each leave the pages holding what it stored, and neither announces +//! a linear attachment's copies. //! - [`a_linear_attachment_beside_a_private_one_renders_through_copies`]: a pass of that texture //! (loaded and stored) beside a private one (cleared), then one clearing the texture and -//! loading the private one: the pages keep their bytes, then hold the clear, the private texture +//! loading the private one: the buffer keeps its bytes, then holds the clear, the private texture //! the other way round; announced exactly where the texture is aliased by the rule. //! - [`a_resolve_into_a_linear_texture_resolves_through_a_scratch`]: a 4-sample private -//! attachment cleared and resolved into the texture: the pages hold the clear; announced +//! attachment cleared and resolved into the texture: the buffer holds the clear; announced //! exactly where the texture is aliased by the rule. //! //! Where the rule lets a pass render the texture in place, the pass still chooses as it ends @@ -37,9 +44,9 @@ //! - [`blends_over_most_of_a_linear_texture_render_in_place`]: three blended draws, the left half, //! the right half and the whole, unscissored: in place. //! - [`scissored_blends_over_a_corner_render_in_place`]: one blended full-viewport draw through a -//! 64x32 scissor: in place, and the pages past the scissor keep their bytes. +//! 64x32 scissor: in place, and the bytes past the scissor keep theirs. //! - [`a_blend_over_most_of_it_inside_a_box_renders_in_place`]: two blended draws through a -//! 192x48 scissor: in place, and the pages past the box keep their bytes. +//! 192x48 scissor: in place, and the bytes past the box keep theirs. //! - [`a_blend_with_no_depth_or_stencil_renders_the_linear_texture_in_place`], //! [`a_blend_beside_a_depth_attachment_renders_the_linear_texture_apart`] and //! [`a_blend_beside_a_stencil_attachment_renders_the_linear_texture_apart`]: one blended @@ -60,7 +67,7 @@ //! [`a_cleared_pass_sampling_its_surface_after_a_barrier_renders_in_place`] and //! [`a_pass_apart_sampling_its_surface_after_a_barrier_reads_its_draws`] (loaded and cleared): //! a panel, a render-target barrier, then a draw sampling the surface's own texture at its -//! pixel: the pages hold the private texture's pass. A cleared one renders in place (a command +//! pixel: the buffer holds the private texture's pass. A cleared one renders in place (a command //! of it may read the bytes); one apart is split at the barrier, merged and copied in again. //! Where the device renders the texture's own image as any other, the pass alone records its //! instances inline (`render/inline_first.rs`, `render/inline_splits.rs`), counted. @@ -136,10 +143,38 @@ fn by_the_rule(device: &Device) -> bool { && !linear.contains(FormatFeatureFlags2::COLOR_ATTACHMENT) } -/// A no-copy buffer over a new mapping of the texture's bytes, which hold `counting` from -/// `start`, and a `BGRA8Unorm` render target over it; `None`, printed, where the device imports -/// no host memory. -fn surface(device: &Device, start: usize) -> Option<(Mapping, Buffer, Texture)> { +/// The bytes of a `Shared` buffer, which the CPU reads and writes through its contents. +struct Contents(Buffer); + +impl Contents { + /// Bytes `range` of the buffer. + fn read(&self, range: std::ops::Range) -> Vec { + assert!(range.end as u64 <= self.0.length()); + let contents = self.0.contents().unwrap(); + // SAFETY: inside the buffer's length; the tests read once the commands writing it + // completed. + unsafe { std::slice::from_raw_parts(contents.as_ptr().add(range.start), range.len()) } + .to_vec() + } + + /// Write `bytes` at byte `at` of the buffer. + fn write(&self, at: usize, bytes: &[u8]) { + assert!((at + bytes.len()) as u64 <= self.0.length()); + let contents = self.0.contents().unwrap(); + // SAFETY: inside the buffer's length; no command reads or writes these bytes meanwhile + // (a pass running meanwhile writes others). + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr().add(at), bytes.len()) + }; + } +} + +/// A `Shared` buffer of the runtime's memory whose bytes hold `counting` from `start`, and a +/// `BGRA8Unorm` render target over it, its rows packed: the texture's own linear image where the +/// device makes one there, and always on a device that renders one only by +/// `VK_NV_linear_color_attachment`'s rule ([`by_the_rule`]), so each pass over it there takes the +/// rule's in place or apart way, counted (`WorkCounts::linear_passes_in_place`, `_through_copies`). +fn surface(device: &Device, start: usize) -> (Contents, Buffer, Texture) { surface_of(device, start, W, H) } @@ -149,6 +184,38 @@ fn surface_of( start: usize, width: u64, height: u64, +) -> (Contents, Buffer, Texture) { + let n = (width * height * TEXEL) as usize; + let buffer = device + .new_buffer(n as u64, ResourceOptions::shared()) + .unwrap(); + let contents = Contents(buffer.clone()); + contents.write(0, &counting(n, start)); + let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, width, height, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, 0, width * TEXEL).unwrap(); + assert!( + !by_the_rule(device) || aliased(&texture), + "a render target over a Shared buffer is no linear image on a device that renders one by \ + the rule" + ); + (contents, buffer, texture) +} + +/// A no-copy buffer over a new mapping of the texture's bytes, which hold `counting` from +/// `start`, and a `BGRA8Unorm` render target over it, a shadow; `None`, printed, where the device +/// imports no host memory. +fn host_surface(device: &Device, start: usize) -> Option<(Mapping, Buffer, Texture)> { + host_surface_of(device, start, W, H) +} + +/// [`host_surface`] of `width` and `height`. +fn host_surface_of( + device: &Device, + start: usize, + width: u64, + height: u64, ) -> Option<(Mapping, Buffer, Texture)> { let n = (width * height * TEXEL) as usize; let len = n.next_multiple_of(GUEST_PAGE); @@ -430,8 +497,8 @@ fn differing(pages: &[u8], expected: &[u8], scissor: Option) -> Str /// The differing bytes [`differing`] lists. const FIRST_DIFFERING: usize = 32; -/// [`blend_pass`] over a render target over host pages (counting from `start`), twice, each time -/// over fresh pages: the pages hold what the same pass leaves in a private texture of the same +/// [`blend_pass`] over a render target over a `Shared` buffer (counting from `start`), twice, each +/// time over a fresh one: its bytes hold what the same pass leaves in a private texture of the same /// bytes, and the bytes past `scissor` keep theirs. Where the texture is aliased by the rule both /// render in place, announcing nothing; elsewhere no pass counts a way. fn blends_over_the_pages(start: usize, scissor: Option, corners: &[[f32; 4]]) { @@ -440,9 +507,7 @@ fn blends_over_the_pages(start: usize, scissor: Option, corners: &[ let before = device.work_counts(); let mut rule = false; for _ in 0..2 { - let Some((mapping, buffer, texture)) = surface(device, start) else { - return; - }; + let (contents, buffer, texture) = surface(device, start); rule = by_the_rule(device) && aliased(&texture); println!( "LINEAR-ATTACHMENT blended over on {}: scissor {scissor:?}, {} draws, by the rule \ @@ -456,7 +521,7 @@ fn blends_over_the_pages(start: usize, scissor: Option, corners: &[ let bytes = counting(n, start); let expected = reference(&queue, &pipeline, &bytes, scissor, corners, None); blend_pass(&queue, &pipeline, &texture, scissor, corners, None); - let pages = mapping.read(0..n); + let pages = contents.read(0..n); assert!( pages == expected, "the pages differ from the private texture's pass: {}", @@ -473,7 +538,7 @@ fn blends_over_the_pages(start: usize, scissor: Option, corners: &[ assert_eq!(changed, 0, "bytes past the scissor changed"); } drop((texture, buffer)); - drop(mapping); + drop(contents); } assert_eq!( ways(device, &before), @@ -516,21 +581,19 @@ fn a_blend_over_most_of_it_inside_a_box_renders_in_place() { blends_over_the_pages(17, Some(ScissorRect::new(32, 8, 192, 48)), &[WHOLE, WHOLE]); } -/// One blended full-viewport draw over a render target over host pages (counting from `start`), -/// which the pass loads and stores, beside a private depth or stencil attachment of `beside`'s -/// format where given (cleared, not stored, not tested): the pages hold what the same pass leaves -/// in a private texture of the same bytes. Where the texture is aliased by the rule, a pass with a -/// depth or stencil attachment renders it apart, announcing `linear-attachment-copies` with a -/// reason naming the attachment, as NVIDIA's hardware renders a linear color only with neither -/// (an RTX 3090 lost the device on such a pass in place: EV `ZIN2-lc3-nvidia`); the pass with -/// neither renders it in place, announcing nothing. Each case runs in its own test, so a device -/// lost in one leaves the others theirs. +/// One blended full-viewport draw over a render target over a `Shared` buffer (counting from +/// `start`), which the pass loads and stores, beside a private depth or stencil attachment of +/// `beside`'s format where given (cleared, not stored, not tested): its bytes hold what the same +/// pass leaves in a private texture of the same bytes. Where the texture is aliased by the rule, a +/// pass with a depth or stencil attachment renders it apart, announcing `linear-attachment-copies` +/// with a reason naming the attachment, as NVIDIA's hardware renders a linear color only with +/// neither (an RTX 3090 lost the device on such a pass in place); the pass +/// with neither renders it in place, announcing nothing. Each case runs in its own test, so a +/// device lost in one leaves the others theirs. fn blend_beside(start: usize, beside: Option) { on_device(|device, messages| { messages.take_notices(); - let Some((mapping, buffer, texture)) = surface(device, start) else { - return; - }; + let (contents, buffer, texture) = surface(device, start); let rule = by_the_rule(device) && aliased(&texture); println!( "LINEAR-ATTACHMENT blended beside {beside:?} on {}: aliased by the rule {rule}", @@ -542,8 +605,18 @@ fn blend_beside(start: usize, beside: Option) { let bytes = counting(n, start); let expected = reference(&queue, &pipeline, &bytes, None, &[WHOLE], beside); messages.take_notices(); + let before = device.work_counts(); blend_pass(&queue, &pipeline, &texture, None, &[WHOLE], beside); - let pages = mapping.read(0..n); + assert_eq!( + ways(device, &before), + match (rule, beside.is_some()) { + (true, false) => (1, 0), + (true, true) => (0, 1), + (false, _) => (0, 0), + }, + "the pass's way, in place and through copies" + ); + let pages = contents.read(0..n); let differ = (0..n).filter(|&i| pages[i] != expected[i]).count(); println!("LINEAR-ATTACHMENT blended beside {beside:?}: {differ} bytes differ"); assert_eq!( @@ -572,7 +645,7 @@ fn blend_beside(start: usize, beside: Option) { "the reason names {named}: {reasons:?}" ); drop((texture, buffer)); - drop(mapping); + drop(contents); }); } @@ -817,9 +890,7 @@ fn colorless_clip(start: usize, stencil: bool) { let states = panel_and_clip(device, stencil); let mut rule = false; for _ in 0..2 { - let Some((mapping, buffer, texture)) = surface(device, start) else { - return; - }; + let (contents, buffer, texture) = surface(device, start); rule = by_the_rule(device) && aliased(&texture); println!( "LINEAR-ATTACHMENT a colorless clip past the blends on {}: stencil {stencil}, by \ @@ -840,13 +911,13 @@ fn colorless_clip(start: usize, stencil: bool) { "the clip zeroes the color" ); zeroing_pass(&queue, &states, &texture, stencil); - let pages = mapping.read(0..n); + let pages = contents.read(0..n); let differ = (0..n / 4) .filter(|&t| pages[t * 4..t * 4 + 4] != expected[t * 4..t * 4 + 4]) .count(); assert_eq!(differ, 0, "texels differ from the private texture's pass"); drop((texture, buffer)); - drop(mapping); + drop(contents); } assert_eq!( ways(device, &before), @@ -890,20 +961,18 @@ const MARK: u8 = 0xab; /// writes. const LAYERS: usize = 600; -/// A loaded pass over a [`WIDE`] render target over host pages (counting from `start`), beside a -/// stencil attachment where `stencil`, of [`LAYERS`] blended rounded panels through a scissor -/// that leaves out the last [`UNDRAWN`] rows, in a command buffer that signals a shared event -/// before it: once the event is signalled the CPU writes [`MARK`] over those rows, which the +/// A loaded pass over a [`WIDE`] render target over a `Shared` buffer (counting from `start`), +/// beside a stencil attachment where `stencil`, of [`LAYERS`] blended rounded panels through a +/// scissor that leaves out the last [`UNDRAWN`] rows, in a command buffer that signals a shared +/// event before it: once the event is signalled the CPU writes [`MARK`] over those rows, which the /// pass never writes, while the pass runs (the more likely the longer it runs). Metal keeps what /// the CPU wrote there, as it stores no tile no draw reaches; so does the pass in place and apart, -/// merged (a copy back of the area would put the rows' old bytes back where the write landed -/// after its copy in). Every other byte -/// holds what the same pass leaves in a private texture of the same bytes. +/// merged (a copy back of the area would put the rows' old bytes back where the write landed after +/// its copy in). Every other byte holds what the same pass leaves in a private texture of the same +/// bytes. fn cpu_write(start: usize, stencil: bool) { on_device(|device, _| { - let Some((mapping, buffer, texture)) = surface_of(device, start, WIDE[0], WIDE[1]) else { - return; - }; + let (contents, buffer, texture) = surface_of(device, start, WIDE[0], WIDE[1]); let rule = by_the_rule(device) && aliased(&texture); println!( "LINEAR-ATTACHMENT a CPU write during the pass on {}: stencil {stencil}, by the rule \ @@ -956,6 +1025,7 @@ fn cpu_write(start: usize, stencil: bool) { let rows = (drawn * w * TEXEL) as usize..n; expected[rows.clone()].fill(MARK); let event = device.new_shared_event().unwrap(); + let before = device.work_counts(); let command_buffer = queue.command_buffer().unwrap(); command_buffer .encode_signal_event(EventRef::from(&event), 1) @@ -964,10 +1034,10 @@ fn cpu_write(start: usize, stencil: bool) { command_buffer.commit().unwrap(); let signalled = event.wait_until_signaled_value(1, WAIT); std::thread::sleep(Duration::from_millis(1)); - mapping.write(rows.start, &vec![MARK; rows.len()]); + contents.write(rows.start, &vec![MARK; rows.len()]); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.error(), None); - let pages = mapping.read(0..n); + let pages = contents.read(0..n); let kept = pages[rows.clone()].iter().filter(|&&b| b == MARK).count(); println!( "LINEAR-ATTACHMENT a CPU write during the pass: signalled {signalled}, {kept} of {} \ @@ -975,6 +1045,15 @@ fn cpu_write(start: usize, stencil: bool) { rows.len() ); assert!(signalled, "the event was not signalled"); + assert_eq!( + ways(device, &before), + match (rule, stencil) { + (true, false) => (1, 0), + (true, true) => (0, 1), + (false, _) => (0, 0), + }, + "the pass's way, in place and through copies" + ); assert_eq!(kept, rows.len(), "the pass wrote rows no draw reaches"); let differ = (0..n).filter(|&i| pages[i] != expected[i]).count(); assert_eq!( @@ -982,7 +1061,7 @@ fn cpu_write(start: usize, stencil: bool) { "the pages differ from the private texture's pass" ); drop((texture, buffer)); - drop(mapping); + drop(contents); }); } @@ -1060,21 +1139,19 @@ fn sampling_pass( assert_eq!(command_buffer.error(), None); } -/// [`sampling_pass`] over a [`WIDE`] render target over host pages (counting from `start`), and -/// over a private texture of the same bytes: the pages hold the private texture's texels, so the -/// draw after the barrier read the panel the pass drew. Where the texture is aliased by the rule -/// the pass renders in place, loaded or cleared (a command of it may read the texture's bytes, +/// [`sampling_pass`] over a [`WIDE`] render target over a `Shared` buffer (counting from `start`), +/// and over a private texture of the same bytes: its bytes hold the private texture's texels, so +/// the draw after the barrier read the panel the pass drew. Where the texture is aliased by the +/// rule the pass renders in place, loaded or cleared (a command of it may read the texture's bytes, /// so no clear is copied), announcing no `linear-attachment-clear-copies`; beside a stencil -/// attachment apart, split at the barrier: the stand-in merged back (or, cleared, copied back) -/// and copied in again before the reading draw. Where the device renders the texture's own -/// image as any other, the pass alone records both its instances inline, the reading draw's -/// after the split (`WorkCounts::inline_split_instances`). +/// attachment apart, split at the barrier: the stand-in merged back (or, cleared, copied back) and +/// copied in again before the reading draw. Where the device renders the texture's own image as any +/// other, the pass alone records both its instances inline, the reading draw's after the split +/// (`WorkCounts::inline_split_instances`). fn sampling(start: usize, load: LoadAction, stencil: bool) { on_device(|device, messages| { messages.take_notices(); - let Some((mapping, buffer, texture)) = surface_of(device, start, WIDE[0], WIDE[1]) else { - return; - }; + let (contents, buffer, texture) = surface_of(device, start, WIDE[0], WIDE[1]); let rule = by_the_rule(device) && aliased(&texture); let inline = aliased(&texture) && !by_the_rule(device) && !stencil; println!( @@ -1111,7 +1188,7 @@ fn sampling(start: usize, load: LoadAction, stencil: bool) { }, "passes inline, of them split, and instances after a split inline" ); - let pages = mapping.read(0..n); + let pages = contents.read(0..n); let differ = (0..n / 4) .filter(|&t| pages[t * 4..t * 4 + 4] != expected[t * 4..t * 4 + 4]) .count(); @@ -1129,7 +1206,7 @@ fn sampling(start: usize, load: LoadAction, stencil: bool) { let notices = counts(&messages.take_notices()); assert_eq!(notices.get(&Degradation::LinearAttachmentClearCopies), None); drop((texture, buffer)); - drop(mapping); + drop(contents); }); } @@ -1248,7 +1325,7 @@ fn detached_in_an_open_pass( fn a_detach_while_a_pass_over_host_pages_is_open_fails_its_command_buffer() { on_device(|device, messages| { messages.take_notices(); - let Some((mapping, buffer, texture)) = surface_of(device, 59, WIDE[0], WIDE[1]) else { + let Some((mapping, buffer, texture)) = host_surface_of(device, 59, WIDE[0], WIDE[1]) else { return; }; let n = (WIDE[0] * WIDE[1] * TEXEL) as usize; @@ -1316,7 +1393,7 @@ fn a_detach_while_a_pass_in_a_no_copy_heap_is_open_fails_its_command_buffer() { #[test] fn a_rebind_while_a_pass_over_host_pages_is_open_is_refused() { on_device(|device, _| { - let Some((mapping, buffer, texture)) = surface(device, 61) else { + let Some((mapping, buffer, texture)) = host_surface(device, 61) else { return; }; let queue = device.new_command_queue().unwrap(); @@ -1347,41 +1424,50 @@ fn a_rebind_while_a_pass_over_host_pages_is_open_is_refused() { }); } -/// A render target over host pages is aliased where the device renders it by the rule, and a -/// pass of it alone renders it in place: nothing announced, the pages hold what it stored. +/// A render target over a `Shared` buffer is aliased, and on a device that renders it by the rule +/// a pass of it alone that loads it and draws nothing changes no texel, so it records nothing +/// (`render/untouched.rs`) and is counted neither way, announcing nothing; one that clears it +/// renders it through copies, announcing `linear-attachment-clear-copies` once, counted so. The +/// buffer holds what each stored. #[test] -fn a_render_target_over_host_pages_renders_in_place() { +fn a_cleared_render_target_over_a_shared_buffer_renders_through_copies() { on_device(|device, messages| { messages.take_notices(); - let Some((mapping, buffer, texture)) = surface(device, 3) else { - return; - }; + let (contents, buffer, texture) = surface(device, 3); let rule = by_the_rule(device); let form = aliased(&texture); println!( - "LINEAR-ATTACHMENT on {}: by the rule {rule}, aliased {form}", + "LINEAR-ATTACHMENT over a Shared buffer on {}: by the rule {rule}, aliased {form}", device.name() ); - assert!( - !rule || form, - "a render target over host pages is shadowed by the rule" - ); let queue = device.new_command_queue().unwrap(); let n = (W * H * TEXEL) as usize; + let before = device.work_counts(); pass(&queue, &[(&texture, LoadAction::Load, None)]); + assert_eq!( + ways(device, &before), + (0, 0), + "a pass that loads the texture and draws nothing, in place and through copies" + ); assert!( - mapping.read(0..n) == counting(n, 3), - "a load and store changed the pages" + contents.read(0..n) == counting(n, 3), + "a load and store changed the buffer" ); assert_eq!( announced(messages, Degradation::LinearAttachmentClearCopies), 0, "a pass that loads the texture" ); + let before = device.work_counts(); pass(&queue, &[(&texture, LoadAction::Clear, None)]); + assert_eq!( + ways(device, &before), + (0, u64::from(rule)), + "a pass that clears the texture, in place and through copies" + ); assert!( - mapping.read(0..n) == cleared(), - "a clear did not reach the pages" + contents.read(0..n) == cleared(), + "a clear did not reach the buffer" ); let notices = counts(&messages.take_notices()); let count = |kind| notices.get(&kind).copied().unwrap_or(0); @@ -1392,8 +1478,55 @@ fn a_render_target_over_host_pages_renders_in_place() { ); assert_eq!( count(Degradation::LinearAttachmentClearCopies), - usize::from(rule && form), - "a pass that clears the texture, once a device where it is aliased by the rule" + usize::from(rule), + "a pass that clears the texture, once a device that renders it by the rule" + ); + drop((texture, buffer)); + drop(contents); + }); +} + +/// A render target over host pages is a shadow on every device, never an image bound to the +/// pages: a pass of it alone that loads it and one that clears it each leave the pages holding +/// what it stored, and neither announces a linear attachment's copies. +#[test] +fn a_render_target_over_host_pages_is_a_shadow() { + on_device(|device, messages| { + messages.take_notices(); + let Some((mapping, buffer, texture)) = host_surface(device, 3) else { + return; + }; + println!( + "LINEAR-ATTACHMENT on {}: by the rule {}, aliased {}", + device.name(), + by_the_rule(device), + aliased(&texture) + ); + assert!( + !aliased(&texture), + "a render target over host pages is an image bound to them" + ); + let queue = device.new_command_queue().unwrap(); + let n = (W * H * TEXEL) as usize; + pass(&queue, &[(&texture, LoadAction::Load, None)]); + assert!( + mapping.read(0..n) == counting(n, 3), + "a load and store changed the pages" + ); + pass(&queue, &[(&texture, LoadAction::Clear, None)]); + assert!( + mapping.read(0..n) == cleared(), + "a clear did not reach the pages" + ); + let notices = counts(&messages.take_notices()); + let count = |kind| notices.get(&kind).copied().unwrap_or(0); + assert_eq!( + ( + count(Degradation::LinearAttachmentCopies), + count(Degradation::LinearAttachmentClearCopies) + ), + (0, 0), + "a shadow's passes" ); drop((texture, buffer)); drop(mapping); @@ -1401,15 +1534,13 @@ fn a_render_target_over_host_pages_renders_in_place() { } /// A pass of the texture beside a private attachment renders it through copies, announced once -/// where it is aliased by the rule: what it loads and stores, and clears, reaches the pages, and +/// where it is aliased by the rule: what it loads and stores, and clears, reaches the buffer, and /// the private texture keeps its own. #[test] fn a_linear_attachment_beside_a_private_one_renders_through_copies() { on_device(|device, messages| { messages.take_notices(); - let Some((mapping, buffer, texture)) = surface(device, 5) else { - return; - }; + let (contents, buffer, texture) = surface(device, 5); let apart = by_the_rule(device) && aliased(&texture); println!( "LINEAR-ATTACHMENT beside a private one on {}: apart {apart}", @@ -1418,6 +1549,7 @@ fn a_linear_attachment_beside_a_private_one_renders_through_copies() { let queue = device.new_command_queue().unwrap(); let other = private(device, 1); let n = (W * H * TEXEL) as usize; + let before = device.work_counts(); pass( &queue, &[ @@ -1426,7 +1558,7 @@ fn a_linear_attachment_beside_a_private_one_renders_through_copies() { ], ); assert!( - mapping.read(0..n) == counting(n, 5), + contents.read(0..n) == counting(n, 5), "a load and store changed the pages" ); assert!( @@ -1441,32 +1573,35 @@ fn a_linear_attachment_beside_a_private_one_renders_through_copies() { ], ); assert!( - mapping.read(0..n) == cleared(), + contents.read(0..n) == cleared(), "a clear did not reach the pages" ); assert!( blit_out(&queue, &other) == cleared(), "the private texture's load" ); + assert_eq!( + ways(device, &before), + (0, 2 * u64::from(apart)), + "the passes' ways, in place and through copies" + ); assert_eq!( copies_announced(messages), usize::from(apart), "once a device" ); drop((texture, buffer, other)); - drop(mapping); + drop(contents); }); } -/// A multisampled attachment cleared and resolved into the texture: the pages hold the clear, +/// A multisampled attachment cleared and resolved into the texture: the buffer holds the clear, /// announced once where the texture is aliased by the rule. #[test] fn a_resolve_into_a_linear_texture_resolves_through_a_scratch() { on_device(|device, messages| { messages.take_notices(); - let Some((mapping, buffer, texture)) = surface(device, 7) else { - return; - }; + let (contents, buffer, texture) = surface(device, 7); let apart = by_the_rule(device) && aliased(&texture); println!( "LINEAR-ATTACHMENT resolved into on {}: apart {apart}", @@ -1477,7 +1612,7 @@ fn a_resolve_into_a_linear_texture_resolves_through_a_scratch() { let n = (W * H * TEXEL) as usize; pass(&queue, &[(&samples, LoadAction::Clear, Some(&texture))]); assert!( - mapping.read(0..n) == cleared(), + contents.read(0..n) == cleared(), "the resolve did not reach the pages" ); assert_eq!( @@ -1486,6 +1621,6 @@ fn a_resolve_into_a_linear_texture_resolves_through_a_scratch() { "once a device" ); drop((texture, buffer, samples)); - drop(mapping); + drop(contents); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs index 13e54e923..739b21db7 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs @@ -1,33 +1,24 @@ //! Device tests of 2D textures (and 2D arrays) over no-copy buffers on the device the cfg selects. -//! A texture over the caller's host pages is a linear image bound to the buffer's imported memory, -//! made for host allocations, where the device makes one that lies on Metal's layout there; on a -//! driver that runs on Metal, an image of a Metal texture over the import's `MTLBuffer`; elsewhere -//! a shadow image the encoders copy the texels into and back (`shadowed-texture`). Each form reads -//! and writes the caller's bytes as Metal's texture over the buffer does. +//! A texture over the caller's host pages is a shadow image the encoders copy the texels into and +//! back (`shadowed-texture`): it reads and writes the caller's bytes as Metal's texture over the +//! buffer does. //! //! - [`textures_over_no_copy_buffers_read_and_write_the_caller_s_pages`], under the validation //! layer: the consumer's surface formats (and `BGR10_XR`, an extended-range format held in an //! integer image) at 1920x1080 with packed rows, and with rows padded by 64 bytes as a guest //! browser's surfaces have them (the `_padded` tests), as render targets the shaders read (and //! write), and as textures the shaders only read (and write): the bytes the caller wrote before -//! the texture was made are what a blit reads out of it (a linear image made for host allocations -//! starts `UNDEFINED`, and its move to `GENERAL` must keep them); a render pass's clear (a blit's -//! write, without render target usage) lands in the pages, as the next blit reads the texture; +//! the texture was made are what a blit reads out of it; a render pass's clear (a blit's write, +//! without render target usage) lands in the pages, as the next blit reads the texture; //! the caller's later writes are what the next blit reads; and a blit's write through the texture //! read through the buffer by a blit, and the other way round, in one blit encoder and in two of //! one command buffer, read the write (the texture and its buffer are one resource to hazard //! tracking, which on MoltenVK leaves blits to Metal's tracking). Padded rows' bytes between -//! the rows are never written. Each texture's form is printed (`NOCOPY-TEXTURE`): aliased where -//! `vk_image` answers its own image over the pages, shadowed where it answers none, and the -//! images the making counted (`WorkCounts::pitched_host_images`, `shadowed_textures`). A shadow -//! is made without zeroing its image (`shadows_zeroed`, `images_started_on_the_host`: its copy -//! in writes every texel first); a padded texture is a shadow but on a driver that runs on -//! Metal (a linear image over the pages would hold the bytes between the rows, which Vulkan -//! lets a render pass write back); and making the same texture again asks the driver no -//! format's modifier features -//! (`modifier_feature_queries`), nor a layout at Metal's row pitch it refused -//! (`pitched_host_image_refusals`, `pitched_host_image_refusals_recalled`), and takes the same -//! form. +//! the rows are never written. Each texture's form is printed (`NOCOPY-TEXTURE`): a shadow, which +//! `vk_image` answers no image for, counted (`WorkCounts::shadowed_textures`) and made without +//! zeroing its image (`shadows_zeroed`, `images_started_on_the_host`: its copy in writes every +//! texel first); making it, and making it again, asks the driver no format's modifier features +//! (`modifier_feature_queries`), and the second takes the same form. //! - [`two_slice_arrays_over_no_copy_buffers_read_and_write_the_caller_s_pages`], under the //! validation layer: two-slice `RGBA8Unorm` 2D arrays made by the linear call, a 4x4 sampled one //! and an 8x8 render target, read and written a slice at a time at Metal's slice places @@ -56,7 +47,6 @@ use metal2vulkan::metal::{ BlendFactor, ColorWriteMask, PixelFormat, PrimitiveType, TextureType, TextureUsage, }; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; -use metal2vulkan::vk::DriverId; use metal2vulkan_devtools::llvm_assemble; use metal2vulkan_runtime::{ BlitOption, Buffer, ClearColor, CommandQueue, Degradation, Device, IoSurfacePlane, LoadAction, @@ -198,13 +188,6 @@ fn padding(bytes: &[u8], bpr: u64, row: u64) -> Vec { .collect() } -/// Whether the device runs on Metal (MoltenVK), where a texture over host pages is an image of a -/// Metal texture over the buffer, which keeps the bytes between its rows as Metal does: anywhere -/// else a texture over padded rows is a shadow. -fn on_metal(device: &Device) -> bool { - device.properties().description.driver_id == Some(DriverId::MOLTENVK) -} - /// A `Shared` buffer holding `bytes`. pub(super) fn staged(device: &Device, bytes: &[u8]) -> Buffer { let buffer = device @@ -339,59 +322,29 @@ fn read_and_write_the_caller_s_pages(pf: PixelFormat, texel: u64, pad: u64) { let counted = device.work_counts(); let made = aliased(&texture); let what = format!("{} usage {usage:?}, rows of {bpr} bytes", pf.name()); - let pitched = counted.pitched_host_images - before.pitched_host_images; let shadowed = counted.shadowed_textures - before.shadowed_textures; - if made { - assert_eq!( - shadowed, 0, - "{what}: an aliased texture counted as shadowed" - ); - } else { - // Its copy in writes every texel before any command reads it: no zeros first. - assert_eq!(shadowed, 1, "{what}: a shadow not counted"); - assert_eq!( - counted.shadows_zeroed - before.shadows_zeroed, - 0, - "{what}: the shadow's image was zeroed" - ); - assert_eq!( - counted.images_started_on_the_host - before.images_started_on_the_host, - 0, - "{what}: the shadow's image was zeroed on the host" - ); - } - if pad != 0 && !on_metal(&device) { - assert!( - !made && pitched == 0, - "{what}: rows with bytes between them aliased by a linear image (pitched \ - images {pitched})" - ); - } - // A format's modifier features are asked of the driver once, and a layout it refused - // is not asked again: making the same texture again asks neither, and takes the same - // form. + // A texture over host pages is a shadow, whose copy in writes every texel before any + // command reads it: no zeros first. + assert!(!made, "{what}: a texture over host pages aliased"); + assert_eq!(shadowed, 1, "{what}: a shadow not counted"); + assert_eq!( + counted.shadows_zeroed - before.shadows_zeroed, + 0, + "{what}: the shadow's image was zeroed" + ); + assert_eq!( + counted.images_started_on_the_host - before.images_started_on_the_host, + 0, + "{what}: the shadow's image was zeroed on the host" + ); + // Making it asks the driver no format's modifier features, nor does making it again, + // which takes the same form. let again = buffer.new_texture(&d, 0, bpr).unwrap(); let asked = device.work_counts(); assert_eq!( - asked.modifier_feature_queries - counted.modifier_feature_queries, + asked.modifier_feature_queries - before.modifier_feature_queries, 0, - "{what}: the same texture's making asked the driver's modifier features again" - ); - // The first making's refusal was asked or recalled (an earlier usage's image may be - // this one's); the second recalls it. - let refused = (counted.pitched_host_image_refusals - - before.pitched_host_image_refusals) - + (counted.pitched_host_image_refusals_recalled - - before.pitched_host_image_refusals_recalled); - assert_eq!( - ( - asked.pitched_host_image_refusals - counted.pitched_host_image_refusals, - asked.pitched_host_image_refusals_recalled - - counted.pitched_host_image_refusals_recalled, - ), - (0, refused), - "{what}: the same texture's making asked the driver a layout it refused (refused \ - or recalled at first {refused})" + "{what}: the texture's making asked the driver's modifier features" ); assert_eq!(aliased(&again), made, "{what}: made again in another form"); drop(again); @@ -462,8 +415,7 @@ fn read_and_write_the_caller_s_pages(pf: PixelFormat, texel: u64, pad: u64) { ordered(&queue, &texture, &buffer, (bpr, row), true); ordered(&queue, &texture, &buffer, (bpr, row), false); eprintln!( - "NOCOPY-TEXTURE on {}: {what} {W}x{H}: {} (pitched host images {pitched}, \ - refused {refused}, shadows {shadowed})", + "NOCOPY-TEXTURE on {}: {what} {W}x{H}: {} (shadows {shadowed})", device.name(), form(made) ); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs index b9821d339..36b477183 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs @@ -8,14 +8,9 @@ //! lie one after another, of a height that is no multiple of 4, with the pages' later bytes past //! their last row (a surface's next plane). //! -//! Whatever form the device gives the texture (its own linear image, a `DRM_FORMAT_MOD_LINEAR` -//! image laid out at Metal's row pitch, or a shadow), every step reads and writes Metal's bytes at -//! Metal's places, and no write reaches the bytes between the rows or past the last. A texture -//! that renders or writes, whose rows lie with bytes between them, is never a linear image over -//! the pages (Vulkan lets a render pass's load and store operations write every byte of an -//! attachment's subresource), but on a driver that runs on Metal, whose image is a Metal texture -//! over the buffer; nor is one that only reads under the lane's policy (`exact_answers`, -//! `PaddedReadsPolicy::Shadow`). The steps: +//! Each texture is a shadow (no image over the pages: `vk_image` answers none), and every step +//! reads and writes Metal's bytes at Metal's places, and no write reaches the bytes between the +//! rows or past the last. The steps: //! //! - **reads**: a blit out, `get_bytes`, a fragment function's `read`, and its `sample` through a //! nearest sampler give the caller's texels; a linear sampler gives what it gives over a private @@ -37,31 +32,17 @@ //! an ordinary buffer's padded rows: a texture that only reads names its layout transitions, a //! render target a render pass's load and store operations too. //! -//! Under the policy's default (`PaddedReadsPolicy::Alias`), a texture that only reads (`ShaderRead` -//! usage) is an image over its padded rows where the device lays one at their pitch. -//! [`a_texture_that_only_reads_keeps_every_byte_of_its_pages`] makes one over each layout and -//! reads it first through its image, before anything else touches the pages: its image's first -//! move keeps its texels (the runtime copies them out and back around it) and the bytes between -//! its rows as far as the device's move does, and a lapse fails here, naming the bytes. Then it -//! samples, blits out, reads the -//! caller's later bytes (the bytes between the rows rewritten too), blits a buffer's box and a -//! private texture's box in and replaces a box: after each, every byte of the pages is checked. -//! [`a_padded_texture_that_only_reads_copies_no_shadow_by_default`] counts its copies -//! (`WorkCounts::shadow_copies`: none across its uses, and a shadow's under -//! `PaddedReadsPolicy::Shadow`), and -//! [`a_padded_texture_that_renders_or_writes_is_a_shadow_under_either_policy`] keeps a render -//! target's, a written texture's and an `Unknown` usage's shadow. +//! [`a_texture_that_only_reads_keeps_every_byte_of_its_pages`] makes a texture that only reads +//! (`ShaderRead` usage) over each layout and reads it first, before anything else touches the +//! pages. Then it samples, blits out, reads the caller's later bytes (the bytes between the rows +//! rewritten too), blits a buffer's box and a private texture's box in and replaces a box: after +//! each, every byte of the pages is checked. [`a_padded_texture_that_only_reads_is_a_shadow`] +//! counts its copies (`WorkCounts::shadow_copies`: some for its uses), and +//! [`a_padded_texture_that_renders_or_writes_is_a_shadow`] keeps a render target's, a written +//! texture's and an `Unknown` usage's shadow. //! -//! [`a_texture_s_first_move_keeps_the_bytes_it_lies_over`] makes a texture over each layout, and -//! over packed 1080p and tile rows, with no submission reaching it before its first use: that -//! batch makes an aliasing image's move from `UNDEFINED`, the host keeping the bytes the image is -//! bound to (`WorkCounts::first_move_keeps` counts one per aliased texture, none per shadow, none -//! at a second use; `first_move_kept_bytes` those bytes, from the first texel to at most the last -//! row's pitch), the read gives the pages' texels, and every byte of the pages stays -//! (`FIRST-MOVE-KEEP`). [`a_cpu_write_during_a_texture_s_first_move_stays_outside_its_bytes`] -//! writes bytes between the rows and past the image's from the CPU while that first use runs, and -//! finds the texels and each write past the image's bytes in the pages after it; the writes -//! between rows the keep undid are printed (`FIRST-MOVE-WINDOW`). +//! [`a_texture_over_read_only_pages_reads_them`] makes a texture that only reads over pages the +//! process maps read-only: its first use reads their texels and writes none of their bytes. //! //! [`a_loaded_color_beside_a_cleared_depth_copies_inside_its_scissor`] draws under a scissor //! beside a depth attachment the pass clears and stores, of the color's size and larger, whose @@ -76,6 +57,12 @@ //! loads another: their copies in share one barrier before and one after, and the pass records //! as many pipeline barriers whatever the number of textures it reads. //! +//! [`passes_on_one_shadow_count_once_a_command_buffer`] counts the passes on shadowed attachments +//! and the textures each command buffer takes them on (`WorkCounts::shadow_attachment_passes`, +//! `shadow_attachment_textures`). +//! +//! Printed per layout (`PITCHED-SURFACE`): the shadows the making counted +//! (`WorkCounts::shadowed_textures`), and the shadow's reason. Printed once //! (`SHADOW-COPY-BACK`, [`a_pass_copies_in_and_back_only_the_texels_its_scissors_reach`]): whether //! a shadow's copy back ran as a dispatch (`WorkCounts::shadow_copies_back_dispatched`). @@ -87,6 +74,7 @@ use super::{validated_device, validated_device_with, Messages, ScratchCache, WAI use crate::air_library::AirLibrary; use crate::gpu::TEST_DEVICE; use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::device::DriverFact; use metal2vulkan::metal::{ BarrierScope, PixelFormat, PrimitiveType, RenderStages, SamplerMinMagFilter, TextureUsage, }; @@ -96,7 +84,7 @@ use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ BlitOption, Buffer, ClearColor, CommandQueue, Degradation, Device, IoSurfacePlane, LoadAction, Origin, PipelineOptions, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions, - SamplerState, ScissorRect, Size, StoreAction, Texture, TextureDescriptor, + SamplerState, ScissorRect, Size, StoreAction, Texture, TextureDescriptor, Viewport, }; /// A surface's plane: its name, pixel format and texel bytes, width, height and bytes per row. @@ -458,49 +446,12 @@ pub(super) fn sampler(device: &Device, filter: SamplerMinMagFilter) -> SamplerSt device.new_sampler_state(&d).unwrap() } -/// Whether the device runs on Metal (MoltenVK), where a texture over host pages is an image of a -/// Metal texture over the buffer, which keeps the bytes between its rows as Metal does. -fn on_metal(device: &Device) -> bool { - device.properties().description.driver_id == Some(DriverId::MOLTENVK) -} - /// A texture of `layout` over a no-copy buffer of new anonymous pages, made as a surface's with /// `usage`: the pages hold a pattern of their own, the texels `texels_of(.., 1)` laid at the rows; /// with the buffer, the mapping and the pages as written. `None` where the device imports no host -/// memory. Its form is checked against the making's counts: a shadow counted where it is not -/// aliased, and never a linear image over padded rows off Metal but where `padded_alias` (a -/// texture that only reads, under `PaddedReadsPolicy::Alias`). -fn surface( - device: &Device, - layout: &Layout, - usage: TextureUsage, - padded_alias: bool, -) -> Option { - surface_with(device, layout, usage, padded_alias, true) -} - -/// [`surface`], its image's `VkImage` asked (`Texture::vk_image`, which makes its first move on a -/// submission of its own) where `handed_out`; else whether it is aliased is told by the shadows -/// its making counted alone, and no submission has reached it yet. -fn surface_with( - device: &Device, - layout: &Layout, - usage: TextureUsage, - padded_alias: bool, - handed_out: bool, -) -> Option { - surface_past(device, layout, usage, (padded_alias, handed_out), 0) -} - -/// [`surface_with`], the pages reaching at least `past` bytes past the last row's pitch. -fn surface_past( - device: &Device, - layout: &Layout, - usage: TextureUsage, - (padded_alias, handed_out): (bool, bool), - past: usize, -) -> Option { - let len = (layout.len() + past).next_multiple_of(GUEST_PAGE); +/// memory. It is a shadow, whatever its usage: counted so, and `vk_image` answers no image. +fn surface(device: &Device, layout: &Layout, usage: TextureUsage) -> Option { + let len = layout.len().next_multiple_of(GUEST_PAGE); let mapping = Mapping::anonymous(len); // The pages: texels a blend keeps finite, and the bytes between the rows a pattern of // their own, which no write through the texture reaches. @@ -536,24 +487,14 @@ fn surface_past( let texture = buffer .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, layout.bpr, false)) .unwrap(); - let counted = device.work_counts(); - let pitched = counted.pitched_host_images - before.pitched_host_images; - let shadowed = counted.shadowed_textures - before.shadowed_textures; - let aliased = match handed_out { - // SAFETY: the handle is only compared, while the texture lives. - true => unsafe { texture.vk_image() }.is_some(), - false => shadowed == 0, - }; + let shadowed = device.work_counts().shadowed_textures - before.shadowed_textures; let what = format!("{} ({}, {usage:?})", layout.name, layout.pf.name()); + assert_eq!(shadowed, 1, "{what}: {shadowed} shadows counted"); + // SAFETY: the handle is only compared, while the texture lives. + let image = unsafe { texture.vk_image() }; assert_eq!( - u64::from(!aliased), - shadowed, - "{what}: aliased {aliased}, but {shadowed} shadows counted" - ); - assert!( - !(aliased && layout.padded()) || on_metal(device) || padded_alias, - "{what}: rows with bytes between them aliased by a linear image (pitched images \ - {pitched})" + image, None, + "{what}: a texture over host pages answered an image" ); Some(Surface { texture, @@ -562,7 +503,7 @@ fn surface_past( pages, len, what, - form: (aliased, pitched, shadowed), + shadowed, }) } @@ -577,8 +518,8 @@ struct Surface { len: usize, /// The layout, format and usage, in words. what: String, - /// Whether it is aliased, and the pitched images and shadows its making counted. - form: (bool, u64, u64), + /// The shadows its making counted. + shadowed: u64, } impl Surface { @@ -599,10 +540,9 @@ impl Surface { ); } - /// Print the form and a shadow's reason (`PITCHED-SURFACE`), and drop the texture, then the - /// buffer, then the pages. + /// Print the shadows counted and the shadow's reason (`PITCHED-SURFACE`), and drop the + /// texture, then the buffer, then the pages. fn report(self, device: &Device, messages: &Messages) { - let (aliased, pitched, shadowed) = self.form; let reason = messages .take_notices() .into_iter() @@ -611,11 +551,10 @@ impl Surface { .map(|notice| format!(": {}", notice.reason)) .unwrap_or_default(); eprintln!( - "PITCHED-SURFACE on {}: {}: {} (pitched host images {pitched}, shadows \ - {shadowed}){reason}", + "PITCHED-SURFACE on {}: {}: shadowed (shadows {}){reason}", device.name(), self.what, - if aliased { "aliased" } else { "shadowed" }, + self.shadowed, ); let Surface { texture, @@ -639,7 +578,7 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { let queue = device.new_command_queue().unwrap(); let texel = layout.texel; let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - let Some(surface) = surface(&device, &layout, usage, false) else { + let Some(surface) = surface(&device, &layout, usage) else { return; }; let (texture, what) = (&surface.texture, &surface.what); @@ -798,18 +737,14 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { ); } -/// A texture of `layout` over a no-copy buffer whose first use reads it through its image (a -/// fragment function's `read`), before any command reads or writes the pages another way: the -/// image's first move to `GENERAL` (from `UNDEFINED`, as Vulkan has an image of host allocations -/// made, `VUID-VkImageCreateInfo-pNext-01443`, which "will cause the contents of the image's -/// memory to be undefined") keeps the texels, which the runtime copies out and back around it, -/// and the bytes past them as far as the device's move does. A lapse fails here: the read differs -/// from the texels, or the pages change. +/// A texture of `layout` over a no-copy buffer whose first use reads it (a fragment function's +/// `read`), before any command reads or writes the pages another way: its shadow's copy in reads +/// the pages' texels. A lapse fails here: the read differs from the texels, or the pages change. fn first_use_reads_the_bytes(device: &Device, messages: &Messages, layout: Layout) { { let queue = device.new_command_queue().unwrap(); let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - let Some(surface) = surface(device, &layout, usage, false) else { + let Some(surface) = surface(device, &layout, usage) else { return; }; let texels = rows(&layout, &surface.pages); @@ -833,145 +768,36 @@ fn first_use_reads_the_bytes(device: &Device, messages: &Messages, layout: Layou ); } -/// [`first_use_reads_the_bytes`] over each of [`LAYOUTS`], on one device: an aliased texture's -/// image moves at its first use (a shadow's copy in reads the pages through a buffer). +/// [`first_use_reads_the_bytes`] over each of [`LAYOUTS`], on one device. #[test] fn a_texture_s_first_use_reads_the_bytes_it_was_made_over() { - on_shared_device(None, |device, messages| { + on_shared_device(|device, messages| { for layout in LAYOUTS { first_use_reads_the_bytes(device, messages, layout); } }); } -/// A texture of `layout` over a no-copy buffer, of `usage`, whose first use (a fragment -/// function's `read`, in a command buffer of its own) is the first submission to reach it: where -/// an image aliases the pages, that batch makes the image's move from `UNDEFINED` (an image of host -/// allocations, `VUID-VkImageCreateInfo-pNext-01443`, or on Metal a Metal texture over the -/// buffer), whose bytes the host keeps (`WorkCounts::first_move_keeps`: one; -/// `first_move_kept_bytes`: from the first texel to at most the last row's pitch); a shadow keeps -/// none. The read -/// gives the pages' texels and every byte of the pages stays; a second use keeps nothing more. -/// Whether it was aliased; `None` where the device imports no host memory. -fn first_move_keeps_the_bytes( - device: &Device, - messages: &Messages, - layout: Layout, - usage: TextureUsage, -) -> Option { - let aliased = { - let queue = device.new_command_queue().unwrap(); - let reads = reading(device, layout.pf, "tob_read"); - let before = device.work_counts(); - let padded_alias = !usage.contains(TextureUsage::RENDER_TARGET); - let surface = surface_with(device, &layout, usage, padded_alias, false)?; - let (aliased, _, _) = surface.form; - let texels = rows(&layout, &surface.pages); - for use_ in ["its first use", "its second use"] { - let read = drawn(&queue, &layout, &reads, &surface.texture, None); - let (count, first) = differing(&read, &texels, layout.texel); - assert!( - count == 0, - "{}, {use_}: {count} texels read differ from the pages', the first at texel \ - {first:?}", - surface.what - ); - surface.check(&layout, use_, &surface.pages); - let after = device.work_counts(); - let kept = after.first_move_keeps - before.first_move_keeps; - assert_eq!( - kept, - u64::from(aliased), - "{}, {use_}: {kept} first moves kept their bytes (aliased {aliased})", - surface.what - ); - let bytes = after.first_move_kept_bytes - before.first_move_kept_bytes; - let span = u64::from(aliased) * ((layout.h - 1) * layout.bpr + layout.row()); - let rows = u64::from(aliased) * layout.h * layout.bpr; - assert!( - (span..=rows).contains(&bytes), - "{}: the first move kept {bytes} bytes, not the image's, from the first texel to \ - at most the last row's pitch ({span} to {rows})", - surface.what - ); - let restored = after.first_move_restored_bytes - before.first_move_restored_bytes; - eprintln!( - "FIRST-MOVE-KEEP on {}: {}, {use_}: {} ({kept} kept, {bytes} bytes, {restored} \ - restored)", - device.name(), - surface.what, - if aliased { "aliased" } else { "shadowed" }, - ); - } - surface.report(device, messages); - aliased - }; - assert_eq!( - messages.take(), - Vec::new(), - "{}: the validation layer reported", - layout.name - ); - Some(aliased) -} - -/// Packed rows whose pitch every measured driver lays a linear image at (multiples of 256 -/// bytes): a presented 1080p surface's, and a tile's. +/// Packed rows (multiples of 256 bytes): a presented 1080p surface's, and a tile's. const PACKED: [Layout; 2] = [ Layout::bgra8("1920x1080/7680", 1920, 1080, 7680), Layout::bgra8("1024x512/4096", 1024, 512, 4096), ]; -/// [`first_move_keeps_the_bytes`] over each of [`LAYOUTS`] and [`PACKED`], for a texture that only -/// reads (an image over padded rows too, under the policy's default) and for a render target that -/// reads (an image over packed rows alone, but on Metal), on one device. Where the device imports -/// host memory, at least one texture is aliased, or no keep was checked. -#[test] -fn a_texture_s_first_move_keeps_the_bytes_it_lies_over() { - on_shared_device(Some(PaddedReadsPolicy::Alias), |device, messages| { - let reads = TextureUsage::SHADER_READ; - let renders = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - let before = device.work_counts().first_move_keeps; - let mut aliased = 0; - for usage in [reads, renders] { - for layout in PACKED.into_iter().chain(LAYOUTS) { - match first_move_keeps_the_bytes(device, messages, layout, usage) { - Some(alias) => aliased += u64::from(alias), - None => return, - } - } - } - let kept = device.work_counts().first_move_keeps - before; - eprintln!( - "FIRST-MOVE-KEEP on {}: {kept} keeps in all, {aliased} textures aliased", - device.name() - ); - assert_eq!(kept, aliased); - assert!( - aliased > 0, - "no texture was aliased, so no keep was checked" - ); - }); -} - /// A texture that only reads, of `layout`, over a no-copy buffer whose pages the process maps /// read-only by its first use: made read-only after the buffer was made (Linux refuses read-only /// pages at the import, `a_read_only_page_is_refused_on_linux_and_read_elsewhere`, but not later), /// or, where `from_the_start`, before it (a guest's pages the host maps read-only, which MoltenVK -/// imports in place). Its first use makes the image's first move, across which the host keeps the -/// bytes the image is bound to and stores back only those the move changed -/// (`texture/first_move.rs`'s `KeptBytes::write_back`): a store into the read-only pages would end -/// the process (`SIGBUS` on macOS, `SIGSEGV` on Linux), as every byte's store did. The read gives -/// the pages' texels and every byte of the pages stays, unless the move changed some, which the -/// device then announces (`unrestored-first-move-bytes`). Printed (`FIRST-MOVE-READ-ONLY`): the -/// form and the kept and restored bytes. Whether it was aliased; `None` where the device makes no -/// buffer over the pages. -fn first_move_over_read_only_pages( +/// imports in place). It is a shadow, whose first use copies the pages' texels in and stores +/// nothing into them: a store into the read-only pages would end the process (`SIGBUS` on macOS, +/// `SIGSEGV` on Linux). The read gives the pages' texels and every byte of the pages stays. +/// Printed (`FIRST-USE-READ-ONLY`). `None` where the device makes no buffer over the pages. +fn first_use_over_read_only_pages( device: &Device, messages: &Messages, layout: Layout, from_the_start: bool, -) -> Option { +) -> Option<()> { let queue = device.new_command_queue().unwrap(); let reads = reading(device, layout.pf, "tob_read"); let len = layout.len().next_multiple_of(GUEST_PAGE); @@ -1000,7 +826,7 @@ fn first_move_over_read_only_pages( let buffer = match made { Ok(buffer) => buffer, Err(error) if not_importable(&error) => { - eprintln!("FIRST-MOVE-READ-ONLY: no buffer over the pages: {error:?}"); + eprintln!("FIRST-USE-READ-ONLY: no buffer over the pages: {error:?}"); return None; } Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), @@ -1015,7 +841,7 @@ fn first_move_over_read_only_pages( let texture = buffer .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, layout.bpr, false)) .unwrap(); - let aliased = device.work_counts().shadowed_textures == before.shadowed_textures; + let shadowed = device.work_counts().shadowed_textures - before.shadowed_textures; let what = format!( "{} ({}), read-only {}", layout.name, @@ -1026,54 +852,40 @@ fn first_move_over_read_only_pages( "after the buffer" } ); + assert_eq!(shadowed, 1, "{what}: {shadowed} shadows counted"); let read = drawn(&queue, &layout, &reads, &texture, None); let (count, first) = differing(&read, &rows(&layout, &pages), layout.texel); - let after = device.work_counts(); - let kept = after.first_move_kept_bytes - before.first_move_kept_bytes; - let restored = after.first_move_restored_bytes - before.first_move_restored_bytes; - let unrestored = messages - .take_notices() - .into_iter() - .filter_map(|message| message.degradation) - .any(|notice| notice.degradation == Degradation::UnrestoredFirstMoveBytes); eprintln!( - "FIRST-MOVE-READ-ONLY on {}: {what}: {} ({kept} bytes kept, {restored} restored, \ - unrestored announced {unrestored})", + "FIRST-USE-READ-ONLY on {}: {what}: shadowed, {count} texels read differ", device.name(), - if aliased { "aliased" } else { "shadowed" }, ); - let keeps = after.first_move_keeps - before.first_move_keeps; + assert!( + count == 0, + "{what}: {count} texels read differ from the pages', the first at texel {first:?}" + ); + let now = mapping.read(0..len); + assert!( + now == pages, + "{what}: the read-only pages changed: {}", + padding_changes(&layout, &now, &pages) + ); assert_eq!( - keeps, - u64::from(aliased), - "{what}: {keeps} first moves kept their bytes (aliased {aliased})" + messages.take(), + Vec::new(), + "{what}: the validation layer reported" ); - if !unrestored { - assert!( - count == 0, - "{what}: {count} texels read differ from the pages', the first at texel {first:?}" - ); - let now = mapping.read(0..len); - assert!( - now == pages, - "{what}: the read-only pages changed: {}", - padding_changes(&layout, &now, &pages) - ); - } drop((texture, buffer)); drop(mapping); - Some(aliased) + Some(()) } -/// [`first_move_over_read_only_pages`] over [`PACKED`], with the pages made read-only after the -/// buffer, and off Linux also before it, on one device of the policy's default. Where the device -/// imports host memory, at least one texture is aliased, or no keep over read-only pages was -/// checked. On Linux only lavapipe and NVIDIA's driver keep an import running once its pages lose -/// write permission (`HostMemory::new`'s Linux contract: RADV failed the command buffers submitted -/// after it), so only they take the case. +/// [`first_use_over_read_only_pages`] over [`PACKED`], with the pages made read-only after the +/// buffer, and off Linux also before it, on one device. On Linux only lavapipe and NVIDIA's driver +/// keep an import running once its pages lose write permission (`HostMemory::new`'s Linux +/// contract: RADV failed the command buffers submitted after it), so only they take the case. #[test] -fn a_texture_over_read_only_pages_takes_its_first_move() { - on_shared_device(Some(PaddedReadsPolicy::Alias), |device, messages| { +fn a_texture_over_read_only_pages_reads_them() { + on_shared_device(|device, messages| { let driver = device.properties().description.driver_id; let keeps_running = matches!( driver, @@ -1081,307 +893,32 @@ fn a_texture_over_read_only_pages_takes_its_first_move() { ); if cfg!(target_os = "linux") && !keeps_running { eprintln!( - "FIRST-MOVE-READ-ONLY on {}: {driver:?} is held to the writable pages of \ + "FIRST-USE-READ-ONLY on {}: {driver:?} is held to the writable pages of \ HostMemory::new's Linux contract", device.name() ); return; } - let mut aliased = 0; for layout in PACKED { for from_the_start in [false, true] { if from_the_start && cfg!(target_os = "linux") { continue; } - match first_move_over_read_only_pages(device, messages, layout, from_the_start) { - Some(alias) => aliased += u64::from(alias), - None => return, + if first_use_over_read_only_pages(device, messages, layout, from_the_start) + .is_none() + { + return; } } } - assert!( - aliased > 0, - "no texture over read-only pages was aliased, so no keep over them was checked" - ); - }); -} - -/// How long the CPU waits after the commit before its writes beside a texture -/// ([`a_cpu_write_during_the_first_move_stays_outside`]), one fresh texture each: the first move -/// runs when the device reaches the submission, which takes a time of its own on each device, so -/// the writes start at several times and one of them overlaps the move's keep. -const PADDING_WRITE_DELAYS: [std::time::Duration; 6] = [ - std::time::Duration::from_micros(0), - std::time::Duration::from_micros(500), - std::time::Duration::from_micros(1000), - std::time::Duration::from_micros(2000), - std::time::Duration::from_micros(3000), - std::time::Duration::from_micros(5000), -]; - -/// Spin for `wait`. -fn spin(wait: std::time::Duration) { - let spun = std::time::Instant::now(); - while spun.elapsed() < wait { - std::hint::spin_loop(); - } -} - -/// The bytes past a texture's last row that [`a_cpu_write_during_the_first_move_stays_outside`] -/// writes: a cache line's. -const PAST: u64 = 64; - -/// The CPU writes bytes beside a texture that only reads, over a no-copy buffer's padded rows, -/// while its first use's command buffer runs, which makes its image's first move: each row's first -/// byte past its texels and its last before the next row, inside the bytes the image is bound to, -/// and the first and last of the [`PAST`] bytes past the last row's pitch, outside them; one row -/// after another, a few microseconds apart, from a time after the commit -/// ([`PADDING_WRITE_DELAYS`], a fresh texture each). Metal never writes those bytes, so each write -/// stays. The host keeps the bytes the image is bound to across its move (`texture/first_move.rs`'s -/// `Keep`), so a write past them stays, and so do the texels; a write between rows made between -/// the keep's read and its write back is undone (`docs/FAST-PATHS.md`'s known gap): printed, as -/// `FIRST-MOVE-WINDOW`, not failed. The lapses outside the image's bytes or in the texels, one line -/// each, and whether the texture was aliased. -fn a_cpu_write_during_the_first_move_stays_outside( - device: &Device, - messages: &Messages, - layout: Layout, -) -> Option<(bool, Vec)> { - let mut lapses = Vec::new(); - let mut aliased = false; - let queue = device.new_command_queue().unwrap(); - let reads = reading(device, layout.pf, "tob_read"); - let bound = layout.bpr * layout.h; - for delay in PADDING_WRITE_DELAYS { - let usage = TextureUsage::SHADER_READ; - let surface = surface_past(device, &layout, usage, (true, false), PAST as usize)?; - aliased = surface.form.0; - let (command_buffer, _target) = - draw_reading(&queue, &layout, &reads, &surface.texture, None); - let mut expected = surface.pages.clone(); - let write = |at: u64, expected: &mut Vec| { - let at = at as usize; - let byte = surface.pages[at] ^ 0xA5; - surface.mapping.write(at, &[byte]); - expected[at] = byte; - }; - command_buffer.commit().unwrap(); - spin(delay); - for row in 0..layout.h { - write(row * layout.bpr + layout.row(), &mut expected); - write((row + 1) * layout.bpr - 1, &mut expected); - if row == layout.h / 2 { - write(bound, &mut expected); - } - spin(std::time::Duration::from_micros(8)); - } - write(bound + PAST - 1, &mut expected); - command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert_eq!(command_buffer.error(), None); - let now = surface.mapping.read(0..surface.len); - let (count, first) = differing( - &rows(&layout, &now), - &rows(&layout, &expected), - layout.texel, - ); - if count != 0 { - lapses.push(format!( - "{}, writes from {delay:?} after the commit: {count} texels differ from Metal's, \ - the first at texel {first:?}", - surface.what - )); - } - let outside: Vec = (bound as usize..surface.len) - .filter(|&at| now[at] != expected[at]) - .collect(); - if let Some(&at) = outside.first() { - lapses.push(format!( - "{}, writes from {delay:?} after the commit: {} bytes past the image's changed, \ - the first at byte {at} (its bytes end at {bound}), now {:02x}, was {:02x}", - surface.what, - outside.len(), - now[at], - expected[at] - )); - } - let inside = (0..bound as usize) - .filter(|&at| now[at] != expected[at]) - .count(); - eprintln!( - "FIRST-MOVE-WINDOW on {}: {}: {}, writes from {delay:?} after the commit: {inside} of \ - {} bytes between rows undone, {} of 2 past its bytes", - device.name(), - surface.what, - if aliased { "aliased" } else { "shadowed" }, - 2 * layout.h, - outside.len(), - ); - surface.report(device, messages); - } - assert_eq!( - messages.take(), - Vec::new(), - "{}: the validation layer reported", - layout.name - ); - Some((aliased, lapses)) -} - -/// [`a_cpu_write_during_the_first_move_stays_outside`] over each padded layout of [`LAYOUTS`], on -/// one device of the policy's default. Off Metal, where the device imports host memory, at least -/// one is aliased, or no first move over padded rows was checked. -#[test] -fn a_cpu_write_during_a_texture_s_first_move_stays_outside_its_bytes() { - on_shared_device(Some(PaddedReadsPolicy::Alias), |device, messages| { - let (mut aliased, mut lapses) = (0, Vec::new()); - for layout in LAYOUTS.into_iter().filter(Layout::padded) { - match a_cpu_write_during_the_first_move_stays_outside(device, messages, layout) { - Some((alias, lapsed)) => { - aliased += u64::from(alias); - lapses.extend(lapsed); - } - None => return, - } - } - eprintln!( - "FIRST-MOVE-PADDING on {}: {aliased} padded textures aliased", - device.name() - ); - assert!( - lapses.is_empty(), - "a first use changed the texels, or a CPU write past the image's bytes:\n{}", - lapses.join("\n") - ); - assert!( - aliased > 0 || on_metal(device), - "no padded texture was aliased, so no first move over padded rows was checked" - ); - }); -} - -/// Textures of one image over the same bytes of one import share one `VkImage` -/// (`texture/shared_alias.rs`), held by the import, as a consumer makes a texture over the -/// presented surface at each present: a new no-copy buffer over its pages, which joins the import -/// of a buffer that lives across presents (here the surface's own, with its texture of render -/// target usage), and a texture of its plane over it, the one before released first. Over packed -/// 1080p rows, where the textures are aliased: a texture released unused makes the image, whose -/// move the next submission leaves waiting, no texture over it alive -/// (`WorkCounts::shared_alias_moves_waited`); each present's texture takes that image -/// (`shared_alias_images`), though no texture over it lived meanwhile, the first one's submission -/// keeping its texels once (`first_move_keeps`), and reads the pages' texels; a texture of the -/// surface texture's usage takes that texture's image, and keeps nothing. The pages stay as -/// written. Printed: `SHARED-ALIAS`. -#[test] -fn textures_of_one_image_over_the_same_bytes_share_it() { - const PRESENTS: u64 = 5; - on_shared_device(Some(PaddedReadsPolicy::Alias), |device, messages| { - let layout = PACKED[0]; - let reads = TextureUsage::SHADER_READ; - let renders = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - let queue = device.new_command_queue().unwrap(); - let pipeline = reading(device, layout.pf, "tob_read"); - let Some(surface) = surface_with(device, &layout, renders, false, false) else { - return; - }; - let (aliased, _, _) = surface.form; - let texels = rows(&layout, &surface.pages); - let over = |usage: TextureUsage| { - // SAFETY: the mapping outlives the buffer: both are dropped before the surface. - let made = unsafe { - no_copy( - device, - surface.mapping.pointer(), - surface.len, - ResourceOptions::default(), - None, - ) - }; - let buffer = made.unwrap(); - let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); - d.usage = usage; - d.resource_options = buffer.resource_options(); - let plane = IoSurfacePlane::new(0, layout.bpr, false); - let texture = buffer.new_texture_with_iosurface_plane(&d, plane).unwrap(); - (texture, buffer) - }; - let reads_texels = |texture: &Texture, step: &str| { - let read = drawn(&queue, &layout, &pipeline, texture, None); - let (count, first) = differing(&read, &texels, layout.texel); - assert!( - count == 0, - "{}, {step}: {count} texels read differ from the pages', the first at texel \ - {first:?}", - surface.what - ); - surface.check(&layout, step, &surface.pages); - }; - reads_texels(&surface.texture, "the surface's texture"); - let before = device.work_counts(); - drop(over(reads)); - reads_texels( - &surface.texture, - "the surface's texture, the image's move waiting", - ); - let waiting = device.work_counts(); - let waited = waiting.shared_alias_moves_waited - before.shared_alias_moves_waited; - let kept_waiting = waiting.first_move_keeps - before.first_move_keeps; - for present in 0..PRESENTS { - let made = over(reads); - reads_texels(&made.0, &format!("present {present}")); - drop(made); - } - let counted = device.work_counts(); - let shared = counted.shared_alias_images - before.shared_alias_images; - let kept = counted.first_move_keeps - before.first_move_keeps; - let presents_aliased = counted.shadowed_textures == before.shadowed_textures; - let same = over(renders); - reads_texels(&same.0, "a texture of the surface texture's usage"); - drop(same); - let after = device.work_counts(); - let shared_after = after.shared_alias_images - counted.shared_alias_images; - let kept_after = after.first_move_keeps - counted.first_move_keeps; - eprintln!( - "SHARED-ALIAS on {}: {}: aliased {aliased}; {PRESENTS} presents (aliased \ - {presents_aliased}), each texture released before the next, took {shared} shared \ - images and kept {kept} times, the image's move left waiting {waited} times, keeping \ - {kept_waiting}; the surface texture's usage: {shared_after} shared, {kept_after} \ - keeps", - device.name(), - surface.what, - ); - let (presents, presents_kept) = match presents_aliased { - true => (PRESENTS, 1), - false => (0, 0), - }; - assert_eq!( - (shared, kept), - (presents, presents_kept), - "each present's texture takes the image a texture released unused made, kept once" - ); - assert!( - !presents_aliased || (waited > 0 && kept_waiting == 0), - "a submission with no texture over the shared image alive leaves its move waiting \ - (waited {waited}, kept {kept_waiting})" - ); - assert_eq!( - (shared_after, kept_after), - (u64::from(aliased), 0), - "a texture of the surface texture's usage takes its image" - ); - assert!( - aliased || presents_aliased || !on_metal(device), - "no texture was aliased on Metal" - ); - surface.report(device, messages); }); } /// A texture over a buffer's padded rows (the browser's tile, [`LAYOUTS`]' first) is a shadow on -/// every device, its buffer an ordinary one's, which no image of Metal's aliases either; and its -/// `shadowed-texture` notice names what Vulkan lets write the padding: for a texture that only -/// reads, its image's layout transitions (the first move from the layout it is made in), never a -/// render pass, which no image of its takes; for a render target, a render pass's load and store -/// operations too. Each usage on a device of its own, which announces the kind once. +/// every device, its buffer an ordinary one's; and its `shadowed-texture` notice names what Vulkan +/// lets write the padding: for a texture that only reads, its image's layout transitions (the +/// first move from the layout it is made in), never a render pass, which no image of its takes; +/// for a render target, a render pass's load and store operations too. Each usage on a device of its own, which announces the kind once. #[test] fn a_padded_texture_s_shadow_names_what_may_write_its_padding() { let layout = LAYOUTS[0]; @@ -2261,6 +1798,59 @@ fn merged_writes_match_metal_over_a_narrow_tile() { /// texture of the same texels holds after the same writes, and no other byte of the pages changes. fn writes_as_metal(layout: Layout) { let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let Some(surface) = surface(&device, &layout, usage) else { + return; + }; + let mut expected = surface.pages.clone(); + let texels = rows(&layout, &expected); + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = usage; + d.resource_options = ResourceOptions::private(); + let reference = device.new_texture(&d).unwrap(); + blit_in(&queue, &layout, &reference, &texels); + let writes = reading(&device, layout.pf, "tob_write"); + drawn(&queue, &layout, &writes, &reference, None); + drawn(&queue, &layout, &writes, &surface.texture, None); + lay( + &layout, + &mut expected, + &blit_out(&queue, &layout, &reference), + ); + surface.check(&layout, "a fragment function's writes", &expected); + surface.report(&device, &messages); + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); +} + +/// One test a layout, each its own process: `$name` runs [`LAYOUTS`]`[$index]`. +macro_rules! per_layout { + ($($name:ident => $index:expr;)*) => { + $( + #[test] + fn $name() { + reads_writes_and_renders_as_metal(LAYOUTS[$index]); + } + )* + }; +} + +per_layout! { + a_browser_tile_at_5248_byte_rows_reads_writes_and_renders_as_metal => 0; + a_tile_at_16_byte_padded_rows_reads_writes_and_renders_as_metal => 1; + a_tile_at_256_byte_padded_rows_reads_writes_and_renders_as_metal => 2; + a_tile_at_512_byte_padded_rows_reads_writes_and_renders_as_metal => 3; + a_small_tile_reads_writes_and_renders_as_metal => 4; + a_full_width_strip_reads_writes_and_renders_as_metal => 5; + a_narrow_tile_reads_writes_and_renders_as_metal => 6; a_half_float_tile_reads_writes_and_renders_as_metal => 7; a_tile_of_510_packed_rows_reads_writes_and_renders_as_metal => 8; a_small_tile_of_packed_rows_reads_writes_and_renders_as_metal => 9; @@ -2276,22 +1866,77 @@ fn a_fragment_function_s_writes_leave_the_bytes_between_rows() { } } -/// Run `test` on one lane device, of `padded_reads` where given (else the lane's own policy, -/// `PaddedReadsPolicy::Shadow` with `exact_answers`), -/// which announces `shadowed-texture` for each texture so that each case prints its own reason; -/// then fail on any validation message, leaks included. Each case takes its own validation -/// messages first, to fail by name. -fn on_shared_device( - padded_reads: Option, - test: impl FnOnce(&Device, &Messages), -) { +/// Passes on one shadowed texture count once a pass, and once a command buffer and texture +/// (`WorkCounts::shadow_attachment_passes`, `shadow_attachment_textures`): a command buffer of +/// three passes into one texture over host pages and one into another between them, then a command +/// buffer of one pass into the first, count five passes on three textures (printed: +/// `SHADOW-ATTACHMENTS`). +#[test] +fn passes_on_one_shadow_count_once_a_command_buffer() { + let layout = PACKED[1]; + on_shared_device(|device, messages| { + let queue = device.new_command_queue().unwrap(); + let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + let Some(first) = surface(device, &layout, usage) else { + return; + }; + let Some(second) = surface(device, &layout, usage) else { + return; + }; + let pipeline = blending(device, layout.pf); + let corners = staged(device, &floats([-1.0, -1.0, 0.0, 0.0])); + let color = staged(device, &floats([0.25, 0.5, 0.75, 0.5])); + let pass = |command_buffer: &metal2vulkan_runtime::CommandBuffer, texture: &Texture| { + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(texture.clone()); + attachment.load_action = LoadAction::Load; + attachment.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&pipeline).unwrap(); + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + encoder.set_fragment_buffer(Some(&color), 0, 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + }; + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for texture in [ + &first.texture, + &second.texture, + &first.texture, + &first.texture, + ] { + pass(&command_buffer, texture); + } + run(&command_buffer); + let command_buffer = queue.command_buffer().unwrap(); + pass(&command_buffer, &first.texture); + run(&command_buffer); + let after = device.work_counts(); + let passes = after.shadow_attachment_passes - before.shadow_attachment_passes; + let textures = after.shadow_attachment_textures - before.shadow_attachment_textures; + eprintln!( + "SHADOW-ATTACHMENTS on {}: {passes} passes on shadowed attachments, {textures} \ + textures a command buffer", + device.name() + ); + assert_eq!((passes, textures), (5, 3)); + first.report(device, messages); + second.report(device, messages); + }); +} + +/// Run `test` on one lane device, which announces `shadowed-texture` for each texture so that each +/// case prints its own reason; then fail on any validation message, leaks included. Each case +/// takes its own validation messages first, to fail by name. +fn on_shared_device(test: impl FnOnce(&Device, &Messages)) { let cache = ScratchCache::new().unwrap(); let messages = Messages::default(); { let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { - if let Some(policy) = padded_reads { - options.policy.padded_reads = policy; - } options.announce_each.insert(Degradation::ShadowedTexture); }) .unwrap(); @@ -2312,26 +1957,20 @@ fn lay_box(layout: &Layout, expected: &mut [u8], (bx, by, bw): (u64, u64, u64), } } -/// A texture of `layout` that only reads (`ShaderRead` usage), over a no-copy buffer, on a device -/// of the policy's default (`PaddedReadsPolicy::Alias`): its first use reads it through its image -/// (a fragment function's `read`) before any command reads or writes the pages another way, and -/// must read the pages' texels and leave every byte of the pages, the bytes between the rows -/// among them, as it was: the host keeps them across the image's first move -/// (docs/FAST-PATHS.md's known gaps). Then its reads (a nearest and a linear sample, `get_bytes`, -/// a blit out), the caller's later bytes (texels and the bytes between the rows alike) read by a -/// sample and a blit, and its writes that Metal makes of any texture (a buffer's box blitted in -/// at an odd origin, `replace_region` of a box, a private texture's box blitted in): each reads -/// Metal's texels, and after each every byte of the pages is the program's. Whether it aliased, -/// and whether the device runs on Metal; `None` where it imports no host memory. -fn reads_and_blits_as_metal( - device: &Device, - messages: &Messages, - layout: Layout, -) -> Option<(bool, bool)> { - let made = { +/// A texture of `layout` that only reads (`ShaderRead` usage), over a no-copy buffer: its first use +/// (a fragment function's `read`) comes before any command reads or writes the pages another way, +/// and must read the pages' texels and leave every byte of the pages, the bytes between the rows +/// among them, as it was. Then its reads (a nearest and a linear sample, `get_bytes`, a blit out), +/// the caller's later bytes (texels and the bytes between the rows alike) read by a sample and a +/// blit, and its writes that Metal makes of any texture (a buffer's box blitted in at an odd +/// origin, `replace_region` of a box, a private texture's box blitted in): each reads Metal's +/// texels, and after each every byte of the pages is the program's. `None` where the device +/// imports no host memory. +fn reads_and_blits_as_metal(device: &Device, messages: &Messages, layout: Layout) -> Option<()> { + { let queue = device.new_command_queue().unwrap(); let texel = layout.texel; - let surface = surface(device, &layout, TextureUsage::SHADER_READ, true)?; + let surface = surface(device, &layout, TextureUsage::SHADER_READ)?; let (texture, what) = (&surface.texture, &surface.what); let mut expected = surface.pages.clone(); let check = |step: &str, expected: &[u8]| surface.check(&layout, step, expected); @@ -2459,267 +2098,201 @@ fn reads_and_blits_as_metal( &rows(&layout, &expected), ); check("the last read", &expected); - let made = (surface.form.0, on_metal(device)); surface.report(device, messages); - made - }; + } assert_eq!( messages.take(), Vec::new(), "{}: the validation layer reported", layout.name ); - Some(made) + Some(()) } -/// [`reads_and_blits_as_metal`] over each of [`LAYOUTS`]: a texture that only reads, aliased -/// where the device lays an image at the rows' pitch, keeps every byte of its pages through its -/// first move, its reads, the caller's writes and Metal's blits into it. Printed: how many of the -/// padded layouts aliased (`PITCHED-READS`); off Metal at least one must, or no first move over -/// padded rows was checked. Every layout on one device of the policy's default. +/// [`reads_and_blits_as_metal`] over each of [`LAYOUTS`]: a texture that only reads keeps every +/// byte of its pages through its first use, its reads, the caller's writes and Metal's blits into +/// it. Every layout on one device. #[test] fn a_texture_that_only_reads_keeps_every_byte_of_its_pages() { - let (mut aliased, mut padded, mut metal) = (0, 0, false); - let mut imports = true; - on_shared_device(Some(PaddedReadsPolicy::Alias), |device, messages| { + on_shared_device(|device, messages| { for layout in LAYOUTS { - let Some((alias, on_metal)) = reads_and_blits_as_metal(device, messages, layout) else { - imports = false; + if reads_and_blits_as_metal(device, messages, layout).is_none() { return; - }; - metal = on_metal; - if layout.padded() { - aliased += u64::from(alias); - padded += 1; } } }); - if !imports { - return; - } - eprintln!("PITCHED-READS: {aliased} of {padded} padded layouts that only read aliased"); - assert!( - aliased > 0 || metal, - "no padded layout that only reads was aliased, so no first move over padded rows was \ - checked" - ); } /// A texture that only reads over padded rows (each padded layout of [`LAYOUTS`] over a no-copy -/// buffer) copies no shadow under the policy's default where it is aliased: -/// `WorkCounts::shadow_copies` stays the same across three sampling passes and a blit out. Under -/// `PaddedReadsPolicy::Shadow` the same texture is a shadow (but on Metal, whose image of it is a -/// Metal texture over the buffer either way), copied in for its uses. Off Metal at least one layout -/// is aliased by default. Every layout of a policy on one device of that policy. +/// buffer) is a shadow: its uses (three sampling passes and a blit out) copy it in +/// (`WorkCounts::shadow_copies`), and read the pages' texels. Every layout on one device. #[test] -fn a_padded_texture_that_only_reads_copies_no_shadow_by_default() { - let mut aliased_layouts = 0; - let mut metal = false; - let mut imports = true; - for policy in [PaddedReadsPolicy::Alias, PaddedReadsPolicy::Shadow] { - on_shared_device(Some(policy), |device, messages| { - for layout in LAYOUTS.into_iter().filter(Layout::padded) { - metal = on_metal(device); - let queue = device.new_command_queue().unwrap(); - let alias = policy == PaddedReadsPolicy::Alias; - let usage = TextureUsage::SHADER_READ; - let Some(surface) = surface(device, &layout, usage, alias) else { - imports = false; - return; - }; - let (aliased, _, _) = surface.form; - let what = format!("{} under {policy:?}", surface.what); - if !alias { - assert!(!aliased || metal, "{what}: aliased"); - } - let texels = rows(&layout, &surface.pages); - let samples = reading(device, layout.pf, "tob_sample"); - let nearest = sampler(device, SamplerMinMagFilter::Nearest); - let copies = || device.work_counts().shadow_copies; - let before = copies(); - for _ in 0..3 { - let got = drawn(&queue, &layout, &samples, &surface.texture, Some(&nearest)); - assert!( - got == texels, - "{what}: a sample differs from the pages' texels" - ); - } +fn a_padded_texture_that_only_reads_is_a_shadow() { + on_shared_device(|device, messages| { + for layout in LAYOUTS.into_iter().filter(Layout::padded) { + let queue = device.new_command_queue().unwrap(); + let usage = TextureUsage::SHADER_READ; + let Some(surface) = surface(device, &layout, usage) else { + return; + }; + let what = surface.what.clone(); + let texels = rows(&layout, &surface.pages); + let samples = reading(device, layout.pf, "tob_sample"); + let nearest = sampler(device, SamplerMinMagFilter::Nearest); + let copies = || device.work_counts().shadow_copies; + let before = copies(); + for _ in 0..3 { + let got = drawn(&queue, &layout, &samples, &surface.texture, Some(&nearest)); assert!( - blit_out(&queue, &layout, &surface.texture) == texels, - "{what}" - ); - let copied = copies() - before; - eprintln!( - "PITCHED-READS on {}: {what}: {}, {copied} shadow copies over three samples \ - and a blit out", - device.name(), - if aliased { "aliased" } else { "shadowed" } - ); - if aliased { - assert_eq!(copied, 0, "{what}: an aliased texture copied a shadow"); - aliased_layouts += u64::from(alias); - } else { - assert!(copied > 0, "{what}: a shadow its uses copied nothing into"); - } - surface.check(&layout, "its uses", &surface.pages); - surface.report(device, messages); - assert_eq!( - messages.take(), - Vec::new(), - "{what}: the validation layer reported" + got == texels, + "{what}: a sample differs from the pages' texels" ); } - }); - if !imports { - return; + assert!( + blit_out(&queue, &layout, &surface.texture) == texels, + "{what}" + ); + let copied = copies() - before; + eprintln!( + "PITCHED-READS on {}: {what}: shadowed, {copied} shadow copies over three samples \ + and a blit out", + device.name(), + ); + assert!(copied > 0, "{what}: a shadow its uses copied nothing into"); + surface.check(&layout, "its uses", &surface.pages); + surface.report(device, messages); + assert_eq!( + messages.take(), + Vec::new(), + "{what}: the validation layer reported" + ); } - } - assert!( - aliased_layouts > 0 || metal, - "no padded layout that only reads was aliased by default" - ); + }); } /// A padded texture that renders (`RenderTarget`), that a shader writes (`ShaderWrite`), or of -/// `Unknown` usage (which Metal reports as both) is a shadow under either policy, off Metal: over -/// a no-copy buffer's pages and over an ordinary buffer alike (the browser's tile, [`LAYOUTS`]' -/// first). Every usage of a policy on one device of that policy. +/// `Unknown` usage (which Metal reports as both) is a shadow: over a no-copy buffer's pages and +/// over an ordinary buffer alike (the browser's tile, [`LAYOUTS`]' first). Every usage +/// on one device. #[test] -fn a_padded_texture_that_renders_or_writes_is_a_shadow_under_either_policy() { +fn a_padded_texture_that_renders_or_writes_is_a_shadow() { let layout = LAYOUTS[0]; assert!(layout.padded(), "{}", layout.name); - for policy in [PaddedReadsPolicy::Alias, PaddedReadsPolicy::Shadow] { - on_shared_device(Some(policy), |device, messages| { - for usage in [ - TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, - TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE, - TextureUsage::UNKNOWN, - ] { - // Over a no-copy buffer's pages (`surface` checks the form against the counts). - if let Some(surface) = surface(device, &layout, usage, false) { - surface.report(device, messages); - } - // Over an ordinary buffer. - let buffer = device - .new_buffer(layout.bpr * layout.h, ResourceOptions::default()) - .unwrap(); - let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); - d.usage = usage; - d.resource_options = buffer.resource_options(); - let texture = buffer.new_texture(&d, 0, layout.bpr).unwrap(); - // SAFETY: the handle is only compared, while the texture lives. - let aliased = unsafe { texture.vk_image() }.is_some(); - assert!( - !aliased, - "{} ({usage:?}) under {policy:?}, an ordinary buffer's: aliased", - layout.name - ); - messages.take_notices(); - drop((texture, buffer)); - assert_eq!( - messages.take(), - Vec::new(), - "{} ({usage:?}) under {policy:?}: the validation layer reported", - layout.name - ); + on_shared_device(|device, messages| { + for usage in [ + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE, + TextureUsage::UNKNOWN, + ] { + // Over a no-copy buffer's pages (`surface` checks that it is a shadow). + if let Some(surface) = surface(device, &layout, usage) { + surface.report(device, messages); } - }); - } + // Over an ordinary buffer. + let buffer = device + .new_buffer(layout.bpr * layout.h, ResourceOptions::default()) + .unwrap(); + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = usage; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, 0, layout.bpr).unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + let aliased = unsafe { texture.vk_image() }.is_some(); + assert!( + !aliased, + "{} ({usage:?}), an ordinary buffer's: aliased", + layout.name + ); + messages.take_notices(); + drop((texture, buffer)); + assert_eq!( + messages.take(), + Vec::new(), + "{} ({usage:?}): the validation layer reported", + layout.name + ); + } + }); } /// A texture that only reads over an ordinary `Shared` buffer's padded rows (each padded layout -/// of [`LAYOUTS`]): under the policy's default it is the device's own linear image over the -/// buffer's memory, made `PREINITIALIZED`, where the device lays one at the rows' pitch, and its -/// first use, a fragment function's read through it, reads the buffer's texels and leaves every -/// byte of the buffer, the bytes between the rows among them, as it was; an aliased one copies -/// no shadow over that read and a nearest sample. Under `PaddedReadsPolicy::Shadow` it is a -/// shadow on every device. Printed (`PITCHED-READS`): each layout's form, and a shadow's reason. -/// Every layout of a policy on one device of that policy. +/// of [`LAYOUTS`]) is a shadow on every device, and its first use, a fragment function's read, +/// reads the buffer's texels and leaves every byte of the buffer, the bytes between the rows among +/// them, as it was; so does a nearest sample. Printed (`PITCHED-READS`): each layout's shadow +/// copies and reason. Every layout on one device. #[test] fn a_padded_texture_that_only_reads_over_an_ordinary_buffer_keeps_its_bytes() { - for policy in [PaddedReadsPolicy::Alias, PaddedReadsPolicy::Shadow] { - on_shared_device(Some(policy), |device, messages| { - for layout in LAYOUTS.into_iter().filter(Layout::padded) { - let queue = device.new_command_queue().unwrap(); - let len = layout.bpr * layout.h; - let buffer = device.new_buffer(len, ResourceOptions::default()).unwrap(); - let mut bytes = counting(len as usize, 11); - lay( - &layout, - &mut bytes, - &texels_of(&layout, (layout.row() * layout.h) as usize, 6), - ); - let contents = buffer.contents().unwrap(); - // SAFETY: a new `Shared` buffer of `len` bytes, which no command uses yet. - unsafe { - std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) - }; - let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); - d.usage = TextureUsage::SHADER_READ; - d.resource_options = buffer.resource_options(); - let texture = buffer.new_texture(&d, 0, layout.bpr).unwrap(); - // SAFETY: the handle is only compared, while the texture lives. - let aliased = unsafe { texture.vk_image() }.is_some(); - let what = format!( - "{} (ShaderRead) under {policy:?}, an ordinary buffer's", - layout.name - ); - if policy == PaddedReadsPolicy::Shadow { - assert!(!aliased, "{what}: aliased"); - } - let texels = rows(&layout, &bytes); - let copies = || device.work_counts().shadow_copies; - let before = copies(); - let reads = reading(device, layout.pf, "tob_read"); - let read = drawn(&queue, &layout, &reads, &texture, None); - let (count, first) = differing(&read, &texels, layout.texel); - assert!( - count == 0, - "{what}, its first use: {count} texels read differ from the buffer's, the \ - first at texel {first:?}" - ); - let now = bytes_of(&buffer); - assert!( - now == bytes, - "{what}, its first use: the bytes between the rows (or past the last) \ - changed: {}", - padding_changes(&layout, &now, &bytes) - ); - let samples = reading(device, layout.pf, "tob_sample"); - let nearest = sampler(device, SamplerMinMagFilter::Nearest); - let got = drawn(&queue, &layout, &samples, &texture, Some(&nearest)); - assert!( - got == texels, - "{what}: a sample differs from the buffer's texels" - ); - let copied = copies() - before; - if aliased { - assert_eq!(copied, 0, "{what}: an aliased texture copied a shadow"); - } - assert!( - bytes_of(&buffer) == bytes, - "{what}: the buffer's bytes changed" - ); - let reason = messages - .take_notices() - .into_iter() - .filter_map(|message| message.degradation) - .find(|notice| notice.degradation == Degradation::ShadowedTexture) - .map(|notice| format!(": {}", notice.reason)) - .unwrap_or_default(); - eprintln!( - "PITCHED-READS on {}: {what}: {}, {copied} shadow copies over a read and a \ - sample{reason}", - device.name(), - if aliased { "aliased" } else { "shadowed" } - ); - drop((texture, buffer)); - assert_eq!( - messages.take(), - Vec::new(), - "{what}: the validation layer reported" - ); - } - }); - } + on_shared_device(|device, messages| { + for layout in LAYOUTS.into_iter().filter(Layout::padded) { + let queue = device.new_command_queue().unwrap(); + let len = layout.bpr * layout.h; + let buffer = device.new_buffer(len, ResourceOptions::default()).unwrap(); + let mut bytes = counting(len as usize, 11); + lay( + &layout, + &mut bytes, + &texels_of(&layout, (layout.row() * layout.h) as usize, 6), + ); + let contents = buffer.contents().unwrap(); + // SAFETY: a new `Shared` buffer of `len` bytes, which no command uses yet. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) + }; + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, 0, layout.bpr).unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + let aliased = unsafe { texture.vk_image() }.is_some(); + let what = format!("{} (ShaderRead), an ordinary buffer's", layout.name); + assert!(!aliased, "{what}: aliased"); + let texels = rows(&layout, &bytes); + let copies = || device.work_counts().shadow_copies; + let before = copies(); + let reads = reading(device, layout.pf, "tob_read"); + let read = drawn(&queue, &layout, &reads, &texture, None); + let (count, first) = differing(&read, &texels, layout.texel); + assert!( + count == 0, + "{what}, its first use: {count} texels read differ from the buffer's, the first \ + at texel {first:?}" + ); + let now = bytes_of(&buffer); + assert!( + now == bytes, + "{what}, its first use: the bytes between the rows (or past the last) changed: {}", + padding_changes(&layout, &now, &bytes) + ); + let samples = reading(device, layout.pf, "tob_sample"); + let nearest = sampler(device, SamplerMinMagFilter::Nearest); + let got = drawn(&queue, &layout, &samples, &texture, Some(&nearest)); + assert!( + got == texels, + "{what}: a sample differs from the buffer's texels" + ); + let copied = copies() - before; + assert!( + bytes_of(&buffer) == bytes, + "{what}: the buffer's bytes changed" + ); + let reason = messages + .take_notices() + .into_iter() + .filter_map(|message| message.degradation) + .find(|notice| notice.degradation == Degradation::ShadowedTexture) + .map(|notice| format!(": {}", notice.reason)) + .unwrap_or_default(); + eprintln!( + "PITCHED-READS on {}: {what}: shadowed, {copied} shadow copies over a read and a \ + sample{reason}", + device.name(), + ); + drop((texture, buffer)); + assert_eq!( + messages.take(), + Vec::new(), + "{what}: the validation layer reported" + ); + } + }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs b/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs index 6bdf37e2a..913ff9bf6 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs @@ -1031,22 +1031,25 @@ fn a_heap_s_token_drops_at_its_release_whatever_keeps_its_textures_images() { /// /// - the consumer's surface texture (its `Beside::PendingArgument`): a texture of an IOSurface /// plane over a no-copy buffer of the surface's pages (`new_texture_with_iosurface_plane`), -/// whose deallocator, the consumer's hold on the surface (a use the host sees), runs at the -/// texture's release, as Metal lets go of the surface. The deallocator scribbles over the pages, -/// as a caller reusing them would: the waiting command buffer, which starts after it, reads the -/// neutral through the ID, never the pages, and completes cleanly; -/// - a texture over a buffer of the runtime's memory, whose range token drops then. +/// a shadow on every device (`shadowed-texture`), whose image lies in memory of its own; +/// the buffer's deallocator, the consumer's hold on the surface (a use the host sees), runs at +/// the texture's release, as Metal lets go of the surface. The deallocator scribbles over the +/// pages, as a caller reusing them would: the waiting command buffer, which starts after it, +/// reads the neutral through the ID, never the pages, and completes cleanly; +/// - a texture over a buffer of the runtime's memory, an image bound to the buffer's memory where +/// a linear image of the device holds its texels alone, else a shadow, whose range token drops +/// then. /// -/// A texture over host pages the device holds as a shadow (`shadowed-texture`) is announced as -/// its ID's holder once (`UNNAMED_SHADOWS`): the command binds the heap set holding it with its -/// ID in the argument buffer, neither naming it nor making it resident, so its function may read -/// the shadow stale; nothing else is. +/// A shadow is announced as its ID's holder once (`UNNAMED_SHADOWS`): the command binds the heap +/// set holding it with its ID in the argument buffer, neither naming it nor making it resident, +/// so its function may read the shadow stale; nothing else is. #[test] fn a_buffer_under_a_texture_goes_at_its_release_whatever_keeps_the_image() { let mapping = Mapping::anonymous(GUEST_PAGE); on_device(|device, messages| { let sampling = Sampling::new(device); let reads = Reads::of(device, &sampling); + let mut surface = false; for form in ["surface plane", "runtime memory"] { let gone = Arc::new(AtomicBool::new(false)); let noted = Arc::clone(&gone); @@ -1081,9 +1084,9 @@ fn a_buffer_under_a_texture_goes_at_its_release_whatever_keeps_the_image() { device.new_buffer_with_descriptor(descriptor).unwrap() } }; - // A surface format the devices bind to the pages (an image over them, not a shadow, - // where they can: its rows packed, as wide as a device's linear rows), unsigned as the - // kernel's: what it reads is gone anyway. + // A format and rows a device's linear image holds alone (an image bound to the + // runtime's memory, not a shadow, where it can: its rows packed, as wide as a device's + // linear rows), unsigned as the kernel's: what it reads is gone anyway. let mut d = TextureDescriptor::texture_2d(PixelFormat::RGBA8Uint, ROW_TEXELS, 2, false); d.usage = TextureUsage::SHADER_READ; d.resource_options = buffer.resource_options(); @@ -1101,6 +1104,11 @@ fn a_buffer_under_a_texture_goes_at_its_release_whatever_keeps_the_image() { "SURFACE-HOLD {} {form}: an image bound to the bytes: {bound}", device.name() ); + assert!( + !(bound && form == "surface plane"), + "{form}: a texture over host pages takes an image bound to them" + ); + surface |= form == "surface plane"; drop(buffer); assert!(!gone.load(Ordering::SeqCst), "{form}: its texture keeps it"); let event = device.new_shared_event().unwrap(); @@ -1116,8 +1124,12 @@ fn a_buffer_under_a_texture_goes_at_its_release_whatever_keeps_the_image() { let output = sampling.output(&command_buffer, &buffers); assert_eq!(output, reads.neutral, "{form}"); } - // A shadow where the device's linear rows lie otherwise, which its driver decides. - let shadowed = row_shadow_kinds(device); + // The surface's shadow, and the runtime memory's where the device's linear rows lie + // otherwise, which its driver decides. + let shadowed = match surface { + true => [Degradation::ShadowedTexture, UNNAMED_SHADOWS[0]].into(), + false => row_shadow_kinds(device), + }; println!( "SURFACE-HOLD {}: a shadow: {}", device.name(), @@ -1129,13 +1141,12 @@ fn a_buffer_under_a_texture_goes_at_its_release_whatever_keeps_the_image() { /// A no-copy buffer and a texture over it released while a submitted command buffer that may /// read the texture through its ID runs (its dispatch submitted and done, which an event it -/// signals then shows; a wait for another event after it holds it): where the texture's image is -/// bound to the buffer's pages, the image, and the device's import of the pages, stay until that -/// command buffer completed. With a keep-alive the deallocator runs at the release, as Metal's -/// does (EV XRB-bft1-m4), and the keep-alive goes only once the command buffer completed; with -/// none the deallocator waits for that, counted (`host_deallocators_delayed`) and announced once -/// ([`DELAYED_DEALLOCATORS`]). A texture whose image is its own (a shadow) holds no import: both -/// run at the release. A command buffer committed but not yet submitted holds nothing +/// signals then shows; a wait for another event after it holds it). The texture is a shadow +/// (`shadowed-texture`), whose image lies in memory of its own and holds no import of the pages: +/// the deallocator runs at the release, as Metal's does, with a keep-alive or +/// without, and nothing waits for the command buffer; a keep-alive goes on one of the device's +/// handler threads, after the import's free (`HostImport`'s drop). A command buffer committed but +/// not yet submitted holds nothing /// ([`a_buffer_under_a_texture_goes_at_its_release_whatever_keeps_the_image`]). The device /// reports nothing either way. #[test] @@ -1143,7 +1154,6 @@ fn a_no_copy_buffer_s_deallocator_runs_at_its_release_given_a_keep_alive() { let mapping = Mapping::anonymous(GUEST_PAGE); on_device(|device, messages| { let sampling = Sampling::new(device); - let mut delays = 0; for keeps in [true, false] { let ran = Arc::new(AtomicBool::new(false)); let kept_dropped = Arc::new(AtomicBool::new(false)); @@ -1172,51 +1182,42 @@ fn a_no_copy_buffer_s_deallocator_runs_at_its_release_given_a_keep_alive() { d.usage = TextureUsage::SHADER_READ; d.resource_options = buffer.resource_options(); let doomed = buffer.new_texture(&d, 0, ROW_BYTES).unwrap(); + let what = format!("keep-alive {keeps}"); // SAFETY: the handle is only compared, while the texture lives. let bound = unsafe { doomed.vk_image() }.is_some(); + assert!( + !bound, + "{what}: a texture over host pages takes an image bound to them" + ); let reaching = sampling.reaching(device, &doomed); let delayed = device.work_counts().host_deallocators_delayed; drop(buffer); drop(doomed); - let what = format!("keep-alive {keeps}, an image bound to the bytes {bound}"); println!("DEALLOCATOR-HOLD {}: {what}", device.name()); - // The image holds the import where it is bound to the pages. - let delay = bound && !keeps; - assert_eq!( + assert!( ran.load(Ordering::SeqCst), - !delay, "{what}: the deallocator at the release" ); + // Nothing holds the import: it is freed with only the keep-alive waiting for the free, + // on one of the device's handler threads, and the keep-alive goes there after it. let deadline = Instant::now() + WAIT; + while keeps && !kept_dropped.load(Ordering::SeqCst) && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(10)); } assert_eq!( kept_dropped.load(Ordering::SeqCst), + keeps, "{what}: the keep-alive with the import's free" ); assert_eq!( device.work_counts().host_deallocators_delayed, - delayed + u64::from(delay), + delayed, "{what}: counted delayed" ); reaching.complete(&sampling); - // The import goes as the command buffer lets go of the image: the deallocator waiting - // for it runs then, and the keep-alive goes. - let done = - || ran.load(Ordering::SeqCst) && kept_dropped.load(Ordering::SeqCst) == keeps; - let deadline = Instant::now() + WAIT; - while !done() && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(10)); - } - assert!(done(), "{what}: once the command buffer completed"); - delays += usize::from(delay); - } - // A shadow, where the device's linear rows lie otherwise, reached through its ID is - // announced as the lane above says. - let mut expected = row_shadow_kinds(device); - if delays > 0 { - expected.extend(DELAYED_DEALLOCATORS); } + // The shadow, reached through its ID, is announced as the lane above says. + let expected = [Degradation::ShadowedTexture, UNNAMED_SHADOWS[0]]; sampling.announced(device, messages, &expected); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rotated_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/rotated_textures.rs index dfbfb7efc..fb3d800e3 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rotated_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rotated_textures.rs @@ -414,6 +414,22 @@ fn passes_store_load_and_resolve_rotated_textures_as_metal_turns_them() { // Cleared and drawn over everything. let before = bytes_of(&plane); lane.pass(&texture, LoadAction::Clear, false, &source, (w, h)); + // A rotated texture's rows go back out of its staging buffer as a copy of rows + // (`row_copies.rs`): rows that lie one after another as one region, which takes no + // dispatch; rows that lie apart as one dispatch where the device runs it faster. + let regions = device.work_counts().row_copy_regions - counts.row_copy_regions; + match bpr == sw * TEXEL { + true => assert_eq!( + (dispatched, regions), + (0, copies), + "{what}: packed rows, one region a copy and no dispatch" + ), + false => assert_eq!( + dispatched, + copies * super::row_copies::dispatches(&device), + "{what}: dispatched copies of rows" + ), + } let want = expected(rotation, (w, h), bpr, (w, h), &before, |_, _| [0; 4]); if let Some(at) = first_difference(&bytes_of(&plane), &want, bpr) { panic!("{what}, a clear and a full draw: {at}"); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs index d2d36ea13..8d19f789e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs @@ -22,6 +22,7 @@ //! and 90th percentile of the host's time making the buffer, making the texture and releasing //! both, per texture; per frame, the encoding and the commit-to-completion wall time and the //! process's CPU time; and the device's work counts per frame that the path moves (dma-buf images +//! and fallbacks, shadows and those zeroed as made, images started on the host, internal //! submissions, shadows' copies and the texels their copies in and back move, the merges' //! scratches reused and zeroed, the merges that fetched their texels, the command buffers begun by //! what for, the render pass begins and secondary executions replayed, and the passes whose first @@ -37,25 +38,18 @@ //! memories, to tell the image's tiling from the pages' memory (`SURFTEX-COPY`). //! //! [`read_only_padded_costs`] times a compositor's frame over the padded layouts' textures made -//! with `ShaderRead` usage alone, each sampled by a draw, under each `PaddedReadsPolicy`: an image -//! over the rows (`Alias`, the default) against the shadow copied in at each use (`Shadow`), -//! interleaved (`SURFTEX-READS`). +//! with `ShaderRead` usage alone, each sampled by a draw: shadows copied in at each use, made each +//! frame or once (`SURFTEX-READS`). //! -//! [`tight_keep_costs`] times what a first move that keeps its image's bytes costs, over packed -//! rows: a 1080p surface, a 720p one and four tiles, each texture new each frame over a new buffer -//! (the surface's pages held by nothing else, or joining a buffer kept over them, as a consumer -//! makes one at each present) or made once every 60 frames (`SURFTEX-KEEP`). -//! -//! All six are ignored by default: measurements, not checks. Run them by name with `--run-ignored all`, in a -//! build with `--cfg m2v_system_alloc`, whose lib test binary keeps the system allocator as a -//! consumer's process does. +//! All four are ignored by default: measurements, not checks. Run them by name with +//! `--run-ignored all`, in a build with `--cfg m2v_system_alloc`, whose lib test binary keeps the +//! system allocator as a consumer's process does. use super::dma_buf_imports::{udmabuf_openable, Calls, Memfd, View}; use super::host_memory::{host_page, Mapping, GUEST_PAGE}; use super::no_copy_textures::{blending, floats, staged}; use super::{validated_device_with, Messages, ScratchCache, WAIT}; use crate::gpu::TEST_DEVICE; -use ash::vk; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan_runtime::{ BlitOption, Buffer, CommandQueue, Device, HostMemory, IoSurfacePlane, LoadAction, Origin, @@ -290,8 +284,7 @@ fn frame( fn counts_per_frame(before: &WorkCounts, after: &WorkCounts, frames: usize) -> String { let per = |a: u64, b: u64| (a - b) as f64 / frames as f64; format!( - "shadowed textures {:.2} (zeroed {:.2}), pitched host images {:.2} (refused {:.2}, \ - recalled {:.2}), dma-buf images {:.2}, dma-buf image fallbacks {:.2}, dma-buf imports \ + "shadowed textures {:.2} (zeroed {:.2}), dma-buf images {:.2}, dma-buf image fallbacks {:.2}, dma-buf imports \ {:.2}, images started on the host {:.2}, internal submissions {:.2}, staging submissions \ {:.2}, shadow copies {:.2} (texels copied in {:.0}, back {:.0}; copies back dispatched \ {:.2}; keeps and merges dispatched {:.2}, texels kept {:.0}; merge scratches reused \ @@ -301,15 +294,6 @@ fn counts_per_frame(before: &WorkCounts, after: &WorkCounts, frames: usize) -> S recorded inline {:.2}", per(after.shadowed_textures, before.shadowed_textures), per(after.shadows_zeroed, before.shadows_zeroed), - per(after.pitched_host_images, before.pitched_host_images), - per( - after.pitched_host_image_refusals, - before.pitched_host_image_refusals - ), - per( - after.pitched_host_image_refusals_recalled, - before.pitched_host_image_refusals_recalled - ), per(after.dma_buf_images, before.dma_buf_images), per( after.dma_buf_image_fallbacks, @@ -396,7 +380,6 @@ fn surface_texture_costs() { }) .unwrap(); messages.take_notices(); - print_host_modifier_queries(&device); let queue = device.new_command_queue().unwrap(); let page = host_page(); let lens: Vec = LAYOUTS @@ -787,218 +770,20 @@ fn shadow_copy_costs() { // The copies, then the buffers, then the pages they lie over go, in that order. } -/// The formats [`pitch_classes`] asks about, with their texel bytes. -const SWEPT_FORMATS: [(PixelFormat, u64); 9] = [ - (PixelFormat::BGRA8Unorm, 4), - (PixelFormat::RGBA8Unorm, 4), - (PixelFormat::RGB10A2Unorm, 4), - (PixelFormat::RGBA16Float, 8), - (PixelFormat::R8Unorm, 1), - (PixelFormat::RG8Unorm, 2), - (PixelFormat::R16Float, 2), - (PixelFormat::R32Float, 4), - (PixelFormat::RGBA32Float, 16), -]; - -/// The widths [`pitch_classes`] makes textures of, and their height. -const SWEPT_WIDTHS: [u64; 5] = [5, 64, 300, 1307, 1913]; -const SWEPT_HEIGHT: u64 = 16; - -/// The largest power-of-two class [`pitch_classes`] asks about: 2^12 bytes. -const SWEPT_CLASSES: std::ops::RangeInclusive = 4..=12; - -/// The form a texture over host pages took, by what its making counted. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -enum Form { - /// The driver's own linear image lies at the pitch. - Own, - /// A `DRM_FORMAT_MOD_LINEAR` image at Metal's row pitch. - Pitched, - /// A shadow: the driver refused the image at Metal's row pitch, asked. - Refused, - /// A shadow: the driver refused the same image before, and was not asked again. - Recalled, - /// A shadow for another reason (the modifier's features or the format query). - Shadowed, - /// The texture was refused. - Failed, -} - -/// The two smallest odd multiples of `class` (a power of two) at least `row`: two pitches whose -/// class is exactly `class`. -fn pitches_of_class(row: u64, class: u64) -> [u64; 2] { - let mut first = row.next_multiple_of(class); - if (first / class).is_multiple_of(2) { - first += class; - } - [first, first + 2 * class] -} - -/// A texture of `d` over a new no-copy buffer of `len` bytes of `mapping`, rows `bpr` apart: the -/// form its making took, and the host's time making it. -fn swept( - device: &Device, - mapping: &Mapping, - len: usize, - d: &TextureDescriptor, - bpr: u64, -) -> (Form, f64) { - // SAFETY: the mapping outlives the buffer, dropped here. - let buffer = unsafe { - device.new_buffer_with_bytes_no_copy( - HostMemory::new(mapping.pointer()), - len as u64, - ResourceOptions::default(), - None, - ) - } - .unwrap(); - let mut d = *d; - d.resource_options = buffer.resource_options(); - let before = device.work_counts(); - let began = Instant::now(); - let made = buffer.new_texture(&d, 0, bpr); - let took = since(began); - let after = device.work_counts(); - let moved = |count: fn(&WorkCounts) -> u64| count(&after) > count(&before); - let form = match made { - Err(_) => Form::Failed, - Ok(_) if moved(|c| c.pitched_host_images) => Form::Pitched, - Ok(_) if moved(|c| c.pitched_host_image_refusals) => Form::Refused, - Ok(_) if moved(|c| c.pitched_host_image_refusals_recalled) => Form::Recalled, - Ok(_) if moved(|c| c.shadowed_textures) => Form::Shadowed, - Ok(_) => Form::Own, - }; - (form, took) -} - -#[test] -#[ignore = "a release-mode measurement: run by name"] -fn pitch_classes() { - let cache = ScratchCache::new().unwrap(); - let messages = Messages::default(); - let largest = SWEPT_FORMATS.iter().map(|&(_, texel)| texel).max().unwrap(); - let widest = SWEPT_WIDTHS.iter().max().unwrap() * largest + (4 << *SWEPT_CLASSES.end()); - let len = Surface::len(widest, SWEPT_HEIGHT); - let mapping = Mapping::anonymous(len); - let usages = [ - ("read", TextureUsage::SHADER_READ), - ( - "read+render", - TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET, - ), - ( - "read+write", - TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE, - ), - ( - "read+write+render", - TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE | TextureUsage::RENDER_TARGET, - ), - ]; - let mut times: std::collections::BTreeMap> = Default::default(); - let mut name = String::new(); - for &(pf, texel) in &SWEPT_FORMATS { - for &(usage_name, usage) in &usages { - // A device for each format and usage, which announces its first shadow's reason. - let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { - options.layers.clear(); - }) - .unwrap(); - messages.take_notices(); - name = device.name().to_owned(); - let (mut pitched_classes, mut refused_classes, mut mixed) = - (Vec::new(), Vec::new(), Vec::new()); - for class in SWEPT_CLASSES.map(|bits| 1u64 << bits) { - let mut forms = Vec::new(); - for &w in &SWEPT_WIDTHS { - for bpr in pitches_of_class(w * texel, class) { - let mut d = TextureDescriptor::texture_2d(pf, w, SWEPT_HEIGHT, false); - d.usage = usage; - // Made twice: the second making of a refused image recalls the refusal. - for _ in 0..2 { - let (form, took) = swept(&device, &mapping, len, &d, bpr); - times.entry(form).or_default().push(took); - forms.push((w, bpr, form)); - } - } - } - // Every texture the driver's own linear image does not alias took one answer - // (a recalled refusal is the driver's earlier one). - let answers: std::collections::BTreeSet
= forms - .iter() - .map(|&(_, _, form)| match form { - Form::Recalled => Form::Refused, - form => form, - }) - .filter(|&form| form != Form::Own) - .collect(); - let one = answers.len() <= 1; - match answers.iter().next() { - _ if !one => mixed.push(class), - Some(Form::Pitched) => pitched_classes.push(class), - Some(_) => refused_classes.push(class), - None => {} - } - let count = |form: Form| forms.iter().filter(|&&(_, _, f)| f == form).count(); - println!( - "SURFTEX-PITCH on {}: {} {usage_name} class {class}: own linear {}, pitched \ - {}, refused {} (recalled {}), shadowed {}, failed {}; one answer {one}{}", - device.name(), - pf.name(), - count(Form::Own), - count(Form::Pitched), - count(Form::Refused), - count(Form::Recalled), - count(Form::Shadowed), - count(Form::Failed), - if one { - String::new() - } else { - format!(" ({forms:?})") - }, - ); - } - let reason = messages - .take_notices() - .into_iter() - .find_map(|message| message.degradation.map(|notice| notice.reason)) - .unwrap_or_else(|| "no shadow".to_owned()); - println!( - "SURFTEX-PITCH-RULE on {}: {} {usage_name}: at Metal's pitch {pitched_classes:?}, \ - shadowed {refused_classes:?}, mixed {mixed:?}; the first shadow: {reason}", - device.name(), - pf.name(), - ); - } - } - for (form, took) in times { - let count = took.len(); - let (median, p90) = median_p90(took); - println!( - "SURFTEX-PITCH-TIME on {name}: {form:?}: {count} textures, making {median:.1} us (p90 \ - {p90:.1})" - ); - } -} - /// A compositor's frame over textures that only read: each frame, for each padded layout of /// [`LAYOUTS`] (the tight one left out), a no-copy buffer over its surface's anonymous pages and a /// texture of its plane over it with `ShaderRead` usage alone; one pass into a private target of /// the browser's tile, drawing each texture over the whole target through a nearest sampler; one /// command buffer, committed and waited for; then the textures and buffers are released. Or, where -/// `reused`, the textures are made once and every frame samples them. Run under -/// `PaddedReadsPolicy::Alias` (an image over the rows where the device lays one, whose first move -/// keeps its texels) and `Shadow` (the shadow, copied in before the pass), a device each, the two -/// interleaved in rounds so a drift of the host's falls on both. Printed per policy, reuse and -/// round (`SURFTEX-READS`): the textures' forms, the medians and 90th percentiles of a texture's -/// making, the frame's encoding, commit to completion and process CPU time, and the shadow copies -/// and first moves' keeps a frame. +/// `reused`, the textures are made once and every frame samples them; each texture a shadow, +/// copied in before the pass; a device each, the two interleaved in rounds so a drift of the +/// host's falls on both. Printed per reuse and round (`SURFTEX-READS`): the textures' forms, the +/// medians and 90th percentiles of a texture's making, the frame's encoding, commit to completion +/// and process CPU time, and the shadow copies a frame. #[test] #[ignore = "a release-mode measurement: run by name"] fn read_only_padded_costs() { use super::pitched_surfaces::{reading, sampler}; - use metal2vulkan::device::PaddedReadsPolicy; use metal2vulkan::metal::SamplerMinMagFilter; let chosen: Vec = (0..LAYOUTS.len()) .filter(|&i| LAYOUTS[i].3 != LAYOUTS[i].1 * 4) @@ -1007,17 +792,12 @@ fn read_only_padded_costs() { .iter() .map(|&(_, _, h, bpr)| Surface::Anonymous(Mapping::anonymous(Surface::len(bpr, h)))) .collect(); - let modes = [false, true].into_iter().flat_map(|reused| { - [PaddedReadsPolicy::Alias, PaddedReadsPolicy::Shadow].map(|policy| (reused, policy)) - }); - let modes: Vec<(bool, PaddedReadsPolicy)> = modes.collect(); for round in 0..3 { - for &(reused, policy) in &modes { + for reused in [false, true] { let cache = ScratchCache::new().unwrap(); let messages = Messages::default(); let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { options.layers.clear(); - options.policy.padded_reads = policy; }) .unwrap(); messages.take_notices(); @@ -1101,189 +881,19 @@ fn read_only_padded_costs() { drop(made); let after = device.work_counts(); let copies = (after.shadow_copies - before.shadow_copies) as f64 / FRAMES as f64; - let keeps = (after.first_move_keeps - before.first_move_keeps) as f64 / FRAMES as f64; let (make, make90) = median_p90(makes); let (encode, encode90) = median_p90(encodes); let (wait, wait90) = median_p90(waits); let (cpu, cpu90) = median_p90(cpus); println!( - "SURFTEX-READS on {}: round {round}, {policy:?}, reused {reused}, forms {forms} \ + "SURFTEX-READS on {}: round {round}, reused {reused}, forms {forms} \ (a aliased, s shadowed): making {make:.0} us a texture (p90 {make90:.0}), encode \ {encode:.0} us (p90 {encode90:.0}), commit to completion {wait:.0} us (p90 \ {wait90:.0}), process CPU {cpu:.0} us (p90 {cpu90:.0}); shadow copies a frame \ - {copies:.2}, keeps a frame {keeps:.2}", + {copies:.2}", device.name(), ); } } drop(surfaces); } - -/// A surface's plane: its width, height and bytes per row (`BGRA8Unorm`). -type Plane = (u64, u64, u64); - -/// The packed-row surfaces [`tight_keep_costs`] samples, by shape, at pitches every measured -/// driver lays a linear image at. -const TIGHT: [(&str, &[Plane]); 3] = [ - ("1920x1080", &[(1920, 1080, 7680)]), - ("1280x720", &[(1280, 720, 5120)]), - ("4x512x512", &[(512, 512, 2048); 4]), -]; - -/// How [`tight_keep_costs`] makes its textures, each after the ones before were released: a new -/// buffer and texture over each surface each frame, its pages held by nothing else (`OneUse`); the -/// same while a buffer over each surface's pages lives across frames, whose import the new buffers -/// join (`PerPresent`: a consumer's texture over the presented surface at each present, beside its -/// buffer over the whole surface, where they share one image, `texture/shared_alias.rs`); or as -/// `OneUse` once every 60 frames (`SixtyUses`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Making { - OneUse, - PerPresent, - SixtyUses, -} - -/// The first moves that kept their bytes so far, the bytes (`WorkCounts::first_move_keeps`), and -/// the textures that took a shared image (`shared_alias_images`). -fn keeps(counts: &WorkCounts) -> (u64, u64, u64) { - ( - counts.first_move_keeps, - counts.first_move_kept_bytes, - counts.shared_alias_images, - ) -} - -/// What a texture's first move that keeps its image's bytes costs (`texture/first_move.rs`'s -/// `Keep`), on the device the cfg selects. For each shape of [`TIGHT`] (a 1080p surface, a 720p -/// one, four 512x512 tiles) over anonymous pages, textures with `ShaderRead` usage over no-copy -/// buffers of the surfaces' packed rows, each sampled by a draw of one pass a frame into a private -/// target of the first surface's size, committed and waited for, made as each [`Making`] says; each -/// shape and making on a device of its own, interleaved in rounds so a drift of the host's falls -/// on all. Printed per round, shape and making (`SURFTEX-KEEP`): the textures' forms (shadows -/// counted), the medians and 90th percentiles of a texture's making, the frame's commit to -/// completion and process CPU time, and the keeps, kept bytes and shared images taken a frame. -#[test] -#[ignore = "a release-mode measurement: run by name"] -fn tight_keep_costs() { - use super::pitched_surfaces::{reading, sampler}; - use metal2vulkan::metal::SamplerMinMagFilter; - for round in 0..3 { - for (shape, planes) in TIGHT { - let surfaces: Vec = planes - .iter() - .map(|&(_, h, bpr)| Surface::Anonymous(Mapping::anonymous(Surface::len(bpr, h)))) - .collect(); - for making in [Making::OneUse, Making::PerPresent, Making::SixtyUses] { - let cache = ScratchCache::new().unwrap(); - let messages = Messages::default(); - let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |o| { - o.layers.clear(); - }) - .unwrap(); - let queue = device.new_command_queue().unwrap(); - let pipeline = reading(&device, PixelFormat::BGRA8Unorm, "tob_sample"); - let nearest = sampler(&device, SamplerMinMagFilter::Nearest); - let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); - let (tw, th, _) = planes[0]; - let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, tw, th, false); - d.usage = TextureUsage::RENDER_TARGET; - d.resource_options = ResourceOptions::private(); - let target = device.new_texture(&d).unwrap(); - let texture_over = |buffer: &Buffer, (w, h, bpr): Plane| { - let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, w, h, false); - d.usage = TextureUsage::SHADER_READ; - d.resource_options = buffer.resource_options(); - buffer - .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, bpr, false)) - .unwrap() - }; - let buffers = |device: &Device| -> Vec { - (surfaces.iter().zip(planes)) - .map(|(surface, &(_, h, bpr))| { - surface.buffer(device, Surface::len(bpr, h), None) - }) - .collect() - }; - let kept_buffers = match making { - Making::PerPresent => buffers(&device), - Making::OneUse | Making::SixtyUses => Vec::new(), - }; - let mut made: Vec<(Texture, Buffer)> = Vec::new(); - let (mut makes, mut waits, mut cpus) = (Vec::new(), Vec::new(), Vec::new()); - let mut before = device.work_counts(); - let mut shadows = 0; - for k in 0..WARM + FRAMES { - if k == WARM { - before = device.work_counts(); - } - let cpu = process_cpu_us(); - let anew = match making { - Making::OneUse | Making::PerPresent => true, - Making::SixtyUses => k % 60 == 0, - }; - if anew { - made.clear(); - let counted = device.work_counts().shadowed_textures; - let began = Instant::now(); - made = (buffers(&device).into_iter().zip(planes)) - .map(|(buffer, &plane)| (texture_over(&buffer, plane), buffer)) - .collect(); - if k >= WARM { - makes.push(since(began) / planes.len() as f64); - } - shadows = device.work_counts().shadowed_textures - counted; - } - let command_buffer = queue.command_buffer().unwrap(); - let mut pass = RenderPassDescriptor::new(); - let attachment = &mut pass.color_attachments[0]; - attachment.texture = Some(target.clone()); - attachment.load_action = LoadAction::Clear; - attachment.store_action = StoreAction::Store; - let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); - encoder.set_render_pipeline_state(&pipeline).unwrap(); - encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); - encoder - .set_fragment_sampler_state(Some(&nearest), 0) - .unwrap(); - for (texture, _) in &made { - encoder.set_fragment_texture(Some(texture), 0).unwrap(); - encoder - .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) - .unwrap(); - } - encoder.end_encoding().unwrap(); - let committed = Instant::now(); - command_buffer.commit().unwrap(); - command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert_eq!(command_buffer.error(), None); - let waited = since(committed); - if k >= WARM { - waits.push(waited); - cpus.push(process_cpu_us() - cpu); - } - } - drop(made); - let after = device.work_counts(); - let ((kept, bytes, took), (kept0, bytes0, took0)) = (keeps(&after), keeps(&before)); - let frames = FRAMES as f64; - let (make, make90) = median_p90(makes); - let (wait, wait90) = median_p90(waits); - let (cpu, cpu90) = median_p90(cpus); - println!( - "SURFTEX-KEEP on {}: round {round}, {shape}, {making:?}: {} textures, {shadows} \ - shadowed; making {make:.0} us a texture (p90 {make90:.0}), commit to \ - completion {wait:.0} us (p90 {wait90:.0}), process CPU {cpu:.0} us (p90 \ - {cpu90:.0}); keeps a frame {:.2}, kept MB a frame {:.2}, shared images a \ - frame {:.2}", - device.name(), - planes.len(), - (kept - kept0) as f64 / frames, - (bytes - bytes0) as f64 / frames / 1e6, - (took - took0) as f64 / frames, - ); - drop(kept_buffers); - } - drop(surfaces); - } - } -} diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index c39bed026..1921f51f8 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -3,6 +3,7 @@ use crate::device::profile::{FramebufferFetchPolicy, GuestIsolation, HandleDomain, PointerDomain}; +/// Policy inputs of `Device::new`. Every field but `decoded_texels`, `heap_compression`, /// `completion`, `tile_store`, `resolve` and `batch_order` can change emitted code, so the profile /// carries it (containment as the encoding it selects) and its fingerprint covers it; those six /// are the runtime's alone (the texels of a carried texture's decoded twin, a heap's compressed @@ -98,6 +99,10 @@ impl DevicePolicy { /// emulation runs, native device sampling (a two-plane YCbCr texture's samples among them), /// native device maths, the device's own texel /// conversions, native half rounding, the device's NaN and minimum and maximum, the device's + /// rounding order, the device's blend of a `half` output into a 16-bit float attachment, + /// compact codes in a carried texture's decoded twin, the driver's compressed image of a + /// heap's texture Metal keeps compressed, command buffers ready together in one kernel + /// submission, the device's load and store of a signed normalized or `RGB9E5Float` color /// attachment, the device's resolve of a multisampled color attachment, and batches of one /// queue ordered by their ends where the driver runs them one after another. pub const UNTRUSTED: DevicePolicy = DevicePolicy { @@ -129,6 +134,8 @@ impl DevicePolicy { /// NaN and minimum and maximum ([`NanMinMaxPolicy::Exact`]), its rounding order /// ([`RoundingOrderPolicy::Exact`]), its 16-bit float blend of a `half` output /// ([`HalfBlendPolicy::Exact`]), its filter of a two-plane YCbCr texture + /// ([`YCbCrFilterPolicy::Exact`]), its decode of a carried texture's texels + /// ([`DecodedTexelsPolicy::Exact`]), a heap's texture whose bytes alias the heap's /// as written ([`HeapCompressionPolicy::Uncompressed`]), each command buffer seen complete /// at its own end ([`CompletionPolicy::Exact`]), a loaded attachment's texels as its tile /// store leaves them ([`TileStorePolicy::Exact`]), its multisample color resolve diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index 7d7bd1f2c..ff6721483 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -1304,7 +1304,6 @@ fn largest_stage_words(pipeline: &RenderPipeline) -> u32 { /// two-plane YCbCr texture (`YCbCrFilterPolicy::Exact`, reported with it); `AllNative` drops every /// module-growing exact answer (the fast default's forms). Neither touches the policy's other /// choices (pointer and handle domains, containment, isolation, framebuffer fetch, the 8-bit -/// filter, or `padded_reads`, which changes no module), so a reduced device keeps them. #[derive(Clone, Copy)] enum ReducedForms { NativeSampling, diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index 82ec3bec6..c37c497f3 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -70,6 +70,8 @@ fn choices() -> Vec { nan_and_min_max: _, rounding_order: _, half_blend: _, + // The runtime's: the texels of a carried texture's decoded twin, a heap's compressed + // texture's image, when the host sees a command buffer complete, a loaded attachment's // tile store, a multisampled color attachment's resolve, and how a batch begins after the // earlier ones of its queue. decoded_texels: _, diff --git a/docs/API.md b/docs/API.md index 6d81c46a7..9887c0252 100644 --- a/docs/API.md +++ b/docs/API.md @@ -180,44 +180,19 @@ What the runtime enables for itself outside the vocabulary enters no enable set, or fingerprint: among it the extensions of its dma-buf fallback for no-copy memory whose pointer the device refuses (`HostMemory::with_dma_buf`), `VK_EXT_external_memory_dma_buf` with `VK_KHR_external_memory_fd`, and `VK_EXT_image_drm_format_modifier` with -`VK_EXT_queue_family_foreign` beside them, wherever a device lists them. With them enabled, a -texture over a no-copy buffer's pages imported by their pointer, its rows packed, is also a -`DRM_FORMAT_MOD_LINEAR` image made for host allocations at Metal's row pitch where the driver's own -linear image lays its rows out otherwise and the driver takes that layout, of a format with no depth -or stencil component (Vulkan has no query of where such a format's memory plane lies, so the runtime -makes no `DRM_FORMAT_MOD_LINEAR` image of one) -(`WorkCounts::pitched_host_images`; HOWTO.md section 6 lists what each measured driver takes). -`Texture::vk_image` then gives that image. A layout the driver refused is kept per device and not -asked again (`pitched_host_image_refusals`, `pitched_host_image_refusals_recalled`). +`VK_EXT_queue_family_foreign` beside them, wherever a device lists them. -An image over a no-copy buffer's pages imported by their pointer (the driver's linear image or such -a `DRM_FORMAT_MOD_LINEAR` image, both made for host allocations, and on MoltenVK the image of a -Metal texture over the import's `MTLBuffer`) starts in `VK_IMAGE_LAYOUT_UNDEFINED`, as Vulkan makes -an image for host allocations, and a move from there leaves its memory's contents undefined. Its -first move, made by the next submission that may reach it (any command buffer's, or the internal -submission of a host call on the texture, or `Texture::vk_image`), keeps the bytes the image is -bound to, through the host: before that submission, once every submission made before it on each -queue completed, the runtime reads them through the host pointer, submits the move alone and waits -for it, and writes back the bytes the move changed, so none is stored where it changed none (pages -the process cannot write stay untouched); no GPU command writes them, and no byte outside them is -touched (`WorkCounts::first_move_keeps`, `first_move_kept_bytes`, `first_move_restored_bytes`). -Changed bytes on pages the process no longer maps writable keep the move's values, announced -(`unrestored-first-move-bytes`). The submission waits for that, -`commit` never. A rebind's new image keeps its new pages' bytes the same way. An image -over a dma-buf of its own pages keeps them through its acquire from `VK_QUEUE_FAMILY_FOREIGN_EXT`, -and a linear image of the runtime's own memory through its move from `PREINITIALIZED`. -FAST-PATHS.md's known gaps state what this differs from Metal in. - -Textures of one image over the same bytes of one import of host pages (the same plan, row and -slice pitches and form, at the same place in the import) share one `VkImage`, which the import -holds while it lives (the four images of it made or taken last), and every texture over it holds -too: a consumer's texture over the presented surface made at each present, each over a new no-copy -buffer of the same pages that joins the import of a buffer kept over them, takes the image the -first made, already moved, though the texture before was released, so its texels are kept once per -surface, and over dma-buf pages the pages' source is not asked again -(`WorkCounts::shared_alias_images`). Each texture stays its own object, with its own resource ID, -views and hazard tracking; `Texture::vk_image` gives each the shared `VkImage`. A rebind or detach of -one texture's buffer gives that texture an image of its own over the new pages, or a stand-in. +A texture over a no-copy buffer's host pages (imported by their pointer or as dma-bufs) is a shadow +(`shadowed-texture`): an optimal image of the runtime's own memory, whose texels the encoders copy +in from the pages before a use and back (merged back: only the bytes the commands changed) after a +write. No image is bound to the pages: an image bound to imported memory starts in +`VK_IMAGE_LAYOUT_UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), and its first move, like any +layout transition, may read and write every byte bound to it, where Metal keeps every CPU write to +bytes a command buffer does not write. `Texture::vk_image` gives `None` for such a texture. A +texture placed in a heap over dma-buf pages is an image over a dma-buf of its own pages, which its +first submission acquires from `VK_QUEUE_FAMILY_FOREIGN_EXT`; a linear image over a buffer of the +runtime's own memory starts `VK_IMAGE_LAYOUT_PREINITIALIZED`, and its move from there keeps its +bytes. FAST-PATHS.md's costs and known gaps state what this costs and differs from Metal in. ## 2. A library @@ -963,25 +938,18 @@ how to avoid it in full. [FAST-PATHS.md](FAST-PATHS.md) lists which notes the de fast forms record, and each `PrecisionNote`'s rustdoc states its bound. - `metal2vulkan-degrade-shadowed-texture` (performance). `ShadowedTexture`: A 2D texture over a - buffer is a shadow image: its rows (or an array's slices) lie with the buffer's bytes between - them, and it renders or a shader writes it (or it only reads, under `padded_reads = - PaddedReadsPolicy::Shadow`), which an image over them would hold in its subresource, where - Vulkan lets the image's layout transitions (its first move among them) read and write any byte - of its subresources, and a render pass's load and store operations read and write back any byte - of an attachment's image subresource, and Metal leaves them as the program writes them (but - where the device's image of it is a Metal texture over the buffer, on MoltenVK); or no linear image of the device lays its texels out as - Metal does in the buffer's memory, holding no byte past them (over a no-copy buffer's imported - host memory, no linear image made for host allocations does: neither the driver's own nor, where - the device enables `VK_EXT_image_drm_format_modifier`, a `DRM_FORMAT_MOD_LINEAR` image laid out - at Metal's row pitch, which the driver may refuse for the texture's format, usage or pitch, and - which the runtime makes of no depth or stencil format, nor of a height that is no multiple of 4 - where the driver renders an explicit plane's rows past its height - (`RuntimeDriverDefect::ExplicitPlaneRowsPastHeight`, lavapipe); `WorkCounts::pitched_host_images` - counts those made, `pitched_host_image_refusals` those the driver refused), or the buffer is - over the caller's `VkBuffer`, whose memory backs no image of the runtime's, or over host pages - imported as dma-bufs (`HostMemory::with_dma_buf`) where the device makes no image over a dma-buf - of the texture's own pages (the notice names why; `WorkCounts::dma_buf_image_fallbacks` counts - it). + buffer is a shadow image: the buffer is over host pages (a no-copy buffer's, imported by their + pointer or as dma-bufs), where an image bound to them would start `UNDEFINED` and Vulkan lets its + layout transitions (its first move among them) read and write any byte bound to it, where Metal + keeps every CPU write; or its rows (or an array's slices) lie with the buffer's bytes between + them, which an image over them would hold in its subresource, where Vulkan lets the image's + layout transitions read and write any byte of its subresources, and a render pass's load and + store operations read and write back any byte of an attachment's image subresource, and Metal + leaves them as the program writes them; or no linear image of the device lays its texels out as + Metal does in the buffer's memory, holding no byte past them; or the buffer is over the caller's + `VkBuffer`, whose memory backs no image of the runtime's. Also a heap's texture over host pages + imported as dma-bufs where the device makes no image over a dma-buf of the texture's own pages + (the notice names why; `WorkCounts::dma_buf_image_fallbacks` counts it). Cost: its texels are copied into an image before each use and back after each write; a render pass that loads it as an attachment, takes it in no other way and draws under scissors copies in only the texels inside them (`WorkCounts::shadow_texels_copied_in`). Over a buffer's bytes that @@ -1989,8 +1957,7 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. - `metal2vulkan-degrade-dont-care-stand-in` (performance). `DontCareStandIn`: A pass renders a color attachment that it stores with `DontCare` (or resolves alone, `MultisampleResolve`) and whose texture's image lies over the buffer the texture lies in (a linear image over an ordinary buffer's - memory, a no-copy buffer's host pages, a dma-buf's, a surface's; on MoltenVK, a Metal texture over - a no-copy or surface buffer's `MTLBuffer`) through an image its texture keeps, so that the buffer + memory) through an image its texture keeps, so that the buffer keeps its bytes, as Metal's does: rendered in place, the pass would write them. A pass that stores the attachment renders it in place, at no cost; so does one that hands it to a driver that stores `DONT_CARE` as Metal's own `DontCare` (MoltenVK on the M3 Max and the M4), as one render pass @@ -2106,14 +2073,6 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. draw counted by a `Counting` visibility result whose fragment function writes more than one color attachment, on ANV (`RuntimeDriverDefect::OcclusionCountPerColorOutput`). Cost: the result is Metal's count multiplied by the colors the draw writes; a `Boolean` result is Metal's. -- `metal2vulkan-degrade-unrestored-first-move-bytes` (precision). `UnrestoredFirstMoveBytes`: A - texture's first move over a no-copy buffer's host pages changed bytes the host kept across it, on - pages the process maps without write permission when the host writes them back: on Linux, pages - made read-only after the buffer was made (Linux refuses read-only pages at the import); on macOS - also pages read-only from the start, which Metal reads (a GPU write into them fails its command - buffer). Not observed on RADV, which fails the command buffers submitted after a page of an - import loses write permission (`HostMemory::new`). Cost: those bytes keep what the image's move - from `UNDEFINED` wrote, where Metal's texture leaves its pages as they were. - `metal2vulkan-degrade-float-tininess-after-rounding` (precision). `FloatTininessAfterRounding`: A device whose policy takes native device maths (`FloatMathsPolicy::Native`, the default) where its float functions are not Metal's own (not MoltenVK): Metal flushes a `float` product or fused @@ -2602,6 +2561,8 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. keeps them. - `metal2vulkan-degrade-deallocator-after-release` (retired). No replacement: a no-copy buffer's deallocator runs in its release, on the releasing thread, as Metal runs it. +- `metal2vulkan-degrade-unrestored-first-move-bytes` (retired). No replacement: a texture over a + no-copy buffer's host pages is a shadow, which takes no first move over them. ## 10. Accepted differences diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 8d12dc0cc..26181075b 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -129,6 +129,8 @@ recorded here. its own pixels alone, else every texel or what the instances since drew. After a barrier inside the instance, an own-pixel read takes a snapshot drawn in its subpass (`render/snapshot.rs`, docs/API.md "Snapshot reads") or splits the instance; both are exact. Over a texture whose image + lies over its buffer's bytes (a linear image over an ordinary buffer's packed rows) it takes the + snapshot at any area, where the device makes that linear image with feedback loop usage (`WorkCounts::feedback_loop_alias_images`; NVIDIA's drivers make it without, and a surface's readers split there): on the Iris Xe (`runtime_lane::attachment_read_costs::snapshot_crossover`, @@ -159,13 +161,25 @@ recorded here. sign strip (two copies and a dispatch, or a draw per layer when multisampled) follows a pass with depth writes where no stand-in runs (`texture/signed_depth.rs`). A texture never switched on pays a flag read per pass. -- **A texture over a buffer whose rows lie with bytes between them, which renders or which a shader - writes**, is a shadow on every device but MoltenVK (`shadowed-texture`): its texels copied in - before each use and back after each write (only those inside the draws' scissors for a pass that - takes it as a loaded attachment alone): an image over those rows holds the bytes between them in - its subresources, which a render pass's load and store operations and the image's first move may - rewrite. On ANV making a 1307x512 tile took about 135 µs as a shadow against 41 µs as an image. - Packed rows avoid it. +- **A texture over a no-copy buffer's host pages, or over a buffer whose rows lie with bytes + between them,** is a shadow on every device, whatever its usage (`shadowed-texture`): its texels + copied in before each use and merged back after each write (only those inside the draws' + scissors for a pass that takes it as a loaded attachment alone). An image bound to host pages + starts `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), and its first move may read and write + every byte bound to it, which the host could keep only by undoing a CPU write made meanwhile, + where Metal keeps it; an image over padded rows holds the bytes between them, which a render + pass's load and store operations may rewrite too. On the UHD 770 (ANV) a 1080p `BGRA8Unorm` + surface's pass that loads, draws and stores (`guest_frame_costs`) took 1.9 ms from commit to + completion, 1.4 ms of it the copies (copy in 0.21 ms, keep 0.60, merge 0.60), against 0.4 ms + into a `Private` texture; a linear image over the pages took 2.6-3.1 ms, its draws slow in host + memory. Twelve such passes in one command buffer took 21 ms against the linear image's 27.5 ms, + and 0.4-0.5 ms more of the process's CPU a frame (1.2 ms against 0.7): about 20 µs a pass on the + encoding thread, 10 µs on the queue's waiter and 10 µs on the recorder and reaper together. On + ANV making a 1307x512 tile took about 135 µs as a shadow against 41 µs as an image; a frame + sampling four `BGRA8Unorm` tiles over no-copy pages + (`surface_texture_costs::read_only_padded_costs`) took 3.2-5.3 ms with the textures made once + and 3.4-7.1 ms with new ones each frame, where images over the rows took 3.0-6.1 and 4.6-8.6 + ms. An ordinary buffer's packed rows avoid it. - **On MoltenVK, a texture over a buffer that renders or that blits write keeps a shadow.** MoltenVK 1.4.1 reports a format's linear-tiling attachment and blit-destination features from uninitialized memory, so no MoltenVK description states them @@ -380,6 +394,9 @@ driver's. Each is open work. word runs past the buffer, the merge copies the bytes from the texture's first to its last into its scratch, merges there, and copies them back (`shadow_merge.rs`). Another writer's write to them between the two copies is undone. +- **A linear image over a `Shared` or `Managed` buffer's packed rows moves out of + `PREINITIALIZED` at its first use**, a transition Vulkan lets read and write every byte bound to + it: a CPU write to those bytes during it could be undone, where Metal keeps it (not observed). - **A cold pipeline making on NVIDIA grows with a module's sampling sites.** NVIDIA's compiler takes about 1 s for macOS 26's largest CoreAnimation fragment (210,033 words) on the RTX 5080 Laptop GPU, once per cold cache; states that share the module then take 13 to 16 ms, and a warm cache diff --git a/docs/HOWTO.md b/docs/HOWTO.md index e50139f7b..628b9cc65 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -224,6 +224,28 @@ used (no command reaches them unnamed yet), `host_rebind_imports_made` those reb `host_rebind_imports_covered` those whose pages lay within bytes a buffer over host pages lay over already. +A texture over a no-copy buffer's host pages, imported by their pointer or as dma-bufs, is a +shadow (`shadowed-texture`) on every device, whatever its usage and row pitch: an optimal image of +the runtime's own memory, its texels copied in from the pages before a use and merged back after a +write. An image bound to imported memory starts in `VK_IMAGE_LAYOUT_UNDEFINED` +(`VUID-VkImageCreateInfo-pNext-01443`), and its layout transitions "may perform read and write +accesses on all memory bound to the image subresource range"; every image takes one, its first move +from the layout it is made in, before any use, and the host could keep the bytes across it only by +reading them before it and writing them back after, which would undo a CPU write made meanwhile, +where Metal keeps every write to bytes a command buffer does not write. + +A texture over another buffer's bytes (the runtime's own memory) is a linear image over them where +its rows lie one after another (`bytes_per_row` is its texels' bytes, or it has one row; an array's +slices likewise), the device lays a linear image's rows at that pitch, and the image holds no byte +past its texels; it starts `VK_IMAGE_LAYOUT_PREINITIALIZED`, which keeps its bytes. A texture whose +rows lie with bytes between them is a shadow (`shadowed-texture`), whatever its usage: an image at +that pitch holds the bytes between the rows in its subresource (`VkSubresourceLayout`: "size +includes any extra memory that is required based on rowPitch"), which its layout transitions and a +render pass's load and store operations ("read and write back any memory locations within the image +subresource bound for that attachment"; lavapipe writes back the bytes its 4-texel blocks reach +past a row, a signaling NaN's bits quieted) may write, where Metal leaves them as the program writes +them. + ## 7. Check the integration