diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 0a9c90abd..0dc70c50a 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -618,13 +618,21 @@ through its views alone, each with an index of its own, as `Device::new_texture_ a texture: the textures a consumer makes over a plane are its views. A plane's image lists, for views of another format, the formats of the texture's own list that its tiling samples, and none where the device refuses that list; a view of another format it does not list is `Gap::TextureView` of -`TextureViewKind::SurfacePixelFormat`. The images move to the general layout in a submission the -call waits for before the handle leaves, and stay in it through every copy. That wait is counted -in `Metrics::surface_waits`, with its time in `surface_wait_nanos`, the longest in +`TextureViewKind::SurfacePixelFormat`. The make submits nothing and waits for nothing: the +images move out of the undefined layout into the general one in the runtime's next submission, +and stay in it through every copy. + +**The ready point.** That move may discard what the memory holds, so the other API writes an +in-place surface's memory only once it has completed: before the other API's first write, the +consumer calls `Surface::wait_until_ready()` on its own thread, which returns once the move's +submission has completed and has that submission go at once where it is not yet made. The +runtime's own commands need no wait: the move goes ahead of every command buffer committed after +the make. In the copy form the call returns at once. Each call in place is counted in +`Metrics::surface_waits`, with its time in `surface_wait_nanos`, the longest in `surface_wait_max_nanos`, and in `surface_wait_submissions` the runtime's submissions it waited for: those not yet complete as it began, the one that moves the planes among them unless it -completed first (where another thread's submission took the moves). A wait far longer than those -submissions' GPU times waited behind work the runtime did not submit. +completed first (a submission made after the make, for any command buffer, takes the moves). A +wait far longer than those submissions' GPU times waited behind work the runtime did not submit. **The copy form** is taken where any of that fails, and the answer's `SurfaceForm::Copy` names why (`SurfaceCopy`): `NoModifier`, `Tiling`, `Dedicated`, `Pitch`, `Start` or `MemoryType`. The @@ -634,13 +642,14 @@ that the submissions copy the bytes into and back (`Metrics::over_copies`). A st driver cannot take falls to the copy form with no error: the answer's `form` is the only sign. `Metrics::surfaces_in_place` and `Metrics::surfaces_copied` count each form made. -One contract for both forms, the exported block's above. Once the other API's work that wrote the -surface has completed, the consumer calls `Surface::external_writes_done()` before it commits the -command buffers that use what was written: in place, each plane's image's acquire from the other -API's queue family, the general layout kept, one barrier in the upload; in the copy form the -block's acquire. Where the other API is to read what the runtime's commands wrote, the consumer -calls `BlitCommandEncoder::release_surface_to_external(&surface)` after the last command that -writes the planes: in place, each plane's image's release, one barrier; in the copy form the +One contract for both forms, the exported block's above, after the ready point. Once the other +API's work that wrote the surface has completed, the consumer calls +`Surface::external_writes_done()` before it commits the command buffers that use what was +written: in place, each plane's image's acquire from the other API's queue family, the general +layout kept, one barrier in the upload; in the copy form the block's acquire. Where the other +API is to read what the runtime's commands wrote, the consumer calls +`BlitCommandEncoder::release_surface_to_external(&surface)` after the last command that writes +the planes: in place, each plane's image's release, one barrier; in the copy form the block's release, the planes' images copied back first. Both count in `Metrics::external_acquires` and `Metrics::external_releases`. From a release until the consumer's next write into the surface through the runtime, the consumer encodes no read of its planes. diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 95b22ec50..b93e1637e 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -1295,9 +1295,9 @@ pub struct Metrics { /// [`SurfaceForm::Copy`](crate::SurfaceForm::Copy)). pub surfaces_copied: u64, /// Waits of surfaces made in place for the submission that moves their planes to the general - /// layout, on the making thread, before - /// [`Device::new_exported_surface`](crate::Device::new_exported_surface) returns: one per - /// surface made in place. + /// layout ([`Surface::wait_until_ready`](crate::Surface::wait_until_ready)), on the + /// consumer's thread: one per call. The make + /// ([`Device::new_exported_surface`](crate::Device::new_exported_surface)) waits for none. pub surface_waits: u64, /// The nanoseconds of [`host_time`](crate::host_time) the surface waits took, in total. pub surface_wait_nanos: u64, @@ -1306,9 +1306,10 @@ pub struct Metrics { pub surface_wait_max_nanos: u64, /// The runtime's submissions the surface waits waited for, in total: at each wait's start, /// those of the device not yet complete, through the one that moves the planes, which is - /// among them unless it had completed before the wait began (where another thread's - /// submission took the moves first). Another API's work is not counted: a wait much longer - /// than these submissions' GPU times waited behind work the runtime did not submit. + /// among them unless it had completed before the wait began (a submission made after the + /// make, for any command buffer, takes the moves). Another API's work is not counted: a wait + /// much longer than these submissions' GPU times waited behind work the runtime did not + /// submit. pub surface_wait_submissions: u64, /// `vkQueueBindSparse` calls: one for each import over several dma-bufs /// (`Device::import_dma_bufs`, on Unix), binding its imports into its buffer. Each signals a diff --git a/crates/metal2vulkan-rt/src/submit.rs b/crates/metal2vulkan-rt/src/submit.rs index bd0693c29..429a82888 100644 --- a/crates/metal2vulkan-rt/src/submit.rs +++ b/crates/metal2vulkan-rt/src/submit.rs @@ -156,6 +156,8 @@ pub(crate) struct WorkState { next_place: u64, /// The progress value of the last submission. progress: u64, + /// The progress value of the last submission that took an upload, 0 before the first. + uploaded: u64, /// Zero fills, copies and moves to a home layout recorded and not yet submitted. upload: Option, /// Textures made since the last submission, not held: the next submission's upload moves @@ -221,6 +223,9 @@ pub(crate) struct Upload { /// The staging region's spans its copies use, and their bytes. spans: Vec, span_bytes: u64, + /// Where a surface waits for the moves this upload records ([`Work::ready_point`]): set to + /// the progress value of the submission that takes it, 0 until then. + ready: Option>, } /// What an upload keeps until it retires. @@ -263,6 +268,7 @@ impl Upload { staging: 0, spans: Vec::new(), span_bytes: 0, + ready: None, }), Err(error) => { core.recorders.give_back(core, recorder); @@ -430,6 +436,7 @@ impl Work { next_seq: 0, next_place: 0, progress: 0, + uploaded: 0, upload: None, homes: Vec::new(), prune_at: HOMES_PRUNE, @@ -924,6 +931,39 @@ impl Work { value } + /// The point at which every move to a home layout recorded so far has completed, with no + /// submission of its own: the pending upload's, whose submission sets it, or where none is + /// pending, the last submission that took one. [`ready_value`](Self::ready_value) reads it. + pub(crate) fn ready_point(&self) -> Arc { + let mut state = self.lock(); + let uploaded = state.uploaded; + match &mut state.upload { + Some(upload) => Arc::clone( + upload + .ready + .get_or_insert_with(|| Arc::new(AtomicU64::new(0))), + ), + None => Arc::new(AtomicU64::new(uploaded)), + } + } + + /// The progress value at which `point` ([`ready_point`](Self::ready_point)) is reached: the + /// value of the submission that took its upload, or where that upload is still pending, the + /// next submission's, which this call has go at once ([`flush`](Self::flush)). + pub(crate) fn ready_value(&self, point: &AtomicU64) -> u64 { + let mut state = self.lock(); + // A submission takes the upload under this lock, setting the point as it does. + match point.load(Ordering::Relaxed) { + 0 => { + let value = state.flush(); + drop(state); + self.wake(); + value + } + value => value, + } + } + /// Ends `queue`'s command buffers not yet in a submission or a group with `NotRun`. A group /// it holds still goes: its command buffers are scheduled. pub(crate) fn abandon(&self, core: &Core, queue: &QueueInner) { @@ -1029,6 +1069,10 @@ impl WorkState { fn take_upload(&mut self, core: &Core, released: &AtomicU64, value: u64) -> Option { let mut upload = self.upload.take()?; released.store(0, Ordering::Relaxed); + self.uploaded = value; + if let Some(ready) = &upload.ready { + ready.store(value, Ordering::Relaxed); + } if let Some(region) = &mut self.region { for &number in &upload.spans { region.ring.set(number, At::Submitted(value)); diff --git a/crates/metal2vulkan-rt/src/surface.rs b/crates/metal2vulkan-rt/src/surface.rs index 6fab654c6..273bad552 100644 --- a/crates/metal2vulkan-rt/src/surface.rs +++ b/crates/metal2vulkan-rt/src/surface.rs @@ -32,6 +32,7 @@ use crate::submit::Held; use crate::texture::{Backing, SurfaceImage, Texture, TextureDescriptor, TextureObject}; use crate::times::host_time; use ash::vk; +use std::sync::atomic::AtomicU64; use std::sync::{Arc, Mutex}; /// The most planes a surface has: a DRM format's memory planes. @@ -156,6 +157,10 @@ pub struct Surface { handle: Option, planes: Vec, kind: Kind, + /// In place, where the planes' moves to the general layout complete + /// ([`Surface::wait_until_ready`]); `None` in the copy form, whose images the other API + /// never reaches, and for a Direct3D 11 import, whose images are general as imported. + ready: Option>, } /// The surface's form, and what its buffer is ([`Surface::buffer`]). @@ -587,9 +592,10 @@ impl Device { /// /// **Form.** In place where the device's queries and the images made hold the layout exactly /// (the crate's guide says what each handle asks); else the copy form, whose reason the - /// answer names, laid alike at the tightest pitch the multiples allow. Decided at the make: - /// each plane's image in place moves to the general layout in a submission the call waits - /// for, before the handle leaves. Each form counts in + /// answer names, laid alike at the tightest pitch the multiples allow. Decided at the make. + /// The call makes no submission and waits for nothing: each plane's image in place moves to + /// the general layout in the runtime's next submission, and the other API's first write into + /// the memory waits for it ([`Surface::wait_until_ready`]). Each form counts in /// [`Metrics::surfaces_in_place`](crate::Metrics::surfaces_in_place) or /// [`Metrics::surfaces_copied`](crate::Metrics::surfaces_copied). /// @@ -667,18 +673,9 @@ impl Device { } } } - // The images move to the general layout before the handle leaves. The progress reached - // is read before the flush wakes the submit thread: a submission it then makes, the - // moves' among them, cannot have completed by the read, so it is counted. - let began = host_time(); - // SAFETY: the progress semaphore is the device's, live while the core is. - let reached = unsafe { core.device.get_semaphore_counter_value(core.done.progress) } - .map_err(Error::vulkan("vkGetSemaphoreCounterValue"))?; - let value = core.work.flush(); - core.done.wait(core, value)?; - let waited = host_time().saturating_sub(began); - core.counters - .surface_wait(waited, value.saturating_sub(reached)); + // The images move to the general layout in the next submission, which the make does not + // wait for: the consumer waits for it on its own thread (`Surface::wait_until_ready`). + let ready = Some(core.work.ready_point()); core.counters.count(Metric::SurfacesInPlace); let view = View { unit, @@ -690,6 +687,7 @@ impl Device { handle: Some(handle), planes, kind: Kind::InPlace(view), + ready, }; let export = SurfaceExport { export: made.export, @@ -737,6 +735,7 @@ impl Device { handle: Some(spec.handle), planes, kind: Kind::Copy(block, buffer), + ready: None, }; let export = SurfaceExport { export, @@ -1190,6 +1189,7 @@ impl Surface { handle: None, planes, kind: Kind::Imported, + ready: None, } } @@ -1330,6 +1330,49 @@ impl Surface { Ok(buffer) } + /// No Metal counterpart: waits until the surface's memory is the other API's to write, on + /// the calling thread, the consumer's own. Metal has no such wait: an IOSurface's planes are + /// ready as it is made. + /// + /// In place, each plane's image moves out of the undefined layout into the general one in + /// the runtime's first submission after the make, which + /// [`Device::new_exported_surface`] does not wait for; that move may discard what the memory + /// holds, so the other API's first write into the memory comes after it. The call returns + /// once that submission has completed, and has it go at once where it is not yet made. The + /// runtime's own commands need no such wait: the move goes ahead of every command buffer + /// committed after the make. In the copy form, whose planes' images the other API never + /// reaches, and for a Direct3D 11 import + /// ([`Device::import_d3d11_surface`](crate::Device::import_d3d11_surface)), whose images are + /// general as imported, the call returns at once. Each call in place counts in + /// [`Metrics::surface_waits`](crate::Metrics::surface_waits), with its time and the + /// submissions it waited for. + /// + /// Err: [`Refusal::InScheduledHandler`] in a scheduled handler; [`Error::Quiesced`]; + /// [`Error::Vulkan`] where the device is lost first or the progress semaphore cannot be read. + pub fn wait_until_ready(&self) -> Result<(), Error> { + let Some(ready) = &self.ready else { + return Ok(()); + }; + crate::command::not_in_scheduled_handler()?; + let core = self.device.core(); + if core.closed() { + return Err(Error::Quiesced); + } + // The progress reached is read before `ready_value` can wake the submit thread: a + // submission it then makes, the moves' among them, cannot have completed by the read, so + // it is counted. + let began = host_time(); + // SAFETY: the progress semaphore is the device's, live while the core is. + let reached = unsafe { core.device.get_semaphore_counter_value(core.done.progress) } + .map_err(Error::vulkan("vkGetSemaphoreCounterValue"))?; + let value = core.work.ready_value(ready); + core.done.wait(core, value)?; + let waited = host_time().saturating_sub(began); + core.counters + .surface_wait(waited, value.saturating_sub(reached)); + Ok(()) + } + /// No Metal counterpart: the other API's writes into this surface are done, and the /// runtime's commands may now read and write its planes, as /// [`Block::external_writes_done`] is for a block. The consumer calls it once the other API's diff --git a/crates/metal2vulkan-rt/src/tests/surface.rs b/crates/metal2vulkan-rt/src/tests/surface.rs index faabea27e..515fd5d1c 100644 --- a/crates/metal2vulkan-rt/src/tests/surface.rs +++ b/crates/metal2vulkan-rt/src/tests/surface.rs @@ -526,9 +526,21 @@ mod on_device { let made = began.elapsed(); let form = export.form; let after = counters.metrics(); - let waited = after.surface_waits - before.surface_waits; - let wait_nanos = after.surface_wait_nanos - before.surface_wait_nanos; - let behind = after.surface_wait_submissions - before.surface_wait_submissions; + // The make submits nothing and waits for nothing. + assert_eq!( + (after.submissions, after.surface_waits), + (before.submissions, before.surface_waits), + "{label}: the make's submissions and waits" + ); + // The other API's first write waits for the planes' moves. + let began = Instant::now(); + (surface.wait_until_ready()) + .unwrap_or_else(|error| panic!("{label}: the ready wait: {error}")); + let readied = began.elapsed(); + let ready = counters.metrics(); + let waited = ready.surface_waits - after.surface_waits; + let wait_nanos = ready.surface_wait_nanos - after.surface_wait_nanos; + let behind = ready.surface_wait_submissions - after.surface_wait_submissions; match form { SurfaceForm::InPlace => { assert_eq!( @@ -536,18 +548,22 @@ mod on_device { before.surfaces_in_place + 1, "{label}" ); - // The make waits once, for at least the submission of the moves: - // nothing else submits here, so the moves are still pending at the - // make's flush, and their submission, made after the wait began, is - // counted, however fast the device completes it. - assert_eq!(waited, 1, "{label}: the make's wait counted"); + // The ready wait waits once, for the submission of the moves, which + // it has go: nothing else submits here, so the moves are still + // pending at its flush, and their submission, made after the wait + // began, is counted, however fast the device completes it. + assert_eq!(waited, 1, "{label}: the ready wait counted"); assert!(behind >= 1, "{label}: {behind} submissions waited for"); assert!( - wait_nanos <= made.as_nanos() as u64, - "{label}: the wait's {wait_nanos} ns within the make's {made:?}" + ready.submissions > after.submissions, + "{label}: the moves' submission made by the ready wait" ); assert!( - after.surface_wait_max_nanos >= wait_nanos, + wait_nanos <= readied.as_nanos() as u64, + "{label}: the wait's {wait_nanos} ns within the call's {readied:?}" + ); + assert!( + ready.surface_wait_max_nanos >= wait_nanos, "{label}: the longest wait" ); } @@ -560,7 +576,7 @@ mod on_device { assert_eq!( (waited, wait_nanos, behind), (0, 0, 0), - "{label}: the copy form's make waits for nothing" + "{label}: the copy form's ready wait waits for nothing" ); } } @@ -568,11 +584,12 @@ mod on_device { let flags = flag_names(kinds.memory_types_as_slice()[index as usize].property_flags); println!( - "surface: {label}: form {form:?}, pitch {}, plane 1 at {}, size {}, memory type {index} ({flags}), made in {:.3} ms, its wait {:.3} ms for {behind} submissions", + "surface: {label}: form {form:?}, pitch {}, plane 1 at {}, size {}, memory type {index} ({flags}), made in {:.3} ms, ready {:.3} ms later, its wait {:.3} ms for {behind} submissions", export.planes[0].row_pitch, export.planes[1].offset, export.export.size, made.as_secs_f64() * 1e3, + readied.as_secs_f64() * 1e3, wait_nanos as f64 / 1e6 ); check_layout(&label, row, planes, &export); @@ -1109,9 +1126,9 @@ mod on_device { /// A surface make behind a busy queue: for each row the device exports, fills of a 256 MiB /// Private buffer committed back to back until about 100 ms of the GPU's work is ahead, then - /// a 1080p NV12 surface made at once. Printed: the make's time, the surface waits it counted - /// with their time and the submissions they waited for, and when the last fill completed, - /// from the make's start. + /// a 1080p NV12 surface made at once, which waits for nothing, and its ready wait. Printed: + /// the make's time, when the surface was ready, the ready wait's time and the submissions it + /// waited for, and when the last fill completed, each from the make's start. #[test] fn every_device_times_a_surface_make_behind_a_busy_queue() { each_device("surface_busy", |name, _, device| { @@ -1167,19 +1184,30 @@ mod on_device { .unwrap_or_else(|error| panic!("{label}: {error}")); let made = began.elapsed(); let after = counters.metrics(); + assert_eq!( + after.surface_waits, before.surface_waits, + "{label}: the make waits for nothing" + ); + (surface.wait_until_ready()) + .unwrap_or_else(|error| panic!("{label}: the ready wait: {error}")); + let readied = began.elapsed(); + let ready = counters.metrics(); let last = fills.last().expect("a fill"); finished(&label, last); let drained = began.elapsed(); println!( "surface-busy: {label}: {count} fills ahead ({:.3} ms each alone), form {:?}: \ - the make {:.3} ms, {} surface waits of {:.3} ms for {} submissions; the last \ - fill done {:.3} ms after the make began", + the make {:.3} ms, {} surface waits in it; ready {:.3} ms after the make \ + began, {} surface waits of {:.3} ms for {} submissions; the last fill done \ + {:.3} ms after the make began", each.as_secs_f64() * 1e3, export.form, made.as_secs_f64() * 1e3, after.surface_waits - before.surface_waits, - (after.surface_wait_nanos - before.surface_wait_nanos) as f64 / 1e6, - after.surface_wait_submissions - before.surface_wait_submissions, + readied.as_secs_f64() * 1e3, + ready.surface_waits - after.surface_waits, + (ready.surface_wait_nanos - after.surface_wait_nanos) as f64 / 1e6, + ready.surface_wait_submissions - after.surface_wait_submissions, drained.as_secs_f64() * 1e3, ); for command_buffer in &fills { diff --git a/crates/metal2vulkan-rt/src/texture.rs b/crates/metal2vulkan-rt/src/texture.rs index d6facb344..6dbfbc589 100644 --- a/crates/metal2vulkan-rt/src/texture.rs +++ b/crates/metal2vulkan-rt/src/texture.rs @@ -4423,11 +4423,11 @@ impl Device { } /// The texture of a surface plane's image, at `index` as for [`Device::new_texture`]: its - /// home layout general, from undefined in the next upload, which the surface's make submits - /// and waits for, or already general where the image is (a Direct3D 11 texture's). Its - /// format is the descriptor's, a view of the image's own where they differ. The texture holds - /// the image, which its drop frees with its memory. It takes `unit`'s id in the hazard sets, - /// the surface's ([`HeapId::unit`]). + /// home layout general, from undefined in the next upload, which goes ahead of every command + /// buffer committed after the make, or already general where the image is (a Direct3D 11 + /// texture's). Its format is the descriptor's, a view of the image's own where they differ. + /// The texture holds the image, which its drop frees with its memory. It takes `unit`'s id in + /// the hazard sets, the surface's ([`HeapId::unit`]). /// /// Err: [`Refusal::TextureIndex`]; [`Gap::SurfaceUsage`] for a usage the texture's uses ask /// that the image lacks; [`Error::Vulkan`] where a view cannot be made; what the texture's @@ -4517,8 +4517,8 @@ impl Device { Some(index) => { let sampled = sampled.map(|view| (view, home)); // SAFETY: the texture's views are live; its image is in its home layout whenever - // work uses it: the waited upload of its make goes first, or it is general after - // the other API's access. + // work uses it: the upload that moves it goes ahead of that work, or it is general + // after the other API's access. let owner = unsafe { (core.arrays).place_texture( &core.device, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index c12e3d12e..36a5bca72 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -9816,6 +9816,7 @@ method metal2vulkan-rt::Surface::buffer pub fn buffer(&self) -> Result Result<(), Error> method metal2vulkan-rt::Surface::handle pub fn handle(&self) -> Option method metal2vulkan-rt::Surface::planes pub fn planes(&self) -> &[Texture] +method metal2vulkan-rt::Surface::wait_until_ready pub fn wait_until_ready(&self) -> Result<(), Error> method metal2vulkan-rt::Texture::descriptor pub fn descriptor(&self) -> &TextureDescriptor method metal2vulkan-rt::Texture::drawable_acquired pub unsafe fn drawable_acquired(&self) -> Result<(), Error> method metal2vulkan-rt::Texture::get_bytes pub fn get_bytes(&self, bytes: &mut [u8], bytes_per_row: u64, bytes_per_image: u64, region: Region, level: u32, slice: u32) -> Result<(), Error>