diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index b8a04c762..58597ac99 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -112,7 +112,6 @@ use super::values::CommandBufferStatus; use super::work_counts::Counters; use super::write_routes::{AtCommit, Routes}; use super::{Buffer, CommandQueue, Device}; -use crate::host_ram::copy::StagedFill; use crate::release; use ash::vk; use batches::Batches; @@ -779,10 +778,6 @@ pub(super) struct State { pub(super) executions: Vec, /// The commands' own data, released when the command buffer completes. pub(super) uploads: Uploads, - /// Its gathers from a guest RAM staged through the CPU (`host_ram/copy.rs`), each copied - /// into its region of `uploads` by the host step of the batch its encoder is in, released - /// with them. - pub(super) staged: Vec>, /// The device's heap sets its commands bound (`heap_sets.rs`), released with the uploads. pub(super) heaps: HeapUse, /// Its commands' function-table snapshots, written again as it commits. @@ -1717,21 +1712,6 @@ impl State { } } - /// The place the encoder open now takes among the ended encoders as it ends - /// ([`encoder_ended`](Self::encoder_ended)). - pub(super) fn next_encoder(&self) -> usize { - self.ended.len() - } - - /// The staged gathers of batch `index` its host step has not copied yet: those its encoders - /// recorded ([`State::staged`]). - fn staged_unfilled(&self, index: usize) -> impl Iterator> { - let parts = &self.recorded[self.batch_range(index)]; - (self.staged.iter()).filter(move |fill| { - !fill.filled() && parts.iter().any(|part| part.encoder == fill.encoder) - }) - } - /// The encoders (or parts of them) of batch `index`. pub(super) fn batch_range(&self, index: usize) -> Range { let batches = self.batches.all(); @@ -2169,7 +2149,6 @@ impl CommandBuffer { routes: Routes::default(), executions: Vec::new(), uploads: Uploads::new(), - staged: Vec::new(), heaps: HeapUse::default(), table_snapshots: Vec::new(), unlisted_argument_samplers: false, @@ -3559,8 +3538,7 @@ impl CommandBuffer { || encoder.sparse.iter().any(SparseUpdate::needs_step) || (state.ended.get(encoder.encoder)) .is_some_and(|record| record.replay.is_some()) - }) - || state.staged_unfilled(index).next().is_some(), + }), checked: state.checks.is_some(), }) .collect(); @@ -4182,9 +4160,9 @@ impl CommandBufferShared { } /// Whether batch `index` waits for a host step: a segment of it executes commands the GPU may - /// write, not recorded since, or an indirect sparse update of it reads regions the GPU may - /// write, not read since, or a gather of it staged through the CPU was not copied yet - /// (`host_ram/copy.rs`). + /// write, or its step records it (a copy staged through the CPU, `host_ram/copy.rs`), not + /// recorded since, or an indirect sparse update of it reads regions the GPU may write, not + /// read since. pub(crate) fn needs_host_step(&self, index: usize) -> bool { if self.stepping(index) { return true; @@ -4204,7 +4182,6 @@ impl CommandBufferShared { .iter() .flat_map(|encoder| &encoder.sparse) .any(SparseUpdate::needs_step) - || state.staged_unfilled(index).next().is_some() } /// The scheduler handed batch `index`'s host step to its steps' thread (`scheduler/steps.rs`): @@ -4226,7 +4203,7 @@ impl CommandBufferShared { /// What the host step of batch `index` waits for ([`needs_host_step`](Self::needs_host_step)): /// the work submitted before it, where the GPU may write what a segment or an indirect /// sparse update of it reads, or the host bytes a gather of it staged through the CPU reads - /// (`StagedFill::waits_for_the_gpu`), its own `VkQueue`'s alone where those are loops' + /// (`Deferred::steps_after_the_gpu_now`), its own `VkQueue`'s alone where those are loops' /// checks; and the pipelines its segments record, while one is being made, and what a loop's /// check runs again. pub(crate) fn step_waits(&self, index: usize) -> StepWaits { @@ -4237,8 +4214,9 @@ impl CommandBufferShared { .iter() .flat_map(|encoder| &encoder.sparse) .any(SparseUpdate::needs_step); - let staged = - (state.staged_unfilled(index)).any(|fill| fill.waits_for_the_gpu(&self.device)); + let staged = segments() + .filter(|segment| segment.needs_step()) + .any(|segment| segment.work.steps_after_the_gpu_now(&self.device)); // A loop's check reads only what its laying, on its own `VkQueue`, wrote (`rerun.rs`). let checks_alone = !sparse && !staged @@ -4424,7 +4402,6 @@ impl CommandBufferShared { }) .collect() }; - self.fill_staged(index); self.read_mappings(index); if steps.is_empty() { return; @@ -4434,7 +4411,7 @@ impl CommandBufferShared { // (`gpu_execute::Rerecord`), unless a route outgrew it (`Deferred::outgrown`), which the // step records from the records; nor does work recorded again for the CPU's writes since // the commit alone (`Deferred::rewritten`), or for its pipelines alone; nor a loop's check, - // which records nothing, nor a staged scatter's copies (`host_ram/copy.rs`). + // which records nothing, nor a staged copy's steps (`host_ram/copy.rs`). let announced = steps .iter() .find(|(_, work, inputs)| { @@ -4491,22 +4468,6 @@ impl CommandBufferShared { } } - /// The host step's copies of batch `index`'s gathers staged through the CPU, before its - /// segments' steps (`host_ram/copy.rs`): each copies its runs' host bytes into its region of - /// the arena, without the command buffer's lock. - fn fill_staged(&self, index: usize) { - let staged: Vec> = { - let state = lock(&self.state); - if state.step_failure.is_some() { - return; - } - state.staged_unfilled(index).cloned().collect() - }; - for fill in staged { - fill.fill(&self.device); - } - } - /// 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, and held until the command buffer completes. A refusal is kept for the batch's @@ -5562,18 +5523,17 @@ impl CommandBufferShared { // `vkBindBufferMemory` holds across a commit that took 24 to 39 ms for a 1 GiB block // on the M3 Max, `gpu_pools.rs`), so they go after the completed handlers, which wait // for none of them, and after what the program's commands used. - let (uploads, staged, index_pool, mesh_pool, mut descriptors, completed) = { + let (uploads, index_pool, mesh_pool, mut descriptors, completed) = { let mut state = lock(&self.state); ( state.uploads.take(), - std::mem::take(&mut state.staged), state.index_pool.take(), state.mesh_pool.take(), state.descriptors.take(), state.status == CommandBufferStatus::Completed, ) }; - drop((uploads, staged, index_pool, mesh_pool, released_versions)); + drop((uploads, index_pool, mesh_pool, released_versions)); // A command buffer that completed gives its descriptor pools back to the device's // spares; one that failed releases them. if completed { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 862363ec8..a396c7d98 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -337,9 +337,10 @@ impl State { /// `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 one whose pipelines are being made (which goes, the encoding again having left one of - /// its own in its place), work its commit recorded on the GPU alone, or a run's merge (which - /// goes, the encoding again merging after itself, `pass_runs.rs`), or its group was - /// submitted, or the command buffer completed. + /// its own in its place), work its commit recorded on the GPU alone, a run's merge (which + /// goes, the encoding again merging after itself, `pass_runs.rs`), or a staged gather (which + /// goes, the encoding again copying through the imports, `host_ram/copy.rs`), or its group + /// was submitted, or the command buffer completed. pub(super) fn splice_replay( &mut self, at: usize, @@ -354,7 +355,10 @@ impl State { let recorded = &self.recorded[*part]; recorded.sparse.is_empty() && (recorded.segments.iter()).all(|segment| { - segment.keeps_pipelines() || segment.gpu_alone || segment.work.joins_a_run() + segment.keeps_pipelines() + || segment.gpu_alone + || segment.work.joins_a_run() + || segment.work.recorded_by_an_encoding_again() }) }; let unjudged = self.unjudged_parts(); @@ -400,7 +404,8 @@ impl State { recorded.raws = raws; recorded.summary = summary; // 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. + // pending dispatch's place, and its work on the GPU alone in segments of its own, and + // recorded each staged gather's copy at once. // What the commit recorded of one stays retained, never submitted, as the first // recording does. for segment in recorded.segments.drain(..) { diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index 471b59879..c973597d6 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -10,7 +10,7 @@ use super::device::lock; use super::encoder::RecordedSegment; use super::error::{internal, Error}; use super::gpu_execute::{self, Rerecord}; -use super::host_ram::copy::StagedScatter; +use super::host_ram::copy::{StagedGather, StagedScatter}; use super::indirect_dispatch::ArgumentDispatch; use super::indirect_execute::{self, Execute, Settled, Unforeseen}; use super::pass_runs::RunMerge; @@ -53,6 +53,11 @@ pub(super) enum Deferred { /// The check after a predicated loop's laying, which runs it again while the loop would run /// on (`command_buffer/rerun.rs`): it records nothing, and its batch waits for it. Loop(Arc), + /// A gather from a guest RAM staged through the CPU (`host_ram/copy.rs`, + /// [`StagedGather::stage`]): its batch's host step takes the staging, fills it by the CPU and + /// records the GPU's copy from it, so the staging's memory is not made on the encoding thread; + /// it waits for the work before it only where the GPU may write the pages it reads. + GatherStage(Arc), /// A scatter into a guest RAM staged through the CPU, its GPU's copy into the staging /// (`host_ram/copy.rs`, [`StagedScatter::stage`]): its batch's host step records it, waiting /// for no work on the GPU, so the staging's memory is not made on the encoding thread. @@ -87,6 +92,7 @@ const _: fn(&Deferred) = |work| { Deferred::RenderPass(work) => shared(work), Deferred::Pending(work) => shared(work), Deferred::Loop(work) => shared(work), + Deferred::GatherStage(work) => shared(work), Deferred::ScatterStage(work) => shared(work), Deferred::ScatterDrain(work) => shared(work), } @@ -111,8 +117,8 @@ pub(super) enum StepInputs { RenderPass, /// A loop's check: nothing past the check itself. Loop, - /// A staged scatter's copies: nothing past the work itself. - Scatter, + /// A staged gather's or scatter's copies: nothing past the work itself. + Staged, /// An execution `commit` recorded on the GPU alone with no barrier between its commands, which /// its batch's submission records again with them where a route encoded since may set a /// barrier in a record (`gpu_execute::Rerecord`); no work on the GPU is waited for. @@ -179,6 +185,7 @@ impl Deferred { (Deferred::RenderPass(a), Deferred::RenderPass(b)) => Arc::ptr_eq(a, b), (Deferred::Pending(a), Deferred::Pending(b)) => Arc::ptr_eq(a, b), (Deferred::Loop(a), Deferred::Loop(b)) => Arc::ptr_eq(a, b), + (Deferred::GatherStage(a), Deferred::GatherStage(b)) => Arc::ptr_eq(a, b), (Deferred::ScatterStage(a), Deferred::ScatterStage(b)) => Arc::ptr_eq(a, b), (Deferred::ScatterDrain(a), Deferred::ScatterDrain(b)) => Arc::ptr_eq(a, b), _ => false, @@ -193,14 +200,15 @@ impl Deferred { /// at the dispatch, and its writes are its encoder's to copy back. Nor is a gated copy in, /// which is one of the encoder's shadow copies, nor a run's merge (`pass_runs.rs`): a linear /// attachment's touches no shadowed texture, and a shadowed texture's is the copy back its - /// encoder took out of its shadows to leave there. A staged scatter's copies do: the GPU's - /// reads the buffer, and the CPU's writes the pages, after every command before them. + /// encoder took out of its shadows to leave there. A staged copy's do: a gather's writes the + /// buffer, a scatter's reads it and writes the pages, after every command before them. pub(super) fn leaves_shadows(&self) -> bool { match self { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => true, Deferred::RenderPass(_) @@ -229,6 +237,7 @@ impl Deferred { | Deferred::GatedCopyIn(_) | Deferred::RunMerge(_) | Deferred::Pending(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) => false, Deferred::RenderPass(pass) => pass.gpu_written(), } @@ -444,22 +453,24 @@ impl Deferred { bound: None, held: false, }), - // Recorded by host steps: the GPU's copy by its batch's, which waits for nothing - // (`records_at_its_step`); the CPU's, which records nothing on the GPU, once the work - // before it completed. Their uses are their encoder's, noted at the call - // (`host_ram/copy.rs`): the CPU's records none of its own. - Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => Ok(Prepared { - recorded: None, - for_good: false, - inputs: StepInputs::Scatter, - retained: None, - pipelines: false, - bound: match self { - Deferred::ScatterDrain(_) => Some(EncoderUses::new(true).finish()), - _ => None, - }, - held: false, - }), + // Recorded by host steps: a gather's and a scatter's GPU copy by its batch's + // (`records_at_its_step`); a scatter's CPU copy, which records nothing on the GPU, + // once the work before it completed. Their uses are their encoder's, noted at the call + // (`host_ram/copy.rs`): the steps' recordings name none of their own. + Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => { + Ok(Prepared { + recorded: None, + for_good: false, + inputs: StepInputs::Staged, + retained: None, + pipelines: false, + bound: match self { + Deferred::ScatterDrain(_) => Some(EncoderUses::new(true).finish()), + _ => None, + }, + held: false, + }) + } // Recorded now where its pipelines are made; else by a host step once they are, // which makes again one whose making failed. Deferred::Pending(dispatch) => { @@ -487,11 +498,29 @@ impl Deferred { } /// Whether `commit` leaves its recording to its batch's host step, which waits for no work on - /// the GPU: a staged scatter's copy into its staging, whose region of the arena that step - /// takes, so its memory is made on neither the encoding nor the committing thread - /// (`host_ram/copy.rs`). + /// the GPU but where [`steps_after_the_gpu_now`](Self::steps_after_the_gpu_now) says: a + /// staged gather's or scatter's GPU copy, whose region of the arena that step takes, so its + /// memory is made on neither the encoding nor the committing thread (`host_ram/copy.rs`). pub(super) fn records_at_its_step(&self) -> bool { - matches!(self, Deferred::ScatterStage(_)) + matches!(self, Deferred::GatherStage(_) | Deferred::ScatterStage(_)) + } + + /// Whether its host step, not yet run, waits for the work submitted before it to complete + /// though the work is not GPU-written for good ([`gpu_written`](Self::gpu_written)): a staged + /// gather's where the GPU may write the pages it reads now (`StagedGather::waits_for_the_gpu`). + pub(super) fn steps_after_the_gpu_now(&self, device: &Device) -> bool { + match self { + Deferred::GatherStage(gather) => gather.waits_for_the_gpu(device), + _ => false, + } + } + + /// Whether a rebind's encoding again of its encoder records it at once in its place, leaving + /// no segment of it (`command_buffer/reencode.rs`): a staged gather, which an encoder encoded + /// again copies through the imports (`host_ram/copy.rs`). The encoding again's parts are the + /// first's: a gather's segment starts none. + pub(super) fn recorded_by_an_encoding_again(&self) -> bool { + matches!(self, Deferred::GatherStage(_)) } /// Whether a commit may record it on the GPU alone, for good @@ -530,6 +559,7 @@ impl Deferred { | Deferred::RunMerge(_) | Deferred::Pending(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => Ok(None), } @@ -567,7 +597,7 @@ impl Deferred { | StepInputs::None | StepInputs::RenderPass | StepInputs::Loop - | StepInputs::Scatter => { + | StepInputs::Staged => { return Err(internal("an execution's host step without its states")); } }; @@ -582,6 +612,7 @@ impl Deferred { Deferred::RenderPass(pass) => pass.record(command_buffer, true), Deferred::Pending(dispatch) => dispatch.record(command_buffer), Deferred::Loop(check) => check.step(command_buffer), + Deferred::GatherStage(gather) => gather.stage(command_buffer), Deferred::ScatterStage(scatter) => scatter.stage(command_buffer), Deferred::ScatterDrain(scatter) => scatter.drain(command_buffer.device()), } @@ -602,6 +633,7 @@ impl Deferred { | Deferred::RunMerge(_) | Deferred::Pending(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => false, } @@ -621,6 +653,7 @@ impl Deferred { | Deferred::RunMerge(_) | Deferred::Pending(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => false, } @@ -631,7 +664,9 @@ impl Deferred { pub(super) fn holds(&self) -> bool { match self { Deferred::Loop(check) => check.running(), - Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => false, + Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => { + false + } Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) @@ -653,6 +688,7 @@ impl Deferred { | Deferred::GatedCopyIn(_) | Deferred::RunMerge(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => false, } @@ -664,8 +700,8 @@ impl Deferred { /// commands its step resolves from records, an indirect dispatch and a scrub, which their /// steps or submissions record. A dispatch whose pipelines were being made records the uses /// its encoding noted, a gated copy in writes the shadow it names, a run's merge - /// the bytes its pass noted it writes, a loop's check records nothing, and a staged - /// scatter's copies write the runtime's staging and the pages its call noted. + /// the bytes its pass noted it writes, a loop's check records nothing, and a staged copy's + /// steps write the runtime's staging and the buffer or pages its call noted. pub(super) fn reaches_unnamed(&self) -> bool { match self { Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) => true, @@ -674,6 +710,7 @@ impl Deferred { | Deferred::RunMerge(_) | Deferred::Pending(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => false, } @@ -690,13 +727,14 @@ impl Deferred { /// (`render/pending_tile.rs`). So does a run's merge (`pass_runs.rs`), which writes only the /// bytes its encoder's commands named (a linear attachment's, none over host pages; a /// shadowed texture's truth, whose uses its pass noted): a rebind of them encodes that - /// encoder again, the merge with it. So do a staged scatter's copies, from the buffer its call - /// resolved (`blit_at`) and into the pages it named. Everything else its step resolves as it + /// encoder again, the merge with it. So do a staged copy's steps, between the buffer its call + /// resolved (`blit_at`) and the pages it named. Everything else its step resolves as it /// records: a rebind meanwhile is refused. pub(super) fn resolved_at_its_calls(&self, pipelines: bool) -> bool { match self { Deferred::Pending(_) | Deferred::RunMerge(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => true, Deferred::RenderPass(pass) => pipelines && !pass.executes(), @@ -723,6 +761,7 @@ impl Deferred { | Deferred::GatedCopyIn(_) | Deferred::RunMerge(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => false, } @@ -732,13 +771,15 @@ impl Deferred { /// (`DeferredPass::known_summary`): a render pass's that executes no render commands. `None` /// for the rest, whose uses their recording finds: an execution's or an indirect dispatch's /// from the records and arguments it reads, a scrub's at its submission; a loop's check's are - /// its laying's (`CommandBufferShared::footprint`). A staged scatter's copy into its staging - /// uses none past what its call noted in its encoder's part. + /// its laying's (`CommandBufferShared::footprint`). A staged copy's GPU copy uses none past + /// what its call noted in its encoder's part. pub(super) fn known_summary(&self, device: &Device) -> Option> { match self { Deferred::RenderPass(pass) => pass.known_summary(device), Deferred::Pending(dispatch) => Some(dispatch.known_summary()), - Deferred::ScatterStage(_) => Some(EncoderUses::new(true).finish()), + Deferred::GatherStage(_) | Deferred::ScatterStage(_) => { + Some(EncoderUses::new(true).finish()) + } Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) @@ -760,6 +801,7 @@ impl Deferred { | Deferred::GatedCopyIn(_) | Deferred::RunMerge(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => {} } @@ -777,6 +819,7 @@ impl Deferred { | Deferred::GatedCopyIn(_) | Deferred::RunMerge(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => {} } @@ -792,6 +835,7 @@ impl Deferred { | Deferred::RunMerge(_) | Deferred::Pending(_) | Deferred::Loop(_) + | Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => {} Deferred::RenderPass(pass) => pass.degrade(device), diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 0db3f5b68..e41ee63f4 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -241,9 +241,14 @@ impl Segment { /// pipelines were being made ([`pends`](Self::pends)), left as a segment again, work a /// commit may record on the GPU alone, recorded there again (`Deferred::record_on_gpu`), or a /// run's pass's merge, which the pass encoded again records after itself as a pass alone - /// does, leaving its run (`pass_runs.rs`). Its log is kept only where every segment does. + /// does, leaving its run (`pass_runs.rs`), or a staged gather, which the encoding again + /// copies through the imports in its place (`Deferred::recorded_by_an_encoding_again`). 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() || self.work.joins_a_run() + self.pends() + || self.work.may_run_on_gpu_alone() + || self.work.joins_a_run() + || self.work.recorded_by_an_encoding_again() } /// What its recording will use, on `device`, while `commit` left it to the host step for the diff --git a/crates/metal2vulkan-runtime/src/host_ram/copy.rs b/crates/metal2vulkan-runtime/src/host_ram/copy.rs index 15b219e67..865e6b386 100644 --- a/crates/metal2vulkan-runtime/src/host_ram/copy.rs +++ b/crates/metal2vulkan-runtime/src/host_ram/copy.rs @@ -32,7 +32,7 @@ //! (`WorkCounts::host_ram_copy_import_waits`, `host_ram_copy_import_wait_nanos`). A copy over //! a chunk the device's thread imports takes neither: it takes the CPU's path below, unless it //! is encoded again. -//! - **First touch through the CPU** ([`StagedFill`], [`StagedScatter`]). A copy over a chunk not +//! - **First touch through the CPU** ([`StagedGather`], [`StagedScatter`]). A copy over a chunk not //! imported yet, which the device's thread imports (`RamOnDevice::copy_take`), on a device whose //! plan is not `Plan::listed`, and over none whose import only the copy would make, is staged //! instead of importing its ranges alone or waiting for the chunk's: an import of a copy's @@ -44,16 +44,18 @@ //! waited for, and no page pinned for it; each chunk is taken as an object takes it, and asked //! of the device's thread, which imports it before its window's next //! (`RamOnDevice::ask_for_copy`), so the copies after it go through the chunks' imports. -//! - A gather takes a region of the command buffer's arena as long as the copy's bytes, -//! host-visible memory of the runtime's own, which the host step of the copy's batch fills by -//! the CPU from the pages, each piece at its byte, before the batch is submitted; and one -//! `vkCmdCopyBuffer` of the bytes the runs cover from it into the buffer (at most -//! [`MOST_REGIONS`] regions a command, a byte two runs name taking the later's, as the CPU -//! wrote it last). Its uses are the chunks' bytes it reads, by their keys, and the buffer's -//! writes, so hazard tracking orders it as it orders a copy through the imports, the later -//! writers of those bytes among them. It reads what Metal's copy would: the step runs once -//! the batch is otherwise ready, after its event waits are met and every batch before it in -//! its order was submitted, so the CPU's writes before the commit, or before a signal its +//! - A gather leaves its work to the host step of its batch (`Deferred::GatherStage`), before +//! the batch is submitted: the step takes a region of the command buffer's arena as long as +//! the copy's bytes, host-visible memory of the runtime's own, so the region's memory is made +//! on neither the encoding nor the committing thread; fills it by the CPU from the pages, each +//! piece at its byte; and records one `vkCmdCopyBuffer` of the bytes the runs cover from it +//! into the buffer (at most [`MOST_REGIONS`] regions a command, a byte two runs name taking +//! the later's, as the CPU wrote it last), at the copy's place among the encoder's commands. +//! Its uses, noted at the call there, are the chunks' bytes it reads, by their keys, and the +//! buffer's writes, so hazard tracking orders it as it orders a copy through the imports, the +//! later writers of those bytes among them. It reads what Metal's copy would: the step runs +//! once the batch is otherwise ready, after its event waits are met and every batch before it +//! in its order was submitted, so the CPU's writes before the commit, or before a signal its //! batch waits for, are in the pages. Where some use but a copy's read may write the copy's //! host bytes (a buffer or heap over host pages lies over them, which it does until every //! command buffer that used it completed, or a copy into those chunks was recorded: @@ -61,9 +63,10 @@ //! `VkQueue` completed what was submitted before it, as a host step that reads what the GPU //! writes waits (`scheduler/mod.rs`), and reads after. A gather over bytes some use in its own //! command buffer may write takes the imports' path, since that work is not submitted before -//! its step; so does one whose staging the device has no memory for. Counted: -//! `WorkCounts::host_ram_copies_staged`, `host_ram_staged_fills_gated`, -//! `host_ram_staged_fill_nanos`. +//! its step. A region the device has no memory for fails the command buffer at the step. A +//! rebind's encoding again of its encoder (`command_buffer/reencode.rs`) records the copy +//! through the imports in its place. Counted: `WorkCounts::host_ram_copies_staged`, +//! `host_ram_staged_fills_gated`, `host_ram_staged_fill_nanos`. //! - A scatter leaves its work to two host steps (`Deferred::ScatterStage`, //! `Deferred::ScatterDrain`). The host step of the copy's batch, which waits for no work on the //! GPU, takes a region of the command buffer's arena as long as the copy's bytes and records @@ -273,32 +276,31 @@ impl RamOnDevice { } } -/// A gather staged through the CPU (the module docs' "First touch"): its runs' host bytes, which -/// the host step of its batch copies into `region` of its command buffer's arena before the batch -/// is submitted, and from which the copy's `vkCmdCopyBuffer` reads. Held by its command buffer -/// (`State::staged`) until it completes. -pub(crate) struct StagedFill { - /// The place of the encoder that recorded it among its command buffer's ended encoders. - pub(crate) encoder: usize, +/// A gather staged through the CPU (the module docs' "First touch"), its work left to the host +/// step of its batch ([`stage`](Self::stage), `Deferred::GatherStage`), before the batch is +/// submitted: it takes a region of its command buffer's arena, copies each piece's host bytes +/// into it, and records the GPU's copy of the bytes the pieces cover from there into the buffer. +/// Held by its segment until its command buffer completes. +pub(crate) struct StagedGather { ram: Arc, - region: Upload, + /// The buffer's `VkBuffer` and the byte of it the copy's first byte is at (`blit_at`, whose + /// command buffer keeps it live until it completes). + destination: (vk::Buffer, u64), + /// The copy's bytes: the region's length. + length: u64, + /// The bytes of the copy the pieces cover ([`covered`]): the GPU's regions, each byte once. + covered: Vec>, /// Each piece's first host byte, its length and its byte of the region, in the runs' order: /// where two name one byte of the buffer, the later's bytes stay. pieces: Vec<(u64, u64, u64)>, /// The host bytes the pieces lie in, joined as the copy's uses name them, each with its /// chunk. touched: Vec<(usize, Range)>, - /// The host step found that the GPU may write them ([`StagedFill::waits_for_the_gpu`]). + /// The host step found that the GPU may write them ([`StagedGather::waits_for_the_gpu`]). gated: AtomicBool, - filled: AtomicBool, } -impl StagedFill { - /// Whether the host step copied its bytes. - pub(crate) fn filled(&self) -> bool { - self.filled.load(Ordering::Acquire) - } - +impl StagedGather { /// Whether its host step waits for every batch submitted before it to complete: some use but /// a copy's read may write its host bytes ([`RamOnDevice::written_over`]), which the GPU may /// be doing. Else no work on the GPU may write them, and the CPU's writes before the commit @@ -311,19 +313,44 @@ impl StagedFill { waits } - /// The host step's copy of its pieces' bytes into its region, before its batch is submitted - /// (`CommandBufferShared::host_step`), counted on `device`. - pub(crate) fn fill(&self, device: &Device) { + /// Its host step, on the steps' thread before its batch is submitted: the region of the + /// arena, each piece's bytes copied into it by the CPU, counted on the device, and the GPU's + /// copy from it into the buffer, at most [`MOST_REGIONS`] regions a command, after every + /// command before it (`EncoderCore::segment`'s barrier) and before every later one. Refused, + /// failing the command buffer, where the device has no memory for the region. + pub(crate) fn stage(&self, command_buffer: &CommandBuffer) -> Result { + let device = command_buffer.device().clone(); + let region = (command_buffer.state().uploads).unset(&device, self.length)?; let started = Instant::now(); for &(host, length, at) in &self.pieces { // SAFETY: the piece's host bytes lie in the RAM's ranges (`pieces`), which stay // mapped and readable while `ram` holds the RAM (`HostRam::new`); the region is // memory of the runtime's own, apart from them. - unsafe { self.region.copy_in(at, host as *const u8, length) }; + unsafe { region.copy_in(at, host as *const u8, length) }; } - self.filled.store(true, Ordering::Release); let nanos = u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX); (device.shared().counts).host_ram_staged_filled(nanos, self.gated.load(Ordering::Relaxed)); + let (destination, at) = self.destination; + let source = region.raw(); + let regions: Vec = (self.covered.iter()) + .map(|bytes| vk::BufferCopy { + src_offset: region.offset() + bytes.start, + dst_offset: at + bytes.start, + size: bytes.end - bytes.start, + }) + .collect(); + let mut core = EncoderCore::segment(command_buffer, true)?; + core.command(TRANSFER, &[], |functions, raw| { + for part in regions.chunks(MOST_REGIONS) { + // SAFETY: the segment's command buffer is recording, outside a render pass; the + // arena's region and the buffer are live until the command buffer completes (the + // arena, and `blit_at`); each region lies inside the arena's (as long as the + // copy's bytes) and inside the buffer's bytes (`bytes_in`), and no byte is written + // by two (`covered`). + unsafe { functions.cmd_copy_buffer(raw, source, destination, part) }; + } + }); + core.end_segment() } } @@ -1043,13 +1070,8 @@ impl BlitCommandEncoder { if call.copy == PagesCopy::Gather && self.stages(ram, importer, (&pieces, &spans), PagesCopy::Gather) { - // Its staging, unless the device has no memory for it: the imports' path then. - let staging = (self.core().command_buffer().state().uploads) - .unset(&device, span.end - span.start); - if let Ok(region) = staging { - let bytes = (raw, at, span, total); - return self.record_staged(call, ram, (&pieces, &spans), region, bytes); - } + let bytes = (raw, at, span, total); + return self.record_staged(call, ram, (&pieces, &spans), bytes); } // The bytes of each chunk the pieces touch, and the imports they are read or written // through, held until the command buffer completes: the chunk's, or, where it is not @@ -1238,29 +1260,20 @@ impl BlitCommandEncoder { } /// Record `call`, a gather staged through the CPU ([`stages`](Self::stages)), into the - /// buffer's bytes `span`, from byte `at` of its `raw`: `region` of the command buffer's - /// arena, as long as `span`, each piece's bytes at its byte there, which its batch's host step - /// copies from the pages (`State::staged`, [`StagedFill`]), and a `vkCmdCopyBuffer` of the - /// bytes the pieces cover from it into the buffer, at most [`MOST_REGIONS`] regions a - /// command, its uses the chunks' bytes it reads, by their keys, and the buffer's. Each chunk - /// is taken as an object over it takes it, and asked of the device's thread where it is not - /// imported ([`RamOnDevice::ask_for_copy`]). + /// buffer's bytes `span`, from byte `at` of its `raw` (the module docs' "First touch"): its + /// work left to its batch's host step ([`StagedGather`]), at its place in the encoder, its + /// uses noted there: the chunks' bytes it reads, by their keys, and the buffer's writes. Each + /// chunk is taken as an object over it takes it, and asked of the device's thread where it is + /// not imported ([`RamOnDevice::ask_for_copy`]). A buffer detached since records nothing, as a + /// command over it does. fn record_staged( &mut self, call: &HostRamCall, ram: &Arc, (pieces, spans): (&[Piece], &[Range]), - region: Upload, (raw, at, span, total): (vk::Buffer, u64, Range, u64), ) -> Result<(), Error> { let device = self.core().device().clone(); - let regions: Vec = (covered(pieces).into_iter()) - .map(|bytes| vk::BufferCopy { - src_offset: region.offset() + bytes.start, - dst_offset: at + bytes.start, - size: bytes.end - bytes.start, - }) - .collect(); let read = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_READ); let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE); let touched = chunk_ranges(pieces, MOST_RANGES); @@ -1271,21 +1284,9 @@ impl BlitCommandEncoder { uses.push(Use::reads(key, true, UseRange::Bytes(range.clone()), read)); } } - uses.push(writes_by(&call.buffer, span, write)); - let source = region.raw(); - self.command_in(TRANSFER, &uses, |functions, command_buffer| { - for part in regions.chunks(MOST_REGIONS) { - // SAFETY: the encoder's command buffer is recording, outside a render pass; the - // arena's region and the buffer are live until it completes (the arena, and - // `blit_at`); each region lies inside the arena's (as long as the copy's bytes) - // and inside the buffer's bytes (`bytes_in`), and no byte is written by two - // (`covered`). - unsafe { functions.cmd_copy_buffer(command_buffer, source, raw, part) }; - } - })?; - for slot in touched.keys() { - ram.take_for_copy(*slot); - ram.ask_for_copy(*slot); + uses.push(writes_by(&call.buffer, span.clone(), write)); + if !self.core().note_left_uses(TRANSFER, &uses) { + return Ok(()); } let in_pages: Vec<(u64, u64, u64)> = (pieces.iter()) .map(|piece| { @@ -1296,19 +1297,20 @@ impl BlitCommandEncoder { ) }) .collect(); - let touched = touched_bytes(pieces, spans); - let mut state = self.core().command_buffer().state(); - let fill = StagedFill { - encoder: state.next_encoder(), + let staged = StagedGather { ram: Arc::clone(ram), - region, + destination: (raw, at), + length: span.end - span.start, + covered: covered(pieces), pieces: in_pages, - touched, + touched: touched_bytes(pieces, spans), gated: AtomicBool::new(false), - filled: AtomicBool::new(false), }; - state.staged.push(Arc::new(fill)); - drop(state); + self.core().defer(Deferred::GatherStage(Arc::new(staged)))?; + for slot in touched.keys() { + ram.take_for_copy(*slot); + ram.ask_for_copy(*slot); + } let counts = &device.shared().counts; counts.host_ram_copied(total, 0); counts.host_ram_copy_staged(); diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs index 5c068ab5f..8e3fd03c3 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs @@ -61,12 +61,16 @@ //! and a buffer over one of them reads them in a later encoder and in a command buffer of //! another queue committed after it. So is one of few ranges, whose encoding imports nothing, //! and the scatter after it, over the chunks the thread imported, goes through their imports. +//! No staged copy's encoding takes its staging of the command buffer's arena. A rebind before +//! the first submission of a no-copy buffer that a staged gather's encoder fills encodes that +//! encoder again, and the command buffer completes with both copies' bytes in place. //! //! Every other test holds the device's thread back (`Device::hold_host_ram_imports`). //! //! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind //! of device the cfg selects. A device that imports no host memory says so and passes. +use super::rebind_behind_a_wait as rebind; use crate::host_ram::AHEAD_CHUNKS; use crate::{ Buffer, CommandBuffer, CommandBufferStatus, Device, DeviceKind, DeviceOptions, DirtyPages, @@ -1470,6 +1474,10 @@ fn a_first_gather_over_chunks_the_thread_imports_reads_its_pages_by_the_cpu_at_i .copy_from_buffer_to_buffer(&cache, 0, &back, 0, total) .unwrap(); encoder.end_encoding().unwrap(); + assert!( + command_buffer.state().uploads.bytes() < total, + "the encoding took the staging" + ); // The CPU's writes after the encoding, before the commit: in the pages the copy reads. write_pattern(runs[5].clone(), 4); write_pattern(runs[30].clone(), 4); @@ -1556,6 +1564,10 @@ fn a_first_gather_of_few_ranges_imports_nothing_on_the_encoding_thread() { .unwrap(); encoder.end_encoding().unwrap(); let encoded = device.work_counts(); + assert!( + command_buffer.state().uploads.bytes() < total, + "the encoding took the staging" + ); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); @@ -1585,6 +1597,87 @@ fn a_first_gather_of_few_ranges_imports_nothing_on_the_encoding_thread() { drop((used, ram)); } +/// A staged gather leaves its encoder's log in place (`Deferred::recorded_by_an_encoding_again`): +/// a rebind, before the command buffer's first submission, of a no-copy buffer the same encoder +/// fills encodes the encoder again, which copies the gather through the imports; the command +/// buffer completes with the fill in the pages the buffer lies in now and the gather's bytes in +/// its buffer. +#[test] +fn a_rebind_before_the_first_submission_encodes_a_staged_gather_s_encoder_again() { + // Declared before the device, so dropped after it. + let pages = [rebind::Page::new(), rebind::Page::new()]; + let Some((device, used, ram, start, _)) = ahead_ram() else { + return; + }; + let runs = scattered_pages(start); + for run in &runs { + write_pattern(run.clone(), 14); + } + let total: u64 = runs.iter().map(|run| run.end - run.start).sum(); + let out = shared(&device, total, |_| 0); + let length = rebind::BYTES as u64; + // 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(), + length, + ResourceOptions::shared(), + None, + ) + }; + let over = match made { + Ok(buffer) => buffer, + Err(Error::Unsupported(gap)) => { + eprintln!("HOST-RAM-COPY: the device imports no such pages: {gap:?}"); + return; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + // Its command buffer waits for an event only the host signals, below: the rebind comes + // before its first submission. + let gate = device.new_shared_event().unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::Shared(&gate), 1) + .unwrap(); + let encoding = device.work_counts(); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encoder.copy_from_host_ram(&ram, &runs, &out, 0).unwrap(); + encoder.fill_buffer(&over, 0..length, 0x5a).unwrap(); + encoder.end_encoding().unwrap(); + let held = command_buffer.state().uploads.bytes(); + command_buffer.commit().unwrap(); + assert_eq!(over.detach_backing(), Ok(true)); + // SAFETY: as above. + unsafe { over.rebind_bytes_no_copy(pages[1].memory(), None, None) }.unwrap(); + let rebound = device.work_counts(); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!( + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) + ); + assert!(held < total, "the first encoding took the staging"); + assert_eq!( + rebound.host_ram_copies_staged - encoding.host_ram_copies_staged, + 1, + "the first encoding staged the gather" + ); + assert_eq!( + rebound.encoders_reencoded - encoding.encoders_reencoded, + 1, + "the rebind encoded the encoder again" + ); + assert!( + pages[1].written() && !pages[0].written(), + "the fill in the pages the buffer lies in now" + ); + assert!(contents(&out) == gathered(&runs), "the gathered pages"); + drop((over, used, ram)); +} + #[test] fn a_staged_gather_after_a_gpu_write_over_its_pages_waits_for_that_write() { let Some((device, used, ram, start, before)) = ahead_ram() else { @@ -1685,6 +1778,10 @@ fn a_first_scatter_over_chunks_the_thread_imports_is_in_its_pages_once_it_comple encoder.copy_to_host_ram(&cache, 0, &ram, &runs).unwrap(); encoder.end_encoding().unwrap(); let encoded = device.work_counts(); + assert!( + command_buffer.state().uploads.bytes() < total, + "the encoding took the staging" + ); eprintln!( "HOST-RAM-FIRST-SCATTER {}: staged {}, run imports made once encoded {}, chunks imported \ by copies {}, import waits {}", @@ -1785,6 +1882,10 @@ fn a_first_scatter_of_few_ranges_imports_nothing_on_the_encoding_thread() { encoder.copy_to_host_ram(&source, 0, &ram, &runs).unwrap(); encoder.end_encoding().unwrap(); let encoded = device.work_counts(); + assert!( + command_buffer.state().uploads.bytes() < total, + "the encoding took the staging" + ); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 7a67cc166..8d8ed189b 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -724,10 +724,12 @@ submission, can give the device the guest's RAM once instead: ranges, imports those ranges alone, as an object's run is imported (not on MoltenVK or ANV). No staged copy makes or waits for an import, no page is pinned for it, and the thread imports each such chunk next, so the copies after it go through the imports. - - A staged gather's CPU copies its runs from the pages into memory of the command buffer's own - once its batch is otherwise ready to submit (its event waits met), and the GPU copies them - from there into the buffer (`WorkCounts::host_ram_copies_staged`, - `host_ram_staged_fill_nanos`). Where a buffer or heap over host pages lies over the runs' + - A staged gather's work is its batch's host step, off the encoding and committing threads, + once the batch is otherwise ready to submit (its event waits met): it takes memory of the + command buffer's own, copies the runs from the pages into it by the CPU, and records the + GPU's copy from there into the buffer (`WorkCounts::host_ram_copies_staged`, + `host_ram_staged_fill_nanos`). A rebind before the first submission that encodes its encoder + again copies the gather through the imports instead. Where a buffer or heap over host pages lies over the runs' bytes, or a scatter into those chunks was recorded, the CPU's copy first waits until every queue completed the work submitted before it (`host_ram_staged_fills_gated`), and where that is so at the encoding the copy takes the imports' path.