diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 2cc1dada5..bd3b50918 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -102,7 +102,7 @@ use super::replay::Replay; use super::residency::Residency; use super::resource::{ObjectId, ResourceKey}; use super::scheduler::{BatchSync, Hand, StepWaits}; -use super::shadow::ShadowCarry; +use super::shadow::{ShadowCarry, ShadowCopy}; use super::spares::CommandPool; use super::sparse::encoder::SparseUpdate; use super::sparse::indirect; @@ -678,9 +678,12 @@ pub(super) struct State { /// How many batches it had once its last ended encoder joined one: the encoder opening next /// carries nothing where it starts another ([`State::shadows_to_carry`]). carry_batches: usize, - /// Its open runs of passes over a linear attachment rendered apart, merged once - /// (`pass_runs.rs`). + /// Its open runs of passes over one attachment merged once: a linear attachment rendered + /// apart, or a shadowed texture merged back (`pass_runs.rs`). pass_runs: PassRuns, + /// The keeps the encoder being encoded again records after itself, where it leaves a run of + /// passes another pass went on in (`pass_runs.rs`, `command_buffer/reencode.rs`). + pub(super) replaying_keeps: Vec, /// The pools of its commands' set 0 (`descriptor_arena.rs`), given back or released with /// the uploads. pub(super) descriptors: DescriptorArena, @@ -1460,7 +1463,7 @@ impl State { } } - /// Its open runs of passes over a linear attachment rendered apart (`pass_runs.rs`). + /// Its open runs of passes over one attachment merged once (`pass_runs.rs`). pub(super) fn pass_runs(&mut self) -> &mut PassRuns { &mut self.pass_runs } @@ -1994,6 +1997,7 @@ impl CommandBuffer { shadow_carry: Some(ShadowCarry::default()), carry_batches: 1, pass_runs: PassRuns::default(), + replaying_keeps: Vec::new(), descriptors: DescriptorArena::default(), status_words: None, mesh_grid_past: false, @@ -3141,6 +3145,11 @@ impl CommandBuffer { state.retained.push(Box::new(ticket)); } state.status = CommandBufferStatus::Committed; + // No run of passes goes on past the commit: each lets go of its scratch and kept + // image, its merge recorded at its batch's submission (`pass_runs.rs`). + for held in state.pass_runs.close() { + held.end(); + } // Its set-0 cache is shut here, before anything records again: from the commit on it // holds what its commands took only weakly (below), so no handle a kept set holds is // held against another object taking it -- which is the cache's own precondition diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index c79ce0592..0157e3bc7 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -43,6 +43,11 @@ //! its host step needs. Work a host step recorded again since (with the barriers between its //! commands, `gpu_execute::Rerecord`, or as a route outgrew it, `DeferredPass::outgrown`) //! keeps that step's recording. +//! - **Runs of passes.** An encoder encoded again that was a pass of a run of passes over a +//! shadowed texture merged once (`pass_runs.rs`) leaves the run once it is put in place: the +//! merge of the run's pass before it, which it took over, records after all, and it keeps the +//! run's scratch after its own merge where a later pass went on over it (`State::replaying_keeps`, +//! recorded by `EncoderCore::finish_replay`). Its run's other passes are not encoded again. //! - **What cannot be encoded again stays as before.** An encoder whose log is gone (a compute //! encoder of a command buffer that used command predication whose unit laid a step before it //! opened, or one of its own that the unit's later encoders read, or a loop, or left work out; @@ -56,6 +61,7 @@ use super::rebound_use::Unlogged; use super::{lock, CommandBuffer, CommandBufferShared, State}; use crate::deferred::{Deferred, StepInputs}; use crate::encoder::{RecordedSegment, Replayed, ReplayedPart, Segment}; +use crate::pass_runs::RunMerge; use crate::pipeline::budget::Urgency; use crate::replay::Replay; use crate::residency::Residency; @@ -136,15 +142,27 @@ impl CommandBufferShared { // A compute encoder of a command buffer that used command predication, which // encodes again exactly, does so in its unit begun anew // (`Predication::replaying`). - let residency = { + // The merges its first encoding left to runs of passes (`pass_runs.rs`): encoded again, + // it leaves them, and keeps after itself what a later pass of a run went on over. + let (residency, runs) = { let mut state = lock(&self.state); state.replaying_predication = match state.predicated { true => state.predication.replaying(at), false => None, }; - state.residency_before(at, replay.kind()) + let runs: Vec> = (state.recorded.iter()) + .filter(|part| part.encoder == at) + .flat_map(|part| &part.segments) + .filter_map(|segment| match &segment.work { + Deferred::RunMerge(merge) => Some(Arc::clone(merge)), + _ => None, + }) + .collect(); + state.replaying_keeps = runs.iter().filter_map(|run| run.keep_after()).collect(); + (state.residency_before(at, replay.kind()), runs) }; let run = replay.run(&handle, residency); + lock(&self.state).replaying_keeps.clear(); // Its steps' gates listed as the commit lists the first encoding's. let run = { let mut state = lock(&self.state); @@ -190,6 +208,9 @@ impl CommandBufferShared { Ok(()) => { counts.encoder_reencoded(); spliced.push(at); + for run in &runs { + run.leave(); + } } Err(unspliced) => { counts.reencode_refused(); @@ -314,7 +335,8 @@ 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) or work its commit recorded on the GPU alone, or its group was + /// 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. pub(super) fn splice_replay( &mut self, @@ -329,8 +351,9 @@ impl State { let replaces = |part: &usize| { let recorded = &self.recorded[*part]; recorded.sparse.is_empty() - && (recorded.segments.iter()) - .all(|segment| segment.keeps_pipelines() || segment.gpu_alone) + && (recorded.segments.iter()).all(|segment| { + segment.keeps_pipelines() || segment.gpu_alone || segment.work.joins_a_run() + }) }; let unjudged = self.unjudged_parts(); let fits = !self.finished() diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index a216c9933..4d3b162c8 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -197,7 +197,7 @@ use super::hang; use super::kept_barriers::{KeptBarriers, SlotStamps}; use super::{lock, recording_error, submission_error, CommandBufferShared, State}; use crate::deferred::Deferred; -use crate::encoder::RecordedSegment; +use crate::encoder::{count_shadow_copies, RecordedSegment}; use crate::error::CommandBufferError; use crate::error::{internal, Error}; use crate::event::EventShared; @@ -1301,9 +1301,9 @@ impl CommandBufferShared { /// Record the segments of encoders `range` that their batch's submission records: the /// scrubs (`Deferred::SparseScrub`), with the mappings it applied, and the gated copies in /// (`Deferred::GatedCopyIn`), with the regions their logs say changed since the commit's - /// stamp, published by now; and the merges of runs of passes over a linear attachment - /// (`Deferred::RunMerge`), each the run's last pass's, the ones taken over recording - /// nothing. + /// stamp, published by now; and the merges of runs of passes over a linear attachment or a + /// shadowed texture (`Deferred::RunMerge`), each the run's last pass's (or the last before a + /// pass encoded again), the ones taken over recording nothing. fn record_scrubs( &self, state: &mut State, @@ -1349,10 +1349,15 @@ impl CommandBufferShared { }, // SAFETY: the command buffer is recording, outside a render pass; the merge, // its images and its scratch are held until it completes (its pass's encoder - // retains them), and the images rest in `GENERAL`. + // retains them, and the segment its copies), and the images rest in + // `GENERAL`. Deferred::RunMerge(merge) => { unsafe { merge.record(device.shared().vk(), buffer) }; - device.shared().counts.linear_merge_recorded(); + let counts = &device.shared().counts; + match merge.shadow() { + Some(copy) => count_shadow_copies(counts, std::slice::from_ref(copy)), + None => counts.linear_merge_recorded(), + } } _ => {} } diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index 138524d3e..06967d66b 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -40,9 +40,9 @@ pub(super) enum Deferred { /// a scrub, neither `commit` nor a host step records it, but its batch's submission, once the /// commit's stamp is published (`shadow::GatedCopyIn`, `dirty_pages.rs`). GatedCopyIn(Arc), - /// The merge of a run's pass over a linear attachment rendered apart (`pass_runs.rs`): as - /// with a scrub, neither `commit` nor a host step records it, but its batch's submission, - /// unless a later pass of the run took it over. + /// The merge of a run's pass over a linear attachment rendered apart, or over a shadowed + /// texture merged back (`pass_runs.rs`): as with a scrub, neither `commit` nor a host step + /// records it, but its batch's submission, unless a later pass of the run took it over. RunMerge(Arc), /// A render pass that executes render commands (`render/executions.rs`). RenderPass(Arc), @@ -127,8 +127,9 @@ impl Deferred { /// before it and back as the encoder ends (`render/shadows.rs`). /// Nor is a dispatch whose pipelines were being made: its shadowed textures were copied in /// 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 linear attachment's merge, which - /// touches no shadowed texture (`pass_runs.rs`). + /// 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. pub(super) fn leaves_shadows(&self) -> bool { match self { Deferred::Execute(_) @@ -340,6 +341,12 @@ impl Deferred { } } + /// Whether it is a run's pass's merge (`pass_runs.rs`), which an encoding again of its pass + /// replaces with that pass's own merge (`command_buffer/reencode.rs`). + pub(super) fn joins_a_run(&self) -> bool { + matches!(self, Deferred::RunMerge(_)) + } + /// Whether a commit may record it on the GPU alone, for good /// ([`record_on_gpu`](Self::record_on_gpu)): an execution's, or a render pass's that executes /// render commands. @@ -421,7 +428,7 @@ impl Deferred { Deferred::Dispatch(dispatch) => dispatch.record(command_buffer), Deferred::SparseScrub(_) => Err(internal("a sparse scrub's host step")), Deferred::GatedCopyIn(_) => Err(internal("a gated copy in's host step")), - Deferred::RunMerge(_) => Err(internal("a linear merge's host step")), + Deferred::RunMerge(_) => Err(internal("a run's merge's host step")), Deferred::RenderPass(pass) => pass.record(command_buffer, true), Deferred::Pending(dispatch) => dispatch.record(command_buffer), Deferred::Loop(check) => check.step(command_buffer), @@ -497,7 +504,7 @@ impl Deferred { /// command buffer's execution and a render pass that executes render commands, whose /// 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 linear attachment's merge + /// its encoding noted, a gated copy in writes the shadow it names, a run's merge /// the bytes its pass noted it writes, and a loop's check records nothing. pub(super) fn reaches_unnamed(&self) -> bool { match self { @@ -518,17 +525,19 @@ impl Deferred { /// what its encoding resolved (`pending_dispatch.rs`), and so does a render pass `commit` /// left for the pipelines its draws and tile dispatches record (`pipelines`) that executes no /// render commands, whose instances' commands its calls recorded - /// (`render/pending_tile.rs`). Everything else its step resolves as it records: a rebind - /// meanwhile is refused. + /// (`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. 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(_) => true, + Deferred::Pending(_) | Deferred::RunMerge(_) => true, Deferred::RenderPass(pass) => pipelines && !pass.executes(), Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) | Deferred::GatedCopyIn(_) - | Deferred::RunMerge(_) | Deferred::Loop(_) => false, } } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 6c60446dc..457dc5517 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -53,7 +53,9 @@ use super::residency::{Residency, Used}; use super::resource::ResourceKey; use super::retained::Retained; use super::row_copies::RowCopies; -use super::shadow::{CopyCause, GatedCopyIn, ShadowCopy, ShadowSync, ShadowUse, Step, Within}; +use super::shadow::{ + CopyCause, GatedCopyIn, ShadowCopies, ShadowCopy, ShadowSync, ShadowUse, Step, Within, +}; use super::shadow_copy_in::CopyIn; use super::shadow_merge::{MergeLease, ShadowMerge}; use super::sparse::encoder::SparseUpdate; @@ -63,7 +65,7 @@ use super::unique_identifier::ScheduledWork; use super::used_resources::EncoderKind; use super::Device; use crate::device::functions::Vk; -use crate::work_counts::Begun; +use crate::work_counts::{Begun, Counters}; use ash::vk; use metal2vulkan::bind::ReplayFaults; use std::any::Any; @@ -71,7 +73,7 @@ use std::collections::BTreeSet; use std::marker::PhantomData; use std::panic::Location; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, Weak}; /// The next core's [`EncoderCore::id`]: from 1, so none is `retained::HeldBy`'s 0. static CORES: AtomicU64 = AtomicU64::new(1); @@ -194,11 +196,12 @@ impl Segment { } /// 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. + /// 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. pub(super) fn records_again(&self) -> bool { - self.pends() || self.work.may_run_on_gpu_alone() + self.pends() || self.work.may_run_on_gpu_alone() || self.work.joins_a_run() } /// What its recording will use, on `device`, while `commit` left it to the host step for the @@ -328,9 +331,10 @@ pub(super) struct EncoderCore { /// in the command buffer (`WorkCounts::shadow_texels_first_copied_in_again`). first_copies: Vec<(ResourceKey, u64)>, /// Its holds on the kept images its merges took from its queue (`texture/kept_image.rs`), - /// and on the scratch they took from its command buffer (`merge_scratch.rs`): no keep of - /// another encoder takes one before this one ends, its merges done. - kept_leases: Vec, + /// and on the scratch they took from its command buffer (`merge_scratch.rs`), each with the + /// merge that took it: no keep of another encoder takes one before this one ends, its merges + /// done, or a run of passes that took it over ends (`pass_runs.rs`). + kept_leases: Vec<(Weak, MergeLease)>, /// The heaps its commands used through what the encoder made resident; `end` hands them, /// and those of `keys`, to the command buffer, whose commit marks them used. heaps: Vec, @@ -1471,18 +1475,23 @@ impl EncoderCore { let aliased = self.aliased(uses); let uses = aliased.as_deref().unwrap_or(uses); // The kept images its merges take are held to the encoder's end, those of a refused - // command let go of here. + // command let go of here. An encoder encoded again borrows none, nor its command buffer's + // scratch: its place may lie inside a run of passes that holds one (`pass_runs.rs`). let images = self.open.command_buffer.command_queue().kept_images(); let pool = self.open.command_buffer.merge_scratch(); + let lent = !self.replaying && !crate::replay::is_replaying(); let held = self.kept_leases.len(); let leases = &mut self.kept_leases; let planned = self .shadows .before(shadows, uses, |copies, made_for, area| { let merging = (made_for.two_ways, made_for.blocks, area); - let (merge, lease) = ShadowMerge::new(&device, copies, merging, (images, pool))?; - leases.extend(lease); - Ok(Arc::new(merge)) + let made = ShadowMerge::new(&device, copies, merging, (images, pool), lent)?; + let (merge, lease) = (Arc::new(made.0), made.1); + if let Some(lease) = lease { + leases.push((Arc::downgrade(&merge), lease)); + } + Ok(merge) }); let copies = match planned { Ok(copies) => copies, @@ -1569,40 +1578,7 @@ impl EncoderCore { /// into the scratch dispatch (`WorkCounts::shadow_merge_copies_dispatched`), and the texels the /// keeps copy (`WorkCounts::shadow_texels_kept`). fn count_shadow_copies(&self, copies: &[ShadowCopy]) { - let texels_in = copies.iter().map(ShadowCopy::texels_in).sum(); - let texels_back = copies.iter().map(ShadowCopy::texels_back).sum(); - let counts = &self.device().shared().counts; - counts.shadow_copies_planned(copies.len(), texels_in, texels_back); - for copy in copies { - counts.shadow_copy_in_planned(copy); - } - let bounded = (copies.iter()) - .filter(|copy| copy.cause == Some(CopyCause::Bounded)) - .count(); - if bounded > 0 { - counts.bounded_shadow_copies_planned(bounded); - } - let dispatched = copies - .iter() - .filter(|copy| match ©.step { - Step::Keep(merge) => merge.dispatches(), - Step::Merge(merge) => merge.changed_dispatches(), - Step::Into | Step::Back => false, - }) - .count(); - if dispatched > 0 { - counts.shadow_merge_copies_dispatched(dispatched); - } - let kept: u64 = copies - .iter() - .filter_map(|copy| match ©.step { - Step::Keep(merge) => Some(merge.texels_kept()), - _ => None, - }) - .sum(); - if kept > 0 { - counts.shadow_texels_kept(kept); - } + count_shadow_copies(&self.device().shared().counts, copies); } /// Note that the encoder's work from here on waits for another writer the program ordered @@ -1914,6 +1890,33 @@ impl EncoderCore { self.replaying } + /// Go on with a run of passes over the shadowed texture of `copies`, kept in `merge` before + /// the run's first (`pass_runs.rs`, `ShadowSync::go_on`): whether the encoder carries its + /// image, and took it so. + pub(super) fn go_on_shadow( + &mut self, + copies: &Arc, + merge: Arc, + ) -> bool { + self.shadows.go_on(copies, merge) + } + + /// The merge of what the encoder's commands wrote through the shadowed texture of `copies`, + /// which a run's pass leaves to its batch's submission (`pass_runs.rs`, + /// `ShadowSync::leave_merge`). + pub(super) fn leave_shadow_merge(&mut self, copies: &ShadowCopies) -> Option { + self.shadows.leave_merge(copies) + } + + /// The encoder's hold on what `merge` took (its scratch, or its kept image), handed to a run + /// of passes that holds it past the encoder's end (`pass_runs.rs`); `None` where it holds + /// none for it. + pub(super) fn take_lease(&mut self, merge: &Arc) -> Option { + let merge = Arc::downgrade(merge); + let at = (self.kept_leases.iter()).position(|(of, _)| of.ptr_eq(&merge))?; + Some(self.kept_leases.swap_remove(at).1) + } + /// The new `VkCommandBuffer` the encoder's commands go on in after a segment /// ([`defer`](Self::defer)), allocated from the command buffer's pool and begun. Left unused /// on a refusal, it goes with the pool. @@ -2371,6 +2374,14 @@ impl EncoderCore { let copies = self.sample_moves(copies); self.count_shadow_copies(&copies); self.shadow_copies(&copies); + // A pass of a run that a later pass went on over keeps the run's scratch again, from the + // image it left, for that pass's run (`pass_runs.rs`); the encoding again clears them + // as it ends (`command_buffer/reencode.rs`). + let keeps = (self.open.command_buffer.state().replaying_keeps).clone(); + if !keeps.is_empty() { + self.count_shadow_copies(&keeps); + self.shadow_copies(&keeps); + } if self.uses.broke_hold() { return Err(internal("a held depth used but as its attachment")); } @@ -2703,7 +2714,7 @@ pub(super) struct Captured { pub(super) taken: Taken, holds: Holds, heaps: Vec, - kept_leases: Vec, + kept_leases: Vec<(Weak, MergeLease)>, attachment_shadows: Vec, first_copies: Vec<(ResourceKey, u64)>, twin_writes: Vec, @@ -2884,3 +2895,42 @@ fn keep_with_copy_in( let both = merge.keep_in(device, ©.copies, ®ion)?; Some((j, both, merge.keep_in_uses(©.copies))) } + +/// Count shadowed textures' `copies` as planned into `counts` ([`EncoderCore`]'s +/// `count_shadow_copies`): also a run's merge as its batch's submission records it +/// (`pass_runs.rs`). +pub(super) fn count_shadow_copies(counts: &Counters, copies: &[ShadowCopy]) { + let texels_in = copies.iter().map(ShadowCopy::texels_in).sum(); + let texels_back = copies.iter().map(ShadowCopy::texels_back).sum(); + counts.shadow_copies_planned(copies.len(), texels_in, texels_back); + for copy in copies { + counts.shadow_copy_in_planned(copy); + } + let bounded = (copies.iter()) + .filter(|copy| copy.cause == Some(CopyCause::Bounded)) + .count(); + if bounded > 0 { + counts.bounded_shadow_copies_planned(bounded); + } + let dispatched = copies + .iter() + .filter(|copy| match ©.step { + Step::Keep(merge) => merge.dispatches(), + Step::Merge(merge) => merge.changed_dispatches(), + Step::Into | Step::Back => false, + }) + .count(); + if dispatched > 0 { + counts.shadow_merge_copies_dispatched(dispatched); + } + let kept: u64 = copies + .iter() + .filter_map(|copy| match ©.step { + Step::Keep(merge) => Some(merge.texels_kept()), + _ => None, + }) + .sum(); + if kept > 0 { + counts.shadow_texels_kept(kept); + } +} diff --git a/crates/metal2vulkan-runtime/src/merge_scratch.rs b/crates/metal2vulkan-runtime/src/merge_scratch.rs index fe90539a2..57b3a77d6 100644 --- a/crates/metal2vulkan-runtime/src/merge_scratch.rs +++ b/crates/metal2vulkan-runtime/src/merge_scratch.rs @@ -13,7 +13,8 @@ //! once its pass's merge is recorded (`LinearMerge::record_merge`), or a run's of passes merged //! once as the pass that ends the run ends, after which its merge lies (`pass_runs.rs`); a //! shadow's as the encoder that planned it goes (its [`ScratchLease`], held with the encoder's -//! kept-image leases). A +//! kept-image leases), or that of a run of passes over a shadowed texture as the run ends or +//! its command buffer commits (`pass_runs.rs`). A //! scratch the pool lends is held by the merges that used it, which their command buffer //! retains until it completes; the pool holds none of them (a weak reference each), so the //! bytes go as before, once the command buffer completed: a shadow's back to its spares, for a @@ -27,14 +28,15 @@ //! submission order (a run's, by its first pass's fill and keep and the merge its last pass //! leaves, between which it is lent to none); a shadow's by its keeps and merges, which the //! encoder records before its next command that touches the bytes another way, or as it -//! ends (`shadow.rs`). +//! ends (`shadow.rs`), or a run's by its first pass's keep and the merge its last pass +//! leaves, between which it is lent to none (`pass_runs.rs`). //! 2. A command buffer's encoders go in order: one is open at a time (a render encoder's end //! left to the lowering thread is lowered before the next encoder opens, //! `render/deferral.rs`), and its batches go to its queue's one `VkQueue` in order, which the //! queue keeps from the command buffer's making to its completion (`queue_share.rs`). A //! predicated loop's laying submitted again, and an encoder a rebind encodes again -//! (`command_buffer/reencode.rs`), repeat or replace whole encoders; the latter's linear -//! merges borrow no scratch, as its place may lie inside a run's span. So the spans from the +//! (`command_buffer/reencode.rs`), repeat or replace whole encoders; the latter's merges +//! borrow no scratch, as its place may lie inside a run's span. So the spans from the //! first to the last command of two encoders that took one scratch never interleave in //! submission order. //! 3. Each span writes every byte of the scratch it reads before reading it (the copies into diff --git a/crates/metal2vulkan-runtime/src/pass_runs.rs b/crates/metal2vulkan-runtime/src/pass_runs.rs index f746a5332..2d02dadd3 100644 --- a/crates/metal2vulkan-runtime/src/pass_runs.rs +++ b/crates/metal2vulkan-runtime/src/pass_runs.rs @@ -1,87 +1,144 @@ -//! Runs of passes over one linear attachment rendered apart, merged once (`linear_merge.rs`). +//! Runs of passes over one attachment merged once: a linear attachment rendered apart +//! (`linear_merge.rs`), or a shadowed texture merged back (`shadow.rs`, `shadow_merge.rs`). //! //! A pass that renders a bound linear attachment through the image its texture keeps copies the //! box its draws write in, keeps it, renders, and merges the words it changed back into the -//! surface's bytes (`linear_attachment.rs`). A WebGPU frame split at every indexed draw renders -//! hundreds of such passes in one command buffer, each over the same attachment: hundreds of -//! copies in, keeps and merges, each between barriers from every command to every command. +//! surface's bytes (`linear_attachment.rs`). A pass that renders a shadowed texture whose truth +//! another writer may write (a no-copy buffer's host pages, a `Shared` buffer's bytes) keeps the +//! shadow's texels before it and merges the words it changed back as its encoder ends +//! (`shadow.rs`'s **Merged back**); its encoder takes the image the one before it left holding +//! the truth, with no copy in (`shadow::ShadowCarry`). A WebGPU frame split at every indexed draw, +//! or a window server drawing each layer in a pass of its own, renders hundreds of such passes in +//! one command buffer, each over the same attachment: hundreds of keeps and merges (and, for a +//! linear attachment, copies in), each between barriers from every command to every command. //! -//! - **A run** is a command buffer's passes over one attachment rendered apart through one kept -//! image, in one batch, each loading and storing it, with nothing between them that may touch -//! the surface's bytes or the kept image. Its first pass copies its box in and keeps it, as a -//! pass does alone; each later pass, whose box lies in the run's, renders over what the one -//! before left in the kept image, with no copy in and no keep; and the merge after its last -//! pass compares the first pass's keep with the image the last pass left, so it writes every -//! word one of the passes changed, and no other. A pass whose box reaches past its run's ends -//! that run and opens the next over its whole render area, which every later box lies in. +//! - **A run** is a command buffer's passes over one attachment (a linear attachment rendered +//! apart through one kept image, or one shadowed texture), in one batch, each loading and +//! storing it, with nothing between them that may touch its bytes or the image the passes +//! render. Its first pass copies in and keeps as a pass does alone; each later pass renders +//! over what the one before left in the image, with no copy in and no keep; and the merge after +//! its last pass compares the first pass's keep with the image the last pass left, so it writes +//! every word one of the passes changed, and no other. A linear attachment's pass whose box +//! reaches past its run's ends that run and opens the next over its whole render area, which +//! every later box lies in. A shadowed texture's pass that writes outside the rectangle its +//! run's keep holds merges what the run kept before it and keeps every texel again; one that +//! reads outside the texels its image holds (the first pass copied in its scissors' alone) +//! merges it and copies every texel in first (`ShadowSync::before`, as a command of one encoder +//! would); and the run goes on over that keep, every later pass inside both. //! - **The merge goes last.** Each pass of a run leaves its merge to its batch's submission -//! ([`RunMerge`], `Deferred::RunMerge`), a segment between its own command buffers and the -//! next encoder's; a later pass of the run, as its encoder ends, takes it over, and that -//! segment records nothing. The merge recorded is the run's last pass's, in that pass's place, -//! between the same barriers. Its uses are noted as each pass ends, as a merge recorded there -//! notes them, so the tracker orders the work after each pass after a write of the bytes. -//! - **Why the bytes are Metal's.** Within the run, nothing reads the surface's bytes or writes -//! them another way (below): between two of its passes the bytes are what the first copy in -//! read, and the kept image holds them, as Metal's tile stores would have left them, merged. -//! Each pass then renders over what Metal's would load, and the merge after the last writes -//! each word as the last pass that changed it left it, as the merges after each pass would -//! have, one after the other; a word changed and changed back is written either way with the -//! value it holds. Another writer's write of a word no pass changed is kept, as it is by -//! merges after each pass; one of a word a pass changed races that pass in Metal too. After the -//! run the bytes are those merges' and, at the merge's end, a barrier from every command to -//! every command orders all later work after it, as the merge after each pass does. -//! - **What ends a run** (its last merge recorded, the scratch lent on, `merge_scratch.rs`): any -//! encoder between its passes but a render encoder that touches none of it (a blit, a compute -//! or a resource state encoder ends it, whatever it names); a render encoder that may touch the -//! surface's bytes or the kept image: one whose commands named the surface's buffer or its host -//! range, reached memory they do not name (a root or handle table, a heap, an execution of -//! render commands, a memory barrier inside the pass), waited for or updated a fence, -//! resolved, wrote visibility results, or recorded later (a pending draw, a tile dispatch, a -//! later color group), or that has an attachment over those bytes or rendered through that -//! image; an event or semaphore wait or a signal, a host step (any new batch, where another -//! queue's work may come between); a pass whose box reaches past the run's, or one that -//! cannot join (below); and the command buffer's end. The work after the run then sees the -//! bytes merged: its last merge lies before it in submission order. -//! - **Which passes join** (each a run's first or a later pass): a pass encoded once, not again: -//! neither its commands nor its attachments name a buffer over host pages, which a rebind would -//! move and encode its encoder again (`command_buffer/reencode.rs`), it renders over no -//! rasterization-rate map, whose reset does the same, and executes no render commands, which a -//! host step records; outside a predicated loop's laying, which its check may submit again; -//! of one part and one color group; whose first instance does not record inline; that names -//! neither the surface's buffer nor its host range and touches nothing past its attachments -//! (as above); and whose other attachments lie over none of the surface's bytes. Every other -//! pass over a linear attachment rendered apart merges after itself, as before; an encoder -//! encoded again changes no run. +//! ([`RunMerge`], `Deferred::RunMerge`), a segment between its own command buffers and the next +//! encoder's; a later pass of the run, as its encoder ends, takes it over, and that segment +//! records nothing. The merge recorded is the run's last pass's, in that pass's place, between +//! barriers from every command to every command. Its uses are noted as each pass ends, as a +//! merge recorded there notes them, so the tracker orders the work after each pass after a +//! write of the bytes. +//! - **Why the bytes are Metal's.** Within the run, nothing reads the attachment's bytes or +//! writes them another way (below): between two of its passes the bytes are what the first +//! copy in read (or what the work before the run left), and the image holds them, as Metal's +//! tile stores would have left them, merged. Each pass then renders over what Metal's would +//! load, and the merge after the last writes each word as the last pass that changed it left +//! it, as the merges after each pass would have, one after the other; a word changed and +//! changed back is written either way with the value it holds. Another writer's write of a word +//! no pass changed is kept, as it is by merges after each pass; one of a word a pass changed +//! races that pass in Metal too, which the program cannot order inside the run (it has no +//! signal, wait or host step). A shadowed texture's merge that stores whole blocks of its rows +//! (`shadow.rs`'s **Stored attachments**) stores each word of a block holding a change that no +//! pass changed as the bytes held it when the merge read it, as a pass's merge alone does: only +//! a write made between that read and the store is undone. After the run the bytes are those +//! merges' and, at the merge's end, a barrier from every command to every command orders all +//! later work after it, as the merge after each pass does. +//! - **What ends a run** (its last merge recorded where its last pass left it, its scratch lent +//! on, `merge_scratch.rs`): any encoder between its passes but a render encoder that touches +//! none of it (a blit, a compute or a resource state encoder ends it, whatever it names); a +//! render encoder that may touch the attachment's bytes or the image: one whose commands named +//! the bytes' buffer or its host range, reached memory they do not name (a root or handle +//! table, a heap, an execution of render commands, a memory barrier inside the pass), waited +//! for or updated a fence, resolved, wrote visibility results, or recorded later (a pending +//! draw, a tile dispatch, a later color group), or that has an attachment over those bytes or +//! rendered through that image, or whose draws or attachments take a shadowed texture over +//! them (the run's own included, bound to a draw); an event or semaphore wait or a signal, a +//! host step (any new batch, where another queue's work may come between); a pass whose box +//! reaches past a linear run's, or one that cannot join (below); and the command buffer's end. +//! A shadowed texture's run ends too where its encoder no longer carries the image +//! (`shadow::ShadowCarry`: dropped at a fence's wait, or a write of the truth another way). +//! The work after the run then sees the bytes merged: its last merge lies before it in +//! submission order. +//! - **Which passes join** (each a run's first or a later pass): a pass of one part and one +//! color group, of one render pass instance for a shadowed texture, outside a predicated loop's +//! laying, whose first instance does not record inline, that names neither the bytes' buffer +//! nor its host range and touches nothing past its attachments (as above), whose other +//! attachments lie over none of the bytes, and that renders over no rasterization-rate map. +//! A linear attachment's pass joins only where it is encoded once: neither its commands nor its +//! attachments name a buffer over host pages, which a rebind would move and encode its encoder +//! again (`command_buffer/reencode.rs`), and it executes no render commands. A shadowed +//! texture's: one loaded and stored as a color (no stand-in, no planes, no resolve), whose +//! truth is a buffer's bytes it merges back into, laid out as one image's texels. Every other +//! pass merges after itself, as before; an encoder encoded again changes no run. +//! - **Encoded again.** A shadowed texture's run may hold passes over host pages, which a rebind +//! before the command buffer's first submission encodes again (`command_buffer/reencode.rs`): +//! each pass whose commands named a buffer that moved, and no other. Such a pass leaves its +//! run ([`RunMerge::leave`]): encoded again, it copies in, keeps and merges after itself as a +//! pass alone does, and its runs' passes before it and after it form runs of their own. The +//! merge it had taken over records after all, at the pass before it, so the bytes hold what +//! the passes before it wrote when it copies them in; and where a pass after it had taken its +//! merge over, it keeps the run's scratch again after its own merge +//! ([`RunMerge::keep_after`]), so that pass's run merges what the passes after it change +//! against what the bytes hold then. The merges of a pass encoded again take no scratch the +//! command buffer or its queue lends (`ShadowMerge::new`): its place may lie inside a run's +//! span. A run's merge records from what its pass resolved, the bytes its encoder named +//! (`Deferred::resolved_at_its_calls`): its command buffer's holds on host pages go at the +//! commit, and a rebind of one encodes the encoders that named it again rather than being +//! refused. //! -//! Counted: `WorkCounts::linear_merges_recorded` (one per run, one per pass that merges alone) -//! and `WorkCounts::linear_merges_taken_over`. +//! Counted: `WorkCounts::linear_merges_recorded` (one per linear run, one per pass that merges +//! alone) and `WorkCounts::linear_merges_taken_over`; a shadowed texture's run's keep and merge +//! once each in `WorkCounts::shadow_copies` (its merge as it records) and +//! `WorkCounts::shadow_texels_kept`, its scratch planned once +//! (`WorkCounts::shadow_merge_dispatches_planned`). use super::linear_merge::LinearMerge; use super::resource::ResourceKey; +use super::shadow::{ShadowCopy, Step}; +use super::shadow_merge::{MergeLease, ShadowMerge}; +use super::tracker::Barrier; use crate::device::functions::Vk; use ash::vk; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -/// A run's pass's merge, left to its batch's submission (`Deferred::RunMerge`): recorded -/// there unless a later pass of the run took it over. +/// The merge a run's pass leaves to its batch's submission: a linear attachment's +/// (`LinearMerge::record_alone`), or a shadowed texture's, a merge of its shadow's copies. +pub(super) enum RunWork { + Linear(Arc), + Shadow(ShadowCopy), +} + +/// A run's pass's merge, left to its batch's submission (`Deferred::RunMerge`): recorded there +/// unless a later pass of the run took it over and was not encoded again since. pub(super) struct RunMerge { - merge: Arc, + work: RunWork, taken: AtomicBool, + /// The pass that took it over was encoded again, and left the run ([`leave`](Self::leave)). + given_back: AtomicBool, + /// The merge of the run's pass before it, which this one took over. + took: Option>, } impl RunMerge { - /// The merge `merge` of a run's pass, not taken over. - pub(super) fn new(merge: Arc) -> Arc { + /// The merge `work` of a run's pass, not taken over, that took `took` over. + pub(super) fn new(work: RunWork, took: Option>) -> Arc { Arc::new(RunMerge { - merge, + work, taken: AtomicBool::new(false), + given_back: AtomicBool::new(false), + took, }) } - /// Whether a later pass of its run took it over: its segment records nothing. + /// Whether a later pass of its run took it over, and still holds it: its segment records + /// nothing. pub(super) fn taken(&self) -> bool { - self.taken.load(Ordering::Acquire) + self.taken.load(Ordering::Acquire) && !self.given_back.load(Ordering::Acquire) } /// Take it over: a later pass of its run left its own merge to its batch's submission, @@ -90,25 +147,78 @@ impl RunMerge { self.taken.store(true, Ordering::Release); } - /// Record the merge, not taken over, into `command_buffer` on its own - /// (`LinearMerge::record_alone`). + /// Its pass was encoded again, in place of its first recording and this merge (the module's + /// **Encoded again**): the merge it took over records after all. + pub(super) fn leave(&self) { + if let Some(before) = &self.took { + before.given_back.store(true, Ordering::Release); + } + } + + /// The keep its pass, encoded again, records after itself where a later pass of its run took + /// its merge over: of the image that pass went on over into the scratch its run's merge + /// compares (the module's **Encoded again**). `None` for a linear attachment's run, whose + /// passes are never encoded again, and a merge no later pass took over. + pub(super) fn keep_after(&self) -> Option { + let RunWork::Shadow(copy) = &self.work else { + return None; + }; + let Step::Merge(merge) = ©.step else { + return None; + }; + self.taken.load(Ordering::Acquire).then(|| ShadowCopy { + copies: Arc::clone(©.copies), + step: Step::Keep(Arc::clone(merge)), + kept: false, + area: None, + cause: None, + moves: None, + }) + } + + /// The shadowed texture's merge it records, for the counters; `None` for a linear + /// attachment's. + pub(super) fn shadow(&self) -> Option<&ShadowCopy> { + match &self.work { + RunWork::Shadow(copy) => Some(copy), + RunWork::Linear(_) => None, + } + } + + /// Record the merge, not taken over, into `command_buffer` on its own, between barriers from + /// everything before and to everything after (`LinearMerge::record_alone`). /// /// # Safety /// - /// As for `LinearMerge::record_alone`. + /// As for `LinearMerge::record_alone`, or `ShadowCopy::record` for a shadowed texture's: + /// `command_buffer` is recording, outside a render pass; the merge, its images, its scratch + /// and the texture's bytes are held until it completes, and the images rest in `GENERAL`. pub(super) unsafe fn record(&self, device: &Vk, command_buffer: vk::CommandBuffer) { // SAFETY: the caller's contract. - unsafe { self.merge.record_alone(device, command_buffer) } + unsafe { + match &self.work { + RunWork::Linear(merge) => merge.record_alone(device, command_buffer), + RunWork::Shadow(copy) => { + Barrier::everything().record(device, command_buffer); + copy.record(device, command_buffer, None); + Barrier::everything().record(device, command_buffer); + } + } + } } } -/// What a run's passes have in one: the image they render, and the surface's own image and its -/// subresource (`(level, layer, layers)`). +/// What a run's passes have in one: for a linear attachment, the image they render, and the +/// surface's own image and its subresource (`(level, layer, layers)`); for a shadowed texture, +/// its shadow's identity (`ShadowCopies::shadow_key`). #[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub(super) struct RunKey { - pub(super) backing: vk::Image, - pub(super) surface: vk::Image, - pub(super) subresource: (u32, u32, u32), +pub(super) enum RunKey { + Linear { + backing: vk::Image, + surface: vk::Image, + subresource: (u32, u32, u32), + }, + Shadow(ResourceKey), } /// Where an encoder ends among its command buffer's: the encoders ended before it, and the @@ -120,7 +230,8 @@ pub(super) struct RunPoint { pub(super) signals: bool, } -/// A pass's color that may join a run: the run's key, the key of its surface's bytes, and a box +/// A pass's color that may join a run: the run's key, the key of its bytes (a linear +/// attachment's surface's, a shadowed texture's truth), and, for a linear attachment, a box /// (`[x0, y0, x1, y1]`, half-open): the one its draws write in, or a run's. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) struct Joining { @@ -129,13 +240,49 @@ pub(super) struct Joining { pub(super) area: [u32; 4], } +impl Joining { + /// Whether it may go on with `run`, of its key: a linear attachment's box lies in the run's; + /// a shadowed texture's always may (a write outside its run's keep merges and keeps again, + /// the module's **A run**). + fn fits(&self, run: &Joining) -> bool { + match self.key { + RunKey::Linear { .. } => within(self.area, run.area), + RunKey::Shadow(_) => true, + } + } +} + +/// What an open run holds for its next pass: a linear attachment's merge, its scratch lent on as +/// the run ends; or the merge of a shadowed texture's run, whose keep it compares, with the hold +/// on its scratch or kept image, which no other merge takes until the run ends. +pub(super) enum RunHeld { + Linear(Arc), + Shadow { + merge: Arc, + lease: Option, + }, +} + +impl RunHeld { + /// The run ended: its merge lies before every command recorded from here on, so its + /// scratch is lent on (`merge_scratch.rs`), and a shadowed texture's kept image goes back to + /// its queue (`texture/kept_image.rs`). + pub(super) fn end(self) { + match self { + RunHeld::Linear(merge) => merge.lend(), + RunHeld::Shadow { lease, .. } => drop(lease), + } + } +} + /// What a color that may join a run takes as its pass ends ([`PassRuns::end_of`]). pub(super) enum Joined { - /// It goes on with the run before it: the run's box, its merge, and its last pass's merge - /// left to its submission, which the pass takes over once it left its own. + /// It goes on with the run before it: the run's box (a linear attachment's), what the run + /// holds, and its last pass's merge left to its submission, which the pass takes over once + /// it left its own. On { area: [u32; 4], - merge: Arc, + held: RunHeld, last: Arc, }, /// The run before it ended there, the box its draws write in reaching past the run's: it @@ -145,11 +292,11 @@ pub(super) enum Joined { Opens, } -/// An open run: its color's box, its merge, the latest pass's merge left to its submission, -/// where that pass ended, and how many render encoders ended since that touch none of it. +/// An open run: its color, what it holds, the latest pass's merge left to its submission, where +/// that pass ended, and how many render encoders ended since that touch none of it. struct Open { joining: Joining, - merge: Arc, + held: RunHeld, last: Arc, at: RunPoint, passed: usize, @@ -179,66 +326,70 @@ pub(super) struct PassRuns { impl PassRuns { /// For a render encoder ending at `now`, whose colors `joining` may join a run: what each - /// takes, and the merges of the runs it ends, to lend their scratch on. A run goes on with - /// the color of its key and bytes where the pass follows its last (`Open::follows`) and the - /// color's box lies in the run's; it ends where the color's box reaches past it + /// takes, and what the runs it ends hold, to let go of ([`RunHeld::end`]). A run goes on + /// with the color of its key and bytes where the pass follows its last (`Open::follows`) and + /// the color fits it ([`Joining::fits`]); it ends where a linear color's box reaches past it /// ([`Joined::Outgrew`]), where the pass does not follow it, or where the pass `touches` it - /// (by the run's key and the key of its surface's bytes); every other run counts the pass - /// as passed. + /// (by the run's key and the key of its bytes); every other run counts the pass as passed. pub(super) fn end_of( &mut self, now: RunPoint, joining: &[Joining], touches: impl Fn(&RunKey, ResourceKey) -> bool, - ) -> (Vec, Vec>) { + ) -> (Vec, Vec) { let mut joined: Vec = joining.iter().map(|_| Joined::Opens).collect(); let mut ended = Vec::new(); - self.open.retain_mut(|run| { + let mut open = Vec::with_capacity(self.open.len()); + for mut run in self.open.drain(..) { let follows = run.follows(now); let at = (joining.iter()) .position(|j| j.key == run.joining.key && j.bytes == run.joining.bytes); match at { - Some(at) if follows && within(joining[at].area, run.joining.area) => { + Some(at) if follows && joining[at].fits(&run.joining) => { joined[at] = Joined::On { area: run.joining.area, - merge: Arc::clone(&run.merge), - last: Arc::clone(&run.last), + held: run.held, + last: run.last, }; - false } Some(at) if follows => { joined[at] = Joined::Outgrew; - ended.push(Arc::clone(&run.merge)); - false + ended.push(run.held); } _ if !follows || touches(&run.joining.key, run.joining.bytes) => { - ended.push(Arc::clone(&run.merge)); - false + ended.push(run.held); } _ => { run.passed += 1; - true + open.push(run); } } - }); + } + self.open = open; (joined, ended) } - /// Open (or go on with) the run of `joining`, whose pass ending at `now` left its merge - /// `last`, of `merge`, to its batch's submission. + /// Open (or go on with) the run of `joining`, holding `held`, whose pass ending at `now` left + /// its merge `last` to its batch's submission. pub(super) fn open( &mut self, joining: Joining, - merge: Arc, + held: RunHeld, last: Arc, now: RunPoint, ) { self.open.push(Open { joining, - merge, + held, last, at: now, passed: 0, }); } + + /// End every open run as the command buffer commits, after which none goes on: what each + /// holds, to let go of ([`RunHeld::end`]). + pub(super) fn close(&mut self) -> Vec { + self.open.drain(..).map(|run| run.held).collect() + } } diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index d6f2f4a0c..62201edfd 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -303,7 +303,7 @@ use super::linear_merge::{LinearMerge, MERGE_STAGES}; use super::live_bind::{Emptied, LiveBind, Reshape, SettledHere}; use super::nan_clear::{keeps_nan_sign, NanDepthWrite}; use super::owned_kernel::OwnedModule; -use super::pass_runs::{Joined, Joining, RunKey, RunMerge}; +use super::pass_runs::{Joined, Joining, RunHeld, RunKey, RunMerge, RunWork}; use super::pipeline::Settled; use super::pipeline::{BufferForms, DrawPipeline}; use super::pipeline::{DrawDynamic, RawPipeline, RenderVariant, VariantObjects}; @@ -333,7 +333,8 @@ use super::sample_planes::{self, Planes, PlanesCommands}; use super::sample_positions; use super::sampler::OwnedSampler; use super::sampler::{ArgumentSamplers, SamplerState}; -use super::shadow::{self, ShadowCopy}; +use super::shadow::{self, ShadowCopies, ShadowCopy, ShadowTarget, Step}; +use super::shadow_merge::{MergeLease, ShadowMerge}; use super::shadow_stencil::ShadowStencil; use super::sparse::emulated::Scrub; use super::tessellation::{FactorBuffer, Factors}; @@ -1084,6 +1085,16 @@ struct RunColor { on: Option<(Arc, Arc)>, } +/// A pass's color that is a shadowed texture merged back, joining a run as the pass ends +/// (`pass_runs.rs`): its shadow, its run's key and bytes, and where it goes on with the run +/// before it, that run's merge (whose keep the encoder went on from), the hold on its scratch, +/// and its last pass's merge left to its submission. +struct ShadowRunColor { + copies: Arc, + joining: Joining, + on: Option<(Arc, Option, Arc)>, +} + /// One render pass instance of an encoder's pass (the module docs). struct Instance { /// The secondary command buffer its draws record into, against `compatible`. Null for a @@ -4691,11 +4702,13 @@ impl RenderLowering { (loaded(index, c) && stored(c)).then_some((index, c, own)) }) .collect::>(); - // A linear attachment's passes rendered apart, one after another, merge once, after the - // last (`pass_runs.rs`): the colors whose merge the pass leaves to its batch's - // submission, each with what it took from the runs, and the runs it goes on with, ends - // or passes. Nothing changes where the encoder is encoded again. + // A linear attachment's passes rendered apart, and a shadowed texture's merged back, one + // after another, merge once, after the last (`pass_runs.rs`): the colors whose merge the + // pass leaves to its batch's submission, each with what it took from the runs, and the + // runs it goes on with, ends or passes. Nothing changes where the encoder is encoded + // again. let mut runs: Vec = Vec::new(); + let mut shadow_runs: Vec = Vec::new(); let run_point = match core.encodes_again() || crate::replay::is_replaying() { true => None, false => Some(core.command_buffer().state().run_point()), @@ -4737,10 +4750,12 @@ impl RenderLowering { }) }; // The keys and images of the pass's attachments: their textures', their stand-ins' - // and their planes'. + // and their planes'; and the shadows among them. let mut attached: Vec<(ResourceKey, Option)> = Vec::new(); + let mut attached_shadows: Vec> = Vec::new(); let mut attach = |texture: &Texture| { attached.push((texture.use_key(), texture.raw_image().ok())); + attached_shadows.extend(texture.shadow().cloned()); }; for c in layout.colors.iter().flatten() { attach(&c.target.texture); @@ -4771,7 +4786,7 @@ impl RenderLowering { let mut joining = Vec::new(); for &(index, c, own) in &merging { let bytes = own.own.texture.use_key(); - let key = RunKey { + let key = RunKey::Linear { backing: c.target.texture.raw_image()?, surface: own.own.texture.raw_image()?, subresource: (own.own.level, own.own.layer, own.own.layers), @@ -4795,34 +4810,138 @@ impl RenderLowering { joining.push(Joining { key, bytes, area }); } } + // The shadows the pass's draws take. + let drawn_shadows: Vec<&Arc> = (instances.iter()) + .flat_map(|instance| instance.shadows.copies()) + .collect(); + // Whether `copies`, a shadow the pass takes, lies over the bytes `bytes` of a run's + // texture of shadow `key`: that shadow, one over the same bytes, or one over host + // pages they meet (overlapping host ranges name the same bytes, as above). + let pages_meet = |a: ResourceKey, b: ResourceKey| { + let (a, b) = (rebinds.host_range(a), rebinds.host_range(b)); + a.zip(b) + .is_some_and(|(a, b)| a.start < b.end && b.start < a.end) + }; + let over = |copies: &ShadowCopies, key: ResourceKey, bytes: ResourceKey| { + let (truth, _) = copies.truth(); + copies.shadow_key == key + || truth == bytes + || copies.alias() == Some(bytes) + || pages_meet(truth, bytes) + }; + // A shadowed texture's color that joins: one the pass loads and stores and renders + // itself (no stand-in, no planes), of a pass of one render pass instance, its truth a + // buffer's bytes it merges back into, laid out as one image's texels at its first + // level and slice; that names neither those bytes nor their host range, and whose + // other attachments and draws take no shadow over them (the texture itself bound to + // a draw among them) and lie over none of them. + for (c, copies) in (layout.colors.iter().flatten()) + .filter_map(|c| Some((c, c.target.texture.shadow()?))) + { + let (bytes, _) = copies.truth(); + let key = copies.shadow_key; + let image = matches!(copies.target(), Some(ShadowTarget::Image { .. })) + && copies.whole_area().is_some() + && c.target.level == 0 + && c.target.layer == 0; + let alone = attached + .iter() + .filter(|&&(k, _)| k == key || k == bytes) + .count() + == 1 + && (attached_shadows.iter()) + .filter(|other| over(other, key, bytes)) + .count() + == 1 + && !drawn_shadows.iter().any(|other| over(other, key, bytes)); + let joins = quiet + && !laying + && !inline + && instances.len() == 1 + && image + && copies.merges_back() + && c.load == LoadAction::Load + && stored(c) + && c.stand_in.is_none() + && c.planes.is_none() + && !named.contains(&bytes) + && !host_overlap(bytes) + && alone; + if joins { + let joined = Joining { + key: RunKey::Shadow(key), + bytes, + area: [0; 4], + }; + shadow_runs.push(ShadowRunColor { + copies: Arc::clone(copies), + joining: joined, + on: None, + }); + } + } + joining.extend(shadow_runs.iter().map(|run| run.joining)); let touches = |key: &RunKey, bytes: ResourceKey| { + let attached_over = |&(k, image): &(ResourceKey, Option)| match *key { + RunKey::Linear { + backing, surface, .. + } => k == bytes || image.is_some_and(|i| i == backing || i == surface), + RunKey::Shadow(shadow) => k == bytes || k == shadow, + }; + let shadow_over = |copies: &&Arc| match *key { + RunKey::Linear { .. } => false, + RunKey::Shadow(shadow) => over(copies, shadow, bytes), + }; !quiet || named.contains(&bytes) || host_overlap(bytes) - || attached.iter().any(|&(k, image)| { - k == bytes || image.is_some_and(|i| i == key.backing || i == key.surface) - }) + || attached.iter().any(attached_over) + || attached_shadows.iter().any(|copies| shadow_over(&copies)) + || drawn_shadows.iter().any(shadow_over) }; let (joined, ended) = core .command_buffer() .state() .pass_runs() .end_of(now, &joining, touches); - // Each run it ends lends its scratch on: its merge lies before this pass. - for merge in ended { - merge.lend(); + // Each run it ends lets go of its scratch: its merge lies before this pass. + for held in ended { + held.end(); } let whole = [0, 0, layout.extent[0], layout.extent[1]]; - for (run, joined) in runs.iter_mut().zip(joined) { + let mut joined = joined.into_iter(); + for (run, joined) in runs.iter_mut().zip(&mut joined) { match joined { - Joined::On { area, merge, last } => { + Joined::On { + area, + held: RunHeld::Linear(merge), + last, + } => { run.joining.area = area; run.on = Some((merge, last)); } + Joined::On { held, .. } => held.end(), Joined::Outgrew => run.joining.area = whole, Joined::Opens => {} } } + // A shadowed color going on with its run takes its image as the run's passes left + // it, kept before the first: where the encoder still carries it. + for (run, joined) in shadow_runs.iter_mut().zip(joined) { + match joined { + Joined::On { + held: RunHeld::Shadow { merge, lease }, + last, + .. + } => { + if core.go_on_shadow(&run.copies, Arc::clone(&merge)) { + run.on = Some((merge, lease, last)); + } + } + Joined::On { held, .. } => held.end(), + Joined::Outgrew | Joined::Opens => {} + } + } } // Each color's box: a run's where it joins one, else the one its draws write in. let area_of = |index: usize, c: &render_pass::ColorTarget, own: &StandIn| match runs @@ -5765,7 +5884,8 @@ impl RenderLowering { if !core.note_left_uses(MERGE_STAGES, merge.merge_uses()) { continue; } - let left = RunMerge::new(Arc::clone(merge)); + let took = run.on.as_ref().map(|(_, last)| Arc::clone(last)); + let left = RunMerge::new(RunWork::Linear(Arc::clone(merge)), took); core.defer(Deferred::RunMerge(Arc::clone(&left)))?; if let Some((_, last)) = &run.on { last.take_over(); @@ -5774,7 +5894,7 @@ impl RenderLowering { let now = run_point.ok_or_else(|| internal("a run's pass encoded again"))?; (core.command_buffer().state().pass_runs()).open( run.joining, - Arc::clone(merge), + RunHeld::Linear(Arc::clone(merge)), left, now, ); @@ -5871,6 +5991,48 @@ impl RenderLowering { .chain(stood_in) .chain(planes_images) .collect(); + // Each shadowed color of a run leaves its merge to its batch's submission, its uses noted + // here, as its encoder's end would have merged it; the run's merge before it, taken over + // once it is (`pass_runs.rs`). The run holds the merge's scratch past the encoder's end. + for ShadowRunColor { + copies, + joining, + on, + } in shadow_runs + { + let Some(copy) = core.leave_shadow_merge(&copies) else { + continue; + }; + let Step::Merge(merge) = ©.step else { + return Err(internal("a run's copy back that merges nothing")); + }; + let merge = Arc::clone(merge); + if !core.note_left_uses(copy.stages(), ©.uses()) { + continue; + } + // Reported to a log of the pages as the shadow's own, as the copy back would be. + if let Some((log, bytes)) = copy.written_log(&device) { + core.command_buffer().dirty().wrote_back(log, bytes); + } + // The scratch of the run it went on with, or of the keep it made since (a merge of + // the run's, then a keep that holds more, `ShadowSync::before`). + let (lease, took) = match on { + Some((kept, lease, last)) if Arc::ptr_eq(&kept, &merge) => (lease, Some(last)), + Some((_, lease, last)) => { + drop(lease); + (core.take_lease(&merge), Some(last)) + } + None => (core.take_lease(&merge), None), + }; + let left = RunMerge::new(RunWork::Shadow(copy), took.clone()); + core.defer(Deferred::RunMerge(Arc::clone(&left)))?; + if let Some(last) = &took { + last.take_over(); + } + let now = run_point.ok_or_else(|| internal("a run's pass encoded again"))?; + let held = RunHeld::Shadow { merge, lease }; + (core.command_buffer().state().pass_runs()).open(joining, held, left, now); + } // What the pass's commands use, held until the command buffer completes as one object, // which lets go of them in this order: the command buffer lets go of what it holds from // the last retained back. diff --git a/crates/metal2vulkan-runtime/src/render/shadows.rs b/crates/metal2vulkan-runtime/src/render/shadows.rs index 728bf514a..eb3a4237d 100644 --- a/crates/metal2vulkan-runtime/src/render/shadows.rs +++ b/crates/metal2vulkan-runtime/src/render/shadows.rs @@ -228,6 +228,11 @@ impl InstanceShadows { self.shadows.is_empty() } + /// The shadowed textures the draws use. + pub(super) fn copies(&self) -> impl Iterator> { + self.shadows.iter().map(|shadow| &shadow.copies) + } + /// Whether each of `shadows` is among the gathered textures, writing only where the gathered /// use may: an execution's draw uses only what its call gathered (`render/executions.rs`). pub(super) fn covers(&self, shadows: &[ShadowUse]) -> bool { diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index e3ccdb881..5a35627d3 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -71,7 +71,14 @@ //! texel ([`ShadowUse::overwrites`]) keeps nothing, as its copy back writes only texels it //! wrote; that copy back goes before the keep of a later command that writes through the //! texture, since the merge after the keep takes only the words changed since it. The keeps' -//! scratch is the encoder's, one per texture and rectangle. +//! scratch is the encoder's, one per texture and rectangle. A run of render passes over the +//! texture, one after another in one batch with nothing between them that may touch its bytes +//! (`pass_runs.rs`), is kept before its first pass and merged after its last: each later pass +//! goes on over the image the one before left ([`ShadowSync::go_on`]), with no keep, and its +//! merge compares the first keep; a pass of the run that writes outside that keep merges it and +//! keeps every texel next, which every later pass of the run writes inside, and one that needs +//! texels beyond those the image holds (its copy in moved only a pass's scissors' texels) merges +//! what was kept and copies every texel in. //! - **Overwrites over logged pages** ([`ShadowCopies::logged`]: host pages whose consumer logs //! every write to them, `dirty_pages.rs`). A command that replaces every texel of such a shadow //! takes the merge instead of the plain copy back: its copy in (which moves only the rows the @@ -111,9 +118,12 @@ //! the merge reads there is as Metal's answer. A block can reach past the tiles the draws reach //! (a 256-byte block of a row holds 64 such texels, two of those tiles), never past the //! rectangle; and the merge undoes only a write made between its read of the block and its -//! store, a shorter window than a tile's from its load to its store. A use joined with another -//! that writes through the texture otherwise (a draw's write to it as a bound texture) stores -//! the words alone. +//! store, a shorter window than a tile's from its load to its store. A run of such passes +//! (`pass_runs.rs`) merges once over its keep, which holds every pass's rectangle (the first +//! pass's, or every texel once a pass wrote outside it): a block holding a word one pass changed +//! may reach past that pass's rectangle, by less than a block, never past the keep's, under the +//! same window. A use joined with another that writes through the texture otherwise (a draw's +//! write to it as a bound texture) stores the words alone. //! - **Ordering.** A copy is a command of the encoder with uses of both the buffer's bytes and the //! image, so the tracker orders it against the encoder's other commands and other encoders' //! like any use: the texture and its buffer are one resource to it. In an encoder whose @@ -790,6 +800,18 @@ impl ShadowCopies { x0 <= x && y0 <= y && x1 >= x + extent.width && y1 >= y + extent.height } + /// Every texel of a one-region 2D texture's image over a buffer's bytes, `[x0, y0, x1, y1)`, as + /// [`covers`](Self::covers) takes a rectangle; `None` for any other shadow. + pub(super) fn whole_area(&self) -> Option<[u32; 4]> { + let [region] = (self.target())?.image_regions(true)? else { + return None; + }; + let x = u32::try_from(region.image_offset.x).ok()?; + let y = u32::try_from(region.image_offset.y).ok()?; + let extent = region.image_extent; + Some([x, y, x + extent.width, y + extent.height]) + } + /// Whether `used` touches the texture's truth: its bytes, or its image's levels and layers. pub(super) fn meets(&self, used: &Use) -> bool { let (key, range) = self.truth(); @@ -839,7 +861,7 @@ impl ShadowCopies { } /// Whether two shadowed textures copy some of the same truth. - fn shares_truth(&self, other: &ShadowCopies) -> bool { + pub(super) fn shares_truth(&self, other: &ShadowCopies) -> bool { let ((key, range), (other_key, other_range)) = (self.truth(), other.truth()); let mine = [Some(key), self.alias()]; let theirs = [Some(other_key), other.alias()]; @@ -851,7 +873,7 @@ impl ShadowCopies { /// The key of the host memory the truth's buffer joined (`host_aliases.rs`): a use of it /// touches the same bytes as one of the buffer's own. - fn alias(&self) -> Option { + pub(super) fn alias(&self) -> Option { match &self.source { ShadowSource::Bytes { alias, .. } | ShadowSource::Converted { alias, .. } @@ -2135,9 +2157,12 @@ fn merged_back(shadow: &ShadowUse) -> bool { /// texels inside `kept` (`None` every texel), stores whole blocks where it is cut to the texels' /// rows (`shadow_merge.rs`): the command replaces every texel ([`ShadowUse::overwrites`], over /// logged pages, as [`merged_back`] takes it), or writes through it only by a render pass's -/// stores of the tiles of its area ([`ShadowUse::tile_stores`]) and the keep is that area. +/// stores of the tiles of its area ([`ShadowUse::tile_stores`]) and the keep holds that area (it +/// is that area, or the rectangle bounding it and the areas of the passes of its run before it, +/// `pass_runs.rs`, each of which wrote through the texture by such stores alone). fn stores_blocks(shadow: &ShadowUse, kept: Option<[u32; 4]>) -> bool { - shadow.overwrites || (shadow.tile_stores && kept.is_some() && kept == shadow.area) + let kept_area = kept.is_some() && shadow.area.is_some() && holds(kept, shadow.area); + shadow.overwrites || (shadow.tile_stores && kept_area) } /// Whether a command that replaces every texel of `shadow` ([`ShadowUse::overwrites`]) takes no @@ -2349,6 +2374,12 @@ struct Entry { /// first use's copy in is the one the carry takes off the run /// (`WorkCounts::shadow_texels_first_copy_in_carried`). carried: bool, + /// Its image goes on from a run of passes before this encoder's, kept in `merge` before the + /// run's first ([`ShadowSync::go_on`], `pass_runs.rs`): a command that writes outside what + /// that keep holds keeps every texel of the texture next, and one that needs texels beyond + /// what the image holds copies every texel in, so the run's later passes write inside the + /// keep and read inside the image. + run: bool, /// When [`Standing::Current`], the rectangle bounding the texels whose bytes changed since the image's /// copy in, where only writes [`Within`] it changed them (the module's rules): the next /// command that uses the texture copies those in first, or those of them it reads where it @@ -2763,6 +2794,7 @@ impl ShadowSync { scratch: None, stale, carried: carried.is_some(), + run: false, }); self.entries.len() - 1 } @@ -2823,6 +2855,52 @@ impl ShadowSync { } } + /// Go on with a run of passes over the texture of `copies` (`pass_runs.rs`): its image, which + /// the encoder carries, as the run's passes left it, written through since `merge` kept it + /// before the run's first, as an earlier command of this encoder would have left it. So the + /// encoder's first command that writes through it takes no keep, and the copy back after its + /// last is a merge in `merge` (or in a scratch a later keep took, where a command writes + /// outside what `merge` keeps, after a merge in it: [`before`](Self::before)). Whether it + /// could: `false`, changing nothing, where the encoder carries no such image, or one stale + /// somewhere, or met the texture already. + pub(super) fn go_on(&mut self, copies: &Arc, merge: M) -> bool { + let key = copies.shadow_key; + let met = self.entries.iter().any(|e| e.copies.shadow_key == key); + let carried = (self.carry.entries.iter()) + .any(|carried| carried.copies.shadow_key == key && carried.stale.is_none()); + if met || !carried { + return false; + } + let i = self.entry(copies); + let entry = &mut self.entries[i]; + entry.dirty = true; + entry.area = None; + entry.merge = Some(merge.clone()); + entry.scratch = Some(merge); + entry.run = true; + true + } + + /// The copy back of what the encoder's commands wrote through the texture of `copies`, taken + /// now as the merge a run's pass leaves to its batch's submission (`pass_runs.rs`): where its + /// image was kept as it merges back and written through since, not two ways, its merge + /// ([`copy_back`](Self::copy_back)), after which the image holds the truth as the commands + /// left it, carried on as the encoder ends. `None`, changing nothing, for any other texture. + pub(super) fn leave_merge(&mut self, copies: &ShadowCopies) -> Option> { + let key = copies.shadow_key; + let i = self + .entries + .iter() + .position(|e| e.copies.shadow_key == key)?; + let entry = &self.entries[i]; + if !entry.dirty || entry.merge.is_none() || entry.two_ways { + return None; + } + let mut copies = Vec::new(); + self.copy_back(i, &mut copies); + copies.pop() + } + /// The copies to record, in order, before a command that uses the shadowed textures /// `shadows` and has `uses` (every use of the command, the textures' among them): merges of /// the textures kept before the command before, copies back of what the command touches, @@ -2873,20 +2951,26 @@ impl ShadowSync { merged_kept.push(Arc::clone(&shadow.copies)); // The texels the command writes, where it bounds them and the copies are cut so. let writes = shadow.area.filter(|_| shadow.copies.cuts_back()); - let scratch = self + let entry = self .entries .iter() - .find(|e| e.copies.shadow_key == shadow.copies.shadow_key) - .and_then(|e| e.scratch.as_ref()); + .find(|e| e.copies.shadow_key == shadow.copies.shadow_key); + let scratch = entry.and_then(|e| e.scratch.as_ref()); // A scratch made for a command of the other kind (one whose merge stores whole // blocks, or one whose does not) is merged and kept again in a new one: only such // a command's merge stores whole blocks (`shadow_merge.rs`). let same = |scratch: &M| scratch.in_blocks() == stores_blocks(shadow, writes); + // A run's pass that writes outside its run's keep keeps every texel next, which + // every later pass of the run writes inside (`pass_runs.rs`). + let run = entry.is_some_and(|e| e.run); let area = match scratch { Some(scratch) if holds(scratch.kept_area(), writes) && same(scratch) => { continue } - Some(scratch) => bounding(scratch.kept_area(), writes), + Some(scratch) => match (run, writes, shadow.copies.whole_area()) { + (true, Some(_), Some(whole)) => Some(whole), + _ => bounding(scratch.kept_area(), writes), + }, None => writes, }; let made_for = MergeFor { @@ -2960,6 +3044,12 @@ impl ShadowSync { let entry = &self.entries[i]; let beyond_held = entry.standing == Standing::Current && !overwrites && !holds(entry.held, needs); + // A pass of a run of passes that needs texels beyond those takes every texel in, so + // the run's later passes need none beyond them (`pass_runs.rs`). + let needs = match beyond_held && entry.run { + true => None, + false => needs, + }; // The image holds the buffer's texels only inside its last copy in's rectangle: what // the encoder wrote through it goes back first, then the copy in below moves what // this command needs. diff --git a/crates/metal2vulkan-runtime/src/shadow_merge.rs b/crates/metal2vulkan-runtime/src/shadow_merge.rs index 144fe9c1a..e8a0b433d 100644 --- a/crates/metal2vulkan-runtime/src/shadow_merge.rs +++ b/crates/metal2vulkan-runtime/src/shadow_merge.rs @@ -336,12 +336,15 @@ impl ShadowMerge { /// texels (the module docs), else of every texel. A kept image is one of `images`, its /// queue's, held by the lease returned, which the encoder keeps to its end, else one made /// and kept there; a scratch one `pool`, its command buffer's, lends, else one made, held by - /// the lease too. Refused as `new_buffer` refuses the scratch. + /// the lease too. Where not `lent` (an encoder encoded again, whose place may lie inside a + /// run of passes holding one, `pass_runs.rs`), neither is taken from `images` or `pool`. + /// Refused as `new_buffer` refuses the scratch. pub(super) fn new( device: &Device, copies: &ShadowCopies, (two_ways, blocks, area): (bool, bool, Option<[u32; 4]>), (images, pool): (&KeptImages, &Arc), + lent: bool, ) -> Result<(ShadowMerge, Option), Error> { let ( ShadowSource::Bytes { @@ -429,7 +432,7 @@ impl ShadowMerge { let mut lease = None; let mut zero = None; let (held, placed) = if let Some((texel, extent)) = kept_image { - let image = match images.take(texel, extent) { + let image = match lent.then(|| images.take(texel, extent)).flatten() { Some(TakenImage { image, lease: taken, @@ -465,7 +468,10 @@ impl ShadowMerge { let written = cut.is_some() || (in_place && copies.copies_out_whole(rounded)); let spares = copies.merge_scratch.clone(); let whole = roles * rounded.next_multiple_of(PART_ALIGNMENT); - let lent = pool.take(ScratchKind::Shadow, length).or_else(|| { + let pooled = lent + .then(|| pool.take(ScratchKind::Shadow, length)) + .flatten(); + let lent = pooled.or_else(|| { let spare = spares.take(length)?; Some(Scratch::new( spare, diff --git a/crates/metal2vulkan-runtime/src/tests/linear_runs.rs b/crates/metal2vulkan-runtime/src/tests/linear_runs.rs index bdadb4b57..5590e358d 100644 --- a/crates/metal2vulkan-runtime/src/tests/linear_runs.rs +++ b/crates/metal2vulkan-runtime/src/tests/linear_runs.rs @@ -97,7 +97,7 @@ const RUNS: u64 = 7; /// The state that draws a rectangle (`tob_rect`) of the color in fragment buffer 0 /// (`tob_solid`) with no attachment. -fn attachmentless(device: &Device) -> RenderPipelineState { +pub(super) fn attachmentless(device: &Device) -> RenderPipelineState { let library = library(device, "engine/tob_renders.ll"); let function = |name: &str| { let function = library.new_function_with_name(name).unwrap(); diff --git a/crates/metal2vulkan-runtime/src/tests/merge_scratch.rs b/crates/metal2vulkan-runtime/src/tests/merge_scratch.rs index 9a3c49be2..49b944ae7 100644 --- a/crates/metal2vulkan-runtime/src/tests/merge_scratch.rs +++ b/crates/metal2vulkan-runtime/src/tests/merge_scratch.rs @@ -13,11 +13,11 @@ //! (`linear_attachment.rs`, `linear_merge.rs`), as NVIDIA's devices render it beside a depth //! attachment: the passes form a run or two merged once each (`pass_runs.rs`, //! `tests::linear_runs`), each merge taking one scratch, and the runtime's device memory grows by -//! no scratch a pass. A target that is a shadow -//! (host pages on every device, and rows the device's linear images do not lay out) is merged -//! back at each encoder's end (`shadow_merge.rs`): its merges after the first take the scratch an -//! earlier encoder was done with. Either way the texels equal those the same passes leave in a -//! private texture of the same first texels, and the bytes between the rows keep theirs. +//! no scratch a pass. A target that is a shadow merged back (host pages on every device, and +//! rows the device's linear images do not lay out, `shadow_merge.rs`) is kept before the first +//! pass and merged back after the last, its passes one run (`pass_runs.rs`, +//! `tests::shadow_runs`). Either way the texels equal those the same passes leave in a private +//! texture of the same first texels, and the bytes between the rows keep theirs. //! //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are the owned fixture @@ -337,8 +337,8 @@ fn reference(queue: &CommandQueue, state: &RenderPipelineState, width: u64) -> V /// [`passes`] over a target over `over`'s buffer of `width` texels a row, `row` bytes apart, the /// rule forced: its texels equal the private texture's, the bytes between its rows keep theirs, /// and its merges take few scratches (a linear image's, one a run; a shadow's merged back, one -/// lent to every later one), the device's memory growing by less than an eighth of what a -/// scratch a pass would take. +/// keep and one merge for the run of passes), the device's memory growing by less than an eighth +/// of what a scratch a pass would take. fn one_scratch(over: Over, (width, row): (u64, u64)) { let cache = Scratch::new(&format!("merge-scratch-{over:?}-{width}")); let host = Host::new(row * H); @@ -371,14 +371,15 @@ fn one_scratch(over: Over, (width, row): (u64, u64)) { let recorded = delta(|c| c.linear_merges_recorded); let taken_over = delta(|c| c.linear_merges_taken_over); let shadow_reused = delta(|c| c.shadow_merge_scratches_reused); + let kept = delta(|c| c.shadow_texels_kept); let grown = encoded.device_memory_allocated - before.device_memory_allocated; // A merge of every texel's rows: its kept and changed parts. let scratch = 2 * width * TEXEL * H; println!( "MERGE-SCRATCH {over:?}: {apart} passes apart, linear merges {recorded} recorded and \ {taken_over} taken over, linear scratches {made} made and {reused} reused, shadow \ - scratches {shadow_reused} reused; device memory grew {grown} bytes while encoding ({} \ - merges' scratch)", + scratches {shadow_reused} reused, shadow texels kept {kept}; device memory grew {grown} \ + bytes while encoding ({} merges' scratch)", grown / scratch ); match (linear, merged) { @@ -401,10 +402,8 @@ fn one_scratch(over: Over, (width, row): (u64, u64)) { "each run's merge takes one scratch" ); } - (false, true) => assert!( - shadow_reused >= PASSES as u64 - 1, - "every shadow merge after the first takes a scratch: {shadow_reused}" - ), + // One run of passes (`pass_runs.rs`): kept once, every texel, before the first. + (false, true) => assert_eq!(kept, width * H, "the passes keep once, as one run"), (false, false) => println!("MERGE-SCRATCH {over:?}: no merge"), } assert!( diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 540a4b02f..f08460f03 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -311,6 +311,8 @@ mod shadow_carried_read; mod shadow_host_writes; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod shadow_merge_read; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod shadow_runs; mod shadow_stencil; #[cfg(all(debug_assertions, any(m2v_gpu, m2v_cpu_icd)))] mod shared_draw_locks; diff --git a/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs b/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs new file mode 100644 index 000000000..f8111419f --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs @@ -0,0 +1,868 @@ +//! Runs of passes over a shadowed texture merged back, merged once (`pass_runs.rs`): a 2D +//! `BGRA8Unorm` texture of 1024 x 1024 texels over a no-copy buffer's host pages whose rows lie +//! 15360 bytes apart (a 3840-texel surface's), so each row holds 11264 bytes past its texels that +//! no pass writes: a shadow on every device, its writes merged back into the bytes +//! (`shadow.rs`'s **Merged back**). +//! +//! One command buffer mixes passes over the texture (each loading and storing it, blending a +//! rectangle over it) with the encoders and commands that end a run or pass it: a 1x1 +//! attachmentless render encoder, a pass over another texture, a blit reading the texture's +//! texels, a blit reading the buffer's bytes, an event signal, a pass naming the texture's +//! buffer, and a pass over a second texture over the same bytes. The sequence runs three times: +//! over the texture, where its passes form the runs the steps make, kept and merged once each; +//! over the texture again with a blit between every two encoders, which ends every run, so every +//! pass keeps and merges for itself; and over a private texture of the same first texels. The +//! texels each blit read mid-sequence, and those the sequence left, are the same in all three, +//! and the bytes between the rows keep theirs. +//! +//! A second sequence draws over the whole texture under a scissor a pass at a time: the run's +//! first pass keeps its scissor's texels, the second, outside them, merges that keep and keeps +//! every texel, and the run goes on over that keep, its merges storing whole blocks of the rows +//! as a pass's alone does (`shadow.rs`'s **Stored attachments**). +//! +//! A third sequence encodes passes over the texture, some binding a second no-copy buffer +//! (which their function does not read), behind a wait for a shared event only the host +//! signals; the second buffer is rebound before the signal, which encodes those passes again +//! before the command buffer's first submission (`command_buffer/reencode.rs`): each leaves its +//! run, and the texels are still the private texture's. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are the owned fixture +//! `validation/fixtures/public/engine/tob_renders.ll` (`llvm-as`). + +use super::blit_holds::{device, Scratch, WAIT}; +use super::encoder_holds::{bytes_of, library}; +use super::linear_runs::attachmentless; +use super::merge_scratch::{blit, drawn, read, staged, TEXEL}; +use crate::{ + BlitOption, Buffer, CommandBuffer, CommandQueue, Device, Error, EventRef, HostMemory, + LoadAction, Origin, PipelineOptions, RenderPassDescriptor, RenderPipelineState, + ResourceOptions, ScissorRect, Size, StoreAction, Texture, TextureDescriptor, WorkCounts, +}; +use metal2vulkan::metal::{BlendFactor, PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use std::alloc::Layout; +use std::ptr::NonNull; + +/// The texture's width and height, and its rows' pitch in the buffer. +const W: u64 = 1024; +const H: u64 = 1024; +const ROW: u64 = 15360; + +/// The byte the bytes between the rows hold, which no pass writes. +const BETWEEN: u8 = 0x5a; + +/// One step of the sequence. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Step { + /// A pass over the texture blending rectangle `i` (`drawn`). + Draw(usize), + /// A 1x1 render encoder of no attachment, one draw. + Lone, + /// A pass over another texture, binding the texture's buffer as a fragment buffer its + /// function does not read where `true`, else a buffer of its own. + Other(bool), + /// A blit copying the texture's texels into a buffer, read after the command buffer. + Read, + /// A blit copying the buffer's bytes into a buffer, read after the command buffer (the + /// private texture's texels, for it). + Bytes, + /// An event signal. + Signal, + /// A pass over a second texture over the same bytes blending rectangle `i` (the private + /// texture itself, for it). + Alias(usize), +} + +use Step::{Alias, Bytes, Draw, Lone, Other, Read, Signal}; + +/// The passes of the sequence's last run, which goes to the command buffer's end. +const LAST_RUN: usize = 40; + +/// The sequence, and the runs it makes, each of the passes noted: +/// 1. `Draw(0)` to `Draw(3)`: the 1x1 encoder and the pass over another texture pass it; the +/// blit reading the texels ends it (4 passes); +/// 2. `Draw(4)`, `Draw(5)`: the blit reading the bytes ends it (2); +/// 3. `Draw(6)`, `Draw(7)`: the signal ends it (2); +/// 4. `Draw(8)`, the first pass after the signal, which ends as the signal is pending: no pass +/// follows it (`pass_runs::Open::follows`) (1); +/// 5. `Draw(9)`: the pass naming the texture's buffer ends it (1); +/// 6. `Draw(10)`: the pass over the second texture over the same bytes ends it (1); +/// 7. `Alias(11)`, a run of its own over the second texture, which the next pass over the +/// texture ends (1); +/// 8. `Draw(12)`, `Draw(13)`: the blit reading the bytes ends it (2); +/// 9. `Draw(14)` on, [`LAST_RUN`] passes, past a 1x1 encoder, to the command buffer's end. +fn steps() -> Vec { + let mut steps = vec![ + Draw(0), + Draw(1), + Lone, + Draw(2), + Other(false), + Draw(3), + Read, + Draw(4), + Draw(5), + Bytes, + Draw(6), + Draw(7), + Signal, + Draw(8), + Draw(9), + Other(true), + Draw(10), + Alias(11), + Draw(12), + Draw(13), + Bytes, + ]; + for i in 0..LAST_RUN { + if i == LAST_RUN / 2 { + steps.push(Lone); + } + steps.push(Draw(14 + i)); + } + steps +} + +/// The passes over the texture or the second one among [`steps`], and the runs they make, each +/// opened by one of [`FIRSTS`], the passes that keep. +const PASSES: u64 = 14 + LAST_RUN as u64; +const RUNS: u64 = 9; +const FIRSTS: [Step; RUNS as usize] = [ + Draw(0), + Draw(4), + Draw(6), + Draw(8), + Draw(9), + Draw(10), + Alias(11), + Draw(12), + Draw(14), +]; + +/// The state that blends a half-transparent rectangle (`tob_rect`, corners from vertex buffer 0) +/// of the color in fragment buffer 0 (`tob_solid`) over a `BGRA8Unorm` color, of no depth. +fn blending(device: &Device) -> RenderPipelineState { + let library = library(device, "engine/tob_renders.ll"); + let function = |name: &str| { + let function = library.new_function_with_name(name).unwrap(); + StageSource::Function(function.function_descriptor()) + }; + let mut descriptor = RenderPipelineDescriptor::new(function("tob_rect")); + descriptor.fragment = Some(function("tob_solid")); + let mut color = ColorAttachmentDescriptor::new(PixelFormat::BGRA8Unorm); + color.blending_enabled = true; + color.source_rgb_blend_factor = BlendFactor::SourceAlpha; + color.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; + color.source_alpha_blend_factor = BlendFactor::One; + color.destination_alpha_blend_factor = BlendFactor::Zero; + descriptor.color_attachments[0] = Some(color); + device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// What the texture's bytes hold first, rows `row` bytes apart: each texel's bytes a counting +/// pattern of its place among the texels, which no pass draws, and [`BETWEEN`] between the rows. +fn first_bytes(row: u64) -> Vec { + (0..row * H) + .map(|i| match i % row < W * TEXEL { + true => ((i / row * W * TEXEL + i % row) * 7 % 251) as u8, + false => BETWEEN, + }) + .collect() +} + +/// The texels of `bytes`, rows [`ROW`] bytes apart, packed. +fn texels(bytes: &[u8]) -> Vec { + (bytes.chunks(ROW as usize)) + .flat_map(|r| &r[..(W * TEXEL) as usize]) + .copied() + .collect() +} + +/// The bytes between the rows of `bytes` that no longer hold [`BETWEEN`]. +fn between_changed(bytes: &[u8]) -> usize { + (0..bytes.len()) + .filter(|&i| (i as u64 % ROW) >= W * TEXEL && bytes[i] != BETWEEN) + .count() +} + +/// Page-aligned host memory of `length` bytes, freed when dropped: declared before the device's +/// buffer over it, so dropped after it. +struct Host(NonNull, Layout); + +impl Host { + fn new(length: u64) -> Host { + let layout = + Layout::from_size_align(length.next_multiple_of(64 << 10) as usize, 64 << 10).unwrap(); + // SAFETY: the layout's size is not zero. + let pointer = unsafe { std::alloc::alloc_zeroed(layout) }; + Host(NonNull::new(pointer).unwrap(), layout) + } + + /// Its pages, for a no-copy buffer or a rebind. + /// + /// # Safety + /// + /// They outlive every buffer over them, which alone uses them while it lives. + unsafe fn memory(&self) -> HostMemory { + // SAFETY: the caller's contract. + unsafe { HostMemory::new(self.0) } + } + + fn length(&self) -> u64 { + self.1.size() as u64 + } +} + +impl Drop for Host { + fn drop(&mut self) { + // SAFETY: allocated with this layout in `new`. + unsafe { std::alloc::dealloc(self.0.as_ptr(), self.1) }; + } +} + +/// A no-copy buffer over `host`; `None`, printed, where the device imports no host memory. +fn over_pages(device: &Device, host: &Host) -> Option { + // SAFETY: the memory outlives the buffer, and only its commands use it meanwhile. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + host.memory(), + host.length(), + ResourceOptions::default(), + None, + ) + }; + match made { + Ok(buffer) => Some(buffer), + Err(Error::Unsupported(gap)) => { + eprintln!("SHADOW-RUNS: the device imports no host memory: {gap:?}"); + None + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + } +} + +/// A `BGRA8Unorm` texture of [`W`] x [`H`] over `buffer`'s first bytes, rows [`ROW`] apart: a +/// shadow merged back. +fn texture_over(buffer: &Buffer) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, W, H, false); + descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + descriptor.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&descriptor, 0, ROW).unwrap(); + assert!( + texture.shadow().is_some_and(|copies| copies.merges_back()), + "the texture is a shadow merged back" + ); + texture +} + +/// A `Private` `BGRA8Unorm` texture of [`W`] x [`H`] holding [`first_bytes`]'s texels. +fn private_texture(queue: &CommandQueue) -> Texture { + let device = queue.device(); + let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, W, H, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::private(); + let texture = device.new_texture(&d).unwrap(); + let packed = W * TEXEL; + let source = staged(device, &first_bytes(packed)); + blit(queue, |b| { + (b.copy_from_buffer_to_texture( + &source, + 0, + packed, + packed * H, + Size::new(W, H, 1), + &texture, + 0, + 0, + Origin::new(0, 0, 0), + BlitOption::None, + )) + .unwrap() + }); + texture +} + +/// Where a pass's rectangle comes from: [`drawn`]'s for its index, or a buffer holding its +/// corners, bound as vertex buffer 0. +#[derive(Clone, Copy)] +enum Corners<'a> { + Drawn, + From(&'a Buffer), +} + +/// Encode a pass over `texture`, loading and storing it, that blends rectangle `i` of +/// `corners` in `i`'s color with `state`; binding `named` as fragment buffer 1, which the +/// function does not read. +fn pass( + command_buffer: &CommandBuffer, + texture: &Texture, + state: &RenderPipelineState, + (i, corners): (usize, Corners<'_>), + named: Option<&Buffer>, +) { + let mut descriptor = RenderPassDescriptor::new(); + let color = &mut descriptor.color_attachments[0]; + color.texture = Some(texture.clone()); + color.load_action = LoadAction::Load; + color.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap(); + encoder.set_render_pipeline_state(state).unwrap(); + let (rect, rgba) = drawn(i); + match corners { + Corners::Drawn => { + (encoder.set_vertex_bytes(&bytes_of(&rect, f32::to_le_bytes), 0)).unwrap(); + } + Corners::From(buffer) => encoder.set_vertex_buffer(Some(buffer), 0, 0).unwrap(), + } + (encoder.set_fragment_bytes(&bytes_of(&rgba, f32::to_le_bytes), 0)).unwrap(); + if let Some(named) = named { + encoder.set_fragment_buffer(Some(named), 0, 1).unwrap(); + } + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); + encoder.end_encoding().unwrap(); +} + +/// Encode a blit copying `texture`'s texels into `out`, packed. +fn read_texels(command_buffer: &CommandBuffer, texture: &Texture, out: &Buffer) { + let packed = W * TEXEL; + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + (encoder.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(W, H, 1), + out, + 0, + packed, + packed * H, + BlitOption::None, + )) + .unwrap(); + encoder.end_encoding().unwrap(); +} + +/// What the sequence runs over: the texture, its buffer (`None` for the private texture), the +/// second texture over its bytes, the other texture, and the states. +struct Scene<'a> { + texture: &'a Texture, + buffer: Option<&'a Buffer>, + alias: &'a Texture, + other: &'a Texture, + blending: &'a RenderPipelineState, + attachmentless: &'a RenderPipelineState, +} + +/// What a read mid-sequence copied: the texels, packed, and the bytes between the rows that +/// changed (none for the private texture). +type Got = (Vec, usize); + +/// [`steps`] over `over` in one command buffer, committed and completed; a blit between every +/// two encoders where `apart`, copying 4 bytes between buffers of its own. What each [`Read`] +/// and [`Bytes`] copied, and the steps that kept a shadowed texture's texels as they were +/// encoded (`WorkCounts::shadow_texels_kept`). +fn sequence(queue: &CommandQueue, over: &Scene<'_>, apart: bool) -> (Vec, Vec) { + let device = queue.device(); + let packed = W * TEXEL; + let unread = device.new_buffer(256, ResourceOptions::private()).unwrap(); + let (from, into) = (staged(device, &[1; 4]), staged(device, &[0; 4])); + let event = device.new_event().unwrap(); + let steps = steps(); + let length = |step: &Step| match (step, over.buffer) { + (Read, _) | (Bytes, None) => Some(packed * H), + (Bytes, Some(_)) => Some(ROW * H), + _ => None, + }; + let reads = (steps.iter()) + .filter_map(|step| Some((*step, length(step)?))) + .map(|(step, length)| { + let out = device.new_buffer(length, ResourceOptions::shared()); + (step, out.unwrap(), length) + }) + .collect::>(); + let mut read_into = reads.iter(); + let mut keeps = Vec::new(); + let mut kept = device.work_counts().shadow_texels_kept; + let command_buffer = queue.command_buffer().unwrap(); + for (at, step) in steps.iter().enumerate() { + if apart && at > 0 { + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + (encoder.copy_from_buffer_to_buffer(&from, 0, &into, 0, 4)).unwrap(); + encoder.end_encoding().unwrap(); + } + match *step { + Draw(i) => { + let drawn = (i, Corners::Drawn); + pass(&command_buffer, over.texture, over.blending, drawn, None); + } + Alias(i) => { + let drawn = (i, Corners::Drawn); + pass(&command_buffer, over.alias, over.blending, drawn, None); + } + Lone => { + let mut lone = RenderPassDescriptor::new(); + lone.render_target_width = 1; + lone.render_target_height = 1; + lone.default_raster_sample_count = 1; + let mut encoder = command_buffer.render_command_encoder(&lone).unwrap(); + (encoder.set_render_pipeline_state(over.attachmentless)).unwrap(); + let corners = [-1.0f32, -1.0, 1.0, 1.0]; + (encoder.set_vertex_bytes(&bytes_of(&corners, f32::to_le_bytes), 0)).unwrap(); + (encoder.set_fragment_bytes(&bytes_of(&[0.0f32; 4], f32::to_le_bytes), 0)).unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); + encoder.end_encoding().unwrap(); + } + Other(names) => { + let named = match (names, over.buffer) { + (true, Some(buffer)) => buffer, + _ => &unread, + }; + let drawn = (at, Corners::Drawn); + pass( + &command_buffer, + over.other, + over.blending, + drawn, + Some(named), + ); + } + Read => read_texels(&command_buffer, over.texture, &read_into.next().unwrap().1), + Bytes => { + let (_, out, length) = read_into.next().unwrap(); + match over.buffer { + Some(buffer) => { + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + (encoder.copy_from_buffer_to_buffer(buffer, 0, out, 0, *length)).unwrap(); + encoder.end_encoding().unwrap(); + } + None => read_texels(&command_buffer, over.texture, out), + } + } + Signal => { + (command_buffer.encode_signal_event(EventRef::from(&event), at as u64)).unwrap() + } + } + // A pass's keep is planned as its encoder ends, which a reading of the counts lowers. + let now = device.work_counts().shadow_texels_kept; + if now > kept { + keeps.push(*step); + } + kept = now; + } + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + let reads = (reads.iter()) + .map(|(step, out, length)| { + let got = read(out, *length); + match (step, over.buffer) { + (Bytes, Some(_)) => (texels(&got), between_changed(&got)), + _ => (got, 0), + } + }) + .collect(); + (reads, keeps) +} + +/// The texels of the private texture, packed. +fn texels_of(queue: &CommandQueue, texture: &Texture) -> Vec { + let out = (queue.device()) + .new_buffer(W * TEXEL * H, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + read_texels(&command_buffer, texture, &out); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + read(&out, W * TEXEL * H) +} + +/// The bytes of `host`, which no command uses now. +fn host_bytes(host: &Host, length: u64) -> Vec { + // SAFETY: inside the allocation, which no command writes now (its command buffers completed). + unsafe { std::slice::from_raw_parts(host.0.as_ptr(), length as usize) }.to_vec() +} + +/// Write [`first_bytes`] into `host`, which no command uses now. +fn fill(host: &Host) { + let first = first_bytes(ROW); + // SAFETY: inside the allocation, which no command uses now. + unsafe { std::ptr::copy_nonoverlapping(first.as_ptr(), host.0.as_ptr(), first.len()) }; +} + +/// The counts the runs are told by, between two readings. +struct Counted { + copies: u64, + kept: u64, + planned: u64, + copied_in: u64, +} + +impl Counted { + fn between(before: &WorkCounts, after: &WorkCounts) -> Counted { + Counted { + copies: after.shadow_copies - before.shadow_copies, + kept: after.shadow_texels_kept - before.shadow_texels_kept, + planned: after.shadow_merge_dispatches_planned - before.shadow_merge_dispatches_planned, + copied_in: after.shadow_texels_copied_in - before.shadow_texels_copied_in, + } + } +} + +/// Assert that `got` reads `expected`'s texels, and its bytes between the rows kept theirs. +fn same(what: &str, got: &Got, expected: &[u8]) { + let differ = (0..got.0.len()) + .filter(|&i| got.0[i] != expected[i]) + .count(); + assert_eq!( + differ, 0, + "{what}: the texels differ from the private texture's" + ); + assert_eq!(got.1, 0, "{what}: bytes between the rows changed"); +} + +/// [`steps`] over the texture as runs and with every pass apart, against the private texture's: +/// the same texels read mid-sequence and left at its end, the bytes between the rows kept, and +/// one keep and one merge a run (every pass's where apart), each run's first pass the one that +/// keeps ([`FIRSTS`]). +#[test] +fn runs_over_host_pages_keep_and_merge_once() { + let host = Host::new(ROW * H); + let cache = Scratch::new("shadow-runs"); + let device = device(&cache.0); + let queue = device.new_command_queue().unwrap(); + let blending = blending(&device); + let attachmentless = attachmentless(&device); + let other = private_texture(&queue); + let reference = private_texture(&queue); + let on_reference = Scene { + texture: &reference, + buffer: None, + alias: &reference, + other: &other, + blending: &blending, + attachmentless: &attachmentless, + }; + let (expected, _) = sequence(&queue, &on_reference, false); + let left = texels_of(&queue, &reference); + let Some(buffer) = over_pages(&device, &host) else { + return; + }; + let mut counted = Vec::new(); + for apart in [false, true] { + fill(&host); + let texture = texture_over(&buffer); + let alias = texture_over(&buffer); + let on_texture = Scene { + texture: &texture, + buffer: Some(&buffer), + alias: &alias, + other: &other, + blending: &blending, + attachmentless: &attachmentless, + }; + let before = device.work_counts(); + let (got, keeps) = sequence(&queue, &on_texture, apart); + let after = device.work_counts(); + let count = Counted::between(&before, &after); + println!( + "SHADOW-RUNS {W}x{H}, rows of {ROW}, apart {apart}: shadow copies {}, texels kept {}, \ + merge dispatches planned {}, texels copied in {}; merges reused {}; kept at \ + {keeps:?}", + count.copies, + count.kept, + count.planned, + count.copied_in, + after.shadow_merge_scratches_reused - before.shadow_merge_scratches_reused, + ); + let passes = (steps().into_iter()).filter(|step| matches!(step, Draw(_) | Alias(_))); + let firsts: Vec = match apart { + true => passes.collect(), + false => FIRSTS.to_vec(), + }; + assert_eq!(keeps, firsts, "apart {apart}: the passes that keep"); + for (at, (got, expected)) in got.iter().zip(&expected).enumerate() { + same(&format!("apart {apart}, read {at}"), got, &expected.0); + } + drop((texture, alias)); + let bytes = host_bytes(&host, ROW * H); + same( + &format!("apart {apart}, the bytes left"), + &(texels(&bytes), between_changed(&bytes)), + &left, + ); + counted.push(count); + } + let (runs, apart) = (&counted[0], &counted[1]); + // Each keep and merge is over every texel, alike for every pass apart. + assert_eq!(apart.kept % PASSES, 0, "every pass apart keeps alike"); + assert_eq!(apart.planned % PASSES, 0, "every pass apart merges alike"); + let (kept, planned) = (apart.kept / PASSES, apart.planned / PASSES); + assert_eq!(kept, W * H, "a pass apart keeps every texel"); + assert_eq!(runs.kept, RUNS * kept, "one keep a run"); + assert_eq!(runs.planned, RUNS * planned, "one merge a run"); + assert_eq!( + runs.copied_in, apart.copied_in, + "the runs copy in what the passes apart do" + ); + assert_eq!( + apart.copies - runs.copies, + 2 * (PASSES - RUNS), + "each later pass of a run neither keeps nor merges" + ); +} + +/// The passes of [`rebound_passes_leave_their_runs`], and those of them whose rectangle is read +/// from the buffer the rebind moves. +const REBOUND_PASSES: usize = 12; +const NAMING: [usize; 3] = [3, 4, 8]; + +/// The rectangle the moved buffer's pages hold before the rebind, and the one its new pages hold. +const BEFORE: [f32; 4] = [-1.0, -1.0, 1.0, 1.0]; +const MOVED: [f32; 4] = [-0.5, -0.625, 0.25, 0.75]; + +/// Write `corners` at the start of `host`, which no command uses now. +fn write_corners(host: &Host, corners: [f32; 4]) { + let bytes = bytes_of(&corners, f32::to_le_bytes); + // SAFETY: inside the allocation, which no command uses now. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), host.0.as_ptr(), bytes.len()) }; +} + +/// Pass `i`'s rectangle in [`rebound_passes_leave_their_runs`]: read from `from` for those of +/// [`NAMING`], [`drawn`]'s for the others. +fn corners(i: usize, from: &Buffer) -> (usize, Corners<'_>) { + match NAMING.contains(&i) { + true => (i, Corners::From(from)), + false => (i, Corners::Drawn), + } +} + +/// Passes over the texture behind a wait for a shared event only the host signals, three of them +/// drawing the rectangle a second no-copy buffer holds, which is rebound over pages holding +/// another before the signal: the rebind encodes those three again before the first submission +/// (`command_buffer/reencode.rs`), so they draw the new pages' rectangle, each leaving its run as +/// it copies in, keeps and merges for itself; the passes before and after them form runs of +/// their own. The texels left are those of a private texture whose three passes drew the new +/// rectangle, and the bytes between the rows keep theirs. +#[test] +fn rebound_passes_leave_their_runs() { + let (host, moved, moved_to) = (Host::new(ROW * H), Host::new(1 << 16), Host::new(1 << 16)); + write_corners(&moved, BEFORE); + write_corners(&moved_to, MOVED); + let cache = Scratch::new("shadow-runs-rebound"); + let device = device(&cache.0); + let queue = device.new_command_queue().unwrap(); + let blending = blending(&device); + let reference = private_texture(&queue); + let moved_rect = staged(&device, &bytes_of(&MOVED, f32::to_le_bytes)); + + let command_buffer = queue.command_buffer().unwrap(); + for i in 0..REBOUND_PASSES { + pass( + &command_buffer, + &reference, + &blending, + corners(i, &moved_rect), + None, + ); + } + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let left = texels_of(&queue, &reference); + let (Some(buffer), Some(named)) = (over_pages(&device, &host), over_pages(&device, &moved)) + else { + return; + }; + fill(&host); + let texture = texture_over(&buffer); + let gate = device.new_shared_event().unwrap(); + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + (command_buffer.encode_wait_for_event(EventRef::Shared(&gate), 1)).unwrap(); + for i in 0..REBOUND_PASSES { + pass( + &command_buffer, + &texture, + &blending, + corners(i, &named), + None, + ); + } + command_buffer.commit().unwrap(); + assert_eq!(named.detach_backing(), Ok(true), "the detach"); + // SAFETY: the pages outlive every buffer over them, which alone uses them while it lives. + unsafe { named.rebind_bytes_no_copy(moved_to.memory(), None, None) }.unwrap(); + let encoded = device.work_counts(); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let after = device.work_counts(); + let count = Counted::between(&before, &after); + println!( + "SHADOW-RUNS rebound: {:?} {:?}; encoders encoded again {}, refused {}; shadow copies {}, \ + texels kept {}, merge dispatches planned {}", + command_buffer.status(), + command_buffer.error(), + encoded.encoders_reencoded - before.encoders_reencoded, + encoded.reencodes_refused - before.reencodes_refused, + count.copies, + count.kept, + count.planned, + ); + assert_eq!(command_buffer.error(), None); + assert_eq!( + encoded.encoders_reencoded - before.encoders_reencoded, + NAMING.len() as u64, + "the rebind encodes the passes that bound the buffer again" + ); + drop(texture); + let bytes = host_bytes(&host, ROW * H); + same( + "the bytes left", + &(texels(&bytes), between_changed(&bytes)), + &left, + ); +} + +/// The scissors of [`scissored_runs_keep_again_once_and_merge_in_blocks`]'s passes: the first +/// pass's, then one outside it, then others anywhere. +const SCISSORS: [[u64; 4]; 10] = [ + [64, 64, 256, 256], + [512, 512, 256, 256], + [0, 0, 1024, 128], + [700, 100, 300, 600], + [96, 600, 128, 400], + [400, 400, 64, 64], + [0, 960, 1024, 64], + [256, 0, 512, 1024], + [900, 900, 124, 124], + [128, 300, 640, 200], +]; + +/// The counts the scissored passes are told by, between two readings. +struct Scissored { + kept: u64, + planned: u64, + in_blocks: u64, +} + +/// [`SCISSORS`]'s passes over `texture`, each blending its index's color over the whole texture +/// under its scissor, in one command buffer, committed and completed; a blit between every two +/// where `apart`. The passes that kept, and the counts. +fn scissored( + queue: &CommandQueue, + texture: &Texture, + state: &RenderPipelineState, + apart: bool, +) -> (Vec, Scissored) { + let device = queue.device(); + let (from, into) = (staged(device, &[1; 4]), staged(device, &[0; 4])); + let before = device.work_counts(); + let mut keeps = Vec::new(); + let mut kept = before.shadow_texels_kept; + let command_buffer = queue.command_buffer().unwrap(); + for (i, [x, y, width, height]) in SCISSORS.into_iter().enumerate() { + if apart && i > 0 { + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + (encoder.copy_from_buffer_to_buffer(&from, 0, &into, 0, 4)).unwrap(); + encoder.end_encoding().unwrap(); + } + let mut descriptor = RenderPassDescriptor::new(); + let color = &mut descriptor.color_attachments[0]; + color.texture = Some(texture.clone()); + color.load_action = LoadAction::Load; + color.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap(); + encoder.set_render_pipeline_state(state).unwrap(); + (encoder.set_scissor_rect(ScissorRect { + x, + y, + width, + height, + })) + .unwrap(); + let whole = [-1.0f32, -1.0, 1.0, 1.0]; + (encoder.set_vertex_bytes(&bytes_of(&whole, f32::to_le_bytes), 0)).unwrap(); + let rgba = drawn(i).1; + (encoder.set_fragment_bytes(&bytes_of(&rgba, f32::to_le_bytes), 0)).unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); + encoder.end_encoding().unwrap(); + let now = device.work_counts().shadow_texels_kept; + if now > kept { + keeps.push(i); + } + kept = now; + } + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + let after = device.work_counts(); + let counts = Scissored { + kept: after.shadow_texels_kept - before.shadow_texels_kept, + planned: after.shadow_merge_dispatches_planned - before.shadow_merge_dispatches_planned, + in_blocks: after.shadow_merge_dispatches_in_blocks + - before.shadow_merge_dispatches_in_blocks, + }; + (keeps, counts) +} + +/// [`SCISSORS`]'s passes over the texture, as a run and with every pass apart, against a private +/// texture's: the same texels left and the bytes between the rows kept. As a run the first pass +/// keeps its scissor's texels and the second, which writes outside them, every texel, and no +/// later pass keeps; where the passes apart merge in whole blocks, so do the run's merges. +#[test] +fn scissored_runs_keep_again_once_and_merge_in_blocks() { + let host = Host::new(ROW * H); + let cache = Scratch::new("shadow-runs-scissored"); + let device = device(&cache.0); + let queue = device.new_command_queue().unwrap(); + let blending = blending(&device); + let reference = private_texture(&queue); + scissored(&queue, &reference, &blending, false); + let left = texels_of(&queue, &reference); + let Some(buffer) = over_pages(&device, &host) else { + return; + }; + let mut counted = Vec::new(); + for apart in [false, true] { + fill(&host); + let texture = texture_over(&buffer); + let (keeps, count) = scissored(&queue, &texture, &blending, apart); + println!( + "SHADOW-RUNS scissored, apart {apart}: kept at {keeps:?}, texels kept {}, merge \ + dispatches planned {}, in blocks {}", + count.kept, count.planned, count.in_blocks + ); + drop(texture); + let bytes = host_bytes(&host, ROW * H); + same( + &format!("scissored, apart {apart}, the bytes left"), + &(texels(&bytes), between_changed(&bytes)), + &left, + ); + let firsts: Vec = match apart { + true => (0..SCISSORS.len()).collect(), + false => vec![0, 1], + }; + assert_eq!( + keeps, firsts, + "scissored, apart {apart}: the passes that keep" + ); + counted.push(count); + } + let (run, apart) = (&counted[0], &counted[1]); + let [_, _, width, height] = SCISSORS[0]; + assert_eq!( + run.kept, + width * height + W * H, + "the first scissor's texels, then every texel" + ); + if apart.in_blocks == apart.planned { + assert_eq!( + run.in_blocks, run.planned, + "the run's merges store whole blocks too" + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/texture/kept_image.rs b/crates/metal2vulkan-runtime/src/texture/kept_image.rs index 41511e883..a3d01b43f 100644 --- a/crates/metal2vulkan-runtime/src/texture/kept_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/kept_image.rs @@ -12,8 +12,8 @@ //! //! Each command queue keeps the kept images its keeps made ([`KeptImages`]), for any merge of its //! of the same view and extent, whatever its shadow (a texture made each frame over the same -//! bytes takes the last frame's): the encoder that took one holds it to its end -//! ([`KeptLease`]), and the command buffers that used it hold it (`Arc`) until they complete. +//! bytes takes the last frame's): the encoder that took one holds it to its end, or the run of +//! passes it begins to the run's end (`pass_runs.rs`; [`KeptLease`]), and the command buffers that used it hold it (`Arc`) until they complete. //! `WorkCounts::shadow_merge_kept_images_made`, `shadow_merge_kept_images_followed` and //! `shadow_merge_kept_images_live` count them. @@ -105,11 +105,14 @@ impl KeptImage { /// its uses is the queue's: /// 1. A keep and its merge lie in one encoder: a merged-back shadow is merged before the /// encoder's next command that touches its bytes another way or at the encoder's end, and a -/// command writing two ways is merged before the next command (`shadow.rs`). -/// 2. So the spans from a keep to its merge of two encoders that took the image never interleave -/// in submission order: one encoder of a command buffer is open at a time, and they go in -/// order; each span lies in one batch, and a logical queue's batches go to its one `VkQueue` -/// in its order, a command buffer's whole. +/// command writing two ways is merged before the next command (`shadow.rs`); or in one run of +/// render passes, in one batch, which holds the image from its first pass's keep until it ends +/// or its command buffer commits, after its last merge in submission order (`pass_runs.rs`). +/// An encoder a rebind encodes again takes no image of the pool (`ShadowMerge::new`). +/// 2. So the spans from a keep to its merge of two encoders (or runs) that took the image never +/// interleave in submission order: one encoder of a command buffer is open at a time, and they +/// go in order; each span lies in one batch, and a logical queue's batches go to its one +/// `VkQueue` in its order, a command buffer's whole. /// 3. The span submitted second keeps after the first's merge, which ends with a barrier from /// every command to every command (`Barrier::everything`, `shadow_merge.rs`): outside a render /// pass, a pipeline barrier's first synchronization scope is every command before it in @@ -149,7 +152,8 @@ impl Pooled { } /// An open encoder's hold on a kept image it took from its queue's pool ([`KeptImages`]): no -/// other keep takes the image while it lives. The encoder holds it to its end, or its drop. +/// other keep takes the image while it lives. The encoder holds it to its end, or its drop; a run +/// of passes over the shadowed texture, past the encoder's end to the run's (`pass_runs.rs`). pub(crate) struct KeptLease { held: Arc, take: u64, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/linear_attachments.rs b/crates/metal2vulkan-validation/src/runtime_lane/linear_attachments.rs index 97ee9c340..42c3f9eb8 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/linear_attachments.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/linear_attachments.rs @@ -1873,9 +1873,10 @@ fn many_reference(queue: &CommandQueue, pipeline: &RenderPipelineState, width: u /// (`merge_scratch.rs`): its texels equal those the same passes leave in a private texture, and /// the bytes between its rows keep theirs. Where the device renders it apart by the rule /// (`linear_merge.rs`), the passes form a run or two merged once each (`pass_runs.rs`), each -/// merge taking one scratch; where it is a shadow merged back (`shadow_merge.rs`), every -/// merge after the first takes a scratch an earlier encoder was done with. Either way the device's -/// memory grows by less than an eighth of a scratch a pass while they are encoded. +/// merge taking one scratch; where it is a shadow merged back (`shadow_merge.rs`), the passes +/// form one run, kept once before the first and merged once after the last (`pass_runs.rs`). +/// Either way the device's memory grows by less than an eighth of a scratch a pass while they are +/// encoded. fn many_passes_over(over: ManyOver, (width, row): (u64, u64)) { on_device(|device, _| { let queue = device.new_command_queue().unwrap(); @@ -1890,8 +1891,8 @@ fn many_passes_over(over: ManyOver, (width, row): (u64, u64)) { return; }; let apart = by_the_rule(device) && aliased(&texture); - // A shadow merged back at each encoder's end: one over bytes another writer may write, - // all but a tracked `Private` buffer's, whose shadow is copied back. + // A shadow merged back: one over bytes another writer may write, all but a tracked + // `Private` buffer's, whose shadow is copied back. let shadow = !aliased(&texture) && over != ManyOver::Private; let before = device.work_counts(); let encoded = many_passes(&queue, &pipeline, &texture); @@ -1903,6 +1904,7 @@ fn many_passes_over(over: ManyOver, (width, row): (u64, u64)) { let recorded = delta(|c| c.linear_merges_recorded); let taken_over = delta(|c| c.linear_merges_taken_over); let shadow_reused = delta(|c| c.shadow_merge_scratches_reused); + let kept = delta(|c| c.shadow_texels_kept); let grown = encoded.device_memory_allocated - before.device_memory_allocated; // A merge of every texel's rows: its kept and changed parts. let scratch = 2 * width * TEXEL * MANY_H; @@ -1910,8 +1912,8 @@ fn many_passes_over(over: ManyOver, (width, row): (u64, u64)) { "LINEAR-ATTACHMENT many passes over {over:?} {width}x{MANY_H}, rows of {row}, on {}: \ apart by the rule {apart}, shadow {shadow}; {through} passes through copies, linear \ merges {recorded} recorded and {taken_over} taken over, linear scratches {made} made \ - and {reused} reused, shadow scratches {shadow_reused} reused; device memory grew \ - {grown} bytes while encoding", + and {reused} reused, shadow scratches {shadow_reused} reused, shadow texels kept \ + {kept}; device memory grew {grown} bytes while encoding", device.name() ); // One run (`pass_runs.rs`), or two where the second pass's box reaches past the @@ -1933,11 +1935,9 @@ fn many_passes_over(over: ManyOver, (width, row): (u64, u64)) { "each run's merge takes one scratch" ); } + // One run of passes (`pass_runs.rs`): kept once, every texel, before the first. if shadow { - assert!( - shadow_reused >= MANY as u64 - 1, - "every merge after the first takes a scratch: {shadow_reused}" - ); + assert_eq!(kept, width * MANY_H, "the passes keep once, as one run"); } assert!( grown < scratch * MANY as u64 / 8, diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 7f8d028a9..006227bb8 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -296,13 +296,23 @@ recorded here. twelve in one 10.4-12.9 against 14.5-16.2 ms, and one 0.76-0.83 against 0.92-1.42 ms. That image takes the scratch buffer's place, 8.3 MB at 1920x1080, and is its queue's: a later keep of the queue of the same view and extent, whatever its texture, takes it once the encoder that - took it ended, without waiting for the command buffers that used it, which the merge's closing - barrier and the image's tracked uses order (`texture/kept_image.rs`); at most two that no open - encoder holds stay for each view and extent, and none untaken over 256 takes. On the Iris Xe + took it ended (or the run of passes it began, below), without waiting for the command buffers + that used it, which the merge's closing barrier and the image's tracked uses order + (`texture/kept_image.rs`); at most two that no open encoder holds stay for each view and + extent, and none untaken over 256 takes. On the Iris Xe (`surface_texture_costs::surface_texture_cost_parts`, four shadowed textures a frame, 1,582,016 texels), over anonymous pages, merged back, passes that draw took 5.0-5.4 ms a frame from commit to completion, and under scissors (790,448 texels) 3.6-3.9 ms; over tracked `Private` buffers, - copied back, 3.1 ms and 2.2-2.4 ms. + copied back, 3.1 ms and 2.2-2.4 ms. Render passes one after another in one batch over one + such texture, each loading and storing it as a color, with nothing between them that may touch + its bytes, are one run (`pass_runs.rs`): kept before the first pass and merged after the last. + 700 such passes in one command buffer, each blending one rectangle over a 1024x1024 + `BGRA8Unorm` texture over host pages with rows of 15360 bytes, took 3 shadow copies against + 1,401 and kept 1,048,576 texels against 734,003,200; from commit to completion, 31.6-35.3 ms + against 69.3-99.9 ms on the M3 Max (MoltenVK 1.4.2) and 6.6-10.0 ms against 40.6-43.0 ms on + the RTX 5080 Laptop GPU (NVIDIA 615.71.09); with a 1x1 render encoder of no attachment between + every two, 61.6-65.0 ms against 107.4-118.6 ms and 9.7-12.3 ms against 44.5-47.1 ms (the + second to fourth of four such command buffers in a process). - **A no-copy buffer's deallocator runs in its release.** On an M3 Max under macOS 27.0.1 an unused no-copy buffer's deallocator ran inside its final release, on the releasing thread, every time. So a release that frees the buffer's import while a deallocator waits for the free frees it