diff --git a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs index 1bb847173..83c8a6bc7 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs @@ -38,8 +38,11 @@ //! nothing and the command buffer completes with `CommandBufferError::EncodedUseRebound`, every //! other submission running, its signals firing and its handlers running: the gap until the //! encoded uses resolve at submission, announced once -//! (`Degradation::EncodedUseRebound`). A GPU-alone replay's resident set, resolved at the -//! commit (`gpu_execute.rs`), fails alike where a range of it lies elsewhere by then. +//! (`Degradation::EncodedUseRebound`). Work recorded on the GPU alone, whose preprocess's +//! resident set and named buffers the commit resolved (`gpu_execute.rs`, +//! `render/executions/gpu.rs`), is recorded again at each rebind before then (`reencode.rs`); +//! it fails alike where a range of that set lies elsewhere by then all the same (a buffer of it +//! released meanwhile), or the rebind could not record it on the GPU alone again. //! - **Each submission at its own batch**. The first submission finds which of Metal's submissions //! are rebound, against the pages and the table it fixes for every later batch; each fails only //! as its own batch is submitted, after that batch's submission checks (`checks.rs`). One its diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index bb871dd54..ca00d5eec 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -1162,6 +1162,7 @@ impl State { retained, pipelines, } = prepared; + segment.gpu_alone = for_good && recorded.is_some(); segment.recorded = recorded; segment.stepped |= for_good; segment.pipelines |= pipelines; @@ -1948,6 +1949,14 @@ impl CommandBuffer { if !keys.is_empty() { device.shared().rebinds.wait_for_replay(&self.0, keys); } + // So does any rebind its work recorded on the GPU alone, whose resident set the + // commit resolved. + let gpu_alone = (state.recorded.iter()) + .flat_map(|part| &part.segments) + .any(|segment| segment.gpu_alone); + if gpu_alone { + device.shared().rebinds.wait_for_rerecord(&self.0); + } if let Some(slot) = &mut state.slot { slot.committed(); } @@ -2596,6 +2605,8 @@ impl CommandBufferShared { Ok(done) => { let segment = &mut state.recorded[encoder].segments[at]; segment.stepped = true; + // Its recording is the step's now, which a rebind does not record again. + segment.gpu_alone = false; let before = segment.recorded.replace(done); if let Some(mut before) = before { state.retained.extend(before.retained.into_entry()); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 53b8eaf86..f709e2bda 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -18,15 +18,28 @@ //! 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. +//! - **Work recorded on the GPU alone, recorded again.** Work its commit recorded on the GPU +//! alone, for good (a GPU-written execution's preprocess and its dispatches or draws, +//! `gpu_execute.rs`, `render/executions/gpu.rs`), resolved there what its commands named and +//! the resident set its preprocess searches: the live buffers and what the encoders made +//! resident, as they lay then. Its commit notes the command buffer for any rebind +//! (`Rebinds::wait_for_rerecord`), and each rebind before the first submission records that +//! work again in its place, as the commit did, over where the buffers lie now: its +//! recording, what its commands took and what its host step needs. Its encoder, which logs +//! nothing, stays as it was, and so does such work a host step recorded again since (with +//! the barriers between its commands, `gpu_execute::Rerecord`, or as a route outgrew it, +//! `DeferredPass::outgrown`). //! - **What cannot be encoded again stays as before.** An encoder whose log is gone (a command //! predication's command buffer, failed at the commit) or whose second //! encoding is refused or records otherwise (`EncoderCore::finish_replay`) keeps its first //! recording, which the first submission finds rebound: `CommandBufferError::EncodedUseRebound`, -//! as before. So does any encoder of a kind that logs nothing (a render encoder's). +//! as before. So does any encoder of a kind that logs nothing (a render encoder's), past its +//! work recorded on the GPU alone, and such work the rebind no longer records there. use super::{lock, CommandBuffer, CommandBufferShared, State}; +use crate::deferred::{Deferred, StepInputs}; use crate::device::functions::Vk; -use crate::encoder::{Replayed, Segment}; +use crate::encoder::{RecordedSegment, Replayed, Segment}; use crate::replay::Replay; use crate::residency::Residency; use crate::resource::ResourceKey; @@ -48,10 +61,11 @@ impl CommandBufferShared { } /// Encode again each of its encoders that a command of named a buffer over host pages that - /// lies elsewhere now than the command took it (the module docs), on the rebind's thread, - /// with no lock of the runtime's held; then its first submission may go, and the scheduler - /// looks again. Nothing here fails the rebind: an encoder it cannot encode again keeps its - /// first recording, which its first submission fails. + /// lies elsewhere now than the command took it, and record again the work its commit + /// recorded on the GPU alone (the module docs), on the rebind's thread, with no lock of the + /// runtime's held; then its first submission may go, and the scheduler looks again. Nothing + /// here fails the rebind: an encoder it cannot encode again, or work it cannot record on the + /// GPU alone again, keeps its first recording, which its first submission fails. pub(crate) fn reencode(self: &Arc) { let turn = lock(&self.reencoding); let marked = self.reencode.load(Ordering::Acquire); @@ -99,6 +113,42 @@ impl CommandBufferShared { } } } + // Its work recorded on the GPU alone, each segment by its part and its place there, + // which hold through this turn: only the first submission places segments, and it waits + // for the turn; a host step, which records one, takes the turn too. + let alone: Vec<((usize, usize), Deferred)> = { + let state = lock(&self.state); + match state.submitted { + true => Vec::new(), + false => (state.recorded.iter().enumerate()) + .flat_map(|(part, recorded)| { + let segments = recorded.segments.iter().enumerate(); + segments + .filter(|(_, segment)| segment.gpu_alone && segment.recorded.is_some()) + .map(move |(at, segment)| ((part, at), segment.work.clone())) + }) + .collect(), + } + }; + for (place, work) in alone { + // Its notices were announced as it committed (`replay::is_replaying`), and its + // commands take what they use without holding it. + let again = crate::replay::replaying(|| work.record_on_gpu(&handle)); + let counts = &device.shared().counts; + let Ok(Some((recorded, inputs))) = again else { + counts.reencode_refused(); + continue; + }; + let vk = device.shared().vk(); + let spliced = lock(&self.state).splice_segment(vk, place, recorded, inputs); + match spliced { + Ok(()) => counts.segment_recorded_again(), + Err(unspliced) => { + counts.reencode_refused(); + drop(unspliced); + } + } + } drop(handle); // Its first submission may go, unless a rebind marked it meanwhile: that rebind's turn // comes next and encodes what moved since. @@ -230,6 +280,50 @@ impl State { Ok(()) } + /// Put `recorded`, segment `at` of part `part` recorded again on the GPU alone, in its place + /// before the first submission, with `inputs`, what its host step needs now: what its + /// commands took held weakly until the first submission, as the commit holds them (by its + /// replays too, with `device`, the device's functions: `Replays::hold`). What the first + /// recording retained, its executions and its host step's inputs stay retained; its + /// `VkCommandBuffer`s go with the pool unsubmitted, and what its commands took, held weakly, + /// goes. Refused, changing nothing and giving `recorded` and `inputs` back, where the place + /// holds no such segment, or the command buffer was submitted. + pub(super) fn splice_segment( + &mut self, + device: &Vk, + (part, at): (usize, usize), + mut recorded: RecordedSegment, + inputs: StepInputs, + ) -> Result<(), Box<(RecordedSegment, StepInputs)>> { + let fits = !self.submitted + && (self.recorded.get(part)) + .and_then(|recorded| recorded.segments.get(at)) + .is_some_and(|segment| segment.gpu_alone && segment.recorded.is_some()); + if !fits { + return Err(Box::new((recorded, inputs))); + } + match self.replays.clone() { + Some(replays) => drop(replays.hold(device, |pages| recorded.taken.wait(pages))), + None => recorded.taken.wait(&mut Vec::new()), + } + let segment = &mut self.recorded[part].segments[at]; + let first = segment.recorded.replace(recorded); + let before = segment.inputs.replace(inputs); + if let Some(first) = first { + let RecordedSegment { + retained, + executions, + .. + } = first; + self.retained.extend(retained.into_entry()); + self.retained.push(Box::new(executions)); + } + if let Some(before) = before { + self.retained.push(Box::new(before)); + } + Ok(()) + } + /// As it commits: the logs of encoders no rebind encodes again go, for the caller to let go /// of without this lock: every log where an encoder used command predication, and those of /// encoders the commit's failure fails (they run nothing). The keys the encoders whose logs diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index d606b68fe..676248c8d 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -141,14 +141,11 @@ impl Deferred { // On the GPU alone where it is total (`gpu_execute.rs`): not a checked execution, // whose step reads its records for the caller's check, nor one inside a block of // command predication without its preprocess's gate, whose step reads the counter. - if let Some((recorded, rerecord)) = gpu_execute::record(command_buffer, execute)? { + if let Some((recorded, inputs)) = self.record_on_gpu(command_buffer)? { return Ok(Prepared { recorded: Some(recorded), for_good: true, - inputs: match rerecord { - Some(rerecord) => StepInputs::Rerecord(rerecord), - None => StepInputs::Settled(Vec::new()), - }, + inputs, retained: None, pipelines: false, }); @@ -203,11 +200,11 @@ impl Deferred { // The step waits for the pipelines its draws record too (`render/pending.rs`). // And makes now what the step would make (`render/executions/ahead.rs`). Deferred::RenderPass(pass) if step => { - if let Some(recorded) = pass.record_on_gpu(command_buffer)? { + if let Some((recorded, inputs)) = self.record_on_gpu(command_buffer)? { return Ok(Prepared { recorded: Some(recorded), for_good: true, - inputs: StepInputs::RenderPass, + inputs, retained: None, pipelines: false, }); @@ -264,6 +261,33 @@ impl Deferred { } } + /// Its recording on the GPU alone, for good, with what its host step needs, where it runs + /// there over the buffers as they lie now (`gpu_execute.rs`, `DeferredPass::record_on_gpu`); + /// `None` where it does not, or is work that never runs there. With no lock of + /// `command_buffer` held: at the commit, and at a rebind before the command buffer's first + /// submission, which records it again (`command_buffer/reencode.rs`). + pub(super) fn record_on_gpu( + &self, + command_buffer: &CommandBuffer, + ) -> Result, Error> { + match self { + Deferred::Execute(execute) => { + let recorded = gpu_execute::record(command_buffer, execute)?; + Ok(recorded.map(|(recorded, rerecord)| { + let inputs = match rerecord { + Some(rerecord) => StepInputs::Rerecord(rerecord), + None => StepInputs::Settled(Vec::new()), + }; + (recorded, inputs) + })) + } + Deferred::RenderPass(pass) => Ok(pass + .record_on_gpu(command_buffer)? + .map(|recorded| (recorded, StepInputs::RenderPass))), + Deferred::Dispatch(_) | Deferred::SparseScrub(_) | Deferred::Pending(_) => Ok(None), + } + } + /// Its host step, on the scheduler's thread with no lock of `command_buffer` held: its /// recording from what it reads now and `inputs`. An execution's records name their states /// among those `commit` settled, or for one `commit` recorded from the CPU's records, those diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index c58cb3682..d45c78154 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -111,6 +111,11 @@ pub(super) struct Segment { /// `commit` left its recording to the host step for the pipelines it records, which were /// being made then (`render/pending.rs`). pub(super) pipelines: bool, + /// `commit` recorded it on the GPU alone, for good (`Prepared::for_good`), and no host step + /// recorded it since: its resident set and what its commands named were resolved then, so a + /// rebind before the command buffer's first submission records it again + /// (`command_buffer/reencode.rs`). + pub(super) gpu_alone: bool, } impl Segment { @@ -259,8 +264,9 @@ pub(super) struct EncoderCore { twin_writes: Vec, /// The core's own number in the process ([`id`](Self::id)). id: u64, - /// It encodes an ended encoder's calls again, its command buffer committed (`replay.rs`): - /// its commands take what they use without holding it (`Rebinds::pin`). + /// It encodes an ended encoder's calls again, its command buffer committed (`replay.rs`), or + /// records again work a commit recorded (`command_buffer/reencode.rs`): its commands take + /// what they use without holding it (`Rebinds::pin`). replaying: bool, /// The set 0 its last command allocated and wrote, which a later command that writes the same /// into a set of the same layout binds again ([`set_zero`](Self::set_zero)). @@ -442,7 +448,8 @@ impl EncoderCore { twin_writes: Vec::new(), aliased_uses: Vec::new(), id: CORES.fetch_add(1, Ordering::Relaxed), - replaying: false, + // A segment a rebind records again, its command buffer committed. + replaying: crate::replay::is_replaying(), last_set_zero: LastSetZero::default(), _not_sync: PhantomData, }) @@ -1418,6 +1425,7 @@ impl EncoderCore { recorded: None, stepped: false, pipelines: false, + gpu_alone: false, }); Ok(()) } diff --git a/crates/metal2vulkan-runtime/src/executed_commands.rs b/crates/metal2vulkan-runtime/src/executed_commands.rs index 38bfdaf8b..04fca314d 100644 --- a/crates/metal2vulkan-runtime/src/executed_commands.rs +++ b/crates/metal2vulkan-runtime/src/executed_commands.rs @@ -39,7 +39,9 @@ pub enum RecordsRead { /// Not on the host: the GPU reads them as it runs (`gpu_execute.rs`), so /// [`ExecutedCommands::commands`] is empty and /// [`ExecutedCommands::unread_states_can_encode`] tells of every state the records may name. - /// Decided in `commit`, on the committing thread. + /// Decided in `commit`, on the committing thread, and again on the thread of each rebind of + /// a buffer over host pages before the command buffer's first submission, which records the + /// execution again. Gpu, } diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index 590128654..c98b79f5d 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -114,21 +114,43 @@ pub(super) struct Rebinds { pub(super) stale_count: AtomicUsize, /// The command buffers committed and not yet first submitted that an encoder of theirs can /// encode again (`replay.rs`), with the keys of the buffers over host pages those encoders - /// named: a rebind of one of them has them encoded again before their first submission. + /// named: a rebind of one of them has them encoded again before their first submission. And + /// those with work recorded on the GPU alone, which any rebind has recorded again. /// Taken under `buffers`' lock, after it. waiting: Mutex, } /// The command buffers waiting for their first submission whose encoders a rebind encodes again -/// ([`Rebinds::wait_for_replay`]), each with the keys its replayable encoders named, sorted. +/// ([`Rebinds::wait_for_replay`]), each with the keys its replayable encoders named, sorted; and +/// those whose work recorded on the GPU alone a rebind records again +/// ([`Rebinds::wait_for_rerecord`]). #[derive(Default)] struct Waiting { buffers: Vec<(Weak, Box<[ResourceKey]>)>, + /// The command buffers committed with work recorded on the GPU alone (a GPU-written + /// execution's preprocess and its draws or dispatches) and not yet first submitted: its + /// resident set was resolved at the commit, so a rebind of any buffer before the first + /// submission records that work again ([`Rebinds::wait_for_rerecord`]). + resolved: Vec>, /// The length past which the next registration first lets go of the entries whose command /// buffer went or was submitted. prune_at: usize, } +impl Waiting { + /// Before a registration: where the entries reached `prune_at`, let go of those whose + /// command buffer went before its first submission (its submission failed first), never + /// upgraded, so none goes under the lock. + fn prune(&mut self) { + if self.buffers.len() + self.resolved.len() < self.prune_at { + return; + } + self.buffers.retain(|(buffer, _)| buffer.strong_count() > 0); + self.resolved.retain(|buffer| buffer.strong_count() > 0); + self.prune_at = (2 * (self.buffers.len() + self.resolved.len())).max(16); + } +} + /// A texture over detached bytes whose unnamed reads a submission's reach may not answer as /// Metal's (`Rebinds::stale`, `Device::note_stale`): the texture (by type erased, /// `buffer::NotedTexture`), its object's ID, the hold on the pages of the bytes, whose rebind @@ -243,17 +265,20 @@ impl Rebinds { keys: Box<[ResourceKey]>, ) { let mut waiting = lock(&self.waiting); - // A command buffer that went before its first submission (its submission failed - // first) leaves its entry: let go of here, never upgraded, so none goes under the lock. - if waiting.buffers.len() >= waiting.prune_at { - waiting - .buffers - .retain(|(buffer, _)| buffer.strong_count() > 0); - waiting.prune_at = (2 * waiting.buffers.len()).max(16); - } + waiting.prune(); waiting.buffers.push((Arc::downgrade(buffer), keys)); } + /// Note `buffer`, committed now and not yet first submitted, with work recorded on the GPU + /// alone: a rebind of any buffer before its first submission records that work again + /// ([`Rebinds::replace`], `command_buffer/reencode.rs`). Its first submission lets go of it + /// ([`Submitting::submitted_now`]). + pub(super) fn wait_for_rerecord(&self, buffer: &Arc) { + let mut waiting = lock(&self.waiting); + waiting.prune(); + waiting.resolved.push(Arc::downgrade(buffer)); + } + /// Whether one of `keys` names a detached buffer (`detach.rs`): at no cost while none is. pub(super) fn any_detached(&self, keys: impl IntoIterator) -> bool { if self.detached.load(Ordering::Acquire) == 0 { @@ -350,9 +375,10 @@ impl Rebinds { /// Give the buffer of `key`, whose hold on its pages is `cell`, `pages` from now on, unless /// a hold refuses it: where it lay (a detached one is attached again), and the command /// buffers waiting for their first submission whose replayable encoders named it - /// ([`Rebinds::wait_for_replay`]), each marked under this lock to encode them again before - /// that submission (`CommandBufferShared::reencode`), which the caller runs; `Err` gives - /// `pages` back. + /// ([`Rebinds::wait_for_replay`]) or that hold work recorded on the GPU alone, whose resident + /// set held where it lay ([`Rebinds::wait_for_rerecord`]), each marked under this lock to + /// encode or record them again before that submission (`CommandBufferShared::reencode`), + /// which the caller runs; `Err` gives `pages` back. pub(super) fn replace( &self, key: ResourceKey, @@ -376,16 +402,20 @@ impl Rebinds { // Marked before this lock goes, so a first submission either came before the rebind // (and keeps the old pages) or waits for the encoders encoded again. // Each upgraded one goes to the caller, which lets go of it without this lock. - let mut again = Vec::new(); + let mut again: Vec> = Vec::new(); let waiting = lock(&self.waiting); - for (buffer, keys) in &waiting.buffers { - if keys.binary_search(&key).is_err() { + let named = (waiting.buffers.iter()) + .filter(|(_, keys)| keys.binary_search(&key).is_ok()) + .map(|(buffer, _)| buffer); + for buffer in named.chain(&waiting.resolved) { + let Some(buffer) = buffer.upgrade() else { + continue; + }; + if again.iter().any(|had| Arc::ptr_eq(had, &buffer)) { continue; } - if let Some(buffer) = buffer.upgrade() { - buffer.mark_reencode(); - again.push(buffer); - } + buffer.mark_reencode(); + again.push(buffer); } Ok((lying, again)) } @@ -455,6 +485,9 @@ impl Submitting<'_> { waiting .buffers .retain(|(waiting, _)| !std::ptr::eq(Weak::as_ptr(waiting), buffer)); + waiting + .resolved + .retain(|waiting| !std::ptr::eq(Weak::as_ptr(waiting), buffer)); } /// Judge `taken`, and hold every pin whose pages still live in `retained` until the command diff --git a/crates/metal2vulkan-runtime/src/replay.rs b/crates/metal2vulkan-runtime/src/replay.rs index 102d87b1c..01409b0d2 100644 --- a/crates/metal2vulkan-runtime/src/replay.rs +++ b/crates/metal2vulkan-runtime/src/replay.rs @@ -709,8 +709,9 @@ thread_local! { static REPLAYING: Cell = const { Cell::new(0) }; } -/// Run `f`, which encodes an encoder again, marked ([`is_replaying`]). -fn replaying(f: impl FnOnce() -> T) -> T { +/// Run `f`, which encodes an encoder again, or records again work its commit recorded +/// (`command_buffer/reencode.rs`), marked ([`is_replaying`]). +pub(crate) fn replaying(f: impl FnOnce() -> T) -> T { /// Ends the mark as `f` returns or unwinds. struct Mark; impl Drop for Mark { @@ -723,8 +724,9 @@ fn replaying(f: impl FnOnce() -> T) -> T { f() } -/// Whether this thread is encoding an encoder again now: its notices were announced as the -/// program encoded it (`Device::degrade`). +/// Whether this thread is encoding an encoder again now, or recording again work a commit +/// recorded: its notices were announced as the program encoded it, or as it committed +/// (`Device::degrade`). pub(crate) fn is_replaying() -> bool { REPLAYING.with(Cell::get) > 0 } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index b619ae8da..2deadc8b1 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -311,6 +311,7 @@ pub(crate) struct Counters { replay_logs_kept: AtomicU64, replay_log_bytes: AtomicU64, encoders_reencoded: AtomicU64, + segments_recorded_again: AtomicU64, reencodes_refused: AtomicU64, pipeline_libraries_made: AtomicU64, fragment_shader_libraries_made: AtomicU64, @@ -2019,7 +2020,14 @@ impl Counters { self.encoders_reencoded.fetch_add(1, Ordering::Relaxed); } - /// A rebind could not encode an ended encoder again, which keeps its first recording. + /// A rebind recorded again work its command buffer's commit recorded on the GPU alone + /// (`command_buffer/reencode.rs`). + pub(crate) fn segment_recorded_again(&self) { + self.segments_recorded_again.fetch_add(1, Ordering::Relaxed); + } + + /// A rebind could not encode an ended encoder again, or record again work recorded on the + /// GPU alone, which keeps its first recording. pub(crate) fn reencode_refused(&self) { self.reencodes_refused.fetch_add(1, Ordering::Relaxed); } @@ -3576,9 +3584,12 @@ pub struct WorkCounts { /// Ended encoders a rebind encoded again before their command buffer's first submission /// (`command_buffer/reencode.rs`). pub encoders_reencoded: u64, + /// Work a command buffer's commit recorded on the GPU alone (a GPU-written execution's) that + /// a rebind before its first submission recorded again (`command_buffer/reencode.rs`). + pub segments_recorded_again: u64, /// Ended encoders a rebind could not encode again (a call refused the second time, or a - /// recording unlike the first), which keep their first recording and fail - /// `EncodedUseRebound`. + /// recording unlike the first), and work recorded on the GPU alone it could not record there + /// again, which keep their first recording and fail `EncodedUseRebound`. pub reencodes_refused: u64, /// Fences made to end command buffers, where none was idle (`command_buffer/fences.rs`): /// none on a driver that reads no command buffer's objects after its value, whose queues' @@ -4151,6 +4162,7 @@ impl Device { replay_logs_kept: counters.replay_logs_kept.load(Ordering::Relaxed), replay_log_bytes: counters.replay_log_bytes.load(Ordering::Relaxed), encoders_reencoded: counters.encoders_reencoded.load(Ordering::Relaxed), + segments_recorded_again: counters.segments_recorded_again.load(Ordering::Relaxed), reencodes_refused: counters.reencodes_refused.load(Ordering::Relaxed), fences_made: self.shared().fences.made(), pipeline_libraries_made: counters.pipeline_libraries_made.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/dispatch_executions.rs b/crates/metal2vulkan-validation/src/runtime_lane/dispatch_executions.rs index 0a8956454..2bad41d7b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/dispatch_executions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/dispatch_executions.rs @@ -15,6 +15,8 @@ //! - a concurrent encoder's execution whose buffer's records the CPU sets a barrier in after the //! commit, before its batch is submitted (it waits for an event), recorded again with the //! barriers, still on the GPU alone; +//! - one whose command buffer waits for an event while a buffer over host pages it never uses is +//! rebound, recorded again on the GPU alone at the rebind; //! - a range its own commands alone; //! - with as many live states as the GPU-alone path takes in its encoder's order on the GPU alone, //! and with one more in the host step, which runs it faster; @@ -25,7 +27,10 @@ use super::degrade_notices::assert_made_once; use super::generated_executions::flat_template; +use super::host_memory::Seen; use super::indirect_host_steps::HOST_STEPS; +use super::rebind_reach::{buffer_len, buffer_over, pages}; +use super::rebinds::rebind; use super::shared_kinds; use super::{validated_device_with, Messages, ScratchCache, WAIT}; use crate::air_library::AirLibrary; @@ -40,6 +45,7 @@ use metal2vulkan_runtime::{ Degradation, Device, EventRef, ExecutedPipeline, IndirectCommandBuffer, IndirectCommandBufferDescriptor, PipelineOptions, ResourceOptions, Size, }; +use std::sync::Arc; /// `flat_mark(params, out, p)`: each thread adds `params[0] * 1000 + p.x` to `out[p.x]` by a /// relaxed atomic, reading only `thread_position_in_grid`: it does not observe its threadgroup @@ -462,6 +468,58 @@ fn a_barrier_set_after_the_commit_records_the_commands_again() { }); } +/// A rebind between the commit and the first submission (an event wait holds the command buffer) +/// of a buffer over host pages the commands never use moves the live buffers the preprocess +/// searches, which the commit resolved: the rebind records the execution again on the GPU alone +/// (`command_buffer/reencode.rs`), and it runs what it runs without the rebind, the command +/// buffer completing with a clean report (not `EncodedUseRebound`) and announcing nothing. +#[test] +fn a_rebind_before_the_first_submission_records_the_execution_again() { + on_device(|device, messages| { + let seen = Arc::new(Seen::default()); + let Some(unused) = buffer_over(device, pages(buffer_len(), 0, &[1]), &seen) else { + return; + }; + let queue = device.new_command_queue().unwrap(); + let setup = Setup::new(device); + let event = device.new_shared_event().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + // The wait first: its first batch waits for the event too, so it is submitted after the + // rebind. + command_buffer + .encode_wait_for_event(EventRef::from(&event), 1) + .unwrap(); + setup.writable(&command_buffer); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + setup.resident(&mut encoder); + encoder + .execute_commands_in_buffer(&setup.icb, 0..COMMANDS) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + let before = device.work_counts(); + let rebound = Arc::new(Seen::default()); + rebind(&unused, pages(buffer_len(), 0, &[2]), &rebound).unwrap(); + let after = device.work_counts(); + assert_eq!( + after.segments_recorded_again, + before.segments_recorded_again + 1, + "the rebind recorded the execution again" + ); + assert_eq!(after.reencodes_refused, before.reencodes_refused); + event.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!( + command_buffer.execution_report(), + Some(StatusReport::default()) + ); + assert_eq!(setup.output(), expected(0..COMMANDS as usize)); + assert!(ran_flat(&command_buffer), "on the GPU alone"); + announced(device, messages, &[]); + }); +} + /// The commands of the executions [`MOST_STATES`] bounds: [`PLAN`]'s and as many never written, /// so both bounds fall below the replay's 64 variants (`bind::MAX_REPLAY_VARIANTS`). const BOUNDED: u64 = 2 * COMMANDS; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/render_merged_executions.rs b/crates/metal2vulkan-validation/src/runtime_lane/render_merged_executions.rs index 3070aa597..6b6184fec 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/render_merged_executions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/render_merged_executions.rs @@ -16,12 +16,18 @@ //! them to; //! - into a target over a buffer whose rows the device lays out otherwise (a shadowed texture, //! copied back after the pass): the kernel's triangles in one merged draw, and triangle strips -//! the CPU wrote one indirect draw per command, the same pixels as the host step's there. +//! the CPU wrote one indirect draw per command, the same pixels as the host step's there; +//! - after a rebind between the commit and the first submission, of a buffer over host pages +//! the commands' vertices lie in or of one they never use: recorded again at the rebind, the +//! new pages' points, the command buffer completing. -use super::buffer_with; use super::degrade_notices::{assert_made_once, counts, on_device}; +use super::host_memory::Seen; use super::indirect_host_steps::{complete, HOST_STEPS}; +use super::rebind_reach::{buffer_len, buffer_over, pages}; +use super::rebinds::rebind; use super::render_executions::{forced_with, icb}; +use super::{buffer_with, WAIT}; use crate::air_library::AirLibrary; use metal2vulkan::metal::RenderStages; use metal2vulkan::metal::{ @@ -32,11 +38,12 @@ use metal2vulkan::pipeline::{ }; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ - Buffer, ClearColor, ComputePipelineState, Degradation, Device, IndirectCommandBuffer, - IndirectCommandBufferDescriptor, Library, LoadAction, PipelineOptions, Region, - RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, Texture, - TextureDescriptor, + Buffer, ClearColor, CommandBuffer, CommandBufferStatus, ComputePipelineState, Degradation, + Device, EventRef, IndirectCommandBuffer, IndirectCommandBufferDescriptor, Library, LoadAction, + PipelineOptions, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, + StoreAction, Texture, TextureDescriptor, }; +use std::sync::Arc; /// The target's width and height, and the rows an instance moves its vertices down. const W: u64 = 64; @@ -165,18 +172,30 @@ impl Scene { .unwrap(); } - /// Encode and run, in one command buffer of a new queue: a compute encoder that makes `icb` - /// resident for writing, `writer`, where given, writing it over `threads` threads, then a - /// pass over the target that executes commands `0..count` of it. + /// Encode ([`encode`](Self::encode)) and run, in one command buffer of a new queue. fn run( &self, device: &Device, + pipelines: (Option<&ComputePipelineState>, &RenderPipelineState), + commands: (&IndirectCommandBuffer, u64, u64), + ) { + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + self.encode(device, &command_buffer, pipelines, commands); + complete(&command_buffer); + } + + /// Encode into `command_buffer`: a compute encoder that makes `icb` resident for writing, + /// `writer`, where given, writing it over `threads` threads, then a pass over the target + /// that executes commands `0..count` of it. + fn encode( + &self, + device: &Device, + command_buffer: &CommandBuffer, (writer, state): (Option<&ComputePipelineState>, &RenderPipelineState), (icb, threads, count): (&IndirectCommandBuffer, u64, u64), ) { let arguments = buffer_with(device, &icb.gpu_resource_id().0.to_le_bytes()).unwrap(); - let queue = device.new_command_queue().unwrap(); - let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.compute_command_encoder().unwrap(); encoder .use_resource(icb.as_resource(), ResourceUsage::WRITE) @@ -212,7 +231,6 @@ impl Scene { } encoder.execute_commands_in_buffer(icb, 0..count).unwrap(); encoder.end_encoding().unwrap(); - complete(&command_buffer); } /// The target's pixels, row by row. @@ -456,3 +474,105 @@ fn gpu_forms_draw_into_a_shadowed_target_what_the_host_step_draws() { } }); } + +/// The points `draws` of the kernel's commands draw over `scene`, committed behind an event wait +/// and first submitted only after `rebind` ran: the commit records them in one merged draw, and +/// the rebind records them again (`command_buffer/reencode.rs`), once, over where the buffers lie +/// then; the command buffer completes with a clean report and announces nothing. +fn rebound_run( + device: &Device, + messages: &super::Messages, + scene: &Scene, + draws: &[Draw], + rebind: impl FnOnce(), +) { + let library = library(device); + let writer = writer(device, &library, "points"); + let state = state(device, &library); + let icb = icb(device, &inheriting(), 8); + let queue = device.new_command_queue().unwrap(); + let event = device.new_shared_event().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::from(&event), 1) + .unwrap(); + let pipelines = (Some(&writer), &state); + let (merged, gpu, read) = counted(device, || { + scene.encode( + device, + &command_buffer, + pipelines, + (&icb, draws.len() as u64, 8), + ); + command_buffer.commit().unwrap(); + }); + assert_eq!((merged, gpu, read), (8, 8, 0), "the commit's merged draw"); + let before = device.work_counts(); + rebind(); + let after = device.work_counts(); + assert_eq!( + after.segments_recorded_again, + before.segments_recorded_again + 1, + "the rebind recorded the merged draw again" + ); + assert_eq!(after.reencodes_refused, before.reencodes_refused); + assert_eq!( + after.merged_draw_commands - before.merged_draw_commands, + 8, + "in one merged draw again" + ); + assert_eq!(after.indirect_records_read, before.indirect_records_read); + event.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None); + assert_made_once(messages, &[], &forced_with(device, &[])); +} + +/// A GPU-written execution the commit recorded on the GPU alone is recorded again by a rebind +/// between the commit and the first submission (an event wait holds the command buffer), as +/// Metal resolves what its commands reach as it submits the command buffer. A rebind of a buffer +/// over host pages the commands never use moves the live buffers the preprocess searches, and the +/// draws draw as without it; a rebind of the buffer the commands' vertices lie in, from pages +/// holding vertices off the target to pages holding the row of points, draws the new pages' +/// points, pixel for pixel. Neither fails the command buffer (`EncodedUseRebound`) or announces +/// anything. +#[test] +fn a_rebind_before_the_first_submission_records_the_gpu_form_again_over_the_new_pages() { + on_device(|device, messages| { + let draws: Vec = vec![[0, 5, 1, 0], [8, 3, 2, 1], [30, 6, 3, 2]]; + let points = + |xy: &[[f32; 2]]| pages(buffer_len(), 0, &floats(xy.iter().flatten().copied())); + let seen = Arc::new(Seen::default()); + let Some(unused) = buffer_over(device, points(&[[0.0; 2]]), &seen) else { + return; + }; + let scene = Scene::new(device, &draws, &point_row()); + rebound_run(device, messages, &scene, &draws, || { + let seen = Arc::new(Seen::default()); + rebind(&unused, points(&[[1.0; 2]]), &seen).unwrap(); + }); + assert_eq!( + scene.pixels(), + drawn_points(&draws), + "an unused buffer rebound" + ); + + let off: Vec<[f32; 2]> = point_row().iter().map(|_| [-4.0, -4.0]).collect(); + let xy = buffer_over(device, points(&off), &seen).unwrap(); + let scene = Scene { + xy, + ..Scene::new(device, &draws, &point_row()) + }; + rebound_run(device, messages, &scene, &draws, || { + let seen = Arc::new(Seen::default()); + rebind(&scene.xy, points(&point_row()), &seen).unwrap(); + }); + assert_eq!(scene.pixels(), drawn_points(&draws), "the vertices rebound"); + eprintln!( + "ICB-REBIND {}: GPU forms recorded again at rebinds before the first submission drew \ + the new pages", + device.name() + ); + }); +}