diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index 984caeaf5..89871d230 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -41,6 +41,7 @@ use super::linear_plan::{ LINEAR_ALIGNMENT, }; use super::resource::{Identity, ResourceKey}; +use super::resource_ids::IdPlacement; use super::rotated::{self, Frame, RotatedCopies}; use super::shadow::{ Backing, ShadowBuffer, ShadowCopies, ShadowSource, ShadowStaging, ShadowTarget, @@ -269,6 +270,25 @@ fn refusal_error(call: &'static str, refusal: BufferRefusal) -> Error { } } +/// Whose a texture over a buffer is, for its resource ID (`resource_ids.rs`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Whose { + /// The program's: its descriptor's placement gives its ID. + Program, + /// The runtime's own (`Buffer::new_runtime_texture`): no ID. + Runtime, +} + +impl Whose { + /// How a texture of a descriptor at `placement` takes its ID. + fn id_use(self, placement: IdPlacement) -> IdUse { + match self { + Whose::Program => IdUse::Program(placement), + Whose::Runtime => IdUse::Runtime, + } + } +} + impl Buffer { /// `newTextureWithDescriptor:offset:bytesPerRow:`: a texture of `descriptor` whose texels /// are the buffer's bytes from `offset`, rows `bytes_per_row` apart: a 2D texture or a @@ -304,7 +324,28 @@ impl Buffer { descriptor, offset, bytes_per_row, - BufferTextureCall::Texture, + (BufferTextureCall::Texture, Whose::Program), + None, + ) + } + + /// [`new_texture`](Self::new_texture) of a texture of the runtime's own, which no program + /// made: it takes no resource ID (`IdUse::Runtime`, `resource_ids.rs`), whatever the + /// descriptor's placement, so it moves no ID the program's textures take, on whichever thread + /// it is made. The device's check of textures in place makes its textures here + /// (`in_place_check.rs`). + pub(crate) fn new_runtime_texture( + &self, + descriptor: &TextureDescriptor, + offset: u64, + bytes_per_row: u64, + ) -> Result { + self.texture_over( + "new_texture", + descriptor, + offset, + bytes_per_row, + (BufferTextureCall::Texture, Whose::Runtime), None, ) } @@ -330,7 +371,7 @@ impl Buffer { descriptor, offset, bytes_per_row, - BufferTextureCall::Linear, + (BufferTextureCall::Linear, Whose::Program), None, ) } @@ -445,9 +486,12 @@ impl Buffer { descriptor, plane.offset, plane.bytes_per_row, - BufferTextureCall::IoSurfacePlane { - planar: plane.planar, - }, + ( + BufferTextureCall::IoSurfacePlane { + planar: plane.planar, + }, + Whose::Program, + ), plane.ycbcr, )?; // Metal's device takes a sampler ID as it makes a surface's texture, as for a texture of @@ -457,21 +501,22 @@ impl Buffer { } /// The texture of `descriptor` over the buffer that `call` (made through `form`) makes, over - /// a surface of `surface`'s YCbCr facts where given. Over a heap's buffer it is among the - /// heap's textures while it lives: `useHeap:` makes every resource the heap holds resident, so - /// an encoder that used the heap makes it resident (`residency.rs`), and a shadow's texels are - /// copied in for its commands. + /// a surface of `surface`'s YCbCr facts where given, `whose` it is. Over a heap's buffer it is + /// among the heap's textures while it lives: `useHeap:` makes every resource the heap holds + /// resident, so an encoder that used the heap makes it resident (`residency.rs`), and a + /// shadow's texels are copied in for its commands. fn texture_over( &self, call: &'static str, descriptor: &TextureDescriptor, offset: u64, bytes_per_row: u64, - form: BufferTextureCall, + (form, whose): (BufferTextureCall, Whose), ycbcr_surface: Option, ) -> Result { let over = (offset, bytes_per_row); - let texture = self.make_texture_over(call, descriptor, over, form, ycbcr_surface)?; + let texture = + self.make_texture_over(call, descriptor, over, (form, whose), ycbcr_surface)?; if let Some(heap) = self.heap() { heap.hold_texture(&texture); } @@ -484,7 +529,7 @@ impl Buffer { call: &'static str, descriptor: &TextureDescriptor, (offset, bytes_per_row): (u64, u64), - form: BufferTextureCall, + (form, whose): (BufferTextureCall, Whose), ycbcr_surface: Option, ) -> Result { // A detach waits for none being made over the bytes (`detach.rs`), nor does a rebind of @@ -522,6 +567,7 @@ impl Buffer { resource_options: options, ..asked }; + let id_use = whose.id_use(descriptor.placement); // A texture buffer of more than one level is stopped by `linear_plan`, as Metal's // buffer creator stops it, not refused as the device's gap. let rules = self.device().properties().texture_rules(); @@ -673,7 +719,6 @@ impl Buffer { descriptor, ); let stored = Texels::placed(self.clone(), stored, texel_bytes, descriptor); - let id_use = IdUse::Program(descriptor.placement); return self.device().new_rotated_texture( call, [rows, stored].map(|texels| texels.with_options(options).over_surface(surface)), @@ -691,7 +736,6 @@ impl Buffer { let texels = Texels::placed(self.clone(), placed, texel_bytes, descriptor) .with_options(options) .over_surface(surface); - let id_use = IdUse::Program(descriptor.placement); return self .device() .new_surface_planes_texture(call, texels, descriptor, &layout, id_use, alpha); @@ -700,7 +744,6 @@ impl Buffer { let texels = Texels::placed(self.clone(), placed, texel_bytes, descriptor) .with_options(options) .over_surface(surface); - let id_use = IdUse::Program(descriptor.placement); return self.device().new_converted_texture( call, texels, @@ -712,12 +755,11 @@ impl Buffer { } if layout.texture_type == TextureType::TextureBuffer { let texels = Texels::texture_buffer(self.clone(), placed.gpu, texel_bytes, descriptor)?; - Ok(texels.texture(descriptor, &layout, IdUse::Program(descriptor.placement))) + Ok(texels.texture(descriptor, &layout, id_use)) } else { let texels = Texels::placed(self.clone(), placed, texel_bytes, descriptor) .with_options(options) .over_surface(surface); - let id_use = IdUse::Program(descriptor.placement); let texture = self .device() .new_texture_over_buffer(call, texels, descriptor, &layout, id_use)?; diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index 3253d3ed1..f1208a085 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -6,7 +6,7 @@ //! buffer over anonymous pages it maps, imported by their pointer; a buffer of the runtime's own //! longer than half a pooled block, in fresh pages; a no-copy buffer over pages the device //! refuses by their pointer, imported as dma-bufs), fills a window of it with a pattern, and -//! makes a texture over it through `Buffer::new_texture`, as the program does: the texture takes +//! makes a texture over it as the program does (`Buffer::new_runtime_texture`): the texture takes //! the image in place exactly as the product's would ([`checking`](crate::in_place::checking) //! lets it whatever the verdict). A thread of its own then writes the pattern's complement into //! the window, each byte once, at a stride that reaches texels, the bytes between rows and the @@ -20,6 +20,11 @@ //! the program makes its resources, so a range of the space it took would refuse a pin of the //! program's there, or move a range the runtime picks for it. Its pages, their import, the //! image and the move do not depend on the address, so neither does a verdict. +//! - **Its textures take no resource ID** (`IdUse::Runtime`, `resource_ids.rs`): the check runs +//! on its thread while the program makes its textures, so a plain ID one of its textures held +//! would move the program's next texture's ID past Metal's, and a texture reservation after it +//! would be ignored. The ID does not touch the image, its pages or its move, so neither does a +//! verdict. //! - **Its cost** is the pattern's fill and compare of each window, at the speed of a copy and a //! comparison of memory (a 3840x2160 surface's 33 MB among them), and each image's making and //! first move: the writes themselves run only while the move does. @@ -246,9 +251,11 @@ fn check_round(pages: &ClassPages, shape: Shape, round: usize, page: u64) -> Rou let mut descriptor = TextureDescriptor::texture_2d(shape.format, shape.width, shape.height, false); descriptor.usage = TextureUsage::SHADER_READ; + // The runtime's own texture: it takes no resource ID, so the program's IDs are Metal's + // whether or when the check runs. let Ok(texture) = pages .buffer - .new_texture(&descriptor, 0, shape.bytes_per_row) + .new_runtime_texture(&descriptor, 0, shape.bytes_per_row) else { return Round::NotMade; }; diff --git a/crates/metal2vulkan-runtime/src/resource_ids.rs b/crates/metal2vulkan-runtime/src/resource_ids.rs index 5f98060b7..7f6dc48dc 100644 --- a/crates/metal2vulkan-runtime/src/resource_ids.rs +++ b/crates/metal2vulkan-runtime/src/resource_ids.rs @@ -16,8 +16,8 @@ //! address space hands out with their records (`address.rs`), from a [`Pool`] as the others'. //! Every sampler state has an ID, with or without argument-buffer support, as on Metal (probes 5 //! and 7), and a texture view has one of its own, as each `MTLTexture` does. The runtime's own -//! textures (scratch and checks no program sees) take none: they answer 0. A function table's ID -//! is always plain. +//! textures (scratch and checks no program sees, the in-place check's on its thread among them) +//! take none: they answer 0. A function table's ID is always plain. //! - **Numbering is Metal's** (the coordinator's ruling of 2026-10-07: a program that writes an ID //! into memory and reads it back sees the number, and the consumer measured Metal's, so Metal's //! numbers are the contract, where only "plain allocation skips reserved IDs" was kept before). diff --git a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs index f3c18e18e..c76e6a87e 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs @@ -1,7 +1,8 @@ //! The device's check of the first move in place (`in_place_check.rs`) takes no range of the Metal //! address space: its buffers, one per class of pages, lie outside it (`address.rs`, "Outside the //! space"), so no pin or pick of the program's depends on whether or when the check runs, and the -//! space's state changes no verdict. +//! space's state changes no verdict. Nor does it take a texture ID: its textures are the +//! runtime's own (`resource_ids.rs`), so the program's IDs are Metal's whether or when it runs. //! //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. Each device's shader cache is a fresh @@ -11,8 +12,9 @@ use super::blit_holds::{device, Scratch}; use crate::address::{PAGE, SPACE_BASE, SPACE_END}; use crate::{ AddressPlacement, Buffer, BufferContents, BufferDescriptor, Device, Error, GpuAddress, - ResourceOptions, + ResourceId, ResourceIdKind, ResourceOptions, Texture, TextureDescriptor, }; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; use std::time::{Duration, Instant}; /// The longest a check may take. @@ -96,3 +98,90 @@ fn the_in_place_check_takes_no_range_of_the_metal_space() { assert_eq!(answered, reference, "the verdicts with the space held"); drop((held, pool)); } + +/// A private 4x4 `RGBA8Unorm` texture of the program's, at a plain ID. +fn texture(device: &Device) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 4, 4, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + device.new_texture(&descriptor).unwrap() +} + +/// Whether the device's check made a texture: a class it checked, passed or failed. +fn checked_a_texture(device: &Device) -> bool { + let counts = device.work_counts(); + counts.in_place_checks_passed + counts.in_place_checks_failed > 0 +} + +/// The device's check takes no texture ID: its textures are the runtime's own, which answer 0 +/// and count in no plain allocation (`resource_ids.rs`). A check run to its end before the +/// program's first texture leaves the program's reservation of texture ID 5 taken, so its +/// textures take 1 to 4, then 6, as Metal's do. A check texture that took a plain ID would have +/// started the pool, and the reservation would be ignored (Metal's pool logs "reserve() must be +/// called before any allocation takes place"): 5 would follow 4. +#[test] +fn the_in_place_check_takes_no_texture_id() { + let scratch = Scratch::new("in-place-check-ids"); + let device = device(&scratch.0); + assert!(device.settle_in_place_checks(WAIT), "the check answered"); + if !checked_a_texture(&device) { + eprintln!( + "IN-PLACE-CHECK-IDS on {}: the check made no texture ({:?})", + device.name(), + device.in_place_check_report() + ); + return; + } + device + .reserve_resource_ids(ResourceIdKind::Texture, &[ResourceId(5)]) + .unwrap(); + let made: Vec = (0..5).map(|_| texture(&device)).collect(); + let ids: Vec = made.iter().map(|t| t.gpu_resource_id().0).collect(); + assert_eq!( + ids, + [1, 2, 3, 4, 6], + "after the check, on {}", + device.name() + ); +} + +/// The program's textures keep Metal's IDs while the device's check runs on its thread: a +/// texture made and released over and over takes ID 1 each time, as on a device that makes no +/// other texture. A check texture holding a plain ID while the program made one would move the +/// program's to 2, which is how a consumer's sequence of IDs came out one past Metal's under +/// load (the check started at its texture over a surface's pages, and its first texture took the +/// next ID). +#[test] +fn texture_ids_keep_metals_order_while_the_in_place_check_runs() { + let scratch = Scratch::new("in-place-check-ids-during"); + let device = device(&scratch.0); + let started = Instant::now(); + let mut made = 0; + let mut ids = std::collections::BTreeMap::::new(); + while !device.settle_in_place_checks(Duration::ZERO) { + assert!(started.elapsed() < WAIT, "the check answered"); + let t = texture(&device); + *ids.entry(t.gpu_resource_id().0).or_default() += 1; + drop(t); + made += 1; + } + if !checked_a_texture(&device) { + eprintln!( + "IN-PLACE-CHECK-IDS-DURING on {}: the check made no texture ({:?})", + device.name(), + device.in_place_check_report() + ); + return; + } + eprintln!( + "IN-PLACE-CHECK-IDS-DURING on {}: {made} textures made while the check ran, by ID: \ + {ids:?}", + device.name() + ); + assert!(made > 0, "no texture was made while the check ran"); + assert_eq!( + ids.keys().copied().collect::>(), + [1], + "the IDs of the textures made while the check ran" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/internal_texture_ids.rs b/crates/metal2vulkan-runtime/src/tests/internal_texture_ids.rs new file mode 100644 index 000000000..4e8a278d3 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/internal_texture_ids.rs @@ -0,0 +1,96 @@ +//! The runtime's own textures take no texture ID (`resource_ids.rs`): a pass of separate depth +//! and stencil textures renders through a combined scratch image (`depth_stencil_scratch.rs`), +//! and a memoryless attachment through a backing the runtime keeps (`attachment_stand_in.rs`), +//! each a texture of the runtime's, made as the program encodes. The program's textures made +//! before, between and after them take Metal's IDs: 1 on, in the order the program made them. +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. + +use super::blit_holds::{device, Scratch, WAIT}; +use crate::{ + ClearColor, CpuCacheMode, Device, HazardTrackingMode, LoadAction, RenderPassDescriptor, + ResourceOptions, StorageMode, StoreAction, Texture, TextureDescriptor, +}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; + +/// A 4x4 texture of the program's of `pf`, `usage` and `storage`, at a plain ID. +fn texture(device: &Device, pf: PixelFormat, usage: TextureUsage, storage: StorageMode) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(pf, 4, 4, false); + descriptor.usage = usage; + descriptor.resource_options = match storage { + StorageMode::Private => ResourceOptions::private(), + storage => ResourceOptions::new( + storage, + CpuCacheMode::DefaultCache, + HazardTrackingMode::Default, + ), + }; + device.new_texture(&descriptor).unwrap() +} + +/// A private 4x4 `RGBA8Unorm` texture of the program's. +fn plain(device: &Device) -> Texture { + let usage = TextureUsage::SHADER_READ; + texture(device, PixelFormat::RGBA8Unorm, usage, StorageMode::Private) +} + +/// The program's textures take IDs 1 to 7 in the order it makes them, with a pass of separate +/// depth and stencil textures and a pass of a memoryless attachment encoded between them: the +/// scratch image and the backing those passes render through take none. +#[test] +fn the_runtime_s_own_textures_take_no_texture_id() { + let scratch = Scratch::new("internal-texture-ids"); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let target = TextureUsage::RENDER_TARGET; + let mut ids = Vec::new(); + let mut held = Vec::new(); + let mut note = |t: Texture, ids: &mut Vec| { + ids.push(t.gpu_resource_id().0); + held.push(t.clone()); + t + }; + note(plain(&device), &mut ids); + let private = StorageMode::Private; + let depth = note( + texture(&device, PixelFormat::Depth32Float, target, private), + &mut ids, + ); + let stencil = note( + texture(&device, PixelFormat::Stencil8, target, private), + &mut ids, + ); + let transient = StorageMode::Memoryless; + let memoryless = note( + texture(&device, PixelFormat::RGBA8Unorm, target, transient), + &mut ids, + ); + let command_buffer = queue.command_buffer().unwrap(); + // Separate depth and stencil textures: the pass renders into a combined scratch image. + let mut descriptor = RenderPassDescriptor::new(); + descriptor.depth_attachment.texture = Some(depth); + descriptor.depth_attachment.load_action = LoadAction::Clear; + descriptor.depth_attachment.store_action = StoreAction::Store; + descriptor.stencil_attachment.texture = Some(stencil); + descriptor.stencil_attachment.load_action = LoadAction::Clear; + descriptor.stencil_attachment.store_action = StoreAction::Store; + let encoder = command_buffer.render_command_encoder(&descriptor).unwrap(); + note(plain(&device), &mut ids); + encoder.end_encoding().unwrap(); + // A memoryless attachment: the pass renders into a backing the runtime keeps. + let mut descriptor = RenderPassDescriptor::new(); + let color = &mut descriptor.color_attachments[0]; + color.texture = Some(memoryless); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::DontCare; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + let encoder = command_buffer.render_command_encoder(&descriptor).unwrap(); + note(plain(&device), &mut ids); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + note(plain(&device), &mut ids); + assert_eq!(ids, [1, 2, 3, 4, 5, 6, 7], "on {}", device.name()); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 98d21b419..f1caf4859 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -169,6 +169,8 @@ mod indirect_command_buffer; mod inline_continues; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod inline_splits; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod internal_texture_ids; mod interop; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod joined_residency;