diff --git a/crates/metal2vulkan-conformance/src/cost.rs b/crates/metal2vulkan-conformance/src/cost.rs index 73dcc5468..1b0695da9 100644 --- a/crates/metal2vulkan-conformance/src/cost.rs +++ b/crates/metal2vulkan-conformance/src/cost.rs @@ -822,7 +822,7 @@ const TRANSLATION: [&str; 20] = [ /// The name prefixes that put a count in [`Region::Submission`]: the commit path, our own other /// threads and the GPU. -const SUBMISSION: [&str; 52] = [ +const SUBMISSION: [&str; 54] = [ "commands_recorded.", "command_buffers_", "command_pools_made", @@ -834,6 +834,10 @@ const SUBMISSION: [&str; 52] = [ "submit_infos", "internal_submissions", "staging_submissions", + // The staging queue's submissions that carried the copies host calls queued, and the + // batches' GPU waits for them: work a burst of calls left to a later submission. + "staging_flushes", + "staging_gpu_waits", "grouped_submissions", "batches_", "group_ends_", diff --git a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs index 30e9d42d1..e35518314 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs @@ -1719,6 +1719,9 @@ impl Gpu for Runtime { ("images_started_on_the_host", c.images_started_on_the_host), ("host_texel_copies", c.host_texel_copies), ("staging_submissions", c.staging_submissions), + ("staging_copies_queued", c.staging_copies_queued), + ("staging_flushes", c.staging_flushes), + ("staging_gpu_waits", c.staging_gpu_waits), ("uncached_host_images", c.uncached_host_images), ("cpu_block_decodes", c.cpu_block_decodes), ("block_decode_passes", c.block_decode_passes), diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 4d3b162c8..3b09e747a 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -51,7 +51,10 @@ //! and the RTX 3090, about 2 ms of CPU in one `vkQueueSubmit` in about every thousand waits and //! signals) takes no such wait: each batch with work starts instead with a command buffer of //! barriers whose first is [`Barrier::after_completed`], which makes what completed batches -//! wrote visible to every later command, and the staging queue's copies signal no timeline. +//! wrote visible to every later command. Every batch, on every driver, waits for the staging +//! queue's last submission while the host has not seen it complete (`Device::staging_wait`): +//! one that carries the copies a burst of host calls queued is made just before the batch and +//! waited for on the GPU, not the host (`texture/staging_copy.rs`). //! Where every batch waited, about twice as many of its submissions took that long as where //! batches only signal. //! @@ -600,6 +603,12 @@ impl CommandBufferShared { // writes until its submission was made (`heap_sets::hold`). let firsts = &shared.textures.first_moves; let first_work = firsts.take_holding(|_| true, || crate::heap_sets::hold(device)); + // The copies queued for the staging queue, submitted there first, which the batch waits + // for on the GPU (below), holding what they copied until it completed + // (`texture/staging_copy.rs`). + let staged = device + .flush_staging() + .map_err(|error| recording_error(device, error))?; let entry = (!entries.is_empty()).then(|| Summary::outside_encoders(entry_uses)); let exit = (!exits.is_empty()).then(|| Summary::outside_encoders(exit_uses)); // The held depths' moves before each encoder that names one, into the layout it needs @@ -821,6 +830,14 @@ impl CommandBufferShared { wait_values.push(value); wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); } + // And the staging queue's last submission, on every `VkQueue`, until the host saw it + // complete: what it copied may be among what the work reads (`device/staging.rs`). + if let Some((timeline, value)) = device.staging_wait() { + wait_semaphores.push(timeline); + wait_values.push(value); + wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS); + shared.counts.staging_gpu_wait(); + } let mut order_semaphores: Vec = order_waits.iter().map(|&(s, _)| s).collect(); let mut order_values: Vec = order_waits.iter().map(|&(_, value)| value).collect(); @@ -975,6 +992,9 @@ impl CommandBufferShared { if let Some(ticket) = state.heaps.submit(device) { state.retained.push(Box::new(ticket)); } + if let Some(staged) = staged { + state.retained.push(Box::new(staged)); + } // The batch waits in the group, its submission's changes made below, where it may and // took no first work, the device wrapped no image of the caller's it names since it was // found ready, and it waits for nothing but values seen complete where a group is held: a diff --git a/crates/metal2vulkan-runtime/src/device/staging.rs b/crates/metal2vulkan-runtime/src/device/staging.rs index 71396260e..75c7824b4 100644 --- a/crates/metal2vulkan-runtime/src/device/staging.rs +++ b/crates/metal2vulkan-runtime/src/device/staging.rs @@ -12,21 +12,26 @@ //! the graphics family is not enough: on the 3090 (615.71.09) a readback there waited 1.88 s for //! a 2 s kernel running on the first, where the copy engine's took 7.8 to 13.5 ms with the //! kernel still running, and 2.65 ms idle (raw Vulkan). Here nothing but these -//! copies runs, each waited for before the next, so a copy waits for itself alone. +//! copies runs, so a copy waits for itself and the staging work submitted before it alone. //! - **What it waits for.** Each submission waits, on the GPU, for the value through which each //! of the device's other `VkQueue`s completed as the host saw it: work that already completed, //! so the wait costs nothing, and the writes of every command buffer the program saw complete //! are visible to the copy. It never waits for work in flight: a command in flight meanwhile //! is the program's race, as on Metal. -//! - **What waits for it.** Each submission signals the staging queue's own timeline, and every -//! batch with work waits for that timeline at the value the host saw it reach -//! (`submit.rs`, `OwnTimeline`): what the copies wrote is visible to the batch. Where the -//! driver's submissions stall on semaphore operations, a batch's first barrier makes it -//! visible instead (`command_buffer/submit.rs`), and the copies signal no timeline. +//! - **What waits for it.** Each submission signals the staging queue's own timeline. A host call +//! that needs what it did on the CPU (`get_bytes`, a texture's `VkImage` handed out, the +//! program's own use of a `VkQueue`) waits for it on the host. Every other submission of the +//! device's, a batch or an internal one on any `VkQueue`, waits for it on the GPU until the host +//! saw it complete ([`Device::staging_wait`]): the copies it made are visible to the commands +//! after that wait, which never waits for work of the program's. A submission is not waited for +//! before the next one is recorded: its command buffer is one of up to [`BUFFERS`], each reused +//! once the host saw the value it signalled reached. //! - **Who uses it.** A texture made to copy through it (`texture/staging_copy.rs`) has its first -//! move and zeros written here as it is made, and its `replace_region` and `get_bytes` copied -//! here, each waited for, so none of its work waits in `texture/first_move.rs` for a batch (a -//! batch submitted later finds it in `GENERAL`, its bytes written). +//! move and zeros written here as it is made, waited for, and its `replace_region` copies queued +//! for the next submission here, which carries them all ([`StagingLock::submit`]): the next +//! batch or internal submission of the device's makes it before its own, and a `get_bytes` +//! carries them before its read. So none of its work waits in `texture/first_move.rs` for a +//! batch. use super::{lock, Device, LoaderWord}; use crate::error::{internal, vulkan, Error}; @@ -36,12 +41,17 @@ use crate::sharing::Sharing; use crate::work_counts::Begun; use ash::vk; use ash::vk::Handle; -use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard, OnceLock}; use std::time::Duration; /// How long one wait for a staging submission lasts before it is repeated. const WAIT_SLICE: Duration = Duration::from_millis(100); +/// The most command buffers the staging queue records into: past them, a submission waits on the +/// host for the oldest one's before it records (the module docs). +pub(crate) const BUFFERS: usize = 8; + /// The staging queue and its objects. pub(super) struct StagingQueue { /// The queue's family: one of transfers alone. @@ -54,8 +64,13 @@ pub(super) struct StagingQueue { /// The queue's loader word, put back before each use (`relay.rs`). word: LoaderWord, /// The queue, and the objects its submissions use once made: under one lock, held for a - /// copy's submission and its wait. + /// submission's recording and its `vkQueueSubmit`, never for a wait. objects: Mutex, + /// The timeline every submission signals, once made: read with no lock + /// ([`Device::staging_wait`]). + timeline: OnceLock, + /// The value the last submission made signals, stored under `objects`' lock once it was made. + submitted: AtomicU64, } struct Objects { @@ -63,15 +78,14 @@ struct Objects { made: Option, } -/// The command pool, command buffer, fence and timeline of the staging submissions, made on -/// first use. +/// The command pool, command buffers and timeline of the staging submissions, made on first use. struct Made { pool: vk::CommandPool, - buffer: vk::CommandBuffer, - fence: vk::Fence, - /// The timeline each submission signals, and the value the last one signalled: none where - /// batches make completed work visible by a barrier (the module docs). - timeline: Option, + /// Each command buffer, and the value of the last submission of it: free once the host saw + /// the timeline reach it (0: never submitted). + buffers: Vec<(vk::CommandBuffer, u64)>, + timeline: vk::Semaphore, + /// The value the last submission signalled. signalled: u64, } @@ -95,6 +109,8 @@ impl StagingQueue { // SAFETY: the caller's contract. word: unsafe { LoaderWord::of_handle(queue.as_raw()) }, objects: Mutex::new(Objects { queue, made: None }), + timeline: OnceLock::new(), + submitted: AtomicU64::new(0), } } @@ -103,10 +119,7 @@ impl StagingQueue { if let Some(made) = lock(&self.objects).made.take() { // SAFETY: the device is idle and nothing else holds these objects. unsafe { - release::object(device, made.fence); - if let Some(timeline) = made.timeline { - release::object(device, timeline); - } + release::object(device, made.timeline); release::object(device, made.pool); } } @@ -124,52 +137,185 @@ impl Made { .queue_family_index(family); // SAFETY: the device is live and `pool_info` valid. let pool = unsafe { raw.create_command_pool(&pool_info, None) }.map_err(vulkan)?; - let made = (|| { - let allocate = vk::CommandBufferAllocateInfo::default() - .command_pool(pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(1); - let buffer = device.allocate_command_buffers(&allocate)?[0]; - // SAFETY: the device is live. - let fence = unsafe { raw.create_fence(&vk::FenceCreateInfo::default(), None) } - .map_err(vulkan)?; - let timeline = match device.shared().completed_by_barrier { - true => None, - false => { - let mut kind = vk::SemaphoreTypeCreateInfo::default() - .semaphore_type(vk::SemaphoreType::TIMELINE) - .initial_value(0); - let info = vk::SemaphoreCreateInfo::default().push_next(&mut kind); - // SAFETY: the device is live and enables `timelineSemaphore`. - match unsafe { raw.create_semaphore(&info, None) } { - Ok(timeline) => { - device.shared().staging_done.made(timeline); - Some(timeline) - } - Err(error) => { - // SAFETY: the fence is unused. - unsafe { release::object(raw, fence) }; - return Err(vulkan(error)); - } - } - } - }; - Ok(Made { + let mut kind = vk::SemaphoreTypeCreateInfo::default() + .semaphore_type(vk::SemaphoreType::TIMELINE) + .initial_value(0); + let info = vk::SemaphoreCreateInfo::default().push_next(&mut kind); + // SAFETY: the device is live and enables `timelineSemaphore`. + match unsafe { raw.create_semaphore(&info, None) } { + Ok(timeline) => Ok(Made { pool, - buffer, - fence, + buffers: Vec::new(), timeline, signalled: 0, - }) - })(); - if made.is_err() { - // SAFETY: nothing allocated from the pool is in use. - unsafe { release::object(raw, pool) }; + }), + Err(error) => { + // SAFETY: nothing allocated from the pool is in use. + unsafe { release::object(raw, pool) }; + Err(vulkan(error)) + } } - made } } +/// The staging queue's lock, held to record and make a submission (the module docs). +pub(crate) struct StagingLock<'a> { + device: &'a Device, + staging: &'a StagingQueue, + objects: MutexGuard<'a, Objects>, +} + +impl StagingLock<'_> { + /// Record `record` into a free command buffer of the staging queue and submit it there, + /// waiting on the GPU for what the device's other `VkQueue`s completed as the host saw (the + /// module docs); the value it signals, not waited for ([`Device::wait_staging`]). `record` + /// runs outside a render pass, for a family of transfers alone, whose queue flags it is + /// given: it records copies, fills and barriers, of color aspects alone. + pub(crate) fn submit( + &mut self, + record: impl FnOnce(&ash::Device, vk::CommandBuffer, vk::QueueFlags), + ) -> Result { + let device = self.device; + if device.is_lost() { + return Err(Error::DeviceLost); + } + let shared = device.shared(); + let raw = shared.vk(); + let staging = self.staging; + let objects = &mut *self.objects; + if objects.made.is_none() { + let made = Made::new(device, staging.family)?; + let _ = staging.timeline.set(made.timeline); + shared.staging_done.made(made.timeline); + objects.made = Some(made); + } + let queue = objects.queue; + let Some(made) = objects.made.as_mut() else { + unreachable!("made above"); + }; + let at = free_buffer(device, made)?; + let buffer = made.buffers[at].0; + let begin = vk::CommandBufferBeginInfo::default() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + // SAFETY: the command buffer is not pending (the host saw the value of its last + // submission reached) and the staging lock is held; beginning it resets it (the pool + // resets command buffers). + unsafe { raw.begin_command_buffer(buffer, &begin) }.map_err(vulkan)?; + shared.counts.command_buffer_begun(Begun::Internal); + record(raw, buffer, staging.flags); + // SAFETY: as above. + unsafe { raw.end_command_buffer(buffer) }.map_err(vulkan)?; + // The completed work of every other queue: a wait that costs nothing, for visibility. + let completed: Vec<(vk::Semaphore, u64)> = (shared.queues.iter()) + .map(|slot| (slot.timeline, slot.completed_value())) + .filter(|&(_, value)| value > 0) + .collect(); + let wait_semaphores: Vec = completed.iter().map(|w| w.0).collect(); + let wait_values: Vec = completed.iter().map(|w| w.1).collect(); + let wait_stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; completed.len()]; + // It signals its own timeline, which a host call or the device's next submissions wait + // for. + let value = made.signalled + 1; + let signal_semaphores = [made.timeline]; + let signal_values = [value]; + let mut timeline = vk::TimelineSemaphoreSubmitInfo::default() + .wait_semaphore_values(&wait_values) + .signal_semaphore_values(&signal_values); + let buffers = [buffer]; + let submit = vk::SubmitInfo::default() + .wait_semaphores(&wait_semaphores) + .wait_dst_stage_mask(&wait_stages) + .command_buffers(&buffers) + .signal_semaphores(&signal_semaphores) + .push_next(&mut timeline); + // 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()); + let submitted = unsafe { + staging.word.restore(); + raw.queue_submit(queue, &[submit], vk::Fence::null()) + }; + exit_guard::called(Call::QueueSubmit); + submitted.map_err(|error| device.failed(error))?; + made.signalled = value; + made.buffers[at].1 = value; + staging.submitted.store(value, Ordering::Release); + shared.counts.staging_submission(); + Ok(value) + } +} + +/// The index of a command buffer of `made` no submission holds: one whose last submission the +/// host saw complete, else a new one while there are fewer than [`BUFFERS`], else the oldest, +/// once a wait on the host saw its value reached. +fn free_buffer(device: &Device, made: &mut Made) -> Result { + let shared = device.shared(); + let seen = shared.staging_done.value(); + let oldest = (made.buffers.iter().enumerate()) + .min_by_key(|(_, &(_, value))| value) + .map(|(at, &(_, value))| (at, value)); + if let Some((at, value)) = oldest { + if value <= seen || reached(device, made.timeline, value, 0)? { + return Ok(at); + } + } + if made.buffers.len() < BUFFERS { + let allocate = vk::CommandBufferAllocateInfo::default() + .command_pool(made.pool) + .level(vk::CommandBufferLevel::PRIMARY) + .command_buffer_count(1); + let buffer = device.allocate_command_buffers(&allocate)?[0]; + made.buffers.push((buffer, 0)); + return Ok(made.buffers.len() - 1); + } + let Some((at, value)) = oldest else { + unreachable!("BUFFERS command buffers are made"); + }; + wait_for(device, made.timeline, value)?; + Ok(at) +} + +/// Whether the host saw `timeline` reach `value` within `timeout` nanoseconds (0: at once, "If +/// timeout is zero, then vkWaitSemaphores does not wait"); the staging timeline's completion +/// noted where it did. A wait, not a read: Vulkan orders host operations after a signal only +/// through a wait (`device/submit.rs`, `binding_seen`). +fn reached( + device: &Device, + timeline: vk::Semaphore, + value: u64, + timeout: u64, +) -> Result { + let shared = device.shared(); + let semaphores = [timeline]; + let values = [value]; + let info = vk::SemaphoreWaitInfo::default() + .semaphores(&semaphores) + .values(&values); + // SAFETY: the timeline is the device's, live while the device is. + let waited = unsafe { shared.vk().wait_semaphores(&info, timeout) }; + exit_guard::called(Call::WaitSemaphores); + match waited { + Ok(()) => { + shared.staging_done.reached(value); + Ok(true) + } + Err(vk::Result::TIMEOUT) => Ok(false), + Err(error) => Err(device.failed(error)), + } +} + +/// Wait on the host until `timeline` reached `value`, a slice at a time. +fn wait_for(device: &Device, timeline: vk::Semaphore, value: u64) -> Result<(), Error> { + let slice = WAIT_SLICE.as_nanos() as u64; + while !reached(device, timeline, value, slice)? { + if device.is_lost() { + return Err(Error::DeviceLost); + } + } + Ok(()) +} + impl Device { /// Whether the device reserved a staging queue (the module docs): a device it created with a /// family of transfers alone whose copies take any texel. @@ -183,88 +329,55 @@ impl Device { (self.shared().staging.as_ref()).map(|staging| Sharing::new(&staging.families)) } - /// Record `record` into the staging queue's command buffer, submit it there, waiting on the - /// GPU for what the device's other `VkQueue`s completed as the host saw (the module docs), - /// and wait for it. `record` runs outside a render pass, for a family of transfers alone, whose - /// queue flags it is given: it records copies, fills and barriers, of color aspects alone. + /// The staging queue's lock, for a submission there ([`StagingLock::submit`]). + pub(crate) fn staging_lock(&self) -> Result, Error> { + let staging = (self.shared().staging.as_ref()) + .ok_or_else(|| internal("a staging copy on a device without a staging queue"))?; + Ok(StagingLock { + device: self, + staging, + objects: lock(&staging.objects), + }) + } + + /// Wait on the host for the staging submission that signals `value`. + pub(crate) fn wait_staging(&self, value: u64) -> Result<(), Error> { + if self.shared().staging_done.value() >= value { + return Ok(()); + } + let staging = (self.shared().staging.as_ref()) + .ok_or_else(|| internal("a staging wait on a device without a staging queue"))?; + let timeline = *(staging.timeline.get()) + .ok_or_else(|| internal("a staging wait before any staging submission"))?; + wait_for(self, timeline, value) + } + + /// Record `record` on the staging queue ([`StagingLock::submit`]) and wait for it on the + /// host. pub(crate) fn submit_staging( &self, record: impl FnOnce(&ash::Device, vk::CommandBuffer, vk::QueueFlags), ) -> Result<(), Error> { - if self.is_lost() { - return Err(Error::DeviceLost); - } + let value = self.staging_lock()?.submit(record)?; + self.wait_staging(value) + } + + /// The staging queue's last submission while the host has not seen it complete: what every + /// other submission of the device's waits for on the GPU (the module docs), as what it copied + /// may be among what it uses. The host sees it complete once a wait of no time returned for + /// it. + pub(crate) fn staging_wait(&self) -> Option<(vk::Semaphore, u64)> { let shared = self.shared(); - let staging = (shared.staging.as_ref()) - .ok_or_else(|| internal("a staging copy on a device without a staging queue"))?; - let raw = shared.vk(); - let mut objects = lock(&staging.objects); - if objects.made.is_none() { - objects.made = Some(Made::new(self, staging.family)?); + let staging = shared.staging.as_ref()?; + let submitted = staging.submitted.load(Ordering::Acquire); + if submitted <= shared.staging_done.value() { + return None; } - let queue = objects.queue; - let Some(made) = objects.made.as_mut() else { - unreachable!("made above"); - }; - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - // SAFETY: the command buffer is not pending (every submission is waited for below) and - // the staging lock is held; beginning it resets it (the pool resets command buffers). - unsafe { raw.begin_command_buffer(made.buffer, &begin) }.map_err(vulkan)?; - shared.counts.command_buffer_begun(Begun::Internal); - record(raw, made.buffer, staging.flags); - // SAFETY: as above. - unsafe { raw.end_command_buffer(made.buffer) }.map_err(vulkan)?; - // SAFETY: the fence is unsignaled or signaled and not pending. - unsafe { raw.reset_fences(&[made.fence]) }.map_err(vulkan)?; - // The completed work of every other queue: a wait that costs nothing, for visibility. - let completed: Vec<(vk::Semaphore, u64)> = (shared.queues.iter()) - .map(|slot| (slot.timeline, slot.completed_value())) - .filter(|&(_, value)| value > 0) - .collect(); - let wait_semaphores: Vec = completed.iter().map(|w| w.0).collect(); - let wait_values: Vec = completed.iter().map(|w| w.1).collect(); - let wait_stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; completed.len()]; - // It signals its own timeline, which every batch with work then waits for, where it has - // one. - let value = made.signalled + 1; - let signal_semaphores: Vec = made.timeline.into_iter().collect(); - let signal_values: Vec = signal_semaphores.iter().map(|_| value).collect(); - let mut timeline = vk::TimelineSemaphoreSubmitInfo::default() - .wait_semaphore_values(&wait_values) - .signal_semaphore_values(&signal_values); - let buffers = [made.buffer]; - let submit = vk::SubmitInfo::default() - .wait_semaphores(&wait_semaphores) - .wait_dst_stage_mask(&wait_stages) - .command_buffers(&buffers) - .signal_semaphores(&signal_semaphores) - .push_next(&mut timeline); - // 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()); - let submitted = unsafe { - staging.word.restore(); - raw.queue_submit(queue, &[submit], made.fence) - }; - exit_guard::called(Call::QueueSubmit); - submitted.map_err(|error| self.failed(error))?; - made.signalled = value; - shared.counts.staging_submission(); - loop { - // SAFETY: the fence was submitted just now. - match unsafe { raw.wait_for_fences(&[made.fence], true, WAIT_SLICE.as_nanos() as u64) } - { - Ok(()) => { - if made.timeline.is_some() { - shared.staging_done.reached(value); - } - return Ok(()); - } - Err(vk::Result::TIMEOUT) => continue, - Err(error) => return Err(self.failed(error)), - } + let timeline = *staging.timeline.get()?; + // A failed wait (a lost device) leaves the submission waited for. + match reached(self, timeline, submitted, 0) { + Ok(true) => None, + _ => Some((timeline, submitted)), } } } diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs index e6b0aa51e..bb7765c41 100644 --- a/crates/metal2vulkan-runtime/src/device/submit.rs +++ b/crates/metal2vulkan-runtime/src/device/submit.rs @@ -63,6 +63,11 @@ impl OwnTimeline { let _ = self.semaphore.set(semaphore); } + /// The value through which the host saw its submissions complete (0 before the first). + pub(super) fn value(&self) -> u64 { + self.completed.load(Ordering::Acquire) + } + /// The host saw the timeline reach `value`. pub(super) fn reached(&self, value: u64) { self.completed.fetch_max(value, Ordering::AcqRel); @@ -175,6 +180,10 @@ impl Device { *internal = Some(Internal::new(self)?); } let taken = firsts.take(&named); + // The copies queued for the staging queue, submitted there first, which this waits for on + // the GPU (below), holding what they copied until it completed + // (`texture/staging_copy.rs`). + let _staged = self.flush_staging()?; let Some(objects) = internal.as_mut() else { unreachable!("made above"); }; @@ -215,10 +224,16 @@ impl Device { // SAFETY: the fence is unsignaled or signaled and not pending. unsafe { raw.reset_fences(&[objects.fence]) }.map_err(vulkan)?; let buffers = [objects.buffer]; - // And the last binding of a no-copy buffer's dma-bufs, until it completed. + // And the last binding of a no-copy buffer's dma-bufs, and the staging queue's last + // submission, until each completed. + let staging = self.staging_wait(); + if staging.is_some() { + shared.counts.staging_gpu_wait(); + } let waits: Vec<(vk::Semaphore, u64)> = (waits.iter()) .map(|point| (shared.queues[point.queue].timeline, point.value)) .chain(self.binding_wait()) + .chain(staging) .collect(); let wait_semaphores: Vec = waits.iter().map(|wait| wait.0).collect(); let wait_values: Vec = waits.iter().map(|wait| wait.1).collect(); diff --git a/crates/metal2vulkan-runtime/src/interop.rs b/crates/metal2vulkan-runtime/src/interop.rs index f992fc741..1820a4aeb 100644 --- a/crates/metal2vulkan-runtime/src/interop.rs +++ b/crates/metal2vulkan-runtime/src/interop.rs @@ -491,6 +491,10 @@ impl CommandQueue { // The caller's own submissions are GPU work of the program's: textures' host shadows are // read against the device's count of it (`texture/host_shadow.rs`). shared.program_gave_gpu_work(); + // The copies queued for the staging queue are made first, waited for: the caller's + // submissions may read what they wrote (`texture/staging_copy.rs`). A failure there is a + // lost device, which the caller's own submissions then meet. + let _ = self.device().flush_staging_waited(); // The queue keeps this `VkQueue` for good from here on, so the caller's submissions there // stay in its order (`queue_share.rs`). let vk_queue = self.pinned_vk_queue(); diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 39fa0cf83..02353d17e 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -1105,6 +1105,10 @@ impl Image { /// handed out, which rests in `GENERAL` (`Texture::vk_image`), and holds what host calls copied /// in. fn settle(&self) -> Result<(), Error> { + // The copies queued for the staging queue, waited for (`texture/staging_copy.rs`). + if self.takes_staging_copies() { + self.device.flush_staging_waited()?; + } let firsts = &self.device.shared().textures.first_moves; let at: *const Image = self; if !self.move_waits() && !firsts.texels_wait(at.cast()) { @@ -3848,6 +3852,50 @@ pub(super) fn zero_copies( (length, copies) } +/// A host-visible, mapped buffer of `len` bytes for copies both ways, bound to its placement: a +/// staging buffer's objects ([`Staging`], `staging_copy::StagedBytes`). +fn staging_buffer(device: &Device, len: u64) -> Result<(vk::Buffer, Placement), Error> { + let shared = device.shared(); + let raw_device = shared.vk(); + usize::try_from(len).map_err(|_| Error::OutOfMemory(MemoryKind::Host))?; + let info = shared.sharing().buffer( + vk::BufferCreateInfo::default() + .size(len) + .usage(vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::TRANSFER_DST), + ); + // SAFETY: the device is live and `info` valid. + let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; + // SAFETY: `raw` is a live buffer of this device. + let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; + let placement = match crate::memory::allocate( + &shared.memory, + raw_device, + &requirements, + MemoryClass::Shared, + ) { + Ok(placement) => placement, + Err(error) => { + // SAFETY: the buffer is unused. + unsafe { release::object(raw_device, raw) }; + return Err(error); + } + }; + // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. + let bound = unsafe { + crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset) + }; + if placement.mapped.is_none() || bound.is_err() { + // SAFETY: the buffer is unused. + unsafe { release::object(raw_device, raw) }; + lock(&shared.memory).free(raw_device, &placement); + return Err(match bound { + Err(error) => vulkan(error), + Ok(()) => Error::OutOfMemory(MemoryKind::Host), + }); + } + Ok((raw, placement)) +} + /// A host-visible buffer `replace_region` and `get_bytes` copy through, released when dropped. struct Staging<'a> { device: &'a Device, @@ -3859,51 +3907,14 @@ struct Staging<'a> { impl Staging<'_> { /// A staging buffer of `len` bytes. fn new(device: &Device, len: u64) -> Result, Error> { - let shared = device.shared(); - let raw_device = shared.vk(); let size = usize::try_from(len).map_err(|_| Error::OutOfMemory(MemoryKind::Host))?; - let info = shared.sharing().buffer( - vk::BufferCreateInfo::default() - .size(len) - .usage(vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::TRANSFER_DST), - ); - // SAFETY: the device is live and `info` valid. - let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; - // SAFETY: `raw` is a live buffer of this device. - let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; - let placement = match crate::memory::allocate( - &shared.memory, - raw_device, - &requirements, - MemoryClass::Shared, - ) { - Ok(placement) => placement, - Err(error) => { - // SAFETY: the buffer is unused. - unsafe { release::object(raw_device, raw) }; - return Err(error); - } - }; - let staging = Staging { + let (raw, placement) = staging_buffer(device, len)?; + Ok(Staging { device, raw, placement, len: size, - }; - if staging.placement.mapped.is_none() { - return Err(Error::OutOfMemory(MemoryKind::Host)); - } - // SAFETY: the placement meets the buffer's requirements and is not bound elsewhere. - unsafe { - crate::creation::bind_buffer( - raw_device, - raw, - staging.placement.memory, - staging.placement.offset, - ) - } - .map_err(vulkan)?; - Ok(staging) + }) } /// The staging bytes, through the mapping. @@ -5526,7 +5537,7 @@ impl Texture { } // Packed into the staging buffer from the caller's bytes. if truth.takes_staging_copies() - && truth.staging_write(copy, len as u64, |staged| bytes.pack(&host, staged))? + && truth.staging_write(truth, copy, len as u64, |staged| bytes.pack(&host, staged))? { // A decoded twin's decode, staged; on the CPU while a batch may read it. return truth.decode_written(&image_region, pack); diff --git a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs index c39fe0602..3cda71909 100644 --- a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs +++ b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs @@ -1066,7 +1066,11 @@ impl Image { /// [`twin_decoded`](Self::twin_decoded) then lets the batches that wait for it go. A failure /// is said on the device's message sink as an error (`metal2vulkan-twin-decode-failed`): the /// call that queued it has returned. - pub(super) fn finish_twin_decode(&self, region: &ImageRegion, blocks: Option<&[u8]>) { + pub(super) fn finish_twin_decode( + self: &Arc, + region: &ImageRegion, + blocks: Option<&[u8]>, + ) { let shared = self.device.shared(); let result = match self.decoded.as_deref() { Some(decoded) => self.write_decoded(decoded, region, blocks), @@ -1121,7 +1125,7 @@ impl Image { /// threads: whether on the host (else on the staging queue). An internal error where the twin /// takes neither copy, or took none. fn write_decoded( - &self, + self: &Arc, decoded: &Decoded, region: &ImageRegion, blocks: Option<&[u8]>, @@ -1185,7 +1189,8 @@ impl Image { } false => { let (copy, len) = (buffer_image_copy(&band), texels.len() as u64); - twin.staging_write(copy, len, |staged| staged.copy_from_slice(&texels))? + let fill = |staged: &mut [u8]| staged.copy_from_slice(&texels); + twin.staging_write(self, copy, len, fill)? } }; if !written { diff --git a/crates/metal2vulkan-runtime/src/texture/first_move.rs b/crates/metal2vulkan-runtime/src/texture/first_move.rs index 84853ed39..011f12a00 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -47,7 +47,9 @@ //! -- waiting for what the submission waits for: MoltenVK runs each `VkSubmitInfo` as a Metal //! command buffer of its own, so it adds none (`command_buffer/submit.rs`). //! - **Staged copies**. `replace_region` of a texture whose `VkImage` is its own for good (in -//! memory of its own, or a heap's own pages) and takes no host copies stages the bytes +//! memory of its own, or a heap's own pages) and takes no host or staging-queue copies (those +//! are queued for the staging queue instead, whose submission of them every submission of the +//! device's makes before its own: `texture/staging_copy.rs`) stages the bytes //! ([`TexelCopy`], [`FirstMoves::register_texels`]): the next submission copies them in at //! the start of its work, after the first work's `VkSubmitInfo`, each copy after the writes before //! it, and holds the image and the staging buffer until it completed. @@ -606,11 +608,11 @@ enum Zero { /// The most bytes host calls' copies stage for the device's next submission before one is made /// for them, waited for (the module docs). -const STAGED_BYTES: u64 = 256 << 20; +pub(super) const STAGED_BYTES: u64 = 256 << 20; /// The most copies host calls stage for the device's next submission before one is made for /// them, waited for (the module docs): a bound on the work waiting, whatever its bytes. -const STAGED_COPIES: usize = 4096; +pub(super) const STAGED_COPIES: usize = 4096; /// A new buffer's fill: copies of the device's zeros onto `range` of `buffer`, or a fill of its /// words with zeros (`word_fill.rs`), or copies of the bytes a staging buffer holds, or a @@ -859,6 +861,10 @@ pub(crate) struct FirstMoves { /// (`texture/decoded_twin.rs`, `PassScratch::Device`), and its bytes: made at the first such /// decode, kept with the device. decode_scratch: Mutex>, + /// The work queued for the staging queue's next submission (`texture/staging_copy.rs`): + /// copies into images that copy there, which every submission of the device's makes there + /// before its own. + pub(super) staging: Mutex, } /// The side of each of the device's multisampled scratch images ([`FirstMoves::scratch`]): its @@ -1229,6 +1235,7 @@ impl FirstMoves { /// Release the buffer of zeros, the patterns' and the scratch images into `memory`; the /// device is idle. pub(crate) fn destroy(&self, device: &ash::Device, memory: &mut Memory) { + lock(&self.staging).destroy(device, memory); if let Some(zeros) = &*lock(&self.zeros) { zeros.destroy(device, memory); } diff --git a/crates/metal2vulkan-runtime/src/texture/staging_copy.rs b/crates/metal2vulkan-runtime/src/texture/staging_copy.rs index 9cd00f62c..7e61dd60c 100644 --- a/crates/metal2vulkan-runtime/src/texture/staging_copy.rs +++ b/crates/metal2vulkan-runtime/src/texture/staging_copy.rs @@ -14,30 +14,230 @@ //! - **Made.** It is moved to `GENERAL` and zeroed on the staging queue as it is made, from a //! staging buffer of zeros (a copy engine clears nothing), waited for //! (`FirstMove::record_alone`): no batch finds its move waiting. -//! - **Copied.** `replace_region` packs the caller's bytes into a staging buffer and copies them -//! into the image on the staging queue; `get_bytes` copies the image's texels into one there -//! and lays them out from it into the caller's bytes. Each waits for its own submission alone: the copy and one submission's -//! round trip, whatever the program has in flight. A later batch finds the bytes written (the -//! submission completed before the call returned); `get_bytes` reads what every command buffer -//! the host saw complete wrote. +//! - **Copied in.** `replace_region` packs the caller's bytes into a staging buffer of their own +//! before it returns, and queues the copy into the image for the staging queue's next +//! submission ([`Queued`]), which carries every copy queued so far, in the order they were +//! queued, a barrier between two into one image: a burst of calls makes one submission, not one +//! each. That submission is made by the first of the device's next batch or internal +//! submission, on any `VkQueue`, before its own, which waits for it on the GPU +//! (`Device::staging_wait`, `device/staging.rs`); a `get_bytes` of any image that copies here, +//! which carries them before its read; a texture's `VkImage` handed out, and the program's own +//! use of a `VkQueue`, which wait for it on the host; and the call that queues past +//! [`STAGED_COPIES`] copies or [`STAGED_BYTES`] bytes, which waits for it on the host. So a +//! later command buffer's commands, the device's own copies of the texture, and every CPU read +//! find the bytes written. Counted: `WorkCounts::staging_copies_queued`, +//! `WorkCounts::staging_flushes`, `WorkCounts::staging_gpu_waits`. +//! - **Copied out.** `get_bytes` copies the image's texels into a staging buffer on the staging +//! queue, after the copies queued, and lays them out from it into the caller's bytes, waiting +//! for that submission alone: the copies and one submission's round trip, whatever the program +//! has in flight. It reads what every command buffer the host saw complete wrote. //! - **A race is the program's,** as on the host (`host_copy.rs`): a command in flight meanwhile -//! reads or writes texels the copy may or may not have moved. A copy runs under the lock a -//! detach takes, so it never reaches a `VkImage` that went; while the image presents a -//! stand-in, or a host call's copy into it still waits for a batch (made while it presented -//! one), the call takes the submission's path. +//! reads or writes texels the copy may or may not have moved, and one submitted before the +//! queued copies were (a command buffer committed before the call, still running or waiting on +//! an event) may read the texels before or after them, as Metal leaves a `replaceRegion` while +//! the GPU may use the texture. A `get_bytes` runs under the lock a detach takes, so it never +//! reaches a `VkImage` that went; a queued copy goes into the `VkImage` the image presented at +//! the call, its own, which a detach keeps for the reattach, and the submission that carries it +//! holds the image until it completed. While the image presents a stand-in, or a host call's +//! copy into it still waits for a batch (made while it presented one), the call takes the +//! submission's path. //! - **With a decoded twin** (`decoded_twin.rs`; a carried texture) too: `get_bytes` copies its //! carrier's blocks, which hold its texels, and `replace_region` copies the blocks into it, then //! queues their decode on the CPU, which copies the texels into the twin on the staging queue //! (`Image::decode_written`): the twin is made to take the staging queue's copies where its //! carrier does. -use super::{image_aspects, transfer_barrier, Image, ImagePlan, Staging}; +use super::first_move::{STAGED_BYTES, STAGED_COPIES}; +use super::{image_aspects, staging_buffer, transfer_barrier, Image, ImagePlan, Staging}; use crate::device::{lock, Device}; use crate::error::Error; +use crate::exit_guard::{self, Call}; +use crate::memory::Placement; +use crate::release; use ash::vk; use metal2vulkan::metal::format::is_depth_stencil; use metal2vulkan::metal::PixelFormat; use metal2vulkan::vk::{ImageAspectFlags, ImageUsageFlags}; +use std::sync::{Arc, Weak}; + +/// The work queued for the staging queue's next submission (the module docs), in the device's +/// first moves (`FirstMoves::register_staging`), and what bounds it. +#[derive(Default)] +pub(crate) struct Queued { + work: Vec, + /// The bytes of the staging buffers `work` holds. + bytes: u64, + /// Submissions that took work from here and have not yet stored the value they signal, under + /// the staging queue's lock: while one has not, a submission elsewhere that finds nothing + /// queued takes the lock before it reads that value ([`Device::flush_staging`]). + draining: usize, +} + +/// One copy queued: of `copy` from the staging buffer `bytes` into `raw`, the `VkImage` of the +/// image `keeper` keeps (its own, or its decoded twin's), held weakly: an image gone takes its +/// copy with it. +struct Work { + keeper: Weak, + raw: vk::Image, + bytes: StagedBytes, + copy: vk::BufferImageCopy, +} + +/// A staging buffer's objects, which nothing frees as they drop: the queue that holds them +/// frees them ([`StagedBytes::free`]), as it holds no device. +pub(super) struct StagedBytes { + raw: vk::Buffer, + placement: Placement, + len: u64, +} + +impl StagedBytes { + /// A staging buffer of `len` bytes, host-visible, shared as `Staging`'s. + fn new(device: &Device, len: u64) -> Result { + let (raw, placement) = staging_buffer(device, len)?; + Ok(StagedBytes { + raw, + placement, + len, + }) + } + + /// Its bytes, through the mapping. + fn bytes(&mut self) -> &mut [u8] { + let Some(mapped) = self.placement.mapped else { + unreachable!("checked when the staging buffer was made"); + }; + // SAFETY: the mapping covers the placement's `len` bytes, which only this staging buffer + // uses; the memory is host-coherent, and no submission uses it yet. + unsafe { std::slice::from_raw_parts_mut(mapped.as_ptr(), self.len as usize) } + } + + /// Free it; no pending submission uses it. + fn free(self, device: &Device) { + // Once the process is exiting, the buffer is left to its end (`exit_guard`). + let Some(_busy) = exit_guard::enter() else { + return; + }; + let shared = device.shared(); + // SAFETY: the caller's. + unsafe { release::object(shared.vk(), self.raw) }; + lock(&shared.memory).free(shared.vk(), &self.placement); + } +} + +impl Queued { + /// Queue `work`; whether the work queued now passed [`STAGED_COPIES`] or [`STAGED_BYTES`]. + fn push(&mut self, work: Work) -> bool { + self.bytes += work.bytes.len; + self.work.push(work); + self.work.len() > STAGED_COPIES || self.bytes > STAGED_BYTES + } + + /// Whether a submission elsewhere has queued work to carry or to wait for (the docs of + /// `draining`). + pub(super) fn waits(&self) -> bool { + !self.work.is_empty() || self.draining > 0 + } + + /// The device's teardown: free the staging buffers queued; the device is idle. + pub(super) fn destroy(&mut self, device: &ash::Device, memory: &mut crate::memory::Memory) { + for work in self.work.drain(..) { + // SAFETY: the device is idle and no submission used the buffer. + unsafe { release::object(device, work.bytes.raw) }; + memory.free(device, &work.bytes.placement); + } + self.bytes = 0; + } +} + +/// What a staging submission that carried queued work holds until it completed: the images it +/// copied into and the staging buffers it copied from, then freed. Its drop waits on the host for +/// the submission where the host has not seen it complete (a batch that holds it completed after +/// it, so that wait returns at once). +pub(crate) struct Flushed { + device: Device, + value: u64, + bytes: Vec, + _images: Vec>, +} + +impl Drop for Flushed { + fn drop(&mut self) { + // A failed wait (a lost device) leaves nothing running that uses them. + let _ = self.device.wait_staging(self.value); + for bytes in self.bytes.drain(..) { + bytes.free(&self.device); + } + } +} + +/// The queued work taken by one submission: each copy whose image is still there, and the +/// staging buffers of those gone, to free. +struct Taken { + live: Vec<(Arc, Work)>, + gone: Vec, +} + +impl Taken { + /// Record the copies in order, a barrier before each into an image an earlier one wrote: + /// copies into one image keep their order. + /// + /// # Safety + /// + /// `command_buffer` is recording on the staging queue, after a barrier from every command + /// before; every image is live, in `GENERAL`, shared with the staging queue; every staging + /// buffer holds its bytes. + unsafe fn record(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer) { + let mut written: Vec = Vec::new(); + for (_, work) in &self.live { + if written.contains(&work.raw) { + let barrier = vk::MemoryBarrier::default() + .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) + .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE); + // SAFETY: the caller's. + unsafe { + raw.cmd_pipeline_barrier( + command_buffer, + vk::PipelineStageFlags::TRANSFER, + vk::PipelineStageFlags::TRANSFER, + vk::DependencyFlags::empty(), + &[barrier], + &[], + &[], + ); + } + exit_guard::called(Call::CmdPipelineBarrier); + written.clear(); + } + // SAFETY: the caller's. + unsafe { + raw.cmd_copy_buffer_to_image( + command_buffer, + work.bytes.raw, + work.raw, + vk::ImageLayout::GENERAL, + &[work.copy], + ); + } + exit_guard::called(Call::CmdCopyBufferToImage); + written.push(work.raw); + } + } + + /// What the submission that carried it holds until it completed, the value it signals. + fn flushed(self, device: &Device, value: u64) -> Flushed { + for bytes in self.gone { + bytes.free(device); + } + let (images, bytes) = self.live.into_iter().map(|(i, w)| (i, w.bytes)).unzip(); + Flushed { + device: device.clone(), + value, + bytes, + _images: images, + } + } +} impl Device { /// Whether a new `Shared` or `Managed` texture's image of `plan`, for a texture of @@ -51,6 +251,118 @@ impl Device { && !is_depth_stencil(pixel_format) && plan.usage.contains(both) } + + /// Make the staging queue's submission of the work queued so far (the module docs), for a + /// submission of the device's about to be made, which waits for it on the GPU + /// ([`Device::staging_wait`]); what that submission holds until it completed, `None` where + /// nothing was queued. Where another submission took queued work and has not yet stored the + /// value it signals, this waits for the staging queue's lock until it has. + pub(crate) fn flush_staging(&self) -> Result, Error> { + if !self.has_staging_queue() { + return Ok(None); + } + let firsts = &self.shared().textures.first_moves; + if !lock(&firsts.staging).waits() { + return Ok(None); + } + self.submit_queued(None::) + } + + /// [`flush_staging`](Self::flush_staging), waited for on the host: for a host call whose + /// result needs what it copied (a texture's `VkImage` handed out, the program's own use of a + /// `VkQueue`), or that queued past the bound. + pub(crate) fn flush_staging_waited(&self) -> Result<(), Error> { + if let Some(flushed) = self.flush_staging()? { + self.wait_staging(flushed.value)?; + } + Ok(()) + } + + /// Take the queued work under the staging queue's lock and submit it there in one + /// submission, then `after` (a read of the caller's) behind a barrier from it: copies in + /// queued order, a barrier before each into an image an earlier one wrote. What the + /// submission holds until it completed, and the value it signals; `None` where nothing was + /// queued (no copy into an image still there) and there is no `after`, and nothing is + /// submitted. Work taken and not submitted goes back to the queue's front. + fn submit_queued( + &self, + after: Option, + ) -> Result, Error> { + let firsts = &self.shared().textures.first_moves; + let mut staging = self.staging_lock()?; + let work = { + let mut queued = lock(&firsts.staging); + if queued.work.is_empty() && after.is_none() { + return Ok(None); + } + queued.bytes = 0; + queued.draining += 1; + std::mem::take(&mut queued.work) + }; + let mut taken = Taken { + live: Vec::with_capacity(work.len()), + gone: Vec::new(), + }; + for work in work { + match work.keeper.upgrade() { + Some(image) => taken.live.push((image, work)), + None => taken.gone.push(work.bytes), + } + } + let copies = taken.live.len(); + let submitted = match (copies, after) { + (0, None) => Ok(None), + (copies, after) => staging + .submit(|raw, command_buffer, _| { + if copies > 0 { + transfer_barrier(raw, command_buffer, true); + // SAFETY: recording on the staging queue after a barrier from every + // command before; each image is held live (`taken`), rests in `GENERAL` + // (moved as it was made) and is shared with the staging queue; each + // staging buffer holds the bytes packed into it. + unsafe { taken.record(raw, command_buffer) }; + } + match after { + Some(after) => after(raw, command_buffer), + None => transfer_barrier(raw, command_buffer, false), + } + }) + .map(Some), + }; + // The value is stored (or no submission made) before another submission may read it. + lock(&firsts.staging).draining -= 1; + drop(staging); + match submitted { + Ok(Some(value)) => { + if copies > 0 { + self.shared().counts.staging_flush(); + } + Ok(Some(taken.flushed(self, value))) + } + Ok(None) => { + for bytes in taken.gone { + bytes.free(self); + } + Ok(None) + } + Err(error) => { + let mut queued = lock(&firsts.staging); + let later = std::mem::take(&mut queued.work); + queued.bytes = 0; + for (_, work) in taken.live { + queued.push(work); + } + for work in later { + queued.push(work); + } + drop(queued); + for bytes in taken.gone { + bytes.free(self); + } + Err(error) + } + } + } } impl Image { @@ -67,47 +379,49 @@ impl Image { !(self.device.shared().textures.first_moves).texels_wait(at.cast()) } - /// Copy `len` bytes, laid out as `copy` reads them from a buffer, which `fill` writes into the - /// staging buffer where they lie, into the image on the staging queue; the image [takes - /// staging copies](Self::takes_staging_copies). Whether it did: not while it presents a - /// stand-in, and then `fill` is not called. + /// Queue the copy of `len` bytes, laid out as `copy` reads them from a buffer, which `fill` + /// writes into a staging buffer of their own before this returns, into the image for the + /// staging queue's next submission (the module docs); the image [takes staging + /// copies](Self::takes_staging_copies), and `keeper` is what holds it (itself, or the texture + /// whose decoded twin it is). Whether it did: not while it presents a stand-in, and then + /// `fill` is not called. Where the image's `VkImage` was handed out (`Texture::vk_image`), whose + /// user the runtime does not see, or the work queued passed its bound, the submission is + /// made now and waited for. pub(super) fn staging_write( &self, + keeper: &Arc, copy: vk::BufferImageCopy, len: u64, fill: impl FnOnce(&mut [u8]), ) -> Result { - let detached = lock(&self.detached); - if detached.is_some() || !self.nothing_staged() { - return Ok(false); - } - let mut staging = Staging::new(&self.device, len)?; - fill(staging.bytes()); - let (buffer, image) = (staging.raw, self.raw.get()); - self.device.submit_staging(|raw, command_buffer, _| { - transfer_barrier(raw, command_buffer, true); - // SAFETY: the staging command buffer is recording; the staging buffer and the image - // are live (the detach lock keeps the image's own `VkImage` presented), and the image - // rests in `GENERAL` (moved as it was made), shared with the staging queue. - unsafe { - raw.cmd_copy_buffer_to_image( - command_buffer, - buffer, - image, - vk::ImageLayout::GENERAL, - &[copy], - ); + let raw = { + let detached = lock(&self.detached); + if detached.is_some() || !self.nothing_staged() { + return Ok(false); } - transfer_barrier(raw, command_buffer, false); - })?; - drop(detached); + self.raw.get() + }; + let mut bytes = StagedBytes::new(&self.device, len)?; + fill(bytes.bytes()); + let work = Work { + keeper: Arc::downgrade(keeper), + raw, + bytes, + copy, + }; + let shared = self.device.shared(); + let past = lock(&shared.textures.first_moves.staging).push(work); + shared.counts.staging_copy_queued(); + if past || self.handed_out() { + self.device.flush_staging_waited()?; + } Ok(true) } /// Copy the image's texels `copy` reaches, `len` bytes laid out as `copy` writes them to a - /// buffer, on the staging queue, and hand them to `take` where they lie, in the staging - /// buffer; the image [takes staging copies](Self::takes_staging_copies). Whether it did: not - /// while it presents a stand-in. + /// buffer, on the staging queue, after the copies queued for it there, and hand them to + /// `take` where they lie, in the staging buffer; the image [takes staging + /// copies](Self::takes_staging_copies). Whether it did: not while it presents a stand-in. pub(super) fn staging_read( &self, copy: vk::BufferImageCopy, @@ -120,7 +434,7 @@ impl Image { } let mut staging = Staging::new(&self.device, len)?; let (buffer, image) = (staging.raw, self.raw.get()); - self.device.submit_staging(|raw, command_buffer, _| { + let read = |raw: &ash::Device, command_buffer: vk::CommandBuffer| { transfer_barrier(raw, command_buffer, true); // SAFETY: the staging command buffer is recording; the staging buffer and the image // are live (the detach lock keeps the image's own `VkImage` presented), and the image @@ -135,7 +449,12 @@ impl Image { ); } transfer_barrier(raw, command_buffer, false); - })?; + }; + let Some(flushed) = self.device.submit_queued(Some(read))? else { + unreachable!("a submission with a read is made"); + }; + self.device.wait_staging(flushed.value)?; + drop(flushed); drop(detached); take(staging.bytes()); Ok(true) diff --git a/crates/metal2vulkan-runtime/src/texture/storage_form.rs b/crates/metal2vulkan-runtime/src/texture/storage_form.rs index 899ba7ca3..de13789ba 100644 --- a/crates/metal2vulkan-runtime/src/texture/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/texture/storage_form.rs @@ -257,6 +257,12 @@ impl Drop for Riding { impl Image { /// The `VkImage`, handed out: the image keeps it for good (it takes no storage form after). + /// Whether its `VkImage` was handed out (`Texture::vk_image`): the caller may use it + /// anywhere from then on, unseen. + pub(super) fn handed_out(&self) -> bool { + self.form.exported.load(Ordering::Relaxed) + } + fn export(&self) -> vk::Image { let _views = lock(&self.views); self.form.exported.store(true, Ordering::Relaxed); diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 2764b9399..74267faa3 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -244,6 +244,9 @@ pub(crate) struct Counters { texel_shadow_reads: AtomicU64, texel_shadows_dropped: AtomicU64, staging_submissions: AtomicU64, + staging_copies_queued: AtomicU64, + staging_flushes: AtomicU64, + staging_gpu_waits: AtomicU64, uncached_host_images: AtomicU64, cpu_block_decodes: AtomicU64, block_decode_passes: AtomicU64, @@ -1767,6 +1770,23 @@ impl Counters { self.staging_submissions.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) { + self.staging_copies_queued.fetch_add(1, Ordering::Relaxed); + } + + /// A staging submission carried queued copies (`texture/staging_copy.rs`). + pub(crate) fn staging_flush(&self) { + self.staging_flushes.fetch_add(1, Ordering::Relaxed); + } + + /// A submission of the device's waited on the GPU for a staging submission the host had not + /// seen complete (`device/staging.rs`). + pub(crate) fn staging_gpu_wait(&self) { + self.staging_gpu_waits.fetch_add(1, Ordering::Relaxed); + } + /// A texture's host-transfer image was placed in memory the host does not cache /// (`memory::host_cached_placement`). pub(crate) fn uncached_host_image(&self) { @@ -4576,10 +4596,23 @@ pub struct WorkCounts { /// texture's texels (`texture/host_shadow.rs`): a commit of the program's, its own Vulkan /// submission, another `VkImage` presented, or a detach. pub texel_shadows_dropped: u64, - /// Submissions on the device's staging queue (`device/staging.rs`), each one a host call - /// waits for: a `Shared` or `Managed` texture's first move, `replace_region` or `get_bytes` - /// on a device that copies none on the host from memory the host caches. + /// Submissions on the device's staging queue (`device/staging.rs`): a `Shared` or `Managed` + /// texture's first move, a `get_bytes`, or the copies queued for it + /// (`staging_copies_queued`), on a device that copies none on the host from memory the host + /// caches. pub staging_submissions: 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, + /// Staging submissions that carried queued copies: one per burst of them, made before the + /// device's next batch or internal submission, or by a `get_bytes` before its read, a + /// texture's `VkImage` handed out, the program's use of a `VkQueue`, or past the bound + /// (`texture/staging_copy.rs`). + pub staging_flushes: u64, + /// Batches and internal submissions that waited on the GPU for a staging submission the host + /// had not seen complete (`Device::staging_wait`, `device/staging.rs`), in place of a wait on + /// the host. + pub staging_gpu_waits: u64, /// New `Shared` and `Managed` textures' images with host-transfer usage placed in memory the /// host does not cache, where the device has none the image may take /// (`texture/host_copy.rs`): their host copies read at uncached memory's speed (a 1080p @@ -6162,6 +6195,9 @@ 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), + staging_copies_queued: counters.staging_copies_queued.load(Ordering::Relaxed), + staging_flushes: counters.staging_flushes.load(Ordering::Relaxed), + staging_gpu_waits: counters.staging_gpu_waits.load(Ordering::Relaxed), uncached_host_images: counters.uncached_host_images.load(Ordering::Relaxed), cpu_block_decodes: counters.cpu_block_decodes.load(Ordering::Relaxed), block_decode_passes: counters.block_decode_passes.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 53c35805f..d7ea98b4f 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -799,6 +799,8 @@ mod stage_in_regions; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod stage_in_strides; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod staging_batches; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod state_ids; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod steps_apart; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs index 38b2168bc..5bd99c57c 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs @@ -498,7 +498,7 @@ fn astc_cpu_writes_decode_on_the_cpu() { target.replace_region(whole, 0, 0, &blocks, row, 0).unwrap(); let after = device.work_counts(); let routed = after.host_texel_copies > before.host_texel_copies - || after.staging_submissions > before.staging_submissions; + || after.staging_copies_queued > before.staging_copies_queued; let out = buffer_with(device, &[0; 16 * 16 * 16]).unwrap(); let reads = read_after(&queue, &state, &target, &out, None); reads.wait_until_completed_for(WAIT).unwrap(); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/compressed_decode.rs b/crates/metal2vulkan-validation/src/runtime_lane/compressed_decode.rs index ab7b0cb0c..718d23967 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/compressed_decode.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/compressed_decode.rs @@ -1244,7 +1244,7 @@ fn writes_behind_work_in_flight_read_the_new_blocks() { let after = device.work_counts(); let cpu = after.cpu_block_decodes - before.cpu_block_decodes; let hosted = after.host_texel_copies > before.host_texel_copies; - let staged = after.staging_submissions > before.staging_submissions; + let staged = after.staging_copies_queued > before.staging_copies_queued; let route = match (hosted, staged) { (true, _) => "on the host", (false, true) => "on the staging queue", diff --git a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs index 4afab104d..af0b8ffe8 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs @@ -1510,7 +1510,8 @@ fn shared_textures_copy_on_the_host_while_the_gpu_is_busy() { ); assert_eq!(copied.host_texel_copies - before.host_texel_copies, 3); } - // On the staging queue each copy waits for its own submission alone. + // On the staging queue each read waits for its own submission alone, the second + // carrying the write queued before it. if staged { assert_eq!( (read_mark_then, write_mark_then), @@ -1522,7 +1523,9 @@ fn shared_textures_copy_on_the_host_while_the_gpu_is_busy() { copied.internal_submissions, before.internal_submissions, "{mode:?} on {name}: a staging copy made an internal submission" ); - assert_eq!(copied.staging_submissions - made.staging_submissions, 3); + assert_eq!(copied.staging_submissions - made.staging_submissions, 2); + assert_eq!(copied.staging_copies_queued - made.staging_copies_queued, 1); + assert_eq!(copied.staging_flushes - made.staging_flushes, 1); } release(&mark); busy_work.wait_until_completed_for(WAIT).unwrap(); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/staging_batches.rs b/crates/metal2vulkan-validation/src/runtime_lane/staging_batches.rs new file mode 100644 index 000000000..0b9e31bf2 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/staging_batches.rs @@ -0,0 +1,465 @@ +//! Bursts of host calls on `Shared` and `Managed` color textures, as a guest process makes them at +//! its start (the consumer's Safari GPU process: 1776 `replaceRegion`s back to back), on whichever +//! path the device copies through: on the host (`texture/host_copy.rs` in the runtime), or on its +//! staging queue (`texture/staging_copy.rs`), where a burst's copies are queued and carried by one +//! submission there. Metal's contract holds either way, and each test checks it: +//! +//! - the call copies the caller's bytes before it returns: the caller may change or free them; +//! - every later command buffer's GPU use of the texture sees them, through the texture or a view +//! of it; +//! - every CPU read sees them, through the texture or a view; +//! - overlapping writes into one texture keep their order. +//! +//! Where the device copies on its staging queue, the counts show the batching +//! (`WorkCounts::staging_copies_queued`, `staging_flushes`, `staging_gpu_waits`): no submission +//! during a burst, one that carries it all, waited for on the GPU by the batch that reads it. +//! Each test prints the path it saw (`STAGING-BATCH` lines). + +use super::host_memory::on_device; +use super::read_buffer; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan_runtime::{ + BlitOption, Buffer, CommandBuffer, CpuCacheMode, Device, HazardTrackingMode, HostBytes, Origin, + Region, ResourceOptions, Size, StorageMode, Texture, TextureDescriptor, WorkCounts, +}; +use std::time::Duration; + +/// The longest a command buffer here may take. +const WAIT: Duration = Duration::from_secs(60); + +/// The staging queue's bound on the copies queued for one submission (`STAGED_COPIES`). +const STAGED_COPIES: usize = 4096; + +fn managed() -> ResourceOptions { + ResourceOptions::new( + StorageMode::Managed, + CpuCacheMode::DefaultCache, + HazardTrackingMode::Default, + ) +} + +/// A 2D texture of `format`, `side` texels square, sampled, of `options`. +fn texture(device: &Device, format: PixelFormat, side: u64, options: ResourceOptions) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(format, side, side, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = options; + device.new_texture(&descriptor).unwrap() +} + +/// `side`² 4-byte texels: byte `i` is `i * 7 + seed` modulo 251. +fn texels(side: u64, seed: u64) -> Vec { + (0..4 * side * side) + .map(|i| ((i * 7 + seed) % 251) as u8) + .collect() +} + +/// The whole first level of a texture `side` square, read back by `get_bytes`. +fn read_back(texture: &Texture, side: u64) -> Vec { + let mut bytes = vec![0xee; (4 * side * side) as usize]; + let region = Region::new_2d(0, 0, side, side); + texture + .get_bytes(&mut bytes, 4 * side, 0, region, 0, 0) + .unwrap(); + bytes +} + +/// A buffer `command_buffer` fills with `texture`'s first level by a blit, `side` square. +fn copy_out(command_buffer: &CommandBuffer, texture: &Texture, side: u64) -> Buffer { + let device = command_buffer.device(); + let out = device + .new_buffer(4 * side * side, ResourceOptions::shared()) + .unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(side, side, 1), + &out, + 0, + 4 * side, + 0, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + out +} + +/// The counts that tell the path apart: host copies, staging submissions, copies queued for the +/// staging queue, staging submissions that carried them, GPU waits for them, internal +/// submissions. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Path { + host: u64, + staging: u64, + queued: u64, + flushes: u64, + gpu_waits: u64, + internal: u64, +} + +impl Path { + fn between(before: &WorkCounts, after: &WorkCounts) -> Path { + Path { + host: after.host_texel_copies - before.host_texel_copies, + staging: after.staging_submissions - before.staging_submissions, + queued: after.staging_copies_queued - before.staging_copies_queued, + flushes: after.staging_flushes - before.staging_flushes, + gpu_waits: after.staging_gpu_waits - before.staging_gpu_waits, + internal: after.internal_submissions - before.internal_submissions, + } + } + + /// The path a burst of `calls` writes took, said. + fn said(&self, calls: usize) -> &'static str { + match (self.host as usize == calls, self.queued as usize == calls) { + (true, _) => "copied on the host", + (false, true) => "queued for the staging queue", + _ => "copied through submissions", + } + } +} + +/// 1776 `replace_region`s back to back, each into a `Managed` texture of its own of +/// `RGBA8Unorm` or `BGRA8Unorm`, 16 to 256 texels square, from the caller's bytes at a pointer +/// (`replace_region_with_host_bytes`, the consumer's call): a later command buffer's blits read +/// every texture's bytes, and so does `get_bytes`. Where the device copies on its staging queue, +/// the burst made no submission, and the command buffer's batch made one there that carried all +/// 1776, which it waited for on the GPU. +#[test] +fn a_burst_of_replace_regions_shares_one_staging_submission() { + const CALLS: usize = 1776; + const SHAPES: [(PixelFormat, u64); 5] = [ + (PixelFormat::RGBA8Unorm, 16), + (PixelFormat::BGRA8Unorm, 32), + (PixelFormat::RGBA8Unorm, 64), + (PixelFormat::BGRA8Unorm, 128), + (PixelFormat::RGBA8Unorm, 256), + ]; + on_device(|device| { + let name = device.name(); + let queue = device.new_command_queue().unwrap(); + let textures: Vec<(Texture, u64)> = (0..CALLS) + .map(|i| { + let (format, side) = SHAPES[i % SHAPES.len()]; + (texture(device, format, side, managed()), side) + }) + .collect(); + let written: Vec> = (0..CALLS) + .map(|i| texels(textures[i].1, i as u64)) + .collect(); + let before = device.work_counts(); + for ((texture, side), bytes) in textures.iter().zip(&written) { + let region = Region::new_2d(0, 0, *side, *side); + let host = HostBytes::from_slice(bytes); + (texture.replace_region_with_host_bytes(region, 0, 0, host, 4 * side, 0)).unwrap(); + } + let burst = Path::between(&before, &device.work_counts()); + // Every texture read by blits of one command buffer committed after the calls. + let command_buffer = queue.command_buffer().unwrap(); + let outs: Vec = (textures.iter()) + .map(|(texture, side)| copy_out(&command_buffer, texture, *side)) + .collect(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "{name}: the blits"); + let read = Path::between(&before, &device.work_counts()); + for (i, (out, bytes)) in outs.iter().zip(&written).enumerate() { + assert!( + read_buffer(out, 0, bytes.len() as u64).unwrap() == *bytes, + "{name}: the blit of texture {i} reads its replace_region's bytes" + ); + } + // And `get_bytes` of each. + for (i, ((texture, side), bytes)) in textures.iter().zip(&written).enumerate() { + assert!( + read_back(texture, *side) == *bytes, + "{name}: get_bytes of texture {i} reads its replace_region's bytes" + ); + } + println!( + "STAGING-BATCH {name}: {CALLS} replace_regions {}: the burst {burst:?}, with the \ + command buffer that read them {read:?}", + burst.said(CALLS) + ); + if burst.queued > 0 { + assert_eq!( + (burst.queued as usize, burst.staging, burst.internal), + (CALLS, 0, 0), + "{name}: a burst queued for the staging queue makes no submission" + ); + assert_eq!( + (read.staging, read.flushes), + (1, 1), + "{name}: the command buffer's batch carried the burst in one staging submission" + ); + assert!( + read.gpu_waits >= 1, + "{name}: the batch waited for the staging submission on the GPU" + ); + } + }); +} + +/// Overlapping writes into one texture keep their order, whether read by `get_bytes` or by a later +/// command buffer, through the texture or a view of it: the whole level written twice, then a +/// part of it, then a part through a view; the reads see the last whole write with the two parts +/// over it. +#[test] +fn overlapping_queued_writes_keep_their_order() { + const SIDE: u64 = 64; + on_device(|device| { + let name = device.name(); + let queue = device.new_command_queue().unwrap(); + for options in [ResourceOptions::shared(), managed()] { + let mode = options.storage_mode(); + let texture = texture(device, PixelFormat::RGBA8Unorm, SIDE, options); + let view = texture.new_texture_view(PixelFormat::RGBA8Unorm).unwrap(); + let whole = Region::new_2d(0, 0, SIDE, SIDE); + let (first, second) = (texels(SIDE, 1), texels(SIDE, 2)); + let part = Region::new_2d(8, 8, 32, 32); + let part_bytes = texels(32, 3); + let through_view = Region::new_2d(24, 24, 32, 32); + let view_bytes = texels(32, 4); + let mut wanted = second.clone(); + for (region, bytes) in [(part, &part_bytes), (through_view, &view_bytes)] { + for y in 0..32 { + let at = (4 * ((region.origin.y + y) * SIDE + region.origin.x)) as usize; + let from = (4 * y * 32) as usize; + wanted[at..at + 128].copy_from_slice(&bytes[from..from + 128]); + } + } + let before = device.work_counts(); + texture + .replace_region(whole, 0, 0, &first, 4 * SIDE, 0) + .unwrap(); + texture + .replace_region(whole, 0, 0, &second, 4 * SIDE, 0) + .unwrap(); + texture + .replace_region(part, 0, 0, &part_bytes, 128, 0) + .unwrap(); + view.replace_region(through_view, 0, 0, &view_bytes, 128, 0) + .unwrap(); + let writes = Path::between(&before, &device.work_counts()); + // A command buffer's blits of the texture and the view. + let command_buffer = queue.command_buffer().unwrap(); + let (out, view_out) = ( + copy_out(&command_buffer, &texture, SIDE), + copy_out(&command_buffer, &view, SIDE), + ); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "{mode:?} on {name}"); + let bytes = 4 * SIDE * SIDE; + assert!( + read_buffer(&out, 0, bytes).unwrap() == wanted, + "{mode:?} on {name}: a blit of the texture reads the writes in their order" + ); + assert!( + read_buffer(&view_out, 0, bytes).unwrap() == wanted, + "{mode:?} on {name}: a blit of the view reads the writes in their order" + ); + // And the CPU, with the writes made again first, read before any batch. + texture + .replace_region(whole, 0, 0, &first, 4 * SIDE, 0) + .unwrap(); + texture + .replace_region(whole, 0, 0, &second, 4 * SIDE, 0) + .unwrap(); + view.replace_region(part, 0, 0, &part_bytes, 128, 0) + .unwrap(); + texture + .replace_region(through_view, 0, 0, &view_bytes, 128, 0) + .unwrap(); + let queued = device.work_counts(); + assert!( + read_back(&view, SIDE) == wanted, + "{mode:?} on {name}: get_bytes of the view reads the writes in their order" + ); + let read = Path::between(&queued, &device.work_counts()); + assert!( + read_back(&texture, SIDE) == wanted, + "{mode:?} on {name}: get_bytes of the texture reads the writes in their order" + ); + println!( + "STAGING-BATCH {name}: {mode:?} overlapping writes {}: {writes:?}, the first \ + read after more {read:?}", + writes.said(4) + ); + if writes.queued > 0 { + assert_eq!( + (writes.queued, writes.staging), + (4, 0), + "{mode:?} on {name}" + ); + assert_eq!( + (read.staging, read.flushes), + (1, 1), + "{mode:?} on {name}: the read carried the four writes queued before it" + ); + } + } + }); +} + +/// The call copies the caller's bytes before it returns: bytes changed and freed right after the +/// call, before anything reads the texture, leave what the call was given. +#[test] +fn a_queued_write_holds_the_caller_s_bytes_as_they_were() { + const SIDE: u64 = 128; + on_device(|device| { + let name = device.name(); + let queue = device.new_command_queue().unwrap(); + let (gpu_read, cpu_read) = ( + texture(device, PixelFormat::BGRA8Unorm, SIDE, managed()), + texture(device, PixelFormat::BGRA8Unorm, SIDE, managed()), + ); + let wanted = texels(SIDE, 9); + let region = Region::new_2d(0, 0, SIDE, SIDE); + for texture in [&gpu_read, &cpu_read] { + let mut bytes = wanted.clone(); + let host = HostBytes::from_slice(&bytes); + (texture.replace_region_with_host_bytes(region, 0, 0, host, 4 * SIDE, 0)).unwrap(); + bytes.fill(0x5a); + drop(bytes); + } + let command_buffer = queue.command_buffer().unwrap(); + let out = copy_out(&command_buffer, &gpu_read, SIDE); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "{name}"); + assert!( + read_buffer(&out, 0, wanted.len() as u64).unwrap() == wanted, + "{name}: a later blit reads the bytes as the call was given them" + ); + assert!( + read_back(&cpu_read, SIDE) == wanted, + "{name}: get_bytes reads the bytes as the call was given them" + ); + }); +} + +/// Past the staging queue's bound on queued copies, the call that queues past it makes their +/// submission, waited for: a burst of `STAGED_COPIES + 4` writes into one texel makes one there +/// before anything reads it, and the read sees the last write. +#[test] +fn queued_writes_past_the_bound_are_made_by_the_call() { + const CALLS: usize = STAGED_COPIES + 4; + on_device(|device| { + let name = device.name(); + let texture = texture(device, PixelFormat::RGBA8Unorm, 4, managed()); + let texel = Region::new_2d(1, 2, 1, 1); + let before = device.work_counts(); + for i in 0..CALLS { + let bytes = (i as u32).to_le_bytes(); + texture.replace_region(texel, 0, 0, &bytes, 4, 0).unwrap(); + } + let burst = Path::between(&before, &device.work_counts()); + let mut read = [0; 4]; + texture.get_bytes(&mut read, 4, 0, texel, 0, 0).unwrap(); + assert_eq!( + u32::from_le_bytes(read), + CALLS as u32 - 1, + "{name}: the last write" + ); + println!( + "STAGING-BATCH {name}: {CALLS} writes into one texel {}: {burst:?}", + burst.said(CALLS) + ); + if burst.queued > 0 { + assert_eq!( + (burst.staging, burst.flushes), + (1, 1), + "{name}: the call past the bound made one staging submission" + ); + } + }); +} + +/// A texture let go of with its write still queued takes the write with it: the next command +/// buffer's batch submits nothing for it on the staging queue, and runs. +#[test] +fn a_texture_gone_takes_its_queued_write() { + const SIDE: u64 = 32; + on_device(|device| { + let name = device.name(); + let queue = device.new_command_queue().unwrap(); + let kept = texture(device, PixelFormat::RGBA8Unorm, SIDE, managed()); + let gone = texture(device, PixelFormat::RGBA8Unorm, SIDE, managed()); + let whole = Region::new_2d(0, 0, SIDE, SIDE); + // Settle the kept texture's own writes first. + kept.replace_region(whole, 0, 0, &texels(SIDE, 5), 4 * SIDE, 0) + .unwrap(); + assert!(read_back(&kept, SIDE) == texels(SIDE, 5), "{name}"); + let before = device.work_counts(); + gone.replace_region(whole, 0, 0, &texels(SIDE, 6), 4 * SIDE, 0) + .unwrap(); + drop(gone); + let command_buffer = queue.command_buffer().unwrap(); + let out = copy_out(&command_buffer, &kept, SIDE); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "{name}"); + assert!( + read_buffer(&out, 0, 4 * SIDE * SIDE).unwrap() == texels(SIDE, 5), + "{name}: the kept texture" + ); + let path = Path::between(&before, &device.work_counts()); + println!("STAGING-BATCH {name}: a texture gone with its write queued: {path:?}"); + if path.queued > 0 { + assert_eq!( + (path.staging, path.flushes), + (0, 0), + "{name}: nothing submitted for a texture gone" + ); + } + }); +} + +/// A texture whose `VkImage` was handed out (`Texture::vk_image`), which the caller may use on +/// its own queues unseen: the hand-out makes the copies queued before it, waited for, and each +/// later write into that texture is made by its own call, waited for. +#[test] +fn a_handed_out_texture_s_writes_are_made_by_their_calls() { + const SIDE: u64 = 32; + on_device(|device| { + let name = device.name(); + let texture = texture(device, PixelFormat::RGBA8Unorm, SIDE, managed()); + let whole = Region::new_2d(0, 0, SIDE, SIDE); + let before = device.work_counts(); + texture + .replace_region(whole, 0, 0, &texels(SIDE, 7), 4 * SIDE, 0) + .unwrap(); + // SAFETY: the handle is only compared with null; the texture outlives it. + let image = unsafe { texture.vk_image() }; + let handed = Path::between(&before, &device.work_counts()); + let later = device.work_counts(); + texture + .replace_region(whole, 0, 0, &texels(SIDE, 8), 4 * SIDE, 0) + .unwrap(); + let after = Path::between(&later, &device.work_counts()); + assert!(read_back(&texture, SIDE) == texels(SIDE, 8), "{name}"); + println!( + "STAGING-BATCH {name}: a write before a hand-out ({}) {handed:?}, after it {after:?}", + match image { + Some(_) => "handed out", + None => "no image", + } + ); + if handed.queued > 0 && image.is_some() { + assert_eq!( + (handed.staging, handed.flushes), + (1, 1), + "{name}: the hand-out made the queued write" + ); + assert_eq!( + (after.staging, after.flushes), + (1, 1), + "{name}: a handed-out texture's write is made by its call" + ); + } + }); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 9abfb3e72..c75c97ccd 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2970,6 +2970,9 @@ field metal2vulkan-runtime::WorkCounts.stage_entries_shared pub stage_entries_sh field metal2vulkan-runtime::WorkCounts.stage_entries_specialized pub stage_entries_specialized: u64 field metal2vulkan-runtime::WorkCounts.stage_tables_read pub stage_tables_read: u64 field metal2vulkan-runtime::WorkCounts.stage_tables_read_in_part pub stage_tables_read_in_part: u64 +field metal2vulkan-runtime::WorkCounts.staging_copies_queued pub staging_copies_queued: u64 +field metal2vulkan-runtime::WorkCounts.staging_flushes pub staging_flushes: u64 +field metal2vulkan-runtime::WorkCounts.staging_gpu_waits pub staging_gpu_waits: u64 field metal2vulkan-runtime::WorkCounts.staging_submissions pub staging_submissions: u64 field metal2vulkan-runtime::WorkCounts.stale_detached_reaches pub stale_detached_reaches: u64 field metal2vulkan-runtime::WorkCounts.stamped_buffers_kept pub stamped_buffers_kept: u64