diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 4788f04c4..a8b512373 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -18,7 +18,11 @@ //! new `VkCommandBuffer`s of the command buffer's pool, and puts what it recorded in the //! encoder's place: its recordings, uses, executions, keys and what its commands took (held //! weakly, as the commit holds them). The first recording is never submitted. No GPU work is -//! waited for. Rebinds on two threads take turns (`reencoding`); a rebind during another's +//! waited for, and no pipeline's making: a dispatch whose pipelines are being made leaves a +//! segment of its own, as the first encoding left one (`pending_dispatch.rs`), which the +//! submission or the host step records once they are made, so no Metal compile runs or is +//! waited for on the program's thread inside the rebind's call. +//! Rebinds on two threads take turns (`reencoding`); a rebind during another's //! turn marks the command buffer again, and its own turn encodes what moved since. A host step //! of the command buffer, which records into its pool on the scheduler's thread, takes the //! same turns: Vulkan synchronizes a pool's recordings externally. @@ -53,6 +57,7 @@ use crate::buffer::HostPages; use crate::deferred::{Deferred, StepInputs}; use crate::device::functions::Vk; use crate::encoder::{RecordedSegment, Replayed, ReplayedPart, Segment}; +use crate::pipeline::budget::Urgency; use crate::replay::Replay; use crate::residency::Residency; use crate::resource::ResourceKey; @@ -198,6 +203,28 @@ impl CommandBufferShared { } } } + // Each making a spliced dispatch's segment now waits for wakes the scheduler as it + // finishes, with no lock held, registered before the scheduler looks at the batches again + // (the wake at the end of this turn): a making that finished between that look and a + // later registration would leave the batch held with nothing to wake the scheduler. Its + // batch waits for them now, so they go before the makings nothing waits for, at the rank + // the commit asks for the first encoding's (`CommandBuffer::commit`). + let pending: Vec = { + let state = lock(&self.state); + (state.recorded.iter()) + .filter(|part| spliced.contains(&part.encoder)) + .flat_map(|part| part.segments.iter()) + .filter(|segment| segment.steps_after_pipelines()) + .map(|segment| segment.work.clone()) + .collect() + }; + if !pending.is_empty() { + let waker = device.shared().scheduler.waker(); + for work in &pending { + work.when_made(&waker); + work.hasten(Urgency::Committed); + } + } // Its work recorded on the GPU alone in encoders not encoded again that named a buffer // over host pages that lies elsewhere now, before its first submission (which alone // points their resident tables), each segment by its part and its place there, which @@ -284,10 +311,10 @@ impl State { /// and so does what its first segments recorded and what their host steps needed; its /// `VkCommandBuffer`s go with the pool unsubmitted. Refused, changing nothing and giving /// `replayed` back, where its place holds other parts than the encoding again's, or a segment - /// but a pending dispatch's (which goes, the encoding again having recorded it at once) or - /// work its commit recorded on the GPU alone, or its group was submitted, or the command - /// buffer completed. Its replays hold what its commands took with `device`, the device's - /// functions (`Replays::hold`). + /// but a pending dispatch's (which goes, the encoding again having left one of its own in its + /// place) or work its commit recorded on the GPU alone, or its group was submitted, or the + /// command buffer completed. Its replays hold what its commands took with `device`, the + /// device's functions (`Replays::hold`). pub(super) fn splice_replay( &mut self, device: &Vk, @@ -354,9 +381,10 @@ impl State { let recorded = &mut self.recorded[part]; recorded.raws = raws; recorded.summary = summary; - // Its first segments go: the encoding again recorded its pending dispatches at once, - // and its work on the GPU alone in segments of its own. What the commit recorded of - // one stays retained, never submitted, as the first recording does. + // Its first segments go: the encoding again left a segment of its own in each + // pending dispatch's place, and its work on the GPU alone in segments of its own. + // What the commit recorded of one stays retained, never submitted, as the first + // recording does. for segment in recorded.segments.drain(..) { if let Some(mut before) = segment.recorded { self.retained.extend(before.retained.into_entry()); diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 760520066..d18074c29 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -2355,8 +2355,9 @@ fn record( // The dispatch binds the variant: the kinds its making announces at every occurrence. let formats: BoundFormats<'_> = &|slot| bound_tables.bound_format(slot); // An encoder's own dispatch waits for no making: where one of its regions' pipelines is not - // made, it records later (`pending_dispatch.rs`). - // An encoder encoded again (`replay.rs`) waits for them, in the rebind's call. + // made, it records later (`pending_dispatch.rs`). An encoder encoded again (`replay.rs`) + // waits for none either, and leaves the same segment: the making is its submission's to wait + // for, as the first encoding left it, never the rebind's call on the program's thread. // Where the driver loses a layout's baked samplers after a copy in the same // `VkCommandBuffer` (`RuntimeDriverDefect::ImmutableSamplersLostAfterCopies`), a variant that // bakes them records in one of its own, as one being made does. @@ -2370,7 +2371,7 @@ fn record( // may submit again (`command_buffer/rerun.rs`), is not split for it; but where its variant // records in one of its own. let laying = core.command_buffer().state().predication_mut().laying(); - let waits = core.encodes_again() || (laying && !apart_samplers(&device, &objects)); + let waits = laying && !apart_samplers(&device, &objects); let (pipelines, pending) = match (own.filter(|_| !waits), kept_made) { (Some(_), Some(made)) => { if let Some(kept) = &kept { diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 885c2cfba..51e00cf93 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -162,16 +162,16 @@ impl Segment { } /// Whether it is a dispatch whose pipelines were being made (`pending_dispatch.rs`): an - /// encoder encoded again (`replay.rs`) records it at once, waiting for them, so it leaves no - /// segment there. + /// encoder encoded again (`replay.rs`) leaves one of its own in its place, prepared as the + /// commit prepared this one, and waits for no making. pub(super) fn pends(&self) -> bool { matches!(self.work, Deferred::Pending(_)) } - /// Whether an encoder encoded again (`replay.rs`) records it at once: a dispatch whose - /// pipelines were being made ([`pends`](Self::pends)), or work a commit may record on the GPU - /// alone, recorded there again (`Deferred::record_on_gpu`). Its log is kept only where every - /// segment does. + /// Whether an encoder encoded again (`replay.rs`) records its place: a dispatch whose + /// pipelines were being made ([`pends`](Self::pends)), left as a segment again, or work a + /// commit may record on the GPU alone, recorded there again (`Deferred::record_on_gpu`). Its + /// log is kept only where every segment does. pub(super) fn records_again(&self) -> bool { self.pends() || self.work.may_run_on_gpu_alone() } @@ -1681,7 +1681,9 @@ impl EncoderCore { } /// Whether it encodes an ended encoder's calls again ([`replaying`](Self::replaying)): its - /// dispatches wait for their pipelines, leaving no segment (`pending_dispatch.rs`). + /// tile dispatches wait for their pipelines, leaving no segment (`render/pending_tile.rs`). + /// Its compute dispatches wait for none, and leave the segment the first encoding left + /// (`pending_dispatch.rs`). pub(super) fn encodes_again(&self) -> bool { self.replaying } @@ -2179,6 +2181,17 @@ impl EncoderCore { let mut parts = Vec::with_capacity(split.len()); for ((raws, mut segments), summary) in split.into_iter().zip(summaries) { for segment in &mut segments { + // A dispatch whose pipelines are being made is left as the first encoding left + // it, prepared as its commit prepared that one (`Deferred::prepare`): recorded + // here where they are made, else by the host step once they are + // (`pending_dispatch.rs`). The rebind's call waits for no making. + if segment.pends() { + let prepared = segment.work.prepare(&open.command_buffer, false)?; + segment.recorded = prepared.recorded; + segment.inputs = Some(prepared.inputs); + segment.pipelines = prepared.pipelines; + continue; + } let recorded = segment.work.record_on_gpu(&open.command_buffer)?; let Some((recorded, inputs)) = recorded else { return Err(internal( diff --git a/crates/metal2vulkan-runtime/src/tests/rebind_making_wait.rs b/crates/metal2vulkan-runtime/src/tests/rebind_making_wait.rs index 34bc4a54b..554fcd10a 100644 --- a/crates/metal2vulkan-runtime/src/tests/rebind_making_wait.rs +++ b/crates/metal2vulkan-runtime/src/tests/rebind_making_wait.rs @@ -201,3 +201,141 @@ fn a_rebind_does_not_wait_for_the_making_its_encoding_again_meets() { fn a_rebind_waits_for_nothing_where_its_encoding_again_finds_the_pipeline_made() { leg(Warm::Made); } + +/// How long the command buffer is watched not to complete while its segment's making is held. +const WATCHED_COMPLETION: Duration = Duration::from_millis(500); + +/// The safety net: a second hold dropped after this, so a regression that makes the rebind block +/// again ends this test instead of wedging it while it holds the Mac's GPU lock. +const NET: Duration = Duration::from_secs(30); + +/// The segment the encoding again leaves is a pending dispatch's, awaited where the first +/// encoding's would have been: its command buffer cannot complete while the making is held, +/// though the rebind returned and the event was signalled, and once the making lands the segment +/// records and the dispatch's writes are in the pages the buffer lies in. +/// +/// This is the end-to-end witness that the segment survives `State::splice_replay` -- the splice +/// refuses a place whose parts or segments do not match, and a refusal would show here as +/// `EncodedUseRebound` instead. It is not the regression guard for the wait itself +/// ([`a_rebind_does_not_wait_for_the_making_its_encoding_again_meets`] is): the net below would +/// let a blocking rebind through. +#[test] +fn a_dispatch_the_encoding_again_left_as_a_segment_records_once_its_making_lands() { + // Declared before the device, so dropped after it. + let pages = [Page::new(), Page::new()]; + let scratch = Scratch::new("rebind-making-segment"); + let device: Device = device(&scratch.0); + let state = state(&device); + let queue = device.new_command_queue().unwrap(); + let bytes: Vec = (0..COUNT).flat_map(|i| (i as f32).to_le_bytes()).collect(); + let input = device + .new_buffer_with_bytes(&bytes, ResourceOptions::shared()) + .unwrap(); + let scale = device + .new_buffer_with_bytes(&SCALE.to_le_bytes(), ResourceOptions::shared()) + .unwrap(); + + // Two holds: the net's, dropped on its own after `NET`, and this test's, dropped where it + // means the making to land. A piece waits while either lives. + let net = held::hold(); + let hold = held::hold(); + let (past, wedged) = std::sync::mpsc::channel::<()>(); + let watchdog = std::thread::spawn(move || { + // Ends as soon as the test says it is past the rebind (the sender dropped), else after + // `NET`, which is the only case the net is for. + let _ = wedged.recv_timeout(NET); + drop(net); + }); + + // SAFETY: each page outlives every buffer over it (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( + pages[0].memory(), + BYTES as u64, + ResourceOptions::shared(), + None, + ) + }; + let output = match made { + Ok(buffer) => buffer, + Err(Error::Unsupported(gap)) => { + eprintln!("REBIND-MAKING-SEGMENT: the device imports no host memory: {gap:?}"); + drop(past); + drop(hold); + watchdog.join().unwrap(); + return; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + + let pooled = device.work_counts().dispatch_pipelines_pooled; + let gate = device.new_shared_event().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::Shared(&gate), 1) + .unwrap(); + dispatch(&command_buffer, &state, &input, &output, &scale); + command_buffer.commit().unwrap(); + assert_eq!( + device.work_counts().dispatch_pipelines_pooled, + pooled + 1, + "the dispatch's making waits in the held pool, so it left a pending segment" + ); + + assert_eq!( + output.detach_backing(), + Ok(true), + "the detach of a buffer whose only use waits for an event" + ); + // SAFETY: as above. + unsafe { output.rebind_bytes_no_copy(pages[1].memory(), None, None) }.unwrap(); + let counts = device.work_counts(); + assert_eq!( + (counts.encoders_reencoded, counts.reencodes_refused), + (1, 0), + "the rebind encoded the dispatch's encoder again, and the splice took it" + ); + + // Past the rebind: the net is not needed, and the watchdog ends. + drop(past); + + // Nothing of the GPU's holds it now: its batch waits for the making its segment records. + gate.set_signaled_value(1); + assert!( + command_buffer + .wait_until_completed_for(WATCHED_COMPLETION) + .is_err(), + "the command buffer completed though the making its segment records is held" + ); + assert_ne!( + command_buffer.status(), + CommandBufferStatus::Completed, + "the segment the encoding again left awaits its making, as the first encoding's would" + ); + assert!( + !pages[0].written() && !pages[1].written(), + "nothing ran while the making was held" + ); + + drop(hold); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let (status, error) = (command_buffer.status(), command_buffer.error()); + let (old, new) = (pages[0].written(), pages[1].written()); + println!("rebind-making-segment: {status:?} {error:?} old {old} new {new}"); + watchdog.join().unwrap(); + + assert!( + !old, + "the dispatch wrote the pages it was encoded over ({status:?}, {error:?})" + ); + assert_eq!( + error, None, + "the segment recorded and ran over the new pages" + ); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + new, + "the segment recorded once its making landed, over the pages the buffer lies in" + ); +} diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index f48e0b603..4ab3d61e0 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -8ee4fe7a9213f4d2756f630a27cf463a18d8c0e2a7c5d76017a9b8a587847070 +ba638aa7e192e5522e979d31d0203a5588a6feeaef62cc4d40b8db76b9962224 diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 86a0bb0e1..3c50c8f32 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 450; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1630; +pub const RUNTIME_VERSION: u32 = 1631; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles