Files
metal2vulkan/crates/metal2vulkan-runtime/src/command_buffer/gate.rs
T
Anees Iqbal bd3c50d741 Take the device's own Depth16 bias and its store of an extended-range, padded or bfloat attachment's untouched texels
The device's depth bias unit on every format, and the device's store of untouched texels in
place of the unused-bits load pass (deleted with its capture machinery); the NaN depth
discard documented as capability. SEMANTICS 1910, RUNTIME 1682.

One work packet, landed as 7 commit(s) (88bcfeaea8..6aec9db4e9 on archive/development-linear-2026-10-28-evening), in order:

* Take the device's depth bias on a Depth16Unorm depth

Rule 1: the device's depth bias is its native form, so it is the only one. A
constant bias (or a slope alone) on a Depth16Unorm depth was recorded through
VK_EXT_depth_bias_control's depthBiasExact as Metal's own rule, c + 1 units of
1/65535 for c of 0 or more and c - 1 below (one unit for a slope alone), in
depth (floatRepresentation) or in 2^-16. Now `metal::state::depth_bias` hands
Metal's constant to vkCmdSetDepthBias in the device's own unit r on every depth
format; Vulkan leaves a fixed-point format's r to the implementation, at most
2 x 2^-16 ("Depth Bias", primsrast.adoc).

Deleted, nothing reading them any more: `depth16_units`, `DepthBiasUnit` and
`DepthBias::unit`, the `depth_format` parameter of `depth_bias` and of the
runtime's `vk_depth_bias`; the runtime's vkCmdSetDepthBias2EXT path
(`DepthBiasCommand`, `depth_bias_command`, the record's pinned representation,
the device's command, its priming and `DEPTH_BIAS_CALLS`, the exit guard's and
recorder's `CmdSetDepthBias2`, `Logged::SetDepthBias2` and its thunk, so
`CommandsReplayed::cmd_set_depth_bias2` goes). VK_EXT_depth_bias_control is
still described but no longer consumed, so the core recommends enabling neither
it nor its three features.

RADV on the 780M no longer takes DriverDeviation::MetalDepth16BiasedStores: it
was measured through the exact unit. MoltenVK keeps it (it hands Metal its
constant, by construction). Elsewhere `unorm-depth-bias` announces the device's
bias; its cost text, docs/API.md's entry, the deviation and property docs and a
new FAST-PATHS device-gap row state it.

