diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index deb2aedfc..1d2cf91ff 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -109,7 +109,7 @@ use super::sparse::indirect; use super::texture::faces::TurnPoint; use super::texture::storage_form::Riding; use super::texture::Texture; -use super::tracker::{Footprint, Use}; +use super::tracker::{Footprint, Summary, Use}; use super::unique_identifier::ScheduledWork; use super::upload::{Upload, Uploads}; use super::used_resources::{names_any, EncoderKind, EncoderRecord, Reached, ReadRecord}; @@ -942,6 +942,16 @@ pub(super) struct State { residency: Option, /// The ended encoders whose resources `residency` holds joined: those before this place. joined: usize, + /// What its work may write through its residency (`Residency::written_uses`), set at its + /// commit: every resource made resident for writing, by any of its encoders. A function of + /// any of its encoders may write such a resource unnamed (residency is the command + /// buffer's), so the device's tracker takes each of its batches as writing them all: joined + /// to the summary of the batch's first part, in the plan its submission makes (`submit.rs`) + /// and in its footprint ([`CommandBufferShared::footprint`]). A host step's gate then + /// covers such a writer of what it reads (`scheduler/mod.rs`'s `gate_heads`): an earlier + /// batch of its own command buffer, or one of an earlier command buffer of any queue. `None` + /// where no encoder made a resource resident for writing. + resident_writes: Option>, /// Its ended encoders, in the order they ended, each with what its commands use /// (`used_resources.rs`): the keys its commands' uses and bindings named, its placed /// segments' among them, and what it made resident. Their uses are let go as it completes. @@ -1339,6 +1349,25 @@ impl State { shadows } + /// Set [`resident_writes`](Self::resident_writes) from what each ended encoder made resident + /// for writing, read from the encoders' own residencies (joining them into its residency + /// would cost a command buffer whose work never reads that residency the join), with the + /// uses of their host memory `aliases` adds, as an encoder's tracked uses take them: at its + /// commit. + fn note_resident_writes(&mut self, aliases: &super::host_aliases::HostAliases) { + let uses: Vec> = (self.ended.iter()) + .filter_map(|record| record.residency.as_ref()) + .flat_map(Residency::written_uses) + .collect(); + self.resident_writes = match uses.is_empty() { + true => None, + false => { + let uses = aliases.augment(&uses).unwrap_or(uses); + Some(Summary::of_no_stage(uses)).filter(|summary| !summary.is_empty()) + } + }; + } + /// Let go of what its ended encoders' commands use, as it completes: their keys, and what /// they made resident, for the caller to release without this lock. fn let_go_of_uses(&mut self) -> Vec { @@ -2348,6 +2377,7 @@ impl CommandBuffer { holds: Vec::new(), residency: None, joined: 0, + resident_writes: None, ended: Vec::new(), root_tables: Vec::new(), root_ranges: HashSet::new(), @@ -3569,6 +3599,9 @@ impl CommandBuffer { // Its heaps reach every texture they hold now, for the work recorded below and by its // host steps. state.sync_heaps(&self.0.device.shared().counts); + // Each of its batches writes what any of its encoders made resident for writing, for + // the device's tracker (`State::resident_writes`). + state.note_resident_writes(&device.shared().aliases); let (segments, places): (Vec<(Deferred, bool)>, Vec) = state .recorded .iter() @@ -4640,7 +4673,9 @@ impl CommandBufferShared { } /// What batch `index` uses, for the scheduler's order across queues (`scheduler/order.rs`): - /// its encoders' summaries and its segments' recordings, and for a segment its host step + /// its encoders' summaries and its segments' recordings, with what the command buffer's work + /// may write through its residency where the batch has a part (`State::resident_writes`), + /// and for a segment its host step /// records for the pipelines it waits for alone, what its work uses, known at encode time /// (`Segment::known_summary`): Metal makes the pipeline at `newRenderPipelineState`, so only a /// batch that shares a resource with it waits for it; and for a segment its host step records @@ -4682,6 +4717,11 @@ impl CommandBufferShared { let mut summaries = Vec::new(); let mut known = Vec::new(); let mut probes = Vec::new(); + // What its work may write through its residency, as its submission's plan takes it + // (`State::resident_writes`). + if !recorded.is_empty() { + summaries.extend(&state.resident_writes); + } for (at, encoder) in recorded.iter().enumerate() { if !encoder.sparse.is_empty() { return None; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 109fe8b69..af2cd84ee 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -120,6 +120,15 @@ //! image outside the encoder joined to its summary, and recorded the same way, after the barrier //! the tracker planned for the encoder. The layouts the batch leaves count from its submission on. //! +//! **Writes through the residency** (`State::resident_writes`). Residency is the command +//! buffer's (`residency.rs`), so a function of any of its encoders may write a resource any of +//! them made resident for writing, in an encoder whose commands name it nowhere. Each batch with a +//! part plans those writes with its first part, as writes of each whole resource in every stage +//! that widen none of the stages the part's fences cover: the tracker then holds the batch as their +//! last writer, so what reads them later on any queue, and a later host step's gate +//! (`scheduler/mod.rs`'s `gate_heads`), orders after it. A resource made resident for reading +//! alone is planned as the commands that name it use it. +//! //! **New resources' first work** (`texture/first_move.rs`). Every batch first does the first GPU //! work of the resources made since the device's last submission: each new image's move to //! `GENERAL`, and the zeros a new texture, stand-in or buffer reads. It runs before every command @@ -716,20 +725,30 @@ impl CommandBufferShared { None => (&unnamed, &[][..]), } })); - // Each encoder's summary with its moves' uses joined, where it has moves. - let moved: Vec>> = match held_moves.is_empty() { - true => Vec::new(), - false => (encoders.iter().enumerate()) - .map(|(at, recorded)| { - let uses = held_moves.uses(at); - (!uses.is_empty()).then(|| { - let mut summary = recorded.summary.clone(); - summary.join(Summary::outside_encoders(uses.to_vec())); - summary + // Each encoder's summary with its moves' uses joined, where it has moves; the first's + // with what the command buffer's work may write through its residency, which any of its + // encoders may write (`State::resident_writes`). + let resident_writes = state.resident_writes.as_ref(); + let moved: Vec>> = + match held_moves.is_empty() && resident_writes.is_none() { + true => Vec::new(), + false => (encoders.iter().enumerate()) + .map(|(at, recorded)| { + let uses = held_moves.uses(at); + let writes = resident_writes.filter(|_| at == 0); + (!uses.is_empty() || writes.is_some()).then(|| { + let mut summary = recorded.summary.clone(); + if !uses.is_empty() { + summary.join(Summary::outside_encoders(uses.to_vec())); + } + if let Some(writes) = writes { + summary.join(writes.clone()); + } + summary + }) }) - }) - .collect(), - }; + .collect(), + }; let summaries = (encoders.iter().enumerate()).map(|(at, recorded)| { let moved = moved.get(at).and_then(Option::as_ref); moved.unwrap_or(&recorded.summary) diff --git a/crates/metal2vulkan-runtime/src/residency.rs b/crates/metal2vulkan-runtime/src/residency.rs index 650139a76..b7f03abf6 100644 --- a/crates/metal2vulkan-runtime/src/residency.rs +++ b/crates/metal2vulkan-runtime/src/residency.rs @@ -356,6 +356,18 @@ impl Used { Used::Texture(_) | Used::IndirectCommandBuffer(_) => None, } } + + /// A use of all of it, reading by `read` and writing by `write` (either may be + /// `Access::NONE`): a buffer's, a heap's own buffer's and an indirect command buffer's records' + /// bytes, a texture's whole image (`Texture::bound_use`). + fn whole_use(&self, read: Access, write: Access) -> Use { + let bytes = match self { + Used::Texture(texture) => return texture.bound_use(read, write), + Used::Buffer(buffer) | Used::Heap { bytes: buffer, .. } => buffer, + Used::IndirectCommandBuffer(icb) => icb.storage(), + }; + whole_use(bytes, read, write) + } } impl Residency { @@ -631,16 +643,27 @@ impl Residency { true => Access::new(stages, vk::AccessFlags2::MEMORY_WRITE), false => Access::NONE, }; - let bytes = match used { - Used::Texture(texture) => return texture.bound_use(read, write), - Used::Buffer(buffer) | Used::Heap { bytes: buffer, .. } => buffer, - Used::IndirectCommandBuffer(icb) => icb.storage(), - }; - whole_use(bytes, read, write) + used.whole_use(read, write) }) .collect() } + /// What any work of a command buffer whose residency this is may write of it, for the + /// device's tracker (`State::resident_writes` in `command_buffer/mod.rs`): each resource made + /// resident for writing, written over all its bytes (a texture over its whole image) in every + /// stage. Residency is the command buffer's (the module docs), so a function of any of its + /// encoders may write such a resource, through an address or an ID held in memory, in an + /// encoder whose commands name it nowhere. A resource made resident for reading alone is not + /// among them. + pub(super) fn written_uses(&self) -> Vec> { + let stages = vk::PipelineStageFlags2::ALL_COMMANDS; + let write = Access::new(stages, vk::AccessFlags2::MEMORY_WRITE); + (self.held().used.iter()) + .filter(|(_, usage, _)| usage.contains(ResourceUsage::WRITE)) + .map(|(used, ..)| used.whole_use(Access::NONE, write)) + .collect() + } + /// The heaps used (`use_heap`), a sparse heap among them. pub(super) fn used_heaps(&self) -> impl Iterator { self.heaps.iter().map(|used| &used.heap) diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index ac7c25940..87e8736ae 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -2527,7 +2527,11 @@ fn gate_heads(state: &mut State, behind: &[u64], left: &mut Left, awaits: /// (`Tracker::last_writes`), so the step waits for those batches alone, and a command buffer's /// executions behind one writer wait for it once; else every queue's last submitted value, /// `values`. A gate that leaves out work submitted before it is counted -/// (`WorkCounts::host_step_gates_narrowed`). +/// (`WorkCounts::host_step_gates_narrowed`). The tracker holds a write through a command buffer's +/// residency as one of each of its batches (`State::resident_writes` in `command_buffer/mod.rs`): +/// so the gate of a step that reads records made resident for writing covers the batch whose +/// function wrote them unnamed, an earlier one of the step's own command buffer or one of an +/// earlier command buffer of any queue. /// /// Every batch that may write what the step reads was submitted by then: an earlier batch of its /// line went before it, a batch of an earlier commit on another line that may write those bytes diff --git a/crates/metal2vulkan-runtime/src/tests/tracker.rs b/crates/metal2vulkan-runtime/src/tests/tracker.rs index acabf7f2b..d302d9ddd 100644 --- a/crates/metal2vulkan-runtime/src/tests/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tests/tracker.rs @@ -2485,3 +2485,56 @@ fn a_host_read_waits_for_the_last_writes_of_its_bytes_alone() { tracker.completed(1, 2); assert_eq!(last(&tracker, &records), Some(vec![0, 0]), "seen complete"); } + +/// A command buffer's writes through its residency (`State::resident_writes` in +/// `command_buffer/mod.rs`), joined to its batch's first encoder, which names none of them: they +/// keep the tracked uses that touch something, leave the stages the encoder's fence update covers +/// as they were (a later wait on the fence orders after the encoder's transfer alone), and make +/// the batch the last writer a later host read of their bytes waits for. +#[test] +fn writes_of_no_stage_widen_no_fence_and_name_their_batch_the_writer() { + let fence: Key = 100; + let every = vk::PipelineStageFlags2::ALL_COMMANDS; + let written = Access::new(every, vk::AccessFlags2::MEMORY_WRITE); + let resident = Summary::of_no_stage(vec![ + writes(9, bytes(0..64), written), + Use::writes(8, false, bytes(0..64), written), + writes(7, bytes(0..0), written), + writes(9, bytes(0..64), written), + ]); + assert_eq!( + resident.keys().collect::>(), + [9], + "tracked, touching something, once" + ); + let mut first = EncoderUses::new(true); + first.record(TRANSFER, &[writes(5, bytes(0..64), copy_write())], None); + first.update_fence(fence, None); + let mut joined = first.finish(); + joined.join(resident); + let mut tracker = Tracker::default(); + submit(&mut tracker, &[joined], on(0, 1)); + let mut second = EncoderUses::new(false); + second.wait_for_fence(fence, None); + second.record(COMPUTE, &[reads(6, bytes(0..64), shader_read())], None); + let (barriers, _) = submit(&mut tracker, &[second.finish()], on(0, 2)); + let after = Access::new( + COMPUTE, + vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE, + ); + assert_eq!( + barriers, + [barrier( + Access::new(TRANSFER, vk::AccessFlags2::MEMORY_WRITE), + after + )], + "the fence's stages" + ); + let read = Access::new(every, vk::AccessFlags2::MEMORY_READ); + let records = reads(9, bytes(0..8), read); + assert_eq!( + tracker.last_writes(std::slice::from_ref(&records), 2), + Some(vec![1, 0]), + "the batch writes them" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs index bf6a9aa02..19cbdf80f 100644 --- a/crates/metal2vulkan-runtime/src/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tracker.rs @@ -2111,6 +2111,27 @@ impl Summary { } } + /// The summary of what work of no stage of its own may make: `uses` of the resources Metal + /// tracks, one per resource and range. Joined to an encoder's summary + /// ([`join`](Self::join)), it widens none of the stages the encoder's fences cover: a + /// command buffer's writes through its residency, which may lie in any of its encoders + /// (`State::resident_writes` in `command_buffer/mod.rs`). + pub(super) fn of_no_stage(mut uses: Vec>) -> Summary { + uses.retain(|used| used.tracked && !used.is_nothing()); + merge(&mut uses); + Summary { + uses, + stages: vk::PipelineStageFlags2::NONE, + waits: Vec::new(), + updates: Vec::new(), + } + } + + /// Whether it holds no use, no wait and no update. + pub(super) fn is_empty(&self) -> bool { + self.uses.is_empty() && self.waits.is_empty() && self.updates.is_empty() + } + /// The summary of a resource state encoder, which records no command: it waits for the fences /// `waits` and updates `updates`, in every stage, so a wait on its queue orders after all of /// its batch's work before it, which its sparse binding precedes.