diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index c06021ada..5887bc24c 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -5553,13 +5553,10 @@ impl CommandBufferShared { /// queue's command buffer that waits for its later signal go meanwhile, where Metal schedules /// both at once (`queue_turns.rs`, "Whole command buffers"). pub(crate) fn held_for_turn(&self, index: usize) -> Option<(usize, u64, Option)> { - if index > 0 || self.queue.unshared() || self.device.is_lost() { + if index > 0 || self.device.is_lost() || !self.takes_turns() { return None; } let index = self.queue.vk_queue(); - if !self.device.takes_turns_on(index) { - return None; - } let shared = self.device.shared(); let slot = &shared.queues[index]; let own = (self.queue.id(), &**self.queue.expected()); @@ -5573,6 +5570,26 @@ impl CommandBufferShared { } } + /// Whether `reaches` holds for an event signal of batch `index` or a later one, given its event + /// and value (`scheduler/mod.rs`'s `mark_awaited_signals`). + pub(crate) fn signals_any_from( + &self, + index: usize, + mut reaches: impl FnMut(&Arc, u64) -> bool, + ) -> bool { + let state = lock(&self.state); + let batches = state.batches.all(); + (batches.get(index..).unwrap_or_default().iter()) + .flat_map(|batch| &batch.signals) + .any(|(event, value)| reaches(event, *value)) + } + + /// Whether its batches take turns on their `VkQueue` (`queue_turns.rs`): its queue is not + /// unshared, and the device's queues take turns on a `VkQueue` other command queues share. + pub(crate) fn takes_turns(&self) -> bool { + !self.queue.unshared() && self.device.takes_turns_on(self.queue.vk_queue()) + } + /// Whether a batch of it goes before other queues' batches a pass finds ready with it /// (`scheduler/order.rs`, "Heads put first"): its queue is unshared, and its `VkQueue` holds /// other queues' work back for it (`unshared_hold.rs`). diff --git a/crates/metal2vulkan-runtime/src/queue_turns.rs b/crates/metal2vulkan-runtime/src/queue_turns.rs index 448f65d86..ae1551f1f 100644 --- a/crates/metal2vulkan-runtime/src/queue_turns.rs +++ b/crates/metal2vulkan-runtime/src/queue_turns.rs @@ -49,6 +49,15 @@ //! submitted), where Metal schedules both at once (`runtime_lane::submission_checks`: a program //! that gives the signal once the other command buffer is scheduled waited for the watchdog, //! `command_buffer/stall.rs`). +//! - **Awaited signals.** A head whose line holds a batch that signals a value another line's +//! head waits for, which no submitted signal or host set reaches yet, takes no turn +//! (`scheduler/mod.rs`'s `mark_awaited_signals`, asked at each look): holding it would hold the +//! waiting head too, the opposite of what a turn is for, and the batch of its queue in flight +//! may wait on the GPU for a signal the program gives only once that head is scheduled (the +//! caller's, `Event::reserve_vk_signal`), where Metal schedules both at once +//! (`runtime_lane::events`). Once the signal went, the line takes its turns again. Only lines +//! whose queue takes turns are read, one read of a command buffer's signals each, and only at +//! a look that found a head waiting so. //! - **When it goes.** A pass that holds such a batch leaves the scheduler's thread waiting for //! the completion that lets it go, or that makes the batch of its queue whose run does so the //! oldest on its `VkQueue` (`unshared_hold::turn_through`), not for each completion before it; diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index 65cd7a000..c5cccb3fa 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -754,6 +754,10 @@ pub(crate) struct State { /// turn there, may go there, found by the last look (`await_room`): the thread sleeps no /// later. wake_by: Option, + /// The values a look found heads waiting for that nothing submitted or set reaches, each with + /// its head's logical queue ([`mark_awaited_signals`]): emptied after each look, kept with its + /// room. + awaited: Vec<(u64, Arc, u64)>, } impl State { @@ -884,6 +888,10 @@ struct Held { /// `VkQueue` (`SlotShare::posted_unshared`): it holds another queue's batch there whose room /// came after it was posted while it is on its way ([`unshared_on_their_way`]). unshared_place: Option, + /// Where it leads its line, a batch of the line signals a value another line's head waits for + /// that no submitted signal or host set reaches yet, as this pass's look found + /// ([`mark_awaited_signals`]): it takes no turn (`queue_turns.rs`, "Awaited signals"). + signals_awaited: bool, } impl Held { @@ -960,6 +968,7 @@ impl Scheduler { lists: BatchLists::default(), group: Group::default(), grouped: Vec::new(), + awaited: Vec::new(), }), sleep: Mutex::new(Sleep::default()), wake: Condvar::new(), @@ -1783,6 +1792,7 @@ fn take_in(state: &mut State, commits: &mut Vec, spent: &mut Spent) - held_since: None, unshared_noted: None, unshared_place: unshared.map(|(_, place)| place), + signals_awaited: false, }); // Where the device notes queue times, a command buffer committed to an empty line is // its head as it is taken in. @@ -1983,6 +1993,8 @@ fn submit_ready( let busy = exit_guard::enter().ok_or(Exiting)?; // What the heads wait for from the GPU is found again by this pass's looks. awaits.clear(); + // The heads whose lines signal what another line's head waits for take no turn. + mark_awaited_signals(&mut state.order, &mut state.awaited); // The heads that wait behind a batch committed before them that keeps its place: no step, // check or submission of theirs before it is submitted (`order.rs`). // Of those whose host step or checks may start (`gate_heads`, `check_heads`), and of the @@ -2039,8 +2051,12 @@ fn submit_ready( } // Held back from a `VkQueue` it shares with other command queues, while its own // queue's work enough is in flight there (`queue_turns.rs`): another queue's later - // commit goes ahead of it. - if let Some(room) = held.buffer.held_for_turn(held.index) { + // commit goes ahead of it. Not where another line's head waits for its line's signal. + let turn = match held.signals_awaited { + true => None, + false => held.buffer.held_for_turn(held.index), + }; + if let Some(room) = turn { held.held_for(HeldFor::QueueTurn); await_room(held, room, awaits, &mut room_wake); isolating = true; @@ -2276,6 +2292,49 @@ fn goes_first(held: &Held) -> bool { held.buffer.goes_ahead_of_held_work() } +/// Mark each line's head by whether a batch of its line signals a value another line's head waits +/// for that no submitted signal or host set reaches yet (`EventShared::landing`): such a head +/// takes no turn on its `VkQueue` (`queue_turns.rs`, "Awaited signals"), as holding it would hold +/// the waiting head too, and the first batch of its queue in flight may wait on the GPU for a +/// signal the program gives only once that head is scheduled. Asked again at each look, so a line +/// whose awaited signal went takes its turns again. Where no head waits so, no batch's signals are +/// read; else those of the lines whose queue takes turns, one read per command buffer (a command +/// buffer's batches lie together in its line). `awaited` holds the values meanwhile, and is left +/// empty. +fn mark_awaited_signals(order: &mut Order, awaited: &mut Vec<(u64, Arc, u64)>) { + for (queue, head) in order.line_heads() { + for (event, value) in &head.waits { + if event.landing(*value).is_none() { + awaited.push((queue, Arc::clone(event), *value)); + } + } + } + if awaited.is_empty() { + for head in order.heads_mut(&[]) { + head.signals_awaited = false; + } + return; + } + // Whether the line asked about takes turns, read at its head. + let mut turns = false; + order.mark_heads( + |queue, held, head| { + if head { + turns = held.buffer.takes_turns(); + } + turns + && (head || held.index == 0) + && held.buffer.signals_any_from(held.index, |event, value| { + (awaited.iter()).any(|(waiting, awaited, at_least)| { + *waiting != queue && Arc::ptr_eq(awaited, event) && value >= *at_least + }) + }) + }, + |head, found| head.signals_awaited = found, + ); + awaited.clear(); +} + /// A head held back from `VkQueue` `queue` for an unshared queue there (`unshared_hold.rs`), or for /// its turn there (`queue_turns.rs`), until /// the batch there of value `through` completes, the oldest in flight past the completed value the diff --git a/crates/metal2vulkan-runtime/src/scheduler/order.rs b/crates/metal2vulkan-runtime/src/scheduler/order.rs index e8cd190d1..2e32880c8 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/order.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/order.rs @@ -262,6 +262,28 @@ impl Order { .map(|(sequence, head)| (*sequence, head)) } + /// Each line's head, with its line's queue. + pub(crate) fn line_heads(&self) -> impl Iterator + '_ { + (self.lines.iter()).filter_map(|(queue, line)| line.front().map(|(_, head)| (*queue, head))) + } + + /// Give each line's head to `mark` with whether `select` holds for a batch of its line, asked + /// of them in order from the head, with the line's queue and whether the batch is the head, + /// until it holds for one. + pub(crate) fn mark_heads( + &mut self, + mut select: impl FnMut(u64, &B, bool) -> bool, + mut mark: impl FnMut(&mut B, bool), + ) { + for (queue, line) in &mut self.lines { + let found = + (line.iter().enumerate()).any(|(at, (_, batch))| select(*queue, batch, at == 0)); + if let Some((_, head)) = line.front_mut() { + mark(head, found); + } + } + } + /// The commit sequence numbers of the line heads `select` holds for. pub(crate) fn heads_where(&self, mut select: impl FnMut(&B) -> bool) -> Vec { self.lines diff --git a/crates/metal2vulkan-validation/src/runtime_lane/events.rs b/crates/metal2vulkan-validation/src/runtime_lane/events.rs index 5e31cd73f..e7d14235b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/events.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/events.rs @@ -14,13 +14,14 @@ use super::{ run_with, validated_device_with, validated_plan_options, Messages, ScratchCache, }; use crate::gpu::TEST_DEVICE; +use ash::vk; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan_runtime::DeviceOptions; use metal2vulkan_runtime::{ host_time, BlitCommandEncoder, BlitOption, Buffer, CommandBuffer, CommandBufferStatus, - CommandQueue, CommitFailure, CpuCacheMode, Device, Error, EventRef, HazardTrackingMode, + CommandQueue, CommitFailure, CpuCacheMode, Device, Error, Event, EventRef, HazardTrackingMode, Invalid, Origin, Problem, ResourceOptions, RuntimeGap, SharedEvent, SharedEventListener, Size, - StorageMode, Texture, TextureDescriptor, + StorageMode, Texture, TextureDescriptor, VkEventSignal, }; use std::sync::mpsc; use std::sync::{Arc, Mutex}; @@ -558,6 +559,134 @@ fn a_held_command_buffer_holds_back_only_its_own_queue() { }); } +/// A plain event's first signal, the test's own (`Event::reserve_vk_signal`), given from the host +/// once: by [`open`](Gate::open), or as it drops, so no command buffer waits for it for good. +struct Gate { + device: Device, + event: Event, + counter: u64, + opened: bool, +} + +impl Gate { + fn new(device: &Device) -> Gate { + let event = device.new_event().unwrap(); + // SAFETY: the one signal of the reservation is given once, from the host, by `open`: a + // fresh event's first, so after nothing. + let reserved = unsafe { event.reserve_vk_signal(1) }.unwrap(); + let VkEventSignal::Counter { + counter, + after: None, + } = reserved + else { + panic!("a fresh event's first signal reserved as {reserved:?}"); + }; + Gate { + device: device.clone(), + event, + counter, + opened: false, + } + } + + /// Give the reserved signal from the host, once. + fn open(&mut self) -> Result<(), vk::Result> { + if self.opened { + return Ok(()); + } + self.opened = true; + let info = vk::SemaphoreSignalInfo::default() + // SAFETY: the semaphore the event holds while it lives, signalled only as reserved. + .semaphore(unsafe { self.event.vk_semaphore() }) + .value(self.counter); + // SAFETY: the reservation's one signal operation, from the host, of a semaphore of the + // live device; none of the device's objects is destroyed. + unsafe { self.device.raw().device.signal_semaphore(&info) } + } +} + +impl Drop for Gate { + fn drop(&mut self) { + if let Err(error) = self.open() { + eprintln!("the gate's signal failed as it dropped: {error}"); + } + } +} + +/// A command buffer that signals what another queue's command buffer waits for is scheduled +/// though the command buffer of its own queue before it waits on the GPU for a signal the program +/// gives only once that waiter is scheduled, as Metal schedules them all: where the queues share +/// a `VkQueue`, the signalling command buffer takes no turn there behind the earlier one +/// (`queue_turns.rs`, "Awaited signals"), which would hold the waiter until the watchdog. +#[test] +fn a_signal_another_queue_waits_for_takes_no_turn_behind_a_gpu_wait() { + on_device(|device| { + let (signalling_queue, waiting_queue) = ( + device.new_command_queue().unwrap(), + device.new_command_queue().unwrap(), + ); + let shared = signalling_queue.vk_queue_sharing().0 == waiting_queue.vk_queue_sharing().0; + let mut gate = Gate::new(device); + let waited = device.new_event().unwrap(); + let shared_buffer = || { + let buffer = device.new_buffer(16, ResourceOptions::default()).unwrap(); + fill_on_host(&buffer, 0); + buffer + }; + let (first, second, third) = (shared_buffer(), shared_buffer(), shared_buffer()); + // The first command buffer of the signalling queue waits on the GPU for the gate: a wait + // for a reserved signal goes to its `VkQueue` at once. + let gated = signalling_queue.command_buffer().unwrap(); + gated + .encode_wait_for_event(EventRef::from(&gate.event), 1) + .unwrap(); + let mut encoder = gated.blit_command_encoder().unwrap(); + encoder.fill_buffer(&first, 0..16, 1).unwrap(); + encoder.end_encoding().unwrap(); + gated.commit().unwrap(); + gated.wait_until_scheduled().unwrap(); + // The second signals what the other queue's command buffer waits for. + let signalling = blit(&signalling_queue, |encoder| { + encoder.fill_buffer(&second, 0..16, 2).unwrap() + }); + signalling + .encode_signal_event(EventRef::from(&waited), 1) + .unwrap(); + signalling.commit().unwrap(); + let waiter = waiting_queue.command_buffer().unwrap(); + waiter + .encode_wait_for_event(EventRef::from(&waited), 1) + .unwrap(); + let mut encoder = waiter.blit_command_encoder().unwrap(); + encoder.fill_buffer(&third, 0..16, 3).unwrap(); + encoder.end_encoding().unwrap(); + waiter.commit().unwrap(); + // The gate opens only once the waiter is scheduled. + let start = Instant::now(); + while waiter.status() == CommandBufferStatus::Committed && start.elapsed() < WAIT { + std::thread::sleep(Duration::from_micros(200)); + } + let scheduled = waiter.status() != CommandBufferStatus::Committed; + println!( + "AWAITED-SIGNAL one VkQueue {shared}: the waiter scheduled {scheduled} after {:?}, \ + the signalling command buffer {:?}, with the gate closed", + start.elapsed(), + signalling.status() + ); + assert!( + scheduled, + "the waiter stays committed while the gate is closed" + ); + gate.open().unwrap(); + for command_buffer in [&gated, &signalling, &waiter] { + completed(command_buffer); + } + for (buffer, byte) in [(&first, 1), (&second, 2), (&third, 3)] { + assert_eq!(bytes_of(buffer), [byte; 16]); + } + }); +} + /// The work before a wait runs and signals while the wait is pending, and the command buffer /// stays committed until its last batch goes (as measured on Metal). #[test] diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 831be9cb6..e0161f8cc 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 525; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2519; +pub const RUNTIME_VERSION: u32 = 2522; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index c1d5c464c..3a8e1c45b 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -220,7 +220,10 @@ known. The rest of the differences are docs/API.md section 9's precision notes. first batch takes a turn: its later batches (split at a mid-buffer event wait or signal) go as each is ready, as Metal schedules a command buffer whole, so a command buffer whose first batch waits on the GPU for a signal not yet given reads `Scheduled` at once, and another queue's - command buffer waiting for its later signal goes at once too. The next batch goes in + command buffer waiting for its later signal goes at once too. Nor does a head take a turn + whose line holds a batch signalling a value another queue's head waits for and nothing + submitted or set reaches yet: that queue's command buffer goes at once, as on Metal. The next + batch goes in before the one ahead ends (the scheduler's thread woken at the completion that lets it go or makes its queue's batch whose run does so the oldest, and at the time that run brings the work left under the budget, no sleep slice's), so the GPU idles for the hold only