From 42e11abcd496241ee2ec08cda403b7a9a9d18443 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 12 Nov 2026 02:42:03 -0800 Subject: [PATCH] Textures over buffers only the device's ordered commands write hold their rows' padding in place What: a texture that renders nothing over a buffer of the runtime's own memory whose rows lie with the buffer's bytes between them is now the device's linear image, made PREINITIALIZED, at the buffer's pitch, where only the device's commands, in the runtime's order, write those bytes: a Private buffer, and a Managed buffer's own on a device without unified memory (a two-copy no-copy buffer's device copy, or one with its own host copy), not one whose VkBuffer was handed out or whose memory is exportable (Buffer::gpu_bytes_ordered). linear_plan::holding answers what an image may hold besides the texels (Between::{Nothing, Unobserved, Kept}); Kept takes route 1 alone: the linear image whose rowPitch the driver reports equal to the buffer's (vkGetImageSubresourceLayout, aliases with within_padding). No DRM_FORMAT_MOD_LINEAR image at Metal's pitch, no image over exportable memory or in exportable blocks, as each is made UNDEFINED. A render target stays a shadow. Counted: WorkCounts::kept_padding_aliases. Also two pairs of counts of what the program asks of a two-copy Managed buffer, beside the bytes the runtime copies: managed_ranges_modified and managed_bytes_modified (did_modify_range), managed_resources_synchronized and managed_bytes_synchronized (synchronize_resource), to compare with managed_bytes_copied_in and managed_bytes_copied_out. Why: the RTX 2080 guest census (reims's v302 run) made 230 textures over Managed buffers, 200 of them RGBA8 ShaderRead|ShaderWrite at 3884, 4208 and 2448 texels a row with rows rounded up to 256 bytes, every one a shadow for its padded rows ("its rows lie N bytes apart"): 2.52 G shadow texels first copied in, 1.26 G kept, 1.26 G words examined by merges back. Owner's rule: in place where possible, a shadow only where impossible. Main approved the route and its conditions. Basis (Vulkan 1.4, docs/API.md's shadowed-texture entry): 7.1.1 Image Layout Transitions, "Image layout transitions may perform read and write accesses on all memory bound to the image subresource range ... If the old layout matches the current layout of the image subresource range, the transition preserves the contents of that range": the image's one transition is its first move, PREINITIALIZED to GENERAL, out of the layout it is in, ordered after and before every write of those bytes, as only the device's ordered commands write them. 12.11 Memory Aliasing: "Buffers, linear tensors, and linear image subresources are considered host-accessible subresources when they are in any of these layouts: VK_IMAGE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_GENERAL ... If two aliases are both host-accessible, then they interpret the contents of the memory in consistent ways, and data written to one alias can be read by the other alias." VkSubresourceLayout's "size includes any extra memory that is required based on rowPitch" puts the padding inside the range. A kernel's writes may change the padding as on the x86 Macs (in_place::Padding::Free); a render pass's load and store "may read and write back" it, so render targets keep the shadow. Verified: not built yet. tests::kept_padding (a Private buffer at 416, 448 and 512 bytes a row, the buffer read back whole after the image's first move; a Managed two-copy texture changed in one row through did_modify_range, then a blit-written row synchronized out, every byte between rows as given, against a Shared buffer's shadow), tests::linear_plan's holding cases and tests::texture_placement run on lavapipe next, then one RTX 3090 run. --- crates/metal2vulkan-runtime/src/blit.rs | 5 + crates/metal2vulkan-runtime/src/buffer.rs | 12 + .../metal2vulkan-runtime/src/degradation.rs | 6 +- .../metal2vulkan-runtime/src/linear_plan.rs | 71 +++- crates/metal2vulkan-runtime/src/managed.rs | 6 + .../src/tests/kept_padding.rs | 389 ++++++++++++++++++ .../src/tests/linear_plan.rs | 118 +++++- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/texture_placement.rs | 6 +- crates/metal2vulkan-runtime/src/texture.rs | 91 ++-- .../metal2vulkan-runtime/src/texture/route.rs | 24 +- .../src/texture_placement.rs | 7 +- .../metal2vulkan-runtime/src/work_counts.rs | 51 +++ crates/metal2vulkan/tests/api_signatures.tsv | 5 + docs/API.md | 18 +- docs/HOWTO.md | 7 +- 16 files changed, 749 insertions(+), 69 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/kept_padding.rs diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 5ed18c25e..8971b104a 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -638,6 +638,11 @@ impl BlitCommandEncoder { } let (own, start) = buffer.at(range.start); let bytes = range.end - range.start; + // A two-copy buffer over the caller's pages (`managed_copy.rs`): the range the + // program asked, which the command copies out. + if buffer.caller_copy().is_some() { + (this.core.device().shared().counts).managed_asked(bytes, false); + } match host { SyncTarget::Own(host) => { let copy = region(start, range.start, bytes); diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 7b4e481bb..05c1d47ad 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -4022,6 +4022,18 @@ impl Buffer { self.s().padding_unobserved.load(Ordering::Acquire) } + /// Whether only the device's commands, in the order the runtime records and submits them, + /// write the bytes the GPU uses: a `Private` buffer's, which no CPU maps + /// ([`Buffer::mapped_contents`]), and a `Managed` buffer's own on a device without unified + /// memory ([`HostCopy`]), which the CPU's writes reach only through the copies the device's + /// next submission makes before its commands (`managed.rs`, `managed_copy.rs`). Not one whose + /// `VkBuffer` was handed out (`Buffer::vk_buffer`) or whose memory was made exportable + /// (`exported_memory.rs`), which work of another API's may write. + pub(super) fn gpu_bytes_ordered(&self) -> bool { + let own = self.storage_mode() == StorageMode::Private || self.mirror().is_some(); + own && !self.s().handed_out.load(Ordering::Acquire) && self.exported().is_none() + } + /// [`Buffer::at`] for `reason`, which a no-copy buffer's import counts its read apart for /// (`HostImport::note_read_apart`). pub(super) fn at_for(&self, offset: u64, reason: ReadApart) -> (vk::Buffer, u64) { diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index d387f14df..1e88fce2e 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -260,7 +260,11 @@ degradations! { /// 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 + /// attachment's image subresource, and Metal leaves them as the program writes them (but + /// for a texture that renders nothing over a buffer only the device's ordered commands + /// write, a `Private` one or a `Managed` one's own on a device without unified memory, + /// whose linear image, made `PREINITIALIZED`, keeps them through its one layout + /// transition: docs/API.md); 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; or it is a tiled texture of more than one level diff --git a/crates/metal2vulkan-runtime/src/linear_plan.rs b/crates/metal2vulkan-runtime/src/linear_plan.rs index 4d12059ac..bbd79b927 100644 --- a/crates/metal2vulkan-runtime/src/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/linear_plan.rs @@ -1261,20 +1261,19 @@ 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 the texture's texels ([`texels_alone`]), or, where the buffer -/// declares the bytes between rows and slices unobserved (`padding_unobserved`, -/// `BufferDescriptor::padding_unobserved`), none but its texels and those bytes -/// ([`within_padding`]), 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`]), or, where `between` (the +/// image may hold the bytes between rows and slices: [`Between::Unobserved`], +/// [`Between::Kept`]), none but its texels and those bytes ([`within_padding`]), 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, memory_offset: u64, room: u64, image: &LinearImage, - padding_unobserved: bool, + between: bool, ) -> bool { - let held = match padding_unobserved { + let held = match between { true => within_padding(layout, image.subresource, image.array_pitch), false => texels_alone(layout, image.subresource, image.array_pitch), }; @@ -1287,6 +1286,28 @@ pub(super) fn aliases( && image.size <= room } +/// What an image over a buffer's texels holds besides them, as [`holding`] lets it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Between { + /// No byte: the texels' rows (and slices) lie one after another, or there is one of each. + Nothing, + /// The bytes between their rows and slices, which the buffer declares unobserved + /// (`BufferDescriptor::padding_unobserved`): any image over the texels may hold them, and its + /// operations change them. + Unobserved, + /// The bytes between their rows and slices, which only the device's ordered commands write, of + /// a texture that renders nothing: the device's linear image made `PREINITIALIZED` alone holds + /// them, its one transition keeping them. + Kept, +} + +impl Between { + /// Whether an image may hold the bytes between the texels' rows and slices. + pub(crate) fn held(self) -> bool { + self != Between::Nothing + } +} + /// 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 consecutive rows share bytes (an IOSurface plane's on Metal's GPU, which no image holds @@ -1318,14 +1339,30 @@ pub(super) fn aliases( /// `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; but where `padding_unobserved` (the buffer, of the runtime's own memory, declares that -/// nothing reads those bytes: `BufferDescriptor::padding_unobserved`), an image over its rows and -/// slices may hold the bytes between them, which those operations may then change. +/// alone; but an image over its rows and slices may hold the bytes between them ([`Between`]): +/// +/// - where `padding_unobserved` (the buffer, of the runtime's own memory, declares that nothing +/// reads those bytes: `BufferDescriptor::padding_unobserved`), any such image, whose operations +/// may then change them ([`Between::Unobserved`]); +/// - where `ordered` (only the device's commands, in the order the runtime records them, write the +/// bytes the GPU uses: `Buffer::gpu_bytes_ordered`) and the texture renders nothing, the device's +/// linear image made `PREINITIALIZED` alone ([`Between::Kept`]). Its one transition, its first +/// move to `GENERAL`, is from the layout it is in, and of such a one the same section says "If +/// the old layout matches the current layout of the image subresource range, the transition +/// preserves the contents of that range" (Vulkan 7.1.1), ordered after every write of those +/// bytes before it and before every one after; and in `GENERAL`, the image and the buffer are +/// both host-accessible subresources, which "interpret the contents of the memory in +/// consistent ways, and data written to one alias can be read by the other alias" (12.11, Memory +/// Aliasing). A shader's writes of the texture may change its rows' padding, as on the x86 Macs +/// (`in_place::Padding::Free`); no render pass writes them back. An image made `UNDEFINED`, as a +/// `DRM_FORMAT_MOD_LINEAR` one and one for external memory are, takes none of them: its first +/// move may discard them. pub(super) fn holding( layout: &BufferLayout, usage: TextureUsage, padding_unobserved: bool, -) -> Result<(), String> { + ordered: bool, +) -> Result { // An IOSurface plane's rows that overlap: no image holds them, whatever its usage. let shared = layout.shared_bytes(); if shared != 0 { @@ -1337,7 +1374,7 @@ pub(super) fn holding( } let (rows, slices) = apart(layout); if padding_unobserved { - return Ok(()); + return Ok(Between::Unobserved); } let apart = if rows { format!( @@ -1350,9 +1387,13 @@ pub(super) fn holding( layout.slice_pitch, layout.rows, layout.row_pitch ) } else { - return Ok(()); + return Ok(Between::Nothing); }; - let writers = if usage.contains(TextureUsage::RENDER_TARGET) { + let renders = usage.contains(TextureUsage::RENDER_TARGET); + if ordered && !renders { + return Ok(Between::Kept); + } + let writers = if renders { "its layout transitions read and write, and a render pass's load and store operations \ write back" } else { diff --git a/crates/metal2vulkan-runtime/src/managed.rs b/crates/metal2vulkan-runtime/src/managed.rs index 667c874fd..7e2a0def0 100644 --- a/crates/metal2vulkan-runtime/src/managed.rs +++ b/crates/metal2vulkan-runtime/src/managed.rs @@ -54,6 +54,12 @@ impl Buffer { }, )); } + // A two-copy buffer over the caller's pages (`managed_copy.rs`): the range the program + // asked, which the upload copies in. + if self.caller_copy().is_some() && !range.is_empty() { + let counts = &self.device().shared().counts; + counts.managed_asked(range.end - range.start, true); + } self.upload(range) } } diff --git a/crates/metal2vulkan-runtime/src/tests/kept_padding.rs b/crates/metal2vulkan-runtime/src/tests/kept_padding.rs new file mode 100644 index 000000000..0d9bf0148 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/kept_padding.rs @@ -0,0 +1,389 @@ +//! A texture that renders nothing over a buffer whose bytes only the device's ordered commands +//! write (`Buffer::gpu_bytes_ordered`: a `Private` buffer, a `Managed` one's own on a device +//! without unified memory), its rows lying with the buffer's bytes between them +//! (`linear_plan::Between::Kept`): +//! +//! - **Over a `Private` buffer.** An `RGBA8Unorm` texture of 101x48 texels (404 bytes a row) at 416, +//! 448 and 512 bytes a row (the next multiples of 16, 64 and 256, at which drivers lay linear +//! rows: MoltenVK, llvmpipe and ANV, RADV and NVIDIA), read alone or read and written by shaders, +//! is the device's linear image, made `PREINITIALIZED`, over the buffer's memory where the device +//! lays its rows at the pitch: counted (`WorkCounts::kept_padding_aliases`), no shadow +//! (`shadowed_textures`), answering `NotHostPages`; else a shadow whose answer names its cause, +//! never `BytesBetweenRows`. At least one pitch takes the image. A blit reads the texels the +//! buffer holds, and once that blit took the image's first move, the buffer read back holds +//! every byte it was given, the bytes between the rows among them. +//! - **A `Managed` texture changed in one row.** On a device without unified memory, over a +//! `Managed` no-copy buffer that is two copies (`managed_copy.rs`), at the first pitch the +//! device lays its linear rows at: in place, as over a `Private` buffer. The CPU writes one row +//! of the caller's pages and `did_modify_range` names it +//! (`WorkCounts::managed_ranges_modified`, `managed_bytes_modified`); the next blit of the +//! texture reads that row, with no shadow texel copied in. A blit writes another row into the +//! texture and `synchronize_resource` copies its span out (`managed_resources_synchronized`, +//! `managed_bytes_synchronized`): the caller's pages hold both rows, and every byte between the +//! rows as given. The same texture over a `Shared` buffer, which the CPU writes at any time, is +//! a shadow (`BytesBetweenRows`), whose copy of the texels in at that blit is counted +//! (`shadow_texels_copied_in`): what the `Managed` texture paid before its route. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. Printed (`KEPT-PADDING`): each pitch's +//! answer and route, and the counts. + +use super::blit_holds::{device, Host, Scratch, BYTES, WAIT}; +use crate::{ + BlitCommandEncoder, BlitOption, Buffer, CommandQueue, CpuCacheMode, Device, HazardTrackingMode, + HostBacking, Origin, ResourceOptions, ResourceRef, Size, StorageMode, Texture, + TextureDescriptor, TexturePlacement, TextureShadowReason, +}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; + +/// The texture's texels a row, and its rows. +const WIDTH: u64 = 101; +const HEIGHT: u64 = 48; + +/// The bytes of a row's texels. +const ROW: u64 = WIDTH * 4; + +/// The pitches past its 404-byte rows the texture is made at. +const PITCHES: [u64; 3] = [416, 448, 512]; + +/// `Managed` storage. +fn managed() -> ResourceOptions { + ResourceOptions::new( + StorageMode::Managed, + CpuCacheMode::DefaultCache, + HazardTrackingMode::Default, + ) +} + +/// `length` bytes that name their place and `seed`, none of them zero. +fn named(length: u64, seed: u64) -> Vec { + (0..length) + .map(|i| ((i * 13 + i / 251 + seed) % 251) as u8 + 1) + .collect() +} + +/// The texture's descriptor, of `options` and `usage`. +fn descriptor(options: ResourceOptions, usage: TextureUsage) -> TextureDescriptor { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, WIDTH, HEIGHT, false); + descriptor.usage = usage; + descriptor.resource_options = options; + descriptor +} + +/// One command buffer of `queue` of the blit commands `encode` encodes, completed. +fn run(queue: &CommandQueue, encode: impl FnOnce(&mut BlitCommandEncoder)) { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + encode(&mut blit); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); +} + +/// The first `length` bytes the CPU maps of `buffer` (a two-copy buffer's: the caller's pages). +fn mapped(buffer: &Buffer, length: u64) -> Vec { + let at = buffer.contents().expect("a buffer the CPU maps"); + // SAFETY: the buffer's mapped bytes, at least `length` of them, which no command uses now. + unsafe { std::slice::from_raw_parts(at.as_ptr(), length as usize) }.to_vec() +} + +/// Write `bytes` from byte `at` of the bytes the CPU maps of `buffer`. +fn write(buffer: &Buffer, at: u64, bytes: &[u8]) { + assert!(at + bytes.len() as u64 <= buffer.length()); + let to = buffer.contents().expect("a buffer the CPU maps"); + // SAFETY: the buffer's mapped bytes hold `at + bytes.len()` bytes (above), which no command + // uses now. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), to.as_ptr().add(at as usize), bytes.len()) + }; +} + +/// `buffer`'s first `length` bytes, through a blit into a `Shared` buffer. +fn read_back(device: &Device, queue: &CommandQueue, buffer: &Buffer, length: u64) -> Vec { + let read = device + .new_buffer(length, ResourceOptions::shared()) + .unwrap(); + run(queue, |blit| { + blit.copy_from_buffer_to_buffer(buffer, 0, &read, 0, length) + .unwrap(); + }); + mapped(&read, length) +} + +/// The texels of `texture` as a blit copies them into a buffer of rows one after another. +fn blitted(device: &Device, queue: &CommandQueue, texture: &Texture) -> Vec { + let read = device + .new_buffer(ROW * HEIGHT, ResourceOptions::shared()) + .unwrap(); + run(queue, |blit| { + blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(WIDTH, HEIGHT, 1), + &read, + 0, + ROW, + ROW * HEIGHT, + BlitOption::None, + ) + .unwrap(); + }); + mapped(&read, ROW * HEIGHT) +} + +/// The texels `bytes` holds at `pitch`, rows one after another. +fn texels_of(bytes: &[u8], pitch: u64) -> Vec { + (0..HEIGHT) + .flat_map(|y| { + let at = (y * pitch) as usize; + bytes[at..at + ROW as usize].iter().copied() + }) + .collect() +} + +#[test] +fn a_texture_over_a_private_buffer_holds_its_rows_padding_in_place_and_keeps_it() { + let scratch = Scratch::new("kept-padding-private"); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let mut in_place = Vec::new(); + for usage in [ + TextureUsage::SHADER_READ, + TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE, + ] { + for pitch in PITCHES { + let what = format!("{usage:?} at {pitch}"); + let length = pitch * HEIGHT; + let written = named(length, pitch); + let staging = device + .new_buffer_with_bytes(&written, ResourceOptions::shared()) + .unwrap(); + let buffer = device + .new_buffer(length, ResourceOptions::private()) + .unwrap(); + assert!(buffer.gpu_bytes_ordered(), "{what}: a Private buffer"); + run(&queue, |blit| { + blit.copy_from_buffer_to_buffer(&staging, 0, &buffer, 0, length) + .unwrap(); + }); + let d = descriptor(ResourceOptions::private(), usage); + let answer = buffer.texture_placement(&d, 0, pitch).unwrap(); + let before = device.work_counts(); + let texture = buffer.new_texture(&d, 0, pitch).unwrap(); + let after = device.work_counts(); + let aliases = texture.aliases_buffer(); + assert_eq!(aliases, texture.shadow().is_none(), "{what}"); + assert_eq!( + answer == TexturePlacement::NotHostPages, + aliases, + "{what}: the answer {answer:?} is the making's" + ); + assert_ne!( + answer, + TexturePlacement::Shadow(TextureShadowReason::BytesBetweenRows), + "{what}: its padding is no cause" + ); + assert_eq!( + after.kept_padding_aliases - before.kept_padding_aliases, + u64::from(aliases), + "{what}: counted as an image over kept padding" + ); + assert_eq!( + after.shadowed_textures - before.shadowed_textures, + u64::from(!aliases), + "{what}: counted as a shadow" + ); + assert!( + blitted(&device, &queue, &texture) == texels_of(&written, pitch), + "{what}: a blit reads the buffer's texels" + ); + let back = read_back(&device, &queue, &buffer, length); + let changed = (0..length as usize) + .filter(|&i| back[i] != written[i]) + .count(); + assert_eq!(changed, 0, "{what}: bytes of the buffer changed"); + if aliases { + in_place.push(what.clone()); + } + eprintln!( + "KEPT-PADDING on {}: {what} over a Private buffer: {answer:?}, in place {aliases}", + device.name() + ); + } + } + assert!(!in_place.is_empty(), "no pitch took the linear image"); +} + +#[test] +fn a_managed_texture_changed_in_one_row_reads_it_in_place_where_a_shared_one_copies_its_shadow() { + let host = Host::new(); + let scratch = Scratch::new("kept-padding-managed"); + let device = device(&scratch.0); + if device.properties().has_unified_memory { + eprintln!( + "KEPT-PADDING on {}: skipped, a Managed buffer is one copy on unified memory", + device.name() + ); + return; + } + let queue = device.new_command_queue().unwrap(); + let usage = TextureUsage::SHADER_READ; + // The first pitch at which the texture over a two-copy buffer is in place. + let mut found = None; + for pitch in PITCHES { + let length = pitch * HEIGHT; + assert!(length as usize <= BYTES); + // SAFETY: the host memory outlives the buffer, dropped before it, and only it uses them. + let buffer = + unsafe { device.new_buffer_with_bytes_no_copy(host.memory(), length, managed(), None) } + .unwrap(); + if buffer.host_backing() != Some(HostBacking::DeviceCopy) { + eprintln!( + "KEPT-PADDING on {}: skipped, the Managed no-copy buffer is no two copies ({:?})", + device.name(), + buffer.host_backing() + ); + return; + } + let texture = buffer + .new_texture(&descriptor(managed(), usage), 0, pitch) + .unwrap(); + eprintln!( + "KEPT-PADDING on {}: Managed at {pitch}: in place {}", + device.name(), + texture.aliases_buffer() + ); + if texture.aliases_buffer() { + found = Some(pitch); + break; + } + } + let Some(pitch) = found else { + panic!("no pitch took the linear image over a Managed buffer"); + }; + let length = pitch * HEIGHT; + let written = named(length, 7); + let words: Vec = (written.chunks_exact(4)) + .map(|word| u32::from_le_bytes(word.try_into().unwrap())) + .collect(); + host.set(0, &words); + // SAFETY: as above. + let buffer = + unsafe { device.new_buffer_with_bytes_no_copy(host.memory(), length, managed(), None) } + .unwrap(); + let made = device.work_counts(); + let texture = buffer + .new_texture(&descriptor(managed(), usage), 0, pitch) + .unwrap(); + let after = device.work_counts(); + assert!(texture.aliases_buffer(), "in place at {pitch}"); + assert_eq!(after.kept_padding_aliases - made.kept_padding_aliases, 1); + assert!(blitted(&device, &queue, &texture) == texels_of(&written, pitch)); + + // The CPU writes row 7's texels; `did_modify_range` names them. + let mut expected = written.clone(); + let row = (7 * pitch) as usize..(7 * pitch + ROW) as usize; + expected[row.clone()].copy_from_slice(&named(ROW, 99)); + write(&buffer, row.start as u64, &expected[row.clone()]); + let before = device.work_counts(); + buffer + .did_modify_range(row.start as u64..row.end as u64) + .unwrap(); + let read = blitted(&device, &queue, &texture); + let after = device.work_counts(); + assert!(read == texels_of(&expected, pitch), "the blit reads row 7"); + let asked = ( + after.managed_ranges_modified - before.managed_ranges_modified, + after.managed_bytes_modified - before.managed_bytes_modified, + ); + assert_eq!(asked, (1, ROW), "the range asked"); + let copied_in = after.managed_bytes_copied_in - before.managed_bytes_copied_in; + let shadow_in = after.shadow_texels_copied_in - before.shadow_texels_copied_in; + assert_eq!(shadow_in, 0, "no shadow texel copied in"); + + // A blit writes row 20 into the texture; `synchronize_resource` copies its span out. + let row20 = named(ROW, 55); + let source = device + .new_buffer_with_bytes(&row20, ResourceOptions::shared()) + .unwrap(); + let synced = device.work_counts(); + run(&queue, |blit| { + blit.copy_from_buffer_to_texture( + &source, + 0, + ROW, + ROW, + Size::new(WIDTH, 1, 1), + &texture, + 0, + 0, + Origin::new(0, 20, 0), + BlitOption::None, + ) + .unwrap(); + blit.synchronize_resource(ResourceRef::Texture(&texture)) + .unwrap(); + }); + let done = device.work_counts(); + let at = (20 * pitch) as usize; + expected[at..at + ROW as usize].copy_from_slice(&row20); + let pages = mapped(&buffer, length); + let changed = (0..length as usize) + .filter(|&i| pages[i] != expected[i]) + .count(); + assert_eq!( + changed, 0, + "bytes of the caller's pages otherwise than expected" + ); + let synchronized = ( + done.managed_resources_synchronized - synced.managed_resources_synchronized, + done.managed_bytes_synchronized - synced.managed_bytes_synchronized, + ); + let span = (HEIGHT - 1) * pitch + ROW; + assert_eq!(synchronized, (1, span), "the span asked"); + let copied_out = done.managed_bytes_copied_out - synced.managed_bytes_copied_out; + drop((texture, buffer)); + + // The same over a `Shared` buffer: a shadow, which copies its texels in at the blit; but one + // in a block of the runtime's own pages takes the route over fresh pages + // (`memory.rs`'s `Holds::PageBuffers`). + let shared = device + .new_buffer(length, ResourceOptions::shared()) + .unwrap(); + if shared.in_page_block() { + eprintln!( + "KEPT-PADDING on {}: Managed at {pitch} in place: row 7 asked {asked:?}, copied in \ + {copied_in} bytes, shadow texels copied in {shadow_in}; synchronize_resource asked \ + {synchronized:?}, copied out {copied_out} bytes; the Shared buffer lies in a block \ + of the runtime's own pages", + device.name() + ); + return; + } + write(&shared, 0, &written); + let d = descriptor(ResourceOptions::shared(), usage); + assert_eq!( + shared.texture_placement(&d, 0, pitch).unwrap(), + TexturePlacement::Shadow(TextureShadowReason::BytesBetweenRows) + ); + let shadowed = shared.new_texture(&d, 0, pitch).unwrap(); + assert!(shadowed.shadow().is_some()); + write(&shared, row.start as u64, &expected[row]); + let before = device.work_counts(); + let read = blitted(&device, &queue, &shadowed); + let after = device.work_counts(); + assert!(read[7 * ROW as usize..8 * ROW as usize] == named(ROW, 99)); + let shared_in = after.shadow_texels_copied_in - before.shadow_texels_copied_in; + assert!(shared_in > 0, "the shadow copies its texels in"); + eprintln!( + "KEPT-PADDING on {}: Managed at {pitch} in place: row 7 asked {asked:?}, copied in \ + {copied_in} bytes, shadow texels copied in {shadow_in}; synchronize_resource asked \ + {synchronized:?}, copied out {copied_out} bytes; the Shared texture's shadow copied in \ + {shared_in} texels", + device.name() + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs index 1b5fa490b..be47dfc55 100644 --- a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs @@ -7,8 +7,9 @@ use super::super::dma_buf::ModifierMemory; use super::super::image_plan::plan_image; use super::super::linear_plan::{ aliases, apart_from_plane, check_linear_limits, holding, is_linear, linear_alignment, - linear_lack, plan_buffer_texture, BufferFacts, BufferLayout, BufferRefusal, BufferTexture, - BufferTextureCall, BufferTextureProblem, LinearImage, LinearLack, Placed, LINEAR_ALIGNMENT, + linear_lack, plan_buffer_texture, Between, 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; @@ -868,8 +869,12 @@ fn a_linear_image_aliases_only_metals_layout() { TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, TextureUsage::SHADER_READ, ] { - assert!(holding(&padded, usage, false).is_err(), "{usage:?}"); - assert_eq!(holding(&single, usage, false), Ok(()), "{usage:?}"); + assert!(holding(&padded, usage, false, false).is_err(), "{usage:?}"); + assert_eq!( + holding(&single, usage, false, false), + Ok(Between::Nothing), + "{usage:?}" + ); } // One row has nothing between rows, but its pitch's padding past the texels. let row = BufferLayout { @@ -877,7 +882,10 @@ fn a_linear_image_aliases_only_metals_layout() { slice_pitch: 80, ..padded }; - assert_eq!(holding(&row, TextureUsage::SHADER_READ, false), Ok(())); + assert_eq!( + holding(&row, TextureUsage::SHADER_READ, false, false), + Ok(Between::Nothing) + ); assert!(!aliases( &row, 4096, @@ -926,7 +934,7 @@ fn a_linear_image_aliases_only_metals_layout() { TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, TextureUsage::SHADER_READ, ] { - assert!(holding(&apart, usage, false).is_err(), "{usage:?}"); + assert!(holding(&apart, usage, false, false).is_err(), "{usage:?}"); } assert!(!aliases( &apart, @@ -990,7 +998,11 @@ fn unobserved_padding_lets_an_image_hold_the_bytes_between_rows_alone() { TextureUsage::SHADER_READ, TextureUsage::SHADER_WRITE, ] { - assert_eq!(holding(&padded, usage, true), Ok(()), "{usage:?}"); + assert_eq!( + holding(&padded, usage, true, false), + Ok(Between::Unobserved), + "{usage:?}" + ); } // The subresource to the last row's pitch, and one that stops at its texels. assert!(aliases(&padded, 4096, 320, &image, true)); @@ -1020,7 +1032,10 @@ fn unobserved_padding_lets_an_image_hold_the_bytes_between_rows_alone() { slice_pitch: 384, ..padded }; - assert_eq!(holding(&apart, TextureUsage::SHADER_READ, true), Ok(())); + assert_eq!( + holding(&apart, TextureUsage::SHADER_READ, true, false), + Ok(Between::Unobserved) + ); let stacked = LinearImage { size: 1088, array_pitch: 384, @@ -1037,10 +1052,91 @@ fn unobserved_padding_lets_an_image_hold_the_bytes_between_rows_alone() { row_bytes: 96, ..padded }; - assert!(holding(&shared, TextureUsage::SHADER_READ, true).is_err()); + assert!(holding(&shared, TextureUsage::SHADER_READ, true, false).is_err()); assert!(!aliases(&shared, 4096, 320, &image, true)); } +/// Over a buffer whose bytes only the device's ordered commands write (`Buffer::gpu_bytes_ordered`), +/// the device's linear image made `PREINITIALIZED` may hold the bytes between a texture's rows and +/// slices where the texture renders nothing (`Between::Kept`), as within declared padding +/// (`linear_plan::within_padding`); a render target's stay refused, as a render pass's load and +/// store write them back, and so do rows that share bytes. A declaration of the padding unobserved +/// takes precedence, and texels with nothing between their rows hold nothing more. +#[test] +fn ordered_writes_let_a_texture_that_renders_nothing_hold_its_rows_padding() { + let padded = BufferLayout { + offset: 256, + row_pitch: 80, + slice_pitch: 320, + row_bytes: 68, + rows: 4, + slices: 1, + }; + for usage in [ + TextureUsage::SHADER_READ, + TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE, + TextureUsage::SHADER_WRITE, + TextureUsage::SHADER_READ | TextureUsage::PIXEL_FORMAT_VIEW, + ] { + assert_eq!( + holding(&padded, usage, false, true), + Ok(Between::Kept), + "{usage:?}" + ); + assert_eq!( + holding(&padded, usage, true, true), + Ok(Between::Unobserved), + "{usage:?}" + ); + } + for usage in [ + TextureUsage::RENDER_TARGET, + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + effective_usage(TextureUsage::UNKNOWN), + ] { + assert!(holding(&padded, usage, false, true).is_err(), "{usage:?}"); + } + let apart = BufferLayout { + slices: 3, + slice_pitch: 384, + ..padded + }; + assert_eq!( + holding(&apart, TextureUsage::SHADER_READ, false, true), + Ok(Between::Kept) + ); + let packed = BufferLayout { + row_bytes: 80, + ..padded + }; + assert_eq!( + holding(&packed, TextureUsage::SHADER_READ, false, true), + Ok(Between::Nothing) + ); + let shared = BufferLayout { + row_bytes: 96, + ..padded + }; + assert!(holding(&shared, TextureUsage::SHADER_READ, false, true).is_err()); + // The image holds the bytes between rows to the last row's pitch, as within declared padding. + let image = LinearImage { + alignment: 16, + size: 320, + offset: 0, + subresource: 320, + row_pitch: 80, + array_pitch: 320, + }; + assert!(aliases(&padded, 4096, 320, &image, Between::Kept.held())); + assert!(!aliases( + &padded, + 4096, + 320, + &image, + Between::Nothing.held() + )); +} + /// 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 @@ -1071,7 +1167,7 @@ fn a_padded_texture_s_shadow_names_what_may_write_its_padding() { TextureUsage::BLOCK_WRITES_ONLY, ] { assert_eq!( - holding(&padded, usage, false), + holding(&padded, usage, false, false), Err(transitions.to_owned()), "{usage:?}" ); @@ -1082,7 +1178,7 @@ fn a_padded_texture_s_shadow_names_what_may_write_its_padding() { effective_usage(TextureUsage::UNKNOWN), ] { assert_eq!( - holding(&padded, usage, false), + holding(&padded, usage, false, false), Err(passes.to_owned()), "{usage:?}" ); diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index d4146f684..1836f0877 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -326,6 +326,8 @@ mod kept_heap_uses; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod kept_images; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod kept_padding; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod kept_shadowed_draws; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod kept_variants; diff --git a/crates/metal2vulkan-runtime/src/tests/texture_placement.rs b/crates/metal2vulkan-runtime/src/tests/texture_placement.rs index cc5d8bc40..38cae93b9 100644 --- a/crates/metal2vulkan-runtime/src/tests/texture_placement.rs +++ b/crates/metal2vulkan-runtime/src/tests/texture_placement.rs @@ -2,6 +2,7 @@ //! takes (`texture/route.rs`) answers its own placement, and every shadow cause its own reason. use crate::in_place::{Access, Padding, PagesClass, Refusal, RowEnds, ShadowCause}; +use crate::linear_plan::Between; use crate::texture::{HostWay, Route}; use crate::{InPlaceAccess, InPlaceRefusal, InPlaceRowEnds, TexturePlacement, TextureShadowReason}; @@ -25,7 +26,10 @@ fn each_route_answers_its_own_placement() { P::Shadow(R::Mipmapped { levels: 6 }) ); assert_eq!(Route::Past.placement(), P::Shadow(R::PastLength)); - assert_eq!(Route::Device { holds: Ok(()) }.placement(), P::NotHostPages); + for between in [Between::Nothing, Between::Unobserved, Between::Kept] { + let holds = Ok(between); + assert_eq!(Route::Device { holds }.placement(), P::NotHostPages); + } assert_eq!( Route::Device { holds: Err("its rows lie apart".to_owned()) diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 255992815..59b669042 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -87,7 +87,9 @@ use super::image_plan::{ }; use super::in_place::{self, PagesClass, Refusal, ShadowCause, Verdict}; use super::key_hash::KeyMap; -use super::linear_plan::{aliases, check_linear_limits, linear_lack, LinearImage, LinearLack}; +use super::linear_plan::{ + aliases, check_linear_limits, linear_lack, Between, LinearImage, LinearLack, +}; use super::memory::{BoundMemory, MemoryClass, Placement, FD_BLOCKS_HANDLE}; use super::nan_clear; use super::neutral::Neutrals; @@ -917,6 +919,9 @@ struct AliasCount { /// Its rows (or slices) lie apart over bytes its buffer declares unobserved /// (`WorkCounts::unobserved_padding_aliases`). unobserved: bool, + /// Its rows (or slices) lie apart over bytes only the device's ordered commands write, which + /// its image, made `PREINITIALIZED`, keeps (`WorkCounts::kept_padding_aliases`). + kept: bool, /// It took the feedback loop usage (`WorkCounts::feedback_loop_alias_images`). feedback: bool, } @@ -930,6 +935,9 @@ impl AliasCount { if self.unobserved { counts.unobserved_padding_alias(); } + if self.kept { + counts.kept_padding_alias(); + } if self.feedback { counts.feedback_loop_alias_image(); } @@ -2932,11 +2940,16 @@ impl Device { /// (`memory.rs`'s `Memory::bound_memory`), with whether it is the `DRM_FORMAT_MOD_LINEAR` one: /// /// - In memory the device allocated with no export: the device's own linear image, made - /// `PREINITIALIZED`, where it holds exactly Metal's texels there (`linear_plan::aliases`) in - /// memory of the buffer's type; else a `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch, made - /// `UNDEFINED`, where the device makes one so and its check passed for its pooled memory - /// ([`Device::pooled_pitched_image`]). The device's check of its pooled memory makes no + /// `PREINITIALIZED`, where it holds exactly Metal's texels there (`linear_plan::aliases`, and + /// the bytes `between` their rows lets it) in memory of the buffer's type; else a + /// `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch, made `UNDEFINED`, where the device makes + /// one so and its check passed for its pooled memory ([`Device::pooled_pitched_image`]), but + /// for rows whose bytes between them only the linear image keeps (`Between::Kept`), which + /// that image's first move may discard. The device's check of its pooled memory makes no /// linear image: it measures the pitched one. + /// - Rows whose bytes between them only the linear image made `PREINITIALIZED` keeps + /// (`Between::Kept`), in memory allocated exportable (either kind below): no image, as one + /// there names the memory's handle type and so starts `UNDEFINED`. /// - In a block exported as an opaque file descriptor or a dma-buf (`exported_memory.rs`): /// the same two images, each made for that handle type, which an image bound there must name /// (`VUID-vkBindImageMemory-memory-02728`), and so made `UNDEFINED` @@ -2965,8 +2978,7 @@ impl Device { fn alias_unbound( &self, plan: &ImagePlan, - texels: &Texels, - usage: TextureUsage, + (texels, between, usage): (&Texels, Between, TextureUsage), facts: &ImageFacts<'_>, ) -> Result, Error> { // The buffer lies in a block of the runtime's buffers allocated exportable. @@ -3005,11 +3017,23 @@ impl Device { ))); } }; + // Bytes between the rows that the device's linear image, made `PREINITIALIZED`, alone + // keeps (`linear_plan::holding`): an image in memory allocated exportable names its handle + // type, and so starts `UNDEFINED`. + let kept = between == Between::Kept; + if kept && (blocks || memory != ModifierMemory::Own) { + let why = "its rows lie with bytes between them that only the device's linear image \ + made PREINITIALIZED keeps, and an image in memory allocated exportable \ + names its handle type and starts UNDEFINED" + .to_owned(); + let cause = ShadowCause::Refused(Refusal::Image, why.clone()); + return Ok(Err((why, cause))); + } let (_, buffer_offset, type_index) = texels.buffer.memory(); let memory_offset = buffer_offset + texels.layout.offset; let raw_device = self.shared().vk(); let room = texels.buffer.padded_length() - texels.layout.offset; - let unobserved = texels.buffer.padding_unobserved(); + let held = between.held(); // Why an image the device made does not hold exactly Metal's texels in the buffer's // memory: `None` where it does (`aliases`) and takes memory of the buffer's type. let elsewhere = |made: &LinearMade| { @@ -3021,7 +3045,7 @@ impl Device { row_pitch: made.report.row_pitch, array_pitch: made.report.array_pitch, }; - let lies = aliases(&texels.layout, memory_offset, room, &image, unobserved); + let lies = aliases(&texels.layout, memory_offset, room, &image, held); let typed = made.requirements.memory_type_bits & (1 << type_index) != 0; (!lies || !typed).then(|| { format!( @@ -3065,6 +3089,13 @@ impl Device { Err(why) => format!("the device makes no linear image of the texture: {why}"), }; let pitched = match (memory, blocks) { + // Its first move, out of `UNDEFINED`, may discard the bytes between the rows. + _ if kept => Err(ShadowCause::Refused( + Refusal::Pitch, + "its rows lie with bytes between them that a DRM_FORMAT_MOD_LINEAR image at \ + Metal's pitch, made UNDEFINED, may discard at its first move" + .to_owned(), + )), (_, true) => Err(ShadowCause::Refused( Refusal::Pitch, "a block of the runtime's buffers allocated exportable takes no \ @@ -3119,16 +3150,17 @@ impl Device { } /// Whether [`alias_image`](Self::alias_image) makes an image over `texels` (of a texture of - /// Metal `usage` and `plan`), by its steps up to the bind ([`Device::alias_unbound`]), the - /// image released unbound; else the cause of the shadow the texture is. + /// Metal `usage` and `plan`, holding `between` besides them), by its steps up to the bind + /// ([`Device::alias_unbound`]), the image released unbound; else the cause of the shadow the + /// texture is. pub(crate) fn alias_image_made( &self, plan: &ImagePlan, - texels: &Texels, - usage: TextureUsage, + (texels, between, usage): (&Texels, Between, TextureUsage), facts: &ImageFacts<'_>, ) -> Result, Error> { - Ok(match self.alias_unbound(plan, texels, usage, facts)? { + let made = self.alias_unbound(plan, (texels, between, usage), facts)?; + Ok(match made { Ok((made, _)) => { // SAFETY: the image is live and unbound, and no command uses it. unsafe { release::object(self.shared().vk(), made.raw) }; @@ -3356,16 +3388,18 @@ impl Device { /// an image bound to it would have to be made for (a texture over the caller's host pages /// takes the image in place or a shadow: `storage_over_buffer`, `in_place.rs`). 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. Over a buffer that declares the bytes - /// between rows and slices unobserved (`BufferDescriptor::padding_unobserved`), the image may - /// hold those bytes too (`linear_plan::within_padding`). With what it counts as the texture's - /// ([`AliasCount`]: a `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch, rows or slices that lie - /// apart over unobserved bytes, the feedback loop usage), which the caller counts. + /// hold the texels (`linear_plan::holding`), and what besides, or why not. Over a buffer that + /// declares the bytes between rows and slices unobserved (`BufferDescriptor::padding_unobserved`), + /// and over one whose bytes only the device's ordered commands write for a texture that renders + /// nothing (its linear image alone, made `PREINITIALIZED`), the image may hold those bytes too + /// (`linear_plan::within_padding`). With what it counts as the texture's ([`AliasCount`]: a + /// `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch, rows or slices that lie apart over + /// unobserved or kept bytes, the feedback loop usage), which the caller counts. fn alias_image( &self, plan: ImagePlan, descriptor: &TextureDescriptor, - (texels, holds, usage): (&Texels, &Result<(), String>, TextureUsage), + (texels, holds, usage): (&Texels, &Result, TextureUsage), facts: &ImageFacts<'_>, ) -> Result { match texels.buffer.caller_memory() { @@ -3382,13 +3416,15 @@ impl Device { ))) } } - if let Err(why) = holds { - return Ok(Err((why.clone(), None))); - } + let between = match holds { + Ok(between) => *between, + Err(why) => return Ok(Err((why.clone(), None))), + }; let (memory, buffer_offset, _) = texels.buffer.memory(); let memory_offset = buffer_offset + texels.layout.offset; let raw_device = self.shared().vk(); - let (made, pitched) = match self.alias_unbound(&plan, texels, usage, facts)? { + let over = (texels, between, usage); + let (made, pitched) = match self.alias_unbound(&plan, over, facts)? { Ok(made) => made, Err((linear, cause)) => { let last = @@ -3455,6 +3491,7 @@ impl Device { let count = AliasCount { pitched, unobserved: texels.buffer.padding_unobserved() && texels.layout.padded(), + kept: between == Between::Kept, feedback: (image.plan().usage).contains(ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT), }; Ok(Ok((image.shared(), count))) @@ -3516,6 +3553,7 @@ impl Device { let count = AliasCount { pitched: false, unobserved: texels.buffer.padding_unobserved() && texels.layout.padded(), + kept: false, feedback: (image.plan().usage).contains(ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT), }; (image.shared(), count) @@ -3551,7 +3589,7 @@ impl Device { &self, plan: &ImagePlan, (descriptor, layout): (&TextureDescriptor, &TextureLayout), - (texels, holds, usage): (&Texels, &Result<(), String>, TextureUsage), + (texels, holds, usage): (&Texels, &Result, TextureUsage), facts: &ImageFacts<'_>, ) -> Result { let wider = undeclared_usage(plan.clone(), layout, usage, facts, |_, w| Ok(w))?; @@ -3585,7 +3623,8 @@ impl Device { return Ok(None); }; let unobserved = texels.buffer.padding_unobserved(); - let holds = crate::linear_plan::holding(&texels.layout, pending.usage, unobserved); + let ordered = texels.buffer.gpu_bytes_ordered(); + let holds = crate::linear_plan::holding(&texels.layout, pending.usage, unobserved, ordered); let over = (texels, &holds, pending.usage); let made = self.alias_over_device(&pending.plan, (descriptor, &layout), over, facts)?; Ok(made.ok()) diff --git a/crates/metal2vulkan-runtime/src/texture/route.rs b/crates/metal2vulkan-runtime/src/texture/route.rs index 26625b359..977e5c0c5 100644 --- a/crates/metal2vulkan-runtime/src/texture/route.rs +++ b/crates/metal2vulkan-runtime/src/texture/route.rs @@ -14,7 +14,7 @@ use crate::buffer::CallerMemory; use crate::buffer_texture::Texels; use crate::image_plan::{plan_image, ImageFacts, ImagePlan}; use crate::in_place::{self, Access, Padding, PagesClass, Refusal, RowEnds, ShadowCause, Verdict}; -use crate::linear_plan::holding; +use crate::linear_plan::{holding, Between}; use crate::texture_descriptor::{texture_usage, TextureDescriptor, TextureLayout}; use crate::texture_placement::TexturePlacement; use crate::{Device, Error}; @@ -31,11 +31,12 @@ pub(crate) enum Route { /// the shadow, its tail holding them. Past, /// The buffer's bytes are no host pages: an image aliasing the buffer's memory where `holds` - /// (an image over the texels may hold them, `linear_plan::holding`: their rows lie one after - /// another, or the buffer declares the bytes between them unobserved, - /// `BufferDescriptor::padding_unobserved`) and the device makes one on Metal's layout, else + /// (an image over the texels may hold them, and what besides, `linear_plan::holding`: their + /// rows lie one after another, the buffer declares the bytes between them unobserved, + /// `BufferDescriptor::padding_unobserved`, or only the device's ordered commands write those + /// bytes, of a texture that renders nothing) and the device makes one on Metal's layout, else /// the shadow; `holds` says why not where it does not. - Device { holds: Result<(), String> }, + Device { holds: Result }, /// Over host pages of `class`, its texels lying in the device's lines as `rows` says, and /// `padding` saying whether a shader's writes may change their rows' padding. Host { @@ -116,11 +117,12 @@ impl Device { // Over the device's own memory, whether the making's image aliases the bytes: the // device's linear image, or one at Metal's pitch where its check passed for its pooled // memory (`Device::alias_image_made`); else the cause of the shadow it is. - Route::Device { holds: Ok(()) } if texels.buffer.caller_memory().is_none() => { - if let Err(cause) = self.alias_image_made(&plan, texels, usage, &facts)? { + Route::Device { holds: Ok(between) } if texels.buffer.caller_memory().is_none() => { + let over = (texels, between, usage); + if let Err(cause) = self.alias_image_made(&plan, over, &facts)? { return Ok(cause.placement()); } - Route::Device { holds: Ok(()) } + Route::Device { holds: Ok(between) } } route => route, }; @@ -176,9 +178,11 @@ impl Device { _ => { // Whether an image may hold the texels: none where their rows (or slices) lie // with the buffer's bytes between them, unless the buffer declares those bytes - // unobserved (`linear_plan::holding`), and else why. + // unobserved, or only the device's ordered commands write them and the texture + // renders nothing (`linear_plan::holding`), and else why. let unobserved = texels.buffer.padding_unobserved(); - let holds = holding(&texels.layout, usage, unobserved); + let ordered = texels.buffer.gpu_bytes_ordered(); + let holds = holding(&texels.layout, usage, unobserved, ordered); return Route::Device { holds }; } }; diff --git a/crates/metal2vulkan-runtime/src/texture_placement.rs b/crates/metal2vulkan-runtime/src/texture_placement.rs index 169e652ac..cf5742283 100644 --- a/crates/metal2vulkan-runtime/src/texture_placement.rs +++ b/crates/metal2vulkan-runtime/src/texture_placement.rs @@ -124,7 +124,10 @@ pub enum TextureShadowReason { /// and a render pass's load and store write the bytes it holds; the buffer does not declare /// the bytes between rows unobserved /// ([`BufferDescriptor::padding_unobserved`](crate::BufferDescriptor::padding_unobserved), - /// which no rows that share bytes take). + /// which no rows that share bytes take), and the texture renders, or other writers than the + /// device's ordered commands may write the bytes (a buffer of `Shared` storage, a `Managed` + /// one on unified memory, one whose `VkBuffer` was handed out or whose memory is exportable), + /// where its linear image, made `PREINITIALIZED`, would keep them. BytesBetweenRows, /// On a discrete GPU, a `Managed` texture over a no-copy buffer's bytes (not an IOSurface /// plane's) that only samples or reads, over memory that carries a log of its writes, tracked, @@ -356,7 +359,7 @@ impl Route { return TexturePlacement::Shadow(TextureShadowReason::Mipmapped { levels }); } Route::Past => return TexturePlacement::Shadow(TextureShadowReason::PastLength), - Route::Device { holds: Ok(()) } => return TexturePlacement::NotHostPages, + Route::Device { holds: Ok(_) } => return TexturePlacement::NotHostPages, Route::Device { holds: Err(_) } => { return TexturePlacement::Shadow(TextureShadowReason::BytesBetweenRows) } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 48e399f0c..2a6dcc5e0 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -452,6 +452,10 @@ pub(crate) struct Counters { managed_device_copies_in_place: AtomicU64, managed_bytes_copied_in: AtomicU64, managed_bytes_copied_out: AtomicU64, + managed_ranges_modified: AtomicU64, + managed_bytes_modified: AtomicU64, + managed_resources_synchronized: AtomicU64, + managed_bytes_synchronized: AtomicU64, managed_staging_bytes: AtomicU64, managed_writes_undone: AtomicU64, dma_buf_textures_in_place: AtomicU64, @@ -568,6 +572,7 @@ pub(crate) struct Counters { stand_ins_after_pins: AtomicU64, feedback_loop_alias_images: AtomicU64, unobserved_padding_aliases: AtomicU64, + kept_padding_aliases: AtomicU64, pooled_pitched_images: AtomicU64, pooled_textures_moved_in_place: AtomicU64, pooled_texture_shadows_freed_after_move: AtomicU64, @@ -3861,6 +3866,20 @@ impl Counters { }; } + /// The program asked a two-copy buffer (`managed_copy.rs`) to copy a range of `bytes` bytes: + /// in, by `did_modify_range` (`modified`), or out, by `synchronize_resource`. + pub(crate) fn managed_asked(&self, bytes: u64, modified: bool) { + let (calls, asked) = match modified { + true => (&self.managed_ranges_modified, &self.managed_bytes_modified), + false => ( + &self.managed_resources_synchronized, + &self.managed_bytes_synchronized, + ), + }; + calls.fetch_add(1, Ordering::Relaxed); + asked.fetch_add(bytes, Ordering::Relaxed); + } + /// A staging buffer of `bytes` bytes of a two-copy buffer's copies was made (`made`), or /// went (`managed_copy.rs`). pub(crate) fn managed_staging(&self, bytes: u64, made: bool) { @@ -4431,6 +4450,13 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// The device made its linear image, `PREINITIALIZED`, aliasing a buffer's bytes that holds + /// the bytes between the texture's rows or slices, which only the device's ordered commands + /// write (`linear_plan::Between::Kept`, `Device::storage_over_buffer`). + pub(crate) fn kept_padding_alias(&self) { + self.kept_padding_aliases.fetch_add(1, Ordering::Relaxed); + } + /// The device made a `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch aliasing a buffer's bytes /// in its pooled memory, where its own linear image lays them out otherwise /// (`Device::pooled_pitched_image`). @@ -7734,6 +7760,17 @@ pub struct WorkCounts { /// (counted at the command for an import of the pages, at the command buffer's completion for /// pages no import maps). pub managed_bytes_copied_out: u64, + /// The program's `did_modify_range` calls of a nonempty range on such buffers: each copies + /// its range in (`managed_bytes_copied_in` counts the bytes copied). + pub managed_ranges_modified: u64, + /// The bytes of those ranges. + pub managed_bytes_modified: u64, + /// The program's `synchronize_resource` commands of such a buffer, or of a texture over one, + /// of a nonempty range: the buffer's length, or the texture's span in it, which each copies + /// out (`managed_bytes_copied_out` counts the bytes copied). + pub managed_resources_synchronized: u64, + /// The bytes those commands asked. + pub managed_bytes_synchronized: u64, /// The bytes of the staging buffers of their copies held now: those of copies into or out of /// pages no import maps, each held until the submission or command buffer that uses it /// completed. @@ -8414,6 +8451,14 @@ pub struct WorkCounts { /// declaration the texture is a shadow (`shadowed_textures`). One per image made. A runtime /// extension: Metal has none. pub unobserved_padding_aliases: u64, + /// Linear images aliasing a buffer of the device's own memory, of textures that render + /// nothing, whose rows or slices lie with bytes between them that only the device's ordered + /// commands write (a `Private` buffer, a `Managed` buffer's own on a device without unified + /// memory): each image, made `PREINITIALIZED`, holds those bytes, which its one layout + /// transition preserves (Vulkan's Image Layout Transitions) and which the buffer and the image + /// read alike (Memory Aliasing), where a buffer other writers reach makes the texture a shadow + /// (`shadowed_textures`). One per image made. + pub kept_padding_aliases: u64, /// Images aliasing a buffer of the device's own memory that are `DRM_FORMAT_MOD_LINEAR` images /// at Metal's row pitch (`VK_EXT_image_drm_format_modifier`), made where the device's own /// linear image of the texture lays its rows out otherwise and the device's check of such @@ -9568,6 +9613,11 @@ impl Device { .load(Ordering::Relaxed), managed_bytes_copied_in: counters.managed_bytes_copied_in.load(Ordering::Relaxed), managed_bytes_copied_out: counters.managed_bytes_copied_out.load(Ordering::Relaxed), + managed_ranges_modified: counters.managed_ranges_modified.load(Ordering::Relaxed), + managed_bytes_modified: counters.managed_bytes_modified.load(Ordering::Relaxed), + managed_resources_synchronized: (counters.managed_resources_synchronized) + .load(Ordering::Relaxed), + managed_bytes_synchronized: counters.managed_bytes_synchronized.load(Ordering::Relaxed), managed_staging_bytes: counters.managed_staging_bytes.load(Ordering::Relaxed), managed_writes_undone: counters.managed_writes_undone.load(Ordering::Relaxed), dma_buf_textures_in_place: counters.dma_buf_textures_in_place.load(Ordering::Relaxed), @@ -9663,6 +9713,7 @@ impl Device { stand_ins_after_pins: counters.stand_ins_after_pins.load(Ordering::Relaxed), feedback_loop_alias_images: counters.feedback_loop_alias_images.load(Ordering::Relaxed), unobserved_padding_aliases: counters.unobserved_padding_aliases.load(Ordering::Relaxed), + kept_padding_aliases: counters.kept_padding_aliases.load(Ordering::Relaxed), pooled_pitched_images: counters.pooled_pitched_images.load(Ordering::Relaxed), pooled_textures_moved_in_place: (counters.pooled_textures_moved_in_place) .load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index bb197366b..cdbd0fe52 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3028,6 +3028,7 @@ field metal2vulkan-runtime::WorkCounts.kept_draws_carried pub kept_draws_carried field metal2vulkan-runtime::WorkCounts.kept_draws_carry_dropped_between pub kept_draws_carry_dropped_between: u64 field metal2vulkan-runtime::WorkCounts.kept_draws_carry_dropped_layout pub kept_draws_carry_dropped_layout: u64 field metal2vulkan-runtime::WorkCounts.kept_draws_carry_dropped_under pub kept_draws_carry_dropped_under: u64 +field metal2vulkan-runtime::WorkCounts.kept_padding_aliases pub kept_padding_aliases: u64 field metal2vulkan-runtime::WorkCounts.kept_resident_keys_compared pub kept_resident_keys_compared: u64 field metal2vulkan-runtime::WorkCounts.kept_texels_passes pub kept_texels_passes: u64 field metal2vulkan-runtime::WorkCounts.late_reservation_withheld pub late_reservation_withheld: u64 @@ -3047,10 +3048,14 @@ field metal2vulkan-runtime::WorkCounts.live_tables_uploaded pub live_tables_uplo field metal2vulkan-runtime::WorkCounts.long_queue_settles pub long_queue_settles: u64 field metal2vulkan-runtime::WorkCounts.managed_bytes_copied_in pub managed_bytes_copied_in: u64 field metal2vulkan-runtime::WorkCounts.managed_bytes_copied_out pub managed_bytes_copied_out: u64 +field metal2vulkan-runtime::WorkCounts.managed_bytes_modified pub managed_bytes_modified: u64 +field metal2vulkan-runtime::WorkCounts.managed_bytes_synchronized pub managed_bytes_synchronized: u64 field metal2vulkan-runtime::WorkCounts.managed_device_copies pub managed_device_copies: u64 field metal2vulkan-runtime::WorkCounts.managed_device_copies_in_place pub managed_device_copies_in_place: u64 field metal2vulkan-runtime::WorkCounts.managed_device_copies_made pub managed_device_copies_made: u64 field metal2vulkan-runtime::WorkCounts.managed_device_copy_bytes pub managed_device_copy_bytes: u64 +field metal2vulkan-runtime::WorkCounts.managed_ranges_modified pub managed_ranges_modified: u64 +field metal2vulkan-runtime::WorkCounts.managed_resources_synchronized pub managed_resources_synchronized: u64 field metal2vulkan-runtime::WorkCounts.managed_staging_bytes pub managed_staging_bytes: u64 field metal2vulkan-runtime::WorkCounts.managed_writes_undone pub managed_writes_undone: u64 field metal2vulkan-runtime::WorkCounts.memory_allocations_refused_at_limit pub memory_allocations_refused_at_limit: u64 diff --git a/docs/API.md b/docs/API.md index 435b70092..7dcb49bfa 100644 --- a/docs/API.md +++ b/docs/API.md @@ -459,7 +459,8 @@ then (`TexturePlacement`): in place; `Pending`, a shadow made before its verdict where the verdict passes; a shadow and why (`TextureShadowReason`: the policy, the texel width, the check's failed or unchecked verdict with its access and row ends, a refusal, a tiled texture's levels, texels past the buffer's length, a device copy, and over the device's own memory rows with -bytes between them the buffer does not declare unobserved, `BytesBetweenRows`); no host pages (an +bytes between them the buffer does not declare unobserved, of a texture that renders or of a +buffer other writers than the device's ordered commands reach, `BytesBetweenRows`); no host pages (an image aliasing the buffer's memory: the device's linear image where it lays one out as Metal does, else a `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch where the device's check passed for its pooled memory; a texture over that memory that takes neither answers its shadow's cause); or a shape no @@ -1885,7 +1886,20 @@ bound. operations read and write back any byte of an attachment's image subresource, and Metal leaves them as the program writes them, unless the buffer, of the runtime's own memory, declares them unobserved (`BufferDescriptor::padding_unobserved`, a runtime extension: they may then change, - and no other byte does); or no linear image of the device lays its texels out as Metal + and no other byte does), or only the device's commands, in the runtime's order, write the + buffer's bytes (a `Private` buffer, and a `Managed` buffer's own on a device without unified + memory, whose host copy the program's `didModifyRange:` copies in; not one whose `VkBuffer` was + handed out or whose memory is exportable) and the texture renders nothing: then the device's + linear image, made `PREINITIALIZED`, holds them where its rows lie at the buffer's pitch + (`WorkCounts::kept_padding_aliases`). Its one layout transition is out of the layout it is in, + of which Vulkan says "If the old layout matches the current layout of the image subresource + range, the transition preserves the contents of that range" (7.1.1, Image Layout Transitions), + ordered with every write of those bytes; in `GENERAL` the buffer and the image are both + host-accessible subresources, which "interpret the contents of the memory in consistent ways, + and data written to one alias can be read by the other alias" (12.11, Memory Aliasing). A + kernel's writes of such a texture may change those bytes as on the x86 Macs (section 10, + **Kernels**); no `DRM_FORMAT_MOD_LINEAR` image and no image over exportable memory holds them, + as each is made `UNDEFINED`, whose first move may discard 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 (among them a texture whose offset in the buffer misses the device's linear-image alignment, as one 32 bytes in does on RADV, whose images start on a multiple of 256: a buffer made with `BufferDescriptor::aligned_byte` at that diff --git a/docs/HOWTO.md b/docs/HOWTO.md index efdfe362c..1ced7b4c5 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -399,7 +399,12 @@ texels to its pitch (the last row's included) and nothing past the last row's pi and the bytes between slices may change whenever the texture is made or used, and no other byte does (`WorkCounts::unobserved_padding_aliases` counts such images; `Buffer::texture_placement` answers `NotHostPages` for such a texture, else the shadow's cause, and -`Shadow(TextureShadowReason::BytesBetweenRows)` without the declaration). +`Shadow(TextureShadowReason::BytesBetweenRows)` without the declaration). Without it, a texture +that renders nothing over a buffer whose bytes only the device's ordered commands write (a +`Private` buffer, a `Managed` one's own on a device without unified memory) is the device's linear +image at the pitch too, where the device lays one out so, made `PREINITIALIZED`, whose one layout +transition keeps the bytes between its rows (`WorkCounts::kept_padding_aliases`; docs/API.md, +`shadowed-texture`). Such an image is bound at the buffer's memory offset plus the texture's offset, which must be a multiple of the device's linear-image alignment (`Device::minimum_linear_texture_alignment_for_pixel_format`