From 43bb61c60ef3496f0ccca58be435f36ecdbb9df9 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 15 Nov 2026 06:09:09 -0800 Subject: [PATCH] RUNTIME 2344: Runtime: a command queue on the copy engine, and buffer copies merged into runs Device::new_command_queue_for_copies() answers a CommandQueue whose command buffers submit to the device's copy engine (the staging queue's family of transfers alone), or None where the device has none to give (MoltenVK, lavapipe, RADV by default, a copy engine of one queue, an adopted device). Its VkQueue is the copy engine's third queue where it has one, else the fill queue's, whose submissions then take that QueueSlot's lock: NVIDIA's copy engine has two queues, staging's and fill's, and staging must wait for no work in flight. The slot is the last of the device's VkQueues, after presenting's; its family stays out of image sharing (buffers already share it as the staging queue's family, so no ownership transfer is recorded). Its command buffers take blit encoders alone, and of their commands buffer copies, fills and fences: other encoders and blit commands are refused (Invalid, Problem::CopyQueue(CopyQueueProblem::Encoder | Command)), as is a caller's VkBuffer not concurrent with the copy family (Buffer). A copy batch takes buffers' fills alone from first work. Barriers on its VkQueue name the copy family's reads (Barrier::record_reading), not the primary family's, which a family of transfers alone may not name beside ALL_COMMANDS (VUID-vkCmdPipelineBarrier-dstAccessMask-02816). A blit encoder's consecutive copy_from_buffer_to_buffer calls between the same two VkBuffers that its order needs no barrier between are recorded as one vkCmdCopyBuffer of many regions (copy_run.rs), on every queue; counted as WorkCounts::buffer_copies_merged. Batches on the copy slot are counted as WorkCounts::copy_queue_batches. Verified: not yet built (first build job follows). Also in this landing: - Copy queue: docs, and the device test's None answer checked against the device - Copy queue: keep the copy queue's place alive while the families are counted Evidence: lavapipe 425/425 (m3-max-32049), clippy m2v_cpu_icd and m2v_gpu -D warnings (32049, 32053); XTX m3-max-32073: default RADV answers None; RADV_PERFTEST=transfer_queue: 1 batch on the copy engine, 63 of 64 row copies merged, sync file signalled, bytes right, refusals typed, validation layer silent. The derived API table and docs/REFUSALS.md were re-derived on the merged tree (winport's #[cfg(unix)] gates landed beside copyq). --- crates/metal2vulkan-runtime/README.md | 26 ++ crates/metal2vulkan-runtime/src/blit.rs | 105 +++++- crates/metal2vulkan-runtime/src/buffer.rs | 30 +- .../src/command_buffer/kept_barriers.rs | 4 +- .../src/command_buffer/mod.rs | 31 +- .../src/command_buffer/submit.rs | 16 +- crates/metal2vulkan-runtime/src/copy_run.rs | 82 +++++ .../metal2vulkan-runtime/src/device/adopt.rs | 1 + .../metal2vulkan-runtime/src/device/create.rs | 45 ++- crates/metal2vulkan-runtime/src/device/mod.rs | 60 +++- .../src/device/staging.rs | 43 ++- crates/metal2vulkan-runtime/src/encoder.rs | 83 ++++- crates/metal2vulkan-runtime/src/error.rs | 24 ++ .../metal2vulkan-runtime/src/image_barrier.rs | 6 + crates/metal2vulkan-runtime/src/lib.rs | 10 +- crates/metal2vulkan-runtime/src/queue.rs | 80 +++++ crates/metal2vulkan-runtime/src/render.rs | 3 + crates/metal2vulkan-runtime/src/replay.rs | 39 +++ .../src/sparse/encoder.rs | 4 + .../src/tests/copy_queue.rs | 328 ++++++++++++++++++ .../metal2vulkan-runtime/src/tests/device.rs | 97 +++++- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/sync_file.rs | 2 +- .../src/texture/first_move.rs | 12 + crates/metal2vulkan-runtime/src/tracker.rs | 21 +- .../metal2vulkan-runtime/src/work_counts.rs | 25 ++ .../src/wrapped_buffer.rs | 7 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 26 +- docs/REFUSALS.md | 16 +- 30 files changed, 1155 insertions(+), 75 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/copy_run.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/copy_queue.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 257041cac..ac5cd5350 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -609,6 +609,32 @@ Calls Metal does not have, for a consumer that emulates a Metal device: (`WorkCounts::unshared_queues_sharing_a_vk_queue`). A count of 0 and a lost device are refused as `new_command_queue_with_max_command_buffer_count` refuses them. +- `Device::new_command_queue_for_copies()` makes a command queue whose command buffers run on the + device's copy engine (a queue family of transfers alone), beside the graphics family's work + rather than behind it: on an RTX 3090 a readback through another graphics-family queue waited + 1.88 s for a 2 s kernel, where the copy engine's took 7.8 to 13.5 ms. Metal has no such queue. + It answers `None` where the device has no copy engine to give (MoltenVK, lavapipe, RADV unless + `RADV_PERFTEST=transfer_queue`, a copy engine of one queue, a device made with + `Device::from_raw`); keep a plain queue's path there. Every copy queue of a device submits to + one `VkQueue`: the copy engine's third queue, or, on NVIDIA's copy engine of two, the queue the + device's own fills from host memory take (`device/staging.rs`). Its command buffers take blit + encoders alone, and of those `copy_from_buffer_to_buffer`, `fill_buffer` and fence updates and + waits; anything else, and a buffer of the consumer's (`new_buffer_with_vk_buffer`) not + concurrent with the copy engine's family, is refused (`Invalid`, `Problem::CopyQueue`). Every + buffer the runtime makes, a no-copy buffer over host pages among them, is shared with that + family (`VK_SHARING_MODE_CONCURRENT`), so no buffer changes owner; hazards are tracked across + queues as for any queue (a copy that reads what another queue's command buffer committed before + it wrote waits for it on the GPU), and the completion sync file + (`CommandBuffer::export_completion_sync_file`) is signalled on the copy engine. Its batches are + counted (`WorkCounts::copy_queue_batches`). + +- A blit encoder's consecutive `copy_from_buffer_to_buffer` calls between the same two buffers + that need no barrier between them (none reads or writes what an earlier one of the run wrote, + nor writes what it read) are one `vkCmdCopyBuffer` of many regions, on every queue + (`WorkCounts::buffer_copies_merged`). The encoder's hazard order keeps eight ranges of a buffer + and then one span over them all, so a copy into that span takes a barrier and starts a new run: + sort row copies by destination offset (rows in order, tile beside tile) to merge them all. + - `CommandBuffer::commit_failed(CommitFailure)` commits a command buffer as failed, running the encoders Metal would still run and keeping its signals, as a consumer measured on an M3 Max. - `CommandBuffer::set_submission_check` runs a check as the command buffer is submitted, and fails diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 79229824c..19059c9ec 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -26,10 +26,11 @@ use super::blit_fill::FillTiles; use super::buffer::Buffer; use super::command_buffer::CommandBuffer; +use super::copy_run::CopyRun; use super::degradation::Degradation; use super::encoder::{EncoderCore, Replayed}; use super::encoder_fold::Joining; -use super::error::{invalid, Error, Problem}; +use super::error::{invalid, CopyQueueProblem, Error, Problem}; use super::fresh_unwritten::FreshRead; use super::managed_copy::{AtCompletion, CopyBack, Staging, SyncTarget}; use super::managed_sync::{SyncCopy, Target}; @@ -177,6 +178,10 @@ pub struct BlitCommandEncoder { /// The tiles its plain color fills cleared, which its later ones copy from again /// (`blit_fill.rs`). An encoding again starts with none, so it clears them again. fill_tiles: FillTiles, + /// Its buffer copies not yet recorded, which later copies between the same two buffers join + /// as one `vkCmdCopyBuffer` (`copy_run.rs`): recorded before its next other command, and at + /// its end. + run: Option, } impl std::fmt::Debug for BlitCommandEncoder { @@ -210,6 +215,7 @@ impl CommandBuffer { log: Some(self.device().shared().scheduler.spare_logs().blit()), aborts, fill_tiles: FillTiles::default(), + run: None, }) } } @@ -225,14 +231,19 @@ impl BlitCommandEncoder { log: None, aborts: None, fill_tiles: FillTiles::default(), + run: None, }) } /// End an encoder made by [`replaying`](Self::replaying): what it recorded. pub(super) fn finish_replay(self) -> Result { let BlitCommandEncoder { - mut core, pattern, .. + mut core, + pattern, + mut run, + .. } = self; + core.flush_copies(&mut run); if let Some(pattern) = pattern { core.retain(pattern); } @@ -248,12 +259,33 @@ impl BlitCommandEncoder { &mut self, call: impl FnOnce(&mut CallLog) -> BlitCall, run: impl FnOnce(&mut Self) -> Result, + ) -> Result { + self.logged_after(true, call, run) + } + + /// [`logged`](Self::logged), the encoder's run of buffer copies recorded first where + /// `flush` (`copy_run.rs`): every command but a buffer copy, which may join it. + fn logged_after( + &mut self, + flush: bool, + call: impl FnOnce(&mut CallLog) -> BlitCall, + run: impl FnOnce(&mut Self) -> Result, ) -> Result { let _for = self.core.notices_for(); self.refuse_aborted()?; + if flush { + self.core.flush_copies(&mut self.run); + } + let copies = self.core.command_buffer().for_copies(); let at = match self.log.as_mut().filter(|log| !log.muted()) { Some(log) => { let call = call(log); + // A queue made for copies takes buffer copies and fills alone, refused before + // they are logged (an encoder made fresh logs every call it takes). + if let (true, Err(name)) = (copies, call.on_copy_engine()) { + let problem = Problem::CopyQueue(CopyQueueProblem::Command); + return Err(invalid(name, problem)); + } let extra = call.extra(); Some(log.push(call, extra)) } @@ -279,6 +311,17 @@ impl BlitCommandEncoder { } } + /// Refuse `call` over `buffers` on a queue made for copies where the copy engine's family + /// does not share one of them: a buffer the caller made not concurrent with that family + /// (`Invalid`, `CopyQueueProblem::Buffer`, `Device::new_command_queue_for_copies`). + fn refuse_unshared(&self, call: &'static str, buffers: &[&Buffer]) -> Result<(), Error> { + let unshared = buffers.iter().any(|buffer| !buffer.copy_engine_shares()); + match unshared && self.core.command_buffer().for_copies() { + true => Err(invalid(call, Problem::CopyQueue(CopyQueueProblem::Buffer))), + false => Ok(()), + } + } + /// Run `call`, a public call one of the encoder's own makes, unlogged: the call that makes /// it is logged, and encoded again makes it again. pub(super) fn unlogged(&mut self, call: impl FnOnce(&mut Self) -> T) -> T { @@ -351,6 +394,8 @@ impl BlitCommandEncoder { (reads, covered): (&[FreshRead], &[Covered]), record: impl FnOnce(&Vk, vk::CommandBuffer), ) -> Result<(), Error> { + // After the copies of the encoder's run, which records first (`copy_run.rs`). + self.core.flush_copies(&mut self.run); let mut shadows = shadow::copies_used(self.shadows.iter(), uses); shadow::overwritten(&mut shadows, uses, covered); let copies = self.core.plan_shadows(&shadows, uses)?; @@ -360,6 +405,27 @@ impl BlitCommandEncoder { Ok(()) } + /// [`command`](Self::command) of a buffer copy, `copy` (its source, its destination and its + /// region) with `uses`, which joins the encoder's run of copies where it may + /// (`EncoderCore::copy_joining`, `copy_run.rs`): the copies into the heap shadows its uses + /// name go first, as for any command, and none joins a run past them. + fn copy_joining( + &mut self, + uses: &[Use], + copy: (vk::Buffer, vk::Buffer, vk::BufferCopy), + ) -> Result<(), Error> { + let mut shadows = shadow::copies_used(self.shadows.iter(), uses); + shadow::overwritten(&mut shadows, uses, &[]); + let copies = self.core.plan_shadows(&shadows, uses)?; + if !copies.is_empty() { + self.core.flush_copies(&mut self.run); + } + self.core.shadow_copies(&copies); + self.core.copy_joining(uses, copy, &mut self.run); + self.core.shadows_used(&shadows, uses, &[]); + Ok(()) + } + /// Note `texture`, which a blit names: where it is a heap shadow or a tiled texture of more /// than one level, whose image the blit uses (a texture over a buffer blits on its bytes, /// `blit_texture.rs`, `Texture::blit_texels`), its commands take its copies. @@ -386,6 +452,14 @@ impl BlitCommandEncoder { /// A size of 0 copies nothing, wherever its offsets lie, and the encoder's other commands /// run, as plain Metal does (Metal's validation stops it). /// + /// Consecutive copies of the encoder between the same two buffers that need no barrier between + /// them (none reads or writes what an earlier one of the run wrote, nor writes what it read) + /// are one `vkCmdCopyBuffer` of a region each (`WorkCounts::buffer_copies_merged`). The + /// encoder's hazard order keeps eight ranges of a buffer and then one span from the lowest + /// byte of any to the highest, so a copy into that span of the earlier copies' destinations + /// takes a barrier and starts a new run: sort copies by destination offset (a picture's rows + /// in order, tile beside tile) to merge them all. + /// /// A no-copy source buffer is read past its length to the end of its host pages, the /// caller's bytes, as plain Metal reads them (its validation stops it). /// @@ -399,7 +473,9 @@ impl BlitCommandEncoder { destination_offset: u64, size: u64, ) -> Result<(), Error> { - self.logged( + // A copy may join the encoder's run of copies (`copy_run.rs`). + self.logged_after( + false, |_| { BlitCall::CopyBufferToBuffer( source_buffer.clone(), @@ -414,6 +490,7 @@ impl BlitCommandEncoder { this.core.check_device(CALL, source_buffer.generation())?; this.core .check_device(CALL, destination_buffer.generation())?; + this.refuse_unshared(CALL, &[source_buffer, destination_buffer])?; if size == 0 { return Ok(()); } @@ -487,20 +564,11 @@ impl BlitCommandEncoder { ) }); } else { - this.command( - &[reads(source_buffer, from), writes(destination_buffer, to)], - |device, raw| { - // SAFETY: as above; the regions do not overlap. - unsafe { - device.cmd_copy_buffer( - raw, - source, - destination, - &[region(source_at, destination_at, size)], - ); - } - }, - )?; + // One region of the run of copies between the two buffers, where it joins + // (`copy_run.rs`); the regions do not overlap. + let uses = [reads(source_buffer, from), writes(destination_buffer, to)]; + let copy = (source, destination, region(source_at, destination_at, size)); + this.copy_joining(&uses, copy)?; } Ok(()) }, @@ -529,6 +597,7 @@ impl BlitCommandEncoder { |this| { const CALL: &str = "fill_buffer"; this.core.check_device(CALL, buffer.generation())?; + this.refuse_unshared(CALL, &[buffer])?; let size = range.end.saturating_sub(range.start); if size == 0 { return Ok(()); @@ -740,7 +809,9 @@ impl BlitCommandEncoder { log, aborts: _, fill_tiles: _, + mut run, } = self; + core.flush_copies(&mut run); if let Some(pattern) = pattern { core.retain(pattern); } diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 39336e8e1..e3add5a6a 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -2468,7 +2468,11 @@ pub(super) enum Owner { Caller, /// The caller: a `VkBuffer` and the memory it is bound to, which the caller made and keeps /// (`wrapped_buffer.rs`). The runtime destroys and frees neither. - Vulkan, + Vulkan { + /// The caller made it concurrent with the copy engine's queue family, the copy queue's + /// (`Device::new_command_queue_for_copies`), whose commands may then use it. + copy_engine: bool, + }, } /// Whose memory a buffer's bytes are, where they are the caller's. @@ -2540,7 +2544,7 @@ impl Buffer { Lie::Fixed(fixed) => { facts.push_str(", "); facts.push_str(&fixed.pages.memory.placement.failure_facts(types)); - if matches!(own.owner, Owner::Vulkan) { + if matches!(own.owner, Owner::Vulkan { .. }) { facts.push_str(", the caller's VkBuffer"); } match fixed.released.load(Ordering::Acquire) { @@ -3727,7 +3731,7 @@ impl Device { drops_writes, ) } - Owner::Runtime | Owner::Vulkan => Lie::Fixed(Arc::new(FixedPages { + Owner::Runtime | Owner::Vulkan { .. } => Lie::Fixed(Arc::new(FixedPages { device: MadeOn::new(self.clone()), pages, owned: matches!(owner, Owner::Runtime), @@ -5019,7 +5023,7 @@ impl Buffer { .. }) => Some(CallerMemory::HostPages), Bytes::Own(OwnBytes { - owner: Owner::Vulkan, + owner: Owner::Vulkan { .. }, .. }) => Some(CallerMemory::VkBuffer), Bytes::Own(_) => None, @@ -5028,6 +5032,22 @@ impl Buffer { } } + /// Whether the copy engine's queue family, the copy queue's + /// (`Device::new_command_queue_for_copies`), shares the buffer's `VkBuffer`: every one the + /// runtime made, which is concurrent among the device's families and the staging queue's + /// (`sharing.rs`); a caller's where the caller made it concurrent with that family + /// (`wrapped_buffer.rs`); a heap buffer's, its heap's. + pub(super) fn copy_engine_shares(&self) -> bool { + match &self.s().bytes { + Bytes::Own(OwnBytes { + owner: Owner::Vulkan { copy_engine }, + .. + }) => *copy_engine, + Bytes::Own(_) => true, + Bytes::Heap(bytes) => bytes.bytes.copy_engine_shares(), + } + } + /// The pages a buffer of its own lies in for good (the runtime's memory, or the caller's /// `VkBuffer`); `None` for a no-copy buffer and a heap's. fn fixed_pages(&self) -> Option> { @@ -5589,7 +5609,7 @@ impl Buffer { return self.carry_no_copy(last, own, cell, to, of_heap) } (Owner::Caller, _) => return Err(Left::NoCopy), - (Owner::Vulkan, _) | (Owner::Runtime, Lie::Host(_)) => return Err(Left::Caller), + (Owner::Vulkan { .. }, _) | (Owner::Runtime, Lie::Host(_)) => return Err(Left::Caller), }; let from = last.device.shared(); let placement = &fixed.pages.memory.placement; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs b/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs index ff89d38f5..e2a16b634 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs @@ -401,8 +401,10 @@ impl KeptBarriers { exit_guard::called(Call::CmdWriteTimestamp); } } + // Of the queue's family: a copy engine's on the copy queue's `VkQueue`. + let reads = shared.memory_reads_of(queue); for barrier in barriers { - barrier.record(raw, buffer); + barrier.record_reading(raw, buffer, reads); exit_guard::called(Call::CmdPipelineBarrier); } if let Some(stamps) = stamps.filter(|stamps| stamps.start && stamps.after) { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index ee07fb76a..563eba69c 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -3251,6 +3251,33 @@ impl CommandBuffer { shared.queue_family_of(self.0.queue.vk_queue()) } + /// The reads a global memory barrier recorded for its queue's `VkQueue` names in its + /// destination: those of that queue's family (`image_barrier::MemoryReads`), a copy engine's + /// transfers alone on a queue made for copies (`Device::new_command_queue_for_copies`). + pub(crate) fn memory_reads(&self) -> crate::image_barrier::MemoryReads { + let shared = self.0.device.shared(); + shared.memory_reads_of(self.0.queue.vk_queue()) + } + + /// Refuse `call` with `problem` where its queue was made for copies + /// (`Device::new_command_queue_for_copies`): its commands run on a queue family of transfers + /// alone (`Invalid`, `Problem::CopyQueue`). + pub(crate) fn refuse_for_copies( + &self, + call: &'static str, + problem: crate::error::CopyQueueProblem, + ) -> Result<(), Error> { + match self.0.queue.for_copies() { + true => Err(invalid(call, Problem::CopyQueue(problem))), + false => Ok(()), + } + } + + /// Whether its queue was made for copies (`Device::new_command_queue_for_copies`). + pub(crate) fn for_copies(&self) -> bool { + self.0.queue.for_copies() + } + /// Lend `context` to the command buffer while the commit records a chunk to keep /// (`State::kept`), its arenas taking every set and upload meanwhile; `None`: take back the /// one lent, each `VkCommandBuffer` it handed out meanwhile ended there and counted as ended @@ -5612,12 +5639,14 @@ impl CommandBufferShared { }; let device = self.device.shared().vk(); if fold { + let reads = self.device.shared().memory_reads_of(self.queue.vk_queue()); // SAFETY: the tail is recording, outside any render pass (its encoder's passes began // and ended in its own recordings), and only this call records it, under the state // lock; the slot's queries were reset by the batch's start, before it in submission // order (`submit.rs`). unsafe { - crate::batch_order::end(self.device.shared().by_ends).record(device, raw); + let end = crate::batch_order::end(self.device.shared().by_ends); + end.record_reading(device, raw, reads); if let Some((queries, first)) = stamp { let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE; device.cmd_write_timestamp(raw, bottom, queries, first + 1); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index cebb924d7..44ead7575 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -734,7 +734,13 @@ impl CommandBufferShared { // moves' zeros go unrecorded (`texture/first_move.rs`). let overwritten = first_overwrites(encoders, &state.ended); let overwrites = |key: ResourceKey| overwritten.contains(&key); - let mut first_work = firsts.take_holding(|_| true, fill_take, hold, overwrites); + // A batch of a queue made for copies takes buffers' fills alone, which its family of + // transfers alone records: its commands name every buffer they reach and no image, and + // the moves and staged copies wait for the device's next submission elsewhere. + let mut first_work = match self.queue.for_copies() { + true => firsts.take_fills_alone(fill_take), + false => firsts.take_holding(|_| true, fill_take, hold, overwrites), + }; let every_fill = first_work.every_fill(); // What owns the memory of the first work it took, its fills for the fill queue among it. let taken_owners = first_work.owners(); @@ -1553,6 +1559,10 @@ impl CommandBufferShared { state.retained.push(Box::new(held)); } scheduler.values[queue] = at.value; + // A batch on the copy engine's `VkQueue` (`Device::new_command_queue_for_copies`). + if shared.copy_slot() == Some(queue) { + shared.counts.copy_queue_batch(); + } // Its command buffer's wait behind another command queue's batch there, from its first // batch's submission or hold (`queue_wait.rs`). let on = &shared.queues[queue]; @@ -2178,8 +2188,10 @@ impl CommandBufferShared { exit_guard::called(Call::CmdWriteTimestamp); } } + // Of its queue's family: a copy engine's on a queue made for copies. + let reads = device.shared().memory_reads_of(self.queue.vk_queue()); for barrier in barriers { - barrier.record(raw, buffer); + barrier.record_reading(raw, buffer, reads); exit_guard::called(Call::CmdPipelineBarrier); } if !transitions.is_empty() { diff --git a/crates/metal2vulkan-runtime/src/copy_run.rs b/crates/metal2vulkan-runtime/src/copy_run.rs new file mode 100644 index 000000000..bf1f098cd --- /dev/null +++ b/crates/metal2vulkan-runtime/src/copy_run.rs @@ -0,0 +1,82 @@ +//! A blit encoder's run of buffer copies recorded as one `vkCmdCopyBuffer` +//! (`BlitCommandEncoder::copy_from_buffer_to_buffer`). +//! +//! - **Which copies join.** A copy between the same two `VkBuffer`s as the run's, which the +//! encoder's order needs no barrier after (`EncoderCore::copy_joining`): no copy of the run +//! wrote what it reads or reads or writes what it writes, per resource and range, untracked +//! resources' too (a blit's uses name every byte it touches, `tracker.rs`). The run's regions +//! then touch no byte both as a source and as a destination +//! (`VUID-vkCmdCopyBuffer-pRegions-00117`), and no two of them write one byte, so their order +//! inside the command is no order Metal sees. A program that copies tiles side by side, one copy +//! per row, makes one `vkCmdCopyBuffer` of all of them. +//! - **What ends a run.** Any other command of the encoder, a barrier, a copy between other +//! buffers, and the encoder's end: the run records first, in the `VkCommandBuffer` its first copy +//! would have recorded into, so every command keeps its place in encoded order. +//! - **Where a run breaks.** The encoder's order keeps at most eight ranges of a resource, then +//! merges them into one span, from the lowest byte of any to the highest +//! (`tracker::ENTRIES_PER_KEY`). A copy whose destination lies inside that span of the earlier +//! writes, though it meets none of them, takes a barrier there and starts a new run; so does one +//! whose source lies inside it where both are one buffer's. Copies whose destination offsets rise +//! from one copy to the next (a picture's rows in order, tile beside tile) join whole: sort them +//! by destination offset to merge them all. +//! - **Counted.** Each copy that joined a run as another region +//! (`WorkCounts::buffer_copies_merged`). + +use crate::device::functions::Vk; +use crate::work_counts::Counters; +use ash::vk; + +/// A run of copies from one `VkBuffer` into another, recorded as one `vkCmdCopyBuffer` (the +/// module docs). +pub(crate) struct CopyRun { + /// The `VkCommandBuffer` its first copy took, which records it. + raw: vk::CommandBuffer, + source: vk::Buffer, + destination: vk::Buffer, + regions: Vec, +} + +impl CopyRun { + /// A run of `region` of `source` into `destination`, to record into `raw`. + pub(crate) fn new( + raw: vk::CommandBuffer, + (source, destination, region): (vk::Buffer, vk::Buffer, vk::BufferCopy), + ) -> CopyRun { + CopyRun { + raw, + source, + destination, + regions: vec![region], + } + } + + /// Join `copy` to the run where it copies between its two buffers and records into `raw`, the + /// run's own: whether it joined. + pub(crate) fn join( + &mut self, + raw: vk::CommandBuffer, + (source, destination, region): (vk::Buffer, vk::Buffer, vk::BufferCopy), + ) -> bool { + let joins = self.raw == raw && self.source == source && self.destination == destination; + if joins { + self.regions.push(region); + } + joins + } + + /// Record the run: one `vkCmdCopyBuffer` of its regions, each past the first counted. + /// + /// # Safety + /// + /// The run's command buffer is recording, outside a render pass, and nothing was recorded + /// into it since the run's first copy; both buffers live until it completes, and every + /// region lies inside both. + pub(crate) unsafe fn record(self, device: &Vk, counts: &Counters) { + // SAFETY: the caller's contract; the regions touch no byte as both a source and a + // destination (the module docs). + unsafe { + device.cmd_copy_buffer(self.raw, self.source, self.destination, &self.regions); + } + counts.buffer_copies_merged(self.regions.len() as u64 - 1); + } +} diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs index 88a2b341d..947f87417 100644 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ b/crates/metal2vulkan-runtime/src/device/adopt.rs @@ -343,6 +343,7 @@ impl Device { least_plan: false, staging: None, fill: None, + copies: None, reserved_queues: Vec::new(), extra_queues: Vec::new(), compile, diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index b1d899b78..cc9671e97 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -1246,6 +1246,15 @@ pub(crate) struct QueuePlan { /// one; `None` otherwise. An extra queue the caller asks for takes it as a queue the plan /// leaves free ([`extra_queue_places`]). pub(crate) fill: Option<(u32, u32)>, + /// The queue the program's command queues made for copies submit to + /// (`Device::new_command_queue_for_copies`), of the staging queue's family where that family + /// is of transfers alone (a copy engine), has a second queue and writes timestamps of the + /// primary family's valid bits: its first queue past the staging and fill queues where it has + /// one, else the fill queue's, which the fill queue's submissions and those command queues' + /// then share under one lock (`device/staging.rs`); never the staging queue's, which waits + /// for no work in flight. `None` otherwise. An extra queue the caller asks for takes it as a + /// queue the plan leaves free ([`extra_queue_places`]). + pub(crate) copies: Option<(u32, u32)>, } /// The queues a device of `families` takes: where every family is equivalent to the first that @@ -1369,6 +1378,12 @@ pub(crate) fn queue_plan_within( let staging = copy_engine .or_else(beside) .map(|(index, _)| (index as u32, 0)); + // The copy queue: a copy engine's third queue, else its second, the fill queue's. + let copies = copy_engine + .filter(|(_, family)| { + family.queue_count > 1 && family.timestamp_valid_bits == first.timestamp_valid_bits + }) + .map(|(index, family)| (index as u32, if family.queue_count > 2 { 2 } else { 1 })); // Where every family is equivalent, the primary is family 0, so either way the primary // family's first queue leads (internal submissions go there). Some(QueuePlan { @@ -1378,9 +1393,18 @@ pub(crate) fn queue_plan_within( reserved, staging, fill, + copies, }) } +impl QueuePlan { + /// The copy queue's place where it is a `VkQueue` of its own, not the fill queue's: one more + /// queue the device takes (`families_taken`, [`vk_queues`]). + pub(crate) fn copy_queue_apart(&self) -> Option<(u32, u32)> { + self.copies.filter(|&place| Some(place) != self.fill) + } +} + /// What the queue plan gives a device of `families` whose queue limits /// (`DeviceOptions::queue_limits`) gave it `plan` and `extra_places`, for `reserved` reserved and /// `extra` extra queues asked for, on a device whose textures' images may lie in memory the host @@ -1453,6 +1477,7 @@ pub(crate) fn vk_queues((plan, extra): &PlacedQueues) -> usize { + plan.reserved.len() + usize::from(plan.staging.is_some()) + usize::from(plan.fill.is_some()) + + usize::from(plan.copy_queue_apart().is_some()) + extra.iter().flatten().count() } @@ -1460,10 +1485,12 @@ pub(crate) fn vk_queues((plan, extra): &PlacedQueues) -> usize { /// `VkDeviceQueueCreateInfo` each. fn families_taken(plan: &QueuePlan, extra_places: &[Option<(u32, u32)>]) -> Vec<(u32, usize)> { let mut taken: Vec<(u32, usize)> = Vec::new(); + let copies = plan.copy_queue_apart(); let all = (plan.queues.iter().chain(&plan.present)) .chain(&plan.reserved) .chain(&plan.staging) .chain(&plan.fill) + .chain(&copies) .chain(extra_places.iter().flatten()); for &(family, _) in all { match taken.iter_mut().find(|(at, _)| *at == family) { @@ -1619,8 +1646,10 @@ pub(crate) const QUEUE_LIMITS_REACHED: &str = "metal2vulkan-queue-limits-reached /// at its lowest free index; else the last queue the plan reserved for presenting, then the last /// of the round robin's but its first (internal submissions go there), then the staging queue, of /// such a family, which `plan` then gives up; never a queue reserved for the caller. The fill -/// queue is one the plan leaves free: an extra queue may take it, and the plan then gives it up. -/// Flags that are empty, or that no family's contain, take none. +/// queue and the copy queue are queues the plan leaves free: an extra queue may take either, and +/// the plan then gives it up (and the copy queue with the fill queue, where it is the fill +/// queue's, or with the staging queue). Flags that are empty, or that no family's contain, take +/// none. pub(crate) fn extra_queue_places( families: &[vk::QueueFamilyProperties], plan: &mut QueuePlan, @@ -1661,13 +1690,22 @@ pub(crate) fn extra_queue_places( }); if let Some(place) = place { extra.push(place); - // The fill queue is a queue the plan leaves free to the caller's extra queues. + // The fill and copy queues are queues the plan leaves free to the caller's extra + // queues. if plan.fill == Some(place) { plan.fill = None; } + if plan.copies == Some(place) { + plan.copies = None; + } } places.push(place); } + // The copy queue's buffers are those shared with the staging queue's family (`sharing.rs`): + // it goes with that queue. + if plan.staging.is_none() { + plan.copies = None; + } places } @@ -2513,6 +2551,7 @@ pub(super) fn create_on( queues: plan.queues.into_iter().chain(plan.present).collect(), staging: plan.staging, fill: plan.fill, + copies: plan.copies, reserved_queues: plan.reserved, extra_queues: (options.extra_queues.iter().zip(&extra_places)) .filter_map(|(&flags, place)| place.map(|(family, index)| (flags, family, index))) diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index b71bad7ad..ec0fcaed9 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -269,8 +269,11 @@ pub(super) struct DeviceShared { /// buffers are shared among (`sharing.rs`). pub(super) buffer_families: Vec, /// How many of `queues`, the first, logical queues share round robin; the rest are reserved - /// for presenting queues. + /// for presenting queues, but the copy queue's. round_robin: usize, + /// The index of the copy queue's `VkQueue` among `queues`, the last, where the device has + /// one (`queue.rs`, `Device::new_command_queue_for_copies`). + copy_slot: Option, /// The logical queues made round robin so far, unshared ones among them: the next one's turn /// among the round robin's `VkQueue`s the fewest live queues hold is this modulo /// `round_robin` (`Device::take_round_robin`). @@ -1132,18 +1135,36 @@ impl DeviceShared { self.queues[index].flags } + /// The reads a global memory barrier recorded for the device's `VkQueue` at `index` names + /// (`image_barrier::MemoryReads`): its family's. + pub(crate) fn memory_reads_of(&self, index: usize) -> MemoryReads { + self.queues[index].reads + } + /// How many of its `VkQueue`s, the first, the round robin lends logical queues; the rest are - /// reserved for presenting queues. + /// reserved for presenting queues, but the copy queue's. pub(crate) fn round_robin(&self) -> usize { self.round_robin } + /// How many of its `VkQueue`s, after the round robin's, are reserved for presenting queues. + pub(crate) fn presenting(&self) -> usize { + self.queues.len() - self.round_robin - usize::from(self.copy_slot.is_some()) + } + + /// The index of the copy queue's `VkQueue`, where the device has one: the last of its + /// `VkQueue`s, of a family of transfers alone (`queue.rs`, + /// `Device::new_command_queue_for_copies`). + pub(crate) fn copy_slot(&self) -> Option { + self.copy_slot + } + /// Where the device's queue limits changed its round robin's or presenting queues' /// `VkQueue`s from the queue plan's (`DeviceOptions::queue_limits`), how many it took of /// each and how many the plan gives. pub(crate) fn queues_limited(&self) -> Option<((usize, usize), (usize, usize))> { let planned = self.planned?; - let taken = (self.round_robin, self.queues.len() - self.round_robin); + let taken = (self.round_robin, self.presenting()); (taken != planned).then_some((taken, planned)) } @@ -1380,6 +1401,9 @@ pub(crate) struct QueueSlot { /// The family's queue flags: the commands it runs, and so the accesses a barrier recorded /// for it may name (`image_barrier.rs`). flags: vk::QueueFlags, + /// The reads a global memory barrier recorded for it names: its family's + /// (`image_barrier::MemoryReads`), a copy engine's transfers alone on the copy queue's. + reads: MemoryReads, /// The queue's loader word, which MoltenVK overwrites where a message names the queue /// (`relay.rs`): put back before each use. word: LoaderWord, @@ -1971,7 +1995,7 @@ impl Device { if self.test_queue_limited() { create::needs_the_queue_plan("made a command queue for presenting"); } - let reserved = self.shared().queues.len() - self.shared().round_robin; + let reserved = self.shared().presenting(); if let Some((_, planned)) = self.shared().planned { let asked = (self.shared().presenting_asked).fetch_add(1, Ordering::Relaxed); if create::shares_past_limit(asked, reserved, planned) { @@ -2041,6 +2065,11 @@ pub(super) struct Parts { /// `queues` (`staging.rs`): `None` for an adopted device, or where the staging queue's family /// is not of transfers alone or has no second queue. pub(super) fill: Option<(u32, u32)>, + /// The queue the program's command queues made for copies submit to + /// (`create.rs`'s `QueuePlan::copies`), its family (the staging queue's) and index there, + /// outside `queues`: the fill queue's where `fill` is the same place, which the two then + /// share; `None` for an adopted device, or where the plan has none. + pub(super) copies: Option<(u32, u32)>, /// The queues reserved for the caller (`DeviceOptions::reserved_queues`), each its family and /// index there, of `queues`' families, outside `queues` and `staging`: none for an adopted /// device. @@ -2177,6 +2206,7 @@ impl Device { least_plan, staging: staging_place, fill: fill_place, + copies: copy_place, reserved_queues: reserved_places, extra_queues: extra_places, compile, @@ -2219,6 +2249,10 @@ impl Device { line: recovering, recipe, } = parts; + // The copy queue's `VkQueue`, where the device has one, is the last of those the runtime + // submits to, after presenting's (`queue.rs`, `Device::new_command_queue_for_copies`). + let copy_slot = copy_place.map(|_| queue_places.len()); + let queue_places: Vec<(u32, u32)> = queue_places.into_iter().chain(copy_place).collect(); // Every pipeline made on the device from here on is made at the user-initiated class. // SAFETY: the device is live (the caller's contract), and its functions are its own. let raw = unsafe { compiles::route(raw) }; @@ -2315,6 +2349,7 @@ impl Device { stall_due: AtomicBool::new(false), family, flags: flags_of(family), + reads: memory_reads.for_family(flags_of(family)), // SAFETY: the queue was just returned, its word the loader's. word: unsafe { LoaderWord::of_handle(queue.as_raw()) }, flights: OnceLock::new(), @@ -2332,7 +2367,10 @@ impl Device { .collect(); let mut queue_families: Vec = Vec::with_capacity(queues.len()); let reserved_families = reserved_places.iter().map(|&(family, _)| family); - for family in queues + // Not the copy queue's family: its command buffers use buffers alone, which are shared + // with it as the staging queue's family (below); images keep the device's own families. + let own_queues = &queues[..copy_slot.unwrap_or(queues.len())]; + for family in own_queues .iter() .map(|slot| slot.family) .chain(reserved_families) @@ -2355,14 +2393,19 @@ impl Device { }) } }); - // The fill queue, of the staging queue's family, whose sharing every buffer has. + // The fill queue, of the staging queue's family, whose sharing every buffer has. Where the + // copy queue's `VkQueue` is its own, its submissions take that queue's lock. let fill_queue = fill_place.map(|(family, index)| { // SAFETY: as the staging queue's. - unsafe { + let fills = unsafe { loader_word.restored(|| { let queue = raw.get_device_queue(family, index); staging::StagingQueue::new(Role::Fills, family, flags_of(family), queue, &[]) }) + }; + match copy_place == Some((family, index)) { + true => fills.sharing_slot(copy_slot), + false => fills, } }); let reserved_queues = (reserved_places.iter()) @@ -3053,7 +3096,8 @@ impl Device { physical, functions, queue_family, - round_robin: queues.len() - present_queues, + round_robin: queues.len() - present_queues - usize::from(copy_slot.is_some()), + copy_slot, queues: queues.into(), queue_families, buffer_families, diff --git a/crates/metal2vulkan-runtime/src/device/staging.rs b/crates/metal2vulkan-runtime/src/device/staging.rs index a180b852a..4ac8fc276 100644 --- a/crates/metal2vulkan-runtime/src/device/staging.rs +++ b/crates/metal2vulkan-runtime/src/device/staging.rs @@ -121,6 +121,11 @@ //! would need "their ownership explicitly transferred" (7.7.6 Queue Family Ownership Transfer). //! - **What it holds.** Each buffer's memory and each fill's staging buffer, until the batch that //! waited for the submission completed ([`FillSubmission`]). +//! - **Shared with the copy queue.** On a copy engine of two queues (NVIDIA's), the fill queue's +//! `VkQueue` is the copy queue's too (`create::QueuePlan::copies`, +//! `Device::new_command_queue_for_copies`): its submissions take that queue's lock as well, and +//! go in submission order with the copy queue's batches, which wait for work in flight as its +//! own do. On one of three or more the copy queue takes the third. //! - **Not moved.** A texture's first move and zeros, host calls' staged texel copies and an //! internal submission's fills stay where they were; encoders' copies of host shadows run in //! the program's command buffers. @@ -212,6 +217,11 @@ pub(super) struct StagingQueue { families: Vec, /// The queue's loader word, put back before each use (`relay.rs`). word: LoaderWord, + /// The index of the device's `VkQueue` (`DeviceShared::queues`) that is this queue too, whose + /// lock each `vkQueueSubmit` here takes, under this queue's: the fill queue's where the copy + /// queue shares it (`create.rs`'s `QueuePlan::copies`); `None` where the queue is this + /// module's alone. + slot: Option, /// The queue, and the objects its submissions use once made: under one lock, held for a /// submission's recording and its `vkQueueSubmit`, never for a wait. objects: Mutex, @@ -270,6 +280,7 @@ impl StagingQueue { families: families.iter().copied().chain([family]).collect(), // SAFETY: the caller's contract. word: unsafe { LoaderWord::of_handle(queue.as_raw()) }, + slot: None, objects: Mutex::new(Objects { queue, made: None }), timeline: OnceLock::new(), submitted: AtomicU64::new(0), @@ -280,6 +291,12 @@ impl StagingQueue { } } + /// The queue, its `VkQueue` the device's `VkQueue` at `slot` too (`DeviceShared::queues`), + /// whose lock its submissions then take: the fill queue's, where the copy queue shares it. + pub(super) fn sharing_slot(self, slot: Option) -> StagingQueue { + StagingQueue { slot, ..self } + } + /// Destroy the objects; the device is idle. pub(super) fn destroy(&self, device: &ash::Device) { if let Some(made) = lock(&self.objects).made.take() { @@ -424,17 +441,27 @@ impl StagingLock<'_> { if let Some(audit) = raw.pending_audit() { audit.submitted(raw, carried, &[&buffers[..]]); } - // SAFETY: the queue is used under the staging lock alone; the command buffer is - // executable; every value waited for was signalled (the host saw it); the signal of the - // timeline is above its value. shared.counts.queue_submitted(1, buffers.len()); - shared.queue_quiet.began(); let submits = [submit]; - let submitted = unsafe { - staging.word.restore(); - raw.queue_submit(queue, &submits, vk::Fence::null()) + let submitted = match staging.slot { + // The copy queue's `VkQueue` too: under its lock as well, which puts its word back and + // counts the use. + // SAFETY: the queue is used under the staging lock and its slot's; the command buffer + // is executable; every value waited for was signalled (the host saw it); the signal of + // the timeline is above its value. + Some(slot) => shared.queues[slot] + .with(|queue| unsafe { raw.queue_submit(queue, &submits, vk::Fence::null()) }), + None => { + shared.queue_quiet.began(); + // SAFETY: the queue is used under the staging lock alone; as above otherwise. + let submitted = unsafe { + staging.word.restore(); + raw.queue_submit(queue, &submits, vk::Fence::null()) + }; + shared.queue_quiet.ended(); + submitted + } }; - shared.queue_quiet.ended(); exit_guard::called(Call::QueueSubmit); if let Err(result) = submitted { if let Some(audit) = raw.pending_audit() { diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 598ee28bd..c66b37793 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -50,10 +50,13 @@ use super::churn_counts::KeepBy; use super::command_buffer::rebound_use::Unlogged; use super::command_buffer::{recording_error, CommandBuffer, State}; use super::compute::Parked; +use super::copy_run::CopyRun; use super::deferred::{Deferred, StepInputs}; use super::degradation::NoticesFor; use super::encoder_fold::{self, Fold, FoldEnd, Joining}; -use super::error::{internal, invalid, vulkan, CommandBufferError, Error, VkResultCode}; +use super::error::{ + internal, invalid, vulkan, CommandBufferError, CopyQueueProblem, Error, VkResultCode, +}; use super::execution::Execution; use super::fresh_unwritten::{FreshRead, FreshUnwritten}; use super::heap::Heap; @@ -721,6 +724,10 @@ impl EncoderCore { (ordered, joining): (bool, Option), opening: impl FnOnce(&mut State) -> T, ) -> Result<(EncoderCore, T), Error> { + // A queue made for copies takes blit encoders alone. + if kind != EncoderKind::Blit { + command_buffer.refuse_for_copies(call, CopyQueueProblem::Encoder)?; + } let state = command_buffer.state(); if matches!(kind, EncoderKind::Compute | EncoderKind::Render) { state.refuse_protected(call)?; @@ -757,9 +764,10 @@ impl EncoderCore { // Past the encoders whose barriers the scheduler plans, a barrier from everything // before leads the encoder's commands (the module docs). let barriered = (state.encoders_ended() >= PLANNED_BARRIERS).then(|| { + let reads = command_buffer.memory_reads(); // SAFETY: the command buffer was just begun, outside a render pass, under the - // state lock; only this encoder records it. - unsafe { Barrier::everything().record(shared.vk(), raw) }; + // state lock; only this encoder records it, of its queue's family. + unsafe { Barrier::everything().record_reading(shared.vk(), raw, reads) }; shared.counts.encoder_barriered_at_open(); raw }); @@ -1222,8 +1230,10 @@ impl EncoderCore { let Some(raw) = self.recording() else { return; }; - // SAFETY: the encoder's command buffer is recording, and only this encoder records it. - unsafe { barrier.record(self.device().shared().vk(), raw) }; + let reads = self.open.command_buffer.memory_reads(); + // SAFETY: the encoder's command buffer is recording, and only this encoder records it, of + // its queue's family. + unsafe { barrier.record_reading(self.device().shared().vk(), raw, reads) }; } /// Record a memory barrier the program asked for in a compute encoder @@ -1429,8 +1439,9 @@ impl EncoderCore { return; }; let shared = self.open.command_buffer.device().shared(); + let reads = self.open.command_buffer.memory_reads(); // SAFETY: as in `barrier`. - unsafe { barrier.record(shared.vk(), raw) }; + unsafe { barrier.record_reading(shared.vk(), raw, reads) }; shared.counts.command_barrier(); fold.order.ordered(barrier); } @@ -1635,8 +1646,9 @@ impl EncoderCore { }; let device = self.open.command_buffer.device().shared().vk(); if let Some(barrier) = barrier { + let reads = self.open.command_buffer.memory_reads(); // SAFETY: as in `barrier`. - unsafe { barrier.record(device, raw) }; + unsafe { barrier.record_reading(device, raw, reads) }; } record(device, raw); if let Some(writes) = &mut self.alias_writes { @@ -1644,6 +1656,63 @@ impl EncoderCore { } } + /// [`command_named`](Self::command_named) of a buffer copy, `copy` (its source, its + /// destination and its region) with `uses`, that joins `run`, the encoder's run of copies + /// recorded as one `vkCmdCopyBuffer` (`copy_run.rs`), where the encoder's order needs no + /// barrier after the copies before it and the run copies between the same two buffers into + /// the `VkCommandBuffer` the encoder records into; else the run records first, then the + /// copy's barrier, and the copy starts a new run, which records at the encoder's next other + /// command or at its end ([`flush_copies`](Self::flush_copies)). The caller records nothing + /// into the encoder's command buffer meanwhile but through this. + pub(super) fn copy_joining( + &mut self, + uses: &[Use], + copy: (vk::Buffer, vk::Buffer, vk::BufferCopy), + run: &mut Option, + ) { + let split = (self.alias_writes.as_ref()).is_some_and(|writes| writes.meets(uses)); + let none = BTreeSet::new(); + let stages = vk::PipelineStageFlags2::TRANSFER; + let Some(barrier) = self.track(stages, uses, (&none, Reach::Named), &[]) else { + return; + }; + let joined = barrier.is_none() + && !split + && (run.as_mut()).is_some_and(|open| open.join(self.raw, copy)); + if !joined { + self.flush_copies(run); + if split && !self.split_at_aliases() { + return; + } + let Some(raw) = self.recording_ordered() else { + return; + }; + if let Some(barrier) = barrier { + let device = self.open.command_buffer.device().shared().vk(); + let reads = self.open.command_buffer.memory_reads(); + // SAFETY: as in `barrier`. + unsafe { barrier.record_reading(device, raw, reads) }; + } + *run = Some(CopyRun::new(raw, copy)); + } + if let Some(writes) = &mut self.alias_writes { + writes.note(uses); + } + } + + /// Record `run`, the encoder's run of buffer copies ([`copy_joining`](Self::copy_joining)), + /// where it has one: before any other command of the encoder, and at its end. + pub(super) fn flush_copies(&mut self, run: &mut Option) { + if let Some(run) = run.take() { + let shared = self.open.command_buffer.device().shared(); + // SAFETY: the run's command buffer is the encoder's, recording outside a render pass: + // nothing recorded into it or ended it since the run's first copy, as every other + // command and the encoder's end record the run first; its commands retain both + // buffers, and every region lies inside both. + unsafe { run.record(shared.vk(), &shared.counts) }; + } + } + /// End the `VkCommandBuffer` the encoder records into and go on in a new one, before a /// command that uses an image over bytes a command before it there wrote through a buffer, /// on a device whose image uses miss such writes inside one (`alias_split.rs`): the diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 4262a5d13..12a9c2758 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -671,6 +671,12 @@ pub enum Problem { /// /// Basis: ours (a runtime extension: Metal exports no command buffer's completion). SyncFile(SyncFileProblem), + /// A call on a command buffer of a queue made for copies + /// (`Device::new_command_queue_for_copies`) that its copy engine's queue family does not run, + /// or over a resource that family does not share ([`CopyQueueProblem`]). + /// + /// Basis: ours (a runtime extension: Metal has no queue of copies alone). + CopyQueue(CopyQueueProblem), /// No pipeline state is set (plain Metal faults at a compute dispatch without one). /// /// Basis: unknown (plain Metal is held to fault at a dispatch with no pipeline state, on no @@ -1209,6 +1215,24 @@ pub enum SyncFileProblem { Exported, } +/// What a command buffer of a queue made for copies (`Device::new_command_queue_for_copies`, a +/// runtime extension: Metal has none) does not take: its commands run on a queue family of +/// transfers alone, which shares buffers with the device's other families and no image. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CopyQueueProblem { + /// An encoder but a blit encoder: a render, compute, resource state or acceleration + /// structure encoder, whose commands the family does not run. + Encoder, + /// A blit command but `copy_from_buffer_to_buffer`, `fill_buffer` and the fence updates and + /// waits: a texture's (its image is shared only among the device's own families), a + /// resource's synchronization, an indirect command buffer's, a counter's. + Command, + /// A buffer the caller made (`Device::new_buffer_with_vk_buffer`) that is not concurrent with + /// the copy engine's family, whose contents that family would take undefined. + Buffer, +} + /// Why `DeviceOptions::instance_api_version` cannot be requested. The runtime never clamps a /// request to what it can make. #[non_exhaustive] diff --git a/crates/metal2vulkan-runtime/src/image_barrier.rs b/crates/metal2vulkan-runtime/src/image_barrier.rs index 5e6909db3..ec68f50b7 100644 --- a/crates/metal2vulkan-runtime/src/image_barrier.rs +++ b/crates/metal2vulkan-runtime/src/image_barrier.rs @@ -496,6 +496,12 @@ impl MemoryReads { } } + /// The reads of a family of `family`'s queue flags on the same device: a queue of another + /// family's (`DeviceShared::memory_reads_of`). + pub(crate) fn for_family(self, family: vk::QueueFlags) -> MemoryReads { + MemoryReads { family, ..self } + } + /// The destination access mask `dst` beside the destination stages `stages` with /// `MEMORY_READ` in it replaced by the reads it stands for there: every read valid beside /// those stages on the family, which the device has. `dst` itself where one of them has no diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 089665da5..90f3a97d3 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -70,6 +70,7 @@ mod contexts; mod copied; mod copied_base; mod copy_plan; +mod copy_run; mod creation; mod deferred; mod degradation; @@ -316,10 +317,11 @@ pub use error::Nil; pub use error::NotInPlace; pub use error::Unproven; pub use error::{ - ArchivedPipeline, BinaryArchiveError, BinaryArchiveMiss, CommandBufferError, DeadlockCause, - DeviceRefused, DriverSetting, EncoderCall, Error, IndirectRule, InstanceApiVersion, Invalid, - LoaderNotFound, MemoryKind, MeshRecordsOverflow, Problem, RuntimeGap, SamplerLimit, - ShaderCacheError, SyncFileProblem, TessellationRecordsOverflow, TimedOut, VkResultCode, + ArchivedPipeline, BinaryArchiveError, BinaryArchiveMiss, CommandBufferError, CopyQueueProblem, + DeadlockCause, DeviceRefused, DriverSetting, EncoderCall, Error, IndirectRule, + InstanceApiVersion, Invalid, LoaderNotFound, MemoryKind, MeshRecordsOverflow, Problem, + RuntimeGap, SamplerLimit, ShaderCacheError, SyncFileProblem, TessellationRecordsOverflow, + TimedOut, VkResultCode, }; pub use error::{FailedPipeline, FailedState, PipelineCreationCause}; pub use event::{ diff --git a/crates/metal2vulkan-runtime/src/queue.rs b/crates/metal2vulkan-runtime/src/queue.rs index f4131de8c..48cfbded7 100644 --- a/crates/metal2vulkan-runtime/src/queue.rs +++ b/crates/metal2vulkan-runtime/src/queue.rs @@ -44,6 +44,12 @@ //! that finds none free shares the one the fewest hold, counted //! (`WorkCounts::unshared_queues_sharing_a_vk_queue`). //! +//! **Queues made for copies.** A queue made with `Device::new_command_queue_for_copies` submits to +//! the device's copy engine, a `VkQueue` of a family of transfers alone after presenting's +//! (`device/create.rs`, `QueuePlan::copies`), which every such queue of the device takes and none +//! leaves; its command buffers take buffer copies, fills and fences alone (`Problem::CopyQueue`), +//! and its batches are planned against the device's hazard state as any queue's. +//! //! **The caller's own queues.** A caller that submits Vulkan work of its own beside Metal's, and //! must not wait behind a command queue's command buffers nor hold one back, asks the device for //! queues of its own families (`DeviceOptions::reserved_queues`, `DeviceHandles::reserved_queues`): @@ -225,6 +231,9 @@ enum Kind { Unshared, /// `new_command_queue_for_presenting`: never moves. Presenting, + /// `new_command_queue_for_copies`: never moves; its command buffers take buffer copies and + /// fills alone (`Device::new_command_queue_for_copies`). + Copies, } /// Whom a queue was made for, and so whether its places count toward Metal's device ID rules @@ -608,6 +617,65 @@ impl Device { Ok(self.command_queue(count, Kind::Presenting, MadeFor::Program)) } + /// No Metal counterpart: Metal has no queue of copies alone, and runs a blit encoder's copies + /// on any command queue. A queue whose command buffers submit to the device's copy engine (a + /// queue family of transfers alone), of at most 64 uncompleted command buffers as + /// [`new_command_queue`](Self::new_command_queue)'s, for copies between buffers that run + /// beside, not behind, other queues' command buffers: on an RTX 3090 a readback through + /// another queue of the graphics family waited 1.88 s for a 2 s kernel on the first, where the + /// copy engine's took 7.8 to 13.5 ms with the kernel running (`device/staging.rs`). + /// + /// `None` where the device has no copy engine to give it: a device whose staging queue is no + /// family of transfers alone with a second queue that writes timestamps of the primary + /// family's valid bits, or that resets no queries on the host (`hostQueryReset`), or a device + /// the caller made (`Device::from_raw`). MoltenVK's, lavapipe's and RADV's devices have none + /// (RADV lists a family of transfers alone only under `RADV_PERFTEST=transfer_queue`); NVIDIA's + /// copy engine has two queues, the staging queue's and the fill queue's, so its copy queues + /// share the fill queue's `VkQueue` (`device/staging.rs`). Every copy queue of a device submits + /// to that one `VkQueue`, in commit order across them, and none moves. + /// + /// Its command buffers take blit encoders alone, and of their commands + /// [`copy_from_buffer_to_buffer`](crate::BlitCommandEncoder::copy_from_buffer_to_buffer), + /// [`fill_buffer`](crate::BlitCommandEncoder::fill_buffer) and the fence updates and waits. + /// Refused (`Invalid`, `Problem::CopyQueue`): any other encoder (`CopyQueueProblem::Encoder`), + /// any other blit command, a texture's above all, whose images are shared only among the + /// device's own families (`CopyQueueProblem::Command`), and a buffer the caller made + /// ([`new_buffer_with_vk_buffer`](Self::new_buffer_with_vk_buffer)) whose sharing leaves the + /// copy engine's family out (`CopyQueueProblem::Buffer`). + /// + /// Every buffer the device makes, a no-copy buffer over host pages among them, is concurrent + /// (`VK_SHARING_MODE_CONCURRENT`) among the device's queue families and the copy engine's, as + /// the staging queue's (`sharing.rs`), so no buffer changes owner and no queue family + /// ownership transfer is recorded: "concurrent access to any range ... of the object from + /// multiple queue families is supported" (the Vulkan specification, Resource Sharing). Its + /// command buffers' hazards are tracked as any queue's: a copy that reads what another + /// queue's command buffer committed before it writes waits for that command buffer on the GPU + /// (its `VkQueue`'s timeline), and the other way around. Their completion sync files + /// ([`CommandBuffer::export_completion_sync_file`](crate::CommandBuffer::export_completion_sync_file)) + /// are signalled on the copy engine. + /// + /// Refused as `new_command_queue` is on a lost device (`DeviceLost`). + pub fn new_command_queue_for_copies(&self) -> Result, Error> { + self.at_serving(|device| device.new_command_queue_for_copies_now()) + } + + /// [`Device::new_command_queue_for_copies`] on the generation that serves + /// (`device/line.rs`). + pub(crate) fn new_command_queue_for_copies_now(&self) -> Result, Error> { + if self.is_lost() { + return Err(self.lost_refusal()); + } + if self.shared().copy_slot().is_none() || !self.shared().timing.resets_on_host() { + return Ok(None); + } + let count = DEFAULT_MAX_COMMAND_BUFFER_COUNT; + Ok(Some(self.command_queue( + count, + Kind::Copies, + MadeFor::Program, + ))) + } + /// A queue of at most `count` uncompleted command buffers made by `kind`'s constructor for /// `made_for`, with its place on this generation, known to the device's line, whose /// recoveries retire it (`device/line.rs`). @@ -684,6 +752,12 @@ impl Device { self.next_queue(None) } }, + // The copy queue's `VkQueue`; a recovery's new generation, made by the same plan, has + // it too, and one without takes the round robin's, whose family transfers too. + Kind::Copies => match self.shared().copy_slot() { + Some(slot) => (self.shared().contexts.fresh(), slot), + None => self.next_queue(None), + }, } } @@ -1084,6 +1158,12 @@ impl QueueGen { self.0.kind == Kind::Unshared } + /// Whether it was made with `Device::new_command_queue_for_copies`: its command buffers take + /// buffer copies and fills alone (`Problem::CopyQueue`). + pub(crate) fn for_copies(&self) -> bool { + self.0.kind == Kind::Copies + } + /// The expected run of its batches (`unshared_hold.rs`). pub(super) fn expected(&self) -> &Arc { &self.0.expected diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 965624f6b..c0df803ab 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -2225,6 +2225,9 @@ impl CommandBuffer { descriptor: &RenderPassDescriptor, ) -> Result { let _for = self.notices_for(); + // A queue made for copies takes no render encoder (`Device::new_command_queue_for_copies`). + let copies = crate::error::CopyQueueProblem::Encoder; + self.refuse_for_copies("render_command_encoder", copies)?; // The last render encoder's end, where its call left it to the device's lowering thread, // and the kept draw it carried, or its end where it kept none (`render/carried.rs`), // which nothing came between. diff --git a/crates/metal2vulkan-runtime/src/replay.rs b/crates/metal2vulkan-runtime/src/replay.rs index 0c2aaeab6..6915d8f01 100644 --- a/crates/metal2vulkan-runtime/src/replay.rs +++ b/crates/metal2vulkan-runtime/src/replay.rs @@ -786,6 +786,45 @@ pub(super) enum BlitCall { } impl BlitCall { + /// Whether a queue made for copies takes it (`Device::new_command_queue_for_copies`): a copy + /// between buffers, a fill of one, a fence's update or wait, whose commands its copy engine's + /// family of transfers alone records; else the call's name, which that queue refuses + /// (`CopyQueueProblem::Command`). + pub(super) fn on_copy_engine(&self) -> Result<(), &'static str> { + let name = match self { + BlitCall::CopyBufferToBuffer(..) + | BlitCall::FillBuffer(..) + | BlitCall::UpdateFence(_) + | BlitCall::WaitForFence(_) => return Ok(()), + BlitCall::FillBufferPattern4(..) => "fill_buffer_pattern4", + BlitCall::SynchronizeResource(_) => "synchronize_resource", + BlitCall::FillTexture(..) => "fill_texture", + BlitCall::FillTextureColor(_) => "fill_texture_color", + BlitCall::CopyBufferToTexture(_) => "copy_from_buffer_to_texture", + BlitCall::CopyTextureToBuffer(_) => "copy_from_texture_to_buffer", + BlitCall::CopyTextureToTexture(_) => "copy_from_texture_to_texture", + BlitCall::CopyTextureSlices(_) => "copy_texture_slices", + BlitCall::CopyTexture(..) => "copy_texture", + BlitCall::GenerateMipmaps(_) => "generate_mipmaps", + BlitCall::SynchronizeTexture(..) => "synchronize_texture", + BlitCall::OptimizeForGpu(_) => "optimize_contents_for_gpu_access", + BlitCall::OptimizeForGpuSliceLevel(..) => { + "optimize_contents_for_gpu_access_slice_level" + } + BlitCall::OptimizeForCpu(_) => "optimize_contents_for_cpu_access", + BlitCall::OptimizeForCpuSliceLevel(..) => { + "optimize_contents_for_cpu_access_slice_level" + } + BlitCall::CopyIndirectCommandBuffer(_) => "copy_indirect_command_buffer", + BlitCall::ResetCommandsInBuffer(..) => "reset_commands_in_buffer", + BlitCall::OptimizeIndirectCommandBuffer(..) => "optimize_indirect_command_buffer", + BlitCall::InvalidateCompressedTexture(_) => "invalidate_compressed_texture", + BlitCall::InvalidateCompressedTextureSlice(..) => "invalidate_compressed_texture_slice", + BlitCall::HostRamCopy(_) => "copy_from_host_ram", + }; + Err(name) + } + /// The bytes it holds in boxes of its own, besides its size. pub(super) fn extra(&self) -> usize { match self { diff --git a/crates/metal2vulkan-runtime/src/sparse/encoder.rs b/crates/metal2vulkan-runtime/src/sparse/encoder.rs index 71b6df565..2119cff20 100644 --- a/crates/metal2vulkan-runtime/src/sparse/encoder.rs +++ b/crates/metal2vulkan-runtime/src/sparse/encoder.rs @@ -82,6 +82,10 @@ impl CommandBuffer { /// (`Invalid`). pub fn resource_state_command_encoder(&self) -> Result { let _for = self.notices_for(); + // A queue made for copies takes no resource state encoder: its family binds no sparse + // memory (`Device::new_command_queue_for_copies`). + let copies = crate::error::CopyQueueProblem::Encoder; + self.refuse_for_copies("resource_state_command_encoder", copies)?; // The last render encoder's end, where its call left it to the device's lowering thread. self.settle_end(); self.refuse_protected_state_encoder()?; diff --git a/crates/metal2vulkan-runtime/src/tests/copy_queue.rs b/crates/metal2vulkan-runtime/src/tests/copy_queue.rs new file mode 100644 index 000000000..c476a5066 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/copy_queue.rs @@ -0,0 +1,328 @@ +//! A queue made for copies (`Device::new_command_queue_for_copies`, `queue.rs`) and a blit +//! encoder's runs of buffer copies (`copy_run.rs`). +//! +//! - **The copy queue.** Where the device gives one (a copy engine of two queues or more: NVIDIA's; +//! RADV's under `RADV_PERFTEST=transfer_queue`), a command buffer of another queue fills a +//! `Private` buffer behind 1 GiB of fills, and a command buffer of the copy queue committed right +//! after it, with no wait between, copies 64 rows of it, side by side in rising offsets, into a +//! no-copy buffer over host pages: the copies read what the fill wrote (the tracker's wait across +//! the two `VkQueue`s), land where they were asked and nowhere else, run on the copy engine's +//! `VkQueue` (`WorkCounts::copy_queue_batches`) as one `vkCmdCopyBuffer` +//! (`WorkCounts::buffer_copies_merged`), and their command buffer's completion sync file signals. +//! Its command buffers refuse a compute encoder and every blit command but buffer copies, fills +//! and fences (`Problem::CopyQueue`), and the validation layer reports nothing. Where the device +//! gives none (lavapipe's, RADV's by default, MoltenVK's), the answer is `None`, printed +//! (`COPY-QUEUE-NONE`), and the device has no copy engine's `VkQueue` to give. +//! - **Runs of copies, on any queue.** 64 such row copies of one blit encoder are one +//! `vkCmdCopyBuffer` (63 merged); copies that meet (a copy of bytes a copy before wrote, two +//! copies into one range) or go between other buffers take a barrier or a command of their own +//! and merge nothing; every byte lands as the copies in their order leave it. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`). + +use super::blit_holds::{busy, over_host, Host, Scratch, WAIT}; +use super::layer_claim::Watched; +use crate::{ + CommandBufferStatus, CopyQueueProblem, Error, Invalid, Problem, ResourceOptions, ResourceRef, +}; +use std::sync::atomic::AtomicUsize; +use std::sync::Arc; +use std::time::Instant; + +/// The rows each copy leg copies. +const ROWS: u64 = 64; + +/// The bytes of a row. +const ROW: u64 = 256; + +/// Where the rows lie in the source: rows of a picture `SOURCE_PITCH` bytes apart, from byte +/// `SOURCE_AT` of each. +const SOURCE_PITCH: u64 = 1024; +const SOURCE_AT: u64 = 128; + +/// Where they go in the destination: `DESTINATION_PITCH` bytes apart, from byte +/// `DESTINATION_AT` of each. +const DESTINATION_PITCH: u64 = 512; +const DESTINATION_AT: u64 = 64; + +/// The byte the fill writes into the source. +const FILLED: u8 = 0x5a; + +/// The word the destination's host pages hold before the copies. +const BEFORE: u32 = 0xeeee_eeee; + +/// The row copies: each row's source and destination offsets, both rising. +fn rows() -> impl Iterator { + (0..ROWS).map(|row| { + ( + row * SOURCE_PITCH + SOURCE_AT, + row * DESTINATION_PITCH + DESTINATION_AT, + ) + }) +} + +/// Whether byte `at` of the destination is one a row copy wrote. +fn copied(at: u64) -> bool { + let row = at / DESTINATION_PITCH; + let within = at % DESTINATION_PITCH; + row < ROWS && (DESTINATION_AT..DESTINATION_AT + ROW).contains(&within) +} + +/// The invalid call's problem. +fn problem(result: Result) -> Problem { + match result { + Err(Error::Invalid(Invalid { problem, .. })) => problem, + other => panic!("not an invalid call: {other:?}"), + } +} + +/// The copy queue's leg (the module docs). +#[test] +fn copies_on_the_copy_engine_follow_another_queue_s_writes() { + const LEG: &str = "COPY-QUEUE"; + let host = Host::new(); + host.fill(BEFORE); + let watched = Watched::default(); + let scratch = Scratch::new("copy-queue"); + let device = super::pending_rebind::device(&watched, &scratch.0); + let name = device.name().to_owned(); + let Some(copies) = device.new_command_queue_for_copies().unwrap() else { + // `None` for want of a copy engine's queue (lavapipe's one queue, RADV's families by + // default), or of host query resets. + let shared = device.shared(); + let slot = shared.copy_slot(); + let resets = shared.timing.resets_on_host(); + eprintln!( + "COPY-QUEUE-NONE on {name}: the device gives no queue made for copies (copy engine's \ + VkQueue {slot:?}, host query resets {resets})" + ); + assert!( + slot.is_none() || !resets, + "{LEG} on {name}: a copy engine refused" + ); + watched.layer_reported_nothing(LEG); + return; + }; + let runs = Arc::new(AtomicUsize::new(0)); + let Some(destination) = over_host(&device, &host, &runs) else { + return; + }; + let queue = device.new_command_queue().unwrap(); + let source = device + .new_buffer(ROWS * SOURCE_PITCH, ResourceOptions::private()) + .unwrap(); + let delay = device + .new_buffer(super::blit_holds::FILLED, ResourceOptions::private()) + .unwrap(); + // Refusals, which leave the command buffer as it was. + let refused = copies.command_buffer().unwrap(); + assert_eq!( + problem(refused.compute_command_encoder()), + Problem::CopyQueue(CopyQueueProblem::Encoder) + ); + let mut blit = refused.blit_command_encoder().unwrap(); + assert_eq!( + problem(blit.synchronize_resource(ResourceRef::Buffer(&source))), + Problem::CopyQueue(CopyQueueProblem::Command) + ); + blit.end_encoding().unwrap(); + drop(refused); + // The source filled on another queue, behind 1 GiB of fills; the copies committed right after + // it, with no wait. + let before = device.work_counts(); + let filling = busy(&queue, &delay); + let fill = queue.command_buffer().unwrap(); + let mut blit = fill.blit_command_encoder().unwrap(); + blit.fill_buffer(&source, 0..ROWS * SOURCE_PITCH, FILLED) + .unwrap(); + blit.end_encoding().unwrap(); + fill.commit().unwrap(); + let copying = copies.command_buffer().unwrap(); + let mut blit = copying.blit_command_encoder().unwrap(); + for (from, to) in rows() { + blit.copy_from_buffer_to_buffer(&source, from, &destination, to, ROW) + .unwrap(); + } + blit.end_encoding().unwrap(); + copying.add_completion_sync_file().unwrap(); + let committed = Instant::now(); + copying.commit().unwrap(); + let file = match copying.export_completion_sync_file() { + Ok(file) => Some(file), + Err(Error::Invalid(Invalid { + problem: Problem::NotExportable, + .. + })) => { + eprintln!("{LEG} on {name}: the device exports no sync file"); + None + } + Err(error) => panic!("{LEG} on {name}: export_completion_sync_file: {error:?}"), + }; + assert!( + copying.wait_until_completed_for(WAIT).is_ok(), + "{LEG}: the copies" + ); + assert_eq!(copying.status(), CommandBufferStatus::Completed); + let waited = committed.elapsed(); + assert!( + filling.wait_until_completed_for(WAIT).is_ok(), + "{LEG}: the fills" + ); + assert!( + fill.wait_until_completed_for(WAIT).is_ok(), + "{LEG}: the fill" + ); + let after = device.work_counts(); + let signalled = match &file { + Some(Some(file)) => super::sync_file::signaled(file), + // `None`: it ended before the export looked, a sync file already signalled. + Some(None) | None => true, + }; + assert!(signalled, "{LEG} on {name}: the sync file is not signalled"); + // Every row the fill's bytes, every other byte as the CPU left it: the command buffers that + // used the pages completed. + let bytes: &[u8] = bytemuck_bytes(host.words()); + let wrong: Vec = (0..bytes.len() as u64) + .filter(|&at| { + let want = match copied(at) { + true => FILLED, + false => BEFORE.to_ne_bytes()[(at % 4) as usize], + }; + bytes[at as usize] != want + }) + .take(8) + .collect(); + assert!( + wrong.is_empty(), + "{LEG} on {name}: bytes {wrong:?} of the destination are wrong" + ); + let batches = after.copy_queue_batches - before.copy_queue_batches; + let merged = after.buffer_copies_merged - before.buffer_copies_merged; + eprintln!( + "{LEG} on {name}: {batches} batch(es) on the copy engine's VkQueue, {merged} of {ROWS} \ + copies merged, completed {:.2} ms after the commit", + waited.as_secs_f64() * 1e3 + ); + assert!( + batches >= 1, + "{LEG} on {name}: no batch ran on the copy queue's VkQueue" + ); + assert_eq!(merged, ROWS - 1, "{LEG} on {name}: the row copies merged"); + drop(destination); + watched.layer_reported_nothing(LEG); +} + +/// The runs' leg, on any queue (the module docs). +#[test] +fn row_copies_between_two_buffers_are_one_copy_command() { + const LEG: &str = "COPY-RUNS"; + let watched = Watched::default(); + let scratch = Scratch::new("copy-runs"); + let device = super::pending_rebind::device(&watched, &scratch.0); + let name = device.name().to_owned(); + let queue = device.new_command_queue().unwrap(); + let length = ROWS * SOURCE_PITCH; + let shared = ResourceOptions::default(); + let [source, destination, third] = [(); 3].map(|_| device.new_buffer(length, shared).unwrap()); + // The source's bytes: each byte its offset's low byte. + write(&source, |at| at as u8); + write(&destination, |_| 0xee); + write(&third, |_| 0x11); + let merged = |run: &dyn Fn(&mut crate::BlitCommandEncoder)| -> u64 { + let before = device.work_counts().buffer_copies_merged; + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + run(&mut blit); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert!( + command_buffer.wait_until_completed_for(WAIT).is_ok(), + "{LEG}" + ); + device.work_counts().buffer_copies_merged - before + }; + // The rows in rising offsets: one command. + let rows_merged = merged(&|blit| { + for (from, to) in rows() { + blit.copy_from_buffer_to_buffer(&source, from, &destination, to, ROW) + .unwrap(); + } + }); + assert_eq!(rows_merged, ROWS - 1, "{LEG} on {name}: the rows"); + let held = read(&destination); + for at in 0..length { + let want = match copied(at) { + true => { + let (row, within) = (at / DESTINATION_PITCH, at % DESTINATION_PITCH); + (row * SOURCE_PITCH + SOURCE_AT + within - DESTINATION_AT) as u8 + } + false => 0xee, + }; + assert_eq!(held[at as usize], want, "{LEG} on {name}: byte {at}"); + } + // A copy of what the copy before wrote, two copies into one range, and a copy between other + // buffers between two of the pair's: none merges, and the later writes win. + let none = merged(&|blit| { + blit.copy_from_buffer_to_buffer(&source, 0, &destination, 0, 64) + .unwrap(); + blit.copy_from_buffer_to_buffer(&destination, 0, &third, 0, 64) + .unwrap(); + blit.copy_from_buffer_to_buffer(&source, 100, &third, 0, 64) + .unwrap(); + blit.copy_from_buffer_to_buffer(&source, 200, &third, 0, 64) + .unwrap(); + blit.copy_from_buffer_to_buffer(&third, 0, &destination, 1000, 32) + .unwrap(); + blit.copy_from_buffer_to_buffer(&source, 300, &third, 500, 64) + .unwrap(); + }); + assert_eq!(none, 0, "{LEG} on {name}: copies that meet merged"); + let third_held = read(&third); + let destination_held = read(&destination); + for at in 0..64u64 { + assert_eq!( + third_held[at as usize], + (200 + at) as u8, + "{LEG}: the later write" + ); + } + for at in 0..32u64 { + assert_eq!( + destination_held[1000 + at as usize], + (200 + at) as u8, + "{LEG}: in order" + ); + } + for at in 0..64u64 { + assert_eq!( + third_held[500 + at as usize], + (300 + at) as u8, + "{LEG}: the last" + ); + } + eprintln!("{LEG} on {name}: {rows_merged} of {ROWS} row copies merged; {none} of the rest"); + watched.layer_reported_nothing(LEG); +} + +/// The bytes of `words`. +fn bytemuck_bytes(words: &[u32]) -> &[u8] { + // SAFETY: the words' own bytes, as many as they hold, which outlive the slice. + unsafe { std::slice::from_raw_parts(words.as_ptr().cast(), std::mem::size_of_val(words)) } +} + +/// Set each byte of `buffer`, a `Shared` one no command uses now, to `byte(at)`. +fn write(buffer: &crate::Buffer, byte: impl Fn(u64) -> u8) { + let contents = buffer.contents().unwrap(); + for at in 0..buffer.length() { + // SAFETY: within the buffer's mapping, which no command uses now. + unsafe { contents.as_ptr().add(at as usize).write(byte(at)) }; + } +} + +/// The bytes of `buffer`, a `Shared` one no command uses now. +fn read(buffer: &crate::Buffer) -> Vec { + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's mapping, which no command uses now. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }.to_vec() +} diff --git a/crates/metal2vulkan-runtime/src/tests/device.rs b/crates/metal2vulkan-runtime/src/tests/device.rs index d3c98bdd2..60c23e4df 100644 --- a/crates/metal2vulkan-runtime/src/tests/device.rs +++ b/crates/metal2vulkan-runtime/src/tests/device.rs @@ -143,7 +143,9 @@ use crate::device::create::{ pageable_device_local_memory, queue_plan, setting_values, timeline_difference, QueuePlan, LAYERS_DROPPED, }; -use crate::device::create::{extra_queue_places, extra_queues_absent, reserved_queues_absent}; +use crate::device::create::{ + extra_queue_places, extra_queues_absent, reserved_queues_absent, vk_queues, +}; use crate::enables::host_image_copy_names; use crate::{DeviceOptions, Error, InstanceApiVersion, LayerSetting, LayerSettingValue}; use ash::vk; @@ -521,6 +523,8 @@ fn equivalent_queue_families_are_all_taken_in_turn() { reserved: Vec::new(), staging, fill, + // A copy engine of two queues: the copy queue shares the fill queue's. + copies: fill, }) }; let plan = |primary, queues: &[(u32, u32)], present: &[(u32, u32)]| { @@ -727,10 +731,11 @@ fn extra_queues_take_a_free_queue_else_one_the_device_gives_up() { plan, QueuePlan { fill: None, + copies: None, ..before }, "every one was free: the device keeps all its own but the fill queue, the copy engine's \ - second queue, which the transfer queue took" + second queue, which the transfer queue took, and the copy queue with it" ); // MoltenVK's shape: four families of one queue each, every one the device's own. The round // robin gives up its last queues, never its first. @@ -842,6 +847,7 @@ fn reserved_queues_leave_the_round_robin_after_presenting() { reserved: of(0, 15..16), staging: Some((1, 0)), fill: Some((1, 1)), + copies: Some((1, 1)), } ); // As many as the family spares: the round robin keeps four, presenting two, so ten. @@ -908,6 +914,93 @@ fn reserved_queues_leave_the_round_robin_after_presenting() { assert_eq!(reserved_queues_absent(0, 0, "a GPU"), None); } +/// The copy queue (`Device::new_command_queue_for_copies`): a copy engine's (the staging queue's +/// family of transfers alone) third queue, a `VkQueue` the device takes besides; else its second, +/// the fill queue's, which the two share, so the device takes no more; none on a copy engine of +/// one queue, one whose timestamps' valid bits differ from the primary family's, a device with no +/// copy engine (RADV's, lavapipe's, MoltenVK's), or where an extra queue takes its place or the +/// staging queue's. +#[test] +fn the_copy_queue_takes_a_copy_engine_s_third_queue_else_the_fill_queue_s() { + let all = vk::QueueFlags::GRAPHICS + | vk::QueueFlags::COMPUTE + | vk::QueueFlags::TRANSFER + | vk::QueueFlags::SPARSE_BINDING; + let family = |flags: vk::QueueFlags, count: u32| vk::QueueFamilyProperties { + queue_flags: flags, + queue_count: count, + timestamp_valid_bits: 64, + min_image_transfer_granularity: vk::Extent3D { + width: 1, + height: 1, + depth: 1, + }, + }; + let copy = |count| { + family( + vk::QueueFlags::TRANSFER | vk::QueueFlags::SPARSE_BINDING, + count, + ) + }; + // NVIDIA's: a copy engine of two, both the runtime's already. + let nvidia = [ + family(all, 16), + copy(2), + family(all & !vk::QueueFlags::GRAPHICS, 8), + ]; + let plan = queue_plan(&nvidia, 0, true).unwrap(); + assert_eq!( + (plan.staging, plan.fill, plan.copies), + (Some((1, 0)), Some((1, 1)), Some((1, 1))) + ); + assert_eq!(plan.copy_queue_apart(), None); + assert_eq!(vk_queues(&(plan.clone(), Vec::new())), 14 + 2 + 2); + // A copy engine of three: its third queue, one more `VkQueue`. + let three = [family(all, 16), copy(3)]; + let plan = queue_plan(&three, 0, true).unwrap(); + assert_eq!((plan.fill, plan.copies), (Some((1, 1)), Some((1, 2)))); + assert_eq!(plan.copy_queue_apart(), Some((1, 2))); + assert_eq!(vk_queues(&(plan, Vec::new())), 14 + 2 + 3); + // None: one queue, the staging queue's; other timestamps; no copy engine. + let one = queue_plan(&[family(all, 16), copy(1)], 0, true).unwrap(); + assert_eq!((one.staging, one.copies), (Some((1, 0)), None)); + let mut coarse = copy(2); + coarse.timestamp_valid_bits = 36; + let plan = queue_plan(&[family(all, 16), coarse], 0, true).unwrap(); + assert_eq!((plan.fill, plan.copies), (Some((1, 1)), None)); + let radv = [family(all, 1), family(all & !vk::QueueFlags::GRAPHICS, 4)]; + assert_eq!(queue_plan(&radv, 0, false).unwrap().copies, None); + assert_eq!(queue_plan(&[family(all, 1)], 0, true).unwrap().copies, None); + assert_eq!( + queue_plan(&[family(all, 1); 4], 0, true).unwrap().copies, + None + ); + // An extra queue of transfers takes the fill queue's, and the copy queue goes with it where it + // shared it; on a copy engine of three, the copy queue keeps its own. + let transfer = [vk::QueueFlags::TRANSFER]; + let mut plan = queue_plan(&nvidia, 0, true).unwrap(); + assert_eq!( + extra_queue_places(&nvidia, &mut plan, &transfer), + [Some((1, 1))] + ); + assert_eq!((plan.fill, plan.copies), (None, None)); + let mut plan = queue_plan(&three, 0, true).unwrap(); + assert_eq!( + extra_queue_places(&three, &mut plan, &transfer), + [Some((1, 1))] + ); + assert_eq!((plan.fill, plan.copies), (None, Some((1, 2)))); + // Two take the copy queue's too, and a third the staging queue's: the copy queue goes. + let mut plan = queue_plan(&three, 0, true).unwrap(); + let places = extra_queue_places(&three, &mut plan, &[vk::QueueFlags::TRANSFER; 2]); + assert_eq!(places, [Some((1, 1)), Some((1, 2))]); + assert_eq!(plan.copies, None); + let mut plan = queue_plan(&[family(all, 1), copy(3)], 0, true).unwrap(); + let places = extra_queue_places(&[family(all, 1), copy(3)], &mut plan, &[transfer[0]; 4]); + assert_eq!(places, [Some((1, 1)), Some((1, 2)), Some((1, 0)), None]); + assert_eq!((plan.staging, plan.copies), (None, None)); +} + /// The runtime enables `hostImageCopy` itself wherever the device lists the extensions its /// version needs (at the runtime's Vulkan 1.2 instance, `VK_EXT_host_image_copy`, /// `VK_KHR_copy_commands2` and `VK_KHR_format_feature_flags2`) and has the feature: a `Shared` diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index de81e99cb..d8950e1fe 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -116,6 +116,8 @@ mod copies_only_reads; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod copy_bounds; mod copy_plan; +#[cfg(all(unix, any(m2v_gpu, m2v_cpu_icd)))] +mod copy_queue; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod core_image_libraries; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan-runtime/src/tests/sync_file.rs b/crates/metal2vulkan-runtime/src/tests/sync_file.rs index 340c5e5d2..bca03f3ed 100644 --- a/crates/metal2vulkan-runtime/src/tests/sync_file.rs +++ b/crates/metal2vulkan-runtime/src/tests/sync_file.rs @@ -324,7 +324,7 @@ impl Drop for Second { } /// Whether `file` is signaled now (`poll(2)` of a sync file). -fn signaled(file: &OwnedFd) -> bool { +pub(super) fn signaled(file: &OwnedFd) -> bool { let mut poll = libc::pollfd { fd: file.as_raw_fd(), events: libc::POLLIN, diff --git a/crates/metal2vulkan-runtime/src/texture/first_move.rs b/crates/metal2vulkan-runtime/src/texture/first_move.rs index 5adc577cf..6e169f8bc 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -1566,6 +1566,18 @@ impl FirstMoves { self.take_with(named, fills, hold, (|_| true, overwrites)) } + /// As [`take`](Self::take), for a batch of a queue made for copies + /// (`Device::new_command_queue_for_copies`), whose commands name every buffer they reach and + /// no image, on a queue family of transfers alone: the fills `fills` says, and nothing else. + /// The moves and the staged copies wait, in their order, for the device's next submission + /// elsewhere: that family records no clear or pass a move may need, and the device's images + /// are shared only among its own families (`sharing.rs`). It binds no heap set, so it holds + /// no texture slot's writes. + pub(crate) fn take_fills_alone(&self, fills: FillTake<'_>) -> Taken<'_> { + let wanted = |entry: &Waiting| matches!(entry, Waiting::Fill(..)); + self.take_with(|_| true, fills, || None, (wanted, |_| false)) + } + /// The submissions' order, for a submission: taken, and the wait counted where another /// submission holds it ([`FirstMoves::submissions_waited`]). Nothing is read from the host's /// clock where the order is free. diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs index 3546d4862..1eecb5254 100644 --- a/crates/metal2vulkan-runtime/src/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tracker.rs @@ -607,10 +607,29 @@ impl Barrier { /// `command_buffer` is a command buffer of `device` in the recording state, and no other /// thread records it. pub(super) unsafe fn record(self, device: &Vk, command_buffer: vk::CommandBuffer) { + // SAFETY: the caller's contract. + unsafe { self.record_reading(device, command_buffer, device.reads()) }; + } + + /// [`record`](Self::record) on a command buffer of a queue family whose reads `reads` names + /// (`DeviceShared::memory_reads_of`): the copy queue's, a family of transfers alone, where an + /// access mask may name only the accesses its stages make + /// (`VUID-vkCmdPipelineBarrier-dstAccessMask-02816`), which `ALL_COMMANDS` there limits to + /// transfers. + /// + /// # Safety + /// + /// As [`record`](Self::record)'s, `command_buffer` of a pool of `reads`' family. + pub(super) unsafe fn record_reading( + self, + device: &Vk, + command_buffer: vk::CommandBuffer, + reads: crate::image_barrier::MemoryReads, + ) { let masks = self.legacy(); let barrier = vk::MemoryBarrier::default() .src_access_mask(masks.src_access) - .dst_access_mask(device.reads().named(masks.dst_access, masks.dst_stages)); + .dst_access_mask(reads.named(masks.dst_access, masks.dst_stages)); // SAFETY: the caller's contract. unsafe { device.cmd_pipeline_barrier( diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 66c6bc8ac..6b88f4d9f 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -197,6 +197,7 @@ pub(crate) struct Counters { heap_texture_block_compressed_layouts: AtomicU64, heap_texture_untiled_layouts: AtomicU64, fills_recorded: AtomicU64, + buffer_copies_merged: AtomicU64, ycbcr_refreshes: AtomicU64, ycbcr_whole_conversions: AtomicU64, ycbcr_textures_in_place: AtomicU64, @@ -413,6 +414,7 @@ pub(crate) struct Counters { texel_shadow_reads: AtomicU64, texel_shadows_dropped: AtomicU64, staging_submissions: AtomicU64, + copy_queue_batches: AtomicU64, staging_copies_queued: AtomicU64, staging_moves_queued: AtomicU64, staging_flushes: AtomicU64, @@ -2349,6 +2351,13 @@ impl Counters { self.fills_recorded.fetch_add(1, Ordering::Relaxed); } + /// `merged` buffer copies of a blit encoder were recorded as regions of the + /// `vkCmdCopyBuffer` of the copy before them (`copy_run.rs`). + pub(crate) fn buffer_copies_merged(&self, merged: u64) { + self.buffer_copies_merged + .fetch_add(merged, Ordering::Relaxed); + } + /// A YCbCr texture's conversion was recorded through its refresh, converting only where its /// planes changed (`ycbcr.rs`). pub(crate) fn ycbcr_refreshed(&self) { @@ -4030,6 +4039,12 @@ impl Counters { self.staging_submissions.fetch_add(1, Ordering::Relaxed); } + /// A batch was submitted to the copy queue's `VkQueue`, of a family of transfers alone + /// (`Device::new_command_queue_for_copies`). + pub(crate) fn copy_queue_batch(&self) { + self.copy_queue_batches.fetch_add(1, Ordering::Relaxed); + } + /// A host call's copy was queued for the staging queue's next submission /// (`texture/staging_copy.rs`). pub(crate) fn staging_copy_queued(&self) { @@ -7126,6 +7141,10 @@ pub struct WorkCounts { /// Fills recorded as `vkCmdFillBuffer` (`word_fill.rs`): every fill the encoders and the /// runtime's own work record, but a new buffer's first zeros (`new_buffer_zero_fills`). pub fills_recorded: u64, + /// Buffer copies of a blit encoder recorded as one more region of the `vkCmdCopyBuffer` of the + /// copy before them (`copy_run.rs`): consecutive `copy_from_buffer_to_buffer` calls between the + /// same two `VkBuffer`s that the encoder's order needs no barrier between, on any queue. + pub buffer_copies_merged: u64, /// Two-plane YCbCr textures' conversions recorded through their refresh (`ycbcr.rs`): a /// comparison of the planes' words with the copy the last conversion read, and the conversion /// dispatched through indirect arguments that run no workgroup where no word changed. @@ -8472,6 +8491,10 @@ pub struct WorkCounts { /// first moves and copies queued for it (`staging_moves_queued`, `staging_copies_queued`), on /// a device that copies none on the host from memory the host caches. pub staging_submissions: u64, + /// Batches submitted to the copy queue's `VkQueue`, of a queue family of transfers alone: the + /// command buffers of the queues made for copies + /// ([`Device::new_command_queue_for_copies`](crate::Device::new_command_queue_for_copies)). + pub copy_queue_batches: u64, /// `replace_region` copies (and decoded twins' copies) queued for the staging queue's next /// submission rather than submitted each alone (`texture/staging_copy.rs`). pub staging_copies_queued: u64, @@ -11541,6 +11564,7 @@ impl Device { .heap_texture_untiled_layouts .load(Ordering::Relaxed), fills_recorded: counters.fills_recorded.load(Ordering::Relaxed), + buffer_copies_merged: counters.buffer_copies_merged.load(Ordering::Relaxed), ycbcr_refreshes: counters.ycbcr_refreshes.load(Ordering::Relaxed), ycbcr_whole_conversions: counters.ycbcr_whole_conversions.load(Ordering::Relaxed), ycbcr_textures_in_place: counters.ycbcr_textures_in_place.load(Ordering::Relaxed), @@ -11947,6 +11971,7 @@ impl Device { texel_shadow_reads: counters.texel_shadow_reads.load(Ordering::Relaxed), texel_shadows_dropped: counters.texel_shadows_dropped.load(Ordering::Relaxed), staging_submissions: counters.staging_submissions.load(Ordering::Relaxed), + copy_queue_batches: counters.copy_queue_batches.load(Ordering::Relaxed), staging_copies_queued: counters.staging_copies_queued.load(Ordering::Relaxed), staging_moves_queued: counters.staging_moves_queued.load(Ordering::Relaxed), staging_flushes: counters.staging_flushes.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-runtime/src/wrapped_buffer.rs b/crates/metal2vulkan-runtime/src/wrapped_buffer.rs index aa646ea57..2144af514 100644 --- a/crates/metal2vulkan-runtime/src/wrapped_buffer.rs +++ b/crates/metal2vulkan-runtime/src/wrapped_buffer.rs @@ -297,6 +297,11 @@ impl Device { if self.is_lost() { return Err(self.lost_refusal()); } + // Whether the copy queue may use it: concurrent with the copy engine's family + // (`Device::new_command_queue_for_copies`). + let copy_family = (shared.copy_slot()).map(|slot| shared.queue_family_of(slot)); + let copy_engine = (created.families.zip(copy_family)) + .is_some_and(|(families, family)| families.contains(&family)); let placement = Placement::caller( memory.memory, memory.offset, @@ -316,7 +321,7 @@ impl Device { modes, address, reserved, - owner: Owner::Vulkan, + owner: Owner::Vulkan { copy_engine }, release: None, of_heap: false, drops_writes: false, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 326c3afbf..e83fa99d4 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2343; +pub const RUNTIME_VERSION: u32 = 2344; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index cb4c9392a..570036f30 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1329,6 +1329,7 @@ enum metal2vulkan-runtime::BufferTextureProblem #[derive(Clone, Copy, Debug, Par enum metal2vulkan-runtime::CommandBufferError #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum CommandBufferError enum metal2vulkan-runtime::CommandBufferStatus #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum CommandBufferStatus enum metal2vulkan-runtime::CopyProblem #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum CopyProblem +enum metal2vulkan-runtime::CopyQueueProblem #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum CopyQueueProblem enum metal2vulkan-runtime::CpuCacheMode #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum CpuCacheMode enum metal2vulkan-runtime::DeadlockCause #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DeadlockCause enum metal2vulkan-runtime::DegradationCategory #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DegradationCategory @@ -2743,6 +2744,7 @@ field metal2vulkan-runtime::WorkCounts.bounded_run_draws pub bounded_run_draws: field metal2vulkan-runtime::WorkCounts.bounded_shadow_copies pub bounded_shadow_copies: u64 field metal2vulkan-runtime::WorkCounts.buffer_blocks_made_ahead pub buffer_blocks_made_ahead: u64 field metal2vulkan-runtime::WorkCounts.buffer_blocks_made_in_place pub buffer_blocks_made_in_place: u64 +field metal2vulkan-runtime::WorkCounts.buffer_copies_merged pub buffer_copies_merged: u64 field metal2vulkan-runtime::WorkCounts.calibration_deviation_most pub calibration_deviation_most: u64 field metal2vulkan-runtime::WorkCounts.calibration_disagreements pub calibration_disagreements: u64 field metal2vulkan-runtime::WorkCounts.calibration_readings pub calibration_readings: u64 @@ -2837,6 +2839,7 @@ field metal2vulkan-runtime::WorkCounts.copied_unnamed_reach_copy_ins pub copied_ field metal2vulkan-runtime::WorkCounts.copied_unnamed_reach_twin_bytes_compared pub copied_unnamed_reach_twin_bytes_compared: u64 field metal2vulkan-runtime::WorkCounts.copied_unnamed_reach_twin_copy_ins pub copied_unnamed_reach_twin_copy_ins: u64 field metal2vulkan-runtime::WorkCounts.copied_unwritable_pages pub copied_unwritable_pages: u64 +field metal2vulkan-runtime::WorkCounts.copy_queue_batches pub copy_queue_batches: u64 field metal2vulkan-runtime::WorkCounts.copy_regions_split pub copy_regions_split: u64 field metal2vulkan-runtime::WorkCounts.copy_sites pub copy_sites: [CopySite; 32] field metal2vulkan-runtime::WorkCounts.coverage_pools_made pub coverage_pools_made: u64 @@ -8706,6 +8709,7 @@ method metal2vulkan-runtime::Device::new_buffer_with_bytes_no_copy pub unsafe fn method metal2vulkan-runtime::Device::new_buffer_with_descriptor pub fn new_buffer_with_descriptor(&self, descriptor: BufferDescriptor<'_>) -> Result method metal2vulkan-runtime::Device::new_buffer_with_vk_buffer pub unsafe fn new_buffer_with_vk_buffer(&self, buffer: vk::Buffer, info: &vk::BufferCreateInfo<'_>, memory: VkBufferMemory, length: u64, options: ResourceOptions) -> Result method metal2vulkan-runtime::Device::new_command_queue pub fn new_command_queue(&self) -> Result +method metal2vulkan-runtime::Device::new_command_queue_for_copies pub fn new_command_queue_for_copies(&self) -> Result, Error> method metal2vulkan-runtime::Device::new_command_queue_for_presenting pub fn new_command_queue_for_presenting(&self) -> Result method metal2vulkan-runtime::Device::new_command_queue_unshared pub fn new_command_queue_unshared(&self, count: usize) -> Result method metal2vulkan-runtime::Device::new_command_queue_with_max_command_buffer_count pub fn new_command_queue_with_max_command_buffer_count(&self, count: usize) -> Result @@ -8888,9 +8892,9 @@ method metal2vulkan-runtime::HostMemory::with_import_gate pub fn with_import_gat method metal2vulkan-runtime::HostMemory::with_runs pub fn with_runs(self, resolver: RunResolver) -> HostMemory method metal2vulkan-runtime::HostRam::new pub unsafe fn new(ranges: &[(NonNull, u64)], keep_alive: Option) -> Result method metal2vulkan-runtime::HostRam::with_dirty_pages pub fn with_dirty_pages(mut self, source: Arc) -> HostRam where D: DirtyPages + ?Sized + 'static, D::Watch: 'static, -method metal2vulkan-runtime::HostRam::with_dma_buf pub fn with_dma_buf(mut self, source: DmaBufSource) -> HostRam -method metal2vulkan-runtime::HostRam::with_dma_buf_of_runs pub fn with_dma_buf_of_runs(mut self, source: DmaBufRunsSource, most_runs: usize) -> HostRam -method metal2vulkan-runtime::HostRam::with_largest_dma_buf pub fn with_largest_dma_buf(mut self, bytes: u64) -> HostRam +method metal2vulkan-runtime::HostRam::with_dma_buf #[cfg(unix)] pub fn with_dma_buf(mut self, source: DmaBufSource) -> HostRam +method metal2vulkan-runtime::HostRam::with_dma_buf_of_runs #[cfg(unix)] pub fn with_dma_buf_of_runs(mut self, source: DmaBufRunsSource, most_runs: usize) -> HostRam +method metal2vulkan-runtime::HostRam::with_largest_dma_buf #[cfg(unix)] pub fn with_largest_dma_buf(mut self, bytes: u64) -> HostRam method metal2vulkan-runtime::IndirectBufferBinding::new pub fn new(address: GpuAddress, attribute_stride: Option) -> IndirectBufferBinding method metal2vulkan-runtime::IndirectCommandBuffer::allocated_size pub fn allocated_size(&self) -> u64 method metal2vulkan-runtime::IndirectCommandBuffer::as_resource pub fn as_resource(&self) -> ResourceRef<'_> @@ -10435,8 +10439,8 @@ struct metal2vulkan-runtime::DeviceOptions #[derive(Clone)] #[non_exhaustive] pu struct metal2vulkan-runtime::DeviceProperties #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DeviceProperties struct metal2vulkan-runtime::DeviceRefused #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DeviceRefused struct metal2vulkan-runtime::DirtyStamp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DirtyStamp(pub u64) -struct metal2vulkan-runtime::DmaBufChunk #[derive(Clone, Debug)] pub struct DmaBufChunk -struct metal2vulkan-runtime::DmaBufRequest #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DmaBufRequest +struct metal2vulkan-runtime::DmaBufChunk #[cfg(unix)] #[derive(Clone, Debug)] pub struct DmaBufChunk +struct metal2vulkan-runtime::DmaBufRequest #[cfg(unix)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DmaBufRequest struct metal2vulkan-runtime::DynamicLibrary #[derive(Clone, Debug)] pub struct DynamicLibrary(Arc) struct metal2vulkan-runtime::EncodedComputeCommand #[derive(Clone, Debug)] #[non_exhaustive] pub struct EncodedComputeCommand struct metal2vulkan-runtime::EncodedRenderCommand #[derive(Clone, Debug)] #[non_exhaustive] pub struct EncodedRenderCommand @@ -10966,8 +10970,8 @@ trait-impl metal2vulkan-runtime::DeviceHandles impl std::fmt::Debug impl std::fm trait-impl metal2vulkan-runtime::DeviceOptions impl Default impl Default for DeviceOptions trait-impl metal2vulkan-runtime::DeviceOptions impl std::fmt::Debug impl std::fmt::Debug for DeviceOptions trait-impl metal2vulkan-runtime::DeviceRefused impl fmt::Display impl fmt::Display for DeviceRefused -trait-impl metal2vulkan-runtime::DmaBufRequest impl fe impl Send unsafe impl Send for DmaBufRequest -trait-impl metal2vulkan-runtime::DmaBufRequest impl fe impl Sync unsafe impl Sync for DmaBufRequest +trait-impl metal2vulkan-runtime::DmaBufRequest impl fe impl Send #[cfg(unix)] unsafe impl Send for DmaBufRequest +trait-impl metal2vulkan-runtime::DmaBufRequest impl fe impl Sync #[cfg(unix)] unsafe impl Sync for DmaBufRequest trait-impl metal2vulkan-runtime::DrawPrimitiveType impl From impl From for DrawPrimitiveType trait-impl metal2vulkan-runtime::DriverSetting impl fmt::Display impl fmt::Display for DriverSetting trait-impl metal2vulkan-runtime::DynamicLibraryError impl fmt::Display impl fmt::Display for DynamicLibraryError @@ -11155,8 +11159,8 @@ trait-item metal2vulkan::cache::PipelineArtifact::to_bytes fn to_bytes(&self) -> trait-item metal2vulkan::cache::PipelineArtifact::write_to fn write_to(&self, out: &mut dyn std::io::Write) -> std::io::Result<()> type metal2vulkan-air::container::Hash256 pub type Hash256 = [u8; 32] type metal2vulkan-runtime::Deallocator pub type Deallocator = Box, u64) + Send + 'static> -type metal2vulkan-runtime::DmaBufRunsSource pub type DmaBufRunsSource = Arc std::io::Result + Send + Sync + 'static> -type metal2vulkan-runtime::DmaBufSource pub type DmaBufSource = Arc std::io::Result> + Send + Sync + 'static> +type metal2vulkan-runtime::DmaBufRunsSource #[cfg(unix)] pub type DmaBufRunsSource = Arc std::io::Result + Send + Sync + 'static> +type metal2vulkan-runtime::DmaBufSource #[cfg(unix)] pub type DmaBufSource = Arc std::io::Result> + Send + Sync + 'static> type metal2vulkan-runtime::ExecutedCommandsHandler pub type ExecutedCommandsHandler = Arc type metal2vulkan-runtime::Handler pub type Handler = Box type metal2vulkan-runtime::ImportGate pub type ImportGate = Arc bool + Send + Sync + 'static> @@ -12327,6 +12331,9 @@ variant metal2vulkan-runtime::CopyProblem::Offset Offset variant metal2vulkan-runtime::CopyProblem::Region Region variant metal2vulkan-runtime::CopyProblem::SampleCount SampleCount variant metal2vulkan-runtime::CopyProblem::Size Size +variant metal2vulkan-runtime::CopyQueueProblem::Buffer Buffer +variant metal2vulkan-runtime::CopyQueueProblem::Command Command +variant metal2vulkan-runtime::CopyQueueProblem::Encoder Encoder variant metal2vulkan-runtime::CpuCacheMode::DefaultCache DefaultCache variant metal2vulkan-runtime::CpuCacheMode::WriteCombined WriteCombined variant metal2vulkan-runtime::DeadlockCause::CompletionSeenHandler CompletionSeenHandler @@ -12974,6 +12981,7 @@ variant metal2vulkan-runtime::Problem::BufferLength BufferLength { length: u64 } variant metal2vulkan-runtime::Problem::BufferTexture BufferTexture(BufferTextureProblem) variant metal2vulkan-runtime::Problem::CompiledKernel CompiledKernel variant metal2vulkan-runtime::Problem::Copy Copy(CopyProblem) +variant metal2vulkan-runtime::Problem::CopyQueue CopyQueue(CopyQueueProblem) variant metal2vulkan-runtime::Problem::DepthWrittenWithoutAttachment DepthWrittenWithoutAttachment variant metal2vulkan-runtime::Problem::DmaBuf DmaBuf variant metal2vulkan-runtime::Problem::Draw Draw(DrawProblem) diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 0b8866285..d17a11b99 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -34,8 +34,8 @@ Columns: | Translation caps | 14 | 14 | 0 | 0 | 7 | 7 | 0 | | Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 | | The translation deadline | 1 | 1 | 0 | 0 | 0 | 1 | 0 | -| What a call did wrong | 72 | 72 | 0 | 0 | 0 | 0 | 0 | -| What a call did wrong, in detail | 171 | 154 | 0 | 0 | 0 | 0 | 0 | +| What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 | +| What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -48,8 +48,8 @@ Columns: | Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 | | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | | The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | -| What a call did wrong | 22 | 3 | 5 | 0 | 17 | 8 | 17 | 0 | -| What a call did wrong, in detail | 60 | 26 | 23 | 0 | 36 | 26 | 0 | 0 | +| What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 | +| What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -348,6 +348,7 @@ Columns: | `Semaphore` | A semaphore that cannot be one of the caller's binary semaphores | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal has no binary semaphores | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (binary_command)` | `-` | | `NotExportable` | The memory of a buffer, the semaphore of a shared event, or the completion of a command buffer, not made exportable as asked... | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal exports no buffer's memory, no event's semaphore and no command buffer's completion | 5: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (export_completion_sync_file)`, `crates/metal2vulkan-runtime/src/exported_memory.rs (export_memory, 2 sites)` (+2) | `-` | | `SyncFile` | A command buffer's completion sync file asked for at the wrong time (`CommandBuffer::export_completion_sync_file`) | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal exports no command buffer's completion | 5: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (add_completion_sync_file)`, `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (export_completion_sync_file, 4 sites)` | `-` | +| `CopyQueue` | A call on a command buffer of a queue made for copies (`Device::new_command_queue_for_copies`) that its copy engine's queue family does not run,... | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal has no queue of copies alone | 3: `crates/metal2vulkan-runtime/src/blit.rs (logged_after)`, `crates/metal2vulkan-runtime/src/blit.rs (refuse_unshared)` (+1) | `-` | | `NoPipelineState` | No pipeline state is set (plain Metal faults at a compute dispatch without one) | every device (a public call's own check of its arguments) | `unknown`: plain Metal is held to fault at a dispatch with no pipeline state, on no measurement recorded here | 8: `crates/metal2vulkan-runtime/src/compute.rs`, `crates/metal2vulkan-runtime/src/compute.rs (dispatch_indirect_resident)` (+6) | `-` | | `IndexOutOfRange` | An argument-table index past Metal's table (plain Metal writes past its own table | every device (a public call's own check of its arguments) | `metal-measured`: an M4: a compute texture at index 128 faulted the dispatch | 2: `crates/metal2vulkan-runtime/src/argument_table.rs (check_index)`, `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (problem)` | `-` | | `OffsetOutOfRange` | An offset past the end of the buffer | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max, macOS 27.0.1: setVertexBuffer at offset 512 of a buffer of 256 bytes returns, the encoder ends and the pass completes; Metal's API validation alone refuses it | 5: `crates/metal2vulkan-runtime/src/argument_encoder.rs (buffer_word)`, `crates/metal2vulkan-runtime/src/argument_table.rs (check_bound_buffer)` (+3) | `-` | @@ -432,6 +433,9 @@ Columns: | `SyncFileProblem::Committed` | Asked for after the commit (`CommandBuffer::add_completion_sync_file`) | every device (a public call's own check of its arguments) | `ours`: from `Problem::SyncFile` | 1: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (add_completion_sync_file)` | `-` | | `SyncFileProblem::NotCommitted` | The command buffer is not committed | every device (a public call's own check of its arguments) | `ours`: from `Problem::SyncFile` | 1: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (export_completion_sync_file)` | `-` | | `SyncFileProblem::Exported` | The sync file was exported already | every device (a public call's own check of its arguments) | `ours`: from `Problem::SyncFile` | 3: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (export_completion_sync_file, 3 sites)` | `-` | +| `CopyQueueProblem::Encoder` | An encoder but a blit encoder | every device (a public call's own check of its arguments) | `ours`: from `Problem::CopyQueue` | 3: `crates/metal2vulkan-runtime/src/encoder.rs (open)`, `crates/metal2vulkan-runtime/src/render.rs (render_command_encoder)` (+1) | `-` | +| `CopyQueueProblem::Command` | A blit command but `copy_from_buffer_to_buffer`, `fill_buffer` and the fence updates and waits | every device (a public call's own check of its arguments) | `ours`: from `Problem::CopyQueue` | 1: `crates/metal2vulkan-runtime/src/blit.rs (logged_after)` | `-` | +| `CopyQueueProblem::Buffer` | A buffer the caller made (`Device::new_buffer_with_vk_buffer`) that is not concurrent with the copy engine's family, whose contents that family... | every device (a public call's own check of its arguments) | `ours`: from `Problem::CopyQueue` | 1: `crates/metal2vulkan-runtime/src/blit.rs (refuse_unshared)` | `-` | | `TextureProblem::NotAFormat` | `Invalid`, or a format Metal describes none of ([`Device::pixel_format_info`](crate::Device::pixel_format_info) answers... | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: plain Metal's descriptor validation ends the process, "MTLTextureDescriptor has invalid pixelFormat (0)", the API validation layer off | 2: `crates/metal2vulkan-runtime/src/texture.rs (image_error)`, `crates/metal2vulkan-runtime/src/texture_descriptor.rs (check_made)` | `-` | | `TextureProblem::ZeroExtent` | A width, height or depth of 0 | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: plain Metal asserts "MTLTextureDescriptor has width of zero", and the same for a height of zero | 1: `crates/metal2vulkan-runtime/src/texture_descriptor.rs (check_made)` | `-` | | `TextureProblem::ExtentForType` | A height other than 1 for a 1D or buffer texture, or a depth other than 1 for a texture that is not 3D | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: plain Metal asserts "the texture type MTLTextureType1D requires that height is 1", and the same for a 2D texture of depth 2 | 1: `crates/metal2vulkan-runtime/src/texture_descriptor.rs (check_made)` | `-` | @@ -845,6 +849,7 @@ Each refusal's sites, with the function that builds it. - `invalid::Semaphore`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (binary_command)` - `invalid::NotExportable`: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (export_completion_sync_file)`; `crates/metal2vulkan-runtime/src/exported_memory.rs (export_memory, 2 sites)`; `crates/metal2vulkan-runtime/src/exported_memory.rs (external_write_done)`; `crates/metal2vulkan-runtime/src/exported_semaphore.rs (export_semaphore_fd)` - `invalid::SyncFile`: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (add_completion_sync_file)`; `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (export_completion_sync_file, 4 sites)` +- `invalid::CopyQueue`: `crates/metal2vulkan-runtime/src/blit.rs (logged_after)`; `crates/metal2vulkan-runtime/src/blit.rs (refuse_unshared)`; `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (refuse_for_copies)` - `invalid::NoPipelineState`: `crates/metal2vulkan-runtime/src/compute.rs`; `crates/metal2vulkan-runtime/src/compute.rs (dispatch_indirect_resident)`; `crates/metal2vulkan-runtime/src/compute.rs (dispatch_resident)`; `crates/metal2vulkan-runtime/src/compute.rs (inherited_pipeline)`; `crates/metal2vulkan-runtime/src/render.rs (drawn_by)`; `crates/metal2vulkan-runtime/src/render/executions.rs (inherited_pipeline)`; `crates/metal2vulkan-runtime/src/render/mesh.rs (mesh_draws_nothing)`; `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs (dispatch_tiles_resident)` - `invalid::IndexOutOfRange`: `crates/metal2vulkan-runtime/src/argument_table.rs (check_index)`; `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (problem)` - `invalid::OffsetOutOfRange`: `crates/metal2vulkan-runtime/src/argument_encoder.rs (buffer_word)`; `crates/metal2vulkan-runtime/src/argument_table.rs (check_bound_buffer)`; `crates/metal2vulkan-runtime/src/argument_table.rs (check_offsets)`; `crates/metal2vulkan-runtime/src/argument_table.rs (take_buffer_offset)`; `crates/metal2vulkan-runtime/src/render/table_facts.rs (set_buffer_offset)` @@ -912,6 +917,9 @@ Each refusal's sites, with the function that builds it. - `subproblem::SyncFileProblem::Committed`: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (add_completion_sync_file)` - `subproblem::SyncFileProblem::NotCommitted`: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (export_completion_sync_file)` - `subproblem::SyncFileProblem::Exported`: `crates/metal2vulkan-runtime/src/command_buffer/sync_file.rs (export_completion_sync_file, 3 sites)` +- `subproblem::CopyQueueProblem::Encoder`: `crates/metal2vulkan-runtime/src/encoder.rs (open)`; `crates/metal2vulkan-runtime/src/render.rs (render_command_encoder)`; `crates/metal2vulkan-runtime/src/sparse/encoder.rs (resource_state_command_encoder)` +- `subproblem::CopyQueueProblem::Command`: `crates/metal2vulkan-runtime/src/blit.rs (logged_after)` +- `subproblem::CopyQueueProblem::Buffer`: `crates/metal2vulkan-runtime/src/blit.rs (refuse_unshared)` - `subproblem::TextureProblem::NotAFormat`: `crates/metal2vulkan-runtime/src/texture.rs (image_error)`; `crates/metal2vulkan-runtime/src/texture_descriptor.rs (check_made)` - `subproblem::TextureProblem::ZeroExtent`: `crates/metal2vulkan-runtime/src/texture_descriptor.rs (check_made)` - `subproblem::TextureProblem::ExtentForType`: `crates/metal2vulkan-runtime/src/texture_descriptor.rs (check_made)`