Tests: `metal::state::a_unorm_depth_bias_is_metals_constant_in_the_devices_unit`
(the constant as given on lavapipe, NVIDIA and MoltenVK, which have
depthBiasExact or not); the recommendation test leaves the extension and its
features out; the driver-facts test drops RADV's row; the exit-guard tests lose
the priming group and render_state.rs as a keeper of the device's functions.
api_signatures blessed (DepthBiasUnit, DepthBias::unit, depth_bias's signature);
the refusal surface is unchanged. Not bumped here: RUNTIME_VERSION (the versions
commit) and the runtime-sources pin (landing).

Verified: cargo clippy -p metal2vulkan -p metal2vulkan-runtime
-p metal2vulkan-validation --all-targets --all-features -D warnings; nextest of
metal::state, device::tests::{enables,driver_facts,profile}, tests::fast_paths,
api_surface, api_signatures, exit_guard, render_state, degradation_catalogue,
draw_shape_notices and ash_interop: 159 passed.

* Cite the spec that leaves a NaN fragment depth undefined, which makes its discard capability

The native-arithmetic audit asked whether `clamp_depth`'s discard of a positive NaN
depth, on every profile, emulates Metal where the device has a native form. It does
not: Vulkan defines no answer for such a depth. "Depth Clamping and Range
Adjustment" (fragops.adoc, 35.10.1): "If zf is not in the range [zmin, zmax],
then zf is undefined following this step", with or without depthClampEnable, and a
NaN lies in no range; only depthClampZeroOne, which no profile enables, keeps a
float depth unchanged (and then the comparison of a NaN would still pass ALWAYS
and NOT_EQUAL, where Metal's fails every test). So the discard stays, as
capability, and the comment says why, so a later audit does not re-raise it.

Docs only (a doc comment); no behaviour changes.

Verified: cargo fmt --all.

* Drop the cube's unmeasured gradient route from the anisotropic tests' profile comment

The route was deleted with the native cube gradients; the comment still named it as a second
home of the anisotropic emulation. Only a profile without samplerAnisotropy emulates it now.

Verified: comment only; git grep finds no other mention of the unmeasured gradient route.

* Keep the device's store of an extended-range, padded or bfloat attachment's untouched texels

What: a render pass that loads and stores a color attachment of an extended-range, padded
10-bit or bfloat format now keeps the bytes its draws do not write, the device's own load and
store (VK_ATTACHMENT_STORE_OP_STORE of a loaded attachment), on every device. The runtime no
longer reproduces Metal's tile store: the load pass that rewrote the texels' unused bits before
the pass (render/unused_bits_load.rs, bind::unused_bits_module), the capture replay that found
the tiles a pass's draws reach for it (render/capture.rs, bind::capture_assembly_module,
capture_settle_module, tile_reach_module, the translator's capture form
LoweringInputs/VariantKey::captured_positions, CaptureForm, RuntimeFact::CapturedPositions,
PushField/PushHole::CaptureAddress, Feature::TileReach, StatusBits::CAPTURED_REACH_UNMEASURED,
StatusReport::captured_reach_unmeasured) and the pipeline states' capture forms are deleted, with
ExtendedRange::load_code, Degradation::UnreachedTilesRewritten and the WorkCounts fields
unused_bits_load_passes, unused_bits_load_texels and capture_reach_*. Every draw in such a pass
announces extended-range-bits-kept, naming the attachments (render/tile_store.rs, the renamed
module); its catalogue entry, the FAST-PATHS device-gap row and the format docs state what
differs: the unused bits, BGRA10_XR's alpha clamp, a padded sRGB twin's table and a bfloat code
through half, which Metal's pass rewrites in each tile a draw reaches. snorm-minimum-kept and
shared-exponent-kept are unchanged (TileStoreIsMetals still says where the device's store is
Metal's).

The de-indexed and private list forms keep the index read the capture form shared
(PushField::CaptureIndexAddress, CaptureLayout, CapturedIndex); the binder's de-indexed draw no
longer goes through the capture draw, and the vertex function's strip restart return, which only
the capture form's layout could take (a de-indexed strip is NotImplemented(PrimitiveId)), is
gone.

Why: the owner's rule 1. The device has a native load and store; reproducing Metal's tile store
emulated Metal's bits where the device has a native form. The difference is recorded and
announced (rule 2).

Verified: cargo clippy -D warnings, all targets and features, over metal2vulkan,
metal2vulkan-runtime, metal2vulkan-validation and metal2vulkan-conformance, plain and with
--cfg m2v_gpu: clean. api_signatures blessed, REFUSALS.md regenerated. The test runs (translator
and runtime suites, the touched validation lanes on lavapipe and on the M3 Max's MoltenVK) follow
this commit and are reported with the lane.

* Bump the semantics and runtime versions for the device's tile store and depth bias

What: SEMANTICS_VERSION 1907 -> 1908 and RUNTIME_VERSION 1681 -> 1682.

Why: SEMANTICS_VERSION, because the translator's output changes under unchanged keys: the
de-indexed and private list vertex forms no longer carry the strip restart return, and the
capture form, its runtime fact and its push field are gone. RUNTIME_VERSION, because runs of
unchanged artifacts now do something else: a Depth16Unorm depth takes the device's depth bias
(no depthBiasExact or unit rescale), and a pass that loads an extended-range, padded or bfloat
attachment keeps its untouched texels' bytes (no unused-bits load pass, no capture replay) and
announces extended-range-bits-kept. ARTIFACT_FORMAT_VERSION stays: the codec tags variants by
name, and the removed ones (CaptureForm, PushField::CaptureAddress,
RuntimeFact::CapturedPositions) leave their tags unused, so an old entry holding one is a miss.

Verified: the constants alone change; the golden tables and the runtime-sources pin are
re-blessed at landing.

* Hold the lanes and the fact census to the device's store of untouched texels

What: three runtime lanes still expected Metal's tile store after 5e710fb988 made the device's
store the only form, and the mechanism test still counted the deleted
RuntimeFact::CapturedPositions.
- extended_range_blends::a_pass_of_extended_range_and_padded_colors_names_each_loaded_color:
  the padded colors, which the function does not write, keep their bytes (all ones), where
  Metal's pass leaves each word 0xffc0.
- extended_range_blends::a_fetched_two_plane_attachment_written_unblended_stores_metals_write:
  color 2, loaded and unwritten, keeps its bytes, where Metal's pass zeroes its color words' top
  two bits.
- extended_range_blend_table::a_memoryless_color_2_blends_as_a_stored_color_does: the stored
  color 0's bands are compared with the unused bits as Metal's pass leaves them
  (as_metal_leaves), the codes exactly, as the table's other passes already are.
- device::tests::mechanism: the variant census is 0..89 (MergedDraws takes the freed index).

Why: the lanes held the deleted exact form; the device's store is now the contract and
extended-range-bits-kept announces the difference.

Verified: on the M3 Max (MoltenVK, --cfg m2v_gpu, under maclock and memcap) the three lanes and
the rest of extended_range_blends pass (11 of 11, with waiter_submits, which failed once under a
load of 40 and passed on its rerun); on plain, device::tests::mechanism and tests::fast_paths
pass (12 of 12); clippy -D warnings clean, plain and --cfg m2v_gpu, over the four crates.

* Re-pin the runtime sources at the landing tip

The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-10-28 21:19:28 +02:00

270 lines
11 KiB
Rust

//! When a command buffer's waiters return: once it finished (its completed handlers ran) and the
//! runtime's threads let go of every reference they took to it.
//!
//! - **Apart from the command buffer.** The [`Gate`] is not part of what it guards, so a thread
//! lets go of its reference first and leaves the gate after: the gate never opens while a
//! runtime thread still holds the command buffer, or anything it held for it.
//! - **Why.** A program that waits for its last command buffer and then drops its last handles
//! destroys the device on its own thread, before the drop returns. Were a runtime thread to
//! hold the last reference instead, the device would go on that thread, perhaps while the
//! program exits, which drivers do not survive (RADV ended such a process with `SIGSEGV`).
//! - **And what fed its work** (`trails.rs`). A thread that made what the command buffer waited
//! for, and holds what it made it with past its signal, holds the device without holding the
//! command buffer: a pool piece between its making's settle and its give-back (a dispatch's or
//! a draw's pipeline), the reaper with what such a piece gave back to a
//! released state, the twin-decode thread between a decode's end and its job's drop. Each opens
//! a trail before its signal and closes it after its last let-go; the command buffer takes the
//! device's trail mark as it completes, and `wait_until_completed` and its timed form, once the
//! gate opened, wait for the trails below it, so the program's drop right after the wait is the
//! device's last (`tests/teardown_threads.rs` holds a dispatch's piece between the two). The
//! gate itself, the status and the completed handlers do not wait for trails. Metal's
//! `waitUntilCompleted` returns after the completed handlers ended too (the M3 Max: 10 µs at the
//! median, 23 µs at p99, a handler of 20 ms included).
//! - **What it does not cover.** A program that learns of the completion otherwise (from a
//! handler, an event the command buffer signals, or its status) may drop its last handles while
//! the runtime's thread still holds the command buffer; the device then goes on that thread.
//! An exit meanwhile waits for that teardown, or skips it once begun (`exit_guard`).
//! - **Notified only where it opened.** A notify is a system call, and one made while a [`Hold`]
//! is alive wakes every waiting thread to a gate it must find shut and sleep on again. The
//! thread that finishes a command buffer holds one over the whole transition
//! (`Transition::run`), so the finish itself never opens the gate: it sets the flag and leaves
//! the notify to that hold's going, one wake of the program's thread where there were two.
//! Counted: `WorkCounts::gate_waits`, `WorkCounts::gate_waits_slept` and
//! `WorkCounts::gate_wakes_found_shut`, which `tests::gate` holds to none.
//! - **Exit.** Once the process is exiting, the threads that would open a gate end, so a wait
//! answers at once, and one already blocked within `exit_guard::WAKE`.
use crate::device::lock;
use crate::error::{DeadlockCause, TimedOut};
use crate::exit_guard;
use std::ops::Deref;
use std::sync::{Arc, Condvar, Mutex};
use std::time::Instant;
/// A wait that cannot end: the process is exiting.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Exiting;
/// What one wait for a gate did, for the counters its caller keeps
/// (`WorkCounts::gate_waits_slept` and `WorkCounts::gate_wakes_found_shut`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Waited {
/// The gate was shut when the wait arrived, so it slept at least once.
pub(crate) slept: bool,
/// Notifies it was woken by that found the gate still shut, and slept again: work the thread
/// that opens the gate did between its notify and the gate opening. A sleep that ran out its
/// slice is not one ([`exit_guard::WAKE`] is 50 ms, far past any completion), so each of these
/// is a notify made while the gate could not yet open.
pub(crate) woke_shut: u64,
}
impl From<Exiting> for DeadlockCause {
fn from(Exiting: Exiting) -> DeadlockCause {
DeadlockCause::Exiting
}
}
impl From<Exiting> for crate::error::Error {
fn from(exiting: Exiting) -> crate::error::Error {
DeadlockCause::from(exiting).into()
}
}
/// One command buffer's gate.
#[derive(Debug, Default)]
pub(crate) struct Gate {
state: Mutex<GateState>,
changed: Condvar,
}
#[derive(Debug, Default)]
struct GateState {
/// The command buffer finished: its completed handlers ran.
finished: bool,
/// The [`Hold`]s alive.
held: usize,
/// The threads blocked until it opens ([`Gate::awaited`]).
waiting: usize,
}
impl GateState {
fn open(&self) -> bool {
self.finished && self.held == 0
}
}
impl Gate {
/// The command buffer finished; the gate opens once no [`Hold`] is left. Whether it notified
/// the waiters, which it does only where the gate opened here: a notify is a system call, and
/// one made while a [`Hold`] is still alive wakes every waiting thread to a gate it must find
/// shut and sleep on again. The thread that finishes a command buffer holds one over the whole
/// transition (`Transition::run`), so that notify was always such a wake, and the
/// [`leave`](Self::leave) of its hold notifies for it a moment later.
pub(crate) fn finish(&self) -> bool {
let opened = {
let mut state = lock(&self.state);
state.finished = true;
state.open()
};
if opened {
self.changed.notify_all();
}
opened
}
/// Whether the waiters may return.
pub(crate) fn is_open(&self) -> bool {
lock(&self.state).open()
}
/// Whether a thread is blocked until the gate opens, in [`wait`](Self::wait) or
/// [`wait_until`](Self::wait_until): what the thread that finishes the command buffer does
/// before its hold goes delays that thread's return.
pub(crate) fn awaited(&self) -> bool {
lock(&self.state).waiting > 0
}
/// Block until the gate opens, answering what the wait did ([`Waited`]). `Err` once the
/// process is exiting and it is not open: the runtime's threads that would open it end
/// (`exit_guard`).
pub(crate) fn wait(&self) -> Result<Waited, Exiting> {
self.wait_unless(exit_guard::closed)
}
/// [`Gate::wait`], with `exiting` saying whether the process is exiting (the exit guard's
/// [`closed`](exit_guard::closed), or a test's own).
pub(crate) fn wait_unless(&self, exiting: impl Fn() -> bool) -> Result<Waited, Exiting> {
let mut state = lock(&self.state);
state.waiting += 1;
let mut did = Waited::default();
// Whether the sleep before this look ended at a notify rather than at its slice.
let mut notified = false;
let waited = loop {
if state.open() {
break Ok(did);
}
did.woke_shut += u64::from(notified);
if exiting() {
break Err(Exiting);
}
did.slept = true;
let (woke, how) = self
.changed
.wait_timeout(state, exit_guard::WAKE)
.unwrap_or_else(std::sync::PoisonError::into_inner);
state = woke;
notified = !how.timed_out();
};
state.waiting -= 1;
waited
}
/// Block until the gate opens, or until `deadline`, answering what the wait did ([`Waited`]);
/// at once once the process is exiting, as [`Gate::wait`].
pub(crate) fn wait_until(&self, deadline: Instant) -> Result<Waited, TimedOut> {
let mut state = lock(&self.state);
state.waiting += 1;
let mut did = Waited::default();
// Whether the sleep before this look ended at a notify rather than at its slice.
let mut notified = false;
let waited = loop {
if state.open() {
break Ok(did);
}
did.woke_shut += u64::from(notified);
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() || exit_guard::closed() {
break Err(TimedOut);
}
did.slept = true;
let (woke, how) = self
.changed
.wait_timeout(state, left.min(exit_guard::WAKE))
.unwrap_or_else(std::sync::PoisonError::into_inner);
state = woke;
notified = !how.timed_out();
};
state.waiting -= 1;
waited
}
fn enter(&self) {
lock(&self.state).held += 1;
}
fn leave(&self) {
let mut state = lock(&self.state);
state.held -= 1;
let open = state.open();
drop(state);
if open {
self.changed.notify_all();
}
}
}
/// A reference a runtime thread holds (the scheduler's, a completion turn's, a queue
/// context's transition), counted by a [`Gate`]. Its fields drop in declaration order: the
/// reference first, then the count, so the gate cannot open while the reference is alive.
pub(crate) struct Hold<T> {
value: Arc<T>,
_count: Count,
}
/// A [`Hold`]'s place in its gate's count.
struct Count(Arc<Gate>);
impl Drop for Count {
fn drop(&mut self) {
self.0.leave();
}
}
impl<T> Hold<T> {
/// A new reference to `value`, counted by `gate`.
pub(crate) fn new(value: &Arc<T>, gate: &Arc<Gate>) -> Hold<T> {
gate.enter();
Hold {
value: Arc::clone(value),
_count: Count(Arc::clone(gate)),
}
}
/// Whether `self` and `other` hold the same value.
pub(crate) fn same(&self, other: &Hold<T>) -> bool {
Arc::ptr_eq(&self.value, &other.value)
}
/// Let go of the reference here, and leave the gate after, unless it is the value's last:
/// then the value, still counted by the gate, for the caller to let go of on another thread
/// ([`Last`]). Whether it is the last is decided as it goes (`Arc::into_inner`), so another
/// holder's drop meanwhile never leaves the value's drop here.
pub(crate) fn let_go_short_of_last(self) -> Option<Last<T>> {
let Hold { value, _count } = self;
Arc::into_inner(value).map(|value| Last { value, _count })
}
}
/// A [`Hold`]'s value where the hold was its last reference ([`Hold::let_go_short_of_last`]),
/// still counted by its gate: dropped, it drops the value, then leaves the gate.
pub(crate) struct Last<T> {
value: T,
_count: Count,
}
impl<T> Deref for Last<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<T> Deref for Hold<T> {
type Target = Arc<T>;
fn deref(&self) -> &Arc<T> {
&self.value
}
}