From 2dd3557a98421ffec4154f9c127f0217e4eef21b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 25 Oct 2026 11:34:56 +0200 Subject: [PATCH] Hold an IOSurface plane whose GPU rows overlap as a shadow Content: the tree of `development` at 16ad1f5af6, unchanged. --- .../metal2vulkan-runtime/src/blit_texture.rs | 24 +- .../src/buffer_texture.rs | 188 +++++++++--- .../metal2vulkan-runtime/src/degradation.rs | 11 + crates/metal2vulkan-runtime/src/exactness.rs | 4 + .../metal2vulkan-runtime/src/linear_plan.rs | 135 +++++++-- crates/metal2vulkan-runtime/src/shadow.rs | 48 ++- .../src/tests/buffer_texture.rs | 44 ++- .../src/tests/degradation_codes.txt | 1 + .../src/tests/exactness.rs | 6 +- .../src/tests/linear_plan.rs | 277 +++++++++++++++--- .../metal2vulkan-runtime/src/tests/shadow.rs | 61 ++++ .../metal2vulkan-runtime/src/texture/heap.rs | 3 + .../runtime-sources.sha256 | 2 +- .../src/runtime_lane/buffer_texture_blits.rs | 14 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 9 + docs/FAST-PATHS.md | 29 +- 18 files changed, 721 insertions(+), 138 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/blit_texture.rs b/crates/metal2vulkan-runtime/src/blit_texture.rs index f5aac817f..d72e2bbe6 100644 --- a/crates/metal2vulkan-runtime/src/blit_texture.rs +++ b/crates/metal2vulkan-runtime/src/blit_texture.rs @@ -561,6 +561,14 @@ impl BlitCommandEncoder { destination_slice, )?; if let Some(texels) = texture.buffer_texels() { + // Rows that share bytes (an IOSurface plane's on Metal's GPU): the row + // copies leave the later row's bytes where two meet, as a rotated texture's + // plain Metal blit writes them (`blit_plan::RowsCopy`), and Metal's blit + // through such a plane leaves the earlier row's + // (`linear_plan.rs`'s **Rows that overlap**). + if texels.plane_rows_overlap() { + return Err(Error::NotImplemented(RuntimeGap::OverlappingSurfaceRows)); + } let (from, to) = plan_rows_copy( texture.record(), ®ion, @@ -709,6 +717,14 @@ impl BlitCommandEncoder { let unit = unit(CALL, source_texture, options)?; let region = region(CALL, source_origin, size, source_level, source_slice)?; if let Some(texels) = source_texture.buffer_texels() { + // Rows that share bytes (an IOSurface plane's on Metal's GPU): the row + // copies leave the later row's bytes where two meet, as a rotated texture's + // plain Metal blit writes them (`blit_plan::RowsCopy`), and Metal's blit + // through such a plane leaves the earlier row's + // (`linear_plan.rs`'s **Rows that overlap**). + if texels.plane_rows_overlap() { + return Err(Error::NotImplemented(RuntimeGap::OverlappingSurfaceRows)); + } let (to, from) = plan_rows_copy( source_texture.record(), ®ion, @@ -1677,8 +1693,12 @@ impl BlitCommandEncoder { self.rows_copy(&from.buffer, &to.buffer, &RowsCopy::new(&src, &dst)) } (Some(texels), None) | (None, Some(texels)) => { - // Rows that overlap (a rotated texture's) are no layout a buffer-image copy - // states. + // Rows that overlap are no layout a buffer-image copy states: an IOSurface + // plane's on Metal's GPU, which only its shadow's two regions each way hold + // (`linear_plan.rs`'s **Rows that overlap**), or a rotated texture's. + if texels.plane_rows_overlap() { + return Err(Error::NotImplemented(RuntimeGap::OverlappingSurfaceRows)); + } if texels.rows_overlap() { return Err(Error::NotImplemented(RuntimeGap::RotatedTexture)); } diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index 532f83b4b..013e32c5e 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -357,7 +357,14 @@ impl Buffer { /// - under 16 bytes a row, the GPU's rows are 16 bytes apart. There Metal's GPU reads every /// row past the first as memory-dependent bytes; the runtime's reads them where its writes /// put them, a near-equivalent announced once - /// ([`Degradation::NarrowSurfaceRows`](super::Degradation::NarrowSurfaceRows)). + /// ([`Degradation::NarrowSurfaceRows`](super::Degradation::NarrowSurfaceRows)); + /// - where that pitch is below the row, the GPU's rows share bytes: 1 to 15 of them, a whole + /// number of texels, between consecutive rows. A plain plane is made, its shadow's copies + /// reproducing the sharing with two regions a slice each way, so that a read sees it as + /// Metal's does and the shared bytes keep the earlier row's where two of its rows write + /// them, as Metal's blit leaves them; announced once, as a kernel of Metal's leaves the + /// later row's there on an M4 and others on an M3 Max, announced by + /// [`Degradation::CollidingSurfaceRowWrites`](super::Degradation::CollidingSurfaceRowWrites). /// /// Refused: a surface made with `kIOSurfaceClientDirection`, SPI /// ([`AppleOnly::SurfaceClientDirection`](super::AppleOnly::SurfaceClientDirection)); what @@ -367,10 +374,11 @@ impl Buffer { /// whose rows end past it, which plain Metal asserts on); `Memoryless` storage, which plain /// Metal makes and serves on the CPU while its GPU uses fail the command buffer /// (`NotImplemented(MemorylessSurfacePlane)`, which carries the measurement); rows that - /// overlap on Metal's GPU, of more than 16 bytes at a `bytes_per_row` whose multiple of 16 - /// below it is shorter than the row, where Metal's writes depend on their order - /// (`NotImplemented(OverlappingSurfaceRows)`); a plane's own rows or its GPU texels past the - /// buffer, which Metal's surface holds in its pages + /// overlap on Metal's GPU where no shadow of the runtime's holds them + /// (`NotImplemented(OverlappingSurfaceRows)`: a plane a render pass stores into, a two-plane + /// YCbCr, two-plane extended-range, 4:2:2, depth or stencil one, and a blit that addresses + /// such a plane's rows as bytes; `linear_plan.rs`); a plane's own rows or its GPU texels past + /// the buffer, which Metal's surface holds in its pages /// (`NotImplemented(TexelsPastBufferLength)`); and as [`new_texture`](Self::new_texture) /// refuses a format or an image. /// @@ -623,6 +631,7 @@ impl Buffer { offset, bytes_per_row, call: form, + usage: descriptor.usage, }; // A rotated texture: its plane holds it turned, as Metal checks it, its CPU access and // blits address the plane as the texture's own extent at the plane's rows, and its @@ -708,6 +717,9 @@ impl Buffer { if placed.narrow { self.degrade_narrow_rows(&layout, &placed); } + if placed.gpu.shared_bytes() != 0 { + self.degrade_colliding_rows(&layout, &placed); + } Ok(texture) } } @@ -722,6 +734,10 @@ impl Buffer { /// or a format of a texel size other than 1, 2, 4, 8 or 16 bytes (a 4:2:2 one among them), whose /// rotation is not measured. /// +/// A rotated plane's `bytesPerRow` must be a multiple of 16 here, so its GPU rows lie at the +/// pitch itself and never share bytes, which no shadow of a turned frame holds +/// (`linear_plan.rs`'s **Rows that overlap**). +/// /// It reads nothing of the buffer but its length, so a test reaches every refusal from the /// input's own shape with no device — which the pitch rule needs, the texture it refuses being /// one that ends Metal's process. @@ -811,6 +827,30 @@ impl Buffer { (object, reason) }); } + + /// Announce `CollidingSurfaceRowWrites` for an IOSurface plane of `layout` placed as `placed`, + /// whose GPU rows share bytes, once it is made (`linear_plan.rs`'s **Rows that overlap**). + fn degrade_colliding_rows(&self, layout: &TextureLayout, placed: &Placed) { + self.device() + .degrade(Degradation::CollidingSurfaceRowWrites, || { + let [width, height, _] = layout.extent; + let object = format!( + "{width}x{height} {:?} texture of an IOSurface plane at offset {}, {} bytes a \ + row", + layout.pixel_format, placed.cpu.offset, placed.cpu.row_pitch + ); + let reason = format!( + "Metal's GPU reads and writes its rows {} bytes apart from byte {}, {} bytes \ + of texels each, so consecutive rows share {} bytes, and which row's writes \ + stand there depends on the order Metal writes them in", + placed.gpu.row_pitch, + placed.gpu.offset, + placed.gpu.row_bytes, + placed.gpu.shared_bytes(), + ); + (object, reason) + }); + } } impl Texture { @@ -1140,12 +1180,23 @@ impl Texels { self.span().end <= self.buffer.length() } - /// Whether the texels' rows overlap: a rotated texture's whose rows are longer than its - /// plane's (`rotated_rows`). + /// Whether the texels' rows overlap: an IOSurface plane's on Metal's GPU + /// ([`plane_rows_overlap`](Self::plane_rows_overlap)), or a rotated texture's whose rows are + /// longer than its plane's (`rotated_rows`). pub(super) fn rows_overlap(&self) -> bool { self.layout.rows > 1 && self.layout.row_pitch < self.layout.row_bytes } + /// Whether the texels' rows overlap because Metal's GPU reads and writes an IOSurface plane + /// at its pitch rounded down to 16 (`linear_plan::iosurface_gpu_layout`), the plane's own + /// rows lying a row apart, rather than because a quarter turn's rows are longer than the + /// plane's (`rotated_rows`, whose CPU rows overlap as its GPU rows do). The shadow's copies + /// hold the sharing ([`plane_copy_regions`]); a blit that addresses the rows as bytes does + /// not (`blit_texture.rs`). + pub(super) fn plane_rows_overlap(&self) -> bool { + self.rows_overlap() && self.cpu.row_pitch >= self.cpu.row_bytes + } + /// The texels of a texture of `descriptor` at `placed` in `buffer`, `texel_bytes` each. fn new( buffer: Buffer, @@ -1324,30 +1375,11 @@ impl Texels { let start = staging .as_ref() .map_or(at, |staging| staging.into.dst_offset); - let width = layout.row_bytes / self.texel_bytes; // The descriptor's checks bound a texture's extent and slices to `u32`s. let slices = layout.slices as u32; - let regions = (0..slices) - .map(|slice| vk::BufferImageCopy { - // Metal's slices are multiples of 128 bytes apart. - buffer_offset: start + layout.slice_pitch * u64::from(slice), - // Metal's rows are multiples of 16 bytes, so of every texel size. - buffer_row_length: (layout.row_pitch / self.texel_bytes) as u32, - buffer_image_height: 0, - image_subresource: vk::ImageSubresourceLayers { - aspect_mask: aspects, - mip_level: 0, - base_array_layer: slice, - layer_count: 1, - }, - image_offset: vk::Offset3D::default(), - image_extent: vk::Extent3D { - width: width as u32, - height: layout.rows as u32, - depth: 1, - }, - }) - .collect(); + let (regions, back) = plane_copy_regions(layout, self.texel_bytes, start, aspects); + // A copy back dispatches, and a merge fetches, over one region copied in place alone. + let one_region = regions.len() == 1 && slices == 1 && staging.is_none(); let (bytes, tracked) = self.buffer.tracked(layout.offset..layout.end()); Ok(ShadowCopies { source: ShadowSource::Bytes { @@ -1355,12 +1387,11 @@ impl Texels { key: bytes.key, bytes: tracked, target: ShadowTarget::Image { - // A copy back dispatches, and a merge fetches, over one region copied in - // place alone. - words: words.filter(|_| slices == 1 && staging.is_none()), - unorm: unorm.filter(|_| slices == 1 && staging.is_none()), + words: words.filter(|_| one_region), + unorm: unorm.filter(|_| one_region), image, regions, + back, staging, texel: Some(self.texel_bytes), }, @@ -1645,16 +1676,25 @@ pub(super) fn view_usage( /// 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. +/// one a row, but one for rows that lie one after another or share bytes. +/// +/// A row that shares bytes with the one above (an IOSurface plane's on Metal's GPU, +/// `linear_plan::iosurface_gpu_layout`) extends that row's region rather than opening one of its +/// own: a region of each would write the shared bytes twice in one `vkCmdCopyBuffer`, which no +/// two destination regions of one may do (`VUID-vkCmdCopyBuffer-pRegions-12482`; older releases +/// read it off `-00117`'s union of the destination regions). The staging buffer holds the plane's +/// bytes as they lie, the shadow's copy back having written each of them once +/// ([`plane_copy_regions`]), so one region of the rows' whole span moves them as they are. 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 { + let end = start + row + layout.row_bytes; match back.last_mut() { - Some(last) if last.src_offset + last.size == start + row => { - last.size += layout.row_bytes; + Some(last) if last.src_offset + last.size >= start + row => { + last.size = end - last.src_offset; } _ => back.push(vk::BufferCopy { src_offset: start + row, @@ -1665,3 +1705,79 @@ pub(super) fn staged_rows_back(layout: &BufferLayout, start: u64, at: u64) -> Ve } back } + +/// The regions that copy the texels laid out as `layout`, `texel_bytes` each, starting at `start` +/// of the `VkBuffer` the copies address, into a 2D texture's shadow image of `aspects`, and the +/// regions that copy them back out of it (`shadow.rs`, [`Texels::shadow_copies`]): one region a +/// slice each way, the slice's rows of texels, where each row lies a row apart from the one above +/// or further. Metal's slices lie multiples of 128 bytes apart and its rows multiples of 16, so +/// of every texel size. +/// +/// Where consecutive rows share bytes (an IOSurface plane's on Metal's GPU, +/// `linear_plan::iosurface_gpu_layout`: 1 to 15 bytes, a whole number of texels, between +/// consecutive rows alone), no one region states a slice: a region addresses its rows one +/// `bufferRowLength` apart, which is at least its width +/// (`VUID-vkCmdCopyBufferToImage-bufferRowLength-00195`), and the shared bytes hold a texel of +/// each of two rows. Each slice takes two regions instead, split at the texels the sharing +/// covers: +/// +/// - going in, every row's shared head and the rest of every row. Their sources share the bytes, +/// which a copy into an image allows: a memory location may not be read by a source region and +/// written by a destination region of one copy +/// (`VUID-vkCmdCopyBufferToImage-pRegions-00173`), nor written by two destination regions +/// (`-12483`), and the two regions' image texels are disjoint and together every texel; +/// - going back, the rest of every row, and the head of row 0 alone. Those tile the slice's bytes +/// exactly once, so no byte is written by two destination regions +/// (`VUID-vkCmdCopyImageToBuffer-pRegions-12485`), and every shared byte takes the earlier +/// row's tail, the order Metal's blit writes two rows in (`linear_plan.rs`'s **Rows that +/// overlap**). A kernel's two writes there leave the earlier row's too, where Metal's leave the +/// later row's on an M4 and others on an M3 Max +/// ([`Degradation::CollidingSurfaceRowWrites`](super::Degradation::CollidingSurfaceRowWrites)). +pub(super) fn plane_copy_regions( + layout: &BufferLayout, + texel_bytes: u64, + start: u64, + aspects: vk::ImageAspectFlags, +) -> (Vec, Vec) { + let shared = layout.shared_bytes(); + let width = (layout.row_bytes / texel_bytes) as u32; + let pitch = (layout.row_pitch / texel_bytes) as u32; + // The descriptor's checks bound a texture's extent and slices to `u32`s. + let (slices, rows) = (layout.slices as u32, layout.rows as u32); + let region = |slice: u32, at: u64, x: u32, texels: u32, height: u32| vk::BufferImageCopy { + buffer_offset: at + layout.slice_pitch * u64::from(slice), + buffer_row_length: pitch, + buffer_image_height: 0, + image_subresource: vk::ImageSubresourceLayers { + aspect_mask: aspects, + mip_level: 0, + base_array_layer: slice, + layer_count: 1, + }, + image_offset: vk::Offset3D { + x: x as i32, + y: 0, + z: 0, + }, + image_extent: vk::Extent3D { + width: texels, + height, + depth: 1, + }, + }; + if shared == 0 { + let regions: Vec = (0..slices) + .map(|slice| region(slice, start, 0, width, rows)) + .collect(); + return (regions.clone(), regions); + } + let head = (shared / texel_bytes) as u32; + let (mut into, mut back) = (Vec::new(), Vec::new()); + for slice in 0..slices { + into.push(region(slice, start, 0, head, rows)); + into.push(region(slice, start + shared, head, width - head, rows)); + back.push(region(slice, start, 0, head, 1)); + back.push(region(slice, start + shared, head, width - head, rows)); + } + (into, back) +} diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 90fafae80..155885cc0 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1076,6 +1076,17 @@ degradations! { "a GPU read of a row past the first reads the bytes the GPU's writes put there, 16 \ bytes a row apart, where Metal's GPU reads memory-dependent bytes; CPU access and \ the GPU's writes and first row are Metal's"; + /// A texture of an IOSurface plane whose rows share bytes on Metal's GPU + /// (`Buffer::new_texture_with_iosurface_plane`, `linear_plan.rs`): more than one row of + /// over 16 bytes whose `bytesPerRow` rounded down to 16 is below the row, so consecutive + /// rows share 1 to 15 bytes, a whole number of texels. Metal's reads see the sharing and + /// so do the runtime's, through a shadow whose two copy regions each way hold it; but + /// where two rows' writes meet Metal's answer is not one value: its blit leaves the + /// earlier row's bytes, and its kernel the later row's on an M4 and others on an M3 Max. + CollidingSurfaceRowWrites = "colliding-surface-row-writes", Precision, + "where two of the plane's rows write the bytes they share the earlier row's stand, \ + as Metal's blit leaves them, where a kernel of Metal's leaves the later row's on an \ + M4 and others on an M3 Max; reads, CPU access and every other byte are Metal's"; /// A pipeline state's function may read an argument its function constants removed (a /// texture's read, sample, gather, query or atomic, or a sample through a removed /// sampler; `RuntimeFact::AbsentArgumentRead`), which Metal gives no value: its compiler diff --git a/crates/metal2vulkan-runtime/src/exactness.rs b/crates/metal2vulkan-runtime/src/exactness.rs index 5445ae07f..0a8ed63fa 100644 --- a/crates/metal2vulkan-runtime/src/exactness.rs +++ b/crates/metal2vulkan-runtime/src/exactness.rs @@ -68,6 +68,10 @@ impl Degradation { D::ZeroedIndexFetch | D::DontCareStore | D::NarrowSurfaceRows + // Two rows of an IOSurface plane writing the bytes they share: Metal's blit + // leaves the earlier row's and its kernel the later row's on an M4, others on an + // M3 Max; the runtime leaves the earlier row's. + | D::CollidingSurfaceRowWrites | D::RepeatedExecutionStart | D::OverlappingTextureCopyAsMemmove | D::PlainStateUniqueIdentifier diff --git a/crates/metal2vulkan-runtime/src/linear_plan.rs b/crates/metal2vulkan-runtime/src/linear_plan.rs index af4bc4061..0feef1f79 100644 --- a/crates/metal2vulkan-runtime/src/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/linear_plan.rs @@ -96,12 +96,29 @@ //! - **Rows that overlap.** A row of more than 16 bytes whose `bytesPerRow` rounded down to 16 is //! below it overlaps the next row on the GPU: a read sees the overlap, and where two rows' //! writes meet, one of them wins, by the order of the writes: the earlier row's in a blit, and -//! in a kernel the later row's on the M4 and others on the M3 Max. The runtime refuses such a -//! plane of more than one row (`NotImplemented`, `RuntimeGap::OverlappingSurfaceRows`; -//! [`BufferRefusal::OverlappingRows`]). A plane's pitch covers its own row, so the overlap is -//! 1 to 15 bytes, a whole number of texels, and between consecutive rows alone -//! (`tests::linear_plan`); a two-plane YCbCr texture's rows of codes, which no row rule holds, -//! overlap by any amount and across any number of rows (`ycbcr.rs`). +//! in a kernel the later row's on the M4 and others on the M3 Max. A plane's pitch covers its +//! own row, so the overlap is 1 to 15 bytes, a whole number of texels, and between consecutive +//! rows alone (`tests::linear_plan`). No image holds rows that overlap, so such a plane is a +//! shadow whose copies reproduce the sharing: two regions a slice each way, one of every row's +//! shared head and one of the rest of each row going in, and going back the second of them for +//! every row beside the head of row 0 alone, which tile the plane's bytes exactly once and +//! leave the earlier row's bytes where two rows meet, the order Metal's blit writes them in +//! (`buffer_texture.rs`, [`plane_copy_regions`](super::buffer_texture::plane_copy_regions)). A +//! kernel's two writes there leave the earlier row's bytes too, where Metal's leave the later +//! row's on the M4 and others on the M3 Max: one of Metal's own answers, announced +//! (`Degradation::CollidingSurfaceRowWrites`). +//! +//! Still refused ([`BufferRefusal::OverlappingRows`], `NotImplemented`, +//! `RuntimeGap::OverlappingSurfaceRows`): a plane a render pass stores into, where what Metal +//! leaves of the shared bytes is not measured; the shapes whose rows of codes or units no row +//! rule bounds (a two-plane YCbCr texture's, which overlap by any amount across any number of +//! rows, `ycbcr.rs`; a two-plane extended-range one's, a 4:2:2 one's pairs, a depth or stencil +//! plane's elements), which two regions do not express; and a blit that addresses such a +//! plane's rows as bytes (`blit_texture.rs`), whose order Metal leaves the shared bytes in +//! differs from a rotated texture's, the only overlap its row copies hold +//! ([`super::blit_plan::RowsCopy`]). A rotated plane never reaches this at all: its +//! `bytesPerRow` must be a multiple of 16 (`buffer_texture::turned_plane`), so its GPU rows lie +//! at the pitch itself. //! - **Two-plane YCbCr codes** (an M3 Max under macOS 27.0.1; `ycbcr.rs`'s **Surfaces**). Metal //! makes a two-plane YCbCr texture over any plane, its codes at the plane's rows however wide //! they are: a 10-bit format over an 8-bit plane, whose rows of codes overlap where @@ -148,6 +165,7 @@ use super::copy_plan::block_extent; use super::image_plan::{compatible, view_formats, ImageFacts, ImagePlan}; use super::metal_level::MetalLevel; use super::texture_descriptor::TextureLayout; +use super::two_planes; use super::values::StorageMode; use metal2vulkan::error::LinearNeed; use metal2vulkan::metal::format::{is_depth_stencil, ycbcr}; @@ -329,6 +347,10 @@ pub(super) struct BufferTexture { pub(super) offset: u64, pub(super) bytes_per_row: u64, pub(super) call: BufferTextureCall, + /// The descriptor's usage, which only an IOSurface plane whose GPU rows overlap is held to: + /// what Metal's render pass leaves of the bytes two rows share is not measured + /// ([`overlap_held`]). + pub(super) usage: TextureUsage, } /// The buffer a texture is made over: its length. @@ -352,6 +374,17 @@ pub(super) struct BufferLayout { } impl BufferLayout { + /// The bytes consecutive rows share, where the rows overlap: a row's bytes past the pitch, 0 + /// where each row lies at or past the end of the one above. Only an IOSurface plane's GPU + /// layout overlaps ([`iosurface_gpu_layout`]), and then by 1 to 15 bytes, a whole number of + /// texels, between consecutive rows alone (`tests::linear_plan`). + pub(super) fn shared_bytes(&self) -> u64 { + match self.rows > 1 { + true => self.row_bytes.saturating_sub(self.row_pitch), + false => 0, + } + } + /// One past the texture's last texel byte in the buffer. pub(super) fn end(&self) -> u64 { self.offset @@ -388,27 +421,51 @@ impl Placed { /// Where Metal's GPU reads and writes the texels of an IOSurface plane laid out as `cpu` for the /// CPU (the module's rules): from its offset rounded down to 16, rows its pitch rounded down to 16 -/// apart, or 16 apart where that is 0 (a plane under 16 bytes a row, [`Placed::narrow`]). A plane -/// of one row lies there whatever its pitch; refused ([`BufferRefusal::OverlappingRows`]) where -/// later rows would overlap earlier ones, which no image holds. -pub(super) fn iosurface_gpu_layout(cpu: &BufferLayout) -> Result { +/// apart, or 16 apart where that is 0 (a plane under 16 bytes a row, [`Placed::narrow`]). +/// +/// Rows that overlap lie at that pitch itself, which the texture's shadow holds in two copy +/// regions each way (the module's **Rows that overlap**); every other plane's lie at least a row +/// apart, so that one region a slice states them and its `bufferRowLength` covers its width. A +/// plane of one row lies a row apart whatever its pitch: it overlaps nothing, and one region +/// states it. +pub(super) fn iosurface_gpu_layout(cpu: &BufferLayout) -> BufferLayout { let down = |n: u64| n - n % LINEAR_ALIGNMENT; let pitch = down(cpu.row_pitch); - if cpu.rows > 1 && pitch != 0 && pitch < cpu.row_bytes { - return Err(BufferRefusal::OverlappingRows); - } // Every texel size divides a multiple of 16, as the shadow's copies need. - let row_pitch = pitch.max( - cpu.row_bytes - .checked_next_multiple_of(LINEAR_ALIGNMENT) - .unwrap_or(u64::MAX), - ); - Ok(BufferLayout { + let row_pitch = match cpu.rows > 1 && pitch != 0 && pitch < cpu.row_bytes { + true => pitch, + false => pitch.max( + cpu.row_bytes + .checked_next_multiple_of(LINEAR_ALIGNMENT) + .unwrap_or(u64::MAX), + ), + }; + BufferLayout { offset: down(cpu.offset), row_pitch, slice_pitch: row_pitch.saturating_mul(cpu.rows), ..*cpu - }) + } +} + +/// Whether the runtime holds an IOSurface plane of `texture` where its GPU rows overlap, its +/// shadow's two copy regions each way reproducing the sharing (the module's **Rows that +/// overlap**), or refuses it ([`BufferRefusal::OverlappingRows`]). +/// +/// A plain plane is held. Refused are a plane a render pass stores into, where what Metal leaves +/// of the bytes two rows share is not measured, and the shapes whose rows of codes or units no +/// row rule bounds, which two regions do not express: a two-plane YCbCr texture's (`ycbcr.rs`), a +/// two-plane extended-range one's (`texture/surface_two_planes.rs`), a 4:2:2 one's pairs +/// (`chroma_pairs.rs`) and a depth or stencil plane's elements (`texture/surface_depth.rs`). A +/// rotated plane's `bytesPerRow` is already a multiple of 16, so its GPU rows never overlap +/// (`buffer_texture::turned_plane`). +fn overlap_held(texture: &BufferTexture) -> bool { + let pf = texture.layout.pixel_format; + !texture.usage.contains(TextureUsage::RENDER_TARGET) + && !ycbcr(pf) + && !two_planes::holds_planes(pf) + && !is_four_two_two(pf) + && !is_depth_stencil(pf) } /// Why a texture over a buffer is not made. @@ -420,10 +477,13 @@ pub(super) enum BufferRefusal { /// An array whose texels run past the buffer's length, which Metal makes over bytes past /// the length and the runtime has no bytes for (`NotImplemented`). TexelsPastLength, - /// An IOSurface plane whose rows overlap on Metal's GPU, where a write's bytes depend on the - /// order it writes rows in (`NotImplemented`; the module's rules). A plane whose pitch covers - /// its row overlaps by 1 to 15 bytes between consecutive rows; a two-plane YCbCr texture's - /// rows of codes, which no row rule holds, by any amount (`ycbcr.rs`). + /// An IOSurface plane whose rows overlap on Metal's GPU that the runtime holds no form of + /// (`NotImplemented`; the module's **Rows that overlap**): a plane a render pass stores into, + /// or one of a format whose rows of codes or units no row rule bounds (a two-plane YCbCr + /// texture's, which overlap by any amount across any number of rows, `ycbcr.rs`; a two-plane + /// extended-range one's, a 4:2:2 one's pairs, a depth or stencil plane's elements). A plain + /// plane, whose pitch covers its row and whose rows share 1 to 15 bytes, is a shadow of two + /// copy regions each way instead. OverlappingRows, /// An IOSurface plane whose descriptor asks for `Memoryless` storage, which plain Metal makes /// and serves on the CPU while every GPU use fails the command buffer (`NotImplemented`; the @@ -500,7 +560,7 @@ pub(super) fn plan_buffer_texture( rows: height, slices: 1, }; - return plan_iosurface_plane(cpu, planar, buffer.length); + return plan_iosurface_plane(cpu, planar, buffer.length, overlap_held(texture)); } let array = texture_type == T::Type2DArray; let alignment = if array { @@ -557,11 +617,13 @@ pub(super) fn plan_buffer_texture( /// An IOSurface plane laid out as `cpu` in a buffer of `length` bytes, of a planar surface or /// not (`planar`), by the module's rules; its type, levels, options and row were checked as -/// every texture over a buffer's are. +/// every texture over a buffer's are. `held` says whether the runtime holds the plane where its +/// GPU rows overlap ([`overlap_held`]), or refuses it there. fn plan_iosurface_plane( cpu: BufferLayout, planar: bool, length: u64, + held: bool, ) -> Result { use BufferTextureProblem as P; let alignment = LINEAR_ALIGNMENT; @@ -592,7 +654,10 @@ fn plan_iosurface_plane( .into(), }); } - let gpu = iosurface_gpu_layout(&cpu)?; + let gpu = iosurface_gpu_layout(&cpu); + if gpu.shared_bytes() != 0 && !held { + return Err(BufferRefusal::OverlappingRows); + } if gpu.end() > length { return Err(BufferRefusal::TexelsPastLength); } @@ -784,9 +849,10 @@ pub(super) fn aliases( } /// 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), whatever its usage. +/// its rows (and slices) lie one after another, or it has one row (one slice); else why not, +/// where consecutive rows share bytes (an IOSurface plane's on Metal's GPU, which no image holds +/// a texel of twice), or where they lie with bytes between them that are not texels (the +/// buffer's, which Metal's writes of the 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"), @@ -815,6 +881,15 @@ pub(super) fn aliases( /// 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> { + // An IOSurface plane's rows that overlap: no image holds them, whatever its usage. + let shared = layout.shared_bytes(); + if shared != 0 { + return Err(format!( + "its rows lie {} bytes apart, {} bytes of texels each, so consecutive rows share \ + {shared} bytes: no image holds a texel twice", + layout.row_pitch, layout.row_bytes + )); + } let (rows, slices) = apart(layout); let apart = if rows { format!( diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index 81e2419f2..8c4a1ee09 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -72,6 +72,13 @@ //! every copy through it writes the image or the texture's bytes, so the tracker orders it after //! every other copy of the texture. A texture buffer's staging buffer is its shadow, with uses of //! its own, as an image's. +//! - **Rows that share bytes** (`linear_plan.rs`'s **Rows that overlap**). An IOSurface plane +//! whose GPU rows share 1 to 15 bytes is an image of its texels whose copies are two regions a +//! slice each way ([`plane_copy_regions`](super::buffer_texture::plane_copy_regions)): going +//! in each shared byte is read for both the rows that hold it, and going back it is +//! written once, from the earlier row, as Metal's blit leaves it. The rules above are the same; +//! no copy of such a shadow is cut to a rectangle, and none dispatches, both of which take one +//! region. //! - **Render passes** (`render/shadows.rs`). A render pass instance is one command: its draws //! record apart, where no copy goes, so the copies go before the instance and the uses are its //! draws' and its attachments'. @@ -362,10 +369,17 @@ impl ShadowBuffer { /// A shadowed texture's shadow (see the module). pub(super) enum ShadowTarget { /// A 2D texture's image: `regions`, one per slice, copy its texels from the buffer, or from - /// `staging` where Vulkan cannot copy them in place. + /// `staging` where Vulkan cannot copy them in place, and `back` copies them out of the image + /// again. Image { image: vk::Image, regions: Vec, + /// The regions a copy back, and a merge's keep, take out of the image + /// ([`ShadowCopies::record_out`]): `regions` for every shadow but one over an IOSurface + /// plane whose rows share bytes, where going in reads each shared byte for both its rows + /// and going back writes it once, from the earlier row + /// (`buffer_texture::plane_copy_regions`). + back: Vec, staging: Option, /// The bytes of one of its texels in the buffer, by which a copy back of a part of the /// texture ([`ShadowCopy::area`]) offsets its region; `None` where no copy of it is @@ -409,6 +423,24 @@ pub(super) enum ShadowTarget { }, } +impl ShadowTarget { + /// The regions a copy of a 2D texture's image over a buffer's bytes takes, going into the + /// image (`into_shadow`) or back out of it: `regions` in and `back` out, which differ only + /// for an IOSurface plane whose rows share bytes + /// ([`plane_copy_regions`](super::buffer_texture::plane_copy_regions): going in reads each + /// shared byte for both its rows, and going back writes it once, from the earlier row). + /// `None` for every other shadow. + pub(super) fn image_regions(&self, into_shadow: bool) -> Option<&[vk::BufferImageCopy]> { + let ShadowTarget::Image { regions, back, .. } = self else { + return None; + }; + Some(match into_shadow { + true => regions, + false => back, + }) + } +} + /// A shadowed texture's staging buffer (see the module): its bytes, from the first texel to the /// last, laid out as in the texture's buffer from the staging buffer's start. /// A runtime buffer the copies between a view's shadow and its image go through @@ -812,9 +844,10 @@ impl ShadowCopies { tiles.record_out(device, command_buffer, (*image, moves), staging, (to, at)); } } - ShadowTarget::Image { image, regions, .. } => { - let origin = regions.first().map_or(0, |region| region.buffer_offset); - let moved: Vec = regions + ShadowTarget::Image { image, .. } => { + let back = target.image_regions(false).unwrap_or_default(); + let origin = back.first().map_or(0, |region| region.buffer_offset); + let moved: Vec = back .iter() .map(|region| vk::BufferImageCopy { buffer_offset: region.buffer_offset - origin + at, @@ -1442,12 +1475,13 @@ impl ShadowCopy { let (image, regions, staging) = match target { ShadowTarget::Image { image, - regions, staging, texel, .. } => { - let regions = match (self.area, staging, regions.as_slice(), *texel) { + // Going back takes the regions that write each byte once (the variant's `back`). + let regions = target.image_regions(into_shadow).unwrap_or_default(); + let regions = match (self.area, staging, regions, *texel) { (Some(area), None, [region], Some(texel)) => { match part_of(region, area, texel) { Some(part) => std::borrow::Cow::Owned(vec![part]), @@ -1455,7 +1489,7 @@ impl ShadowCopy { None => return, } } - _ => std::borrow::Cow::Borrowed(regions.as_slice()), + _ => std::borrow::Cow::Borrowed(regions), }; (*image, regions, staging.as_ref()) } diff --git a/crates/metal2vulkan-runtime/src/tests/buffer_texture.rs b/crates/metal2vulkan-runtime/src/tests/buffer_texture.rs index ec275523e..67c13bffd 100644 --- a/crates/metal2vulkan-runtime/src/tests/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/tests/buffer_texture.rs @@ -12,7 +12,7 @@ use super::super::texture_descriptor::TextureLayout; use super::super::values::StorageMode; use ash::vk; use metal2vulkan::device::FormatUsage; -use metal2vulkan::metal::{PixelFormat, TextureType}; +use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; /// Whether `result` is the typed gap of a view the runtime does not make. fn not_made(result: Result) -> bool { @@ -54,7 +54,9 @@ fn a_view_names_the_one_kind_its_format_serves_where_maintenance5_allows() { /// 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. +/// another too. Rows that share bytes (an IOSurface plane's on Metal's GPU) join as well: a +/// region of each would write the shared bytes twice in one `vkCmdCopyBuffer` +/// (`VUID-vkCmdCopyBuffer-pRegions-12482`). #[test] fn packed_rows_go_back_as_one_region() { let layout = |row_pitch: u64, rows: u64, slices: u64| BufferLayout { @@ -83,6 +85,43 @@ fn packed_rows_go_back_as_one_region() { (2 * 7744, 2 * 7744 + 5, 7680) ] ); + // Rows 7664 apart, 7680 bytes of texels each: consecutive rows share 16 bytes, and the three + // go back as one region of their whole span. + assert_eq!(regions(layout(7664, 3, 1), 0, 5), [(0, 5, 2 * 7664 + 7680)]); +} + +/// No rotated texture over an IOSurface plane has GPU rows that share bytes, which no shadow of +/// a turned frame holds (`linear_plan.rs`'s **Rows that overlap**): `turned_plane` takes only a +/// `bytesPerRow` that is a multiple of 16, so the plane's GPU pitch is its own pitch and covers +/// its row. The shapes below are exactly the ones a plain plane holds as a shadow of two copy +/// regions each way, and every rotation refuses them for their pitch alone. +#[test] +fn no_rotated_plane_s_gpu_rows_share_bytes() { + let refusal = |rotation: u8, width: u32, height: u32, bytes_per_row: u64| { + let texture = over_a_plane(width, height, bytes_per_row); + let length = bytes_per_row * u64::from(width.max(height)) + 1024; + match turned_plane("t", &texture, rotation, &BufferFacts { length }) { + // A plane whose pitch is a multiple of 16 lies at it, a row apart or further. + Ok((_, placed)) => { + assert_eq!(placed.gpu.shared_bytes(), 0, "rotation {rotation}"); + None + } + Err(error) => Some(format!("{error:?}")), + } + }; + let pitch = Some(format!( + "{:?}", + Error::NotImplemented(RuntimeGap::RotatedTexture) + )); + for rotation in 1..=4u8 { + // 20 bytes of texels a row at 20 and at 28: a plain plane's rows would lie 16 apart and + // share 4 bytes. Here the pitch itself is refused. + assert_eq!(refusal(rotation, 5, 4, 20), pitch, "rotation {rotation}"); + assert_eq!(refusal(rotation, 5, 4, 28), pitch, "rotation {rotation}"); + assert_eq!(refusal(rotation, 4, 5, 20), pitch, "rotation {rotation}"); + // A pitch that is a multiple of 16 and covers both rows is taken, its rows a row apart. + assert_eq!(refusal(rotation, 5, 4, 32), None, "rotation {rotation}"); + } } /// A `width x height` texture of 4-byte texels over an IOSurface plane whose rows are @@ -102,6 +141,7 @@ fn over_a_plane(width: u32, height: u32, bytes_per_row: u64) -> BufferTexture { offset: 0, bytes_per_row, call: BufferTextureCall::IoSurfacePlane { planar: false }, + usage: TextureUsage::SHADER_READ, } } diff --git a/crates/metal2vulkan-runtime/src/tests/degradation_codes.txt b/crates/metal2vulkan-runtime/src/tests/degradation_codes.txt index d7264fe41..7d2082f03 100644 --- a/crates/metal2vulkan-runtime/src/tests/degradation_codes.txt +++ b/crates/metal2vulkan-runtime/src/tests/degradation_codes.txt @@ -12,6 +12,7 @@ metal2vulkan-degrade-capped-anisotropy metal2vulkan-degrade-carried-decoded-twin metal2vulkan-degrade-clipped-coverage-split metal2vulkan-degrade-clipped-depth-pieces +metal2vulkan-degrade-colliding-surface-row-writes metal2vulkan-degrade-color-attachment-groups metal2vulkan-degrade-combined-archive-stages metal2vulkan-degrade-compressed-texel-decode diff --git a/crates/metal2vulkan-runtime/src/tests/exactness.rs b/crates/metal2vulkan-runtime/src/tests/exactness.rs index e94a17883..f896fa60e 100644 --- a/crates/metal2vulkan-runtime/src/tests/exactness.rs +++ b/crates/metal2vulkan-runtime/src/tests/exactness.rs @@ -34,11 +34,15 @@ fn the_kinds_metal_answers_otherwise_are_named() { .copied() .filter(|k| k.exactness() == Exactness::OneOfMetals) .collect(); - assert_eq!(one_of_metals.len(), 11, "{one_of_metals:?}"); + assert_eq!(one_of_metals.len(), 12, "{one_of_metals:?}"); for kind in [ D::ZeroedIndexFetch, D::DontCareStore, D::NarrowSurfaceRows, + // Two rows of an IOSurface plane writing the bytes they share: Metal's blit leaves the + // earlier row's and its kernel the later row's on an M4, others on an M3 Max; the + // runtime's earlier row's is its blit's. + D::CollidingSurfaceRowWrites, D::RepeatedExecutionStart, D::OverlappingTextureCopyAsMemmove, D::PlainStateUniqueIdentifier, diff --git a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs index ee2816dd1..fba7e530b 100644 --- a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs @@ -2,6 +2,7 @@ //! alignment, where Metal lays a texture out in its buffer and which textures it refuses, as //! probes 9 to 9f measured them on an Apple M3 Max (macOS 26.7) and an M4 (27.0.1). +use super::super::buffer_texture::{plane_copy_regions, staged_rows_back}; use super::super::image_plan::plan_image; use super::super::linear_plan::{ aliases, check_linear_limits, holding, is_linear, linear_alignment, linear_lack, @@ -13,6 +14,7 @@ use super::super::values::StorageMode; use super::image_plan::{committed, facts}; use super::texture_descriptor::APPLE; use crate::MetalLevel; +use ash::vk; use metal2vulkan::metal::format::{byte_format, direct_format}; use metal2vulkan::metal::PixelFormat as P; use metal2vulkan::metal::TextureType; @@ -255,6 +257,8 @@ struct Case { bytes_per_row: u64, length: u64, storage: StorageMode, + /// The descriptor's usage, which only an IOSurface plane whose GPU rows overlap is held to. + usage: TextureUsage, } /// A 2D RGBA8Unorm texture through the public call. @@ -271,6 +275,7 @@ fn texture(width: u64, height: u64, offset: u64, bytes_per_row: u64, length: u64 bytes_per_row, length, storage: StorageMode::Shared, + usage: TextureUsage::SHADER_READ, } } @@ -339,6 +344,7 @@ fn placed(case: Case) -> Result { offset: case.offset, bytes_per_row: case.bytes_per_row, call: case.call, + usage: case.usage, }, &BufferFacts { length: case.length, @@ -1293,8 +1299,8 @@ const MEASURED: [&str; 5] = [ /// them on the M3 Max and an M4: the CPU's layout is the plane's; the GPU's starts at the /// plane's offset rounded down to 16, rows the pitch rounded down to 16 apart, or 16 apart under /// 16 bytes a row (`narrow`, where Metal's reads past the first row are memory-dependent); rows -/// that would overlap are refused; a surface without planes takes only a pitch and an offset of -/// 16 bytes. +/// that overlap lie at that pitch, which a plain plane's shadow holds and a render target's is +/// refused for; a surface without planes takes only a pitch and an offset of 16 bytes. #[test] fn iosurface_planes_lie_where_metal_puts_them() { use BufferTextureProblem as Pr; @@ -1391,24 +1397,62 @@ fn iosurface_planes_lie_where_metal_puts_them() { narrow: false, }), ), - // Rows that overlap on the GPU: 20 bytes 16 apart (RGBA8Unorm 5 wide at 20 - // to 28, R8Unorm 20 and 17 wide, RGBA16Uint 3 wide at 24 and 28). + // Rows that overlap on the GPU lie at the pitch itself, which the texture's shadow holds + // in two copy regions each way: RGBA8Unorm 5 wide at 20 and 28 bytes a row (20 bytes of + // texels 16 apart, sharing 4), R8Unorm 17 wide at 31 (sharing 1) and RGBA16Uint 3 wide + // at 24 (sharing 8). ( plane(P::RGBA8Unorm, (5, 4), (0, 20), true, 16384), - Err(BufferRefusal::OverlappingRows), + Ok(Placed { + gpu: at(0, 16, 20, 4), + cpu: at(0, 20, 20, 4), + narrow: false, + }), ), ( plane(P::RGBA8Unorm, (5, 4), (0, 28), true, 16384), - Err(BufferRefusal::OverlappingRows), + Ok(Placed { + gpu: at(0, 16, 20, 4), + cpu: at(0, 28, 20, 4), + narrow: false, + }), ), ( plane(r8, (17, 4), (0, 31), true, 16384), - Err(BufferRefusal::OverlappingRows), + Ok(Placed { + gpu: at(0, 16, 17, 4), + cpu: at(0, 31, 17, 4), + narrow: false, + }), ), ( plane(P::RGBA16Uint, (3, 4), (0, 24), true, 16384), + Ok(Placed { + gpu: at(0, 16, 24, 4), + cpu: at(0, 24, 24, 4), + narrow: false, + }), + ), + // A plane a render pass stores into is refused there: what Metal leaves of the bytes two + // rows share is not measured. Its rows a row apart or further are made as any plane's. + ( + Case { + usage: TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + ..plane(P::RGBA8Unorm, (5, 4), (0, 20), true, 16384) + }, Err(BufferRefusal::OverlappingRows), ), + ( + Case { + usage: TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + ..plane(P::RGBA8Unorm, (4, 4), (0, 20), true, 16384) + }, + Ok(Placed { + gpu: at(0, 16, 16, 4), + cpu: at(0, 20, 16, 4), + narrow: false, + }), + ), // One such row overlaps nothing; nor does one row under 16 bytes read past itself. ( plane(r8, (20, 1), (0, 20), true, 16384), @@ -1640,16 +1684,31 @@ fn every_backed_format_s_texel_divides_the_linear_alignment() { ); } -/// How far the rows of a refused IOSurface plane overlap, which bounds what holding them would -/// take. A plane's `bytesPerRow` covers its own row (`BufferTextureProblem::RowPitch`), so -/// rounding it down to 16 takes under 16 bytes off: the rows overlap by 1 to 15 bytes, a whole -/// number of texels (above), and between consecutive rows alone, since twice the GPU pitch is -/// always past one row. A plane whose rows overlap further is a two-plane YCbCr texture's rows of -/// codes, which no row rule holds (`ycbcr.rs`). +/// How far the rows of an IOSurface plane overlap, and that the copies that hold such a plane +/// tile its bytes exactly once. A plane's `bytesPerRow` covers its own row +/// (`BufferTextureProblem::RowPitch`), so rounding it down to 16 takes under 16 bytes off: the +/// rows overlap by 1 to 15 bytes, a whole number of texels (above), and between consecutive rows +/// alone, since twice the GPU pitch is always past one row. A plane whose rows overlap further is +/// a two-plane YCbCr texture's rows of codes, which no row rule holds (`ycbcr.rs`). /// -/// No plane the runtime makes has rows that overlap at all. +/// For every such plane the sweep takes the shadow's copy regions (`plane_copy_regions`) and the +/// staged copy back (`staged_rows_back`) and holds them to what Vulkan allows and to Metal's +/// order: +/// +/// - a copy in writes each of the image's texels once, each from the byte its own row holds it +/// at, so no two destination regions write one texel +/// (`VUID-vkCmdCopyBufferToImage-pRegions-12483`), and every region's `bufferRowLength` covers +/// its width (`-bufferRowLength-00195`); +/// - a copy back writes each of the plane's bytes once, so no two destination regions write one +/// byte (`VUID-vkCmdCopyImageToBuffer-pRegions-12485`), and a shared byte comes from the +/// earlier of the two rows that hold it, the order Metal's blit writes them in; +/// - a staged copy back's destination ranges never overlap +/// (`VUID-vkCmdCopyBuffer-pRegions-12482`) and keep each row's distance from the first byte. +/// +/// A plane a render pass stores into is refused instead, at exactly the shapes whose rows +/// overlap. #[test] -fn a_refused_plane_s_rows_overlap_by_under_sixteen_bytes() { +fn a_plane_whose_rows_overlap_is_copied_through_two_regions_that_tile_it_once() { let formats = [ (P::R8Unorm, 1), (P::RG8Unorm, 2), @@ -1657,8 +1716,10 @@ fn a_refused_plane_s_rows_overlap_by_under_sixteen_bytes() { (P::RGBA16Uint, 8), (P::RGBA32Uint, 16), ]; - let mut refused = 0; - let mut made = 0; + // The staging buffer's first byte and the texels' first byte in their own `VkBuffer`, which + // the staged copy back moves between. + let (start, at) = (64, 48); + let (mut overlapping, mut apart, mut refused) = (0, 0, 0); for (pf, texel) in formats { for width in 1..=40 { let row_bytes = width * texel; @@ -1673,35 +1734,165 @@ fn a_refused_plane_s_rows_overlap_by_under_sixteen_bytes() { ..texture(width, height, 0, bytes_per_row, 1 << 20) }; let pitch = bytes_per_row - bytes_per_row % LINEAR_ALIGNMENT; - match placed(case) { - Err(BufferRefusal::OverlappingRows) => { - refused += 1; - let overlap = row_bytes.saturating_sub(pitch); - assert!( - (1..LINEAR_ALIGNMENT).contains(&overlap) - && overlap.is_multiple_of(texel) - && pitch >= LINEAR_ALIGNMENT - && 2 * pitch > row_bytes, - "{pf:?} {width}x{height} at {bytes_per_row} bytes a row: \ - {overlap} bytes of overlap at a GPU pitch of {pitch}" - ); - } - Ok(placed) => { - made += 1; - assert!( - placed.gpu.row_pitch >= placed.gpu.row_bytes - && placed.cpu.row_pitch >= placed.cpu.row_bytes, - "{pf:?} {width}x{height} at {bytes_per_row} bytes a row: \ - a made plane's rows overlap" - ); - } - Err(other) => { - panic!("{pf:?} {width}x{height} at {bytes_per_row}: {other:?}") - } + let made = placed(case).unwrap_or_else(|e| panic!("{case:?}: {e:?}")); + let gpu = made.gpu; + let shared = gpu.shared_bytes(); + let target = Case { + usage: TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + ..case + }; + let (into, back) = + plane_copy_regions(&gpu, texel, start, vk::ImageAspectFlags::COLOR); + if shared == 0 { + apart += 1; + assert!(made.cpu.row_pitch >= made.cpu.row_bytes, "{case:?}"); + let same = |r: &[vk::BufferImageCopy]| { + (r.iter()) + .map(|r| { + let e = r.image_extent; + ( + r.buffer_offset, + r.buffer_row_length, + r.image_offset.x, + (e.width, e.height, e.depth), + ) + }) + .collect::>() + }; + assert_eq!(same(&into), same(&back), "{case:?}"); + assert_eq!(into.len(), 1, "{case:?}"); + assert!(placed(target).is_ok(), "{case:?}: a render target refused"); + continue; } + overlapping += 1; + refused += 1; + assert_eq!( + placed(target).err(), + Some(BufferRefusal::OverlappingRows), + "{case:?}: a render target over rows that overlap" + ); + assert!( + (1..LINEAR_ALIGNMENT).contains(&shared) + && shared.is_multiple_of(texel) + && pitch >= LINEAR_ALIGNMENT + && gpu.row_pitch == pitch + && 2 * pitch > row_bytes, + "{pf:?} {width}x{height} at {bytes_per_row} bytes a row: \ + {shared} bytes of overlap at a GPU pitch of {pitch}" + ); + hold_the_copies( + &gpu, + texel, + (start, at), + (&into, &back), + &format!("{case:?}"), + ); } } } } - assert_eq!((refused, made), (1608, 17592)); + assert_eq!((overlapping, apart, refused), (1608, 17592, 1608)); +} + +/// A shadow's copy regions for a plane laid out as `gpu`, `texel` bytes a texel, its texels at +/// `start` of the buffer the copies address and at `at` of the texture's own: each of the image's +/// texels copied in once from the byte its own row holds it at, each of the plane's bytes copied +/// back once and a shared byte from the earlier of its two rows, and a staged copy back whose +/// destination ranges never overlap (the sweep's rules). `case` names the plane in a failure. +fn hold_the_copies( + gpu: &BufferLayout, + texel: u64, + (start, at): (u64, u64), + (into, back): (&[vk::BufferImageCopy], &[vk::BufferImageCopy]), + case: &str, +) { + use std::collections::BTreeMap; + let span = gpu.end() - gpu.offset; + let width = gpu.row_bytes / texel; + assert_eq!((into.len(), back.len()), (2, 2), "{case}"); + for region in into.iter().chain(back) { + assert!( + u64::from(region.buffer_row_length) >= u64::from(region.image_extent.width), + "{case}: a row length of {} under a width of {}", + region.buffer_row_length, + region.image_extent.width + ); + } + // Going in: every texel once, from its own row's byte. + let mut read: BTreeMap<(u32, u32), u64> = BTreeMap::new(); + for region in into { + for (byte, texel_at) in copied_bytes(region, texel) { + if byte % texel == 0 { + assert!( + read.insert(texel_at, byte).is_none(), + "{case}: texel {texel_at:?} copied in twice" + ); + } + } + } + assert_eq!(read.len() as u64, width * gpu.rows, "{case}"); + for ((x, y), byte) in &read { + let want = start + u64::from(*y) * gpu.row_pitch + u64::from(*x) * texel; + assert_eq!(*byte, want, "{case}: texel {:?} read at {byte}", (x, y)); + } + // Going back: every byte of the plane once, a shared byte from the earlier of its two rows. + let mut written: BTreeMap = BTreeMap::new(); + for region in back { + for (byte, texel_at) in copied_bytes(region, texel) { + assert!( + written.insert(byte, texel_at).is_none(), + "{case}: byte {byte} written back twice" + ); + } + } + assert_eq!(written.len() as u64, span, "{case}"); + for (byte, from) in &written { + assert_eq!(*from, earliest_row(gpu, texel, byte - start), "{case}"); + } + // The staged copy back, whose ranges lie in the buffer as the plane's bytes do. + let mut staged: BTreeMap = BTreeMap::new(); + for copy in staged_rows_back(gpu, start, at) { + assert_eq!(copy.dst_offset - at, copy.src_offset - start, "{case}"); + for byte in 0..copy.size { + assert!( + staged + .insert(copy.dst_offset + byte, copy.src_offset) + .is_none(), + "{case}: byte {} written twice by the staged copy back", + copy.dst_offset + byte + ); + } + } + assert_eq!(staged.len() as u64, span, "{case}"); +} + +/// Each byte `region` moves between a buffer and an image, paired with the image texel it belongs +/// to: its region-relative texel `(i, j)` lies at `bufferOffset + (j * bufferRowLength + i) * +/// texel` and is image texel `(imageOffset.x + i, j)` (Vulkan's Buffer and Image Addressing). +fn copied_bytes(region: &vk::BufferImageCopy, texel: u64) -> Vec<(u64, (u32, u32))> { + let extent = region.image_extent; + let row = u64::from(region.buffer_row_length); + let x0 = region.image_offset.x as u32; + let mut bytes = Vec::new(); + for j in 0..extent.height { + for i in 0..extent.width { + let first = region.buffer_offset + (u64::from(j) * row + u64::from(i)) * texel; + for byte in 0..texel { + bytes.push((first + byte, (x0 + i, j))); + } + } + } + bytes +} + +/// The texel of the earliest row of a plane laid out as `gpu` that holds the byte `offset` bytes +/// into it, `texel` bytes a texel: the row whose writes Metal's blit leaves where two meet. +fn earliest_row(gpu: &BufferLayout, texel: u64, offset: u64) -> (u32, u32) { + for row in 0..gpu.rows { + let first = row * gpu.row_pitch; + if (first..first + gpu.row_bytes).contains(&offset) { + return (((offset - first) / texel) as u32, row as u32); + } + } + panic!("byte {offset} lies in no row of {gpu:?}"); } diff --git a/crates/metal2vulkan-runtime/src/tests/shadow.rs b/crates/metal2vulkan-runtime/src/tests/shadow.rs index ac827342d..06dc9a634 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow.rs @@ -77,6 +77,7 @@ fn shadow_in( target: ShadowTarget::Image { image: vk::Image::null(), regions: Vec::new(), + back: Vec::new(), staging: None, texel: Some(4), words: None, @@ -1791,3 +1792,63 @@ fn kept_steps(copies: &[ShadowCopy]) -> Vec { }) .collect() } + +/// A copy of a 2D texture's image takes the regions of its own direction +/// ([`ShadowTarget::image_regions`]): the copy-in set going in, the copy-back set going out. They +/// are one set for every shadow but one over an IOSurface plane whose rows share bytes, where +/// going in reads each shared byte for both its rows and going back writes it once, from the +/// earlier row — so a copy back that took the copy-in set would write the shared bytes twice in +/// one `vkCmdCopyImageToBuffer` (`VUID-vkCmdCopyImageToBuffer-pRegions-12485`). +#[test] +fn a_copy_of_an_image_takes_the_regions_of_its_direction() { + // The two sets a 5x4 RGBA8Unorm plane 16 bytes a row takes + // (`buffer_texture::plane_copy_regions`): the head of every row and the rest of every row + // going in, and going back the rest of every row and the head of row 0 alone. + let region = |at: u64, x: i32, width: u32, height: u32| vk::BufferImageCopy { + buffer_offset: at, + buffer_row_length: 4, + buffer_image_height: 0, + image_subresource: vk::ImageSubresourceLayers { + aspect_mask: vk::ImageAspectFlags::COLOR, + mip_level: 0, + base_array_layer: 0, + layer_count: 1, + }, + image_offset: vk::Offset3D { x, y: 0, z: 0 }, + image_extent: vk::Extent3D { + width, + height, + depth: 1, + }, + }; + let into = vec![region(0, 0, 1, 4), region(4, 1, 4, 4)]; + let back = vec![region(0, 0, 1, 1), region(4, 1, 4, 4)]; + let shape = |regions: &[vk::BufferImageCopy]| { + (regions.iter()) + .map(|r| { + let e = r.image_extent; + (r.buffer_offset, r.image_offset.x, e.width, e.height) + }) + .collect::>() + }; + let target = ShadowTarget::Image { + image: vk::Image::null(), + regions: into.clone(), + back: back.clone(), + staging: None, + texel: Some(4), + words: None, + unorm: None, + }; + assert_eq!( + shape(target.image_regions(true).expect("an image's regions")), + shape(&into) + ); + assert_eq!( + shape(target.image_regions(false).expect("an image's regions")), + shape(&back) + ); + // The two sets differ, so taking the wrong one is visible: the copy-in set reads the shared + // head of all four rows, the copy-back set writes row 0's alone. + assert_ne!(shape(&into), shape(&back)); +} diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index afc62fdbc..ae16fbb4a 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -3488,6 +3488,9 @@ impl Device { bytes: tracked, target: ShadowTarget::Image { image, + // A heap's depth or stencil texture holds no byte twice: its copies back + // are its copies in. + back: regions.clone(), regions, staging: None, texel: None, diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 02fc5c6d9..746c4ddc2 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -d93008b820fb9c05cf7c2c94733e0bea81444d3c165da58594d07651909ccbb2 +c2472e7f6a66c662aa810a456a103f9a22e64b28c8cdbe79478ce63ba5405636 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 470a3d8db..6f5c4579f 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs @@ -958,6 +958,15 @@ fn iosurface_planes_lie_where_metal_puts_them() { .new_texture_with_iosurface_plane(&d, plane) .err() }; + // As `refused`, with render target usage beside the descriptor's own. + let refused_target = |pf, [w, h]: [u64; 2], plane| { + let mut d = TextureDescriptor::texture_2d(pf, w, h, false); + d.resource_options = held.buffer.resource_options(); + d.usage |= TextureUsage::RENDER_TARGET; + held.buffer + .new_texture_with_iosurface_plane(&d, plane) + .err() + }; let flat = IoSurfacePlane::new(0, 4, false); assert_eq!( refused(PixelFormat::R8Unorm, [4, 4], flat), @@ -969,9 +978,12 @@ fn iosurface_planes_lie_where_metal_puts_them() { }), ))) ); + // A plane whose GPU rows share bytes (20 bytes of texels 16 apart): made for a + // plain descriptor, its shadow's copies reproducing the sharing, and refused where a + // render pass would store into it, what Metal leaves there being unmeasured. let overlapping = IoSurfacePlane::new(0, 20, true); assert_eq!( - refused(PixelFormat::RGBA8Unorm, [5, 4], overlapping), + refused_target(PixelFormat::RGBA8Unorm, [5, 4], overlapping), Some(Error::NotImplemented(RuntimeGap::OverlappingSurfaceRows)) ); // A surface made with `kIOSurfaceClientDirection`, SPI, is refused whatever the diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index c8ee37f01..39f0f48c2 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 449; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1596; +pub const RUNTIME_VERSION: u32 = 1597; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 0eb7cb1ba..4b004dffe 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -4898,6 +4898,7 @@ macro-member metal2vulkan-runtime::Degradation::CappedAnisotropy CappedAnisotrop macro-member metal2vulkan-runtime::Degradation::CarriedDecodedTwin CarriedDecodedTwin = "carried-decoded-twin", Performance, macro-member metal2vulkan-runtime::Degradation::ClippedCoverageSplit ClippedCoverageSplit = "clipped-coverage-split"; macro-member metal2vulkan-runtime::Degradation::ClippedDepthPieces ClippedDepthPieces = "clipped-depth-pieces", Precision, +macro-member metal2vulkan-runtime::Degradation::CollidingSurfaceRowWrites CollidingSurfaceRowWrites = "colliding-surface-row-writes", Precision, macro-member metal2vulkan-runtime::Degradation::ColorAttachmentGroups ColorAttachmentGroups = "color-attachment-groups"; macro-member metal2vulkan-runtime::Degradation::CombinedArchiveStages CombinedArchiveStages = "combined-archive-stages", Precision, macro-member metal2vulkan-runtime::Degradation::CompressedTexelDecode CompressedTexelDecode = "compressed-texel-decode", Precision, diff --git a/docs/API.md b/docs/API.md index 64adce172..15b367957 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1810,6 +1810,15 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. after a write, bytes neither the surface's nor written). Cost: a GPU read of a row past the first reads the bytes the GPU's writes put there, 16 bytes a row apart, where Metal's GPU reads memory-dependent bytes; CPU access and the GPU's writes and first row are Metal's. +- `metal2vulkan-degrade-colliding-surface-row-writes` (precision). `CollidingSurfaceRowWrites`: A + texture of an IOSurface plane whose rows share bytes on Metal's GPU: more than one row of over 16 + bytes whose `bytesPerRow` rounded down to 16 is below the row, so consecutive rows share 1 to 15 + bytes, a whole number of texels. Metal's reads see the sharing and so do the runtime's, through a + shadow whose two copy regions each way hold it; but where two rows' writes meet Metal's answer is + not one value: its blit leaves the earlier row's bytes, and its kernel the later row's on an M4 + and others on an M3 Max. Cost: where two of the plane's rows write the bytes they share the + earlier row's stand, as Metal's blit leaves them, where a kernel of Metal's leaves the later + row's on an M4 and others on an M3 Max; reads, CPU access and every other byte are Metal's. - `metal2vulkan-degrade-absent-argument-read` (precision). `AbsentArgumentRead`: A pipeline state's function may read an argument its function constants removed (a texture's read, sample, gather, query or atomic, or a sample through a removed sampler; `RuntimeFact::AbsentArgumentRead`), which diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 5553a5e82..80dc18a60 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -857,17 +857,18 @@ announces `shared-in-system-memory` for every `Shared` buffer and no recording t declare it, which counts 699 of the 5080's cases divergent with 655 of them differing in nothing else. -- **A texture over an IOSurface plane whose GPU rows overlap is refused.** Metal makes it: a plane - of more than one row of over 16 bytes whose `bytesPerRow` rounded down to 16 is below the row - reads and writes its rows that far apart, so consecutive rows share bytes - (`NotImplemented(OverlappingSurfaceRows)`, `linear_plan.rs`). No Vulkan image holds rows that - overlap, so such a texture would be a shadow whose copies reproduce the sharing. For a plane - whose pitch covers its own row the sharing is small and fixed: 1 to 15 bytes, a whole number of - texels, between consecutive rows alone (`tests::linear_plan`), which two copy regions a slice - express in each direction — a copy in that reads every row's shared head and the rest of each - row, and a copy back that writes each row from its head's texels on, with row 0's head alone - beside it, so every byte is written once and the shared bytes keep the earlier row's, the order - Metal's blit leaves. That still needs a note for a kernel's colliding writes, where Metal leaves - the later row's bytes on an M4 and others on an M3 Max, and a render pass's store into such rows - is unmeasured. A two-plane YCbCr texture's rows of codes, which no row rule holds, overlap by any - amount across any number of rows and need more than those two regions. +- **A texture over an IOSurface plane whose GPU rows overlap is served only as a shadow.** A plain + plane of more than one row of over 16 bytes whose `bytesPerRow` rounded down to 16 is below the + row is made: its rows share 1 to 15 bytes, a whole number of texels, between consecutive rows + alone, and its shadow's copies hold the sharing with two regions a slice each way, which + announces `colliding-surface-row-writes` (`linear_plan.rs`, + `buffer_texture::plane_copy_regions`). Still refused + `NotImplemented(OverlappingSurfaceRows)`: a plane a render pass stores into, where what Metal + leaves of the shared bytes is unmeasured; a two-plane YCbCr texture's rows of codes, which no row + rule holds and which overlap by any amount across any number of rows, and the other formats whose + rows no row rule bounds (a two-plane extended-range one's, a 4:2:2 one's pairs, a depth or stencil + plane's elements), which two regions do not express; and a blit that addresses such a plane's rows + as bytes (`blit_texture.rs`), whose row copies leave the later row's bytes where two meet, as a + rotated texture's Metal blit writes them, not the earlier row's that Metal's blit through such a + plane leaves. A rotated plane never reaches any of this: its `bytesPerRow` must be a multiple of + 16, so its GPU rows lie at the pitch itself.