diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index 1ab9edce5..69a5faeb1 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -942,6 +942,12 @@ struct Atomics { surface_wait_nanos: AtomicU64, surface_wait_max_nanos: AtomicU64, surface_wait_submissions: AtomicU64, + restoring_makes: AtomicU64, + restoring_make_drain_nanos: AtomicU64, + restoring_make_wait_nanos: AtomicU64, + restoring_make_wait_submissions: AtomicU64, + restoring_makes_shared: AtomicU64, + restoring_make_shared_wait_nanos: AtomicU64, sparse_binds: AtomicU64, resolves: AtomicU64, preprocess_regions_remade: AtomicU64, @@ -2322,6 +2328,12 @@ impl Counters { surface_wait_nanos: a.surface_wait_nanos.load(Relaxed), surface_wait_max_nanos: a.surface_wait_max_nanos.load(Relaxed), surface_wait_submissions: a.surface_wait_submissions.load(Relaxed), + restoring_makes: a.restoring_makes.load(Relaxed), + restoring_make_drain_nanos: a.restoring_make_drain_nanos.load(Relaxed), + restoring_make_wait_nanos: a.restoring_make_wait_nanos.load(Relaxed), + restoring_make_wait_submissions: a.restoring_make_wait_submissions.load(Relaxed), + restoring_makes_shared: a.restoring_makes_shared.load(Relaxed), + restoring_make_shared_wait_nanos: a.restoring_make_shared_wait_nanos.load(Relaxed), sparse_binds: a.sparse_binds.load(Relaxed), resolves: a.resolves.load(Relaxed), preprocess_regions_remade: a.preprocess_regions_remade.load(Relaxed), @@ -3550,6 +3562,43 @@ pub struct Metrics { /// much longer than these submissions' GPU times waited behind work the runtime did not /// submit. pub surface_wait_submissions: u64, + /// Makes of a texture in place over host memory's import that restored the bytes under its + /// image (the two copies in + /// [`over_copies_host_memory_restore`](Self::over_copies_host_memory_restore)) and waited for + /// that restore on the make's thread ([`Buffer::new_texture`](crate::Buffer::new_texture), + /// [`Buffer::new_texture_in_place`](crate::Buffer::new_texture_in_place) and their fenced + /// forms), each counted once its wait returned. No Metal counterpart: Metal's make touches no + /// bytes and waits for nothing. + pub restoring_makes: u64, + /// The nanoseconds of [`host_time`](crate::host_time) the restoring makes given a + /// [`RestoreFence`](crate::RestoreFence) waited for the GPU work already submitted, before + /// the fence's `before`, in total: outside the span the fence holds. A make without a fence + /// makes no such wait. + pub restoring_make_drain_nanos: u64, + /// The nanoseconds of [`host_time`](crate::host_time) the restoring makes waited for their + /// restores, in total, inside the span a fence holds: from the flush of the uploads not yet + /// submitted, which carry the restore, to the end of the wait for the progress value that + /// flush gave. That wait holds the batch that carries the restore (every upload of any thread + /// not yet submitted, and the copies into the images of a group's textures over a buffer that + /// go in the same submission), the GPU work submitted ahead of it, and, for the + /// [`restoring_makes_shared`](Self::restoring_makes_shared), the group's first part. + pub restoring_make_wait_nanos: u64, + /// The runtime's submissions the restore waits waited for, in total: at each wait's start, + /// those the completion thread had not yet seen complete, through the one that carries the + /// restore, which is among them (a part of a group sent member by member, and a batch of + /// uploads with a progress value of its own, each count as one). More than one for a make: + /// its wait began behind work submitted ahead of its restore. + pub restoring_make_wait_submissions: u64, + /// Of the [`restoring_makes`](Self::restoring_makes), those whose restore went ahead of a + /// group's command buffers in uploads that use memory another API shares (an exported block's + /// or surface's, which an upload writes or holds, as a new buffer's zero fill in one, or which + /// a group's copy into a texture's image reads): such uploads signal no progress value of + /// their own, as that memory is the other API's again only at the release that ends the + /// group's first part, so the make waited for that part's command buffers too. + pub restoring_makes_shared: u64, + /// The nanoseconds of [`restoring_make_wait_nanos`](Self::restoring_make_wait_nanos) that + /// the [`restoring_makes_shared`](Self::restoring_makes_shared) waited. + pub restoring_make_shared_wait_nanos: u64, /// `vkQueueBindSparse` calls: one for each import over several dma-bufs /// (`Device::import_dma_bufs`, on Unix), binding its imports into its buffer. Each signals a /// value the next `vkQueueSubmit2` waits for. diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index f99df682f..a49c27405 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -143,6 +143,7 @@ mod releases_done; mod render; mod resolve; mod restore_batch; +mod restore_waits; mod ring; mod sample_positions; mod sampler; diff --git a/crates/metal2vulkan-runtime/src/tests/restore_waits.rs b/crates/metal2vulkan-runtime/src/tests/restore_waits.rs new file mode 100644 index 000000000..a1d5f2841 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/restore_waits.rs @@ -0,0 +1,278 @@ +//! A restoring make's waits in the device's metrics (`Metrics::restoring_makes` and the fields +//! after it), under a device cfg, on every device of the cfg's kind whose texture over host +//! memory's import is in place (`Device::import_host_memory`, `Device::has_unified_memory`). +//! +//! A make without a fence counts its wait for its restore and no wait before it; a fenced make +//! counts its wait for the GPU work already submitted too. Neither goes with uploads that use +//! memory another API shares, so neither counts among the shared makes. A make whose restore goes +//! ahead of a group's command buffers with such an upload, a new buffer's zero fill in an +//! exported block (`Device::new_exported_block`), counts among them, its wait in theirs: the test +//! pauses the submit thread (`Work::pause`), commits a fill of a buffer of its own, makes the +//! buffer in the export, and makes the texture on a thread of its own, whose restore is flushed +//! (`Work::flushing`), and the thread passes again, sending the three in one submission. + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod on_device { + use crate::tests::command::on_device::each_device; + use crate::tests::import::on_device::{free, host_memory, releasing, wait_until}; + use crate::texture::TextureObject; + use crate::{ + Block, Buffer, Device, ExportHandle, IndexClass, MemoryClass, Metrics, PixelFormat, + RestoreFence, Texture, TextureDescriptor, TextureType, TextureUsage, + }; + use std::alloc::Layout; + use std::ptr::NonNull; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{mpsc, Arc}; + use std::time::{Duration, Instant}; + + const WIDTH: u32 = 16; + const HEIGHT: u32 = 4; + + /// The length of the export the shared test makes a buffer in. + const LEN: u64 = 1 << 16; + + /// How long the make may take once the submit thread passes again. + const MAKE: Duration = Duration::from_secs(10); + + /// A fence that counts its calls. + #[derive(Default)] + struct Counted { + calls: u32, + } + + impl RestoreFence for Counted { + fn before(&mut self) -> Result<(), &'static str> { + self.calls += 1; + Ok(()) + } + + fn after(&mut self) { + self.calls += 1; + } + } + + /// A buffer over host memory's import whose textures are in place, so each make restores. + struct Over { + buffer: Buffer, + import: Block, + d: TextureDescriptor, + pitch: u64, + first: u32, + released: Arc, + mapping: (NonNull, Layout), + } + + impl Over { + /// The import and its buffer, with `makes` texture indices granted, where the device + /// imports host memory and takes a texture over it in place; `None`, said, elsewhere. + fn new(test: &str, name: &str, device: &Device, makes: u32) -> Option { + let Some(&(_, alignment)) = device.core().imports.host.as_ref() else { + println!("{test}: {name}: imports no host memory; skipped"); + return None; + }; + if !device.has_unified_memory() { + println!("{test}: {name}: not unified memory, so no restore; skipped"); + return None; + } + let answer = (device.minimum_linear_texture_alignment(PixelFormat::RGBA8Unorm)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let pitch = (u64::from(WIDTH) * 4).next_multiple_of(answer); + let len = (pitch * u64::from(HEIGHT)).next_multiple_of(alignment); + let (pointer, mapping) = host_memory(len, alignment); + let (release, released) = releasing(); + // SAFETY: the memory is the test's, allocated until it frees it after the import's + // release. + let (import, _) = unsafe { device.import_host_memory(pointer, len, release) } + .unwrap_or_else(|error| panic!("{name}: an import: {error}")); + let buffer = (device.new_buffer(import.id, 0, len, None)).expect("a buffer"); + let mut d = + TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, WIDTH, HEIGHT); + d.usage = TextureUsage::SHADER_READ; + let first = IndexClass::Texture.range().start; + (device.grant_indices(IndexClass::Texture, first, makes)).expect("a grant"); + let over = Over { + buffer, + import, + d, + pitch, + first, + released, + mapping, + }; + if over.make(0).copied_over().is_some() { + println!("{test}: {name}: the texture is the counted copy; skipped"); + over.end(device); + return None; + } + Some(over) + } + + /// A texture over the buffer at the `at`th index granted. + fn make(&self, at: u32) -> Texture { + (self + .buffer + .new_texture(&self.d, Some(self.first + at), 0, self.pitch)) + .unwrap_or_else(|error| panic!("a make: {error}")) + } + + /// Gives up the buffer and the import, and frees the memory once the import's release + /// came. + fn end(self, device: &Device) { + let Over { + buffer, + import, + released, + mapping, + .. + } = self; + drop((buffer, import)); + wait_until(device, "the release", || released.load(Ordering::SeqCst)); + free(mapping); + } + } + + /// What the restoring makes counted between `before` and `after`: the makes, their drain and + /// restore waits' nanoseconds, the submissions they waited for, the shared makes and their + /// waits' nanoseconds. + fn restores(before: &Metrics, after: &Metrics) -> [u64; 6] { + [ + after.restoring_makes - before.restoring_makes, + after.restoring_make_drain_nanos - before.restoring_make_drain_nanos, + after.restoring_make_wait_nanos - before.restoring_make_wait_nanos, + after.restoring_make_wait_submissions - before.restoring_make_wait_submissions, + after.restoring_makes_shared - before.restoring_makes_shared, + after.restoring_make_shared_wait_nanos - before.restoring_make_shared_wait_nanos, + ] + } + + #[test] + fn each_device_counts_a_restoring_makes_waits() { + each_device("restore_waits", |name, _, device| { + let Some(over) = Over::new("restore_waits", name, &device, 3) else { + return; + }; + let start = device.counters().metrics(); + let plain = over.make(1); + let between = device.counters().metrics(); + let [makes, drain, wait, submissions, shared, shared_wait] = restores(&start, &between); + println!( + "restore_waits: {name}: a make without a fence: {makes} make, drain {drain} ns, \ + wait {wait} ns for {submissions} submissions, {shared} shared ({shared_wait} ns)" + ); + assert_eq!(makes, 1, "{name}: the make counted"); + assert_eq!(drain, 0, "{name}: a make without a fence drains nothing"); + assert!(wait > 0, "{name}: the make's wait counted"); + assert!(submissions >= 1, "{name}: its own submission among them"); + assert_eq!((shared, shared_wait), (0, 0), "{name}: no shared upload"); + let mut fence = Counted::default(); + let fenced = (over.buffer).new_texture_fenced( + &over.d, + Some(over.first + 2), + 0, + over.pitch, + &mut fence, + ); + let fenced = fenced.unwrap_or_else(|error| panic!("{name}: a fenced make: {error}")); + assert_eq!(fence.calls, 2, "{name}: the fence's two calls"); + let end = device.counters().metrics(); + let [makes, drain, wait, submissions, shared, shared_wait] = restores(&between, &end); + println!( + "restore_waits: {name}: a fenced make: {makes} make, drain {drain} ns, wait \ + {wait} ns for {submissions} submissions, {shared} shared ({shared_wait} ns)" + ); + assert_eq!(makes, 1, "{name}: the fenced make counted"); + assert!(drain > 0, "{name}: the fenced make's drain counted"); + assert!(wait > 0, "{name}: the fenced make's wait counted"); + assert!(submissions >= 1, "{name}: its own submission among them"); + assert_eq!((shared, shared_wait), (0, 0), "{name}: no shared upload"); + drop((plain, fenced)); + over.end(&device); + }); + } + + #[test] + fn each_device_counts_a_restoring_make_behind_shared_memory() { + each_device("restore_waits_shared", |name, _, device| { + let Some(over) = Over::new("restore_waits_shared", name, &device, 2) else { + return; + }; + let Some(handle) = (ExportHandle::ALL.into_iter()) + .find(|&handle| device.new_exported_block(handle, LEN).is_ok()) + else { + println!("restore_waits_shared: {name}: exports no handle; skipped"); + over.end(&device); + return; + }; + let (export, _handle) = (device.new_exported_block(handle, LEN)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + // Its making goes now, so the submission the test looks at carries none. + (export.wait_until_ready()).unwrap_or_else(|error| panic!("{name}: {error}")); + let block = (device.take_block(MemoryClass::Shared, 256)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let filled = (device.new_buffer(block.id, 0, 256, None)).expect("a buffer"); + let queue = device.new_command_queue(4).expect("a queue"); + let core = device.core(); + let start = device.counters().metrics(); + core.work.pause(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); + (encoder.fill_buffer(&filled, 0..256, 7)) + .unwrap_or_else(|error| panic!("{name}: the fill: {error}")); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + // Zeroed by a GPU fill, an upload that holds the export. + let zeroed = (device.new_buffer(export.id, 0, LEN, Some(0))) + .unwrap_or_else(|error| panic!("{name}: a buffer in the export: {error}")); + let (sent, made) = mpsc::channel(); + std::thread::scope(|scope| { + let over = &over; + scope.spawn(move || { + let made = + over.buffer + .new_texture(&over.d, Some(over.first + 1), 0, over.pitch); + let _ = sent.send(made.map_err(|error| error.to_string())); + }); + let deadline = Instant::now() + MAKE; + while !core.work.flushing() { + if Instant::now() >= deadline { + core.work.resume(); + panic!("{name}: the make flushed no restore within {MAKE:?}"); + } + std::thread::sleep(Duration::from_millis(1)); + } + core.work.resume(); + let texture = (made.recv_timeout(MAKE)) + .unwrap_or_else(|_| panic!("{name}: the make did not return within {MAKE:?}")) + .unwrap_or_else(|error| panic!("{name}: the make: {error}")); + assert!( + texture.copied_over().is_none(), + "{name}: the texture in place, so the make restored" + ); + }); + let end = device.counters().metrics(); + let [makes, _, wait, submissions, shared, shared_wait] = restores(&start, &end); + println!( + "restore_waits_shared: {name}: {makes} make, wait {wait} ns for {submissions} \ + submissions, {shared} shared ({shared_wait} ns)" + ); + assert_eq!(makes, 1, "{name}: the make counted"); + assert_eq!( + shared, 1, + "{name}: the make's restore went ahead of the fill's command buffer with the \ + export's zero fill, which signals no value of its own" + ); + assert!(shared_wait > 0, "{name}: its wait counted"); + assert_eq!( + shared_wait, wait, + "{name}: the one make's wait is the shared one's" + ); + command_buffer + .wait_until_completed() + .unwrap_or_else(|error| panic!("{name}: the fill: {error}")); + assert_eq!(command_buffer.error(), None, "{name}: the fill"); + drop((queue, filled, block, zeroed, export)); + over.end(&device); + }); + } +}