diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 44a5bec05..0890aedb9 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -2904,7 +2904,8 @@ impl CommandBuffer { // The device's logs of host pages hear of its writes and gated copies in, in commit // order, and of the shadows its end left holding their truth (`dirty_pages.rs`). // One that waits for an event or a semaphore may run after work committed later, - // whose writes no commit before it noted: its copies in count on no hold. + // whose writes no commit before it noted: its copies in count on no hold, and its + // writes keep the logs they meet from holding until it completes. if device.shared().dirty.collects() { let held = match (&failure, &state.shadow_carry) { (None, Some(carry)) => carry.held_whole(), @@ -2912,10 +2913,13 @@ impl CommandBuffer { }; let waits = (state.batches.all().iter()) .any(|batch| !batch.waits.is_empty() || !batch.binary_waits.is_empty()); + // Such a one whose writes went unnoted, nothing collecting them as it encoded, + // counts as writing everything (`dirty_pages.rs`, **A waiting writer**). + let unnoted = self.0.unnoted.load(Ordering::Relaxed); device .shared() .dirty - .committed(&lock(&self.0.dirty), &held, waits); + .committed(&mut lock(&self.0.dirty), &held, waits, unnoted); } (segments, places, failure, reached, hangs) }; diff --git a/crates/metal2vulkan-runtime/src/dirty_pages.rs b/crates/metal2vulkan-runtime/src/dirty_pages.rs index c5f0fb9e6..c95864a92 100644 --- a/crates/metal2vulkan-runtime/src/dirty_pages.rs +++ b/crates/metal2vulkan-runtime/src/dirty_pages.rs @@ -31,6 +31,14 @@ //! batches complete, and at its completion ([`DirtyCommit::report_host_writes`]), but for the //! bytes its shadows' copies back report as their own. Metal's contract has a command reach a //! resource only through a binding or a residency it named. +//! - **A waiting writer.** A command buffer that waits for an event or a semaphore may run after +//! work committed after it. Its writes into the pages are reported at its commit, before that +//! work's stamps, so a hold a later commit takes (its image holding the truth as of its stamp) +//! would not count them, though they land after the image's copy. So its writes are kept +//! ([`WaitingWrites`]) until it completes, and while they meet a shadow's truth or the shadow, +//! that shadow's log takes no hold and gives none (`WorkCounts::dirty_holds_withheld`): a log +//! made after the commit too, since a shadow's log is made at its first copy in. Its completion +//! reports the writes again, and the next commit holds again. //! - **Correctness first.** A wait that answers `false`, a source that cannot say, and a copy //! that holds nothing it may count on all copy every byte. //! @@ -375,6 +383,27 @@ pub(crate) struct DirtyShadows { /// once one is ([`DirtyShadows::collects`]). imports: Mutex, imported: AtomicBool, + /// The writes of the committed command buffers not yet completed that wait for an event or a + /// semaphore ([`DirtyShadows::committed`]), each one's apart. + waiting: Mutex>>, +} + +/// A committed command buffer's writes, kept while it waits for an event or a semaphore and has +/// not completed (the module docs' **A waiting writer**): it may run after work committed after +/// it. +struct WaitingWrites { + written: Vec>, + /// Its writes were more than [`WRITES`], or went unnoted while nothing collected them: they + /// meet everything. + overflowed: bool, +} + +impl WaitingWrites { + /// Whether a write of them meets `copies`' truth or its shadow. + fn meets(&self, copies: &ShadowCopies) -> bool { + self.overflowed + || (self.written.iter()).any(|used| used.key == copies.shadow_key || copies.meets(used)) + } } /// The logs of host pages imported in place, by the key of each buffer whose uses name them, held @@ -399,6 +428,7 @@ pub(crate) struct DirtyTally { pub(crate) waits: AtomicU64, pub(crate) waits_unanswered: AtomicU64, pub(crate) wait_nanos: AtomicU64, + pub(crate) holds_withheld: AtomicU64, } /// The writers no other shadow or copy in the process is ever given. @@ -731,6 +761,11 @@ impl DirtyShadows { log.wrote_back(range.clone()); } commit.report_host_writes(); + // Its writes ran and were reported again, stamped after them: the logs they met may hold + // again from the next commit on. + if let Some(writes) = &commit.waiting { + lock(&self.waiting).retain(|kept| !Arc::ptr_eq(kept, writes)); + } if !failed { return; } @@ -757,14 +792,43 @@ impl DirtyShadows { /// the holds as they stand and a stamp each (no hold where it `waits` for an event or a /// semaphore: work committed after it may run before it), its writes let go of the holds of /// the shadows they meet, and the shadows its end left holding every texel of the truth - /// (`held`) hold from their stamp on. - pub(crate) fn committed(&self, commit: &DirtyCommit, held: &[Arc], waits: bool) { + /// (`held`) hold from their stamp on. Where it `waits`, its writes are kept until it + /// completed ([`WaitingWrites`]), and no log they meet holds or is held: it may run after a + /// later commit's work, whose hold its write, reported before that commit's stamp, would not + /// undo. Where some of its commands' writes went `unnoted`, nothing collecting them then, its + /// writes meet every log. + pub(crate) fn committed( + &self, + commit: &mut DirtyCommit, + held: &[Arc], + waits: bool, + unnoted: bool, + ) { + let overflowed = commit.overflowed || unnoted; + if waits && (overflowed || !commit.written.is_empty()) { + let writes = Arc::new(WaitingWrites { + written: commit.written.clone(), + overflowed, + }); + lock(&self.waiting).push(Arc::clone(&writes)); + commit.waiting = Some(writes); + } let DirtyCommit { written, gates, wrote, .. } = commit; + // Whether the writes of a command buffer that waits and has not completed, this one among + // them, meet `log`'s truth or shadow. + let waited = |log: &ShadowLog| { + let Some(copies) = log.copies.upgrade() else { + return false; + }; + lock(&self.waiting) + .iter() + .any(|writes| writes.meets(&copies)) + }; // One stamp per source and commit. let mut stamps: Vec<(Arc, DirtyStamp)> = Vec::new(); let mut stamp_of = |source: &Arc| { @@ -776,8 +840,8 @@ impl DirtyShadows { stamp }; let mut synced: Vec<(Arc, DirtyStamp)> = Vec::new(); - for gate in gates { - let since = match gate.written_before || waits { + for gate in gates.iter() { + let since = match gate.written_before || waits || waited(&gate.log) { true => None, false => *lock(&gate.log.hold), }; @@ -785,10 +849,9 @@ impl DirtyShadows { *lock(&gate.decision) = Some(Decision { since, stamp }); synced.push((Arc::clone(&gate.log), stamp)); } - for (log, range) in wrote { + for (log, range) in wrote.iter() { log.wrote_back(range.clone()); } - commit.report_host_writes(); let logs: Vec> = lock(&self.logs).clone(); for log in &logs { let Some(copies) = log.copies.upgrade() else { @@ -805,10 +868,17 @@ impl DirtyShadows { .copies .upgrade() .is_some_and(|copies| held.iter().any(|h| Arc::ptr_eq(h, &copies))); - if holds { - *lock(&log.hold) = Some(stamp); + if !holds { + continue; + } + match waited(&log) { + false => *lock(&log.hold) = Some(stamp), + true => { + self.tally.holds_withheld.fetch_add(1, Ordering::Relaxed); + } } } + commit.report_host_writes(); } } @@ -820,6 +890,9 @@ pub(crate) struct DirtyCommit { written: Vec>, gates: Vec>, wrote: Vec<(Arc, Range)>, + /// Its writes as the device keeps them while it waits for an event or a semaphore + /// ([`DirtyShadows::committed`]), let go of at its completion. + waiting: Option>, /// Its writes were more than [`WRITES`]: `written` holds the first alone. overflowed: bool, /// Its writes into host pages imported in place whose memory is logged: each pages' logs, diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 5629f0ebd..1427546bb 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -5059,6 +5059,11 @@ pub struct WorkCounts { pub dirty_waits_unanswered: u64, /// The nanoseconds the waits took, on the threads that submit and commit command buffers. pub dirty_wait_nanos: u64, + /// The holds of shadows over logged pages a commit left untaken, a command buffer committed + /// before it that waits for an event or a semaphore having written the shadow's truth and not + /// yet completed: it may run after the commit's work (`dirty_pages.rs`, **A waiting + /// writer**). + pub dirty_holds_withheld: u64, /// Of the keeps and merges among `shadow_copies`, those whose copy of the shadow's texels into /// the merge's scratch is the dispatch a copy back takes, where the device runs one faster /// than its copy (`DriverFact::ShadowCopyBackDispatchFaster`): the same bytes either way. @@ -6064,6 +6069,7 @@ impl Device { dirty_waits: dirty.waits.load(Ordering::Relaxed), dirty_waits_unanswered: dirty.waits_unanswered.load(Ordering::Relaxed), dirty_wait_nanos: dirty.wait_nanos.load(Ordering::Relaxed), + dirty_holds_withheld: dirty.holds_withheld.load(Ordering::Relaxed), shadow_merge_copies_dispatched: counters .shadow_merge_copies_dispatched .load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/cross_queue_shadows.rs b/crates/metal2vulkan-validation/src/runtime_lane/cross_queue_shadows.rs index c64f76fa4..69a22645e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/cross_queue_shadows.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/cross_queue_shadows.rs @@ -1,6 +1,7 @@ -//! A shadowed texture's image carried across one command buffer's encoders, where command buffers -//! of two queues meet the texture or the CPU writes its bytes while one runs (the runtime's -//! `shadow::ShadowCarry`), on the device the cfg selects under the validation layer. The texture is the one `parallel_encodes` uses: 8x8 `RGBA8Unorm` at rows 48 +//! A shadowed texture's image carried across one command buffer's encoders, and a log's hold of +//! logged guest pages, where command buffers of two queues meet the texture (the runtime's +//! `shadow::ShadowCarry` and `dirty_pages.rs`), on the device the cfg selects under the +//! validation layer. The texture is the one `parallel_encodes` uses: 8x8 `RGBA8Unorm` at rows 48 //! bytes apart, 16 bytes past its texels, so it is a shadow on every device. //! //! - **Another queue's encoder in between, a CPU write while it runs.** Command buffer X of queue @@ -21,6 +22,13 @@ //! The CPU waits until the event reads signalled, then writes the buffer. On the M3 Max (macOS //! 27.0.1) Metal's read after the signal took the write in both shapes, as an encoder after a //! batch split does here: it copies in before its read, which runs after the spin. +//! - **A waiting writer under a hold.** Over logged guest pages (`HostMemory::with_dirty_pages`), +//! command buffer Y of queue 2 waits for an event, fills a row of the texture's bytes, and then +//! spins, so it completes late. Command buffer X of queue 1, committed after Y, reads the +//! texture and signals the event: its end holds the texture whole, the hold its commit gives the +//! log. Command buffer Z of queue 1, committed after X, reads it: the tracker runs it after Y's +//! fill, and its read holds the fill, though the fill was reported to the log at Y's commit, +//! before X's hold. //! //! The spin is the owned fixture `kernel_spin_on_an_unraised_word`, dispatched again and again to //! a cap of loads timed on the device beforehand ([`Spin`]). The GPU does not see a CPU store to @@ -29,9 +37,10 @@ //! Metal ended one native dispatch of about 1.5 s the same way, and some of about 0.5 s, so the //! spin is many short dispatches. +use super::host_memory::{Mapping, GUEST_PAGE}; use super::parallel_encodes::{ - completed, texel_dispatch, texel_kernels, texels_of, Rng, TexelKernels, BYTES, ROW, SIDE, - TEXEL_ROW, WORDS, + completed, gated, texel_dispatch, texel_kernels, texels_of, GuestLog, Rng, TexelKernels, BYTES, + ROW, SIDE, TEXEL_ROW, WORDS, }; use super::{ buffer_with, layer_reported_nothing_at_all, read_buffer, validated_device_with, Messages, @@ -43,9 +52,11 @@ use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan_devtools::llvm_assemble; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandBufferStatus, ComputeCommandEncoder, ComputePipelineState, - Device, EventRef, PipelineOptions, Size, Texture, TextureDescriptor, + Device, EventRef, HostMemory, PipelineOptions, ResourceOptions, Size, Texture, + TextureDescriptor, }; use std::path::Path; +use std::sync::Arc; use std::time::{Duration, Instant}; /// About how long a spin runs on the GPU: far past the CPU's write, made [`SETTLE`] after the @@ -406,3 +417,80 @@ fn a_cpu_write_once_a_signal_was_seen_reaches_the_reads_after_it() { drop(device); layer_reported_nothing_at_all(&messages); } + +/// A command buffer that waits for an event writes logged pages a shadowed texture lies in, and +/// runs after a command buffer committed after it took the log's hold: a third command buffer's +/// gated copy in still takes the write (the module docs). +#[test] +fn a_write_of_logged_pages_after_an_event_wait_reaches_a_copy_in_behind_a_later_hold() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + let (device, kernels, spin) = lane(&messages, &cache); + let (first, second) = ( + device.new_command_queue().unwrap(), + device.new_command_queue().unwrap(), + ); + let mapping = Mapping::anonymous(GUEST_PAGE); + let initial = Rng(0x9A6E).bytes(BYTES); + mapping.write(0, &initial); + let log = Arc::new(GuestLog::default()); + log.told(0..BYTES); + // SAFETY: the mapping outlives the buffer, dropped first, and stays writable. + let memory = unsafe { HostMemory::new(mapping.pointer()) }.with_dirty_pages(Arc::clone(&log)); + // SAFETY: as above. + let pages = unsafe { + device.new_buffer_with_bytes_no_copy( + memory, + GUEST_PAGE as u64, + ResourceOptions::default(), + None, + ) + } + .unwrap(); + let texture = shadowed(&device, &pages); + let event = device.new_event().unwrap(); + let (row, value) = (3, 0xa5); + let reads = [(); 2].map(|_| read_target(&device)); + let before = gated(&device.work_counts()); + let withheld = device.work_counts().dirty_holds_withheld; + let y = second.command_buffer().unwrap(); + y.encode_wait_for_event(EventRef::Event(&event), 1).unwrap(); + fill_row(&y, &pages, row, value); + spin.encode(&y); + y.commit().unwrap(); + let x = first.command_buffer().unwrap(); + texel_dispatch(&x, &kernels.read, &texture, &reads[0]); + x.encode_signal_event(EventRef::Event(&event), 1).unwrap(); + x.commit().unwrap(); + let z = first.command_buffer().unwrap(); + texel_dispatch(&z, &kernels.read, &texture, &reads[1]); + z.commit().unwrap(); + for command_buffer in [&x, &y, &z] { + completed(command_buffer); + } + let after = gated(&device.work_counts()); + let name = device.name().to_owned(); + let counts: [u64; 5] = std::array::from_fn(|i| after[i] - before[i]); + let withheld = device.work_counts().dirty_holds_withheld - withheld; + println!( + "CROSS-QUEUE-HOLD on {name}: gated copies in (gated, whole, skipped, bytes whole, bytes \ + copied) {counts:?}, holds withheld {withheld}, the spin {} dispatches of {} loads", + spin.dispatches, spin.cap + ); + assert!(counts[0] > 0, "the copies in were gated"); + assert!( + withheld > 0, + "X's hold was withheld while Y, which waits, had not completed" + ); + let read = |at: usize| read_buffer(&reads[at], 0, 4 * WORDS).unwrap(); + assert_eq!(read(0), texels_of(&initial), "X's read, before the signal"); + assert_eq!( + read(1), + texels_of(&filled(&initial, row, value)), + "Z's read, after Y's fill" + ); + drop((texture, pages, first, second, kernels, spin, event)); + drop(device); + drop(mapping); + layer_reported_nothing_at_all(&messages); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 00abbe4ad..2207cd834 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2581,6 +2581,7 @@ field metal2vulkan-runtime::WorkCounts.dirty_copies_in_skipped pub dirty_copies_ field metal2vulkan-runtime::WorkCounts.dirty_copies_in_whole pub dirty_copies_in_whole: u64 field metal2vulkan-runtime::WorkCounts.dirty_copy_in_bytes_copied pub dirty_copy_in_bytes_copied: u64 field metal2vulkan-runtime::WorkCounts.dirty_copy_in_bytes_whole pub dirty_copy_in_bytes_whole: u64 +field metal2vulkan-runtime::WorkCounts.dirty_holds_withheld pub dirty_holds_withheld: u64 field metal2vulkan-runtime::WorkCounts.dirty_stamps_asked pub dirty_stamps_asked: u64 field metal2vulkan-runtime::WorkCounts.dirty_wait_nanos pub dirty_wait_nanos: u64 field metal2vulkan-runtime::WorkCounts.dirty_waits pub dirty_waits: u64