Queue-switch check: a held round waits for fences of its own on its batches

Where the device's loader word was found overwritten, the check's rounds hold
the word from the gate's signal through the wait for their batches and, where
the queue's failures are relayed, for the relay's marks after them: MoltenVK
names the device as each batch's Metal command buffer completes, after the
timelines the round waits for are signalled. An adopted device's queues are
never relayed (its instance has no relay), so on an adopted MoltenVK device
whose consumer registered a messenger no mark followed the batches, and their
completion messages could come after the round let the word go.

A round started where the word was found overwritten now submits each batch
with a fence of the check's own (two, made with its other objects, released
with them) and waits for them, then resets them, before the step ends, as the
submission checks' own fences end theirs. The hold is decided once, as the
round starts. Elsewhere nothing changes: no fence is submitted.

Test: the loader-word device test settles the queue-switch check too and
asserts its held rounds waited for fences of their own exactly where the word
was overwritten and the check ran (a test-only count, QueueSwitch::fences_waited).
Not built yet.

(cherry picked from commit bdf4c1c5ffd24a425a637fc313bee46d0030db7f)
This commit is contained in:
Anees Iqbal committed 2026-11-07 11:49:38 -08:00
1 parent 01cf2d8553
commit 323265081c
4 files changed
+137 -25

No files matched your search

