From ef7fe8aa5652cc901fc45400bfc7f95fd67a877e Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 19 Oct 2026 00:15:59 +0300 Subject: [PATCH] Hold what a blit, a per-sample copy and an indirect sparse update use until the command buffer completes Metal's command buffer retains what its encoders were given until it completes, so a program may release a buffer or texture once it committed. Two paths did not hold theirs: - A blit between a buffer and a multisampled texture, emulated per sample, retained only its copy's plan (the raw VkBuffer and its own images), not the program's Buffer or the texture. - An indirect sparse mapping update's host step replaced the update with the updates its arguments state; where they state none, nothing held the texture and buffer, and the replaced update was dropped under the command buffer's state lock, so a no-copy buffer's last release could run its deallocator under that lock. What changes: - EncoderCore::blit_at, the one way a blit command takes a buffer's VkBuffer, retains the buffer until completion, so every blit path holds it; the per-sample copy holds the texture it copies into or out of. - read_mappings moves the replaced sparse update into the command buffer's retained list, released at completion outside the lock. - A buffer or texture these commands used is now released at completion rather than at the program's release. Why: the consumer's resource synchronization on an RTX 5080 copies a multisampled Depth32Float texture into a no-copy buffer over guest pages, commits, waits until scheduled and drops the buffer. The import was freed 3 ms after the commit, and the copy engine's write at its first page faulted 285 ms later and lost the device. METAL2VULKAN_LOG_MEMORY placed the fault at offset 0 of the freed import and showed the next import mapped at the same address: with that mapping first, the copy would have written into other guest memory silently. Verified: - tests::blit_holds (device test): each leg puts the blit behind 1 GiB of fills, commits, waits until scheduled, releases the no-copy buffer and asserts its deallocator has not run while pending, then checks the bytes in the host pages (buffer to and from no-copy, fill, multisampled R32Uint both ways, multisampled Depth32Float set Volatile after release). - tests::encoder_holds (device tests), one leg per way a command reaches memory: draws reading vertex, fragment, index and indirect buffers, a draw into a texture over a no-copy buffer, dispatches, an indirect dispatch, use_resource and use_heap reaches, an indirect command buffer's dispatch, and sparse indirect updates that map a level and that map nothing. While pending, the deallocator has not run and every watched object lives. - Before the fix, on lavapipe under the validation layer 17 passed and 2 failed (the sparse update's lost texture, and a heap's placed buffer, which Metal's contract does not hold either and the test no longer watches); on the Iris Xe 18 passed, 1 failed (the placed buffer). - The fixed runtime built under m2v_gpu and m2v_cpu_icd with clippy -D warnings clean; the fixed legs ran in the following device batches. --- .../metal2vulkan-runtime/src/blit_texture.rs | 5 +- .../src/command_buffer/mod.rs | 16 +- crates/metal2vulkan-runtime/src/encoder.rs | 7 + .../src/sample_interleave.rs | 8 +- .../src/tests/blit_holds.rs | 472 +++++++++ .../src/tests/encoder_holds.rs | 941 ++++++++++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 4 + 7 files changed, 1446 insertions(+), 7 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/blit_holds.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/encoder_holds.rs diff --git a/crates/metal2vulkan-runtime/src/blit_texture.rs b/crates/metal2vulkan-runtime/src/blit_texture.rs index 4490cba9b..7468ad5a1 100644 --- a/crates/metal2vulkan-runtime/src/blit_texture.rs +++ b/crates/metal2vulkan-runtime/src/blit_texture.rs @@ -466,8 +466,9 @@ impl BlitCommandEncoder { Some(copy) => { self.command_in(copy.stages, ©.uses, |device, raw| { // SAFETY: the encoder's command buffer is recording outside a render - // pass; the buffer, the texture, and the copy's images and objects are - // live until it completes (retained below). + // pass; the buffer (held by `blit_at`), the texture, and the copy's + // images and objects (held by the copy, retained below) are live until + // it completes. unsafe { copy.record(device, raw) }; })?; // A depth written as the single-sample path writes one announces as it does. diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 64eeffbb5..097e6e449 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -2420,8 +2420,8 @@ impl CommandBufferShared { /// The host step's reading of batch `index`'s indirect sparse updates (`sparse/indirect.rs`), /// before its segments' steps: each is replaced, in its place, by the updates its arguments - /// state now. A refusal is kept for the batch's submission, which fails the command buffer with - /// it, and the rest stay unread. + /// state now, and held until the command buffer completes. A refusal is kept for the batch's + /// submission, which fails the command buffer with it, and the rest stay unread. fn read_mappings(self: &Arc, index: usize) { let device = &self.device; let unread: Vec<(usize, usize, SparseUpdate)> = { @@ -2463,7 +2463,17 @@ impl CommandBufferShared { let mut state = lock(&self.state); match read { Ok(updates) => { - state.recorded[encoder].sparse.splice(at..at + 1, updates); + // The update read goes to `retained`: its texture and buffer are held until + // the command buffer completes, as Metal's command buffer holds what its + // encoders were given, though its arguments map nothing; and it is released + // outside this lock (the buffer's last release may run a deallocator). + let read: Vec = state.recorded[encoder] + .sparse + .splice(at..at + 1, updates) + .collect(); + state + .retained + .extend(read.into_iter().map(|update| Box::new(update) as Box<_>)); } Err(failure) => { state.step_failure = Some(match failure { diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index e342e8b33..0ac3be9cc 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -464,6 +464,12 @@ impl EncoderCore { /// ([`Buffer::blit_at`]): a no-copy buffer's import the device released while idle is /// imported again first, and what the command reads of it held until the command buffer /// completes (`host_residency.rs`). Refused where the device cannot import it again. + /// + /// The buffer itself is held until the command buffer completes too, whatever path records + /// the command (a per-sample copy's plan holds only the raw `VkBuffer`): its `VkBuffer`, and a + /// no-copy buffer's import of the caller's pages, go only once nothing holds the buffer + /// (`HostImport`'s drop), so a program that lets go of it once it committed (as Metal lets it, + /// a command buffer retaining what its commands use) frees nothing a command in flight writes. pub(super) fn blit_at( &mut self, buffer: &Buffer, @@ -473,6 +479,7 @@ impl EncoderCore { if let Some(hold) = hold { self.retain_shared(hold); } + self.retain_shared(buffer.held()); Ok(at) } diff --git a/crates/metal2vulkan-runtime/src/sample_interleave.rs b/crates/metal2vulkan-runtime/src/sample_interleave.rs index 824abcfc5..d6ddb5373 100644 --- a/crates/metal2vulkan-runtime/src/sample_interleave.rs +++ b/crates/metal2vulkan-runtime/src/sample_interleave.rs @@ -611,8 +611,9 @@ enum Recorded { } /// The emulated copy: its steps, the resource uses the command barriers over, the stages it -/// runs in, the band objects, and the scratch and wide textures it holds until the command -/// buffer completes. +/// runs in, the band objects, and the textures it holds until the command buffer completes (the +/// copy's own, its scratch and wide images, and the texture it copies into or out of). The buffer +/// it copies with is held by the encoder (`EncoderCore::blit_at`). pub(super) struct InterleaveCopy { steps: Vec, pub(super) uses: Vec>, @@ -941,6 +942,9 @@ impl InterleaveCopy { }; uses.push(texture.image_use(level..level + 1, layer..layer + 1, stage, into_texture)?); let texture_image = texture.raw_image()?; + // The copy holds the texture its steps record on until its command buffer completes, as + // it holds its wide and scratch images. + textures.push(texture.clone()); for (bx, by, bw, bh) in tiles { let wide_usage = if into_texture { ImageUsageFlags::SAMPLED | ImageUsageFlags::TRANSFER_DST diff --git a/crates/metal2vulkan-runtime/src/tests/blit_holds.rs b/crates/metal2vulkan-runtime/src/tests/blit_holds.rs new file mode 100644 index 000000000..48eec6e7d --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/blit_holds.rs @@ -0,0 +1,472 @@ +//! A blit's buffers and textures held until its command buffer completed: a no-copy buffer that +//! a committed blit writes or reads, released by the program while the blit still waits behind +//! other work, keeps its import (its deallocator unrun) until the command buffer completed, and +//! the blit's bytes land in its pages. The consumer's `SynchronizeAndDiscardResources` on an RTX +//! 5080 copied a multisampled `Depth32Float` texture into a no-copy transfer buffer over its guest +//! pages, committed, waited until scheduled, released the transfer buffer and set the texture +//! `Volatile`: the per-sample copy (`sample_interleave.rs`) held neither the buffer nor the +//! texture, the import was freed 3 ms later with the copy in flight +//! (`VUID-vkDestroyBuffer-buffer-00922`), and the copy engine's write into it faulted (Xid 31), +//! where the next import reusing the address would have taken the write silently. +//! +//! Each leg encodes its blit before the work it waits behind is committed, and commits it after: +//! an encoding that outlasted that work (a per-sample depth copy's, on a Radeon 780M) would leave +//! nothing pending to hold. The harness (the host pages, the no-copy buffer over them, the busy +//! work) serves the render and compute encoders' legs too (`encoder_holds.rs`). +//! +//! 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. + +use crate::error::RuntimeGap; +use crate::{ + BlitCommandEncoder, BlitOption, Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, + Device, DeviceKind, DeviceOptions, Error, HostMemory, Origin, PurgeableState, ResourceOptions, + ShaderCacheOptions, Size, Texture, TextureDescriptor, +}; +use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; +use std::alloc::Layout; +use std::path::{Path, PathBuf}; +use std::ptr::NonNull; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +/// The longest a command buffer, or a release after it, may take. +pub(super) const WAIT: Duration = Duration::from_secs(60); + +/// The no-copy buffer's bytes: whole pages of any host. +pub(super) const BYTES: usize = 4 << 20; + +/// The fills that keep the queue busy before the blit: [`FILLS`] of [`FILLED`] bytes each. +const FILLS: u32 = 16; +pub(super) const FILLED: u64 = 64 << 20; + +/// The word a source holds, the depth a depth source holds (0.5), and the byte a fill writes. +pub(super) const SOURCE: u32 = 0x5a5a_5a5a; +const DEPTH: u32 = 0x3f00_0000; +const FILL: u8 = 0xc3; + +/// A scratch directory for the device's shader cache, removed when dropped. +pub(super) struct Scratch(pub(super) PathBuf); + +impl Scratch { + /// The directory of the leg `leg`. + pub(super) fn new(leg: &str) -> Scratch { + let name = format!("m2v-holds-{leg}-{}", std::process::id()); + let path = std::env::temp_dir().join(name); + std::fs::create_dir_all(&path).unwrap(); + Scratch(path) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Page-aligned host memory of [`BYTES`], zeroed, freed when dropped: declared before the device +/// that uses it, so dropped after it. +pub(super) struct Host(NonNull); + +impl Host { + fn layout() -> Layout { + Layout::from_size_align(BYTES, 64 << 10).unwrap() + } + + pub(super) fn new() -> Host { + // SAFETY: the layout's size is not zero. + let pointer = unsafe { std::alloc::alloc_zeroed(Host::layout()) }; + Host(NonNull::new(pointer).unwrap()) + } + + /// Its words. + pub(super) fn words(&self) -> &[u32] { + // SAFETY: `BYTES` bytes, allocated in `new` aligned past a word, which no command writes + // any more. + unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast(), BYTES / 4) } + } + + /// Whether every word is `value`. + pub(super) fn holds(&self, value: u32) -> bool { + self.words().iter().all(|&word| word == value) + } + + /// Set every word to `value`. + pub(super) fn fill(&self, value: u32) { + // SAFETY: as above; no command uses them now. + let words = unsafe { std::slice::from_raw_parts_mut(self.0.as_ptr().cast(), BYTES / 4) }; + words.fill(value); + } + + /// Set the words from word `at` on to `words`. + pub(super) fn set(&self, at: usize, words: &[u32]) { + assert!(at + words.len() <= BYTES / 4); + // SAFETY: the words are within the allocation (above), which no command uses now. + unsafe { + std::ptr::copy_nonoverlapping( + words.as_ptr(), + self.0.as_ptr().cast::().add(at), + words.len(), + ) + }; + } +} + +impl Drop for Host { + fn drop(&mut self) { + // SAFETY: allocated with this layout in `Host::new`. + unsafe { std::alloc::dealloc(self.0.as_ptr(), Host::layout()) }; + } +} + +/// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU, its shader cache +/// in `cache`. +pub(super) fn device(cache: &Path) -> Device { + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + shader_cache: ShaderCacheOptions { + directory: Some(cache.to_owned()), + ..ShaderCacheOptions::default() + }, + ..DeviceOptions::default() + }; + Device::system_default_with(&options).unwrap() +} + +/// A no-copy buffer over `host`, whose deallocator counts its runs in `runs`; `None`, printed, +/// where the device imports no host memory. +pub(super) fn over_host(device: &Device, host: &Host, runs: &Arc) -> Option { + let runs = Arc::clone(runs); + // SAFETY: the memory outlives the buffer (dropped after the device), and only the buffer's + // commands use it while it lives. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::new(host.0), + BYTES as u64, + ResourceOptions::default(), + Some(Box::new(move |_: NonNull, _: u64| { + runs.fetch_add(1, Ordering::SeqCst); + })), + ) + }; + match made { + Ok(buffer) => Some(buffer), + Err(Error::Unsupported(gap)) => { + eprintln!("BLIT-HOLDS: the device imports no host memory: {gap:?}"); + None + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + } +} + +pub(super) fn busy(queue: &CommandQueue, target: &Buffer) -> CommandBuffer { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + for value in 0..FILLS { + blit.fill_buffer(target, 0..FILLED, value as u8).unwrap(); + } + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + let deadline = Instant::now() + WAIT; + assert!(Instant::now() < deadline, "the batch was never submitted"); + std::thread::yield_now(); + } + command_buffer +} + +/// Wait until `done`, failing with `what` past [`WAIT`]. +pub(super) fn until(what: &str, done: impl Fn() -> bool) { + let deadline = Instant::now() + WAIT; + while !done() { + assert!(Instant::now() < deadline, "{what}"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +/// What a leg's blit does with the no-copy buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Leg { + /// A copy from a `Private` buffer into it. + CopyInto, + /// A copy from it into a `Private` buffer. + CopyFrom, + /// A fill of it. + Fill, + /// A copy from a multisampled `R32Uint` texture into it, per sample (`sample_interleave.rs`). + OutOfMultisampled, + /// A copy from it into a multisampled `R32Uint` texture, per sample. + IntoMultisampled, + /// A copy from a multisampled `Depth32Float` texture into it, per sample, the texture set + /// `Volatile` after the release: the consumer's synchronize and discard. + OutOfMultisampledDepth, +} + +impl Leg { + /// The multisampled texture's format, for a leg that copies with one. + fn multisampled(self) -> Option { + match self { + Leg::OutOfMultisampled | Leg::IntoMultisampled => Some(PixelFormat::R32Uint), + Leg::OutOfMultisampledDepth => Some(PixelFormat::Depth32Float), + Leg::CopyInto | Leg::CopyFrom | Leg::Fill => None, + } + } + + /// The word its source holds. + fn word(self) -> u32 { + match self { + Leg::OutOfMultisampledDepth => DEPTH, + _ => SOURCE, + } + } +} + +/// The multisampled texture's height and texel bytes; its width is what makes its samples' bytes +/// [`BYTES`] at the first sample count of [`MS_SAMPLES`] the device makes it at. +const MS_HEIGHT: u64 = 512; +const MS_TEXEL: u64 = 4; +const MS_SAMPLES: [u64; 2] = [4, 2]; + +/// A `Private` multisampled texture of `pixel_format` whose samples' bytes are [`BYTES`]; +/// `None`, printed, where the device makes none. +fn multisampled(device: &Device, pixel_format: PixelFormat) -> Option { + for samples in MS_SAMPLES { + let width = BYTES as u64 / (MS_HEIGHT * samples * MS_TEXEL); + let mut descriptor = TextureDescriptor::texture_2d(pixel_format, width, MS_HEIGHT, false); + descriptor.texture_type = TextureType::Type2DMultisample; + descriptor.sample_count = samples; + descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + match device.new_texture(&descriptor) { + Ok(texture) => return Some(texture), + Err(error) => eprintln!("BLIT-HOLDS: no {samples}-sample {pixel_format:?}: {error}"), + } + } + None +} + +/// Copy `buffer`'s [`BYTES`] into `texture`'s samples (`into`), or its samples into `buffer`: +/// whether the device ran it (`false`, printed, where it refuses the emulation). +fn per_sample( + blit: &mut BlitCommandEncoder, + buffer: &Buffer, + texture: &Texture, + into: bool, +) -> bool { + let (width, height) = (texture.width(), texture.height()); + let row = width * texture.sample_count() * MS_TEXEL; + let (size, origin) = (Size::new(width, height, 1), Origin::new(0, 0, 0)); + let length = BYTES as u64; + let copied = match into { + true => blit.copy_from_buffer_to_texture( + buffer, + 0, + row, + length, + size, + texture, + 0, + 0, + origin, + BlitOption::None, + ), + false => blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + origin, + size, + buffer, + 0, + row, + length, + BlitOption::None, + ), + }; + match copied { + Ok(()) => true, + Err(Error::NotImplemented(RuntimeGap::MultisampledBufferCopy)) => { + eprintln!("BLIT-HOLDS: the device refuses the per-sample copy"); + false + } + Err(error) => panic!("the per-sample copy: {error}"), + } +} + +/// Run `encode` in a command buffer of `queue`'s and wait for it: whether it encoded. +fn run_now(queue: &CommandQueue, encode: impl FnOnce(&mut BlitCommandEncoder) -> bool) -> bool { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + if !encode(&mut blit) { + return false; + } + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + true +} + +/// Run `leg`: the blit committed behind the busy work and scheduled, the no-copy buffer released +/// at once; its deallocator must not run before the blit's command buffer completed, and the +/// blit's bytes must land. +fn run(leg: Leg) { + let scratch = Scratch::new(&format!("blit-{leg:?}")); + let host = Host::new(); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let length = BYTES as u64; + let private = device + .new_buffer(length, ResourceOptions::private()) + .unwrap(); + let texture = match leg.multisampled() { + Some(pixel_format) => match multisampled(&device, pixel_format) { + Some(texture) => Some(texture), + None => return, + }, + None => None, + }; + // The source: the `Private` buffer, or the multisampled texture's every sample, holds the + // leg's word, copied in from the host pages through a no-copy buffer of its own. + if matches!( + leg, + Leg::CopyInto | Leg::OutOfMultisampled | Leg::OutOfMultisampledDepth + ) { + host.fill(leg.word()); + let Some(staged) = over_host(&device, &host, &Arc::new(AtomicUsize::new(0))) else { + return; + }; + let encoded = run_now(&queue, |blit| match &texture { + Some(texture) => per_sample(blit, &staged, texture, true), + None => blit + .copy_from_buffer_to_buffer(&staged, 0, &private, 0, length) + .is_ok(), + }); + if !encoded { + return; + } + drop(staged); + host.fill(0); + } else if matches!(leg, Leg::CopyFrom | Leg::IntoMultisampled) { + host.fill(leg.word()); + } + let runs = Arc::new(AtomicUsize::new(0)); + let Some(no_copy) = over_host(&device, &host, &runs) else { + return; + }; + let target = device + .new_buffer(FILLED, ResourceOptions::private()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + let ran = match (&texture, leg) { + (None, Leg::CopyInto) => blit + .copy_from_buffer_to_buffer(&private, 0, &no_copy, 0, length) + .is_ok(), + (None, Leg::CopyFrom) => blit + .copy_from_buffer_to_buffer(&no_copy, 0, &private, 0, length) + .is_ok(), + (None, _) => blit.fill_buffer(&no_copy, 0..length, FILL).is_ok(), + (Some(texture), Leg::IntoMultisampled) => per_sample(&mut blit, &no_copy, texture, true), + (Some(texture), _) => per_sample(&mut blit, &no_copy, texture, false), + }; + if !ran { + return; + } + blit.end_encoding().unwrap(); + let busy = busy(&queue, &target); + command_buffer.commit().unwrap(); + command_buffer.wait_until_scheduled().unwrap(); + let pending = command_buffer.status() != CommandBufferStatus::Completed; + drop(no_copy); + if let (Some(texture), Leg::OutOfMultisampledDepth) = (&texture, leg) { + texture + .set_purgeable_state(PurgeableState::Volatile) + .unwrap(); + } + let at_release = runs.load(Ordering::SeqCst); + let still = command_buffer.status() != CommandBufferStatus::Completed; + eprintln!( + "BLIT-HOLDS {leg:?} on {}: pending at the release {pending}, still after it {still}, \ + deallocator runs at the release {at_release}", + device.name() + ); + if pending && still { + assert_eq!( + at_release, 0, + "{leg:?}: the no-copy buffer's import went while its blit's command buffer ran" + ); + } else { + eprintln!("BLIT-HOLDS {leg:?}: the blit completed before the release: nothing to hold"); + } + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + busy.wait_until_completed_for(WAIT).unwrap(); + until("the deallocator never ran", || { + runs.load(Ordering::SeqCst) == 1 + }); + match leg { + Leg::CopyInto | Leg::OutOfMultisampled | Leg::OutOfMultisampledDepth => assert!( + host.holds(leg.word()), + "{leg:?}: the copy's bytes are not in the pages" + ), + Leg::Fill => assert!( + host.holds(u32::from_ne_bytes([FILL; 4])), + "the fill's bytes are not in the pages" + ), + Leg::CopyFrom | Leg::IntoMultisampled => { + // Read the copy back through a second no-copy buffer over the same pages, cleared + // first. + host.fill(0); + let back = over_host(&device, &host, &Arc::new(AtomicUsize::new(0))).unwrap(); + assert!(run_now(&queue, |blit| match &texture { + Some(texture) => per_sample(blit, &back, texture, false), + None => blit + .copy_from_buffer_to_buffer(&private, 0, &back, 0, length) + .is_ok(), + })); + drop(back); + assert!( + host.holds(leg.word()), + "{leg:?}: the copy did not read the pages" + ); + } + } +} + +#[test] +fn a_no_copy_buffer_a_committed_copy_writes_keeps_its_import_until_completion() { + run(Leg::CopyInto); +} + +#[test] +fn a_no_copy_buffer_a_committed_copy_reads_keeps_its_import_until_completion() { + run(Leg::CopyFrom); +} + +#[test] +fn a_no_copy_buffer_a_committed_fill_writes_keeps_its_import_until_completion() { + run(Leg::Fill); +} + +#[test] +fn a_no_copy_buffer_a_committed_per_sample_copy_writes_keeps_its_import_until_completion() { + run(Leg::OutOfMultisampled); +} + +#[test] +fn a_no_copy_buffer_a_committed_per_sample_copy_reads_keeps_its_import_until_completion() { + run(Leg::IntoMultisampled); +} + +#[test] +fn a_no_copy_buffer_a_committed_depth_copy_writes_keeps_its_import_past_a_volatile_texture() { + run(Leg::OutOfMultisampledDepth); +} diff --git a/crates/metal2vulkan-runtime/src/tests/encoder_holds.rs b/crates/metal2vulkan-runtime/src/tests/encoder_holds.rs new file mode 100644 index 000000000..26e1c5eed --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/encoder_holds.rs @@ -0,0 +1,941 @@ +//! A render, compute or resource state encoder's buffers, textures, heaps and states held until +//! its command buffer completed: `blit_holds.rs`'s drop-after-commit legs for the other encoder +//! kinds. Each leg encodes a command that reads or writes a no-copy buffer over host pages, by one +//! way a command reaches a buffer (a binding, an index or indirect buffer, an attachment or a +//! texture over the buffer, an address held in memory that `use_resource` or `use_heap` makes +//! resident, an indirect command buffer's command, a sparse texture's indirect mapping update), +//! before busy work is committed, commits it after that work, and releases the no-copy buffer +//! and every other object the command uses: once at the commit and once more where the command +//! buffer was scheduled. While the command buffer has not completed, the buffer's deallocator +//! must not have run and every object the command buffer holds must live; once it completed, the +//! command's bytes must be where they belong. Memory freed with its command in flight gives its +//! device address to the next allocation, which the command's late writes corrupt silently. +//! +//! 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. The functions are the owned fixtures +//! `validation/fixtures/public/examples/runtime_examples.ll`, `examples/icb_direct_arguments.ll`, +//! `engine/tob_renders.ll` and `engine/ob2_loaded_pointer.ll` (`llvm-as`). + +use super::blit_holds::{ + busy, device, over_host, until, Host, Scratch, BYTES, FILLED, SOURCE, WAIT, +}; +use crate::error::RuntimeGap; +use crate::{ + BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus, CommandQueue, + ComputePipelineState, Device, Error, HeapDescriptor, HeapType, IndirectCommandBufferDescriptor, + Library, LoadAction, Origin, PipelineOptions, Region, RenderPassDescriptor, + RenderPipelineState, ResourceOptions, ResourceRef, Size, StoreAction, Texture, + TextureDescriptor, +}; +use metal2vulkan::bind::TileMapping; +use metal2vulkan::error::Feature; +use metal2vulkan::metal::{ + IndexType, IndirectCommandType, PixelFormat, PrimitiveType, ResourceUsage, TextureType, + TextureUsage, +}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; +use std::any::Any; +use std::path::Path; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +/// The words of the no-copy buffer: a `float` or a `uint` each. +const WORDS: u64 = BYTES as u64 / 4; + +/// The side of a draw's target, and the color it draws: `(0.2, 0.4, 0.6, 1)`, whose `RGBA8Unorm` +/// bytes are exact. +const SIDE: u64 = 64; +const COLOR: [f32; 4] = [0.2, 0.4, 0.6, 1.0]; +const PACKED: u32 = u32::from_le_bytes([51, 102, 153, 255]); + +/// A texture over the no-copy buffer: `RGBA8Unorm`, rows of [`ROW`] bytes, its whole bytes. +const ROW: u64 = 2048; +const OVER_WIDTH: u64 = ROW / 4; +const OVER_HEIGHT: u64 = BYTES as u64 / ROW; + +/// The byte offset of the colors a vertex leg reads after its positions. +const COLORS_AT: u64 = 256; + +/// The threads of a threadgroup of a dispatch over the buffer's words. +const GROUP: u64 = 64; + +/// What a leg's command does with the no-copy buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Leg { + /// A draw whose vertex function reads its positions and colors from it, bound + /// (`set_vertex_buffer`). + VertexBuffers, + /// A draw whose fragment function reads its color from it, bound (`set_fragment_buffer`). + FragmentBuffer, + /// An indexed draw whose indices it holds. + IndexBuffer, + /// An indirect draw whose arguments it holds. + IndirectDraw, + /// A draw into a texture over it, the pass's color attachment. + Attachment, + /// A dispatch that reads it, bound. + KernelReads, + /// A dispatch that writes it, bound. + KernelWrites, + /// An indirect dispatch whose arguments it holds. + IndirectDispatch, + /// A dispatch that writes a texture over it. + TextureWrite, + /// A dispatch that reads and writes it through an address held in memory, made resident with + /// `use_resource`. + UsedResource, + /// A dispatch that writes it, bound, from a heap's buffer that it reads through an address + /// held in memory, the heap made resident with `use_heap`: the heap is held, not the buffer + /// placed in it, as Metal's command buffer holds what its encoders were given. A placed buffer + /// the program releases gives its range back to the heap, which a buffer placed later may take + /// while the command runs, on Metal as here. + UsedHeap, + /// An indirect command buffer's dispatch that writes it, made resident with `use_resource`. + IndirectCommands, + /// A sparse texture's indirect mapping update whose arguments it holds, which map the texture. + SparseMapping, + /// The same, its arguments mapping nothing: the texture and the buffer are held still. + SparseMappingNothing, +} + +/// Where the program releases what the command uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Release { + /// As `commit` returns. + Committed, + /// Once `wait_until_scheduled` returned. + Scheduled, +} + +/// A check of the bytes once the command buffer completed. +type Check = Box; + +/// Whether an object a leg released still lives. +type Lives = Box bool>; + +/// What a leg encoded: the objects the program releases with the no-copy buffer, those of them +/// the command buffer must hold, by name, and the check once it completed. +struct Encoded { + released: Vec>, + watched: Vec<(&'static str, Lives)>, + check: Check, +} + +/// Watch the object `held` is a reference to (a buffer's, texture's or render state's `held`). +fn watch(name: &'static str, held: Arc) -> (&'static str, Lives) { + let weak = Arc::downgrade(&held); + (name, Box::new(move || weak.strong_count() > 0)) +} + +/// Watch a compute state. +fn watch_state(state: &ComputePipelineState) -> (&'static str, Lives) { + let weak = state.downgrade(); + ( + "the compute state", + Box::new(move || weak.upgrade().is_some()), + ) +} + +/// Watch a render state. +fn watch_render_state(state: &RenderPipelineState) -> (&'static str, Lives) { + let weak = state.downgrade().expect("a drawing state"); + ( + "the render state", + Box::new(move || weak.upgrade().is_some()), + ) +} + +/// The little-endian bytes of `values`. +fn bytes_of(values: &[T], to_bytes: impl Fn(T) -> [u8; N]) -> Vec { + values.iter().flat_map(|&value| to_bytes(value)).collect() +} + +/// The bits of `values`. +fn bits(values: &[f32]) -> Vec { + values.iter().map(|value| value.to_bits()).collect() +} + +/// The words of `buffer`, a host-visible buffer no command writes now. +fn words_of(buffer: &Buffer) -> Vec { + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's `length` bytes, which no command buffer writes now. + let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }; + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|word| u32::from_le_bytes(*word)) + .collect() +} + +/// The library of the fixture at `path` under `validation/fixtures/public/`. +fn library(device: &Device, path: &str) -> Library { + let ll = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/fixtures/public") + .join(path); + let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap(); + let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap(); + device.new_library_with_compile_library(library) +} + +/// A state of `kernel` of the fixture at `path`, made for indirect command buffers where `icb`. +fn compute_state(device: &Device, path: &str, kernel: &str, icb: bool) -> ComputePipelineState { + let function = library(device, path) + .new_function_with_name(kernel) + .unwrap(); + let mut descriptor = + ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + descriptor.support_indirect_command_buffers = icb; + device + .new_compute_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// A state that draws into `RGBA8Unorm` with the functions `vertex` and `fragment` of the +/// fixture at `path`. +fn render_state(device: &Device, path: &str, vertex: &str, fragment: &str) -> RenderPipelineState { + let library = library(device, path); + let vertex = library.new_function_with_name(vertex).unwrap(); + let fragment = library.new_function_with_name(fragment).unwrap(); + let mut descriptor = + RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); + descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); + descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// A pass that clears `target` to zero and stores what it draws. +fn pass(target: &Texture) -> RenderPassDescriptor { + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + pass +} + +/// An `RGBA8Unorm` texture over the no-copy buffer's bytes of `usage`; `None`, printed, where the +/// device makes none. +fn over_buffer(no_copy: &Buffer, usage: TextureUsage) -> Option { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, OVER_WIDTH, OVER_HEIGHT, false); + descriptor.usage = usage; + descriptor.resource_options = ResourceOptions::default(); + match no_copy.new_texture(&descriptor, 0, ROW) { + Ok(texture) => Some(texture), + Err(error) => { + eprintln!("ENCODER-HOLDS: no texture over the no-copy buffer: {error}"); + None + } + } +} + +/// A `Shared` buffer of the device's holding `words`. +fn shared_words(device: &Device, words: &[u32]) -> Buffer { + device + .new_buffer_with_bytes( + &bytes_of(words, u32::to_le_bytes), + ResourceOptions::shared(), + ) + .unwrap() +} + +/// Encode `leg`'s command over `no_copy`, the host pages' buffer, in `command_buffer`, the pages +/// holding its inputs first; `None`, printed, where the device has not what the leg needs. +fn encode( + leg: Leg, + device: &Device, + queue: &CommandQueue, + command_buffer: &CommandBuffer, + host: &Host, + no_copy: &Buffer, +) -> Option { + match leg { + Leg::VertexBuffers | Leg::FragmentBuffer | Leg::IndexBuffer | Leg::IndirectDraw => { + Some(draw(leg, device, command_buffer, host, no_copy)) + } + Leg::Attachment => attachment(device, command_buffer, host, no_copy), + Leg::KernelReads | Leg::KernelWrites | Leg::IndirectDispatch => { + Some(dispatch(leg, device, command_buffer, host, no_copy)) + } + Leg::TextureWrite => texture_write(device, command_buffer, host, no_copy), + Leg::UsedResource => Some(used_resource(device, command_buffer, host, no_copy)), + Leg::UsedHeap => Some(used_heap(device, queue, command_buffer, host, no_copy)), + Leg::IndirectCommands => Some(indirect_commands(device, command_buffer, host, no_copy)), + Leg::SparseMapping | Leg::SparseMappingNothing => { + sparse_mapping(leg, device, command_buffer, host, no_copy) + } + } +} + +/// A draw leg: a rectangle (or a triangle) over a `Private` target in the color, read from the +/// no-copy buffer as the leg says, the target copied into a `Shared` buffer after the pass. +fn draw( + leg: Leg, + device: &Device, + command_buffer: &CommandBuffer, + host: &Host, + no_copy: &Buffer, +) -> Encoded { + let state = match leg { + Leg::VertexBuffers => render_state( + device, + "examples/runtime_examples.ll", + "colored_vertex", + "colored_fragment", + ), + _ => render_state(device, "engine/tob_renders.ll", "tob_rect", "tob_solid"), + }; + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + let target = device.new_texture(&descriptor).unwrap(); + let back = device + .new_buffer(SIDE * SIDE * 4, ResourceOptions::shared()) + .unwrap(); + host.fill(0); + let mut encoder = command_buffer + .render_command_encoder(&pass(&target)) + .unwrap(); + encoder.set_render_pipeline_state(&state).unwrap(); + let corners = bytes_of(&[-1.0f32, -1.0, 1.0, 1.0], f32::to_le_bytes); + let color = bytes_of(&COLOR, f32::to_le_bytes); + match leg { + Leg::VertexBuffers => { + // A triangle over the target: its positions, then each vertex's color. + host.set(0, &bits(&[-1.0, -1.0, 3.0, -1.0, -1.0, 3.0])); + host.set(COLORS_AT as usize / 4, &bits(&COLOR.repeat(3))); + encoder.set_vertex_buffer(Some(no_copy), 0, 0).unwrap(); + encoder + .set_vertex_buffer(Some(no_copy), COLORS_AT, 1) + .unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + } + Leg::FragmentBuffer => { + host.set(0, &bits(&COLOR)); + encoder.set_vertex_bytes(&corners, 0).unwrap(); + encoder.set_fragment_buffer(Some(no_copy), 0, 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + } + Leg::IndexBuffer => { + host.set(0, &[1 << 16, 2 | 3 << 16, 4 | 5 << 16]); + encoder.set_vertex_bytes(&corners, 0).unwrap(); + encoder.set_fragment_bytes(&color, 0).unwrap(); + encoder + .draw_indexed_primitives( + PrimitiveType::Triangle, + 6, + IndexType::UInt16, + no_copy, + 0, + 1, + 0, + 0, + ) + .unwrap(); + } + _ => { + // `MTLDrawPrimitivesIndirectArguments`: six vertices, one instance. + host.set(0, &[6, 1, 0, 0]); + encoder.set_vertex_bytes(&corners, 0).unwrap(); + encoder.set_fragment_bytes(&color, 0).unwrap(); + encoder + .draw_primitives_indirect(PrimitiveType::Triangle, no_copy, 0) + .unwrap(); + } + } + encoder.end_encoding().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &target, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(SIDE, SIDE, 1), + &back, + 0, + SIDE * 4, + SIDE * SIDE * 4, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + Encoded { + watched: vec![ + watch("the target", target.held()), + watch_render_state(&state), + ], + released: vec![Box::new(target), Box::new(state)], + check: Box::new(move |_| { + assert!( + words_of(&back).iter().all(|&word| word == PACKED), + "{leg:?}: the draw's color is not in the target" + ); + }), + } +} + +/// The attachment leg: a rectangle in the color over a texture over the no-copy buffer. +fn attachment( + device: &Device, + command_buffer: &CommandBuffer, + host: &Host, + no_copy: &Buffer, +) -> Option { + let target = over_buffer(no_copy, TextureUsage::RENDER_TARGET)?; + let state = render_state(device, "engine/tob_renders.ll", "tob_rect", "tob_solid"); + host.fill(SOURCE); + let mut encoder = command_buffer + .render_command_encoder(&pass(&target)) + .unwrap(); + encoder.set_render_pipeline_state(&state).unwrap(); + let corners = bytes_of(&[-1.0f32, -1.0, 1.0, 1.0], f32::to_le_bytes); + encoder.set_vertex_bytes(&corners, 0).unwrap(); + encoder + .set_fragment_bytes(&bytes_of(&COLOR, f32::to_le_bytes), 0) + .unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + Some(Encoded { + watched: vec![ + watch("the texture over the buffer", target.held()), + watch_render_state(&state), + ], + released: vec![Box::new(target), Box::new(state)], + check: Box::new(|host| { + assert!( + host.holds(PACKED), + "the draw's color is not in the pages under the attachment" + ); + }), + }) +} + +/// A dispatch leg of `scale_and_offset` (`output[i] = input[i] * scale + i`) over the buffer's +/// words, scale 1: reading the no-copy buffer (its words 1), writing it (from zeros), or reading +/// its threadgroup counts from it. +fn dispatch( + leg: Leg, + device: &Device, + command_buffer: &CommandBuffer, + host: &Host, + no_copy: &Buffer, +) -> Encoded { + let state = compute_state( + device, + "examples/runtime_examples.ll", + "scale_and_offset", + false, + ); + // The input where it is not the no-copy buffer, and the output where that is not. + let zeros = (leg != Leg::KernelReads).then(|| shared_words(device, &vec![0; WORDS as usize])); + let output = (leg != Leg::KernelWrites).then(|| { + device + .new_buffer(BYTES as u64, ResourceOptions::shared()) + .unwrap() + }); + match leg { + Leg::KernelReads => host.fill(1.0f32.to_bits()), + Leg::KernelWrites => host.fill(SOURCE), + _ => { + host.fill(0); + host.set(0, &[(WORDS / GROUP) as u32, 1, 1]); + } + } + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder + .set_buffer(Some(zeros.as_ref().unwrap_or(no_copy)), 0, 0) + .unwrap(); + encoder + .set_buffer(Some(output.as_ref().unwrap_or(no_copy)), 0, 1) + .unwrap(); + encoder.set_bytes(&1.0f32.to_le_bytes(), 2).unwrap(); + let group = Size::new(GROUP, 1, 1); + match leg { + Leg::IndirectDispatch => encoder.dispatch_threadgroups_indirect(no_copy, 0, group), + _ => encoder.dispatch_threads(Size::new(WORDS, 1, 1), group), + } + .unwrap(); + encoder.end_encoding().unwrap(); + let base = match leg { + Leg::KernelReads => 1.0, + _ => 0.0, + }; + let expected = move |words: &[u32]| { + words + .iter() + .enumerate() + .all(|(i, &word)| f32::from_bits(word) == base + i as f32) + }; + let mut watched = vec![watch_state(&state)]; + let mut released: Vec> = vec![Box::new(state)]; + if let Some(zeros) = zeros { + watched.push(watch("the input buffer", zeros.held())); + released.push(Box::new(zeros)); + } + Encoded { + watched, + released, + check: Box::new(move |host| match output { + None => assert!( + expected(host.words()), + "the dispatch's words are not in the pages" + ), + Some(output) => assert!( + expected(&words_of(&output)), + "{leg:?}: the dispatch did not read the pages" + ), + }), + } +} + +/// The texture write leg: `invert_texels` from a texture of zeros into a texture over the no-copy +/// buffer, which takes `(1, 1, 1, 0)`. +fn texture_write( + device: &Device, + command_buffer: &CommandBuffer, + host: &Host, + no_copy: &Buffer, +) -> Option { + let destination = over_buffer(no_copy, TextureUsage::SHADER_WRITE)?; + let library = library(device, "examples/runtime_examples.ll"); + let function = library.new_function_with_name("invert_texels").unwrap(); + let state = device + .new_compute_pipeline_state_with_function(&function, &PipelineOptions::default()) + .unwrap(); + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, OVER_WIDTH, OVER_HEIGHT, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::shared(); + let source = device.new_texture(&descriptor).unwrap(); + source + .replace_region( + Region::new_2d(0, 0, OVER_WIDTH, OVER_HEIGHT), + 0, + 0, + &vec![0; BYTES], + ROW, + 0, + ) + .unwrap(); + host.fill(SOURCE); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.set_texture(Some(&source), 0).unwrap(); + encoder.set_texture(Some(&destination), 1).unwrap(); + encoder + .dispatch_threads(Size::new(OVER_WIDTH, OVER_HEIGHT, 1), Size::new(8, 8, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + Some(Encoded { + watched: vec![ + watch_state(&state), + watch("the source texture", source.held()), + watch("the texture over the buffer", destination.held()), + ], + released: vec![Box::new(state), Box::new(source), Box::new(destination)], + check: Box::new(|host| { + assert!( + host.holds(u32::from_le_bytes([255, 255, 255, 0])), + "the dispatch's texels are not in the pages under the texture" + ); + }), + }) +} + +/// The indices `ob2_loaded_pointer`'s eight threads load from (`0` to `7`) and store to (`8` to +/// `15`), as bytes. +fn loaded_pointer_indices() -> Vec { + bytes_of(&(0..16u32).collect::>(), u32::to_le_bytes) +} + +/// The resident resource leg: `ob2_loaded_pointer` through the no-copy buffer's address, which +/// its threads load words 0 to 7 from and store `0xB0000000 | t` to words 8 to 15 of. +fn used_resource( + device: &Device, + command_buffer: &CommandBuffer, + host: &Host, + no_copy: &Buffer, +) -> Encoded { + let state = compute_state( + device, + "engine/ob2_loaded_pointer.ll", + "ob2_loaded_pointer", + false, + ); + let out = device.new_buffer(32, ResourceOptions::shared()).unwrap(); + host.fill(SOURCE); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder + .use_resource( + ResourceRef::Buffer(no_copy), + ResourceUsage::READ | ResourceUsage::WRITE, + ) + .unwrap(); + encoder.set_bytes(&loaded_pointer_indices(), 0).unwrap(); + encoder + .set_bytes(&no_copy.gpu_address().0.to_le_bytes(), 1) + .unwrap(); + encoder.set_buffer(Some(&out), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(8, 1, 1), Size::new(8, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + Encoded { + watched: vec![watch_state(&state)], + released: vec![Box::new(state)], + check: Box::new(move |host| { + let stored: Vec = (0..8).map(|t| 0xB000_0000 | t).collect(); + assert_eq!( + &host.words()[..16], + [[SOURCE; 8].as_slice(), &stored].concat(), + "the stores through the address are not in the pages" + ); + assert_eq!( + words_of(&out), + [SOURCE; 8], + "the loads through the address did not read the pages" + ); + }), + } +} + +/// The resident heap leg: `ob2_loaded_pointer` through the address of a heap's buffer that holds +/// [`SOURCE`], the heap made resident with `use_heap`; its threads load the buffer's words 0 to +/// 7 into the no-copy buffer's. +fn used_heap( + device: &Device, + queue: &CommandQueue, + command_buffer: &CommandBuffer, + host: &Host, + no_copy: &Buffer, +) -> Encoded { + let state = compute_state( + device, + "engine/ob2_loaded_pointer.ll", + "ob2_loaded_pointer", + false, + ); + let heap = device + .new_heap(&HeapDescriptor::new( + HeapType::Automatic, + 1 << 20, + ResourceOptions::private(), + )) + .unwrap(); + let placed = heap + .new_buffer(64 << 10, ResourceOptions::private()) + .unwrap(); + let filling = queue.command_buffer().unwrap(); + let mut blit = filling.blit_command_encoder().unwrap(); + blit.fill_buffer(&placed, 0..placed.length(), SOURCE as u8) + .unwrap(); + blit.end_encoding().unwrap(); + filling.commit().unwrap(); + filling.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(filling.error(), None); + host.fill(0); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.use_heap(&heap).unwrap(); + encoder.set_bytes(&loaded_pointer_indices(), 0).unwrap(); + encoder + .set_bytes(&placed.gpu_address().0.to_le_bytes(), 1) + .unwrap(); + encoder.set_buffer(Some(no_copy), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(8, 1, 1), Size::new(8, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + let weak = heap.downgrade(); + Encoded { + watched: vec![ + watch_state(&state), + ("the heap", Box::new(move || weak.upgrade().is_some())), + ], + released: vec![Box::new(state), Box::new(placed), Box::new(heap)], + check: Box::new(|host| { + assert_eq!( + &host.words()[..9], + [[SOURCE; 8].as_slice(), &[0]].concat(), + "the heap's words are not in the pages" + ); + }), + } +} + +/// The indirect command leg: an indirect command buffer's `scale_and_offset` over the buffer's +/// words from zeros, scale 1, the buffers made resident with `use_resource`. The program keeps +/// the state, which Metal's command does not hold. +fn indirect_commands( + device: &Device, + command_buffer: &CommandBuffer, + host: &Host, + no_copy: &Buffer, +) -> Encoded { + let state = compute_state( + device, + "examples/runtime_examples.ll", + "scale_and_offset", + true, + ); + let zeros = shared_words(device, &vec![0; WORDS as usize]); + let scale = shared_words(device, &[1.0f32.to_bits()]); + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH_THREADS; + descriptor.max_kernel_buffer_bind_count = 3; + let icb = device + .new_indirect_command_buffer(&descriptor, 1, ResourceOptions::shared()) + .unwrap(); + let command = icb.indirect_compute_command_at(0).unwrap(); + command.set_compute_pipeline_state(&state).unwrap(); + command.set_kernel_buffer(Some(&zeros), 0, 0).unwrap(); + command.set_kernel_buffer(Some(no_copy), 0, 1).unwrap(); + command.set_kernel_buffer(Some(&scale), 0, 2).unwrap(); + command + .concurrent_dispatch_threads(Size::new(WORDS, 1, 1), Size::new(GROUP, 1, 1)) + .unwrap(); + host.fill(SOURCE); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder + .use_resource(ResourceRef::Buffer(&zeros), ResourceUsage::READ) + .unwrap(); + encoder + .use_resource(ResourceRef::Buffer(no_copy), ResourceUsage::WRITE) + .unwrap(); + encoder + .use_resource(ResourceRef::Buffer(&scale), ResourceUsage::READ) + .unwrap(); + encoder.execute_commands_in_buffer(&icb, 0..1).unwrap(); + encoder.end_encoding().unwrap(); + Encoded { + watched: vec![ + watch("the input buffer", zeros.held()), + watch("the scale buffer", scale.held()), + ], + released: vec![Box::new(icb), Box::new(zeros), Box::new(scale)], + check: Box::new(move |host| { + // The program's state, released once the command buffer completed. + drop(state); + assert!( + host.words() + .iter() + .enumerate() + .all(|(i, &word)| f32::from_bits(word) == i as f32), + "the indirect command's words are not in the pages" + ); + }), + } +} + +/// A sparse mapping leg: an indirect update that maps every tile of a sparse texture's level 0, or +/// nothing, its `MTLMapIndirectBuffer` in the no-copy buffer; `None`, printed, where the device has +/// no sparse textures. +fn sparse_mapping( + leg: Leg, + device: &Device, + command_buffer: &CommandBuffer, + host: &Host, + no_copy: &Buffer, +) -> Option { + let lacks = |error: &Error| { + matches!(error, Error::Unsupported(u) if matches!(u.feature, Feature::SparseTextures { .. })) + || *error == Error::NotImplemented(RuntimeGap::SparseTileMaps) + }; + let descriptor = HeapDescriptor::new(HeapType::Sparse, 1 << 20, ResourceOptions::private()); + let heap = match device.new_heap(&descriptor) { + Ok(heap) => heap, + Err(error) if lacks(&error) => { + eprintln!("ENCODER-HOLDS: no sparse heap: {error:?}"); + return None; + } + Err(error) => panic!("a sparse heap: {error:?}"), + }; + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::R32Float, 256, 256, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + let texture = match heap.new_texture(&descriptor) { + Ok(texture) => texture, + Err(error) if lacks(&error) => { + eprintln!("ENCODER-HOLDS: no sparse texture: {error:?}"); + return None; + } + Err(error) => panic!("a sparse texture: {error:?}"), + }; + // The count of mappings, then each one's region origin and size in tiles, level and slice. + let tile = device.sparse_tile_size(TextureType::Type2D, PixelFormat::R32Float, 1); + let (across, down) = ((256 / tile.width) as u32, (256 / tile.height) as u32); + host.fill(0); + if leg == Leg::SparseMapping { + host.set(0, &[1, 0, 0, 0, across, down, 1, 0, 0]); + } + let mut encoder = command_buffer.resource_state_command_encoder().unwrap(); + encoder + .update_texture_mapping_indirect(&texture, TileMapping::Map, no_copy, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + let weak = heap.downgrade(); + Some(Encoded { + watched: vec![ + watch("the sparse texture", texture.held()), + ( + "the sparse heap", + Box::new(move || weak.upgrade().is_some()), + ), + ], + released: vec![Box::new(texture), Box::new(heap)], + check: Box::new(|_| ()), + }) +} + +/// Run `leg` at each release: its command encoded, then the busy work committed, then its +/// command buffer committed, and the no-copy buffer and the leg's objects released; the +/// deallocator must not run, nor any watched object go, before the command buffer completed, and +/// the leg's bytes must land. +fn run(leg: Leg) { + let scratch = Scratch::new(&format!("encoder-{leg:?}")); + let host = Host::new(); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let target = device + .new_buffer(FILLED, ResourceOptions::private()) + .unwrap(); + for release in [Release::Committed, Release::Scheduled] { + let runs = Arc::new(AtomicUsize::new(0)); + let Some(no_copy) = over_host(&device, &host, &runs) else { + return; + }; + let command_buffer = queue.command_buffer().unwrap(); + let Some(encoded) = encode(leg, &device, &queue, &command_buffer, &host, &no_copy) else { + return; + }; + let busy = busy(&queue, &target); + command_buffer.commit().unwrap(); + if release == Release::Scheduled { + command_buffer.wait_until_scheduled().unwrap(); + } + let pending = command_buffer.status() != CommandBufferStatus::Completed; + let Encoded { + released, + watched, + check, + } = encoded; + drop(no_copy); + drop(released); + let at_release = runs.load(Ordering::SeqCst); + let gone: Vec<&str> = watched + .iter() + .filter(|(_, lives)| !lives()) + .map(|&(name, _)| name) + .collect(); + let still = command_buffer.status() != CommandBufferStatus::Completed; + eprintln!( + "ENCODER-HOLDS {leg:?} released {release:?} on {}: pending at the release {pending}, \ + still after it {still}, deallocator runs at the release {at_release}, gone {gone:?}", + device.name() + ); + if pending && still { + assert_eq!( + at_release, 0, + "{leg:?}: the no-copy buffer's import went while its command buffer ran" + ); + assert!( + gone.is_empty(), + "{leg:?}: released while its command buffer ran: {gone:?}" + ); + } else { + eprintln!("ENCODER-HOLDS {leg:?}: completed before the release: nothing to hold"); + } + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + busy.wait_until_completed_for(WAIT).unwrap(); + until("the deallocator never ran", || { + runs.load(Ordering::SeqCst) == 1 + }); + check(&host); + } +} + +#[test] +fn a_no_copy_buffer_a_committed_draw_reads_as_vertex_buffers_keeps_its_import_until_completion() { + run(Leg::VertexBuffers); +} + +#[test] +fn a_no_copy_buffer_a_committed_draw_reads_as_a_fragment_buffer_keeps_its_import_until_completion() +{ + run(Leg::FragmentBuffer); +} + +#[test] +fn a_no_copy_buffer_a_committed_draw_reads_indices_from_keeps_its_import_until_completion() { + run(Leg::IndexBuffer); +} + +#[test] +fn a_no_copy_buffer_a_committed_draw_reads_arguments_from_keeps_its_import_until_completion() { + run(Leg::IndirectDraw); +} + +#[test] +fn a_no_copy_buffer_a_committed_draw_renders_into_keeps_its_import_until_completion() { + run(Leg::Attachment); +} + +#[test] +fn a_no_copy_buffer_a_committed_dispatch_reads_keeps_its_import_until_completion() { + run(Leg::KernelReads); +} + +#[test] +fn a_no_copy_buffer_a_committed_dispatch_writes_keeps_its_import_until_completion() { + run(Leg::KernelWrites); +} + +#[test] +fn a_no_copy_buffer_a_committed_dispatch_reads_arguments_from_keeps_its_import_until_completion() { + run(Leg::IndirectDispatch); +} + +#[test] +fn a_no_copy_buffer_a_committed_dispatch_writes_a_texture_over_keeps_its_import_until_completion() { + run(Leg::TextureWrite); +} + +#[test] +fn a_no_copy_buffer_a_committed_dispatch_reaches_by_address_keeps_its_import_until_completion() { + run(Leg::UsedResource); +} + +#[test] +fn a_heap_a_committed_dispatch_reaches_by_address_lives_until_completion() { + run(Leg::UsedHeap); +} + +#[test] +fn a_no_copy_buffer_a_committed_indirect_command_writes_keeps_its_import_until_completion() { + run(Leg::IndirectCommands); +} + +#[test] +fn a_no_copy_buffer_a_committed_sparse_update_reads_keeps_its_import_until_completion() { + run(Leg::SparseMapping); +} + +#[test] +fn a_sparse_update_that_maps_nothing_keeps_its_texture_and_buffer_until_completion() { + run(Leg::SparseMappingNothing); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 97e9afe2a..f65b99b89 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -21,6 +21,8 @@ mod binary; mod binary_archive; mod binding_view; mod blit; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod blit_holds; mod blit_plan; mod buffer_texture; mod capabilities; @@ -45,6 +47,8 @@ mod device; mod dispatch_pending; mod driver_defects; mod enables; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod encoder_holds; mod error_kinds; mod event_timeline; mod exactness;