@@ -29,9 +29,11 @@
//! submissions: on a device whose word was found overwritten, by a restore or as a step starts
//! ([`DeviceWord::overwritten`], a fact of the device and never of its driver), the checks hold the
//! lock across each whole step of theirs that makes no use of a queue (their objects' making and
//! release) and from each submission through the wait for its completion and, where the queue's
//! failures are relayed, for the relay's mark after it ([`DeviceWord::end_step`]: the use's last
//! submission on the queue, whose Metal command buffer completes after the check's own), so the
//! release) and from each submission through the wait for its completion (each check's through a
//! fence of its own, signalled as its Metal command buffer completes: the queue-switch check's
//! timelines are signalled before) and, where the queue's failures are relayed, for the relay's
//! mark after it ([`DeviceWord::end_step`]: the use's last submission on the queue, whose Metal
//! command buffer completes after the check's own), so the
//! runtime's loader-served calls on other threads may wait for one step of theirs, once, while they
//! run (the checks run once per driver and runtime, for milliseconds); elsewhere the word never
//! changes and they hold it across their submission calls alone. A narrower hold, around the calls
@@ -353,6 +353,10 @@ pub(crate) struct QueueSwitch {
/// release of its Vulkan objects, and the drop of its shares of the device's parts.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
last_steps: [AtomicU64; 2],
/// The crate's device tests' count of the fences of the check's own its held rounds waited
/// for (`queue_switch_check.rs`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
fences_waited: AtomicU64,
}
impl QueueSwitch {
@@ -374,6 +378,8 @@ impl QueueSwitch {
held: Default::default(),
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
last_steps: Default::default(),
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
fences_waited: AtomicU64::new(0),
}
}
@@ -462,6 +468,19 @@ impl QueueSwitch {
self.last_steps[step].store(nanos.max(1), Ordering::Release);
}
/// Record that a held round of the check waited for `fences` of its own.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn waited_fences(&self, fences: usize) {
(self.fences_waited).fetch_add(fences as u64, Ordering::Relaxed);
}
/// The fences of its own the check's held rounds waited for so far
/// ([`waited_fences`](Self::waited_fences)).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn fences_waited(&self) -> u64 {
self.fences_waited.load(Ordering::Relaxed)
}
/// How long the check's last two steps took ([`timed_step`](Self::timed_step)).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn last_steps(&self) -> [Duration; 2] {
@@ -253,6 +253,13 @@ impl Parts {
unsafe { self.loader_word.step_hold(None) }
}
/// Whether the device's loader word was found overwritten (`loader_word.rs`): a round
/// started then is held whole.
fn overwritten(&self) -> bool {
// SAFETY: the device is live while its check runs (its teardown stops it first).
unsafe { self.loader_word.overwritten() }
}
/// Settle the device's verdict (`Device::settle_queue_switch`).
fn settle(&self, verdict: Verdict, cost: i64, took: Option<Duration>) {
let slots = &self.queues[..self.round_robin];
@@ -313,14 +320,15 @@ fn measure(parts: &Parts, pair: (usize, usize), made: Made) -> Result<Option<(i6
}
/// The check's Vulkan objects: its command pool and command buffers ([`Made`]), a timestamp pool
/// of two queries per batch, and its timelines: the gate, and one per `VkQueue` its batches
/// signal.
/// of two queries per batch, its timelines (the gate, and one per `VkQueue` its batches signal),
/// and a fence for each of a round's two batches, which a held round's submissions signal.
struct Objects {
pool: vk::CommandPool,
buffers: Vec<vk::CommandBuffer>,
queries: vk::QueryPool,
gate: vk::Semaphore,
done: [vk::Semaphore; 2],
fences: [vk::Fence; 2],
/// Whether every batch submitted completed (or none was submitted): only then are they
/// released (`false` once the process is exiting mid-run).
settled: bool,
@@ -341,6 +349,7 @@ impl Objects {
queries: vk::QueryPool::null(),
gate: vk::Semaphore::null(),
done: [vk::Semaphore::null(); 2],
fences: [vk::Fence::null(); 2],
settled: true,
};
let filled = objects.fill(parts);
@@ -354,8 +363,8 @@ impl Objects {
}
}
/// Make the query pool and the timelines, and record the command buffers, inside the
/// caller's section.
/// Make the query pool, the timelines and the fences, and record the command buffers, inside
/// the caller's section.
fn fill(&mut self, parts: &Parts) -> Result<(), Error> {
let raw = parts.vk();
let batches = self.buffers.len();
@@ -375,6 +384,12 @@ impl Objects {
*semaphore = unsafe { raw.create_semaphore(&info, None) }.map_err(vulkan)?;
exit_guard::called(Call::CreateSemaphore);
}
for fence in &mut self.fences {
// SAFETY: the device is live, inside a section.
*fence = unsafe { raw.create_fence(&vk::FenceCreateInfo::default(), None) }
.map_err(vulkan)?;
exit_guard::called(Call::CreateFence);
}
let begin = vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
for (batch, &buffer) in self.buffers.iter().enumerate() {
@@ -444,12 +459,16 @@ impl Objects {
done: [u64; 2],
) -> Result<bool, Error> {
self.settled = false;
// Where the device's loader word was found overwritten, held from the gate's signal
// through the wait for the batches and the relay's marks after them (`loader_word.rs`):
// MoltenVK names the device as each completes, after the timelines are signalled. Taken
// with no queue's lock held: each batch's submission takes its queue's lock and then the
// word, and lets both go.
let (submitted, refused, step, marks) = match self.submit(parts, batches, gate) {
// Where the device's loader word was found overwritten as the round starts, held from the
// gate's signal through the wait for the batches, for the check's own fences of them and
// for the relay's marks after them (`loader_word.rs`): MoltenVK names the device as each
// completes, after the timelines are signalled. It signals each fence as the batch's
// Metal command buffer completes, as the submission checks' own fences end their steps;
// where the queue's failures are not relayed (an adopted device, whose instance has no
// relay), no mark follows them. Taken with no queue's lock held: each batch's submission
// takes its queue's lock and then the word, and lets both go.
let hold = parts.overwritten();
let (submitted, refused, step, marks) = match self.submit(parts, batches, gate, hold) {
Some(answer) => answer,
None => return Ok(false),
};
@@ -458,7 +477,11 @@ impl Objects {
let lane = usize::from(batch.signal.0 != self.done[0]);
reached[lane] = reached[lane].min(batch.signal.1 - 1);
}
let waited = self.wait(parts, reached)?;
let fenced = match hold {
true => &self.fences[..submitted],
false => &[],
};
let waited = self.wait(parts, reached)? && self.wait_fences(parts, fenced)?;
parts.loader_word.end_step(step, marks);
if !waited {
return Ok(false);
@@ -472,17 +495,27 @@ impl Objects {
/// Submit `batches`, each alone on its `VkQueue`, in order until one is refused, then signal
/// the gate to `gate` from the host, inside one section: how many were submitted, the
/// refusal, the hold of the device's loader word the signal was made under where the word was
/// found overwritten, and the relay's marks after the batches, kept; `None` where the process
/// is exiting.
fn submit<'p>(&self, parts: &'p Parts, batches: &[Batch], gate: u64) -> Option<Submitted<'p>> {
/// refusal, the hold of the device's loader word the signal was made under where the round is
/// held (`hold`, each batch then signalling its fence of the check's own), and the relay's
/// marks after the batches, kept; `None` where the process is exiting.
fn submit<'p>(
&self,
parts: &'p Parts,
batches: &[Batch],
gate: u64,
hold: bool,
) -> Option<Submitted<'p>> {
let _busy = exit_guard::enter()?;
let raw = parts.vk();
let uses = parts.queue_uses();
let mut submitted = 0;
let mut refused = None;
let mut marks = Vec::new();
for batch in batches {
for (batch, &own) in batches.iter().zip(&self.fences) {
let fence = match hold {
true => own,
false => vk::Fence::null(),
};
let buffers = [batch.buffer];
let waits = [batch.wait.0];
let wait_values = [batch.wait.1];
@@ -501,7 +534,8 @@ impl Objects {
// SAFETY: the queue is used under its lock, inside a section; the command buffer is
// recorded, ended and in no other submission; each timeline's signals rise in the order
// they run (each lane's batches run in its queue's order); the gate's wait is
// signalled below. The device's loader word is held across the call and the relay's
// signalled below; the fence, where there is one, is unsignaled (made so, or reset once
// the round before signalled it) and in no pending submission. The device's loader word is held across the call and the relay's
// mark after it (MoltenVK names the device as it logs each, `loader_word.rs`), taken
// inside the queue's lock. None of the round's batches runs before the gate's signal,
// which the caller makes under the word where it was found overwritten, so none
@@ -515,7 +549,7 @@ impl Objects {
|queue| unsafe {
let held = parts.loader_word.held();
parts.counts.queue_submitted(1, 1);
(held, raw.queue_submit(queue, &[submit], vk::Fence::null()))
(held, raw.queue_submit(queue, &[submit], fence))
},
);
drop(held);
@@ -530,7 +564,10 @@ impl Objects {
let signal = vk::SemaphoreSignalInfo::default()
.semaphore(self.gate)
.value(gate);
let step = parts.step_held();
let step = match hold {
true => parts.step_held(),
false => None,
};
// SAFETY: the gate's value rises with each signal, its only signaller the host.
let signalled = unsafe { raw.signal_semaphore(&signal) };
exit_guard::called(Call::SignalSemaphore);
@@ -571,6 +608,39 @@ impl Objects {
}
}
/// Wait for `fences`, the check's own of a held round's batches submitted, a slice at a time,
/// each a section, then reset them for the next round: whether they were signalled (false
/// once the process is exiting).
fn wait_fences(&self, parts: &Parts, fences: &[vk::Fence]) -> Result<bool, Error> {
if fences.is_empty() {
return Ok(true);
}
loop {
let Some(_busy) = exit_guard::enter() else {
return Ok(false);
};
// SAFETY: the check's fences, each in a submission made.
let waited =
unsafe { (parts.vk()).wait_for_fences(fences, true, WAIT_SLICE.as_nanos() as u64) };
exit_guard::called(Call::WaitForFences);
match waited {
Ok(()) => break,
Err(vk::Result::TIMEOUT) => continue,
Err(error) => return Err(vulkan(error)),
}
}
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
parts.switch.waited_fences(fences.len());
let Some(_busy) = exit_guard::enter() else {
return Ok(false);
};
// SAFETY: each is signalled, its submission completed.
let reset = unsafe { parts.vk().reset_fences(fences) };
exit_guard::called(Call::ResetFences);
reset.map_err(vulkan)?;
Ok(true)
}
/// The median gap between batches on the two `VkQueue`s and on one, in nanoseconds, from the
/// timestamps (`Ok(None)` where fewer than [`FEWEST`] of either kind were written).
fn gaps(&self, parts: &Parts) -> Result<Option<(i64, i64)>, Error> {
@@ -655,6 +725,11 @@ impl Objects {
release::object(raw, semaphore);
}
}
for fence in self.fences {
if fence != vk::Fence::null() {
release::object(raw, fence);
}
}
if self.queries != vk::QueryPool::null() {
release::object(raw, self.queries);
}
@@ -235,7 +235,9 @@ fn immediate_tracking() -> Vec<LayerSetting> {
/// MoltenVK names the device in each message, and holds every step after its word was found
/// overwritten (its first steps among them, as the device's own calls found it so first), and,
/// where its queue's failures are relayed, waits for the relay's marks after its submissions
/// before it lets go (MoltenVK names the device as each mark completes too). The checks' threads
/// before it lets go (MoltenVK names the device as each mark completes too); the queue-switch
/// check's held rounds wait for fences of their own on their batches, which cover them where no
/// mark follows (an adopted device's queues, never relayed). The checks' threads
/// make no call the loader serves (their command buffers are made as the device is made).
/// Printed (`LOADER-WORD`): each device's steps held, the marks waited for, the restores on the
/// checks' threads and its checks' run.
@@ -267,6 +269,10 @@ fn the_checks_hold_the_loader_word_across_steps_only_where_it_was_overwritten()
device.settle_submit_checks(SETTLE),
"the checks never answered"
);
assert!(
device.settle_queue_switch_check(SETTLE),
"the queue-switch check never answered"
);
let moltenvk = device.properties().description.driver_id == Some(DriverId::MOLTENVK);
let word = &device.shared().loader_word;
// SAFETY: the device is live.
@@ -275,14 +281,18 @@ fn the_checks_hold_the_loader_word_across_steps_only_where_it_was_overwritten()
let marks = word.marks_waited();
let restores = word.check_thread_restores();
let relayed = device.shared().flights(0).is_some();
let fences = device.shared().queue_switch.fences_waited();
let counts = device.work_counts();
println!(
"LOADER-WORD on {}: MoltenVK {moltenvk}, activities logged at once {immediate}: \
overwritten {overwritten}, steps held {held}, relay's marks waited {marks} \
(relayed {relayed}), restores on the checks' threads {restores}; checks run {}: {}",
(relayed {relayed}), restores on the checks' threads {restores}; checks run {}: {}; \
queue-switch checks run {}, their own fences waited {fences}: {}",
device.name(),
counts.submit_checks_run,
device.submit_check_report()
device.submit_check_report(),
counts.queue_switch_checks_run,
device.queue_switch_check_report()
);
assert_eq!(counts.submit_checks_run, 1, "the checks did not run");
assert_eq!(
@@ -311,5 +321,11 @@ fn the_checks_hold_the_loader_word_across_steps_only_where_it_was_overwritten()
"the held steps waited for the relay's marks elsewhere than where the word was \
overwritten and the queue relayed"
);
assert_eq!(
fences > 0,
overwritten && counts.queue_switch_checks_run > 0,
"the queue-switch check's held rounds waited for fences of their own elsewhere than \
where the word was overwritten and the check ran"
);
}
}